branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>import React, { useState, useEffect } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import axios from 'axios';
//styles
import './UpdateForm.scss';
const UpdateForm = ({getMovieList, movieList, setMovieList}) => {
const [movieToEdit, setMovieToEdit] = useState({});
const {id} = useParams();
let history= useHistory();
useEffect(() => {
const itemToEdit= movieList.find( movie => `${movie.id}` === id );
if(itemToEdit){
setMovieToEdit(itemToEdit);
}//end if
}, [])
const handleChange = e => {
let value= e.target.value;
setMovieToEdit({
...movieToEdit,
[e.target.name]: value
});
console.log('handleChange: ');
}//end handleChange
const sendPut= () => {
axios.put(`http://localhost:5000/api/movies/${movieToEdit.id}`, movieToEdit)
.then(putRes => {
console.log('putRes.data: ', putRes.data);
getMovieList();
history.push(`/movies/${id}`);
})
.catch(putErr => {console.log('putErr: ', putErr)})
}//end sendPut
const handleSubmit = e => {
e.preventDefault();
sendPut();
{console.log('movieToEdit from state: ', movieToEdit)}
console.log('submitted!');
}//end handleSubmit
return (
<div className='updateCont'>
{console.log('movieList from props: ', movieList)}
<form onSubmit={handleSubmit}>
<label htmlFor='title'>Title</label>
<input
onChange={handleChange}
value={movieToEdit.title}
type='text'
name='title'
id='title'
placeholder='Title'
/>
<label htmlFor='director'>Director</label>
<input
onChange={handleChange}
value={movieToEdit.director}
type='text'
name='director'
id='director'
placeholder='Director'
/>
<label htmlFor='metascore'>Metascore</label>
<input
onChange={handleChange}
value={movieToEdit.metascore}
type='text'
name='metascore'
id='metascore'
placeholder='Metascore'
/>
<label htmlFor='actors'>Stars</label>
<input
onChange={handleChange}
value={movieToEdit.stars}
type='text'
name='stars'
id='stars'
placeholder='Stars'
/>
<button
id='updateSubmitBtn'
>Submit Changes</button>
</form>
</div>
)
}
export default UpdateForm;<file_sep>import React from 'react';
import {Link, useHistory} from 'react-router-dom';
import axios from 'axios';
const MovieCard = props => {
const { title, director, metascore, stars, id } = props.movie;
const history= useHistory();
const deleteMovie= id => {
if(window.confirm('Are you sure you want to delete this movie?')){
axios
.delete(`http://localhost:5000/api/movies/${id}`)
.then(delRes => {
props.getMovieList()
history.push('/')
console.log('delRes: ', delRes);
})
.catch(delErr => {
console.log('delErr: ', delErr);
})
}//end if confirm
}//end deleteMovie
return (
<div className="movie-card">
<h2>{title}</h2>
<div className="movie-director">
Director: <em>{director}</em>
</div>
<div className="movie-metascore">
Metascore: <strong>{metascore}</strong>
</div>
<h3>Actors</h3>
{stars.map(star => (
<div key={star} className="movie-star">
{star}
</div>
))}
{
useHistory().location.pathname.includes('movies') && <Link id= 'updateBtn' to= {`/update-movie/${id}`}>Edit Me</Link>}
{useHistory().location.pathname.includes('movies') &&
<button onClick= {() => deleteMovie(`${id}`)} id= 'deleteBtn'>Delete</button>
}
</div>
);
};
export default MovieCard;
<file_sep>import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { useRouteMatch } from 'react-router-dom';
import MovieCard from './MovieCard';
function Movie({getMovieList, addToSavedList }) {
const [movie, setMovie] = useState(null);
const match = useRouteMatch();
//this page only recieves one movie, so we need to format the 'array' portion of the movie if it's a string.
const formatMovie= (movieData) => {
if(Array.isArray(movieData.stars) === false){
//string to array
let newArr= movieData.stars.split(',');
//assign the new array to the movie
movieData.stars= newArr;
return movieData;
}else{
return movieData;
}
}//end formatMovie
const fetchMovie = id => {
axios
.get(`http://localhost:5000/api/movies/${id}`)
.then(res => {
let movieData= res.data
setMovie(formatMovie(movieData));
})
.catch(err => console.log(err.response));
};
const saveMovie = () => {
addToSavedList(movie);
};
useEffect(() => {
fetchMovie(match.params.id);
}, [match.params.id]);
if (!movie) {
return <div>Loading movie information...</div>;
}
return (
<div className='save-wrapper'>
<MovieCard
getMovieList= {getMovieList}
movie={movie} />
<div className='save-button' onClick={saveMovie}>
Save
</div>
</div>
);
}
export default Movie;
| 01349592a56535d523e15b0559ed5bb33b70f847 | [
"JavaScript"
] | 3 | JavaScript | fuston05/HTTP-Movies-Assignment | c591fa6c3b1c651bdd67498b5b20cfc832fd5e62 | e6a80b0cc912fc1dad0f348d0f3deb9594b3291e | |
refs/heads/master | <repo_name>Umar895/SSD_Simulator<file_sep>/die.hh
#ifndef DIE_HH
#define DIE_HH
#include<iostream>
//#include "plane.hh"
//#include "block.hh"
#include "ssd_config.hh"
#include "ssd.hh"
using namespace std;
class Plane;
class Die{
private:
long id;
long long t_zero;
int free_blks;
int free_planes;
int erase_count;
Plane* pln_inuse;
//vector<Plane*> plane_ptrs;
public:
Die(const int & planes, const int & blocks, int new_id);
virtual ~Die(){};
int get_id();
bool set_plnInuse(Plane* plane_id);
Plane* get_plnInuse();
int get_free_blks();
bool set_time(long long time_zero);
long long get_time();
bool inc_erase_count();
int get_erase_count();
bool reset_erase_count();
};
#endif
<file_sep>/page.cpp
#include "page.hh"
Page::Page(){
id = -1;
block_id = -1;
page_in_block = -1;
page_writes = 0;
stat = 0;
lba = 0;
}
Page::Page(uint64_t new_id, int blk_id, int pln_id, int di_id){
this->id = new_id;
this->block_id = blk_id;
this->plane_id = pln_id;
this->die_id = di_id;
page_in_block = -1;
page_writes = 0;
stat = 0;
page_written = 0;
}
//bool Page::set_id(long new_id){
// id = new_id;
// return true;
//}
uint64_t Page::get_id(){
return id;
}
//bool Page::set_block_id(long new_id){
// block_id = new_id;
// return true;
//}
int Page::get_block_id(){
return block_id;
}
int Page::get_plane_id(){
return plane_id;
}
int Page::get_die_id(){
return die_id;
}
bool Page::inc_page_writes(){
page_writes++;
return true;
}
bool Page::set_page_in_block(int seek){
page_in_block = seek;
return true;
}
int Page::get_page_writes(){
return page_writes;
}
uint64_t Page::get_lba(){
return lba;
}
bool Page::write_page(uint64_t lpn){
stat = 1;
page_written++;
lba = lpn;
return true;
}
bool Page::invalidate_page(){
stat = -1;
return true;
}
bool Page::free_page(){
stat = 0;
lba = 0;
return true;
}
int Page::get_page_stat(){
return stat;
}
int Page::get_page_written(){
return page_written;
}
<file_sep>/ssd.cpp
#include "ssd.hh"
//template <class any>
SSD::SSD(const SSD_Config &config){
Die *new_die;
Plane *new_plane;
Block *new_block;
Page *new_page;
N_dies = config.N_dies;
N_planes = config.N_planes;
N_blocks = config.N_blocks;
N_pages = config.N_pages;
op_blocks = (N_blocks * config.O_prov)/100;
//write_delay = config.w_delay;
//read_delay = config.r_delay;
//erase_delay = config.e_delay;
// For uniform distribution of op_blocks across the dies
if(op_blocks%N_dies!=0){
op_blocks = ((op_blocks + N_dies/2) / N_dies) * N_dies;
}
for(auto i=0; i<N_dies; i++){
new_die = new Die(N_planes, N_blocks + op_blocks, t_di);
ssd_die.push_back(new_die);
for(auto j=0; j<N_planes; j++){
new_plane = new Plane(N_blocks + op_blocks,t_pln, t_di);
die_plane[new_die].push_back(new_plane);
for(auto k=0; k<N_blocks+op_blocks; k++){
new_block = new Block(N_pages,t_blk, t_pln, t_di);
//new_plane->set_block(t_blk,new_block);
plane_blk[new_plane].push_back(new_block);
for(auto l=0; l<N_pages; l++){
new_page = new Page(t_page, t_blk, t_pln, t_di);
block_page[new_block].push_back(new_page);
t_page++;
}
t_blk++;
}
t_pln++;
}
t_di++;
}
// A whole die is used for the parity of rest of dies
xor_die = ssd_die.back();
ssd_die.pop_back();
//N_dies = N_dies-1;
cout<<"die:"<<config.N_dies<<" plane:"<<config.N_planes<<" blk:"<<config.N_blocks<<" page:"<<config.N_pages<<endl;
cout<<"die:"<<t_di<<" plane:"<<t_pln<<" blk:"<<t_blk<<" page:"<<t_page<<endl;
if(t_di!=config.N_dies &&
t_pln!=config.N_dies * config.N_planes &&
t_blk!=config.N_dies * config.N_planes * (config.N_blocks + op_blocks)&&
t_page!=config.N_dies * config.N_planes * (config.N_blocks + op_blocks) * config.N_pages){
cout<<" Cannot create the required configuration metrics!!"<<endl;
}else{
cout<<"Total pages, blocks, planes and dies created are as follows:"<<endl;
cout<<"t_pages:"<<t_page<<" t_blks:"<<t_blk<<" t_pln:"<<t_pln<<" t_di:"<<t_di<<endl;
}
High_water_mark = N_blocks + op_blocks - 4;
Low_water_mark = High_water_mark - op_blocks/4 ;
//High_water_mark_xor = N_blocks + op_blocks - 16;
cout<<"high: "<<High_water_mark<<" low: "<<Low_water_mark<<endl;
}
/* Destructor for the SSD */
SSD::~SSD(){
cout<<"destructor is called "<<endl;
ssd_die.push_back(xor_die);
Die *old_die;
Plane *old_plane;
Block *old_block;
Page *old_page;
for(auto i=0; i<N_dies; i++){
old_die = ssd_die.front();
//for(auto j=0; j<die_plane[old_die].size(); j++){
for(auto j:die_plane){
old_plane = die_plane[old_die].front();
//for(auto k=0; k<plane_blk[old_plane].size(); k++){
for(auto k:plane_blk){
old_block = plane_blk[old_plane].front();
//for(auto l=0; l<block_page[old_block].size(); l++){
for(auto l:block_page){
old_page = block_page[old_block].front();
block_page[old_block].pop_front();
delete old_page;
}
plane_blk[old_plane].pop_front();
delete old_block;
}
die_plane[old_die].pop_front();
delete old_plane;
}
ssd_die.pop_front();
delete old_die;
}
}
/* The writing strategy is as follows:
* Die: For each write, die is selected in round robin fashion
* Plane: For each request inside die, planes are also selected in round robin
* Block: The next inuse block in the plane is selected as the block, otherwise next free block of plane
* ####################################################
* For Example:
* we have Die=2, plane=4
*
* Assume incoming request is as follows: (1,2,3,4,5,6,7,8,9,10) and are distributed as follows:
*
* 1 - Die-0 => plane-0 => block-0 => page-0
* 2 - Die-1 => plane-0 => block-0 => page-0
* 3 - Die-0 => plane-1 => block-0 => page-0
* 4 - Die-1 => plane-1 => block-0 => page-0
* 5 - Die-0 => plane-2 => block-0 => page-0
* 6 - Die-1 => plane-2 => block-0 => page-0
* 7 - Die-0 => plane-3 => block-0 => page-0
* 8 - Die-1 => plane-3 => block-0 => page-0
* 9 - Die-0 => plane-0 => block-0 => page-1
* 10- Die-1 => plane-0 => block-0 => page-1
* ####################################################
*
* But in a case when a page is invalidated, then same die is selected to overwrite the invalid page
*/
void SSD::get_write_loc(write_loc *loc, Die* die_inv, Plane* pln_inv){
Die *next_die=NULL;
Plane *next_plane=NULL;
Block *next_block=NULL;
Page* next_page=NULL;
// Round Robin for selecting die to write, every die always has a free block available
next_die = ssd_die.front();
ssd_die.pop_front();
ssd_die.push_back(next_die);
assert(next_die!=0);
// Initially the plane in use is NULL
next_plane = die_plane[next_die].front();
die_plane[next_die].pop_front();
die_plane[next_die].push_back(next_plane);
assert(next_plane!=0);
if(next_plane->get_free_blks()==0){
cout<<"no block available in plane: "<<next_plane->get_id()<<" die: "<<next_die->get_id()<<endl;
assert(1<0);
}
// Initially no block is written, which gives null
next_block = next_plane->get_blkInuse();
if(next_block == NULL){
next_block = plane_blk[next_plane].front();
}
assert(next_block!=0);
if(next_block->get_free_pgs()==0){
cout<<"There is no free pages on the block: "<<next_block->get_id()<<" plane:"<<next_plane->get_id()<<" die:"<<next_die->get_id()<<endl;
assert(1<0);
}
next_plane->set_blkInuse(next_block);
next_page = block_page[next_block].front();
if(next_page->get_page_stat()!=0){
cout<<"page is not free"<<endl;
assert(1<0);
}
block_page[next_block].pop_front();
block_page[next_block].push_back(next_page);
assert(next_page!=0);
loc->die = next_die;
loc->plane = next_plane;
loc->block = next_block;
loc->page = next_page;
}
int SSD::random_gen(int min, int max){
return min + rand() % (max - min);
}
bool SSD::external_read(uint64_t lpn, int IOSize, double time){
Die *die_r=NULL;
/*
int pos = random_gen(1,lpn_ppn.size());
auto it = lpn_ppn.begin();
advance(it,pos);
lpn = it->first;
die_r = lpn_ppn[lpn].die;
if(gc_flag[die_r].write>0){
gc_flag[die_r].blocked++;
}else{
read_bt_gc_flag_zero++;
}
ur++;
*/
auto it = lpn_ppn.find(lpn);
if(it!=lpn_ppn.end()){
die_r = lpn_ppn[lpn].die;
if(gc_flag[die_r].write>0){
gc_flag[die_r].blocked++;
}else{
read_bt_gc_flag_zero++;
}
}
ur++;
if((uw + ur + gcw)%100000==0 && gcw>0){
stat();
}
return true;
}
/*
void SSD::overwrite_parity(Block* blk){
Block *blk_x;
//map<int,Block*>::iterator it = block_m.find(blk);
if(blk->get_die_id()==0){
}
int offset = block_m.size()/(N_dies*N_planes);
N_dies - blk->get_die_id();
blk_x = block_m[blk->get_id() + offset];
}
*/
bool SSD::external_write(uint64_t lpn, int IOSize, double time){
Die *die_i=NULL;
Plane *pln_i = NULL;
Block *blk_i = NULL;
Page *page_i = NULL;
Plane *plane_w;
Block *blk_w;
Page *page_w;
Block *temp_blk = NULL;
write_loc loc;
invalid_page = false;
auto it = lpn_ppn.find(lpn);
if(it!=lpn_ppn.end()){
die_i = lpn_ppn[lpn].die;
pln_i = lpn_ppn[lpn].plane;
blk_i = lpn_ppn[lpn].block;
page_i = lpn_ppn[lpn].page;
lpn_ppn.erase(lpn);
invalid_page = true;
iw++;
blk_i->remove_page(page_i, time);
//overwrite_parity(blk_i);
}
get_write_loc(&loc, die_i, pln_i);
update_gc_flag();
if(time==t_page){uw=gcw;}
page_w = loc.page;
blk_w = loc.block;
plane_w = loc.plane;
blk_w->write_page(lpn,page_w, time);
uw++;
lpn_ppn[lpn].die = loc.die;
lpn_ppn[lpn].plane = plane_w;
lpn_ppn[lpn].block = blk_w;
lpn_ppn[lpn].page = page_w;
//cout<<"free pages in the current block "<<write_blk->get_free_pgs()<<endl;
if(blk_w->get_free_pgs()==0){
//cout<<"time to push the block into filled block"<<endl;
temp_blk = plane_blk[plane_w].front();
plane_w->push_block(temp_blk);
plane_blk[plane_w].pop_front();
plane_w->reduce_free_blks();
xoring_block(blk_w, time);
plane_w->set_blkInuse(plane_blk[plane_w].front());
}
int inf_gc = 0;
if(plane_w->get_block_size()>=High_water_mark){
while(plane_w->get_block_size() >= Low_water_mark){
garbage_collect(loc.die,plane_w,time);
if(inf_gc>1){break;}
inf_gc++;
//if(uw==1363585){
/* if(gcw>4244430){
cout<<"gcw: "<<gcw<<" blks_in_a_pln: "<<plane_w->get_block_size()<<endl;
if(gcw>4246430){assert(1<0);}
}
*/ //if(plane_w->get_block_size()==990){ assert(1<0);}
}
gc_flag_set(loc.die);
}
if((uw + ur + gcw)%100000==0 && gcw>0){
stat();
}
return true;
}
bool SSD::gc_flag_set(Die* di_id){
gc_flag[di_id].write = 8;
gc_flag[di_id].read = 60;
return true;
}
bool SSD::update_gc_flag(){
for (map<Die*,iops>::iterator it=gc_flag.begin(); it!=gc_flag.end(); ++it){
if(it->second.write>0){
it->second.write--;
it->second.read = it->second.read - 8;
}
}
return true;
}
bool SSD::check_distance(int dis1, int dis2, int dis3){
if(dis3-dis2 == dis2-dis1){
//cout<<"equi distant, xor possible"<<endl;
return true;
}else{
cout<<"xor not possible"<<endl;
cout<<"ids 1:"<<dis1<<" 2:"<<dis2<<" 3:"<<dis3<<endl;
return false;
}
}
// Xor of blocks
bool SSD::xoring_block(Block* blk, double time){
Plane *x_plane;
Block *first, *second, *third, *x_blk;
Page *page, *page1, *page2, *x_page;
int dis1, dis2, dis3;
int xo;
// if(blks.size()!=0){
// assert(1<0);
tmp_blks.push_back(blk);
if(tmp_blks.size()==3){
x_plane=die_plane[xor_die].front();
first = tmp_blks.front();
dis1 = first->get_id();
tmp_blks.pop_front();
second = tmp_blks.front();
dis2 = second->get_id();
tmp_blks.pop_front();
third = tmp_blks.front();
dis3 = third->get_id();
tmp_blks.pop_front();
if(!check_distance(dis1,dis2,dis3)){
cout<<"the blocks are unaligned for xor"<<endl;
assert(1<0);
}
x_blk = plane_blk[x_plane].front();
//cout<<"dis1:"<<dis1<<" dis2:"<<dis2<<" dis3:"<<dis3<<" dis4:"<<dis3+offset<<endl;
//assert(1<0);
for(int i=0; i<N_pages; i++){
page = first->get_page_at(i);
page1 = second->get_page_at(i);
page2 = third->get_page_at(i);
uint64_t flags[] = {(page->get_lba()),page1->get_lba(),page2->get_lba()};
xo = accumulate(flags,end(flags),0,bit_xor<int>());
x_page = block_page[x_blk].front();
if(x_page->get_page_stat()!=0){
cout<<"page is not free status:"<<x_page->get_page_stat()<<endl;
cout<<"xblk_id:"<<x_blk->get_die_id()<<endl;
assert(1<0);
}
block_page[x_blk].pop_front();
block_page[x_blk].push_back(x_page);
x_blk->write_xor(xo, x_page, i, time);
xor_w++;
}
if(x_plane->get_id()!=x_blk->get_plane_id()){
cout<<"the planes conflict after the xor"<<endl;
assert(1<0);
}
if(plane_blk[x_plane].front()!=x_blk){
cout<<"serious problem!!"<<endl;
assert(1<0);
}
plane_blk[x_plane].pop_front();
x_plane->push_block(x_blk);
x_plane->reduce_free_blks();
if(x_plane->get_block_size()>=High_water_mark){
garbage_collect(xor_die,x_plane, time);
}
die_plane[xor_die].pop_front();
die_plane[xor_die].push_back(x_plane);
tmp_blks.clear();
}
// }
return true;
}
bool SSD::internal_write(Die* die, uint64_t lpn, Plane* plane, long long time){
Block *next_block=NULL;
Page *next_page=NULL;
Block *temp_blk;
assert(lpn!=0);
plane = die_plane[die].front();
die_plane[die].pop_front();
die_plane[die].push_back(plane);
// Initially no block is written, which gives null
next_block = plane->get_blkInuse();
if(next_block == NULL){
next_block = plane_blk[plane].front();
}
assert(next_block!=0);
if(next_block->get_free_pgs()==0){
cout<<"There is no free pages on the block: "<<next_block->get_id()<<" plane:"<<next_block->get_plane_id()<<" die:"<<next_block->get_die_id()<<endl;
assert(1<0);
}
next_page = block_page[next_block].front();
block_page[next_block].pop_front();
block_page[next_block].push_back(next_page);
//next_page = block_page[next_block].front();
/* if(gcw>4244430){
cout<<"before write"<<endl;
cout<<"plane blk size: "<<plane_blk[plane].size()<<endl;
cout<<"pln: "<<plane<<endl;
for (auto it = plane_blk.begin(); it != plane_blk.end(); it++)
{
cout << it->first << ":";
for (auto lit = it->second.begin(); lit != it->second.end(); lit++)
cout << " " << (*lit)->get_free_pgs();
cout << "\n";
}
}
*/
next_block->write_page(lpn,next_page, time);
//next_block->write_page(next_page,time);
if(next_block->get_free_pgs()==0){
//cout<<"time to push the block into filled block"<<endl;
temp_blk = plane_blk[plane].front();
plane->push_block(temp_blk);
plane_blk[plane].pop_front();
plane->reduce_free_blks();
plane->set_blkInuse(plane_blk[plane].front());
/* if(gcw>4244430){
cout<<"after write"<<endl;
cout<<"plane blk size: "<<plane_blk[plane].size()<<endl;
cout<<"pln: "<<plane<<endl;
for (auto it = plane_blk.begin(); it != plane_blk.end(); it++)
{
cout << it->first << ":";
for (auto lit = it->second.begin(); lit != it->second.end(); lit++)
cout << " " << (*lit)->get_free_pgs();
cout << "\n";
}
}
*/ }
lpn_ppn[lpn].die = die;
lpn_ppn[lpn].plane = plane;
lpn_ppn[lpn].block = next_block;
lpn_ppn[lpn].page = next_page;
return true;
}
void SSD::garbage_collect(Die* die, Plane *plane, long long time){
Block *victim_block;
Page* reset_page;
list<Page*>::iterator it;
victim_block = plane->get_victim_block(time);
/* if(victim_block->get_dirty_pgs()==0){
cout<<"victim blk does not have a dirty page "<<endl;
debug(plane);
assert(1<0);
}
*/
for(it = block_page[victim_block].begin(); it!=block_page[victim_block].end(); it++){
reset_page = *it;
if(reset_page->get_page_stat() == 1){
// shift the write to active block please
if(reset_page->get_lba()!=0){
//internal_write(die,reset_page->get_lba(),plane, time);
lpn_ppn.erase(reset_page->get_lba());
}
gcw++;
}
reset_page->free_page();
}
victim_block->erase_block(time);
plane_blk[plane].push_back(victim_block);
plane->add_free_blks();
die->inc_erase_count();
}
void SSD::stat(){
cout<<"mp_t:"<<lpn_ppn.size();
cout<<" uw:"<<uw<<" ur(%):"<<100*double(ur)/double(uw+ur)<<" wa:"<<double(uw+xor_w+gcw)/double(uw);
cout<<"| dies";
for (map<Die*,iops>::iterator it=gc_flag.begin(); it!=gc_flag.end(); ++it){
cout<<"|"<<it->second.blocked<<"/"<<(it->first)->get_erase_count();
//cout<<"|"<<double((it->first)->get_erase_count())/double(it->second.blocked);
(it->first)->reset_erase_count();
gc_flag[it->first].blocked=0;
}
//cout<<" r_m:"<<read_missed<<" : "<<read_bt_gc_flag_zero;
cout<<'\n';
}
void SSD::debug(Plane* plane){
Block* victim_block;
int dirty=0;
int valid=0;
int ful_blks = plane->get_block_size();
for(int i=0; i<ful_blks; i++){
victim_block = plane->get_victim_block(1);
if(victim_block->get_dirty_pgs() == 0){
dirty++;
}
if(victim_block->get_valid_pgs()==256){
valid++;
}
}
cout<<"ful_blk: "<<ful_blks<<" dirty: "<<dirty<<" valid: "<<valid<<endl;
}
<file_sep>/die.cpp
#include "die.hh"
Die::Die(const int & planes, const int & blocks, int new_id){
/* Set die id */
id = new_id;
free_planes = planes;
//plane_ptrs.resize(planes);
//for(int i=0; i<planes; i++){
// plane_ptrs[i] = NULL;
//}
pln_inuse = NULL;
free_blks = blocks;
erase_count=0;
}
int Die::get_id(){
return id;
}
bool Die::set_time(long long time_zero){
t_zero = time_zero;
return true;
}
long long Die::get_time(){
return t_zero;
}
bool Die::set_plnInuse(Plane* plane_id){
pln_inuse = plane_id;
return true;
}
Plane* Die::get_plnInuse(){
return pln_inuse;
}
int Die::get_free_blks(){
return free_blks;
}
bool Die::inc_erase_count(){
erase_count++;
return true;
}
int Die::get_erase_count(){
return erase_count;
}
bool Die::reset_erase_count(){
erase_count = 0;
return true;
}
<file_sep>/block.hh
#ifndef BLOCK_H
#define BLOCK_H
#include<map>
#include<iostream>
//#include "page.hh"
//#include "ssd.hh"
#include "ssd_config.hh"
#include "plane.hh"
class SSD_Config;
class Page;
class Block{
private:
int id;
int plane_id;
int die_id;
int valid_pgs;
int dirty_pgs;
int free_pgs;
long erase_cnt;
int seek;
long waccess;
long t_zero;
int N_pages;
map<int,Page*> page_ptrs;
public:
Block(const int & Np, int new_id, int pln_id, int di_id);
virtual ~Block(){};
virtual bool erase_block(long long time);
bool write_page(Page *page, long long time);
bool write_page(uint64_t lba, Page *page, long long time);
bool write_xor(uint64_t lba, Page *page, int seek, long long time);
virtual bool remove_page(Page *page, long long time);
//bool set_id(long new_id);
int get_id();
int get_plane_id();
int get_die_id();
int get_free_pgs();
int get_dirty_pgs();
int get_valid_pgs();
long long get_waccess();
//bool set_t_zero();
Page* get_page_at(int pos);
long get_erase_cnt();
};
#endif
<file_sep>/ssd_config.hh
#ifndef SSD_CONFIG_H
#define SSD_CONFIG_H
#include<iostream>
#include<fstream>
#include<string>
#include<sys/stat.h>
#include<sys/types.h>
//#include<fnctl>
#include<unistd.h>
#include "ssd.hh"
using namespace std;
class SSD_Config{
private:
void copyConfigFile(std::string configFile, std::string logFolder);
public:
uint64_t Nlp = 0;
int N_dies = 0; // Dies per SSD
int N_planes = 0; // Planes per Die or channel
int N_blocks = 0; // blocks per plane
int N_pages = 0; // pages per block
int Capacity = 0; // TODO:Not used yet
double w_delay = 0; // Write delay for a single page
double r_delay = 0; // Read delay for a single page
double e_delay = 0; // erase delay for a block
double ctor_delay = 0; // controller to register delay or vice versa for a single page
double O_prov = 0; // percentage of over-provisioing
int seed = 0;
//std::vector<std::string> ignoredKeywords;
bool printConfig = true;
std::string logFolder = "";
std::string traceFile = "";
SSD_Config(string configFile);
//SSD * init_SSD(string configFile) const;
virtual ~SSD_Config(){ }
virtual bool checkConfig()const;
};
#endif
<file_sep>/plane.hh
#ifndef PLANE_HH
#define PLANE_HH
#include<iostream>
#include<vector>
#include<list>
#include<limits>
//#include "block.hh"
//#include "page.hh"
#include "ssd_config.hh"
#include "die.hh"
using namespace std;
class Block;
class Plane{
private:
int id;
int die_id;
//int Nb;
int free_blks;
int written_blk;
Block* blk_inuse;
map<int,Block*> blk_ptrs;
list<Block*> full_blk;
public:
Plane(const int & Nb, int new_id, int di_id);
bool set_id(int new_id);
int get_id();
bool set_dieId(int die_Id);
int get_dieId();
bool set_block(int b_id, Block* new_blk);
bool reduce_free_blks();
int get_free_blks();
bool add_free_blks();
bool set_blkInuse(Block* blk_inuse);
Block* get_blkInuse();
bool push_block(Block* temp_blk);
int get_block_size();
Block* get_full_blk();
Block* get_victim_block(long long time);
};
#endif
<file_sep>/plane.cpp
#include "plane.hh"
Plane::Plane(const int & Nb, int new_id, int di_id){
id = new_id;
die_id = di_id;
free_blks = Nb;
written_blk = 0;
for(int i=0; i<Nb; i++){
blk_ptrs[i] = NULL;
}
blk_inuse = NULL;
}
bool Plane::set_id(int new_id){
id = new_id;
return true;
}
int Plane::get_id(){
return id;
}
bool Plane::set_dieId(int die_Id){
die_id = die_Id;
return true;
}
int Plane::get_dieId(){
return die_id;
}
bool Plane::set_block(int b_id, Block* new_blk){
blk_ptrs[b_id] = new_blk;
return true;
}
bool Plane::reduce_free_blks(){
free_blks--;
written_blk++;
return true;
}
int Plane::get_free_blks(){
return free_blks;
}
bool Plane::add_free_blks(){
free_blks++;
written_blk--;
return true;
}
bool Plane::set_blkInuse(Block* bl_inuse){
blk_inuse = bl_inuse;
return true;
}
Block* Plane::get_blkInuse(){
return blk_inuse;
}
// Returns the block sequentially for xor operations
Block* Plane::get_full_blk(){
Block *next_blk;
next_blk = full_blk.front();
full_blk.pop_front();
full_blk.push_back(next_blk);
return next_blk;
}
bool Plane::push_block(Block* temp_blk){
full_blk.push_back(temp_blk);
return true;
}
int Plane::get_block_size(){
return full_blk.size();
}
Block* Plane::get_victim_block(long long time){
Block* victim_block;
Block* block;
int min_valid = numeric_limits<int>::max();
list<Block*>::iterator it, it_erase;
//cout<<"size blks: "<<full_blk.size()<<endl;
for (it=full_blk.begin();it!=full_blk.end();it++){
block = *it;
//cout<<"valid_pgs "<<block->get_valid_pgs()<<endl;
if(block->get_valid_pgs() < min_valid){
min_valid = block->get_valid_pgs();
victim_block = *it;
it_erase = it;
}
}
//cout<<"victim valid_pgs "<<victim_block->get_valid_pgs()<<endl;
full_blk.erase(it_erase);
//cout<<"size blks: "<<full_blk.size()<<endl;
return victim_block;
}
<file_sep>/Makefile
# SSD Simulator
# 2017 <NAME>. All Rights Reserved
CC = g++
#compiler flags:
# -g adds debugging information to the executable file
# -Wall turns on most, but not all. compiler warnings
CFLAGS = -g -std=c++11 -Wall -D_REENTRANT
#include libs
LDLIB = -g
DEP = ssd_config.hh
SRC = main.cpp ssd_config.cpp ssd.cpp page.cpp block.o plane.o die.o
OBJ = main.o ssd_config.o ssd.o page.o block.o plane.o die.o
main: main.o ssd_config.o ssd.o page.o block.o
$(CC) $(LDFLAGS) $(LDLIBS) -o main $(OBJ)
main.o: $(SRC)
$(CC) $(CFLAGS) -c main.cpp
ssd_config.o: ssd_config.hh ssd_config.cpp
$(CC) $(CFLAGS) -c ssd_config.cpp
ssd.o: ssd.hh ssd.cpp
$(CC) $(CFLAGS) -c ssd.cpp
die.o: die.hh die.cpp
$(CC) $(CFLAGS) -c die.cpp
plane.o: plane.hh plane.cpp
$(CC) $(CFLAGS) -c plane.cpp
block.o: block.hh block.cpp
$(CC) $(CFLAGS) -c block.cpp
page.o: page.hh page.cpp
$(CC) $(CFLAGS) -c page.cpp
clean:
rm *.o
rm main
<file_sep>/main.cpp
#include<iostream>
#include<string>
#include<fstream>
#include<random>
#include<assert.h>
#include<ctime>
#include "ssd_config.hh"
//#include "tracegen/trace.hh"
#include "ssd.hh"
using namespace std;
SSD_Config * config = NULL;
SSD *ssd = NULL;
int random_gen(int min, int max){
static bool first = true;
if(first){
srand(42);
first = false;
}
return min + rand() % (max - min);
}
int main(int argc, char ** argv){
if(argc != 2){
cout<<"\033[1;31mCorrect call <config file> \033[0m "<<endl;
exit(-1);
}
std::string configFile = argv[1];
long long inc_time = 1;
config = new SSD_Config(configFile);
ssd = new SSD(*config);
//ssd->init_SSD(config);
bool validConfig = config->checkConfig();
if(!validConfig){
cout<<"\t################################"<<endl;
cout<<"\tWARNING: config file is not valid !!"<<endl;
cout<<"\t################################"<<endl;
cout<<endl;
}
std::string FileName = config->traceFile;
std::mt19937 gen(config->seed);
std::uniform_int_distribution<>dis(0,config->Nlp-1);
time_t start_time = time(0);
// Sequential Writes
cout<<"Sequential Writes "<<endl;
for(int i=0; i<1; i++){
for(uint64_t z=0; z<config->Nlp; z++){
ssd->external_write(z,1,inc_time);
inc_time++;
}
}
int req_size = 0;
uint64_t req = 0;
int r_w;
// Random Writes
cout<<"Random Writes "<<endl;
for(int j=0; j<2; j++){
for(uint64_t i=0; i<config->Nlp; i++){
//break;
//cout<<"rand:"<<random_gen(0, config->Nlp)<<endl;
req_size = random_gen(1,2);
r_w = random_gen(0,20);
req = random_gen(1, config->Nlp);
for(int x=0; x < req_size; x++){
ssd->external_write(req+x, req_size , inc_time);
inc_time++;
}
if(r_w%3==0){
for(int y=0; y<req_size; y++){
ssd->external_read(req+y, req_size, inc_time);
inc_time++;
}
}
}
}
time_t end_time = time(0);
uint64_t duration = (uint64_t)difftime(end_time, start_time);
cout<<"Total Simulation time: "<<duration/3600<<":"<<(duration%3600)/60<<":"<<((duration%3600)%60)<<endl;
delete config;
delete ssd;
return 0;
}
<file_sep>/README.md
Simulate:
---------
Type make and run the main file by specifying the configuration file.
./main <config file> (ssd.conf is the config file which needs to be mentioned)
All other information is available in configuration file.
<file_sep>/page.hh
#ifndef PAGE_HH
#define PAGE_HH
#include<iostream>
#include "block.hh"
#include "ssd.hh"
using namespace std;
class Page{
private:
uint64_t id;
int block_id;
int plane_id;
int die_id;
int page_in_block;
int page_writes;
/* there will be three states of a page as follows:
free = 0;
write = 1;
invalidate = -1;
*/
int stat;
int page_written;
uint64_t lba;
public:
Page();
//template <class id>
Page(uint64_t new_id, int blk_id, int pln_id, int di_id);
//template <class A>
//bool set_id(uint64_t new_id, int blk_id, int pln_id, int di_id);
uint64_t get_id();
//bool set_block_id(long new_id);
int get_block_id();
int get_plane_id();
int get_die_id();
bool set_page_in_block(int seek);
long get_page_in_block(){return page_in_block;}
bool inc_page_writes();
int get_page_writes();
uint64_t get_lba();
bool write_page(uint64_t lpn);
bool invalidate_page();
bool free_page();
int get_page_stat();
int get_page_written();
};
#endif
<file_sep>/block.cpp
#include "block.hh"
Block::Block(const int & Np, int new_id, int pln_id, int di_id){
N_pages = Np;
/* set block, plane, and die id */
id = new_id;
plane_id = pln_id;
die_id = di_id;
//page_ptrs.resize(Np);
/* initially all pages in a block are invalid */
for(int i=0; i<Np; i++){
page_ptrs[i] = NULL;
}
/* There are only free pages directly after init */
free_pgs = Np;
valid_pgs = 0;
dirty_pgs = 0;
erase_cnt = 0;
t_zero = 0;
/* Start writing from the beginning of the block */
seek = 0;
/* The block has not yet been accessed */
waccess = 0;
}
int Block::get_id(){
return id;
}
int Block::get_plane_id(){
return plane_id;
}
int Block::get_die_id(){
return die_id;
}
int Block::get_free_pgs(){
return free_pgs;
}
int Block::get_dirty_pgs(){
return dirty_pgs;
}
int Block::get_valid_pgs(){
return valid_pgs;
}
long Block::get_erase_cnt(){
return erase_cnt;
}
Page* Block::get_page_at(int pos){
return page_ptrs[pos];
}
bool Block::remove_page(Page* page, long long time){
if(page->get_page_stat()==0 || page->get_page_stat()==-1){
cout<<"page is not written or already invalidated, how it can be invalidated?"<<endl;
cout<<"page status: "<<page->get_page_stat()<<endl;
assert(1<0);
}
page->invalidate_page();
valid_pgs--;
dirty_pgs++;
waccess = time;
return true;
}
bool Block::erase_block(long long time){
erase_cnt++;
for(int i=0; i<N_pages; i++){
page_ptrs[i] = NULL;
}
free_pgs = N_pages;
valid_pgs = 0;
dirty_pgs = 0;
t_zero = time;
seek = 0;
waccess = 0;
return true;
}
bool Block::write_page(Page* page, long long time){
if(free_pgs == 0){
return false;
}
page_ptrs[seek] = page;
page->set_page_in_block(seek);
free_pgs--;
valid_pgs++;
seek++;
if(time!=-1){
waccess = time;
}
//page->write_page();
return true;
}
bool Block::write_xor(uint64_t lba, Page* page, int seek, long long time){
if(free_pgs == 0){
return false;
}
page_ptrs[seek] = page;
page->set_page_in_block(seek);
free_pgs--;
valid_pgs++;
if(time!=-1){
waccess = time;
}
page->write_page(lba);
return true;
}
bool Block::write_page(uint64_t lba, Page* page, long long time){
if(free_pgs == 0){
return false;
}
page_ptrs[seek] = page;
page->set_page_in_block(seek);
free_pgs--;
valid_pgs++;
seek++;
if(time!=-1){
waccess = time;
}
page->write_page(lba);
return true;
}
<file_sep>/ssd_config.cpp
#include "ssd_config.hh"
SSD_Config::SSD_Config(std::string configFile){
std::ifstream in(configFile);
if(! in.is_open()){
std::cerr<<"ERROR: Config file "<<configFile<<" cannot be opened "<<std::endl;
exit(1);
}
std::string keyword;
while(in >> keyword){
if(keyword == "#"){
std::getline(in,keyword);
continue;
}
if(keyword == "logFolder"){
in >> logFolder;
if(logFolder.back() != '/'){
logFolder = logFolder + "/";
}
continue;
}
if(keyword == "traceFile"){
in >> traceFile;
continue;
}
if(keyword == "printConfig"){
in >> printConfig;
continue;
}
if(keyword == "NUM_DIES"){
in >> N_dies;
continue;
}
if(keyword == "NUM_PLANES"){
in >> N_planes;
continue;
}
if(keyword == "NUM_BLOCKS"){
in >> N_blocks;
continue;
}
if(keyword == "NUM_PAGES"){
in >> N_pages;
continue;
}
if(keyword == "OVER_PROV"){
in >> O_prov;
continue;
}
if(keyword == "CAPACITY"){
in >> Capacity;
continue;
}
if(keyword == "PAGE_WRITE_DELAY"){
in >> w_delay;
continue;
}
if(keyword == "PAGE_READ_DELAY"){
in >> r_delay;
continue;
}
if(keyword == "BLOCK_ERASE_DELAY"){
in >> e_delay;
continue;
}
if(keyword == "DELAY_CONTROLLER_TO_REGISTER"){
in >> ctor_delay;
continue;
}
if(keyword == "RANDOM_SEED"){
in >> seed;
continue;
}
std::getline(in,keyword);
}
Nlp = N_pages * N_blocks * N_planes * N_dies;
//std::cout<<logFolder<<std::endl;
mkdir(logFolder.c_str(),0777);
//init_SSD(configFile);
if(printConfig){
cout<<"*****************************"<<endl;
cout<<"Using trace file:"<<traceFile<<endl;
cout<<"Using log folder:"<<logFolder<<endl;
cout<<"die per ssd:"<<N_dies<<endl;
cout<<"planes per die:"<<N_planes<<endl;
cout<<"blocks per plane:"<<N_blocks<<endl;
cout<<"pages per block:"<<N_pages<<endl;
cout<<"Over Provisioning:"<<O_prov<<"%"<<endl;
cout<<"Spare Factor: "<<float(1-float(N_blocks)/(float(N_blocks * O_prov/100) + N_blocks))<<endl;
cout<<"SSD Size: "<<(long long)(Nlp * 4096)/(long long)(1024*1024*1024)<<"GB"<<endl;
cout<<"*****************************"<<endl;
cout<<endl;
}
in.close();
copyConfigFile(configFile, logFolder);
}
bool SSD_Config::checkConfig() const{
bool check = true;
if(logFolder == ""){
cout<<"WARNING: logFolder was not set! "<<endl;
check = false;
}
if(traceFile == ""){
cout<<"WARNING: tracefile was not set! "<<endl;
check = false;
}
if(N_dies == 0){
cout<<"ERROR: Number of dies is not set or is set to 0"<<endl;
check = false;
}
if(N_planes == 0){
cout<<"ERROR: Number of planes is not set or equals to 0"<<endl;
check = false;
}
if(N_blocks == 0){
cout<<"ERROR: Number of blocks per plane is not set or equals to 0!"<<endl;
check = false;
}
if(N_pages == 0){
cout<<"ERROR: Number of pages per block is not set or equals to 0"<<endl;
check = false;
}
if(O_prov == 0){
cout<<"ERROR: Over-provisioning is not set or equals to 0"<<endl;
check = false;
}
if(Capacity == 0){
cout<<"ERROR: capacity of the ssd is not set! or equals to 0 "<<endl;
check = false;
}
if(w_delay == 0){
cout<<"ERROR: write delay is not set!"<<endl;
check = false;
}
if(r_delay == 0){
cout<<"ERROR: read delay is not set!"<<endl;
check = false;
}
if(e_delay == 0){
cout<<"ERROR: erase delay is not set!"<<endl;
check = false;
}
if(ctor_delay == 0){
cout<<"ERROR: channel to register delay is not set! "<<endl;
check = false;
}
if(seed == 0){
cout<<"ERROR: Random Seed is not set! "<<endl;
check = false;
}
if(!check){
cout<<endl;
}
return check;
}
//SSD * SSD_Config::init_SSD(string configFile) const{
// SSD *ssd = NULL;
// ssd = new SSD();
// return ssd;
//}
void SSD_Config::copyConfigFile(std::string configFile, std::string logFolder){
std::ifstream src(configFile, std::ios::binary);
std::ofstream dst(logFolder + "run.conf",std::ios::binary);
dst << src.rdbuf();
src.close();
dst.close();
}
<file_sep>/ssd.hh
#ifndef SSD_H
#define SSD_H
#include<iostream>
#include<vector>
#include<map>
#include<assert.h>
#include<list>
#include<bitset>
#include<functional>
#include<algorithm>
#include "ssd_config.hh"
#include "die.hh"
#include "plane.hh"
#include "block.hh"
#include "page.hh"
using namespace std;
class SSD_Config;
class Die;
class Page;
class SSD{
private:
int N_pages=0;
int N_blocks=0;
int N_planes=0;
int N_dies=0;
int uw=0;
int ur=0;
int gcw=0;
int iw=0;
int xor_w=0;
int reads_blocked=0;
int t_di = 0;
int t_pln = 0;
int t_blk = 0;
int read_missed=0;
int read_bt_gc_flag_zero = 0;
uint64_t t_page = 0;
int op_blocks = 0;
// For GC operation
int High_water_mark = 0;
int Low_water_mark = 0;
bool invalid_page;
Die *xor_die=NULL;
// Data Structures for the corresponding SSD architecture
list<Die*>ssd_die;
map<Die*, list<Plane*> >die_plane;
map<Plane*, list<Block*> >plane_blk;
map<Block*, list<Page*> >block_page;
struct iops{
int write;
int read;
int blocked;
};
map<Die*, iops> gc_flag;
list<Block*>tmp_blks;
public:
struct reverse_ptr{
Die *die;
Plane *plane;
Block *block;
Page *page;
};
map<uint64_t, reverse_ptr>lpn_ppn;
struct write_loc{
Die *die;
Plane *plane;
Block *block;
Page *page;
};
//template <class any>
SSD(const SSD_Config &config);
virtual ~SSD(); // Destructor to clean the Data Structure
bool external_write(uint64_t lpn, int IOSize, double time);
bool external_read(uint64_t lpn, int IOSize, double time);
bool gc_flag_set(Die* di_id);
bool update_gc_flag();
void get_write_loc(write_loc *loc, Die* die_inv, Plane* pln_inv);
int random_gen(int min, int max);
bool xoring_block(Block* blk, double time);
bool check_distance(int dis1, int dis2, int dis3);
void garbage_collect(Die* die,Plane* plane, long long time);
virtual bool internal_write(Die* die,uint64_t lpn, Plane* plane, long long time);
void stat();
void debug(Plane* plane);
};
#endif
| eb93f3f6c9687894bac0fc148f00d27620c90269 | [
"Markdown",
"Makefile",
"C++"
] | 15 | C++ | Umar895/SSD_Simulator | 9859e6275def53063235b07e2d239e9c8f99b6c9 | 52d53e9fad45b4a58240e3007b08545a0bb12cf7 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 21 21:50:58 2019
@author: <NAME>
NFL Big Data Bowl
"""
import os
import re
import pandas as pd
import numpy as np
from scipy import stats
from math import sqrt
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
os.chdir('C:/Users/Brad/Desktop/NFL Data/Big-Data-Bowl-master/Big-Data-Bowl-master/Data')
df = pd.read_csv('plays.csv')
# Exclude penalty and special teams plays
df = df[(df['isPenalty'] == False) & (df['SpecialTeamsPlayType'].isnull())]
# Exclude interceptions, sack plays, and QB runs
# (include complete pass plays, incomplete pass plays, and run plays)
df = df[df['PassResult'].isin(['C', 'I', np.nan])]
# sometimes two-point conversion attempts have a NA for SpecialTeamsPlayType
# and a False for isSTPlay
# Only way to catch them is to exclude down == 0 plays
df[(df['down'] == 0) & (df['SpecialTeamsPlayType'].isnull()) & (df['isSTPlay'] == False)]['playDescription']
df = df[df['down'] != 0]
# Exclude fumble plays (not case sensitive)
df = df[~df['playDescription'].str.contains("fumble", case = False)]
# Determine receiver and ball carrier
def get_rusher(description):
"""
Purpose: collect rusher name on a given play
Input: play description from plays.csv
Output: rusher name
"""
try:
return list(re.findall(r'\w+[\.]+\w+', description))[0]
except IndexError:
# Found a description with no player names
return np.nan
def get_receiver(description):
"""
Purpose: collect receiver name on a given play
Input: play description from plays.csv
Output: receiver name
"""
try:
return list(re.findall(r'\w+[\.]+\w+', description))[1]
except IndexError:
# Found a description with no player names
return np.nan
# Create rushers and receivers columns
rushers = df['playDescription'].apply(get_rusher).where(df['PassResult'].isnull())
receivers = df['playDescription'].apply(get_receiver).where(df['PassResult'].isin(['C', 'I']))
# Quick look
rushers.value_counts()[0:25]
receivers.value_counts()[0:25]
# Add columns
df.insert(loc = 25, column = 'Receiver', value = receivers)
df.insert(loc = 26, column = 'Rusher', value = rushers)
# Create a yards gain vs. needed column to help determine run play success
gained_needed = (round(df['PlayResult']/df['yardsToGo'], 2)).where(df['PassResult'].isnull())
# Add column
df.insert(loc = 27, column = 'GainNeed', value = gained_needed)
# Run play success decision rules require knowing which team is home
# and which is visitor
# Collect home and visitor abbreviations in a dictionary
# gameId: (home, visitor)
games = pd.read_csv('games.csv')
home_visitor = {}
for i in range(games.shape[0]):
gameId = games.iloc[i]['gameId']
home = games.iloc[i]['homeTeamAbbr']
visitor = games.iloc[i]['visitorTeamAbbr']
home_visitor[gameId] = (home, visitor)
# Combine running back play success rules into a function
def rb_success(row, games):
"""
Purpose: calcualte if a run play was a success based on decision rules
Decision rules:
- A play counts as a "Success" if it gains 40% of yards to go on first
down, 60% of yards to go on second down, and 100% of yards to go on
third or fourth down.
- If the team is behind by more than a touchdown in the fourth quarter,
the benchmarks switch to 50%/65%/100%.
- If the team is ahead by any amount in the fourth quarter, the
benchmarks switch to 30%/50%/100%.
inputs:
- An entire row from plays.csv with GainNeed column
- a dict of gameId: (home, visitor)
* Assumes down can take a value of 1,2,3 or 4 (not 0)
output:
- True if criteria met for success on run play
- False if criteria not met
- nan if not a running play
Note: This function will not win any beauty contests
"""
gameId = row['gameId']
quarter = row['quarter']
down = row['down']
poss_team = row['possessionTeam']
gain_need = row['GainNeed']
if pd.isna(gain_need):
# Not a run play
return np.nan
#print()
#print(gain_need)
if poss_team == games[gameId][0]:
diff = row['HomeScoreBeforePlay'] - row['VisitorScoreBeforePlay']
elif poss_team == games[gameId][1]:
diff = row['VisitorScoreBeforePlay'] - row['HomeScoreBeforePlay']
else:
print('Error: posession team not found')
ahead_by = 0
down_by = 0
if diff < 0:
down_by = abs(diff)
elif diff > 0:
ahead_by = diff
else:
ahead_by = 0
if (quarter == 4) and (down_by >= 6):
if down == 1:
return gain_need >= 0.5
elif down == 2:
return gain_need >= 0.65
else:
return gain_need >= 1.0
elif (quarter == 4) and (ahead_by > 0):
if down == 1:
return gain_need >= 0.3
elif down == 2:
return gain_need >= 0.5
else:
return gain_need >= 1.0
elif down == 1:
return gain_need >= 0.4
elif down == 2:
return gain_need >= 0.6
else:
return gain_need >= 1.0
#return np.nan
df = df.reset_index(drop = True)
run_success = pd.Series(np.nan, index = range(df.shape[0]))
for i in range(df.shape[0]):
run_success[i] = rb_success(df.iloc[i], home_visitor)
# Add column
df.insert(loc = 28, column = 'RunSuccess', value = run_success)
# check to see if any touchdown runs are labeled as failures
df[df['playDescription'].str.contains('touchdown', case = False)][['quarter', 'down', 'GainNeed', 'RunSuccess', 'playDescription']]
success_rate = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()/x.shape[0], 2))
rushes = df.groupby('Rusher')['RunSuccess'].count()
successful = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()))
rb_success_rate = pd.DataFrame({'Rushes': rushes, 'Successful': successful, 'SuccessRate':success_rate})
rb_success_rate.sort_values('SuccessRate', inplace = True, ascending = False)
rb_success_rate.to_csv('success_rate.csv')
def ci_lower_bounds(successful_runs, n, confidence):
"""
successful_runs: total runs multiplied by success rate
n: total runs
confidence: desired confidence level (e.g., 0.95)
"""
if n == 0:
return 0
z = stats.norm.ppf(1-(1-0.95)/2)
p_hat = 1.0*successful_runs/n
return (p_hat + z*z/(2*n) - z*sqrt((p_hat*(1 - p_hat) + z*z/(4*n))/n))/(1 + z*z/n)
# sorted by confidence in success rate
rb_success_rate['Conf_Adj_Rank'] = rb_success_rate.apply(lambda x: round(ci_lower_bounds(x['Successful'], x['Rushes'], 0.95), 4), axis = 1)
rb_success_rate.sort_values('Conf_Adj_Rank', inplace = True, ascending = False)
rb_success_rate.to_csv('success_rate_adj.csv')
# Gather run plays
#Group subset of run plays by game ID, collect associated plays
df_rush = df[df['RunSuccess'].isin([True, False])]
rushes_by_gameId = df_rush[['playId', 'gameId', 'RunSuccess', 'Rusher', 'PlayResult']].groupby('gameId')
# Build a rush plays dictionary to associate games with a list of plays
# format:
# key: gameId
# value: [(plays.csv_index, playId, RunSuccess, Rusher, ...]
rush_plays = {}
for name, group in rushes_by_gameId:
rush_plays[name] = list(zip(list(group.index),
list(group['playId']),
list(group['RunSuccess']),
list(group['PlayResult']),
list(group['Rusher'])))
def tot_dist_time(play):
"""
Total distance player traveled on the play
Total time to go that distance
Use for computing efficiency and average speed columns
Input: pandas groupby object; grouped by playId
Output: distance, time
- yards gained will come from the PlayResult column in the game_rush
dataframe
"""
stop_index = play['event'].last_valid_index()
stop_event = play['event'][stop_index]
if stop_event == 'qb_kneel':
return np.nan
dist = 0
time = 0
moving = False
for i in range(play.shape[0]):
#try:
#print(play['event'][i])
#except KeyError:
#print("failed on )
# We do not know which man 'man_in_motion' refers to
# Use 'ball_snap' as start of distance
if play['event'].iloc[i] == 'ball_snap' or play['event'].iloc[i] == 'snap_direct':
moving = True
# final non NA value marks the end of the run
# it will be 'tackle', 'out_of_bounds', 'touchdown', etc...
elif play['event'].iloc[i] == stop_event:
return round(dist, 2), round(time/10, 2)
if moving:
dist += play['dis'].iloc[i]
time += 1
#elif not moving and dist > 0:
# Run has finished
def yards_after_contact(play):
stop_index = play['event'].last_valid_index()
stop_event = play['event'][stop_index]
if stop_event == 'qb_kneel':
return np.nan
dist = 0
moving = False
for i in range(play.shape[0]):
# We do not know which man 'man_in_motion' refers to
# Use 'ball_snap' as start of distance
if play['event'].iloc[i] == 'first_contact':
moving = True
# final non NA value marks the end of the run
# it will be 'tackle', 'out_of_bounds', 'touchdown', etc...
elif play['event'].iloc[i] == stop_event:
return round(dist, 2)
if moving:
dist += play['dis'].iloc[i]
def max_speed(play):
stop_index = play['event'].last_valid_index()
stop_event = play['event'][stop_index]
if stop_event == 'qb_kneel':
return np.nan
speeds = []
moving = False
for i in range(play.shape[0]):
if play['event'].iloc[i] == 'ball_snap' or play['event'].iloc[i] == 'snap_direct':
moving = True
# final non NA value marks the end of the run
# it will be 'tackle', 'out_of_bounds', 'touchdown', etc...
elif play['event'].iloc[i] == stop_event:
try:
return max(speeds)
except:
# Missing ball snap tag in tracking data
return np.nan
if moving:
speeds.append(play['s'].iloc[i])
def contact_speed(play):
"""
Output: player speed at time of contact
"""
for i in range(play.shape[0]):
if play['event'].iloc[i] == 'first_contact' or play['event'].iloc[i] == 'tackle':
return play['s'].iloc[i]
return 'no contact'
# Iteration procedure
num_plays = df.shape[0]
# Get all file names from directory
all_files = os.listdir()
# Collect tracking data filenames
game_filenames = []
for file in all_files:
if file.startswith('tracking'):
game_filenames.append(file)
# Create empty new columns:
# - tot_dist
tot_dist_col = pd.Series(np.nan, index = range(num_plays))
tot_time_col = pd.Series(np.nan, index = range(num_plays))
yds_aft_ct_col = pd.Series(np.nan, index = range(num_plays))
max_spd_col = pd.Series(np.nan, index = range(num_plays))
ct_spd_col = pd.Series(np.nan, index = range(num_plays))
# Loop over all tracking files (steps below)
# 1. load next file
# 2. subset
# 3. group by playId
# 4. apply appropriate function
# 5. fill new empty column with values at appropriate index
total_rows = 0
files_read = 0
missing = 0
for filename in game_filenames:
files_read += 1
print("{} files to go".format(len(game_filenames) - files_read))
game = pd.read_csv(filename)
game['split_name'] = game['displayName'].apply(lambda x: x.split()[0][0].lower() + ' ' + x.split()[1].lower() if len(x.split()) > 1 else x)
game_id = int(re.findall(r'\d+', filename)[0])
print('current gameId: {}'.format(game_id))
# Subset to keep desired rows associated with this game
look_up = pd.DataFrame(rush_plays[game_id], columns = ['orig.index', 'playId', 'RunSuccess', 'PlayResult', 'Rusher'])
look_up['split_name'] = look_up['Rusher'].apply(lambda x: x.split('.')[0][0].lower() + ' ' + x.split('.')[1].lower())
game_rush = pd.merge(look_up, game)
# group by playId and check that only one unique name exists per group
# detect of two players with similar names were on field during same play
rows = game_rush.shape[0]
total_rows += rows
grouped_by_playId = game_rush.groupby('playId')
#if not tag_check(grouped_by_playId):
#print('Unbalanced tags in game {}'.format(game_id))
# Collect playId (index) and time to throw for all plays in one game
d_t = {}
yds_aft_ct = {}
mx_spd = {}
ct_spd = {}
for name, group in grouped_by_playId:
d_t[group['playId'].iloc[0]] = tot_dist_time(group)
yds_aft_ct[group['playId'].iloc[0]] = yards_after_contact(group)
mx_spd[group['playId'].iloc[0]] = max_speed(group)
ct_spd[group['playId'].iloc[0]] = contact_speed(group)
for play in rush_plays[game_id]:
index = play[0]
play_num = play[1]
#print("index: ", index)
#print("play num: ", play_num)
#print("d_t: ", d_t[play_num])
#print(d_t[play_num][1])
try:
tot_dist_col[index] = d_t[play_num][0]
tot_time_col[index] = d_t[play_num][1]
yds_aft_ct_col[index] = yds_aft_ct[play_num]
max_spd_col[index] = mx_spd[play_num]
ct_spd_col[index] = ct_spd[play_num]
except TypeError:
# QB kneel play; nan values for rush_player
tot_dist_col[index] = np.nan
tot_time_col[index] = np.nan
yds_aft_ct_col[index] = np.nan
max_spd_col[index] = np.nan
ct_spd_col[index] = np.nan
except KeyError:
missing += 1
print('Play num {} has been removed from tracking data'.format(play_num))
continue
# Add column
df.insert(loc = 29, column = 'TotalDist', value = tot_dist_col)
df.insert(loc = 30, column = 'TotalTime', value = tot_time_col)
avg_speed = round(df['TotalDist']/df['TotalTime'], 2)
efficiency = round(df['TotalDist']/df['PlayResult'], 2)
df.insert(loc = 31, column = 'AvgSpeed', value = avg_speed)
df.insert(loc = 32, column = 'MaxSpeed', value = max_spd_col)
df.insert(loc = 33, column = 'ContactSpeed', value = ct_spd_col)
df.insert(loc = 34, column = 'YardsAfterContact', value = yds_aft_ct_col)
df.insert(loc = 35, column = 'EFF', value = efficiency)
df = df.replace(np.inf, np.nan)
df = df.replace('no contact', np.nan)
# Save updated version of plays.csv with new columns of calculated values
df.to_csv('plays_v2.csv')
# Recalculate Running Back rankings using new variables
# See how the other variables stack up when sorted by adjusted success rate
success_rate_v2 = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()/x.shape[0], 2))
rushes = df.groupby('Rusher')['RunSuccess'].count()
successful = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()))
avg_eff = round(df.groupby('Rusher')['EFF'].mean(), 2)
avg_max_spd = round(df.groupby('Rusher')['MaxSpeed'].mean(), 2)
avg_ct_spd = round(df.groupby('Rusher')['ContactSpeed'].mean(), 2)
avg_yds_aft_ct = round(df.groupby('Rusher')['YardsAfterContact'].mean(), 2)
rb_success_rate_v2 = pd.DataFrame({'Rushes': rushes,
'Successful': successful,
'AvgEFF': avg_eff,
'AvgMaxSpeed': avg_max_spd,
'AvgCtSpeed': avg_ct_spd,
'AvgYardsAfterContact': avg_yds_aft_ct,
'SuccessRate':success_rate})
# sorted by confidence in success rate
rb_success_rate_v2['Conf_Adj_Rank'] = rb_success_rate.apply(lambda x: round(ci_lower_bounds(x['Successful'], x['Rushes'], 0.95), 4), axis = 1)
rb_success_rate_v2.sort_values('Conf_Adj_Rank', inplace = True, ascending = False)
rb_success_rate_v2.to_csv('success_rate_adj_v2.csv')
import seaborn as sns
import matplotlib.pyplot as plt
# Reset default params
sns.set()
sns.set(rc={'figure.figsize':(11.7,8.27)})
# Set context to `"paper"`
sns.set_context("poster")
sns.swarmplot(x="quarter", y="ContactSpeed", data=df[~df['ContactSpeed'].isin(['no contact'])])
plt.show()
sns.set_context("poster")
ax = sns.violinplot(x = "YardsAfterContact", data=df)
ax.set_title("Yards After Contact (rushing plays)")
#grid.set_xticklabels(rotation=30)
#ax = sns.violinplot(x = "YardsAfterContact", data=df)
# Set the `xlim`
#ax.set(xlim=(0, 100))
ax.figure.savefig("yds_ct_dist.png")
ax = sns.regplot(x="ContactSpeed", y="YardsAfterContact", data=df[~df['ContactSpeed'].isin(['no contact'])], fit_reg = False)
ax.set(xlabel='Speed at Moment of Contact (yds/s)', ylabel='Yards Gained After Contact')
ax.figure.savefig("spd_yds_gain.png")
plt.show()
ax.set_context("poster")
ax = sns.regplot(x="MaxSpeed", y="YardsAfterContact", data=df[~df['MaxSpeed'].isin(['no contact'])], fit_reg = False)
ax.set(xlabel='Max Speed (yds/s)', ylabel='Yards Gained After Contact')
ax.figure.savefig("max_spd_yds_gain2.png")
plt.show()
ax.set_context("poster")
ax = sns.regplot(x="AvgSpeed", y="RunSuccess", data=df[df['RunSuccess'] == True].isin(['no contact'])], fit_reg = False)
ax.set(xlabel='Max Speed (yds/s)', ylabel='Yards Gained After Contact')
ax.figure.savefig("max_spd_yds_gain2.png")
plt.show()
from scipy.stats.stats import pearsonr
x = df['ContactSpeed']
y = df['YardsAfterContact']
def r2(x,y):
nas = nas = np.logical_or(np.isnan(x), np.isnan(y))
return pearsonr(x[~nas], y[~nas])[0]
sns.set_context("poster")
h = sns.jointplot(x, y, kind="reg", stat_func=r2)
h.set_axis_labels(xlabel='Contact Speed (yds/s)', ylabel='Yards Gained After Contact')
plt.show()
h.savefig("spd_yds_gain_corr.png")
x = df['EFF']
y = df['YardsAfterContact']
def r2(x,y):
nas = nas = np.logical_or(np.isnan(x), np.isnan(y))
return pearsonr(x[~nas], y[~nas])[0]
sns.set_context("poster")
h = sns.jointplot(x, y, kind="reg", stat_func=r2)
h.set_axis_labels(xlabel='Rushing Efficiency', ylabel='Yards Gained After Contact')
plt.show()
h.savefig("spd_eff_corr.png")
sns.set_context("poster")
ax = sns.violinplot(x="RunSuccess", y='ContactSpeed', data=df, palette="muted")
ax.figure.savefig("run_spd.png")
sns.set_context("poster")
ax = sns.violinplot(x="RunSuccess", y='YardsAfterContact', data=df, palette="muted")
ax.figure.savefig("run_suc_yds.png")
sns.set_context("poster")
ax = sns.violinplot(x="RunSuccess", y='EFF', data=df, palette="muted")
ax.figure.savefig("run_spd.png")
ax = sns.regplot(x="AvgSpeed", y="EFF", data=df, fit_reg = False)
ax.set(xlabel='Average Speed Throughout A Play (yds/s)', ylabel='Efficiency')
df['MaxSpeed'].describe()
df[df['RunSuccess'] == False]['ContactSpeed'].describe()
df[df['RunSuccess'] == False]['YardsAfterContact'].describe()
success_rate = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()/x.shape[0], 2))
max_speed = df.groupby('Rusher')['MaxSpeed'].mean()
avg_spd = df.groupby('Rusher')['AvgSpeed'].mean()
successful = df.groupby('Rusher')['RunSuccess'].apply(lambda x: round((x*1).sum()))
rb_success_rate = pd.DataFrame({'Rushes': rushes, 'Successful': successful, 'MaxSpeed': max_speed, 'AvgSpeed': avg_spd, 'SuccessRate':success_rate})
rb_success_rate.sort_values('SuccessRate', inplace = True, ascending = False)
eff = df.groupby('Rusher')['EFF'].mean()
<file_sep>---
title: "NFL Big Data Bowl 2019"
author: "<NAME> | <EMAIL> | (310) 923-6337"
date: "January 22, 2019"
output:
pdf_document:
fig_caption: yes
keep_tex: yes
fontsize: 12pt
#output: html_document
#runtime: shiny
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(kableExtra)
library(reticulate)
```
# Introduction
Speed is exciting. It should be no surprise that many of the metrics that football analysts and fans love to quote have an inherent speed component. Sometimes this fascination with speed is explicit. A good example is the Fastest Ball Carriers metric. More often though speed is simply implied like when ranking quarterbacks by Time to Throw or receivers by Yards After Catch. Regardless of the perspective, speed is a crucial aspect of the game.
In some situations understanding the value of speed is straightforward. For example, it is just as important for wide receivers to have explosive acceleration and high top-end speed as it is for the opposing defensive backs who are charged with disrupting pass routes. Additionally, a quarterback who can fire off a pass quickly also needs receivers who can get to their positions on the field rapidly.
In other situations the way that speed contributes to the success of a play is less obvious. As a result, speed metrics might not immediately seem useful. In order to appreciate the impact of speed we need context, and we can establish that context with data. We already collect a lot of data on NFL players and games in order to gain insights and improve our decisions. Now that we have the ability to take substantially more measurements than ever before during an NFL game, we face an exciting new challenge: how do we find value in the data that is actually useful for teams?
To answer that question we need to think critically about what we should measure, and can actually measure, during a game. Once we properly frame the problems we want to solve, we can formulate meaningful questions that reveal what the collected data can explain.
# The Effectiveness of Speed
There are ways to be effective using speed other than simply being the fastest player to run a 40 yard dash. It is definitely exciting to watch an elite player expertly evade defenders and open up the throttle for an uncontested touchdown. It certainly helps to be the fastest player on the field, but the gametime opportunities to get up to top-speed without interruption are limited. It is more useful to think about speed as a capability. In other words, it is not always top speed, but more often optimal speed and optimal movement that win the day.
If a more general way to think about speed is optimal speed, we need to think about what that means. A combination of various decisive factors such as decision-making, speed, balance, maneuverability, momentum, and strength contribute to the success of a football play. While some factors, like decision-making, might be hard to measure, we can study the outcomes of plays as a means to learn about how these factors might interact. Moreover, with Next Gen Stats, we can specifically dive into the necessary details to learn about what encourages the outcomes we want to reproduce.
# Focus of This Study
In recent NFL seasons rule changes, as well as breakout players, have placed the focus on quarterbacks and wide receiver metrics. We are currently in an era of record-breaking offensive performances. As a result, the focus of metrics and analysis is heavily weighted toward understanding, and often revering, NFL teams with a pass-heavy offense. This study takes an alternate approach and considers optimal speed in the rushing game.
Rushing plays fail for many reasons, and many of those reasons are very difficult, if not impossible, to consistently predict. There is legitimate value in determining why a play did not work. Unfortunately, that can often be a fairly complicated and subjective task. So instead, as a more straightforward initial approach, we will look primarily to plays that were successful at gaining yards. We want to understand the speed-related factors that keep a play alive and help propel a drive to the end zone. We want to know what encourages that success.
To help us find our answer, we will focus on several fundamental themes:
1. Efficiency
2. Momentum
# Data Preparation
The Big Data Bowl plays.csv data is our roadmap. It serves as the guide to plan an analysis of the tracking data files. The goal is to find all running plays and associated ball carriers in order to dive into player-level game data. While each of the data sets could have been merged into one large data set, it is more intuitive to start with a specific purpose and then gather only what is needed from each of the 91 game tracking data sets.
First, a subset of all non-penalty and non-special teams plays is taken. Two-point conversion plays are also removed. While these do contain some rushing plays, they represent a special-case and correspond to only a small portion of the data. Therefore they are not included. For similar reasons, fumble plays are excluded as well.
Once this is done, a column containing the names of the ball carriers on each play is inserted into the play data in order to facilitate pairing ball carriers with plays.
# Theme 1: Efficiency
Players who use speed in an optimal way are efficient. Their decision-making and agility often lead to additional yards when they are most needed. To operationalize the concept of rushing efficiency we will in part use the popular Running Back Success Rate and Rushing Efficiency metrics.
> # Running Back Success Rate (credit: Football Outsiders):
> * A play counts as a "Success" if it gains 40% of yards to go on first down, 60% of yards to go on second down, and 100% of yards to go on third or fourth down.
> * If the team is behind by more than a touchdown in the fourth quarter, the benchmarks switch to 50%/65%/100%.
> * If the team is ahead by any amount in the fourth quarter, the benchmarks switch to 30%/50%/100%.
> To calculate success rate a GainNeed column was first added to the plays.csv data set to represent yards gained divided by yards needed for each rushing play. Then, using a function that incorporated the associated decision rules, a new RunSuccess column was generated to indicate if a run was a deemed a success. Determining success rate then became a simple task of grouping the plays.csv data by ball carrier, and dividing a player's total successful runs by their total carries.
> You could stop here and simply sort players by their success rates. However, this presents a few problems. For one, some rushers appear more frequently in the data than others. This imbalance results in their success rate being more representative since it is based on more data. Additionally, other players have few total carries but many of them are successful. This results in a high success rate based on little evidence.
> If success rate is going to be used as criteria for sorting and ranking running backs then we must weight the ranking with a confidence measure. Think of it like this: at an online retailer's website you naturally trust a 4.5-star rating with 1,000 reviews more than a 5-star rating with 10 reviews. When there is less evidence there is greater uncertainty. In our case, the necessary correction can be made using a clever technique that several websites employ to allow users to sort content by "best."
>> # Running Back Ranking Scheme
>> Since the RunSuccess column only takes on values of true or false, we can create an adjusted ranking scheme using a method known as the Lower bound of a Wilson score confidence interval for a Bernoulli parameter. The method takes a set of positive and negative ratings (e.g., true or false) and estimates the real fraction of positive ratings provided a desired confidence level.
>> While the success rate metric seeks to capture the value of a rushing play, this sorting scheme provides a confidence-adjusted ranking. In Table 1 only rushers with a success rate less than one were included in the top ten. This was done to facilitate recognition of the fact that a small sample size and the successful rush proportion can result in the metric not being very useful. Sorting by success rate alone yields does not yield a useful ranking. However, when this confidence-adjusted success rate ranking scheme is employed (Table 2) note how the top ten rushers are a more representative group in terms of total rushes. While more elaborate ranking schemes exist, usually based on the influence of additional metrics, this approach is a very simple way to add context to a commonly used metric.
>> This approach also has the benefit of including all data as opposed to methods that would simply try to ignore some of the data with a subset and an arbitrary threshold (e.g., only display rusers with more than 50 total rushses).
```{python, echo = FALSE}
import pandas as pd
rb1 = pd.read_csv('success_rate.csv')
rb2 = pd.read_csv('success_rate_adj.csv')
```
```{r, fig.cap='test!', echo=FALSE}
py$rb1[py$rb1['SuccessRate'] < 1.0,][1:10,] %>%
kable(caption='Non-adjusted running back ranking by success rate') %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE)
```
\newpage
```{r, echo=FALSE}
py$rb2[py$rb2['SuccessRate'] < 1.0,][1:10,] %>%
kable(caption = 'confidence-adjusted ranking by success rate') %>%
kable_styling(bootstrap_options = c("striped", "hover", "condensed"), full_width = FALSE)
```
> # Rushing Efficiency (credit: Next Gen Stats):
> * Rushing Efficiency is calculated by taking the total distance a player traveled on rushing plays as a ball carrier according to Next Gen Stats (measured in yards) per rushing yards gained. The lower the number, the more of a North/South runner.
> Rushing efficiency is a metric that serves as a proxy for many aspects of a run play. It is the product of a player's athleticism and agility. It is also reflective of a player's effort to fight and weave through traffic to gain more yards. Ultimately, the rushing efficiency metric attempts to account for all of the unique movements related to a particular position.
> To calculate Rushing Efficiency, or EFF, a column was generated by iterating over the game tracking data sets and calculating a rusher's total distances traveled on all plays. This distance column was then divided by the PlayResult column to derive the EFF column.
\newpage
# Theme 2: Momentum
Rushers who use speed in an optimal way are also tenacious. No matter the situation, they find a way to maintain their momentum until the defense forces them to stop, or until they score a touchdown. Sometimes being a battering ram gets the extra yards. In other situations it is all about the agility necessary to avoid or shed tackles. For some players, given their size and strength, the likelihood that they will gain yards after contact might increase after they accelerate up to a certain optimal speed.
The best way to gauge a player's ability to maintain momentum is to measure the yards they gain after first contact with the defense. Measuring yards gained after contact is a way to identify and understand players who best utilize their remaining speed to make forward progress. Additionally, measuring a player's speed at the moment they make contact is vital to understanding what it means to use speed effectively throughout a rushing play.
> # Yards After Contact
> * Reveals the influence of momentum and maneuvering in gaining additional yards before the play is over.
> # Contact Speed
> * Determined by calculating a rushing ball carrier's speed at the moment they make contact with defensive resistance.
The Yards After Contact metric is derived from each of the run plays a particular ball carrier participated in throughout all of the game tracking data files. For a particular game and play, a ball carrier's data is examined in order to determine the total distance they traveled following first contact with a member of the opposing team. A corresponding contact speed was also extracted from the appropriate game tracking files in a similar fashion.
# Additional Variables
In addition to the variables and columns described, additional variables were calculated or derived and inserted into the plays.csv data set to facilitate answering questions and generating exploratory plots. The entire procedure is detailed and available for review in the master.py Python code file that can be found at the GitHub link at the end of this paper.
\newpage
# Results
We might as well begin with the most-interesting observation. In Figure 1 we see the relationship between a player's speed at the time of contact and the yards gained after contact.
```{python, echo = FALSE}
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats.stats import pearsonr
df = pd.read_csv('plays_v2.csv')
```
```{python, echo = FALSE}
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'E:/Apps/Anaconda3/Library/plugins/platforms'
```
```{python, echo = FALSE}
import warnings
import seaborn as sns
x = df['ContactSpeed']
y = df['YardsAfterContact']
def corr(x,y):
nas = np.logical_or(np.isnan(x), np.isnan(y))
return pearsonr(x[~nas], y[~nas])[0]
sns.set_context("paper")
warnings.filterwarnings("ignore")
fig1 = sns.jointplot(x, y, kind="reg", stat_func=corr)
fig1.set_axis_labels(xlabel='Contact Speed (yds/s)', ylabel='Yards After Contact')
plt.show()
plt.clf()
```
\begin{center}{Figure 1: Contact Speed vs. Yards After Contact}\end{center}
\newpage
Note that while the correlation is positive, and moderately strong, we still have quite a few observations that clearly exceed the trend. These apparent outliers should not be a surprise. Their presence simply demonstrates that the majority of the time it is difficult for a rusher to escape the defense for a large yardage gain on a play.
So we know a relationship exists between a ball carrier's contact speed and the yards they gain after contact. But contact speed might be slower and less-representative of what a talented rusher is capable of during a play. To see how else speed might influence the yards gained after contact we will look at the max player speed on a play and compare it to the yards gained after contact.
```{python, echo=FALSE}
fig2 = sns.regplot(x="MaxSpeed", y="YardsAfterContact", data=df[~df['MaxSpeed'].isin(['no contact'])], fit_reg = False)
fig2.set(xlabel='Max Speed (yds/s)', ylabel='Yards After Contact')
plt.show()
plt.clf()
```
\begin{center}{Figure 2: Max Speed vs. Yards After Contact}\end{center}
It is pretty clear to see in Figure 2 that there is a trend suggesting that higher max speeds are related to gaining more yards.
\newpage
However, some of these observations appear to be rare events. Attempting to model this relationship with a non-linear approach might not prove very useful.
Nevertheless, as anticipated, speed appears to be at least partially related to gaining additional yards after contact. Next we will look at the role that efficiency plays. At first glance Figure 3 seems to be suggesting that the rushing efficiency metric and yards gained after contact do not have a strong association.
```{python, echo=FALSE}
fig3 = sns.regplot(x='EFF', y='YardsAfterContact', data=df, fit_reg=False)
fig3.set(xlabel='Rushing Efficiency', ylabel='Yards After Contact')
plt.show()
plt.clf()
```
\begin{center}{Figure 3: Rushing Efficiency vs. Yards After Contact}\end{center}
For clarification, remember that the Rushing Efficiency metric actually takes on positive, negative, and zero values. This forces the plot to appear like it does not define a strong linear relationship between Rushing Efficiency and yards gained after contact. But remember that values "near" zero are indicative of an efficient player, so we are not looking for a linear relationship. If you look closely you will see that the diagram is actually making a very clear claim: players with a Rushing Efficiency value near zero consistently gain yards after contact, while those with Rushing efficiency values far from zero do not gain many yards after contact. In other words efficient runners gain more yards after contact with the defense.
Finally, given we know that contact speed is important, we should examine how contact speed is related to whether or not a run is a success. Through a comparison in Figure 4 it is clear to see that, among the observations in this data set, player's with a successful run have higher contact speeds.
```{python, echo=FALSE}
fig4 = sns.violinplot(x="RunSuccess", y='ContactSpeed', data=df, palette="muted")
fig4.set(xlabel='Run Success', ylabel='Contact Speed')
plt.show()
plt.clf()
```
\begin{center}{Figure 4: Run Success vs. Contact Speed}\end{center}
\newpage
# Conclusion and Recommendations
Data should be used to help make better decisions, and discover opportunities to improve efficiency and decision-making in organizations. Given the research agenda and data available in this study it is interesting to see that higher speeds are most definitely correlated with more yards. However, it is far from a perfectly linear relationship. On many plays it is not the highest top speed that matters. Rather, speed varies according to the needs of the situation. This provides at least some support for the idea that player's try to use their speed in an optimal way whether or not they consciously realize it.
Exploring the relationships in the data suggests that successful runs have a higher contact speed when they meet the defense. That higher contact speed is also correlated with yards gained after contact. It is important to remember that while gaining yards after contact is important, gained yards are simply the result of getting other critical aspects of a run play correct.
We note that max speeds on a play have a somewhat non-linear relationship with yards gained after contact. This could potentially be an indication that teams should run more motion plays (e.g., jet motion) in order to allow their rushers to accelerate to a higher speed prior to moving downfield. In that way pre-snap motion might represent much more than simply deception.
Finally, the data seems to suggest that more efficient runners tend to have successful runs.
# Recommendations for Rushers
1. Strive to make runs efficient
2. High contact speed matters
3. Train to get to your max speed quickly
**Note:** This study has been performed with observational data from a portion of one full NFL season. As such these recommendations are merely supported by the provided data but not guaranteed to yield improved performance. Successful execution of any football play depends on a large number of factors that interact in a complex fashion.
\newpage
# Sources
https://www.evanmiller.org/how-not-to-sort-by-average-rating.html
https://nextgenstats.nfl.com/glossary
# Code
https://github.com/bradleynott/NFL-Big-Data-Bowl
<file_sep># NFL-Big-Data-Bowl
23JAN2019
### Purpose
This repository contains my code and write-up for the NFL Big Data Bowl 2019 sponsored by Next Gen Stats.
Per the contest rules I am not allowed to share the data provided for the project, but the workflow has
comments throughout to explain how I went about the arrangment of data and analysis.
There was a lot of low-level event data. Instead of merging all of that data with the higher level tables
I chose to plan my work using the higher level tables. I then worked my way through each lower level event data
file according to that plan.
### Update 24JUN19
Added my explanation for how I interpreted the 'first_contact' tag, and why I made the assumption that it is a reference to the ball carrier. Curiously enough with this data set the play description field/column in the plays.csv file indicated who the ball carrier on each play was but it used an abbreviation. The sensor data identifies players with their full names. With a little cross referencing of the player profile data and some disambiguation work I was able to identify and extract the data for ball carriers on each rushing play.
### Update 27JAN19
Recreated report PDF (nfl_big_data_bowl_Brad_Nott_v3.pdf) using R markdown to correct the low resolution plots. Markdown file incorporates Python and R code. CSV data loaded in markdown file were derived from the raw data using master.py
R markdown file is now the primary source for plotting code (not master.py)
### Update 25JAN19
Added code at line 522 in master.py that recreates the previously constructed running back ranking to include the new variables generated by iterating over the tracking file data. This way you can not only see how the running backs rank according to the previously calculated adjusted success rate metric, but you can also see their individual performance in other areas that might have contributed to their success rate.
For some reason I was not able to eliminate all QB rushes from consideration so the output of this code includes some quarterbacks with rushes and corresponding calcualted data, and some with rushes and no calculated data.
### Note 1:
I orignially planned to examine rushing player data and wide receiver data. However times constraints led me to structure my research question to focus on rushing plays only. You will notice in my Python script that I initially performed subsets to retain pass plays and rushing plays. However, prior to iterating throug all of the tracking data I created a dictionary of games (keys) and play numbers (values) for ONLY non-QB non-fumble rushing plays. You could certainly extend the ideas that I considered to other player positions, but I limited the scope of my analysis to rushing plays only in order to comply with the deadline.
### Note 2:
In the Python script functions and code appear as the analysis requires instead of placing all functions at the beginning or in a separate file to be imported. If anything is confusing just ask. If you have access to the same data and want to use my code, run it a few lines at a time like you might a Jupyter Notebook.
Compute time (single thread) to loop through all low-level event data files(loop at code line 426), subset, and apply
necessary functions was ~3 min.
Total Data size:
- ~2 GB
Data Structure:
- collection of 94 tables extracted from a relational database
Approach overview:
- Subset primary dataframe to collect desired criteria
- Iterate over 91 data files cotaining low-level player tracking (event) data
- Use appropriate criteria to create lookup table for current data file
- Subset and group each data file and apply appropriate functions
Computer:
- Desktop with Intel core i7-8700k and 32 GB RAM
| becf6d6864d869184138a91d3f5db2677b34f6ff | [
"Markdown",
"Python",
"RMarkdown"
] | 3 | Python | bradleynott/NFL-Big-Data-Bowl | 0798cd6a7fb8749c640b0e9d13acec7efbdd7434 | 9706791ad6c1bd139e426e7ce21dbba429b84dd5 | |
refs/heads/master | <file_sep>import React, { useReducer } from "react";
import "./App.css";
import TodoForm from "./components/TodoForm";
import TodoList from "./components/TodoList";
import { initialState, todoReducer } from "./reducers/todoReducer";
const App = () => {
const [state, dispatch] = useReducer(todoReducer, initialState);
// This is adding a TODO to our state
const addTodo = item => dispatch({ type: "ADD_TODO", payload: item });
// This is toggling a TODO's complete
const toggleCompleted = id => dispatch({ type: "TOGGLE_COMPLETED", id: id });
// This is filtering out the completed TODOs
const clearCompleted = () => dispatch({ type: "CLEAR_COMPLETED" });
// This is updating a selected TODO
const updateTodo = (task, id) =>
dispatch({ type: "UPDATE_TODO", payload: { task, id } });
return (
<div className="App">
<div className="header">
<h1>Todos</h1>
<TodoForm addTodo={addTodo} clearCompleted={clearCompleted} />
<TodoList
todos={state.todos}
toggleCompleted={toggleCompleted}
updateTodo={updateTodo}
/>
</div>
</div>
);
};
export default App;
| 3324501ce9c682972f8dc7f6bff6ad50de104721 | [
"JavaScript"
] | 1 | JavaScript | DannyManzietti/reducer-todo | 5e08c996da9497408659858c43d9c03c4c107c9e | 1860d892f7e1e4e8dbcb1927771526b3a6410b54 | |
refs/heads/master | <file_sep>package com.project.roadsideassistant.ui.fragments.review;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.project.roadsideassistant.data.models.Message;
import com.project.roadsideassistant.data.repositories.MessageRepository;
public class ReviewViewModel extends ViewModel implements MessageRepository.MessageTaskListener {
private MessageRepository messageRepository = new MessageRepository(this);
private MutableLiveData<String> _successMessage = new MutableLiveData<>();
private MutableLiveData<String> _errorMessage = new MutableLiveData<>();
public ReviewViewModel() {
}
public void addMessage(Message message) {
messageRepository.add(message);
}
public LiveData<String> getSuccessMessage() {
return _successMessage;
}
public LiveData<String> getErrorMessage() {
return _errorMessage;
}
@Override
public void onComplete(String message) {
_successMessage.setValue(message);
}
@Override
public void onError(Exception exception) {
_errorMessage.setValue(exception.getLocalizedMessage());
}
}
<file_sep>package com.project.roadsideassistant.ui.fragments.notifications;
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import java.lang.reflect.InvocationTargetException;
public class NotificationViewModelFactory implements ViewModelProvider.Factory {
private String userId;
public NotificationViewModelFactory(String userId) {
this.userId = userId;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
try {
return modelClass.getConstructor(String.class).newInstance(userId);
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
}
<file_sep>package com.project.roadsideassistant.data.repositories;
import android.util.Log;
import com.google.firebase.firestore.FirebaseFirestore;
import com.project.roadsideassistant.data.models.Product;
import java.util.List;
public class ProductsRepository {
private static final String TAG = "ProductsRepository";
private FirebaseFirestore mDatabase;
private ProductTaskListener taskListener;
public ProductsRepository(ProductTaskListener taskListener) {
mDatabase = FirebaseFirestore.getInstance();
this.taskListener = taskListener;
}
public void getProducts() {
mDatabase.collection("products")
.addSnapshotListener((queryDocumentSnapshots, e) -> {
if (e != null) {
Log.e(TAG, "getProducts: Products", e);
assert taskListener != null;
taskListener.showError(e.getLocalizedMessage());
return;
}
Log.d(TAG, "getProducts: Successful we are good to go => count: " + queryDocumentSnapshots.size());
taskListener.showProducts(queryDocumentSnapshots.toObjects(Product.class));
});
}
public interface ProductTaskListener {
void showProducts(List<Product> products);
void showError(String message);
}
}
<file_sep>include ':app'
rootProject.name='RoadSideAssistant'
<file_sep>package com.project.roadsideassistant.utils;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
import com.project.roadsideassistant.RoadAssistantApplication;
public class UIHelpers {
public static void toast(String message) {
Toast.makeText(RoadAssistantApplication.getInstance(), message, Toast.LENGTH_SHORT).show();
}
public static void snackbar(View view, String message) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).setAction("OK", v -> {
}).show();
}
}
<file_sep>package com.project.roadsideassistant.ui.fragments.profile;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.project.roadsideassistant.R;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileFragment extends Fragment {
private ProfileViewModel mViewModel;
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private CircleImageView avatarCIV;
private TextView displayNameTV, emailTV, phoneTV, emailNotVerifiedTV;
private MaterialButton setupAccountButton;
public static ProfileFragment newInstance() {
return new ProfileFragment();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.profile_fragment, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Register the vies associated
displayNameTV = view.findViewById(R.id.display_name_tv);
emailTV = view.findViewById(R.id.email_tv);
phoneTV = view.findViewById(R.id.phone_tv);
emailNotVerifiedTV = view.findViewById(R.id.email_not_verified_tv);
setupAccountButton = view.findViewById(R.id.setup_account_button);
avatarCIV = view.findViewById(R.id.avatar_civ);
setupAccountButton.setOnClickListener(v -> {
Navigation.findNavController(v).navigate(R.id.action_profileFragment_to_setupAccountFragment);
});
//Load the image to the image view
Glide.with(this)
.load(currentUser.getPhotoUrl())
.centerCrop()
.placeholder(R.drawable.ic_account_circle_white)
.into(avatarCIV);
//Set display Name
if (!TextUtils.isEmpty(currentUser.getDisplayName())) {
displayNameTV.setText(currentUser.getDisplayName());
}
//Setting the authenticated email address
emailTV.setText(currentUser.getEmail());
//Check user phone number
if (!TextUtils.isEmpty(currentUser.getPhoneNumber())) {
phoneTV.setText(currentUser.getPhoneNumber());
}
//Checking whether whether the authenticated user email is verified and display or hiding the barge if necessary
if (currentUser.isEmailVerified()) {
emailNotVerifiedTV.setVisibility(View.INVISIBLE);
} else {
emailNotVerifiedTV.setVisibility(View.VISIBLE);
}
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(ProfileViewModel.class);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
}
}
<file_sep>package com.project.roadsideassistant.ui.fragments.products;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.project.roadsideassistant.data.models.Product;
import com.project.roadsideassistant.data.repositories.ProductsRepository;
import java.util.List;
public class ProductsViewModel extends ViewModel implements ProductsRepository.ProductTaskListener {
private static final String TAG = "ProductsViewModel";
private ProductsRepository productsRepository;
private MutableLiveData<List<Product>> _products = new MutableLiveData<>();
public ProductsViewModel() {
productsRepository = new ProductsRepository(this);
productsRepository.getProducts();
}
public LiveData<List<Product>> getProducts() {
return _products;
}
@Override
public void showProducts(List<Product> products) {
Log.d(TAG, "showProducts: products size" + products.size());
_products.setValue(products);
}
@Override
public void showError(String message) {
Log.d(TAG, "showError: viewmodel" + message);
//Show error
}
}
<file_sep>package com.project.roadsideassistant.ui.fragments.gethelp.products;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.project.roadsideassistant.R;
import com.project.roadsideassistant.data.models.Message;
public class ChooseProductFragment extends Fragment {
private static final String TAG = "ChooseProductFragment";
private ChooseProductAdapter chooseProductAdapter;
private RecyclerView productsRecyclerView;
private Message message;
public ChooseProductFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
assert getArguments() != null;
//The the message argument first
message = ChooseProductFragmentArgs.fromBundle(getArguments()).getMessage();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.choose_product_fragment, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
assert getContext() != null;
productsRecyclerView = view.findViewById(R.id.products_recycler_view);
productsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
productsRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
productsRecyclerView.setHasFixedSize(true);
//Register the button and it's click listener
Button nextButton = view.findViewById(R.id.next_button);
nextButton.setOnClickListener(v -> {
assert chooseProductAdapter != null;
message.addProducts(chooseProductAdapter.getCheckedProducts());
ChooseProductFragmentDirections.ActionChooseProductFragmentToLocationFragment action = ChooseProductFragmentDirections.actionChooseProductFragmentToLocationFragment();
action.setMessage(message);
Navigation.findNavController(v).navigate(action);
Log.d(TAG, "onViewCreated: products count: " + chooseProductAdapter.getCheckedProducts().size());
});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ChooseProductViewModel mViewModel = new ViewModelProvider(this).get(ChooseProductViewModel.class);
mViewModel.getProducts().observe(getViewLifecycleOwner(), products -> {
chooseProductAdapter = new ChooseProductAdapter(products);
productsRecyclerView.setAdapter(chooseProductAdapter);
});
}
}
<file_sep>package com.project.roadsideassistant.ui.fragments.profile;
import androidx.lifecycle.ViewModel;
public class SetupAccountViewModel extends ViewModel {
}
<file_sep>package com.project.roadsideassistant.ui;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.project.roadsideassistant.R;
import com.project.roadsideassistant.utils.UIHelpers;
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private FirebaseAuth mAuth;
ProgressBar registerProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Instantiating fire-base instance
mAuth = FirebaseAuth.getInstance();
EditText emailTxt = findViewById(R.id.email_txt);
EditText passwordTxt = findViewById(R.id.password_txt);
Button registerButton = findViewById(R.id.register_button);
TextView gotoLoginTv = findViewById(R.id.goto_login_tv);
registerProgressBar = findViewById(R.id.registerProgressBar);
//Registration
registerButton.setOnClickListener(v -> {
String email = emailTxt.getText().toString().trim();
String password = passwordTxt.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
emailTxt.setError("Email is Required");
emailTxt.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
emailTxt.setError("Email is invalid");
emailTxt.requestFocus();
return;
}
if (password.length() < 6) {
passwordTxt.setError("Password should be at least 6 characters");
passwordTxt.requestFocus();
return;
}
registerProgressBar.setVisibility(View.VISIBLE);
registerUser(email, password);
});
gotoLoginTv.setOnClickListener(v -> finish());
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
private void registerUser(String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(task -> {
registerProgressBar.setVisibility(View.INVISIBLE);
if (task.isSuccessful()) {
Intent intent = new Intent(this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
finish();
} else {
assert task.getException() != null;
UIHelpers.toast("Registration failed: " + task.getException().getLocalizedMessage());
Log.e(TAG, "Authentication Failed: ", task.getException());
}
});
}
}
<file_sep>package com.project.roadsideassistant.data.repositories;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
public class UserRepository {
private FirebaseAuth mAuth;
private FirebaseFirestore mDatabase;
public UserRepository() {
mAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseFirestore.getInstance();
}
public void getUserDetails(){
assert mAuth.getCurrentUser() != null;
}
public interface UserTasksListener{
}
}
<file_sep>package com.project.roadsideassistant.data.repositories;
import android.util.Log;
import com.google.firebase.firestore.FirebaseFirestore;
import com.project.roadsideassistant.data.models.Message;
public class MessageRepository {
private FirebaseFirestore mDatabase;
private MessageTaskListener listener;
private static final String TAG = "MessageRepository";
public MessageRepository(MessageTaskListener listener) {
this.listener = listener;
mDatabase = FirebaseFirestore.getInstance();
}
public void add(Message message) {
mDatabase.collection("messages")
.add(message)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.d(TAG, "add: message added in repository");
listener.onComplete("Request Sent Successfully");
} else {
Log.e(TAG, "add: operation failed", task.getException());
listener.onError(task.getException());
}
});
}
public interface MessageTaskListener {
void onComplete(String message);
void onError(Exception exception);
}
}
| 497eed0dda22a18ec1118958b7384bd11d052a15 | [
"Java",
"Gradle"
] | 12 | Java | Azenga/RoadSideAssistant | 592c65e0cdb4877475a731238e1675302dce941a | 81d2c1956ac8f2fcb0402d1b8483a35ea49b870e | |
refs/heads/master | <file_sep>const path = require('path');
const slash = require('slash');
/**
* @typedef {Object<string, string|number|Array|Object>} BannerData
*/
const stringify = JSON.stringify;
class RuntimeGenerator {
static loadBanner(banner, contextPath) {
const modulePath = slash(path.resolve(contextPath, banner.entry));
return `function() {
return new Promise(function(resolve) {
require.ensure([], function(require) {
resolve(require("${modulePath}"));
});
});
}`;
}
/**
* @param {Array<BannerData>} banners
* @param {string} contextPath
* @return {string}
*/
static banners(banners, contextPath) {
const runtime = banners
.map(banner => RuntimeGenerator.banner(banner, contextPath))
.join(',');
return `[${runtime}]`;
}
/**
* @param {BannerData} banner
* @param {string} [contextPath]
* @return {string}
*/
static banner(banner, contextPath) {
const props = Object.keys(banner).reduce((acc, prop) => {
if (prop !== 'entry') {
acc[prop] = stringify(banner[prop]);
}
return acc;
}, {});
props.load = RuntimeGenerator.loadBanner(banner, contextPath);
const runtime = RuntimeGenerator.props(props);
return `{${runtime}}`;
}
/**
* @param {Object<string, string>} props
* @return {string}
*/
static props(props) {
return Object.keys(props)
.map(name => RuntimeGenerator.prop(name, props[name]))
.join(',');
}
/**
* @param {string} name
* @param {string|number|Object|Array} value
* @return {string}
*/
static prop(name, value) {
const val = typeof value !== 'string' ? stringify(value) : value;
return `"${name}":${val}`;
}
}
module.exports = RuntimeGenerator;
<file_sep># Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="0.3.0"></a>
# [0.3.0](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.2.1...v0.3.0) (2018-09-17)
### Features
* webpack 4 interop ([c10090f](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/c10090f))
<a name="0.2.1"></a>
## [0.2.1](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.2.0...v0.2.1) (2018-08-06)
### Bug Fixes
* fix date parsing ([4016eee](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/4016eee))
<a name="0.2.0"></a>
# [0.2.0](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.1.4...v0.2.0) (2018-07-27)
### Features
* add glob matcher to countries ([16077f7](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/16077f7))
<a name="0.1.4"></a>
## [0.1.4](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.1.3...v0.1.4) (2017-12-07)
<a name="0.1.3"></a>
## [0.1.3](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.1.1...v0.1.3) (2017-12-01)
### Bug Fixes
* build script ([406b00c](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/406b00c))
* **loader:** add banners json file to loader dependencies ([9cadb68](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/9cadb68))
<a name="0.1.2"></a>
## [0.1.2](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.1.1...v0.1.2) (2017-12-01)
### Bug Fixes
* build script ([406b00c](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/406b00c))
* **loader:** add banners json file to loader dependencies ([9cadb68](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/9cadb68))
<a name="0.1.1"></a>
## [0.1.1](https://github.com/kisenka/banner-rotator-webpack-plugin/compare/v0.1.0...v0.1.1) (2017-11-27)
### Bug Fixes
* browser runtime script ([cd59302](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/cd59302))
<a name="0.1.0"></a>
# 0.1.0 (2017-11-27)
### Bug Fixes
* **loader:** pass bannerId prop to processBanners ([a021170](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/a021170))
* **location-matcher:** fix multiple matches ([d05a45f](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/d05a45f))
* **plugin:** banner id generator ([aa20fa3](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/aa20fa3))
* **plugin:** fix wrong import ([9931e8c](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/9931e8c))
* **runtime:** change merging utils ([c071061](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/c071061))
* **runtime:** ewoijgw ([9228b20](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/9228b20))
* **runtime:** kenjrkfbhdjls ([a45c44f](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/a45c44f))
* **runtime:** localStorage values parsing ([9bf1902](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/9bf1902))
* **runtime:** process banners properly ([00e7b1a](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/00e7b1a))
* **runtime:** return processed banners from normalizeBanners ([aaa9a0e](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/aaa9a0e))
* **runtime:** wrong reference ([41259b8](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/41259b8))
* **runtime-generator:** better stringifying ([73f4cd7](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/73f4cd7))
* path resolution on Windows ([ffc43b8](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/ffc43b8))
* **runtime-glob-matcher:** process end of the string properly ([628fa9e](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/628fa9e))
* **runtime/glob-matcher:** process arguments properly ([0c5e61e](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/0c5e61e))
* **tests:** plugin tesst ([1f8712d](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/1f8712d))
### Features
* **plugin:** add `chunkId` option which allows to override banner chunk id ([aea072f](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/aea072f))
* **plugin:** pass banners as external JSON file with ([3e5c80e](https://github.com/kisenka/banner-rotator-webpack-plugin/commit/3e5c80e))
<file_sep>import merge from 'merge-options';
import ClosedStorage from './closed-banners-storage';
import globMatcher from './glob-matcher';
import * as defaultConfig from './config';
/**
* @typedef {Object} BannerRotatorFilterCriteria
* @property {Date} date
* @property {string} location
* @property {string} countryCode
*/
export default class BannerRotator {
/**
* @return {Date}
*/
static getUTCDate() {
const now = new Date();
return new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds(),
now.getUTCMilliseconds()
);
}
/**
* @param {Date} [rangeStart]
* @param {Date} [rangeEnd]
* @param {Date} date
* @return {boolean}
*/
static isRangeContainsDate(rangeStart, rangeEnd, date) {
const time = date.getTime();
const startTime = rangeStart && rangeStart.getTime();
const endTime = rangeEnd && rangeEnd.getTime();
const greaterThanStart = startTime ? time >= startTime : true;
const lessThanEnd = endTime ? time <= endTime : true;
return greaterThanStart && lessThanEnd;
}
constructor(config = {}) {
const cfg = merge(defaultConfig, config);
this.config = cfg;
this.closedBannersStorage = cfg.closedBannersStorage || new ClosedStorage();
this.banners = cfg.banners || __BANNER_ROTATOR_BANNERS_CONFIG__; // eslint-disable-line no-undef
this.banners.forEach(b => {
if (typeof b.startDate === 'string') {
b.startDate = new Date(b.startDate);
}
if (typeof b.endDate === 'string') {
b.endDate = new Date(b.endDate);
}
});
this._handleBannerClose = e => this.closeBanner(e.detail);
window.addEventListener(cfg.closeEventName, this._handleBannerClose);
}
/**
* @param {BannerRotatorFilterCriteria} [filterCriteria]
* @return {Promise<Banner[]>}
*/
run(filterCriteria) {
const banners = this.filterBanners(filterCriteria);
const promises = banners.map(banner => banner.load()
.then(module => (banner.module = module))
.then(() => banner)
);
return Promise.all(promises);
}
/**
* @param {BannerRotatorFilterCriteria} [criteria]
* @return {Array<Banner>}
*/
filterBanners(criteria = {}) {
const {
date = BannerRotator.getUTCDate(),
location = window.location.pathname,
countryCode
} = criteria;
return this.banners.filter(banner => {
const { id, disabled, startDate, endDate, locations, countries } = banner;
const isClosed = id ? this.isBannerClosed(id) : false;
const isDisabled = typeof disabled === 'boolean' ? disabled : false;
const matchDate = BannerRotator.isRangeContainsDate(startDate, endDate, date);
const matchLocation = locations && location ? globMatcher(locations, location) : true;
const matchCountry = countries && countryCode ? globMatcher(countries, countryCode) : true;
return !isClosed && !isDisabled && matchDate && matchLocation && matchCountry;
});
}
/**
* @param {string} id
* @return {boolean}
*/
isBannerClosed(id) {
return this.closedBannersStorage.has(id);
}
/**
* @param {string} id
*/
closeBanner(id) {
if (!this.isBannerClosed(id)) {
this.closedBannersStorage.add(id);
}
}
reset() {
this.closedBannersStorage.clear();
}
/**
* Detach close banner event and destroy closed banners storage
*/
destroy() {
window.removeEventListener(this.config.closeEventName, this._handleBannerClose);
this.closedBannersStorage.destroy();
}
}
<file_sep>import { closeEventName } from './config';
/**
* @param {string} bannerId
* @param {string} [eventName]
*/
export default function dispatchCloseEvent(bannerId, eventName = closeEventName) {
let event;
if (window.CustomEvent) {
event = new CustomEvent(eventName, { detail: bannerId });
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, false, false, bannerId);
}
window.dispatchEvent(event);
}
<file_sep>const path = require('path');
const glob = require('glob');
const { rollup } = require('rollup');
const resolvePlugin = require('rollup-plugin-node-resolve');
const commonjsPlugin = require('rollup-plugin-commonjs');
const bublePlugin = require('rollup-plugin-buble');
const root = path.resolve(__dirname, '..');
const src = path.resolve(root, 'src/browser');
const dest = path.resolve(root, 'browser');
const promises = glob.sync(path.join(src, '*.js')).map(entryPath => {
const entryName = path.basename(entryPath, path.extname(entryPath));
const outputPath = path.resolve(dest, `${entryName}.js`);
return rollup({
input: entryPath,
plugins: [
resolvePlugin(),
commonjsPlugin(),
bublePlugin()
]
})
.then(bundle => {
bundle.write({
file: outputPath,
format: 'cjs',
sourcemap: true
});
})
.catch(e => console.log(`Runtime build ERROR: ${e.message}`));
});
Promise.all(promises);
<file_sep>const Generator = require('../../src/lib/runtime-generator');
describe('runtime-generator', () => {
describe('#prop()', () => {
it('should work', () => {
Generator.prop('foo-bar', 'olala').should.be.equal('"foo-bar":olala');
Generator.prop('foo-bar', '"string"').should.be.equal('"foo-bar":"string"');
Generator.prop('foo-bar', '\'string\'').should.be.equal('"foo-bar":\'string\'');
Generator.prop('foo-bar', 1).should.be.equal('"foo-bar":1');
Generator.prop('foo-bar', 'function(){}').should.be.equal('"foo-bar":function(){}');
Generator.prop('foo-bar', [1, 2, 3]).should.be.equal('"foo-bar":[1,2,3]');
Generator.prop('foo-bar', { a: 1 }).should.be.equal('"foo-bar":{"a":1}');
});
});
describe('#props()', () => {
it('should work', () => {
const input = { a: 1, b: '"2"' };
const expected = `"a":1,"b":"2"`; // eslint-disable-line quotes
Generator.props(input).should.be.equal(expected);
});
});
});
<file_sep>const webpackMerge = require('webpack-merge');
const {
LOADER_PATH,
plugin: defaultConfig
} = require('../../src/lib/config');
const webpackConfig = require('../../webpack.config');
const Plugin = require('../../src/lib/plugin');
const utils = require('../utils');
const { createCompiler } = utils;
const compile = config => {
const merged = webpackMerge(webpackConfig, {
entry: './entry',
mode: 'development',
devtool: false
}, config);
return utils.compile(merged);
};
function containChunkIdRuntime(source, chunkId, asNumber) {
const chunkExpr = asNumber ? chunkId : `"${chunkId}"`;
return source.should.contain(`__webpack_require__.e(/*! require.ensure */ ${chunkExpr}`);
}
describe('plugin', () => {
describe('prepare()', () => {
it('should properly add custom loader rules', () => {
const compiler = createCompiler({ entry: './test-banner' })._compiler;
const plugin = new Plugin();
plugin.addLoaderForRuntime(compiler);
const [rule] = compiler.options.module.rules;
rule.loader.should.be.equal(LOADER_PATH);
rule.test.should.be.equal(defaultConfig.runtimeModule);
});
});
describe('apply()', () => {
const defaultBanners = [{ entry: './banners/test-banner' }];
const defaultExpectedChunkId = 'banners/0';
const defaultExpectedChunkFilename = `${defaultExpectedChunkId}.js`;
it('should replace banners placeholder and create lazy chunk', async () => {
const expectedChunkId = defaultExpectedChunkId;
const expectedChunkFilename = defaultExpectedChunkFilename;
const { assets } = await compile({
plugins: [
new Plugin({ banners: defaultBanners })
]
});
const source = assets['main.js'].source();
containChunkIdRuntime(source, expectedChunkId);
source.should.and.not.contain(defaultConfig.runtimePlaceholder);
assets.should.contain.property(expectedChunkFilename);
});
it('should allow to override banner chunk id', async () => {
const customChunkId = 'qwe/[id]';
const expectedChunkId = 'qwe/0';
const expectedChunkFilename = `${expectedChunkId}.js`;
const { assets } = await compile({
plugins: [
new Plugin({ banners: defaultBanners, chunkId: customChunkId })
]
});
const source = assets['main.js'].source();
containChunkIdRuntime(source, expectedChunkId);
assets.should.contain.property(expectedChunkFilename);
});
it('should allow to pass falsy value as chunkId and dont\'t touch chunk id then', async () => {
const chunkId = null;
const expectedChunkId = '0';
const expectedChunkFilename = `${expectedChunkId}.js`;
const { assets } = await compile({
plugins: [
new Plugin({ banners: defaultBanners, chunkId })
]
});
const source = assets['main.js'].source();
containChunkIdRuntime(source, expectedChunkId, true);
assets.should.contain.property(expectedChunkFilename);
});
it('should allow to pass path to banners json file', async () => {
const { assets } = await compile({
plugins: [
new Plugin({
banners: './banners.json'
})
]
});
const source = assets['main.js'].source();
containChunkIdRuntime(source, defaultExpectedChunkId);
assets.should.contain.property(defaultExpectedChunkFilename);
});
it('should allow to postprocess banners', async () => {
const { assets } = await compile({
plugins: [
new Plugin({
banners: defaultBanners,
process: banners => {
banners.forEach(b => b.id = 'tralala');
return banners;
}
})
]
});
assets['main.js'].source().should.contain('tralala');
});
});
});
<file_sep>const merge = require('merge-options');
const {
NAMESPACE,
LOADER_PATH,
plugin: defaultConfig
} = require('./config');
/**
* @typedef {Object} Banner
* @property {string} id
*/
class BannerRotatorPlugin {
/**
* @param {BannerRotatorPluginConfig} [config]
*/
constructor(config) {
this.config = merge(defaultConfig, config);
}
/**
* @param {Compiler} compiler
* @return {Compiler}
*/
addLoaderForRuntime(compiler) {
const compilerOptions = compiler.options;
const runtimeModule = this.config.runtimeModule;
/* istanbul ignore if */
if (!compilerOptions.module) {
compilerOptions.module = {};
}
/* istanbul ignore if */
if (!compilerOptions.module.rules) {
compilerOptions.module.rules = [];
}
compilerOptions.module.rules.push({
test: runtimeModule,
loader: LOADER_PATH
});
return compiler;
}
getRuntimeModule(compilation) {
return compilation.modules
.find(m => m.loaders
.some(({ loader }) => loader === LOADER_PATH)
);
}
/**
* Return banners chunks
* @param {Array<Chunk>} chunks
* @return {Array<Chunk>}
*/
getBannersChunks(chunks, compilation) {
const runtimeModule = this.getRuntimeModule(compilation);
const runtimeModulePath = this.config.runtimeModule;
if (compilation.hooks) {
const asyncChunks = chunks
.map(chunk => Array.from(chunk.getAllAsyncChunks().values()))
.reduce((acc, chunkChunks) => acc.concat(chunkChunks), []);
const bannersChunks = asyncChunks.filter(chunk => chunk.getModules()
.some(m => m.reasons
.some(reason => reason.module === runtimeModule)
));
return bannersChunks;
}
return chunks.filter(chunk => chunk.origins
.map(origin => origin.module.resource)
.some(resource => resource === runtimeModulePath));
}
apply(compiler) {
this.addLoaderForRuntime(compiler);
if (compiler.hooks) {
compiler.hooks.emit.tapAsync(NAMESPACE, (compilation, done) => {
done();
});
compiler.hooks.thisCompilation.tap(NAMESPACE, compilation => {
compilation.hooks.normalModuleLoader
.tap(NAMESPACE, loaderCtx => this.hookNormalModuleLoader(loaderCtx));
compilation.hooks.afterOptimizeChunkIds
.tap(NAMESPACE, chunks => {
this.hookOptimizeChunkIds(chunks, compilation);
});
});
} else {
compiler.plugin('this-compilation', compilation => {
compilation.plugin('normal-module-loader', loaderCtx => {
this.hookNormalModuleLoader(loaderCtx);
});
compilation.plugin('optimize-chunk-ids', chunks => {
this.hookOptimizeChunkIds(chunks, compilation);
});
});
}
}
hookNormalModuleLoader(loaderContext) {
loaderContext[NAMESPACE] = this;
}
hookOptimizeChunkIds(chunks, compilation) {
const config = this.config;
if (!config.chunkId) {
return;
}
this.getBannersChunks(chunks, compilation).forEach(chunk => {
// Rename banner chunk id
const id = compilation.getPath(config.chunkId, { chunk });
chunk.id = id;
chunk.ids = [id];
});
}
}
module.exports = BannerRotatorPlugin;
<file_sep>#!/usr/bin/env bash
set -e -x
git config user.email "<EMAIL>"
git config user.name "Circle CI"
# Make semantic release
$(npm bin)/standard-version --message 'chore(release): %s [skip ci]' --no-verify
# Publish to NPM
$(npm bin)/ci-publish
# Push to github only if package successfully published to NPM
git push --follow-tags origin master
<file_sep>export const closeEventName = 'banner-rotator-banner-close';
export const closedBannersStorageKey = 'banner-rotator-closed-banners';
<file_sep>import globToRegexp from 'glob-to-regexp';
function isNegative(pattern) {
return pattern.charAt(0) === '!';
}
/**
* Supports:
* - glob star, eg `/path/*`
* - negation of whole expression, eg `!/path/`
* - any single-character match, eg `.jsx?`
* - character ranges [a-z]
* - brace expansion {*.html, *.js}
* - combination of all these things in any proportion
* @see https://github.com/fitzgen/glob-to-regexp#usage
* @param {string} glob Expression with optional glob pattern.
* @return {Function<boolean>} Matcher function
*/
export function createMatcher(glob) {
const negative = isNegative(glob);
const pattern = negative ? glob.substr(1) : glob;
const regexp = globToRegexp(pattern, { extended: true });
/**
* @param {string} value
* @return {boolean}
*/
return function matcher(input) {
const matched = regexp.test(input);
return negative ? !matched : matched;
};
}
/**
* @param {Array<string>} patterns
* @return {Function<boolean>}
*/
export function createMultiMatcher(patterns) {
const normal = patterns.filter(p => !isNegative(p)).map(p => createMatcher(p));
const negation = patterns.filter(p => isNegative(p)).map(p => createMatcher(p));
/**
* @param {string} input
* @return {boolean}
*/
return function multiMatcher(input) {
const satisfyNormal = normal.length > 0
? normal.some(normalMatcher => normalMatcher(input))
: true;
const satisfyNegation = negation.length > 0
? negation.every(negationMatcher => negationMatcher(input))
: true;
return satisfyNormal && satisfyNegation;
};
}
/**
* @param {string|Array<string>} pattern
* @param {string} input
* @return {boolean}
*/
export default function (pattern, input) {
const multiple = Array.isArray(pattern);
const matcher = multiple ? createMultiMatcher(pattern) : createMatcher(pattern);
return matcher(input);
}
<file_sep>/**
* @see https://github.com/leonardoanalista/cz-customizable#options
*/
module.exports = {
types: [
{value: 'feat', name: 'feat: A new feature'},
{value: 'improve', name: 'improve: Kind of small feature, but will not trigger a release'},
{value: 'fix', name: 'fix: A bug fix'},
{value: 'docs', name: 'docs: Documentation changes'},
{value: 'style', name: 'style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)'},
{value: 'refactor', name: 'refactor: A code change that neither fixes a bug nor adds a feature'},
{value: 'perf', name: 'perf: A code change that improves performance'},
{value: 'test', name: 'test: Adding missing tests or update existing'},
{value: 'chore', name: 'chore: Changes to the build process or auxiliary tools and libraries such as documentation generation'},
{value: 'ci', name: 'ci: Continuous intergation related changes'},
{value: 'scripts', name: 'scripts: Scripts related changes'},
{value: 'revert', name: 'revert: Revert to a commit'},
{value: 'WIP', name: 'WIP: Work in progress'}
],
/**
* Specify the scopes for your particular project. Eg.: for some banking system: ["acccounts", "payments"].
* For another travelling application: ["bookings", "search", "profile"].
*/
scopes: [],
/**
* It needs to match the value for field type.
* @example
* scopeOverrides: {
* fix: [
* {name: 'merge'},
* {name: 'style'},
* {name: 'e2eTest'},
* {name: 'unitTest'}
* ]
* }
*/
scopeOverrides: {},
allowCustomScopes: true,
allowBreakingChanges: ['feat', 'fix'],
appendBranchNameToCommitMessage: false,
breakingPrefix: 'BREAKING CHANGE:',
footerPrefix: 'Closes'
};
<file_sep># DEPRECATED
We understood that with modern Webpack we don't need such kind of plugin.
Client side part with improves for requirements of our product
step by step was transformed to product specific.
Also, the plugin was released on npm as alpha version
and by [stat](https://www.npmjs.com/package/webpack-banner-rotator-plugin)
we see max 8 download per week that looks like only our team usages.
By these reasons we decided to deprecate this project. Thanks 🙏
## Webpack Banner Rotator Plugin
<file_sep>/* nyc ignore */
const crypto = require('crypto');
const slugify = require('url-slug');
/**
* @param {Array<Banner>} banners
* @return {Array<Banner>}
*/
function processBanners(banners) {
const filtered = banners.filter(banner => {
const hasEntry = 'entry' in banner;
const isDisabled = typeof banner.disabled === 'boolean' ? banner.disabled : false;
return hasEntry && !isDisabled;
});
filtered.forEach(banner => {
if (typeof banner.id === 'undefined') {
banner.id = slugify(banner.entry);
}
});
return filtered;
}
/**
* @param {Banner} banner
* @param {Array<string>} fields
* @return {string}
*/
function generateId(banner, fields = ['entry', 'id', 'startDate', 'endDate']) {
const data = fields
.filter(field => typeof banner[field] !== 'undefined')
.map(field => JSON.stringify(banner[field]))
.join('_');
const id = crypto.createHash('md5').update(data).digest('hex');
return id;
}
module.exports = processBanners;
module.exports.generateId = generateId;
<file_sep>const path = require('path');
const fs = require('fs');
/**
* @typedef {Object} BannerRotatorPluginConfig
*
* @property {Array<Banner>|string} banners Array of banners or absolute path to JSON file with banners
* @property {string} [chunkId] Use custom chunk id for banner chunks. `[id]` token represents current chunk id.
* NOTICE: it changes only chunk id, which will be used in `chunkFilename` webpack option (`[id].js` by default).
* @example `banners/[id]` will produce chunk files like `banners/0.js`
* @see https://webpack.js.org/configuration/output/#output-chunkfilename
*
* @property {Promise<Array<Banner>>} [process] Process banners by custom used defined function
* @property {string} runtimeModule Path to runtime module. Plugin use it to find modules processed by plugin.
* @property {string} runtimePlaceholder Placeholder which will be replaced with banners config data with runtime to lazy load banner module.
*/
module.exports = {
/**
* Unique filesystem path to identify plugin and share data between plugin and loader.
* @type {string}
*/
NAMESPACE: fs.realpathSync(__dirname),
/**
* Absolute path to loader. Plugin use it when adding loader rules for runtime rotator module.
* @type {string}
*/
LOADER_PATH: path.resolve(__dirname, 'loader.js'),
/**
* @type {BannerRotatorPluginConfig}
*/
plugin: {
banners: undefined,
chunkId: 'banners/[id]',
process: undefined,
runtimeModule: path.resolve(__dirname, '../../browser/rotator.js'),
runtimePlaceholder: '__BANNER_ROTATOR_BANNERS_CONFIG__'
}
};
| e891be98fa7a0b6b78e708f9586c07eecc0a1e4b | [
"JavaScript",
"Markdown",
"Shell"
] | 15 | JavaScript | JetBrains/banner-rotator-webpack-plugin | 391414b4a9f80d32422b61773eedb61a0b8a29bc | 9451d08960839736396bafda4df964ce3e260d02 | |
refs/heads/master | <repo_name>alfredoperez/angular-playground<file_sep>/src/health/workouts/components/workout-type/workout-type.component.ts
import { ChangeDetectionStrategy, Component, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { ControlValueAccessor } from '@angular/forms/src/directives';
export const TYPE_CONTROL_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
// TODO : Remove ForwardRef()
// tslint:disable-next-line:no-forward-ref
useExisting: forwardRef(() => WorkoutTypeComponent),
multi: true
};
@Component({
selector: 'ngx-workout-type',
templateUrl: './workout-type.component.html',
styleUrls: ['./workout-type.component.scss'],
providers: [TYPE_CONTROL_ACCESSOR],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class WorkoutTypeComponent implements ControlValueAccessor {
value: string;
selectors = ['strength', 'endurance'];
private onTouch: Function;
private onModelChange: Function;
writeValue(obj: any): void {
this.value = obj;
}
registerOnChange(fn: any): void {
this.onModelChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
setDisabledState(isDisabled: boolean): void {
throw new Error('Not implemented yet.');
}
setSelected(value: string): void {
this.value = value;
this.onModelChange(value);
this.onTouch();
}
}
<file_sep>/src/health/workouts/containers/workouts/workouts.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
import { Workout, WorkoutsService } from '../../../../shared/services/workouts/workouts.service';
import { Store } from '../../../../store';
@Component({
selector: 'ngx-workouts',
templateUrl: './workouts.component.html',
styleUrls: ['./workouts.component.scss']
})
export class WorkoutsComponent implements OnInit, OnDestroy {
workouts$: Observable<Array<Workout>>;
subscription: Subscription;
constructor(
private store: Store,
private workoutsService: WorkoutsService
) { }
ngOnInit(): void {
this.workouts$ = this.store.select<Array<Workout>>('workouts');
this.subscription = this.workoutsService.workouts$.subscribe();
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
removeWorkout(event: Workout): void {
this.workoutsService.removeWorkout(event.$key);
}
}
| 1c6898c3e404c772916f3ce7fc99ffe4d7250a65 | [
"TypeScript"
] | 2 | TypeScript | alfredoperez/angular-playground | 3aeb236b78102ea9270f3653f6c8b7068941b91f | 35e784a29520ddb36b20527924f3634e1fccb04a | |
refs/heads/master | <file_sep>package front_end;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import back_end.DietaryAccount;
import back_end.Transaction;
public class DietaryAccountView extends JPanel implements ActionListener, Observer{
private BarGraphView barGraph;
private DietaryAccount dietaryAccount;
private JTextField calBalanceTextField, prefField;
private JLabel calBalanceLabel, newCalLabel, unusedCalLabel, mealCalLabel, snackCalLabel, sodaCalLabel, prefLabel, newPref;
private JPanel maxCalPanel, prefPanel, graphLabelPanel, topPanel;
private int mCal, snCal, soCal, totalCal;
public DietaryAccountView(DietaryAccount dietaryAccount) {
this.setLayout(new BorderLayout());
this.dietaryAccount = dietaryAccount;
this.maxCalPanel = new JPanel();
this.prefPanel = new JPanel();
this.topPanel = new JPanel();
maxCalPanel.setLayout(new FlowLayout());
prefPanel.setLayout(new FlowLayout());
topPanel.setLayout(new BoxLayout(topPanel,1));
this.calBalanceLabel = new JLabel("Daily Calories: " + this.dietaryAccount.getMaxCalBalance());
this.maxCalPanel.add(this.calBalanceLabel);
this.newCalLabel = new JLabel(" Set a New Daily Calorie Limit: ");
this.maxCalPanel.add(this.newCalLabel);
this.prefLabel = new JLabel("Preferences: " + this.dietaryAccount.getPreferences());
this.prefPanel.add(prefLabel);
this.newPref = new JLabel(" New Preference: ");
this.prefPanel.add(newPref);
this.calBalanceTextField = new JTextField(6);
this.maxCalPanel.add(this.calBalanceTextField);
this.prefField = new JTextField(12);
this.prefPanel.add(this.prefField);
this.calBalanceTextField.addActionListener(this);
this.prefField.addActionListener(this);
topPanel.add(maxCalPanel);
topPanel.add(prefPanel);
this.add(topPanel, BorderLayout.NORTH);
//this.transactionPanel = new JPanel();
ArrayList<Transaction> transactions = this.dietaryAccount.getTransactions();
mCal=snCal=soCal=0;
for (int i = 0; i < transactions.size(); ++i) {
mCal += transactions.get(i).getMealCal();
snCal += transactions.get(i).getSnackCal();
soCal += transactions.get(i).getSodaCal();
}
int nums[] = {dietaryAccount.getCalBalance(),mCal,snCal,soCal};
barGraph = new BarGraphView(nums);
this.add(barGraph, BorderLayout.CENTER);
unusedCalLabel = new JLabel("Unused: " + dietaryAccount.getCalBalance());
mealCalLabel = new JLabel("Meal: " + mCal);
snackCalLabel = new JLabel("Snack: " + snCal);
sodaCalLabel = new JLabel("Soda: " + soCal);
graphLabelPanel = new JPanel();
graphLabelPanel.setLayout(new FlowLayout(1,75,0));
graphLabelPanel.add(unusedCalLabel);
graphLabelPanel.add(mealCalLabel);
graphLabelPanel.add(snackCalLabel);
graphLabelPanel.add(sodaCalLabel);
this.add(graphLabelPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==calBalanceTextField)
{
int newCalBalance = this.dietaryAccount.getMaxCalBalance();
try {
String temp = calBalanceTextField.getText();
newCalBalance= Integer.parseInt(temp);
} catch (Exception ex){
return;
}
this.dietaryAccount.setMaxCalBalance(newCalBalance);
this.calBalanceLabel.setText("Daily Calories: " + this.dietaryAccount.getMaxCalBalance());
ArrayList<Transaction> transactions = this.dietaryAccount.getTransactions();
mCal=snCal=soCal=0;
for (int i = 0; i < transactions.size(); ++i) {
mCal += transactions.get(i).getMealCal();
snCal += transactions.get(i).getSnackCal();
soCal += transactions.get(i).getSodaCal();
}
int nums[] = {dietaryAccount.getCalBalance(),mCal,snCal,soCal};
this.remove(barGraph);
barGraph = new BarGraphView(nums);
this.add(barGraph, BorderLayout.CENTER);
unusedCalLabel.setText("Unused: " + dietaryAccount.getCalBalance());
mealCalLabel.setText("Meal: " + mCal);
snackCalLabel.setText("Snack: " + snCal);
sodaCalLabel.setText("Soda: " + soCal);
}
if(e.getSource()==prefField)
{
if(prefField.getText().equals("Delete"))
this.dietaryAccount.removePreferences();
else
{
for(int i=0; i<dietaryAccount.getPreferences().size(); i++)
{
if(prefField.getText().toUpperCase().equals(dietaryAccount.getPreferences().get(i)))
return;
}
this.dietaryAccount.addPreference(prefField.getText().toUpperCase());
this.prefLabel.setText("Preferences: " + this.dietaryAccount.getPreferences());
}
}
this.revalidate();
this.repaint();
}
public void update(Observable o, Object arg)
{
this.calBalanceLabel.setText("Daily Calories: " + this.dietaryAccount.getMaxCalBalance());
ArrayList<Transaction> transactions = this.dietaryAccount.getTransactions();
mCal=snCal=soCal=0;
for (int i = 0; i < transactions.size(); ++i) {
mCal += transactions.get(i).getMealCal();
snCal += transactions.get(i).getSnackCal();
soCal += transactions.get(i).getSodaCal();
}
int nums[] = {dietaryAccount.getCalBalance(),mCal,snCal,soCal};
this.remove(barGraph);
barGraph = new BarGraphView(nums);
this.add(barGraph, BorderLayout.CENTER);
unusedCalLabel.setText("Unused: " + dietaryAccount.getCalBalance());
mealCalLabel.setText("Meal: " + mCal);
snackCalLabel.setText("Snack: " + snCal);
sodaCalLabel.setText("Soda: " + soCal);
this.revalidate();
this.repaint();
}
}
<file_sep>#Tue Mar 05 15:34:41 PST 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.10.0.v20181206-0815
<file_sep>package back_end;
import java.io.Serializable;
public class User implements Serializable {
private String password;
private ExpenseAccount expenseAccount;
private DietaryAccount dietaryAccount;
public User(String password) {
this.password = <PASSWORD>;
expenseAccount = new ExpenseAccount(0);
dietaryAccount = new DietaryAccount(2000);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ExpenseAccount getExpenseAccount() {
return expenseAccount;
}
public DietaryAccount getDietaryAccount() {
return dietaryAccount;
}
public void setExpenseAccount(ExpenseAccount expenseAccount) {
this.expenseAccount = expenseAccount;
}
public void setDietaryAccount(DietaryAccount dietaryAccount) {
this.dietaryAccount = dietaryAccount;
}
}
<file_sep>package back_end;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Observer;
public class Cafe extends FoodProvider{
public Cafe(String name, ArrayList<Food> menu, Point location) {
super(name, menu, location);
}
public String getPickupLocation()
{
return "Pickup your order at "+ this.getName();
}
}
<file_sep>package front_end;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import back_end.Cafe;
import back_end.Food;
import back_end.FoodProvider;
import back_end.Transaction;
import back_end.User;
public class FoodProviderView extends JPanel implements ActionListener {
private FoodProvider foodProvider;
private JButton orderButton;
private JLabel nameLabel;
private JPanel menuPanel;
private JCheckBox[] menuItems;
public FoodProviderView(FoodProvider foodProvider) {
this.setLayout(new BorderLayout());
this.foodProvider = foodProvider;
this.orderButton = new JButton("Order");
this.orderButton.addActionListener(this);
this.add(this.orderButton, BorderLayout.SOUTH);
this.nameLabel = new JLabel(this.foodProvider.getName(), JLabel.CENTER);
this.nameLabel.setFont(new Font("Serif", Font.BOLD, 16));
this.add(this.nameLabel, BorderLayout.NORTH);
this.menuPanel = new JPanel();
this.menuPanel.setLayout(new BoxLayout(this.menuPanel, BoxLayout.Y_AXIS));
ArrayList<Food> menuOptions = this.foodProvider.getMenu();
this.menuItems = new JCheckBox[menuOptions.size()];
for (int i = 0; i < menuOptions.size(); ++i) {
JCheckBox menuItem = new JCheckBox(menuOptions.get(i).toString());
this.menuItems[i] = menuItem;
this.menuPanel.add(menuItem);
}
this.add(this.menuPanel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e) {
if (MainView.currentUser != null) {
User user = MainView.currentUser;
ArrayList<Food> selectedItems = new ArrayList<Food>();
for (int i = 0; i < this.menuItems.length; i++) {
if (this.menuItems[i].isSelected()) {
selectedItems.add(this.foodProvider.getMenu().get(i));
}
}
Food[] selectedItemsArray = new Food[selectedItems.size()];
selectedItemsArray = selectedItems.toArray(selectedItemsArray);
Transaction transaction = new Transaction(user, selectedItemsArray);
Boolean insufficientBalance = user.getExpenseAccount().getBalance() < transaction.getTotalCost();
Boolean insufficientCalBal = user.getDietaryAccount().getCalBalance() < transaction.getCal();
if (insufficientBalance) {
JOptionPane.showMessageDialog(null, "Not enough balance in expense account");
} else if (insufficientCalBal) {
JOptionPane.showMessageDialog(null, "Exceeding your calorie balance");
} else {
this.foodProvider.updateAccounts(transaction);
if (this.foodProvider instanceof Cafe) {
JOptionPane.showMessageDialog(null, ((Cafe) this.foodProvider).getPickupLocation());
} else {
JOptionPane.showMessageDialog(null, "Vending machine has dispensed your food");
}
this.setVisible(false);
}
}
}
public FoodProvider getFoodProvider() {
return foodProvider;
}
}
<file_sep>package back_end;
import java.io.Serializable;
import java.util.ArrayList;
public class ExpenseAccount implements Serializable {
private double balance;
private ArrayList<Transaction> transactions;
public ExpenseAccount(double balance) {
this.balance = balance;
this.transactions = new ArrayList<Transaction>();
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
private void decrementBalance(double amount) {
this.setBalance(this.balance - amount);
}
public ArrayList<Transaction> getTransactions() {
return transactions;
}
public void addTransaction(Transaction transactions) {
this.transactions.add(transactions);
this.decrementBalance(transactions.getTotalCost());
}
@Override
public String toString() {
return balance + ";" + transactions;
}
}
<file_sep>package back_end;
import java.io.Serializable;
public class Soda extends Food implements Serializable {
public Soda(String name, int CalCount, double price) {
super(name, CalCount, price);
}
}
<file_sep>package front_end;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import back_end.Cafe;
import back_end.DietaryAccount;
import back_end.ExpenseAccount;
import back_end.Food;
import back_end.Meal;
import back_end.User;
import back_end.UserManager;
import back_end.UserValidator;
public class MainView implements Observer {
public static User currentUser;
public static ExpenseAccountView expenseAccountView;
public static DietaryAccountView dietaryAccountView;
private JFrame frame;
private JTabbedPane tabbedPane;
private UserManager userData;
private CampusMapView mapView;
public MainView() {
currentUser = null;
this.frame = new JFrame("CampusSmartCafe");
this.frame.setLayout(new BorderLayout());
this.tabbedPane = new JTabbedPane();
this.userData = new UserManager();
this.userData.readFromFile();
UserValidator userValid = new UserValidator(this.userData);
LoginTotalView loginView = new LoginTotalView(userValid, this);
this.tabbedPane.addTab("Login", loginView.getLoginPanel());
this.frame.add(this.tabbedPane, BorderLayout.CENTER);
this.frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
userData.writeToFile();
}
});
this.frame.setSize(600, 800);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setLocationRelativeTo(null);
this.frame.setVisible(true);
}
@Override
public void update(Observable o, Object arg) {
User user = (User) arg;
MainView.currentUser = user;
this.tabbedPane.remove(this.mapView);
this.tabbedPane.remove(expenseAccountView);
this.tabbedPane.remove(dietaryAccountView);
expenseAccountView = new ExpenseAccountView(user.getExpenseAccount());
dietaryAccountView = new DietaryAccountView(user.getDietaryAccount());
this.mapView = new CampusMapView();
this.tabbedPane.addTab("Map", mapView);
this.tabbedPane.addTab("Expenses", expenseAccountView);
this.tabbedPane.addTab("Diet", dietaryAccountView);
this.tabbedPane.setSelectedIndex(1);
this.frame.validate();
this.frame.repaint();
}
public static void main(String[] args) {
new MainView();
}
}
<file_sep>package front_end;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import back_end.ExpenseAccount;
import back_end.Transaction;
public class ExpenseAccountView extends JPanel implements ActionListener, Observer {
private ExpenseAccount expenseAccount;
private JTextField balanceTextField;
private JLabel balanceLabel;
private JLabel newBalanceLabel;
private JPanel balancePanel;
private JPanel transactionPanel;
private Border border;
public ExpenseAccountView(ExpenseAccount expenseAccount) {
this.setLayout(new BorderLayout());
this.expenseAccount = expenseAccount;
this.balancePanel = new JPanel();
balancePanel.setLayout(new FlowLayout());
this.balanceLabel = new JLabel("Balance: $" + this.expenseAccount.getBalance(), JLabel.CENTER);
this.balancePanel.add(this.balanceLabel);
this.newBalanceLabel = new JLabel(" Set a New Balance: ");
this.balancePanel.add(this.newBalanceLabel);
this.balanceTextField = new JTextField(6);
this.balanceTextField.addActionListener(this);
this.balancePanel.add(this.balanceTextField);
this.add(balancePanel, BorderLayout.NORTH);
this.transactionPanel = new JPanel();
this.transactionPanel.setLayout(new BoxLayout(this.transactionPanel, BoxLayout.Y_AXIS));
ArrayList<Transaction> transactions = this.expenseAccount.getTransactions();
this.border = BorderFactory.createLineBorder(Color.LIGHT_GRAY, 4);
for (int i = 0; i < transactions.size(); ++i) {
JLabel label = new JLabel("<html>Total Cost: $" + transactions.get(i).getTotalCost() + "<br/>"
+ Arrays.toString(transactions.get(i).getPurchases()) + "</html>");
label.setBorder(this.border);
this.transactionPanel.add(label);
}
this.add(transactionPanel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
double newBalance = this.expenseAccount.getBalance();
try {
newBalance = Double.parseDouble(balanceTextField.getText());
} catch (NumberFormatException ex) {
return;
}
DecimalFormat moneyFormat = new DecimalFormat("#.##");
moneyFormat.setRoundingMode(RoundingMode.DOWN);
newBalance = Double.parseDouble(moneyFormat.format(newBalance));
this.expenseAccount.setBalance(newBalance);
this.balanceLabel.setText("Balance: $" + this.expenseAccount.getBalance());
}
@Override
public void update(Observable o, Object arg) {
Transaction transaction = (Transaction) arg;
JLabel label = new JLabel("<html>Total Cost: $" + transaction.getTotalCost() + "<br/>"
+ Arrays.toString(transaction.getPurchases()) + "</html>");
label.setBorder(this.border);
this.transactionPanel.add(label);
this.balanceLabel.setText("Balance: $" + this.expenseAccount.getBalance());
this.validate();
this.repaint();
}
}
<file_sep># CampusSmartCafe
COEN 160 Final Project
<file_sep>package front_end;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.JPanel;
public class BarGraphView extends JPanel{
private Map<Color, Integer> bars = new LinkedHashMap<Color, Integer>();
private Color barColors[] = {Color.LIGHT_GRAY,Color.RED, Color.BLUE, Color.GREEN}; ;
public BarGraphView(int[] calData) {
for (int i=0; i<barColors.length; ++i) {
if(calData[i]<0)
calData[i]=0;
bars.put(barColors[i],calData[i]);
}
}
protected void paintComponent(Graphics gp) {
super.paintComponent(gp);
// Cast the graphics objects to Graphics2D
Graphics2D g = (Graphics2D) gp;
// determine longest bar
int max = Integer.MIN_VALUE;
for (Integer value : bars.values()) {
max = Math.max(max, value);
}
// paint bars
int width = (getWidth() / bars.size()) - 2;
int x = 1;
for (Color color : bars.keySet()) {
int value = bars.get(color);
int height = (int) ((getHeight() - 50) * ((double) value / max));
g.setColor(color);
g.fillRect(x, getHeight() - height, width, height);
g.setColor(Color.black);
g.drawRect(x, getHeight() - height, width, height);
x += (width + 2);
}
}
public Dimension getPreferredSize() {
return new Dimension(bars.size() * 10 + 2, 50);
}
}
<file_sep>package back_end;
public class UserValidator {
private UserManager users;
public UserValidator(UserManager users)
{
this.users=users;
}
public User login(String userName, String password)
{
User temp = null;
if(checkPassword(userName, password))
temp=users.getUser(userName);
return temp;
}
public UserManager getUserManager()
{
return users;
}
private boolean checkPassword(String userName, String password)
{
User subject;
try
{
subject= users.getUser(userName);
}catch(NullPointerException e) {
return false;
}
if(subject==null)
return false;
if(subject.getPassword().equals(password))
return true;
return false;
}
}
<file_sep>package back_end;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Observer;
public class VendingMachine extends FoodProvider {
public VendingMachine(String name, ArrayList<Food> menu, Point location) {
super(name, menu, location);
}
}
<file_sep>package back_end;
import java.io.Serializable;
import java.util.ArrayList;
public class DietaryAccount implements Serializable {
private int maxCalBalance;
private ArrayList<String> preferences;
private ArrayList<Transaction> transactions;
public DietaryAccount(int calBalance) {
this.maxCalBalance = calBalance;
preferences = new ArrayList<String>();
transactions = new ArrayList<Transaction>();
}
public int getCalBalance() {
int total=0;
for(int i=0; i<transactions.size(); i++)
total+=transactions.get(i).getCal();
return maxCalBalance-total;
}
public int getMaxCalBalance() {
return maxCalBalance;
}
public void setMaxCalBalance(int calBalance) {
this.maxCalBalance = calBalance;
if(this.maxCalBalance<this.getCalBalance())
this.maxCalBalance = this.getCalBalance();
}
public ArrayList<String> getPreferences() {
return preferences;
}
public void addPreference(String preference) {
this.preferences.add(preference);
}
public boolean removePreferences() {
return preferences.removeAll(preferences);
}
public ArrayList<Transaction> getTransactions() {
return transactions;
}
public void addTransaction(Transaction transactions) {
this.transactions.add(transactions);
}
public void clearTransactions()
{
this.transactions.removeAll(transactions);
}
@Override
public String toString() {
return this.getCalBalance() + ";" + maxCalBalance + ";" + preferences + ";" + transactions;
}
}
| cf2d98c2c584e2eb7e613be6ef654e426786f343 | [
"Markdown",
"Java",
"INI"
] | 14 | Java | pwahrens/CampusSmartCafe | b3fbadbaf6123324302d43110550807f46801017 | d53d02578bebdfaee0444f94e6d47532a6ba3a9f | |
refs/heads/master | <repo_name>medranSolus/ZooManager<file_sep>/Test/GetModelsTest.cs
using Moq;
using ZooService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace Test
{
[TestClass]
public class GetModelsTest
{
ZooService.ZooService service;
Mock<ZooContext> IZooContext;
List<Animal> animals;
[TestInitialize]
public void SetUp()
{
IZooContext = new Mock<ZooContext>();
service = new ZooService.ZooService(1111);
animals = new List<Animal>();
var animal = new Animal();
animals.Add(animal);
}
[TestMethod]
public void Returns_not_empty_list()
{
IZooContext.Setup(x => x.GetModels<Animal>()).Returns(animals);
var models = service.GetModels(IZooContext.Object, ZooService.ModelType.Animal);
Assert.IsTrue(models is List<ZooDataModel>);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count > 0);
}
[TestMethod]
public void Returns_empty_list()
{
IZooContext.Setup(x => x.GetModels<Overtime>()).Returns(new List<Overtime>());
IZooContext.Setup(x => x.GetModels<Place>()).Returns(new List<Place>());
IZooContext.Setup(x => x.GetModels<Worker>()).Returns(new List<Worker>());
IZooContext.Setup(x => x.GetModels<Attraction>()).Returns(new List<Attraction>());
IZooContext.Setup(x => x.GetModels<BalanceType>()).Returns(new List<BalanceType>());
IZooContext.Setup(x => x.GetModels<CashBalance>()).Returns(new List<CashBalance>());
IZooContext.Setup(x => x.GetModels<Food>()).Returns(new List<Food>());
var models = service.GetModels(IZooContext.Object, ZooService.ModelType.Overtime);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.Place);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.Worker);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.Attraction);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.BalanceType);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.CashBalance);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
models = service.GetModels(IZooContext.Object, ZooService.ModelType.Food);
Assert.IsTrue(models != null);
Assert.IsTrue(models.Count == 0);
}
[TestMethod]
public void Returns_null()
{
var models = service.GetModels(IZooContext.Object, ZooService.ModelType.Model);
Assert.IsNull(models);
}
}
}
<file_sep>/ZooService/Program.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace ZooService
{
class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
static void Main(string[] args)
{
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "ZooService", out createdNew))
{
if (createdNew)
{
const int port = 2560;
Console.WriteLine($"Starting Zoo Service on port {port}, please wait...");
ZooService service = new ZooService(port);
service.Start();
Console.WriteLine("Zoo Service is ON. Press [E] to stop.");
while (Console.ReadKey().Key == ConsoleKey.E) ;
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}
}
}
<file_sep>/ZooManager/Windows/MainWindow.xaml.cs
using System;
using System.Windows;
using System.Linq;
using System.Threading;
using System.Collections.Generic;
using ZooManager.Views;
using ZooManager.Windows.TabAnimals;
using ZooManager.Windows.TabPlaces;
using ZooManager.Windows.TabWorkers;
using ZooManager.Windows.TabCash;
namespace ZooManager.Windows
{
public partial class MainWindow : Window
{
Thread threadUpdate;
volatile bool update = true;
volatile bool dataGridWorkersShouldClear = false;
volatile bool dataGridAnimalsShouldClear = false;
volatile bool dataGridFoodsShouldClear = false;
volatile bool dataGridPlacesShouldClear = false;
volatile bool dataGridAttractionsShouldClear = false;
List<object> animals = new List<object>();
List<object> attractions = new List<object>();
List<object> cashBalances = new List<object>();
List<object> overtimes = new List<object>();
List<object> workers = new List<object>();
public List<object> BalanceTypes { get; private set; } = new List<object>();
public List<object> Foods { get; private set; } = new List<object>();
public List<object> Places { get; private set; } = new List<object>();
public ZooClient ZooConnection { get; private set; }
public MainWindow()
{
InitializeComponent();
const int port = 2560;
try
{
ZooConnection = new ZooClient(port);
}
catch (Exception e)
{
Logger.LogError($"Cannot load ZooCom.dll: {e.ToString()}", GetType(), "MainWindow()");
Application.Current.Shutdown(-1);
}
dataGridFoods.DataContext = ZooConnection.GetModelType(ModelType.Food);
dataGridPlaces.DataContext = ZooConnection.GetModelType(ModelType.Place);
threadUpdate = new Thread(() =>
{
TimeSpan waitTime = new TimeSpan(0, 5, 0);
while (update)
{
UpdateAnimals();
UpdateAttractions();
UpdateCashBalances();
UpdateFoods();
UpdateOvertimes();
UpdatePlaces();
UpdateWorkers();
Thread.Sleep(waitTime);
}
});
threadUpdate.Start();
}
public IEnumerable<WorkerView> GetWorkerViews()
{
lock (Places)
{
return workers.Join(Places,
worker => ZooClient.GetProperty(worker, "PlaceID"), place => ZooClient.GetProperty(place, "ID"),
(worker, place) => new WorkerView()
{
ID = (int)ZooClient.GetProperty(worker, "ID"),
Surname = (string)ZooClient.GetProperty(worker, "Surname"),
Name = (string)ZooClient.GetProperty(worker, "Name"),
Age = (int)ZooClient.GetProperty(worker, "Age"),
Salary = (decimal)ZooClient.GetProperty(worker, "Salary"),
StartDate = (DateTime)ZooClient.GetProperty(worker, "StartDate"),
Place = (string)ZooClient.GetProperty(place, "Name")
});
}
}
#region Update
void UpdateAnimals()
{
new Thread(() =>
{
IEnumerable<AnimalView> source;
lock (animals)
{
animals = ZooConnection.GetModels(ModelType.Animal);
lock (Places)
lock (Foods)
{
source = animals.Join(Places,
animal => ZooClient.GetProperty(animal, "PlaceID"), place => ZooClient.GetProperty(place, "ID"),
(animal, place) => new
{
ID = (int)ZooClient.GetProperty(animal, "ID"),
Name = (string)ZooClient.GetProperty(animal, "Name"),
Count = (int)ZooClient.GetProperty(animal, "Count"),
MaintenanceCost = (decimal)ZooClient.GetProperty(animal, "MaintenanceCost"),
Place = (string)ZooClient.GetProperty(place, "Name"),
FoodID = (int)ZooClient.GetProperty(animal, "FoodID")
}).Join(Foods,
anon => ZooClient.GetProperty(anon, "FoodID"), food => ZooClient.GetProperty(food, "ID"),
(anon, food) => new AnimalView()
{
ID = anon.ID,
Name = anon.Name,
Count = anon.Count,
MaintenanceCost = anon.MaintenanceCost,
Place = anon.Place,
Food = (string)ZooClient.GetProperty(food, "Name")
});
}
}
dataGridAnimals.Dispatcher.Invoke(() =>
{
buttonModifyAnimal.IsEnabled = false;
buttonRemoveAnimal.IsEnabled = false;
dataGridAnimals.ItemsSource = source;
labelAnimalSpeciesCount.Content = source.Count().ToString();
labelAnimalsCount.Content = source.Sum(animal => animal.Count).ToString();
});
}).Start();
}
void UpdateFoods(int? foodId = null)
{
new Thread(() =>
{
IEnumerable<object> filtered;
lock (Foods)
{
Foods = ZooConnection.GetModels(ModelType.Food);
if (foodId.HasValue)
filtered = Foods.Where(food => (int)ZooClient.GetProperty(food, "ID") == foodId.Value);
else
filtered = Foods;
}
dataGridFoods.Dispatcher.Invoke(() =>
{
buttonModifyFood.IsEnabled = false;
buttonRemoveFood.IsEnabled = false;
dataGridFoods.ItemsSource = filtered;
labelFoodsCount.Content = filtered.Sum(food => (double)ZooClient.GetProperty(food, "Amount")).ToString();
});
}).Start();
}
void UpdateWorkers()
{
new Thread(() =>
{
IEnumerable<WorkerView> source;
lock (workers)
{
workers = ZooConnection.GetModels(ModelType.Worker);
source = GetWorkerViews();
}
dataGridWorkers.Dispatcher.Invoke(() =>
{
buttonModifyWorker.IsEnabled = false;
buttonRemoveWorker.IsEnabled = false;
buttonSubmitOvertime.IsEnabled = false;
dataGridWorkers.ItemsSource = source;
labelWorkersCount.Content = source.Count().ToString();
});
}).Start();
}
void UpdateOvertimes(int? workerId = null)
{
new Thread(() =>
{
IEnumerable<object> filtered;
lock (overtimes)
{
overtimes = ZooConnection.GetModels(ModelType.Overtime);
if (workerId.HasValue)
filtered = overtimes.Where(overtime => (int)ZooClient.GetProperty(overtime, "WorkerID") == workerId.Value);
else
filtered = overtimes;
lock (workers)
{
filtered = filtered.Join(workers,
overtime => ZooClient.GetProperty(overtime, "WorkerID"), worker => ZooClient.GetProperty(worker, "ID"),
(overtime, worker) => CreateOvertimeView(overtime, worker));
}
}
dataGridOvertimes.Dispatcher.Invoke(() =>
{
dataGridOvertimes.ItemsSource = filtered;
});
}).Start();
}
void UpdateCashBalances()
{
new Thread(() =>
{
IEnumerable<CashBalanceView> source;
lock (BalanceTypes)
{
BalanceTypes = ZooConnection.GetModels(ModelType.BalanceType);
lock (cashBalances)
{
cashBalances = ZooConnection.GetModels(ModelType.CashBalance);
source = cashBalances.Join(BalanceTypes,
balance => ZooClient.GetProperty(balance, "BalanceTypeID"), type => ZooClient.GetProperty(type, "ID"),
(balance, type) => new CashBalanceView()
{
ID = (int)ZooClient.GetProperty(balance, "ID"),
SubmitDate = (DateTime)ZooClient.GetProperty(balance, "SubmitDate"),
Money = (decimal)ZooClient.GetProperty(balance, "Money"),
Type = (string)ZooClient.GetProperty(type, "Description"),
DetailedDescription = (string)ZooClient.GetProperty(balance, "DetailedDescription")
});
}
}
dataGridCashBalances.Dispatcher.Invoke(() =>
{
dataGridCashBalances.ItemsSource = source.OrderByDescending(balance => balance.SubmitDate);
});
}).Start();
}
void UpdatePlaces()
{
new Thread(() =>
{
lock (Places)
Places = ZooConnection.GetModels(ModelType.Place);
dataGridPlaces.Dispatcher.Invoke(() =>
{
buttonModifyPlace.IsEnabled = false;
buttonRemovePlace.IsEnabled = false;
dataGridPlaces.ItemsSource = Places;
labelPlacesCount.Content = Places.Count.ToString();
});
}).Start();
}
void UpdateAttractions(int? placeId = null)
{
new Thread(() =>
{
IEnumerable<AttractionView> source;
lock (attractions)
{
attractions = ZooConnection.GetModels(ModelType.Attraction);
IEnumerable<object> filtered;
if (placeId.HasValue)
filtered = attractions.Where(attraction => (int)ZooClient.GetProperty(attraction, "PlaceID") == placeId.Value);
else
filtered = attractions;
lock (Places)
lock (workers)
{
source = filtered.Join(Places,
attraction => ZooClient.GetProperty(attraction, "PlaceID"), place => ZooClient.GetProperty(place, "ID"),
(attraction, place) => new
{
ID = (int)ZooClient.GetProperty(attraction, "ID"),
Name = (string)ZooClient.GetProperty(attraction, "Name"),
Description = (string)ZooClient.GetProperty(attraction, "Description"),
AttractionManagerID = (int)ZooClient.GetProperty(attraction, "AttractionManagerID"),
Place = (string)ZooClient.GetProperty(place, "Name")
}).Join(workers,
anon => ZooClient.GetProperty(anon, "AttractionManagerID"), worker => ZooClient.GetProperty(worker, "ID"),
(anon, worker) => new AttractionView()
{
ID = anon.ID,
Name = anon.Name,
Description = anon.Description,
AttractionManager = (string)ZooClient.GetProperty(worker, "Name") + " " + (string)ZooClient.GetProperty(worker, "Surname"),
Place = anon.Place
});
}
dataGridAttractions.Dispatcher.Invoke(() =>
{
buttonModifyAttraction.IsEnabled = false;
buttonRemoveAttraction.IsEnabled = false;
dataGridAttractions.ItemsSource = source;
labelAttractionsCount.Content = source.Count();
});
}
}).Start();
}
#endregion Update
OvertimeView CreateOvertimeView(object overtime, object worker)
{
return new OvertimeView()
{
ID = (int)ZooClient.GetProperty(overtime, "ID"),
Date = (DateTime)ZooClient.GetProperty(overtime, "Date"),
Hours = (int)ZooClient.GetProperty(overtime, "Hours"),
PaymentPercentage = (int)ZooClient.GetProperty(overtime, "PaymentPercentage"),
Employee = (string)ZooClient.GetProperty(worker, "Name") + " " + (string)ZooClient.GetProperty(worker, "Surname")
};
}
#region Animals Tab
void ButtonRefreshAnimals_Click(object sender, RoutedEventArgs e)
{
UpdateFoods();
UpdatePlaces();
UpdateAnimals();
}
void DataGridAnimals_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (dataGridAnimalsShouldClear && dataGridAnimals.SelectedItem != null)
{
buttonModifyAnimal.IsEnabled = false;
buttonRemoveAnimal.IsEnabled = false;
dataGridAnimals.SelectedItem = null;
DataGridFoods_MouseLeftButtonUp(sender, e);
UpdateFoods();
}
else
dataGridAnimalsShouldClear = true;
}
void DataGridAnimals_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (dataGridAnimals.SelectedItem != null)
{
buttonModifyAnimal.IsEnabled = true;
buttonRemoveAnimal.IsEnabled = true;
dataGridAnimalsShouldClear = false;
DataGridFoods_SelectionChanged(sender, e);
int id = (int)ZooClient.GetProperty(dataGridAnimals.SelectedItem, "ID");
int foodId = 0;
lock (animals)
foodId = (int)ZooClient.GetProperty(animals.FirstOrDefault(animal => (int)ZooClient.GetProperty(animal, "ID") == id), "FoodID");
UpdateFoods(foodId);
}
}
void DataGridFoods_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (dataGridFoodsShouldClear && dataGridFoods.SelectedItem != null)
{
buttonModifyFood.IsEnabled = false;
buttonRemoveFood.IsEnabled = false;
dataGridFoods.SelectedItem = null;
}
else
dataGridFoodsShouldClear = true;
}
void DataGridFoods_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (dataGridFoods.SelectedItem != null)
{
buttonModifyFood.IsEnabled = true;
buttonRemoveFood.IsEnabled = true;
dataGridFoodsShouldClear = false;
}
}
void ButtonAddAnimal_Click(object sender, RoutedEventArgs e)
{
AddAnimalWindow addAnimalWindow = new AddAnimalWindow(this);
bool? isAdded = addAnimalWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
{
UpdateAnimals();
UpdateFoods();
}
}
void ButtonModifyAnimal_Click(object sender, RoutedEventArgs e)
{
if (dataGridAnimals.SelectedItem != null)
{
object animal = null;
lock (animals)
animal = animals.SingleOrDefault(a => (int)ZooClient.GetProperty(a, "ID") == ((AnimalView)dataGridAnimals.SelectedItem).ID);
ModifyAnimalWindow modifyAnimalWindow = new ModifyAnimalWindow(this, animal);
bool? isModified = modifyAnimalWindow.ShowDialog();
if (isModified.HasValue && isModified.Value)
{
UpdateAnimals();
UpdateFoods();
}
}
}
void ButtonRemoveAnimal_Click(object sender, RoutedEventArgs e)
{
if (dataGridAnimals.SelectedItem != null)
{
int id = ((AnimalView)dataGridAnimals.SelectedItem).ID;
new Thread(() =>
{
Tuple<bool, byte> status = ZooConnection.DeleteModel(ModelType.Animal, id);
if (status == null)
MessageBox.Show("[ERROR] Cannot remove animal from Zoo, server connection error!");
else if (!status.Item1)
MessageBox.Show(ZooClient.DecodeDeleteError(status.Item2));
else
{
UpdateAnimals();
UpdateFoods();
}
}).Start();
}
}
void ButtonAddFood_Click(object sender, RoutedEventArgs e)
{
AddFoodWindow addFoodWindow = new AddFoodWindow(this);
bool? isAdded = addFoodWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
{
UpdateAnimals();
UpdateFoods();
}
}
void ButtonModifyFoodCount_Click(object sender, RoutedEventArgs e)
{
if (dataGridFoods.SelectedItem != null)
{
object food = null;
lock (Foods)
food = Foods.SingleOrDefault(f => (int)ZooClient.GetProperty(f, "ID") == (int)ZooClient.GetProperty(dataGridFoods.SelectedItem, "ID"));
ModifyFoodWindow modifyFoodWindow = new ModifyFoodWindow(this, food);
bool? isModified = modifyFoodWindow.ShowDialog();
if (isModified.HasValue && isModified.Value)
UpdateFoods();
}
}
void ButtonRemoveFood_Click(object sender, RoutedEventArgs e)
{
if (dataGridFoods.SelectedItem != null)
{
int id = (int)ZooClient.GetProperty(dataGridFoods.SelectedItem, "ID");
new Thread(() =>
{
Tuple<bool, byte> status = ZooConnection.DeleteModel(ModelType.Food, id);
if (status == null)
MessageBox.Show("[ERROR] Cannot remove food type, server connection error!");
else if (!status.Item1)
MessageBox.Show(ZooClient.DecodeDeleteError(status.Item2));
else
{
UpdateAnimals();
UpdateFoods();
}
}).Start();
}
}
#endregion Animals Tab
#region Workers Tab
void ButtonRefreshWorkers_Click(object sender, RoutedEventArgs e)
{
UpdateWorkers();
UpdateOvertimes();
}
void DataGridWorkers_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (dataGridWorkersShouldClear && dataGridWorkers.SelectedItem != null)
{
buttonModifyWorker.IsEnabled = false;
buttonRemoveWorker.IsEnabled = false;
buttonSubmitOvertime.IsEnabled = false;
dataGridWorkers.SelectedItem = null;
UpdateOvertimes();
}
else
dataGridWorkersShouldClear = true;
}
void DataGridWorkers_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (dataGridWorkers.SelectedItem != null)
{
buttonModifyWorker.IsEnabled = true;
buttonRemoveWorker.IsEnabled = true;
buttonSubmitOvertime.IsEnabled = true;
dataGridWorkersShouldClear = false;
UpdateOvertimes(((WorkerView)dataGridWorkers.SelectedItem).ID);
}
}
void ButtonAddWorker_Click(object sender, RoutedEventArgs e)
{
AddWorkerWindow addWorkerWindow = new AddWorkerWindow(this);
bool? isAdded = addWorkerWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
{
UpdateWorkers();
UpdateOvertimes();
}
}
void ButtonModifyWorker_Click(object sender, RoutedEventArgs e)
{
if (dataGridWorkers.SelectedItem != null)
{
object worker = null;
lock (workers)
worker = workers.SingleOrDefault(w => (int)ZooClient.GetProperty(w, "ID") == ((WorkerView)dataGridWorkers.SelectedItem).ID);
ModifyWorkerWindow modifyWorkerWindow = new ModifyWorkerWindow(this, worker);
bool? isModified = modifyWorkerWindow.ShowDialog();
if (isModified.HasValue && isModified.Value)
{
UpdateWorkers();
UpdateOvertimes();
}
}
}
void ButtonRemoveWorker_Click(object sender, RoutedEventArgs e)
{
if (dataGridWorkers.SelectedItem != null)
{
int id = ((WorkerView)dataGridWorkers.SelectedItem).ID;
new Thread(() =>
{
Tuple<bool, byte> status = ZooConnection.DeleteModel(ModelType.Worker, id);
if (status == null)
MessageBox.Show("[ERROR] Cannot delete worker, server connection error!");
else if (!status.Item1)
MessageBox.Show(ZooClient.DecodeDeleteError(status.Item2));
else
{
UpdateOvertimes();
UpdateWorkers();
}
}).Start();
}
}
void ButtonSubmitOvertime_Click(object sender, RoutedEventArgs e)
{
if (dataGridWorkers.SelectedItem != null)
{
int id = ((WorkerView)dataGridWorkers.SelectedItem).ID;
SubmitOvertimeWindow submitOvertimeWindow = new SubmitOvertimeWindow(this, id);
bool? isAdded = submitOvertimeWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
UpdateOvertimes(id);
}
}
#endregion Workers Tab
#region Cash Tab
void ButtonRefreshCash_Click(object sender, RoutedEventArgs e)
{
UpdateCashBalances();
}
void ButtonAddOperation_Click(object sender, RoutedEventArgs e)
{
AddOperationWindow addOperationWindow = new AddOperationWindow(this);
bool? isAdded = addOperationWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
UpdateCashBalances();
}
void ButtonPayMonthSalary_Click(object sender, RoutedEventArgs e)
{
new Thread(() =>
{
object operation = ZooConnection.CreateModel(ModelType.CashBalance);
ZooClient.SetProperty(operation, "BalanceTypeID", 0);
if (!ZooConnection.AddModel(operation))
MessageBox.Show("[ERROR] Cannot pay month salary to employees, cannot add new operation to database, check log for detailed cause.");
else
MessageBox.Show("Succesfully pay month salary to employees.");
}).Start();
}
#endregion Cash Tab
#region Places Tab
void ButtonRefreshPlaces_Click(object sender, RoutedEventArgs e)
{
UpdatePlaces();
UpdateWorkers();
UpdateAttractions();
}
void DataGridPlaces_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (dataGridPlacesShouldClear && dataGridPlaces.SelectedItem != null)
{
buttonModifyPlace.IsEnabled = false;
buttonRemovePlace.IsEnabled = false;
dataGridPlaces.SelectedItem = null;
DataGridAttractions_MouseLeftButtonUp(sender, e);
UpdateAttractions();
}
else
dataGridPlacesShouldClear = true;
}
void DataGridPlaces_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (dataGridPlaces.SelectedItem != null)
{
buttonModifyPlace.IsEnabled = true;
buttonRemovePlace.IsEnabled = true;
dataGridPlacesShouldClear = false;
DataGridAttractions_SelectionChanged(sender, e);
UpdateAttractions((int)ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
}
}
void DataGridAttractions_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (dataGridAttractionsShouldClear && dataGridAttractions.SelectedItem != null)
{
buttonModifyAttraction.IsEnabled = false;
buttonRemoveAttraction.IsEnabled = false;
dataGridAttractions.SelectedItem = null;
}
else
dataGridAttractionsShouldClear = true;
}
void DataGridAttractions_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
if (dataGridAttractions.SelectedItem != null)
{
buttonModifyAttraction.IsEnabled = true;
buttonRemoveAttraction.IsEnabled = true;
dataGridAttractionsShouldClear = false;
}
}
void ButtonAddPlace_Click(object sender, RoutedEventArgs e)
{
AddPlaceWindow addPlaceWindow = new AddPlaceWindow(this);
bool? isAdded = addPlaceWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
{
UpdatePlaces();
UpdateAttractions();
}
}
void ButtonModifyPlace_Click(object sender, RoutedEventArgs e)
{
if (dataGridPlaces.SelectedItem != null)
{
object place = null;
lock (Places)
place = Places.SingleOrDefault(p => (int)ZooClient.GetProperty(p, "ID") == (int)ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
ModifyPlaceWindow modifyPlaceWindow = new ModifyPlaceWindow(this, place);
bool? isModified = modifyPlaceWindow.ShowDialog();
if (isModified.HasValue && isModified.Value)
{
UpdatePlaces();
UpdateAttractions();
}
}
}
void ButtonRemovePlace_Click(object sender, RoutedEventArgs e)
{
if (dataGridPlaces.SelectedItem != null)
{
int id = (int)ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID");
new Thread(() =>
{
Tuple<bool, byte> status = ZooConnection.DeleteModel(ModelType.Place, id);
if (status == null)
MessageBox.Show("[ERROR] Cannot remove place from Zoo, server connection error!");
else if (!status.Item1)
MessageBox.Show(ZooClient.DecodeDeleteError(status.Item2));
else
{
UpdatePlaces();
UpdateAttractions();
}
}).Start();
}
}
void ButtonAddAttraction_Click(object sender, RoutedEventArgs e)
{
AddAttractionWindow addAttractionWindow = new AddAttractionWindow(this);
bool? isAdded = addAttractionWindow.ShowDialog();
if (isAdded.HasValue && isAdded.Value)
{
UpdatePlaces();
UpdateAttractions();
}
}
void ButtonModifyAttraction_Click(object sender, RoutedEventArgs e)
{
if (dataGridAttractions.SelectedItem != null)
{
object attraction = null;
lock (attractions)
attraction = attractions.SingleOrDefault(a => (int)ZooClient.GetProperty(a, "ID") == (int)ZooClient.GetProperty(dataGridAttractions.SelectedItem, "ID"));
ModifyAttractionWindow modifyAttractionWindow = new ModifyAttractionWindow(this, attraction);
bool? isModified = modifyAttractionWindow.ShowDialog();
if (isModified.HasValue && isModified.Value)
UpdateAttractions();
}
}
void ButtonRemoveAttraction_Click(object sender, RoutedEventArgs e)
{
if (dataGridAttractions.SelectedItem != null)
{
int id = (int)ZooClient.GetProperty(dataGridAttractions.SelectedItem, "ID");
new Thread(() =>
{
Tuple<bool, byte> status = ZooConnection.DeleteModel(ModelType.Attraction, id);
if (status == null)
MessageBox.Show("[ERROR] Cannot remove attraction from Zoo, server connection error!");
else if (!status.Item1)
MessageBox.Show(ZooClient.DecodeDeleteError(status.Item2));
else
{
UpdatePlaces();
UpdateAttractions();
}
}).Start();
}
}
#endregion Places Tab
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
update = false;
if (threadUpdate.ThreadState == ThreadState.WaitSleepJoin)
threadUpdate.Abort();
}
}
}
<file_sep>/ZooManager/Windows/TabWorkers/SubmitOvertimeWindow.xaml.cs
using System;
using System.Windows;
namespace ZooManager.Windows.TabWorkers
{
public partial class SubmitOvertimeWindow : Window
{
MainWindow parentWindow;
int workerID;
public SubmitOvertimeWindow(MainWindow parent, int id)
{
InitializeComponent();
parentWindow = parent;
workerID = id;
datePickerDate.DisplayDateStart = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
datePickerDate.SelectedDate = null;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
object overtime = parentWindow.ZooConnection.CreateModel(ModelType.Overtime);
ZooClient.SetProperty(overtime, "Date", datePickerDate.SelectedDate);
ZooClient.SetProperty(overtime, "Hours", int.Parse(textBoxHours.Text));
ZooClient.SetProperty(overtime, "WorkerID", workerID);
if (!parentWindow.ZooConnection.AddModel(overtime))
{
MessageBox.Show("[ERROR] Cannot submit new overtime to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (!int.TryParse(textBoxHours.Text, out int value))
{
MessageBox.Show(this, "[ERROR] Overtime hours must be specified!");
return false;
}
else if (datePickerDate.SelectedDate == null)
{
MessageBox.Show(this, "[ERROR] Overtime date must be specified!");
return false;
}
return true;
}
}
}
<file_sep>/ZooManager/Windows/TabAnimals/AddFoodWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabAnimals
{
public partial class AddFoodWindow : Window
{
MainWindow parentWindow;
public AddFoodWindow(MainWindow parent)
{
InitializeComponent();
parentWindow = parent;
}
void Button_Click(object sender, RoutedEventArgs e)
{
if(IsDataInputValid())
{
object food = parentWindow.ZooConnection.CreateModel(ModelType.Food);
ZooClient.SetProperty(food, "Name", textBoxName.Text);
ZooClient.SetProperty(food, "Amount", double.Parse(textBoxAmount.Text));
if (!parentWindow.ZooConnection.AddModel(food))
{
MessageBox.Show("[ERROR] Cannot add new food to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Food's name must be specified!");
return false;
}
else if (!double.TryParse(textBoxAmount.Text, out double value) || value < 0)
{
MessageBox.Show("[ERROR] Food's amouont must be specified and be at least 0!");
return false;
}
return true;
}
}
}
<file_sep>/ZooCom/Model/BalanceType.cs
namespace ZooCom.Model
{
[System.Serializable]
public class BalanceType : Model
{
public string Description { get; set; }
public override byte TypeID()
{
return (byte)ModelType.BalanceType;
}
}
}
<file_sep>/Test/DeleteModelTest.cs
using Moq;
using ZooService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class DeleteModelTest
{
MockSequence ctxSeq;
Mock<ZooContext> ctx;
ZooService.ZooService service;
[TestInitialize]
public void Setup()
{
ctxSeq = new MockSequence();
ctx = new Mock<ZooContext>();
ctx.Setup(x => x.DeleteWorker(2)).Returns(new System.Tuple<bool, byte>(false, (byte)ModelType.Attraction));
ctx.InSequence(ctxSeq).Setup(x => x.DeleteAttraction(1)).Returns(new System.Tuple<bool, byte>(true, 0));
ctx.InSequence(ctxSeq).Setup(x => x.DeleteWorker(2)).Returns(new System.Tuple<bool, byte>(true, 0));
service = new ZooService.ZooService(1111);
}
[TestMethod]
public void Delete_worker_before_attraction_fail()
{
var ret = service.DeleteModel(ctx.Object, ModelType.Worker, 2);
Assert.IsFalse(ret.Item1);
Assert.IsTrue(ret.Item2 == (byte)ModelType.Attraction);
}
[TestMethod]
public void Delete_worker_after_deleting_his_attraction()
{
var ret1 = service.DeleteModel(ctx.Object, ModelType.Attraction, 1);
Assert.IsTrue(ret1.Item1);
Assert.IsTrue(ret1.Item2 == 0);
var ret2 = service.DeleteModel(ctx.Object, ModelType.Worker, 2);
Assert.IsTrue(ret2.Item1);
Assert.IsTrue(ret2.Item2 == 0);
ctx.Verify(x => x.DeleteAttraction(1));
ctx.Verify(x => x.DeleteWorker(2));
}
}
}
<file_sep>/ZooManager/Windows/TabPlaces/AddAttractionWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabPlaces
{
public partial class AddAttractionWindow : Window
{
MainWindow parentWindow;
public AddAttractionWindow(MainWindow parent)
{
InitializeComponent();
parentWindow = parent;
dataGridPlaces.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.Place);
lock (parentWindow.Places)
dataGridPlaces.ItemsSource = parentWindow.Places;
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
object attraction = parentWindow.ZooConnection.CreateModel(ModelType.Attraction);
ZooClient.SetProperty(attraction, "Name", textBoxName.Text);
if (!string.IsNullOrWhiteSpace(textBoxDescription.Text))
ZooClient.SetProperty(attraction, "Description", textBoxDescription.Text);
ZooClient.SetProperty(attraction, "PlaceID", ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
if (!parentWindow.ZooConnection.AddModel(attraction))
{
MessageBox.Show("[ERROR] Cannot add new worker to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Attraction's name must be specified!");
return false;
}
else if (dataGridPlaces.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must assign attraction to place, select one from the list!");
return false;
}
return true;
}
}
}
<file_sep>/ZooManager/Windows/TabPlaces/ModifyAttractionWindow.xaml.cs
using System.Windows;
using System.Linq;
namespace ZooManager.Windows.TabPlaces
{
public partial class ModifyAttractionWindow : Window
{
MainWindow parentWindow;
object attraction;
public ModifyAttractionWindow(MainWindow parent, object selectedAttraction)
{
InitializeComponent();
if (selectedAttraction == null)
{
Logger.LogWarning("Error selecting attraction to modify, process terminated.", GetType(), "ModifyAttractionWindow(parent: MainWindow, selectedAttraction: null)");
Close();
}
attraction = selectedAttraction;
parentWindow = parent;
dataGridPlaces.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.Place);
lock (parentWindow.Places)
{
dataGridPlaces.ItemsSource = parentWindow.Places;
int id = (int)ZooClient.GetProperty(attraction, "PlaceID");
dataGridPlaces.SelectedItem = parentWindow.Places.FirstOrDefault(place => (int)ZooClient.GetProperty(place, "ID") == id);
}
textBoxName.Text = (string)ZooClient.GetProperty(attraction, "Name");
textBoxDescription.Text = (string)ZooClient.GetProperty(attraction, "Description");
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
ZooClient.SetProperty(attraction, "Name", textBoxName.Text);
if (!string.IsNullOrWhiteSpace(textBoxDescription.Text))
ZooClient.SetProperty(attraction, "Description", textBoxDescription.Text);
ZooClient.SetProperty(attraction, "PlaceID", ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
if (!parentWindow.ZooConnection.ModifyModel(attraction))
{
MessageBox.Show("[ERROR] Cannot add new worker to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Attraction's name must be specified!");
return false;
}
else if (dataGridPlaces.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must assign attraction to place, select one from the list!");
return false;
}
return true;
}
}
}
<file_sep>/ZooCom/Model/Animal.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Animal : Model
{
decimal _maintenanceCost = 0;
public string Name { get; set; }
public int Count { get; set; } = 0;
public decimal MaintenanceCost
{
get { return _maintenanceCost; }
set
{
if (value < 0)
throw new System.ArgumentOutOfRangeException($"Animal: MaintenanceCost cannot be lower than 0. Provided \"{value}\"");
_maintenanceCost = value;
}
}
public int PlaceID { get; set; }
public int FoodID { get; set; }
public override byte TypeID()
{
return (byte)ModelType.Animal;
}
}
}
<file_sep>/ZooCom/Model/CashBalance.cs
namespace ZooCom.Model
{
[System.Serializable]
public class CashBalance : Model
{
public System.DateTime SubmitDate { get; set; } = System.DateTime.Today;
public decimal Money { get; set; } = 0;
public int BalanceTypeID { get; set; }
public string DetailedDescription { get; set; }
public override byte TypeID()
{
return (byte)ModelType.CashBalance;
}
}
}
<file_sep>/README.md
# Zoo Manager
Project for simple zoo managment. Current components consist of:
- Client app (ZooManager)
- Communication DLL (ZooCom)
- Server (ZooService)
**1. Client app**
WPF application connecting through DLL module with server to obtain data about Zoo.
**2. Communication DLL**
DLL module responsible for transfering data between client app and server. Protocols of how client app will receive data from database are described here.
It is possible to define another method of communication other than TCP connection by replacing ZooCom.dll in client app directory.
Also data types are defined here used both by server and client app to send and receive database data.
**3. Server**
TCP server responsible for communicating with client app and local database. Database is based on SQL Server (schema and initial data in ZooSchema.sql).
To access database Entity Framework is used and standard SqlConnection.
Current versions of used programs:
- IDE: Visual Studio 2017
- Database: SQL Server 2017 Express
- ORM: Entity Framework 6
<file_sep>/ZooManager/Views/AnimalView.cs
namespace ZooManager.Views
{
public class AnimalView
{
public int ID { get; set; }
public string Name { get; set; }
public int Count { get; set; }
public decimal MaintenanceCost { get; set; }
public string Place { get; set; }
public string Food { get; set; }
}
}
<file_sep>/ZooService/ZooService.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Linq;
using System.Data.SqlClient;
namespace ZooService
{
public enum ModelType { Model = 0, Animal = 1, Attraction = 2, BalanceType = 4, CashBalance = 8, Food = 16, Overtime = 32, Place = 64, Worker = 128}
public class ZooService
{
Assembly zooComDll;
readonly Dictionary<ModelType, Type> modelTypes = new Dictionary<ModelType, Type>(Enum.GetNames(typeof(ModelType)).Length);
TcpListener serverModifyModel;
Thread threadModifyModel;
TcpListener serverAddModel;
Thread threadAddModel;
TcpListener serverDeleteModel;
Thread threadDeleteModel;
TcpListener serverGetModels;
Thread threadGetModels;
readonly int tcpPort;
readonly IPAddress localIp;
volatile bool isServerRunning = false;
public ZooService(int port)
{
zooComDll = Assembly.LoadFile($@"D:\Projects\Visual Studio Projects\ZooManager\FitNesse\FitSharp\ZooCom.dll");
foreach (ModelType type in (ModelType[])Enum.GetValues(typeof(ModelType)))
{
modelTypes[type] = zooComDll.GetType($"ZooCom.Model.{Enum.GetName(typeof(ModelType), type)}");
}
tcpPort = port;
IPHostEntry host = Dns.GetHostEntry("localhost");
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIp = ip;
break;
}
}
}
public virtual void Start()
{
serverModifyModel = new TcpListener(localIp, tcpPort + 3);
serverAddModel = new TcpListener(localIp, tcpPort + 2);
serverDeleteModel = new TcpListener(localIp, tcpPort + 1);
serverGetModels = new TcpListener(localIp, tcpPort);
threadModifyModel = new Thread(() =>
{
serverModifyModel.Start();
while (isServerRunning)
{
Socket client = serverModifyModel.AcceptSocket();
new Thread(() =>
{
Logger.LogInfo("New modify model request", GetType(), "threadModifyModel");
byte[] data = new byte[1];
client.Receive(data, 1, SocketFlags.None);
ModelType type = (ModelType)data[0];
data = new byte[sizeof(int)];
client.Receive(data, sizeof(int), SocketFlags.None);
data = new byte[BitConverter.ToInt32(data, 0)];
client.Receive(data, data.Length, SocketFlags.None);
object model = new BinaryFormatter().Deserialize(new MemoryStream(data));
using (ZooContext context = new ZooContext())
{
if (ModifyModel(context, type, ConvertFromZooComModel(model, type)))
Logger.LogInfo($"Modified {type.ToString()}", GetType(), "threadModifyModel");
else
Logger.LogWarning($"Cannot modify {type.ToString()}", GetType(), "threadModifyModel");
}
client.Close();
}).Start();
}
serverModifyModel.Stop();
});
threadAddModel = new Thread(() =>
{
serverAddModel.Start();
while (isServerRunning)
{
Socket client = serverAddModel.AcceptSocket();
new Thread(() =>
{
Logger.LogInfo("New add model request", GetType(), "threadAddModel");
byte[] data = new byte[1];
client.Receive(data, 1, SocketFlags.None);
ModelType type = (ModelType)data[0];
data = new byte[sizeof(int)];
client.Receive(data, sizeof(int), SocketFlags.None);
data = new byte[BitConverter.ToInt32(data, 0)];
client.Receive(data, data.Length, SocketFlags.None);
object model = new BinaryFormatter().Deserialize(new MemoryStream(data));
using (ZooContext context = new ZooContext())
{
if (AddModel(context, type, ConvertFromZooComModel(model, type)))
Logger.LogInfo($"Added new {type.ToString()}", GetType(), "threadAddModel");
else
Logger.LogWarning($"Cannot add new {type.ToString()}", GetType(), "threadAddModel");
}
client.Close();
}).Start();
}
serverAddModel.Stop();
});
threadDeleteModel = new Thread(() =>
{
serverDeleteModel.Start();
while (isServerRunning)
{
Socket client = serverDeleteModel.AcceptSocket();
new Thread(() =>
{
Logger.LogInfo("New delete model request", GetType(), "threadDeleteModel");
byte[] data = new byte[1];
client.Receive(data, 1, SocketFlags.None);
ModelType type = (ModelType)data[0];
data = new byte[sizeof(int)];
client.Receive(data, sizeof(int), SocketFlags.None);
using (ZooContext context = new ZooContext())
{
int id = BitConverter.ToInt32(data, 0);
Tuple<bool, byte> operationDetails = DeleteModel(context, type, id);
client.Send(BitConverter.GetBytes(operationDetails.Item1));
if (operationDetails.Item1)
Logger.LogInfo($"Deleted model of type {type.ToString()}, ID = {id}", GetType(), "threadDeleteModel");
else
{
Logger.LogWarning($"Cannot delete model of type {type.ToString()}, ID = {id}", GetType(), "threadDeleteModel");
client.Send(new byte[1] { operationDetails.Item2 });
}
}
client.Close();
}).Start();
}
serverDeleteModel.Stop();
});
threadGetModels = new Thread(() =>
{
serverGetModels.Start();
while (isServerRunning)
{
Socket client = serverGetModels.AcceptSocket();
new Thread(() =>
{
Logger.LogInfo("New get models request", GetType(), "threadGetModels");
byte[] data = new byte[1];
client.Receive(data, 1, SocketFlags.None);
ModelType type = (ModelType)data[0];
using (MemoryStream dataStream = new MemoryStream())
using (ZooContext context = new ZooContext())
{
try
{
new BinaryFormatter().Serialize(dataStream, GetModels(context, type).Select(model => ConvertToZooComModel(type, model)).ToList());
client.Send(BitConverter.GetBytes(dataStream.ToArray().Length), sizeof(int), SocketFlags.None);
client.Send(dataStream.ToArray());
Logger.LogInfo($"Send models of type {type.ToString()}", GetType(), "threadGetModels");
}
catch (Exception e)
{
Logger.LogError(e.ToString());
}
}
client.Close();
}).Start();
}
serverGetModels.Stop();
});
isServerRunning = true;
threadModifyModel.Start();
threadAddModel.Start();
threadDeleteModel.Start();
threadGetModels.Start();
}
public virtual void Stop()
{
isServerRunning = false;
}
public virtual bool ModifyModel(ZooContext context, ModelType type, ZooDataModel model)
{
switch (type)
{
case ModelType.Animal:
return context.ModifyModel((Animal)model);
case ModelType.Attraction:
return context.ModifyModel((Attraction)model);
case ModelType.BalanceType:
return context.ModifyModel((BalanceType)model);
case ModelType.CashBalance:
return context.ModifyModel((CashBalance)model);
case ModelType.Food:
return context.ModifyModel((Food)model);
case ModelType.Overtime:
return context.ModifyModel((Overtime)model);
case ModelType.Place:
return context.ModifyModel((Place)model);
case ModelType.Worker:
return context.ModifyModel((Worker)model);
default:
return false;
}
}
public virtual bool AddModel(ZooContext context, ModelType type, ZooDataModel model)
{
switch (type)
{
case ModelType.Animal:
return context.AddModel((Animal)model);
case ModelType.Attraction:
return context.AddModel((Attraction)model);
case ModelType.BalanceType:
return context.AddModel((BalanceType)model);
case ModelType.CashBalance:
CashBalance balance = (CashBalance)model;
if(balance.BalanceTypeID == 0)
{
PayMonthSalary();
return true;
}
else
return context.AddModel(balance);
case ModelType.Food:
return context.AddModel((Food)model);
case ModelType.Overtime:
return context.AddModel((Overtime)model);
case ModelType.Place:
return context.AddModel((Place)model);
case ModelType.Worker:
return context.AddModel((Worker)model);
default:
return false;
}
}
public virtual Tuple<bool, byte> DeleteModel(ZooContext context, ModelType type, int id)
{
switch (type)
{
case ModelType.Animal:
return context.DeleteAnimal(id);
case ModelType.Attraction:
return context.DeleteAttraction(id);
case ModelType.Food:
return context.DeleteFood(id);
case ModelType.Place:
return context.DeletePlace(id);
case ModelType.Worker:
return context.DeleteWorker(id);
default:
return new Tuple<bool, byte>(false, 0);
}
}
public virtual List<ZooDataModel> GetModels(ZooContext context, ModelType type)
{
switch (type)
{
case ModelType.Animal:
return context.GetModels<Animal>().Cast<ZooDataModel>().ToList();
case ModelType.Attraction:
return context.GetModels<Attraction>().Cast<ZooDataModel>().ToList();
case ModelType.BalanceType:
return context.GetModels<BalanceType>().Cast<ZooDataModel>().ToList();
case ModelType.CashBalance:
return context.GetModels<CashBalance>().Cast<ZooDataModel>().ToList();
case ModelType.Food:
return context.GetModels<Food>().Cast<ZooDataModel>().ToList();
case ModelType.Overtime:
return context.GetModels<Overtime>().Cast<ZooDataModel>().ToList();
case ModelType.Place:
return context.GetModels<Place>().Cast<ZooDataModel>().ToList();
case ModelType.Worker:
return context.GetModels<Worker>().Cast<ZooDataModel>().ToList();
default:
return null;
}
}
public virtual object GetProperty(object model, string name)
{
return model.GetType().GetProperty(name).GetValue(model);
}
public virtual ZooDataModel ConvertFromZooComModel(object model, ModelType type)
{
switch (type)
{
case ModelType.Animal:
return new Animal()
{
ID = (int)GetProperty(model, "ID"),
Name = (string)GetProperty(model, "Name"),
Count = (int)GetProperty(model, "Count"),
MaintenanceCost = (decimal)GetProperty(model, "MaintenanceCost"),
PlaceID = (int)GetProperty(model, "PlaceID"),
FoodID = (int)GetProperty(model, "FoodID")
};
case ModelType.Attraction:
return new Attraction()
{
ID = (int)GetProperty(model, "ID"),
Name = (string)GetProperty(model, "Name"),
Description = (string)GetProperty(model, "Description"),
AttractionManagerID = (int)GetProperty(model, "AttractionManagerID"),
PlaceID = (int)GetProperty(model, "PlaceID")
};
case ModelType.BalanceType:
return new BalanceType()
{
ID = (int)GetProperty(model, "ID"),
Description = (string)GetProperty(model, "Description")
};
case ModelType.CashBalance:
return new CashBalance()
{
ID = (int)GetProperty(model, "ID"),
SubmitDate = (DateTime)GetProperty(model, "SubmitDate"),
Money = (decimal)GetProperty(model, "Money"),
BalanceTypeID = (int)GetProperty(model, "BalanceTypeID"),
DetailedDescription = (string)GetProperty(model, "DetailedDescription")
};
case ModelType.Food:
return new Food()
{
ID = (int)GetProperty(model, "ID"),
Name = (string)GetProperty(model, "Name"),
Amount = (double)GetProperty(model, "Amount")
};
case ModelType.Overtime:
Overtime overtime = new Overtime()
{
ID = (int)GetProperty(model, "ID"),
Date = (DateTime)GetProperty(model, "Date"),
Hours = (int)GetProperty(model, "Hours"),
WorkerID = (int)GetProperty(model, "WorkerID")
};
overtime.SetPercentage();
return overtime;
case ModelType.Place:
return new Place()
{
ID = (int)GetProperty(model, "ID"),
Name = (string)GetProperty(model, "Name"),
OpenTime = (TimeSpan)GetProperty(model, "OpenTime"),
CloseTime = (TimeSpan)GetProperty(model, "CloseTime"),
MaintenanceCost = (decimal)GetProperty(model, "MaintenanceCost")
};
case ModelType.Worker:
return new Worker()
{
ID = (int)GetProperty(model, "ID"),
Surname = (string)GetProperty(model, "Surname"),
Name = (string)GetProperty(model, "Name"),
Age = (int)GetProperty(model, "Age"),
Salary = (decimal)GetProperty(model, "Salary"),
StartDate = (DateTime)GetProperty(model, "StartDate"),
PlaceID = (int)GetProperty(model, "PlaceID")
};
default:
return null;
}
}
public virtual object ConvertToZooComModel(ModelType type, ZooDataModel model)
{
if (ModelType.Model == type)
return null;
object comModel = Activator.CreateInstance(modelTypes[type]);
SetProperty(comModel, "ID", model.ID);
switch (type)
{
case ModelType.Animal:
if (model is Animal animal)
{
SetProperty(comModel, "Name", animal.Name);
SetProperty(comModel, "Count", animal.Count);
SetProperty(comModel, "MaintenanceCost", animal.MaintenanceCost);
SetProperty(comModel, "PlaceID", animal.PlaceID);
SetProperty(comModel, "FoodID", animal.FoodID);
}
break;
case ModelType.Attraction:
if (model is Attraction attraction)
{
SetProperty(comModel, "Name", attraction.Name);
SetProperty(comModel, "Description", attraction.Description);
SetProperty(comModel, "AttractionManagerID", attraction.AttractionManagerID);
SetProperty(comModel, "PlaceID", attraction.PlaceID);
}
break;
case ModelType.BalanceType:
if (model is BalanceType balanceType)
{
SetProperty(comModel, "Description", balanceType.Description);
}
break;
case ModelType.CashBalance:
if (model is CashBalance cashBalance)
{
SetProperty(comModel, "SubmitDate", cashBalance.SubmitDate);
SetProperty(comModel, "Money", cashBalance.Money);
SetProperty(comModel, "BalanceTypeID", cashBalance.BalanceTypeID);
SetProperty(comModel, "DetailedDescription", cashBalance.DetailedDescription);
}
break;
case ModelType.Food:
if (model is Food food)
{
SetProperty(comModel, "Name", food.Name);
SetProperty(comModel, "Amount", food.Amount);
}
break;
case ModelType.Overtime:
if (model is Overtime overtime)
{
SetProperty(comModel, "Date", overtime.Date);
SetProperty(comModel, "Hours", overtime.Hours);
SetProperty(comModel, "PaymentPercentage", overtime.PaymentPercentage);
SetProperty(comModel, "WorkerID", overtime.WorkerID);
}
break;
case ModelType.Place:
if (model is Place place)
{
SetProperty(comModel, "Name", place.Name);
SetProperty(comModel, "OpenTime", place.OpenTime);
SetProperty(comModel, "CloseTime", place.CloseTime);
SetProperty(comModel, "MaintenanceCost", place.MaintenanceCost);
}
break;
case ModelType.Worker:
if (model is Worker worker)
{
SetProperty(comModel, "Surname", worker.Surname);
SetProperty(comModel, "Name", worker.Name);
SetProperty(comModel, "Age", worker.Age);
SetProperty(comModel, "Salary", worker.Salary);
SetProperty(comModel, "StartDate", worker.StartDate);
SetProperty(comModel, "PlaceID", worker.PlaceID);
}
break;
}
return comModel;
}
public virtual void SetProperty(object model, string name, object value)
{
model.GetType().GetProperty(name).SetValue(model, value);
}
public virtual void PayMonthSalary()
{
using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ZooContextMonthSalary"].ConnectionString))
using (SqlCommand command = new SqlCommand("EXEC CreateMonthPayment", connection))
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
}
<file_sep>/ZooCom/Model/Place.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Place : Model
{
decimal _maintenanceCost = 0;
public string Name { get; set; }
public System.TimeSpan OpenTime { get; set; } = new System.TimeSpan(8, 0, 0);
public System.TimeSpan CloseTime { get; set; } = new System.TimeSpan(18, 0, 0);
public decimal MaintenanceCost
{
get { return _maintenanceCost; }
set
{
if (value < 0)
throw new System.ArgumentOutOfRangeException($"Place: MaintenanceCost cannot be lower than 0. Provided \"{value}\"");
_maintenanceCost = value;
}
}
public override byte TypeID()
{
return (byte)ModelType.Place;
}
}
}
<file_sep>/Test/ConvertToZooComModelTest.cs
using ZooService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Test
{
[TestClass]
public class ConvertToZooComModelTest
{
ZooService.ZooService service;
Animal animalUnit;
object comModel;
const int ID = 1;
const decimal decimalTest = 5;
const string stringTest = "testString";
const int intTest = 50;
[TestInitialize]
public void SetUp()
{
service = new ZooService.ZooService(1111);
comModel = new ZooCom.Model.Animal
{
ID = ID,
MaintenanceCost = decimalTest,
Name = stringTest,
PlaceID = ID,
FoodID = ID,
Count = intTest
};
animalUnit = new Animal
{
ID = ID,
MaintenanceCost = decimalTest,
Name = stringTest,
PlaceID = ID,
FoodID = ID,
Count = intTest
};
}
[TestMethod]
public void Has_the_same_fields_values_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
Assert.IsInstanceOfType(objectResponse, comModel.GetType());
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
Assert.AreEqual(animalObjectAfterConvertion.ID, ID);
Assert.AreEqual(animalObjectAfterConvertion.PlaceID, ID);
Assert.AreEqual(animalObjectAfterConvertion.FoodID, ID);
Assert.AreEqual(animalObjectAfterConvertion.Count, intTest);
Assert.AreEqual(animalObjectAfterConvertion.Name, stringTest);
Assert.AreEqual(animalObjectAfterConvertion.MaintenanceCost, decimalTest);
Assert.AreNotSame(comModel, animalObjectAfterConvertion);
}
[TestMethod]
public void Returns_NULL()
{
var response = service.ConvertToZooComModel(ModelType.Model, animalUnit);
Assert.IsNull(response);
}
[TestMethod]
public void Should_throw_Exception()
{
Animal emptyObject = null;
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Animal, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Attraction, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.BalanceType, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.CashBalance, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Food, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Overtime, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Place, emptyObject);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertToZooComModel(ModelType.Worker, emptyObject);
});
}
}
}
<file_sep>/ZooCom/Model/Model.cs
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace ZooCom.Model
{
public enum ModelType { Model = 0, Animal = 1, Attraction = 2, BalanceType = 4, CashBalance = 8, Food = 16, Overtime = 32, Place = 64, Worker = 128 }
[Serializable]
public abstract class Model
{
public int ID { get; set; }
public long SerializedBytes()
{
using (MemoryStream stream = new MemoryStream())
{
new BinaryFormatter().Serialize(stream, this);
return stream.Length;
}
}
public virtual byte TypeID()
{
return (byte)ModelType.Model;
}
}
}<file_sep>/FitTesto/DeleteModelTest.cs
using Moq;
using ZooService;
using fitlibrary;
namespace FitTesto
{
public class DeleteModelTest : DoFixture
{
MockSequence ctxSeq;
Mock<ZooContext> ctx;
ZooService.ZooService service;
public void SetUp()
{
ctxSeq = new MockSequence();
ctx = new Mock<ZooContext>();
ctx.Setup(x => x.DeleteWorker(2)).Returns(new System.Tuple<bool, byte>(false, (byte)ModelType.Attraction));
ctx.InSequence(ctxSeq).Setup(x => x.DeleteAttraction(1)).Returns(new System.Tuple<bool, byte>(true, 0));
ctx.InSequence(ctxSeq).Setup(x => x.DeleteWorker(2)).Returns(new System.Tuple<bool, byte>(true, 0));
service = new ZooService.ZooService(1111);
}
public bool Delete_worker_before_attraction_fail()
{
var ret = service.DeleteModel(ctx.Object, ModelType.Worker, 2);
return ret.Item1 == false && ret.Item2 == (byte)ModelType.Attraction;
}
public bool Delete_worker_after_deleting_his_attraction()
{
var ret1 = service.DeleteModel(ctx.Object, ModelType.Attraction, 1);
if (ret1.Item1 != true || ret1.Item2 != 0)
return false;
var ret2 = service.DeleteModel(ctx.Object, ModelType.Worker, 2);
return ret2.Item1 && ret2.Item2 == 0;
}
}
}
<file_sep>/Test/AddModelTest.cs
using Moq;
using ZooService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Test
{
[TestClass]
public class AddModelTest
{
Mock<ZooContext> IZooContext;
ZooService.ZooService service;
[TestInitialize]
public void Setup()
{
IZooContext = new Mock<ZooContext>();
service = new ZooService.ZooService(1111);
}
[TestMethod]
public void Should_add_object()
{
Animal unit = new Animal()
{
ID = 1,
Name = "tiger",
Count = 50,
FoodID = 1,
PlaceID = 1,
MaintenanceCost = 5
};
IZooContext.Setup(x => x.AddModel<Animal>(unit)).Returns(true);
var response = service.AddModel(IZooContext.Object, ZooService.ModelType.Animal, unit);
Assert.IsTrue(response);
}
[TestMethod]
public void Should_return_false_on_non_existing_method()
{
Animal unit = new Animal()
{
ID = 1,
Name = "tiger",
Count = 50,
FoodID = 1,
PlaceID = 1,
MaintenanceCost = 5
};
IZooContext.Setup(x => x.AddModel<Animal>(unit)).Returns(true);
var response = service.AddModel(IZooContext.Object, ZooService.ModelType.Model, (ZooDataModel) unit);
Assert.IsFalse(response);
}
}
}
<file_sep>/ZooManager/Windows/TabCash/AddOperationWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabCash
{
public partial class AddOperationWindow : Window
{
MainWindow parentWindow;
public AddOperationWindow(MainWindow parent)
{
InitializeComponent();
parentWindow = parent;
dataGridTypes.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.BalanceType);
lock (parentWindow.BalanceTypes)
dataGridTypes.ItemsSource = parentWindow.BalanceTypes;
}
void Button_Click(object sender, RoutedEventArgs e)
{
if(IsDataInputValid())
{
object operation = parentWindow.ZooConnection.CreateModel(ModelType.CashBalance);
ZooClient.SetProperty(operation, "SubmitDate", datePickerSubmit.SelectedDate);
ZooClient.SetProperty(operation, "Money", decimal.Parse(textBoxMoney.Text));
ZooClient.SetProperty(operation, "BalanceTypeID", ZooClient.GetProperty(dataGridTypes.SelectedItem, "ID"));
if (string.IsNullOrWhiteSpace(textBoxDescription.Text))
ZooClient.SetProperty(operation, "DetailedDescription", textBoxDescription.Text);
if (!parentWindow.ZooConnection.AddModel(operation))
{
MessageBox.Show("[ERROR] Cannot add new finance operation to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (!decimal.TryParse(textBoxMoney.Text, out decimal val))
{
MessageBox.Show("[ERROR] Operation's money must be specified!");
return false;
}
else if (dataGridTypes.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must specify operation type first, select one from the list!");
return false;
}
return true;
}
}
}
<file_sep>/ZooCom/Model/Attraction.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Attraction : Model
{
public string Name { get; set; }
public string Description { get; set; }
public int AttractionManagerID { get; set; }
public int PlaceID { get; set; }
public override byte TypeID()
{
return (byte)ModelType.Attraction;
}
}
}
<file_sep>/ZooManager/Views/CashBalanceView.cs
namespace ZooManager.Views
{
public class CashBalanceView
{
public int ID { get; set; }
public System.DateTime SubmitDate { get; set; }
public decimal Money { get; set; }
public string Type { get; set; }
public string DetailedDescription { get; set; }
}
}
<file_sep>/ZooCom/Model/Food.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Food : Model
{
double _amount = 0.0;
public string Name { get; set; }
public double Amount
{
get { return _amount; }
set
{
if (value < 0.0)
throw new System.ArgumentOutOfRangeException($"Food: Amount cannot be lower than 0. Provided \"{value}\"");
_amount = value;
}
}
public override byte TypeID()
{
return (byte)ModelType.Food;
}
}
}
<file_sep>/ZooManager/Logger.cs
using System;
using System.IO;
using System.Threading;
namespace ZooManager
{
public static class Logger
{
public static void LogError(string msg, Type type = null, string method = null)
{
Log("ERROR", msg, type, method);
}
public static void LogWarning(string msg, Type type = null, string method = null)
{
Log("WARNING", msg, type, method);
}
public static void LogInfo(string msg, Type type = null, string method = null)
{
Log("INFO", msg, type, method);
}
static void Log(string type, string msg, Type objType, string method)
{
new Thread(() =>
{
const string path = "log_manager.txt";
if (objType == null)
method = $"unknown:{method}";
else
method = $"{objType.ToString()}:{method}";
bool isFree = false;
do
{
try
{
using (Mutex writeLock = new Mutex(true, "ZooManager.Logger", out isFree))
{
if (isFree)
{
if (!File.Exists(path))
File.Create(path).Close();
using (TextWriter writer = new StreamWriter(path, true))
writer.WriteLine($"<{DateTime.Now.ToString()}> [{type}] @{method}: {msg}");
writeLock.ReleaseMutex();
}
}
}
catch (Exception)
{
isFree = false;
}
if (!isFree)
Thread.Sleep(1000);
} while (!isFree);
}).Start();
}
static bool IsFileReady(string filename)
{
try
{
using (FileStream inputStream = File.Open(filename, FileMode.Append, FileAccess.Write, FileShare.None))
return true;
}
catch (Exception)
{
return false;
}
}
}
}
<file_sep>/Test/ConvertFromZooComModelTest.cs
using ZooService;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace Test
{
[TestClass]
public class ConvertFromZooComModelTest
{
ZooService.ZooService service;
Animal animalUnit;
object comModel;
const int ID = 1;
const decimal decimalTest = 5;
const string stringTest = "testString";
const int intTest = 50;
[TestInitialize]
public void SetUp()
{
service = new ZooService.ZooService(1111);
comModel = new ZooCom.Model.Animal
{
ID = ID,
MaintenanceCost = decimalTest,
Name = stringTest,
PlaceID = ID,
FoodID = ID,
Count = intTest
};
animalUnit = new Animal
{
ID = ID,
MaintenanceCost = decimalTest,
Name = stringTest,
PlaceID = ID,
FoodID = ID,
Count = intTest
};
}
[TestMethod]
public void Has_the_same_fields_values_after_conversion()
{
var objectResponse = service.ConvertFromZooComModel(comModel, ZooService.ModelType.Animal);
Assert.IsInstanceOfType(objectResponse, animalUnit.GetType());
Animal animalObjectAfterConvertion = (Animal)objectResponse;
Assert.AreEqual(animalObjectAfterConvertion.ID, ID);
Assert.AreEqual(animalObjectAfterConvertion.PlaceID, ID);
Assert.AreEqual(animalObjectAfterConvertion.FoodID, ID);
Assert.AreEqual(animalObjectAfterConvertion.Count, intTest);
Assert.AreEqual(animalObjectAfterConvertion.Name, stringTest);
Assert.AreEqual(animalObjectAfterConvertion.MaintenanceCost,decimalTest);
Assert.AreNotSame(animalUnit, animalObjectAfterConvertion);
}
[TestMethod]
public void Returns_NULL()
{
var response = service.ConvertFromZooComModel(comModel, ZooService.ModelType.Model);
Assert.IsNull(response);
}
[TestMethod]
public void Should_throw_Exception()
{
ZooCom.Model.Animal emptyObject = null;
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Animal);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Attraction);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.BalanceType);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.CashBalance);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Food);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Overtime);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Place);
});
Assert.ThrowsException<NullReferenceException>(() =>
{
service.ConvertFromZooComModel(emptyObject, ZooService.ModelType.Worker);
});
}
}
}
<file_sep>/ZooManager/ZooClient.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
namespace ZooManager
{
public enum ModelType { Model = 0, Animal = 1, Attraction = 2, BalanceType = 4, CashBalance = 8, Food = 16, Overtime = 32, Place = 64, Worker = 128 }
public class ZooClient
{
Assembly zooComDll;
Type zooComClientType;
readonly Dictionary<ModelType, Type> modelTypes = new Dictionary<ModelType, Type>(Enum.GetNames(typeof(ModelType)).Length);
Dictionary<string, MethodInfo> zooComMethods = new Dictionary<string, MethodInfo>(3);
readonly object zooComClient;
public ZooClient(int port)
{
zooComDll = Assembly.LoadFile($@"{AppDomain.CurrentDomain.BaseDirectory}ZooCom.dll");
zooComClientType = zooComDll.GetType("ZooCom.ZooComClient");
foreach (ModelType type in (ModelType[])Enum.GetValues(typeof(ModelType)))
{
modelTypes[type] = zooComDll.GetType($"ZooCom.Model.{Enum.GetName(typeof(ModelType), type)}");
}
zooComClient = Activator.CreateInstance(zooComClientType, new object[] { port });
foreach (string method in new string[] { "ModifyModel", "AddModel", "DeleteModel", "GetModels" })
{
zooComMethods.Add(method, zooComClientType.GetMethod(method));
}
}
public bool ModifyModel(object model)
{
if (!modelTypes.ContainsValue(model.GetType()))
{
Logger.LogWarning($"Unknown object passed to method of type: {model.GetType()}", GetType(), $"ModifyModel(model: {model})");
return false;
}
try
{
if ((bool)zooComMethods["ModifyModel"].MakeGenericMethod(model.GetType()).Invoke(zooComClient, new object[] { model }))
return true;
Logger.LogError("Cannot connect to database, internal connection error!", GetType(), $"ModifyModel(model: {model})");
}
catch (Exception e)
{
Logger.LogError($"Cannot modify object {model.GetType()}. Exception {e.ToString()}", GetType(), $"ModifyModel(model: {model})");
}
return false;
}
public bool AddModel(object model)
{
if (!modelTypes.ContainsValue(model.GetType()))
{
Logger.LogWarning($"Unknown object passed to method of type: {model.GetType()}", GetType(), $"AddModel(model: {model})");
return false;
}
try
{
if ((bool)zooComMethods["AddModel"].MakeGenericMethod(model.GetType()).Invoke(zooComClient, new object[] { model }))
return true;
Logger.LogError("Cannot connect to database, internal connection error!", GetType(), $"AddModel(model: {model})");
}
catch (Exception e)
{
Logger.LogError($"Cannot add object {model.GetType()} to database. Exception {e.ToString()}", GetType(), $"AddModel(model: {model})");
}
return false;
}
public Tuple<bool, byte> DeleteModel(ModelType type, int id)
{
try
{
Tuple<bool, byte> response = (Tuple<bool, byte>)zooComMethods["DeleteModel"].MakeGenericMethod(modelTypes[type]).Invoke(zooComClient, new object[] { id });
if (response == null)
Logger.LogError("Cannot connect to database, internal connection error!", GetType(), $"DeleteModel(type: {type.ToString()}, id: {id})");
else if (!response.Item1)
Logger.LogError($"Cannot delete model due to its contraints, error code: {Convert.ToString(response.Item2, 2)}", GetType(), $"DeleteModel(type: {type.ToString()}, id: {id})");
return response;
}
catch (Exception e)
{
Logger.LogError($"Cannot delete {type.ToString()} with ID: {id}. Exception {e.ToString()}", GetType(), $"DeleteModel(type: {type}, id: {id})");
}
return null;
}
public List<object> GetModels(ModelType type)
{
try
{
IList models = (IList)zooComMethods["GetModels"].MakeGenericMethod(modelTypes[type]).Invoke(zooComClient, null);
if (models != null)
return models.Cast<object>().ToList();
Logger.LogError("Cannot connect to database, internal connection error!", GetType(), $"GetModels(type: {type.ToString()})");
}
catch (Exception e)
{
Logger.LogError($"Cannot get objects {type.ToString()}. Exception {e.ToString()}", GetType(), $"GetModels(model: {type})");
}
return null;
}
public Type GetModelType(ModelType type)
{
return modelTypes[type];
}
public object CreateModel(ModelType type)
{
return Activator.CreateInstance(modelTypes[type]);
}
public static object GetProperty(object model, string name)
{
return model.GetType().GetProperty(name).GetValue(model);
}
public static void SetProperty(object model, string name, object value)
{
model.GetType().GetProperty(name).SetValue(model, value);
}
public static string DecodeDeleteError(byte code)
{
StringBuilder msg = new StringBuilder("[ERROR] ");
if (code == (byte)ModelType.Model)
msg.Append("Unknown database internal error!");
else
{
msg.Append("Cannot delete model due to existing contraints on following tables: ");
if ((code & (byte)ModelType.Animal) > 0)
msg.Append("Animals, ");
if ((code & (byte)ModelType.Attraction) > 0)
msg.Append("Attractions, ");
if ((code & (byte)ModelType.BalanceType) > 0)
msg.Append("BalanceTypes, ");
if ((code & (byte)ModelType.CashBalance) > 0)
msg.Append("CashBalances, ");
if ((code & (byte)ModelType.Food) > 0)
msg.Append("Foods, ");
if ((code & (byte)ModelType.Overtime) > 0)
msg.Append("Overtimes, ");
if ((code & (byte)ModelType.Place) > 0)
msg.Append("Places, ");
if ((code & (byte)ModelType.Worker) > 0)
msg.Append("Workers, ");
msg.Remove(msg.Length - 2, 2);
msg.Append(".");
}
return msg.ToString();
}
}
}
<file_sep>/ZooCom/Model/Worker.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Worker : Model
{
int _age = 0;
decimal _salary = 0;
public string Surname { get; set; }
public string Name { get; set; }
public int Age
{
get { return _age; }
set
{
if (value < 16)
throw new System.ArgumentOutOfRangeException($"Worker: Age cannot be lower than 16. Provided \"{value}\"");
_age = value;
}
}
public decimal Salary
{
get { return _salary; }
set
{
if (value < 0)
throw new System.ArgumentOutOfRangeException($"Worker: Salary cannot be lower than 16. Provided \"{value}\"");
_salary = value;
}
}
public System.DateTime StartDate { get; set; } = System.DateTime.Today;
public int PlaceID { get; set; }
public override byte TypeID()
{
return (byte)ModelType.Worker;
}
}
}
<file_sep>/ZooManager/Windows/TabPlaces/AddPlaceWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabPlaces
{
public partial class AddPlaceWindow : Window
{
MainWindow parentWindow;
public AddPlaceWindow(MainWindow parent)
{
InitializeComponent();
parentWindow = parent;
}
void Button_Click(object sender, RoutedEventArgs e)
{
if(IsDataInputValid())
{
object place = parentWindow.ZooConnection.CreateModel(ModelType.Place);
ZooClient.SetProperty(place, "Name", textBoxName.Text);
ZooClient.SetProperty(place, "OpenTime", timePickerOpen.Value.Value.TimeOfDay);
ZooClient.SetProperty(place, "CloseTime", timePickerClose.Value.Value.TimeOfDay);
ZooClient.SetProperty(place, "MaintenanceCost", decimal.Parse(textBoxCost.Text));
if (!parentWindow.ZooConnection.AddModel(place))
{
MessageBox.Show("[ERROR] Cannot add new place to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Place's name must be specified!");
return false;
}
else if (timePickerClose.Value.Value.TimeOfDay <= timePickerOpen.Value.Value.TimeOfDay)
{
MessageBox.Show("[ERROR] Close time cannot be equal or bigger than open time!");
return false;
}
else if (!decimal.TryParse(textBoxCost.Text, out decimal val))
{
MessageBox.Show("[ERROR] Place's maintenace cost must be specified!");
return false;
}
return true;
}
}
}
<file_sep>/ZooManager/Windows/TabPlaces/ModifyPlaceWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabPlaces
{
public partial class ModifyPlaceWindow : Window
{
MainWindow parentWindow;
object place;
public ModifyPlaceWindow(MainWindow parent, object selectedPlace)
{
InitializeComponent();
if (selectedPlace == null)
{
Logger.LogWarning("Error selecting place to modify, process terminated.", GetType(), "ModifyPlaceWindow(parent: MainWindow, selectedPlace: null)");
Close();
}
place = selectedPlace;
parentWindow = parent;
textBoxName.Text = (string)ZooClient.GetProperty(place, "Name");
timePickerOpen.Value = System.DateTime.Now.Date + ((System.TimeSpan)ZooClient.GetProperty(place, "OpenTime"));
timePickerClose.Value = System.DateTime.Now.Date + ((System.TimeSpan)ZooClient.GetProperty(place, "CloseTime"));
textBoxCost.Text = ((decimal)ZooClient.GetProperty(place, "MaintenanceCost")).ToString();
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
object place = parentWindow.ZooConnection.CreateModel(ModelType.Place);
ZooClient.SetProperty(place, "Name", textBoxName.Text);
ZooClient.SetProperty(place, "OpenTime", timePickerOpen.Value.Value.TimeOfDay);
ZooClient.SetProperty(place, "CloseTime", timePickerClose.Value.Value.TimeOfDay);
ZooClient.SetProperty(place, "MaintenanceCost", decimal.Parse(textBoxCost.Text));
if (!parentWindow.ZooConnection.ModifyModel(place))
{
MessageBox.Show("[ERROR] Cannot modify place, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Place's name must be specified!");
return false;
}
else if (timePickerClose.Value.Value.TimeOfDay <= timePickerOpen.Value.Value.TimeOfDay)
{
MessageBox.Show("[ERROR] Close time cannot be equal or bigger than open time!");
return false;
}
else if (!decimal.TryParse(textBoxCost.Text, out decimal val))
{
MessageBox.Show("[ERROR] Place's maintenace cost must be specified!");
return false;
}
return true;
}
}
}
<file_sep>/ZooManager/Views/WorkerView.cs
namespace ZooManager.Views
{
public class WorkerView
{
public int ID { get; set; }
public string Surname { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public decimal Salary { get; set; }
public System.DateTime StartDate { get; set; }
public string Place { get; set; }
}
}
<file_sep>/ZooCom/Model/Overtime.cs
namespace ZooCom.Model
{
[System.Serializable]
public class Overtime : Model
{
public System.DateTime Date { get; set; }
public int Hours { get; set; }
public int PaymentPercentage { get; set; }
public int WorkerID { get; set; }
public override byte TypeID()
{
return (byte)ModelType.Overtime;
}
}
}
<file_sep>/ZooManager/Windows/TabAnimals/ModifyFoodWindow.xaml.cs
using System.Windows;
namespace ZooManager.Windows.TabAnimals
{
public partial class ModifyFoodWindow : Window
{
MainWindow parentWindow;
object food;
public ModifyFoodWindow(MainWindow parent, object selectedFood)
{
InitializeComponent();
if (selectedFood == null)
{
Logger.LogWarning("Error selecting food to modify, process terminated.", GetType(), "ModifyFoodWindow(parent: MainWindow, selectedFood: null)");
Close();
}
food = selectedFood;
parentWindow = parent;
textBoxName.Text = (string)ZooClient.GetProperty(food, "Name");
textBoxAmount.Text = ((double)ZooClient.GetProperty(food, "Amount")).ToString();
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
ZooClient.SetProperty(food, "Name", textBoxName.Text);
ZooClient.SetProperty(food, "Amount", double.Parse(textBoxAmount.Text));
if (!parentWindow.ZooConnection.ModifyModel(food))
{
MessageBox.Show("[ERROR] Cannot add new food to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Food's name must be specified!");
return false;
}
else if (!double.TryParse(textBoxAmount.Text, out double value) || value < 0)
{
MessageBox.Show("[ERROR] Food's amouont must be specified and be at least 0!");
return false;
}
return true;
}
}
}
<file_sep>/ZooCom/ZooComClient.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Linq;
namespace ZooCom
{
public class ZooComClient
{
readonly int tcpPort;
public ZooComClient(int port)
{
tcpPort = port;
}
public bool ModifyModel<T>(T model) where T : Model.Model
{
using (TcpClient tcpClient = Connect(tcpPort + 3))
{
if (tcpClient == null)
return false;
using (NetworkStream netStream = tcpClient.GetStream())
using (MemoryStream dataStream = new MemoryStream())
{
netStream.WriteByte(model.TypeID());
netStream.Flush();
new BinaryFormatter().Serialize(dataStream, model);
byte[] data = dataStream.ToArray();
netStream.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
netStream.Flush();
netStream.Write(data, 0, data.Length);
netStream.Flush();
}
return true;
}
}
public bool AddModel<T>(T model) where T : Model.Model
{
using (TcpClient tcpClient = Connect(tcpPort + 2))
{
if (tcpClient == null)
return false;
using (NetworkStream netStream = tcpClient.GetStream())
using (MemoryStream dataStream = new MemoryStream())
{
netStream.WriteByte(model.TypeID());
netStream.Flush();
new BinaryFormatter().Serialize(dataStream, model);
byte[] data = dataStream.ToArray();
netStream.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
netStream.Flush();
netStream.Write(data, 0, data.Length);
netStream.Flush();
}
return true;
}
}
public Tuple<bool, byte> DeleteModel<T>(int id) where T : Model.Model, new()
{
using (TcpClient tcpClient = Connect(tcpPort + 1))
{
if (tcpClient == null)
return null;
using (NetworkStream netStream = tcpClient.GetStream())
{
netStream.WriteByte(new T().TypeID());
netStream.Write(BitConverter.GetBytes(id), 0, sizeof(int));
netStream.Flush();
byte[] response = new byte[sizeof(bool)];
netStream.Read(response, 0, response.Length);
bool status = BitConverter.ToBoolean(response, 0);
byte errorCode = (byte)Model.ModelType.Model;
if (!status)
{
netStream.Read(response, 0, 1);
errorCode = response[0];
}
return new Tuple<bool, byte>(status, errorCode);
}
}
}
public List<T> GetModels<T>() where T : Model.Model, new()
{
using (TcpClient tcpClient = Connect(tcpPort))
{
if (tcpClient == null)
return null;
List<T> models = null;
using (NetworkStream netStream = tcpClient.GetStream())
{
netStream.WriteByte(new T().TypeID());
netStream.Flush();
byte[] data = new byte[sizeof(int)];
netStream.Read(data, 0, sizeof(int));
data = new byte[BitConverter.ToInt32(data, 0)];
netStream.Read(data, 0, data.Length);
models = ((List<object>)new BinaryFormatter().Deserialize(new MemoryStream(data))).Cast<T>().ToList();
netStream.Close();
}
return models;
}
}
TcpClient Connect(int port, bool isFirstCall = true)
{
try
{
return new TcpClient("localhost", port)
{
NoDelay = true
};
}
catch (Exception e)
{
if (isFirstCall && System.Diagnostics.Process.GetProcessesByName("ZooService").Length <= 0)
{
Logger.LogWarning("ZooService is down, starting up...", GetType(), $"Connect(port: {port}, isFirstCall: {isFirstCall})");
try
{
System.Diagnostics.Process.Start("ZooService.exe");
System.Threading.Thread.Sleep(2000);
return Connect(port, false);
}
catch (Exception)
{
Logger.LogError("Cannot start ZooService!", GetType(), $"Connect(port: {port}, isFirstCall: {isFirstCall})");
return null;
}
}
Logger.LogError($"Cannot open tcp connection on port. Exception: {e.ToString()}", GetType(), $"Connect(port: {port}, isFirstCall: {isFirstCall})");
return null;
}
}
}
}
<file_sep>/ZooManager/Windows/TabAnimals/ModifyAnimalWindow.xaml.cs
using System.Linq;
using System.Windows;
namespace ZooManager.Windows.TabAnimals
{
public partial class ModifyAnimalWindow : Window
{
MainWindow parentWindow;
object animal;
public ModifyAnimalWindow(MainWindow parent, object selectedAnimal)
{
InitializeComponent();
if (selectedAnimal == null)
{
Logger.LogWarning("Error selecting animal to modify, process terminated.", GetType(), "ModifyAnimalWindow(parent: MainWindow, selectedAnimal: null)");
Close();
}
animal = selectedAnimal;
parentWindow = parent;
textBoxName.Text = (string)ZooClient.GetProperty(animal, "Name");
textBoxCount.Text = ((int)ZooClient.GetProperty(animal, "Count")).ToString();
textBoxCost.Text = ((decimal)ZooClient.GetProperty(animal, "MaintenanceCost")).ToString();
dataGridPlaces.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.Place);
lock (parentWindow.Places)
{
dataGridPlaces.ItemsSource = parentWindow.Places;
int id = (int)ZooClient.GetProperty(animal, "PlaceID");
dataGridPlaces.SelectedItem = parentWindow.Places.FirstOrDefault(place => (int)ZooClient.GetProperty(place, "ID") == id);
}
dataGridFoods.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.Food);
lock (parentWindow.Foods)
{
dataGridFoods.ItemsSource = parentWindow.Foods;
int id = (int)ZooClient.GetProperty(animal, "FoodID");
dataGridFoods.SelectedItem = parentWindow.Foods.FirstOrDefault(food => (int)ZooClient.GetProperty(food, "ID") == id);
}
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
ZooClient.SetProperty(animal, "Name", textBoxName.Text);
ZooClient.SetProperty(animal, "Count", int.Parse(textBoxCount.Text));
ZooClient.SetProperty(animal, "MaintenanceCost", decimal.Parse(textBoxCost.Text));
ZooClient.SetProperty(animal, "PlaceID", ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
ZooClient.SetProperty(animal, "FoodID", ZooClient.GetProperty(dataGridFoods.SelectedItem, "ID"));
if (!parentWindow.ZooConnection.ModifyModel(animal))
{
MessageBox.Show("[ERROR] Cannot add new animal to database, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Animal's name must be specified!");
return false;
}
else if (!int.TryParse(textBoxCount.Text, out int value) || value < 0)
{
MessageBox.Show("[ERROR] Animal's count must be specified and be at least 0!");
return false;
}
else if (dataGridPlaces.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must assign animal to place, select one from the list!");
return false;
}
else if (dataGridFoods.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must assign food to animal, select one from the list!");
return false;
}
else if (!decimal.TryParse(textBoxCost.Text, out decimal val))
{
MessageBox.Show("[ERROR] Animal's maintenance cost must be specified!");
return false;
}
return true;
}
}
}
<file_sep>/FitTesto/ConvertToZooComModelTest.cs
using System;
using ZooService;
using fitlibrary;
namespace FitTesto
{
public class ConvertToZooComModelTest : DoFixture
{
ZooService.ZooService service = new ZooService.ZooService(1111);
Animal animalUnit;
object comModel;
int ID = 1;
int placeID = 3;
int foodID = 5;
decimal maintenanceCost = 21;
string name = "Cowabunga";
int count = 42;
public void SetUp()
{
comModel = new ZooCom.Model.Animal
{
ID = ID,
MaintenanceCost = maintenanceCost,
Name = name,
PlaceID = placeID,
FoodID = foodID,
Count = count
};
animalUnit = new Animal
{
ID = ID,
MaintenanceCost = maintenanceCost,
Name = name,
PlaceID = placeID,
FoodID = foodID,
Count = count
};
}
public bool Is_COM_MODEL_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
return objectResponse.GetType() == comModel.GetType();
}
public bool Has_same_ID_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.ID == ID;
}
public bool Has_same_PlaceID_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.PlaceID == placeID;
}
public bool Has_same_FoodID_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.FoodID == foodID;
}
public bool Has_same_Count_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.Count == count;
}
public bool Has_same_Name_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.Name == name;
}
public bool Has_same_Maintenance_Cost_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return animalObjectAfterConvertion.MaintenanceCost == maintenanceCost;
}
public bool Are_not_same_objects_after_conversion()
{
var objectResponse = service.ConvertToZooComModel(ModelType.Animal, animalUnit);
ZooCom.Model.Animal animalObjectAfterConvertion = (ZooCom.Model.Animal)objectResponse;
return comModel != animalObjectAfterConvertion;
}
public bool Returns_NULL()
{
var response = service.ConvertToZooComModel(ModelType.Model, animalUnit);
return response == null;
}
public bool Should_throw_Exception()
{
Animal emptyObject = null;
try
{
service.ConvertToZooComModel(ModelType.Animal, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.Attraction, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.BalanceType, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.CashBalance, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.Food, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.Overtime, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.Place, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
try
{
service.ConvertToZooComModel(ModelType.Worker, emptyObject);
return false;
}
catch (NullReferenceException) { }
catch
{
return false;
}
return true;
}
}
}
<file_sep>/ZooManager/Views/OvertimeView.cs
namespace ZooManager.Views
{
public class OvertimeView
{
public int ID { get; set; }
public System.DateTime Date { get; set; }
public int Hours { get; set; }
public int PaymentPercentage { get; set; }
public string Employee { get; set; }
}
}
<file_sep>/ZooManager/Windows/TabWorkers/ModifyWorkerWindow.xaml.cs
using System;
using System.Linq;
using System.Windows;
namespace ZooManager.Windows.TabWorkers
{
public partial class ModifyWorkerWindow : Window
{
MainWindow parentWindow;
object worker;
public ModifyWorkerWindow(MainWindow parent, object selectedWorker)
{
InitializeComponent();
if (selectedWorker == null)
{
Logger.LogWarning("Error selecting worker to modify, process terminated.", GetType(), "ModifyWorkerWindow(parent: MainWindow, selectedWorker: null)");
Close();
}
worker = selectedWorker;
parentWindow = parent;
dataGridPlaces.DataContext = parentWindow.ZooConnection.GetModelType(ModelType.Place);
lock (parentWindow.Places)
{
dataGridPlaces.ItemsSource = parentWindow.Places;
int id = (int)ZooClient.GetProperty(worker, "PlaceID");
dataGridPlaces.SelectedItem = parentWindow.Places.FirstOrDefault(place => (int)ZooClient.GetProperty(place, "ID") == id);
}
textBoxSurname.Text = (string)ZooClient.GetProperty(worker, "Surname");
textBoxName.Text = (string)ZooClient.GetProperty(worker, "Name");
textBoxAge.Text = ((int)ZooClient.GetProperty(worker, "Age")).ToString();
textBoxSalary.Text = ((decimal)ZooClient.GetProperty(worker, "Salary")).ToString();
datePickerStartDate.SelectedDate = (DateTime)ZooClient.GetProperty(worker, "StartDate");
}
void Button_Click(object sender, RoutedEventArgs e)
{
if (IsDataInputValid())
{
ZooClient.SetProperty(worker, "Surname", textBoxSurname.Text);
ZooClient.SetProperty(worker, "Name", textBoxName.Text);
ZooClient.SetProperty(worker, "Age", int.Parse(textBoxAge.Text));
ZooClient.SetProperty(worker, "Salary", decimal.Parse(textBoxSalary.Text));
ZooClient.SetProperty(worker, "StartDate", datePickerStartDate.SelectedDate);
ZooClient.SetProperty(worker, "PlaceID", ZooClient.GetProperty(dataGridPlaces.SelectedItem, "ID"));
if (!parentWindow.ZooConnection.ModifyModel(worker))
{
MessageBox.Show("[ERROR] Cannot modify worker, check log for detailed cause.");
DialogResult = false;
}
else
DialogResult = true;
Close();
}
}
bool IsDataInputValid()
{
if (string.IsNullOrWhiteSpace(textBoxName.Text))
{
MessageBox.Show("[ERROR] Worker's name must be specified!");
return false;
}
else if (string.IsNullOrWhiteSpace(textBoxSurname.Text))
{
MessageBox.Show("[ERROR] Worker's surname must be specified!");
return false;
}
else if (!int.TryParse(textBoxAge.Text, out int value) || value < 16)
{
MessageBox.Show("[ERROR] Worker's age must be specified and be at least 16!");
return false;
}
else if (!decimal.TryParse(textBoxSalary.Text, out decimal val))
{
MessageBox.Show("[ERROR] Worker's salary must be specified!");
return false;
}
else if (dataGridPlaces.SelectedItems.Count <= 0)
{
MessageBox.Show("[ERROR] Must assign worker to working place, select one from the list!");
return false;
}
return true;
}
}
}
| 6b34af54590a3b055d52bc3264f4e72eaeacd34f | [
"Markdown",
"C#"
] | 37 | C# | medranSolus/ZooManager | ed20017d3eea163dbf618a5112b6400248200e37 | 541aebd2eab6af8f96746b94ad5464e35c5c0610 | |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
import urllib
import urllib2
import re
import cookielib
import logging
import os
import json
logging.basicConfig(level=logging.DEBUG)
cookies = cookielib.LWPCookieJar('cookies.txt')
try:
cookies.load(ignore_discard=True)
except:
pass
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
def login():
if islogin():
logging.info('Already logged in')
return True
url = 'http://www.zhihu.com/login/email'
user = '<EMAIL>'
passwd = '<PASSWORD>'
form = {'email': user, 'password': <PASSWORD>, 'remember_me': True}
form['_xsrf'] = get_xsrf()
form['captcha'] = get_captcha()
post_data = urllib.urlencode(form)
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36",
'Host': "www.zhihu.com",
'Origin': "http://www.zhihu.com",
'Pragma': "no-cache",
'Referer': "http://www.zhihu.com/",
'X-Requested-With': "XMLHttpRequest"
}
request = urllib2.Request(url, post_data, headers)
r = urllib2.urlopen(request)
if int(r.getcode()) != 200:
raise RuntimeError("Upload failed!")
if r.headers['content-type'].lower() == "application/json":
try:
result = json.loads(r.read())
except Exception as e:
logging.error("JSON parse failed!")
logging.debug(e)
return None
if result["r"] == 0:
logging.info("Loggin success!")
cookies.save()
return True
elif result["r"] == 1:
logging.error("Loggin failed!")
print {"error": {"code": int(result['errcode']), "message": result['msg'], "data": result['data']}}
return False
else:
logging.warning("Unkown error! \n \t %s )" % (str(result)))
return False
else:
logging.warning("Parse error")
return False
def get_xsrf():
url = 'http://www.zhihu.com'
r = urllib2.urlopen(url)
results = re.compile(
r"\<input\stype=\"hidden\"\sname=\"_xsrf\"\svalue=\"(\S+)\"", re.DOTALL).findall(r.read())
if len(results) < 1:
logging.warning("Extract xsrf code failed")
return None
return results[0]
def get_captcha():
url = 'http://www.zhihu.com/captcha.gif'
r = urllib2.urlopen(url)
image_name = 'captcha.'+r.headers['content-type'].split('/')[1]
with open(image_name, 'wb') as f:
f.write(r.read())
return raw_input('Please open image file "%s"\nInput the captcha code: ' % os.path.abspath(image_name))
def islogin():
# check session
url = "https://www.zhihu.com/settings/profile"
r = urllib2.urlopen(url)
redirect_url = r.geturl()
return redirect_url == url
if __name__ == '__main__':
login()
r = urllib2.urlopen('https://www.zhihu.com/settings/profile').read()
#open('temp.html', 'wb').write(r)
full_name = re.compile(
r'<div class="top-nav-profile">.*?<span class="name">(.*?)</span>', re.DOTALL).search(r).group(1)
print full_name#.decode('utf-8').encode('gbk')
avatar_src = re.compile(
r'<img class="avatar avatar-s".*?src="(.*?)"', re.DOTALL).search(r).group(1)
r = urllib2.urlopen(avatar_src).read()
avatar_file = 'avatar.' + avatar_src.split('.')[-1]
open(avatar_file, 'wb').write(r)
<file_sep># 知乎小工具
* 支持cookie登录 | 2fe6c1bbcafa831c25e9ff594411e868497465d9 | [
"Markdown",
"Python"
] | 2 | Python | frostming/zhihutool | 604851cfb0e33fedeb20f173dbd40529244faa21 | 706b352cc3707a167a820b9450e0b7272bcb08f1 | |
refs/heads/master | <repo_name>sakshis24/TaviscaCodejamTraining2017<file_sep>/Stack_Implementation/Stack_Operations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack_Implementation
{
public class Stack_Operations
{
private int[] stack;
private int size;
private int top_of_stack = -1;
public bool push(int data_value)
{
if (top_of_stack == size - 1)
{
Console.WriteLine("stack is empty");
return false;
}
else
{
stack[++top_of_stack] = data_value;
Console.WriteLine("stack is {0}", stack[top_of_stack]);
return true;
}
}
public int pop()
{
if (top_of_stack == -1)
{
Console.WriteLine("stack is empty");
return int.MaxValue;
}
else
{
int k = stack[top_of_stack--];
return k;
}
}
public Stack_Operations(int size_of_array)
{
stack = new int[size_of_array];
size = size_of_array;
}
}
}
<file_sep>/Stack_Implementation/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Stack_Implementation
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the size of array");
int size_of_datastructure = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter the data element to be inserted");
int data_item = Convert.ToInt32(Console.ReadLine());
Stack_Operations stackobject = new Stack_Operations(size_of_datastructure);
int choice;
bool op = true;
while (op)
{
Console.WriteLine("Enter your choice");
Console.WriteLine("1) PUSH/n 2)POP/n 3) Exit");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
stackobject.push(data_item);
break;
case 2:
stackobject.pop();
break;
case 3:
op = false;
break;
default:
Console.WriteLine("invalid choice");
break;
}
}
}
}
}
<file_sep>/Queue_Implementation/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Queue_Implementation
{
public class Queue
{
public static void Main(string[] args)
{
Console.WriteLine("enter the size of queue");
int size_of_Queue = Convert.ToInt32(Console.ReadLine());
Queue_Operations q = new Queue_Operations(size_of_Queue);
while (true)
{
int choice;
Console.WriteLine("enter your choice 1) ENQUEUE/n 2)DEQUEUE/n 3)DISPLAY/n 4)EXIT");
choice = Convert.ToInt32(Console.ReadLine());
switch(choice)
{
case 1:
Console.WriteLine("enter the element to be inserted");
int number_to_be_inserted = Convert.ToInt32(Console.ReadLine());
q.Enqueue(number_to_be_inserted);
break;
case 2: q.Dequeue();
break;
case 3:q.Display();
break;
case 4:Environment.Exit(100);
break;
default: Console.WriteLine("entered invalid choice");
break;
}
}
}
}
}
<file_sep>/Queue_Implementation/Queue_Operations.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Queue_Implementation
{
public class Queue_Operations
{
private int[] queue_array;
private int front = -1;
private int rear = -1;
int size_of_queue;
public void Enqueue(int data_item)
{
if(rear==size_of_queue-1)
{
Console.WriteLine("OVERFLOW");
}
else
{
if (front == -1)
{
front = 0;
Console.WriteLine("element to be inserted");
data_item = Convert.ToInt32(Console.ReadLine());
queue_array[++rear] = data_item;
Console.WriteLine("element inserted is {0}",queue_array[rear]);
}
}
}
public void Dequeue()
{
if(front==-1||front>rear)
{
Console.WriteLine("Underflow");
}
else
{
Console.WriteLine("queue present element after dequeue {0}", queue_array[front]);
front++;
}
}
public void Display()
{
if(front==-1)
{
Console.WriteLine("queue is empty");
}
else
{
for(int i=front;i<=rear;i++)
{
Console.WriteLine(queue_array[i] + " ");
}
}
}
public Queue_Operations(int size )
{
queue_array = new int[size];
size_of_queue = size;
}
}
}
<file_sep>/Queue_using_two_Stacks/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Queue_using_two_Stacks
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the size of the queue");
int size = Convert.ToInt32(Console.ReadLine());
Queue_using_arrays q = new Queue_using_arrays(size);
while (true)
{
Console.WriteLine("Enter 1)Enqueue\n2)Dequeue3)Display\n4)Exit");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("Enter an element");
q.Enqueue(Convert.ToInt32(Console.ReadLine()));
break;
case 2:
q.Dequeue();
break;
case 3:
q.Display();
break;
case 4:
Environment.Exit(1);
break;
}
}
}
}
}
<file_sep>/Queue_using_two_Stacks/Stack.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Queue_using_two_Stacks
{
class Stack
{
private int top_of_stack = -1;
private int[] stack;
public bool push(int data)
{
if (top_of_stack >= stack.Length)
{
return false;
}
else
{
stack[++top_of_stack] = data;
Console.WriteLine(stack[top_of_stack]);
return true;
}
}
public int pop()
{
if (top_of_stack == -1)
{
return int.MaxValue;
}
else
{
int k = stack[top_of_stack--];
return k;
}
}
public void display()
{
if (top_of_stack != -1)
{
for (int i = 0; i < top_of_stack; i++)
{
Console.WriteLine(stack[i]);
}
}
else
{
Console.WriteLine("empty");
}
}
public Stack(int SizeOfStack)
{
stack = new int[SizeOfStack];
}
}
}
<file_sep>/Queue_using_two_Stacks/Queue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Queue_using_two_Stacks
{
public class Queue_using_arrays
{
private Stack stack_inside, stack_outside;
private int size_of_queue;
public bool Enqueue(int data)
{
if (stack_inside.push(data))
{
return true;
}
else return false;
}
public void Dequeue()
{
int i = stack_inside.pop(), temp;
while (i != int.MaxValue)
{
stack_outside.push(i);
i = stack_inside.pop();
}
temp = stack_outside.pop();
i = stack_outside.pop();
while (i != int.MaxValue)
{
stack_inside.push(i);
i = stack_outside.pop();
}
}
public void Display()
{
stack_inside.display();
}
public Queue_using_arrays(int SizeOfQueue)
{
stack_inside = new Stack(SizeOfQueue);
stack_outside = new Stack(SizeOfQueue);
size_of_queue = SizeOfQueue;
}
}
}
<file_sep>/tavisca.training.2017.check_substring/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tavisca.training._2017.check_substring
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.push();
}
void push()
{
int top = -1;
Console.WriteLine("enter the string:");
String s = Console.ReadLine();
var character = s.ToCharArray();
Console.WriteLine("Original string: {0}", s);
Console.WriteLine("Character array:");
for (int i = 0; i < character.Length; i++)
{
Console.WriteLine("{0} {1}", i, character[i]);
}
Console.WriteLine("enter the string to compare:");
String s1 = Console.ReadLine();
var character1 = s1.ToCharArray();
Console.WriteLine("String to compare: {0}", s1);
Console.WriteLine(":");
for (int j = 0; j < character1.Length; j++)
Console.WriteLine("{0} {1}", j, character1[j]);
if (s.Contains(s1))
{
Console.WriteLine("s is substring of s1");
}
else
{
Console.WriteLine("s is not a substring");
}
Console.ReadLine();
}
}
}
<file_sep>/Factorial/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Zeros_in_Factorial
{
public class Factorial
{
public static void Main(string[] args)
{
Console.WriteLine("enter number :");
int n = int.Parse(Console.ReadLine());
long factorial = 1; int number_of_zero = 0;
for (int i = 1; i <= n; i++)
{
factorial = factorial * i;
}
Console.WriteLine(factorial);
while (factorial % 10 == 0)
{
number_of_zero++;
factorial /= 10;
}
Console.WriteLine(number_of_zero);
Console.ReadLine();
}
}
}
| 333383c83acc6674a67add14a3788873c8e4f00e | [
"C#"
] | 9 | C# | sakshis24/TaviscaCodejamTraining2017 | 7d8c2f8967bd9fd99af55535ee46610071ae3798 | 6dd3a667a73f8ef61255d001a1f08ed8d8bcc1ea | |
refs/heads/master | <file_sep>#include "serpent.h"
Serpent init_serpent(void){
Serpent snake ;
snake.tab[0] = (Case) {N/2, M/2};
snake.tab[1] = (Case) {N/2 - 1, M/2};
snake.dir.x = 1 ;
snake.dir.y = 0 ;
snake.taille = 2;
int i = 2 ;
for (; i <= snake.taille + 2; ++i){
snake.tab[i] = (Case) {N/2 - i, M/2};
}
return snake ;
}<file_sep>#include "pomme.h"
Pomme pomme_gen_alea(int n, int m){
assert (n > 0);
assert (m > 0);
Pomme p ;
p.pomme.x = MLV_get_random_integer (0,n) ;
p.pomme.y = MLV_get_random_integer (0,m) ;
return p ;
}
Case mur_gen_alea(int n, int m){
assert (n > 0);
assert (m > 0);
Case c ;
c.x = MLV_get_random_integer (0,n) ;
c.y = MLV_get_random_integer (0,m) ;
return c ;
}<file_sep>CFLAGS = -g -O2 -Wall -Werror `pkg-config --cflags MLV`
LDLIBS = `pkg-config --libs MLV`
Snake: plateau.o affichage.o serpent.o pomme.o main.o
gcc -o Snake plateau.o affichage.o serpent.o pomme.o main.o $(CFLAGS) $(LDLIBS)
pomme.o: pomme.c pomme.h serpent.h
gcc -c pomme.c $(CFLAGS) $(LDLIBS)
plateau.o: plateau.c plateau.h pomme.h serpent.h son.c
gcc -c plateau.c $(CFLAGS)
affichage.o: affichage.c affichage.h plateau.c
gcc -c affichage.c $(CFLAGS) $(LDLIBS)
serpent.o: serpent.c serpent.h
gcc -c serpent.c $(CFLAGS)
son.o: son.c son.h
gcc -c serpent.c $(CFLAGS) $(LDLIBS)
main.o: main.c plateau.h serpent.h affichage.h pomme.h
gcc -c main.c $(CFLAGS)
<file_sep>#ifndef __serpent__
#define __serpent__
#include <stdlib.h>
#include <stdio.h>
#define M 64
#define N 32
typedef struct Case{
int x ;
int y ;
}Case;
typedef struct {
int x ;
int y ;
}Direction ;
typedef struct serpent {
Case tab[N*M] ;
Direction dir ;
int taille ;
}Serpent;
/* renvoie un serpent dans sa position initiale
avec 1 tete et une partie pour le corp sa direction
est a l'EST et sa taille est donc 2 */
Serpent init_serpent(void);
#endif<file_sep>#include "son.c"
#include "plateau.h"
int est_case_pomme(Monde* monde_pomme, Case c){
assert(monde_pomme >= 0);
int i = 0;
for (i = 0; i < monde_pomme->nb_pommes; i++){
if ((c.x == monde_pomme->apple[i].pomme.x ) && ((c.y) == monde_pomme->apple[i].pomme.y))
return 1;
}
return 0;
}
int est_case_serpent(Monde* monde_serpent, Case c){
assert(monde_serpent != NULL);
int i = 0;
for (i = 0; i < monde_serpent->snake.taille; i++){
if ((c.x == monde_serpent->snake.tab[i].x ) && ((c.y) == monde_serpent->snake.tab[i].y))
return 1;
}return 0;
}
int est_case_pomme_poison(Monde* monde_pomme_poison, Case c){
assert(monde_pomme_poison != NULL);
int i = 0;
for (i = 0; i < monde_pomme_poison->nb_pommes_poisons ; i++){
if ((c.x == monde_pomme_poison->appleP[i].pomme.x ) && ((c.y) == monde_pomme_poison->appleP[i].pomme.y))
return 1;
}
return 0;
}
int est_case_mur(Monde* mon,Case c){
assert(mon != NULL);
Case cx1 = {c.x+1,c.y} ;
Case cx2 = {c.x-1,c.y};
Case cy1 = {c.x,c.y+1};
Case cy2 = {c.x,c.y-1};
if (est_case_pomme(mon, c) || est_case_serpent(mon, c) || est_case_pomme_poison(mon,c)
|| est_case_serpent(mon,cy2) || est_case_serpent(mon,cy1) || est_case_serpent(mon,cx1)
|| est_case_serpent(mon,cx2)){
return 1;
}
return 0;
}
void ajouter_pomme_monde(Monde *mon){
assert(mon != NULL);
Pomme p;
do {
p = pomme_gen_alea (N,M);
// regenerer une nouvelle pomme tant que la case de la pomme est occupée
}while ((est_case_pomme(mon, p.pomme)) || (est_case_serpent(mon, p.pomme)));
mon->apple[mon->nb_pommes] = p;
mon->nb_pommes++;
}
int mur_present(Monde *mon ,Case c){
if (mon->mur.x == c.x && c.y == mon->mur.y)
return 1;
return 0 ;
}
void ajouter_pomme_poison_monde(Monde *mon){
assert(mon != NULL);
Pomme p;
do {
p = pomme_gen_alea (N,M);
// regenerer une nouvelle pomme tant que la case de la pomme est occupée
}while ((est_case_pomme(mon, p.pomme)) || (est_case_serpent(mon, p.pomme)) || (est_case_pomme_poison(mon,p.pomme)));
mon->appleP[mon->nb_pommes_poisons] = p;
mon->nb_pommes_poisons++;
}
void ajouter_mur_monde(Monde *mon){
assert(mon != NULL);
Case p;
do {
p = mur_gen_alea(N,M);
// regenerer une nouveau mur tant que la case du mur est occupée
}while (est_case_mur(mon,p));
mon->mur = p ;
}
void supp_pomme(Monde* mon, Case c){
assert(mon != NULL);
int i = 0;
for (i =0; i < mon->nb_pommes; i++){
if ((c.x == mon->apple[i].pomme.x) && (c.y == mon->apple[i].pomme.y)){
mon->apple[i].pomme.x = MLV_get_random_integer (0,N) ;
mon->apple[i].pomme.y = MLV_get_random_integer (0,M) ;
mon->nb_pomme_manger += 1 ;
}
}
}
Monde init_monde(int nb_pommes,int nb_pommes_poisons){
assert(nb_pommes >= 0 );
assert(nb_pommes_poisons >= 0);
Monde world ;
world.snake = init_serpent();
world.nb_pommes = 0;
world.nb_pomme_manger = 0 ;
int i = 0 ;
int ii = 0 ;
while (i < nb_pommes){
ajouter_pomme_monde(&world);
i++ ;
}
while (ii < nb_pommes_poisons){
ajouter_pomme_poison_monde(&world);
ii++ ;
}
ajouter_mur_monde(&world);
return world ;
}
int manger_pomme_serpent(Monde *mon){
assert(mon != NULL);
int i;
Serpent* serpent = &mon->snake;
Direction dir = serpent->dir;
Case courante = serpent->tab[0];
Case prochaine = {courante.x + dir.x, courante.y + dir.y};
// verifier que la prochaine case est bien dans le quadrillage
if (prochaine.x < 0 || prochaine.y < 0 || prochaine.y > M+1 || prochaine.x > N+1)
return 0;
// verifier que le serpent n'est pas deja sur la case "prochaine"
if (est_case_serpent(mon, prochaine))
return 0;
// verifier que la case suivante est bien une pomme
if (est_case_pomme(mon, prochaine)){
MLV_init_audio();
MLV_Music* manger = MLV_load_music( "manger.mp3" );
son(manger);
supp_pomme(mon, prochaine);
ajouter_mur_monde(mon);
serpent->taille = serpent->taille + 1 ;
for (i = serpent->taille - 1; i > 0; i--)
serpent->tab[i] = serpent->tab[i-1];
serpent->tab[0] = prochaine;
}
return 1;
}
int deplacer_serpent(Monde *mon){
assert(mon != NULL);
int i;
Serpent* serpent = &mon->snake;
Direction dir = serpent->dir;
Case courante = serpent->tab[0];// a verifier
Case prochaine = {courante.x + dir.x, courante.y + dir.y};
// verifier que la prochaine case est bien dans le quadrillage
if (prochaine.x < -1 || prochaine.y < -1 || prochaine.y > M || prochaine.x > N)
return 0;
// verifier qu'aucune pomme empoisonée n'est sur la case "prochaine"
if (est_case_pomme_poison(mon, prochaine))
return 0 ;
// verifier que le serpent ou mur n'est pas deja sur la case "prochaine"
if (est_case_serpent(mon, prochaine) || mur_present(mon,prochaine))
return 0;
// avancer la tete du sepent vers la direction souhaiter grace a case suivante et faire suivre le corp
for (i = serpent->taille + 1; i > 0; i--){
serpent->tab[i].x = serpent->tab[i-1].x;
serpent->tab[i].y = serpent->tab[i-1].y;
}
serpent->tab[0] = prochaine;
return 1;
}
int mort_serpent(Monde *mon){
assert(mon != NULL);
Serpent* serpent = &mon->snake;
Direction dir = serpent->dir;
MLV_init_audio();
MLV_Music* mort = MLV_load_music( "mort.mp3" );
Case courante = serpent->tab[0];
Case prochaine = {courante.x + dir.x, courante.y + dir.y};
// verifier que la prochaine case est bien dans le quadrillage
if (prochaine.x <-1 || prochaine.y <-1 || prochaine.y > M || prochaine.x > N){
son(mort);
return 1;
}
// verifier que le serpent n'est pas deja sur la case "prochaine"
if (est_case_serpent(mon, prochaine)){
son(mort);
return 1;
}
// verifier qu'aucune pomme poison n'est sur la case "prochaine" ou un mur
if (est_case_pomme_poison(mon, prochaine) ){
son(mort);
return 1;
}
if (mur_present(mon,prochaine)){
son(mort);
return 1;
}
else
return 0;
}<file_sep>#include "affichage.h"
#include "plateau.h"
#define WIDTH 700
#define HEIGHT 700
int main(int argc, char const *argv[]){
int temp = 0;
char temp_text[50];
Monde monde = init_monde(3,2);
MLV_Keyboard_button touche;
MLV_init_audio( );
MLV_create_window( "snake", "tp3", WIDTH, HEIGHT );
do{
MLV_clear_window(MLV_COLOR_BLACK);
afficher_monde(&monde);
temp = MLV_get_time();//une fonction qui va recupere le temps depuis le lancement du jeux
sprintf(temp_text,"Temps écoulés: %ds/120s",temp/1000 );//convertit le temps pour un char
MLV_draw_adapted_text_box(500 ,100 ,temp_text,20 ,MLV_COLOR_GREEN,MLV_COLOR_BLUE,MLV_COLOR_WHITE,MLV_TEXT_CENTER);//affiche le temps
MLV_actualise_window();
MLV_get_event (&touche, NULL, NULL,NULL, NULL,NULL, NULL, NULL,NULL);
MLV_wait_milliseconds(50);
if( touche == MLV_KEYBOARD_z ){
monde.snake.dir.x = 0;
monde.snake.dir.y = -1;
}
if( touche == MLV_KEYBOARD_s ){
monde.snake.dir.x = 0;
monde.snake.dir.y = 1;
}
if( touche == MLV_KEYBOARD_d ){
monde.snake.dir.x = 1;
monde.snake.dir.y = 0;
}
if( touche == MLV_KEYBOARD_q ){
monde.snake.dir.x = -1;
monde.snake.dir.y = 0;
}
while (touche == MLV_KEYBOARD_p){
// pour faire la pause
MLV_wait_keyboard(&touche,NULL,NULL );
}
touche = MLV_KEYBOARD_m ;
manger_pomme_serpent(&monde);
deplacer_serpent(&monde);
}while (!(mort_serpent(&monde)) && temp/1000 < 120);
MLV_free_window();
return 0;
}
<file_sep>#ifndef __pomme__
#define __pomme__
#include <assert.h>
#include <MLV/MLV_all.h>
#include "serpent.h"
typedef struct pomme {
Case pomme ;
}Pomme;
/* prend en argument 2 int correspondant respectivement a la largeur
et a la hauteur du quadrillage affecte ensuite des coordonnées
aleatoire comprises entre les 2 int a une pomme puis la renvoie */
Pomme pomme_gen_alea(int n, int m);
/* prend en argument 2 int correspondant respectivement a la largeur
et a la hauteur du quadrillage affecte ensuite des coordonnées
aleatoire comprises entre les 2 int a une case puis la renvoie */
Case mur_gen_alea(int n, int m);
#endif<file_sep>#include "son.h"
void son (MLV_Music* music){
MLV_play_music( music, 1.0, -1 );
MLV_wait_seconds(1);
MLV_stop_music();
MLV_free_music( music );
MLV_free_audio();
}
<file_sep>#include "affichage.h"
void afficher_quadrillage(void){
int i = 0 ;
int j = 0 ;
for (; i < N ; i++){
for (j = 0; j < M; j++){
MLV_draw_rectangle((i*10),j*10,10,10,MLV_COLOR_BLUE);
}
}
}
void afficher_pomme(Pomme *pom){
assert(pom != NULL);
int i = 0 ;
int j ;
int x = pom->pomme.x ;
int y = pom->pomme.y ;
MLV_Image * image ;
image =MLV_load_image ("pomme.jpg");
MLV_resize_image (image,10,10);
for (; i < N ; i++){
for (j = 0; j < M; j++){
if (i == x && j == y ){
//MLV_draw_filled_circle(i*10 + 5,j*10 + 5,3, MLV_COLOR_GREEN);
MLV_draw_image (image,i*10 ,j*10);
}
}
}
}
void afficher_pomme_poison(Pomme *pom){
assert(pom != NULL);
int i = 0 ;
int j ;
int x = pom->pomme.x ;
int y = pom->pomme.y ;
MLV_Image * image ;
image =MLV_load_image ("pommeP.jpg");
MLV_resize_image (image,10,10);
for (; i < N ; i++){
for (j = 0; j < M; j++){
if (i == x && j == y ){
//MLV_draw_filled_circle(i*10 + 5,j*10 + 5,3, MLV_COLOR_GREEN);
MLV_draw_image (image,i*10 ,j*10);
}
}
}
}
void afficher_serpent(Serpent *ser){
assert(ser != NULL);
int i = 2 ;
MLV_draw_filled_rectangle((ser->tab[0].x)*10,(ser->tab[0].y)*10,10,10, MLV_COLOR_ORANGE);
MLV_draw_filled_rectangle((ser->tab[1].x)*10,(ser->tab[1].y)*10,10,10, MLV_COLOR_RED);
for (; i < ser->taille + 2; ++i){
MLV_draw_filled_rectangle((ser->tab[i].x)*10,(ser->tab[i].y)*10,10,10, MLV_COLOR_RED);
}
}
void afficher_mur(Case c){
assert(c.x >= 0 && c.y >= 0);
MLV_draw_filled_rectangle(c.x*10,c.y*10,10,10, MLV_COLOR_RED);
}
void afficher_score(Monde *mon){
assert(mon != NULL);
char str[10] = "";
int nombre = mon->nb_pomme_manger;
sprintf(str, "%d", nombre); // transforme le score qui est un (int) en une chaine de caractere afin de l'afficher
MLV_draw_text(500, 335, "Votre score :", MLV_COLOR_WHITE);
MLV_draw_text(535, 350, str, MLV_COLOR_WHITE);
}
void afficher_monde(Monde *mon ){
assert(mon != NULL);
assert(mon->mur.x >= 0 && mon->mur.y >= 0);
assert(mon->apple != NULL);
assert(mon->appleP != NULL);
afficher_quadrillage();
afficher_pomme(&(mon->apple[0]));
afficher_pomme(&(mon->apple[1]));
afficher_pomme(&(mon->apple[2]));
afficher_pomme_poison(&(mon->appleP[0]));
afficher_pomme_poison(&(mon->appleP[1]));
afficher_serpent(&(mon->snake));
afficher_mur(mon->mur);
afficher_score(mon);
}
<file_sep>#include <MLV/MLV_all.h>
#ifndef __son__
#define __son__
/* Prend un son en argument, le joue, l'arrete, puis le free de la memoire */
void son();
#endif
<file_sep>#ifndef __plateau__
#define __plateau__
#include "pomme.h"
typedef struct monde{
Serpent snake ;
Pomme apple[N * M];
Pomme appleP[N * M];
Case mur ;
int nb_pommes;
int nb_pommes_poisons;
char nb_pomme_manger ;
}Monde;
/* prend une case et un monde en argument et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par une pomme, renvoie 1 si c'est le cas et 0 sinon. */
int est_case_pomme(Monde* monde_pomme, Case c);
/* prend une case et un monde en argument et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par le serpent, renvoie 1 si c'est le cas et 0 sinon. */
int est_case_serpent(Monde* monde_pomme, Case c);
/* prend une case et un monde en argument et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par une pomme empoisonnées, renvoie 1 si c'est le cas et 0 sinon. */
int est_case_pomme_poison(Monde* monde_pomme_poison, Case c);
/* ajoute une pomme generer aleatoirement par pomme_gen_alea dans un monde donné en argument */
void ajouter_pomme_monde(Monde *mon);
/* ajoute une pomme empoisonnées generer aleatoirement par pomme_gen_alea dans un monde donné en argument */
void ajouter_pomme_poison_monde(Monde *mon);
/* prend une case et un monde en argument et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par une pomme empoisonnées, si c'est le cas
genere une nouvelle pomme et incremente le score (nb_pomme_manger) */
void supp_pomme(Monde* mon, Case c);
/* prend en argument un nombre de pomme et de pomme empoisonnées et
renvoie un monde dans sa position initiale avec le serpent initialisé
grace init_serpent et le bon nombre de pommes données en arguments */
Monde init_monde(int nb_pommes, int nb_pommes_poisons);
/* prend un monde en argument et si la case suivante correspondante a la direction du serpent
est une pomme, effectue la suppression de la pomme et se regeneraion ailleur
assure aussi le deplacement suivant du serpent et l'augmentation de sa taille
renvoie 1 si la case suivante est bien une pomme et 0 sinon */
int manger_pomme_serpent(Monde *mon);
/* prend un monde en argument et si la case suivante correspondante a la direction du serpent
n'est pas une case occupée par quoi que ce soit, effectue le deplacement suivant du serpent
et l'augmentation de sa taille renvoie 1 si la case suivante est bien libre et 0 sinon */
int deplacer_serpent(Monde *mon);
/* prend un monde en argument et si la case suivante correspondante a la direction du serpent
est soit une partie du serpent, soit une case en dehors du quadrillage ou soit une pomme empoisonnées
renvoie 1 et 0 sinon */
int mort_serpent(Monde *mon);
/* ajoute un mur generer aleatoirement par mur_gen_alea dans un monde donné en argument */
void ajouter_mur_monde(Monde *mon);
/* prend une case et un monde en argument et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par une pomme empoisonnées,serpent ,pomme
renvoie 1 si c'est le cas et 0 sinon. */
int est_case_mur(Monde* mon,Case c);
/* prend une case et un monde en argument et une case et verifie si
les coordonnées de la case corespondent a cellle d'une
case occupée par un mur , renvoie 1 si c'est le cas et 0 sinon. */
int mur_present(Monde *mon ,Case c);
#endif
<file_sep>#ifndef __affichage__
#define __affichage__
#include "plateau.h"
#include <MLV/MLV_all.h>
/* affiche le quadrillage N*M */
void afficher_quadrillage();
/* affiche le quadrillage N*M */
void afficher_pomme(Pomme *pom);
/* la meme chose avec une pomme (bleu) poison */
void afficher_pomme_poison(Pomme *pom);
/* prend un serpent en argument et l'affiche sur le quadrillage */
void afficher_serpent(Serpent *ser);
/* prend un monde en argument et recupere nb_pomme_manger afin d'afficher le score */
void afficher_score(Monde *mon);
/* prend un monde en argument et affiche tout ce qu'il contient (quadrillage, pomme, score, sepent, mur, score)*/
void afficher_monde(Monde *mon);
/* affiche un mur sur une case données */
void afficher_mur(Case c);
#endif
| 3627a42a6ffbfc34acb1e216e03febacd8b41f0e | [
"C",
"Makefile"
] | 12 | C | amadious/Snake | c78a20613ab343f3bff858f0cb830705e6ed68a7 | 050636d840615a2002f468da92589b349c35b899 | |
refs/heads/master | <repo_name>skwongg/Backseat_DJ_backend<file_sep>/deploy/before_restart.rb
# run "cd /srv/www/Backseat_DJ_backend/current && /usr/local/bin/bundle exec rake assets:precompile"
run "cd /srv/www/photopoll/current && /usr/local/bin/bundle exec rake assets:precompile"<file_sep>/config/environment.rb
# Fix the environment
if ENV['STAGING']
%w(RACK_ENV RAILS_ENV).each do |key|
ENV[key] = 'staging'
end
end
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
| d81652e18c296a69cc02d13724baa89ecf7cee92 | [
"Ruby"
] | 2 | Ruby | skwongg/Backseat_DJ_backend | e0e5abc9890eac19dfd6de6ee5c6a67fab4b0d1a | 15e140e23688c70107c85db844b9dd4055bb7806 | |
refs/heads/master | <repo_name>anamikapainuly/RetrofitAPI-Nav-Graph-Anamika-Test<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/ui/weather/future/detail/FutureDetailWeatherFragment.kt
package com.anupras.apl.anamika_test.ui.weather.future.detail
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.anupras.apl.anamika_test.R
import com.anupras.apl.anamika_test.constant.CITY_NAME
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.synthetic.main.future_detail_weather_fragment.*
class FutureDetailWeatherFragment : Fragment() {
companion object {
fun newInstance() =
FutureDetailWeatherFragment()
}
private lateinit var viewModel: FutureDetailWeatherViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.future_detail_weather_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(FutureDetailWeatherViewModel::class.java)
textView_city_name_detail.text = CITY_NAME
date_to_show_detail.text = arguments?.getString("day")
textView_condition_detail.text = arguments?.getString("description").toString().capitalize()
textView_temperature_detail.text = arguments?.getString("temp")
textView_min_max_temperature_detail.text = arguments?.getString("tempMinMax")
val options: RequestOptions = RequestOptions()
.centerCrop()
.error(R.mipmap.ic_launcher_round)
Glide .with(this)
.load(arguments?.getString("icon").toString()).apply(options)
.into(imageView_condition_icon_detail)
}
}<file_sep>/app/build/generated/source/navigation-args/debug/com/anupras/apl/anamika_test/ui/weather/future/list/FutureListWeatherFragmentDirections.java
package com.anupras.apl.anamika_test.ui.weather.future.list;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.navigation.NavDirections;
import com.anupras.apl.anamika_test.R;
import java.lang.IllegalArgumentException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.HashMap;
public class FutureListWeatherFragmentDirections {
private FutureListWeatherFragmentDirections() {
}
@NonNull
public static ActionDetail actionDetail(@NonNull String day, @NonNull String description,
@NonNull String temp, @NonNull String icon, @NonNull String tempMinMax) {
return new ActionDetail(day, description, temp, icon, tempMinMax);
}
public static class ActionDetail implements NavDirections {
private final HashMap arguments = new HashMap();
private ActionDetail(@NonNull String day, @NonNull String description, @NonNull String temp,
@NonNull String icon, @NonNull String tempMinMax) {
if (day == null) {
throw new IllegalArgumentException("Argument \"day\" is marked as non-null but was passed a null value.");
}
this.arguments.put("day", day);
if (description == null) {
throw new IllegalArgumentException("Argument \"description\" is marked as non-null but was passed a null value.");
}
this.arguments.put("description", description);
if (temp == null) {
throw new IllegalArgumentException("Argument \"temp\" is marked as non-null but was passed a null value.");
}
this.arguments.put("temp", temp);
if (icon == null) {
throw new IllegalArgumentException("Argument \"icon\" is marked as non-null but was passed a null value.");
}
this.arguments.put("icon", icon);
if (tempMinMax == null) {
throw new IllegalArgumentException("Argument \"tempMinMax\" is marked as non-null but was passed a null value.");
}
this.arguments.put("tempMinMax", tempMinMax);
}
@NonNull
public ActionDetail setDay(@NonNull String day) {
if (day == null) {
throw new IllegalArgumentException("Argument \"day\" is marked as non-null but was passed a null value.");
}
this.arguments.put("day", day);
return this;
}
@NonNull
public ActionDetail setDescription(@NonNull String description) {
if (description == null) {
throw new IllegalArgumentException("Argument \"description\" is marked as non-null but was passed a null value.");
}
this.arguments.put("description", description);
return this;
}
@NonNull
public ActionDetail setTemp(@NonNull String temp) {
if (temp == null) {
throw new IllegalArgumentException("Argument \"temp\" is marked as non-null but was passed a null value.");
}
this.arguments.put("temp", temp);
return this;
}
@NonNull
public ActionDetail setIcon(@NonNull String icon) {
if (icon == null) {
throw new IllegalArgumentException("Argument \"icon\" is marked as non-null but was passed a null value.");
}
this.arguments.put("icon", icon);
return this;
}
@NonNull
public ActionDetail setTempMinMax(@NonNull String tempMinMax) {
if (tempMinMax == null) {
throw new IllegalArgumentException("Argument \"tempMinMax\" is marked as non-null but was passed a null value.");
}
this.arguments.put("tempMinMax", tempMinMax);
return this;
}
@Override
@SuppressWarnings("unchecked")
@NonNull
public Bundle getArguments() {
Bundle __result = new Bundle();
if (arguments.containsKey("day")) {
String day = (String) arguments.get("day");
__result.putString("day", day);
}
if (arguments.containsKey("description")) {
String description = (String) arguments.get("description");
__result.putString("description", description);
}
if (arguments.containsKey("temp")) {
String temp = (String) arguments.get("temp");
__result.putString("temp", temp);
}
if (arguments.containsKey("icon")) {
String icon = (String) arguments.get("icon");
__result.putString("icon", icon);
}
if (arguments.containsKey("tempMinMax")) {
String tempMinMax = (String) arguments.get("tempMinMax");
__result.putString("tempMinMax", tempMinMax);
}
return __result;
}
@Override
public int getActionId() {
return R.id.actionDetail;
}
@SuppressWarnings("unchecked")
@NonNull
public String getDay() {
return (String) arguments.get("day");
}
@SuppressWarnings("unchecked")
@NonNull
public String getDescription() {
return (String) arguments.get("description");
}
@SuppressWarnings("unchecked")
@NonNull
public String getTemp() {
return (String) arguments.get("temp");
}
@SuppressWarnings("unchecked")
@NonNull
public String getIcon() {
return (String) arguments.get("icon");
}
@SuppressWarnings("unchecked")
@NonNull
public String getTempMinMax() {
return (String) arguments.get("tempMinMax");
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
ActionDetail that = (ActionDetail) object;
if (arguments.containsKey("day") != that.arguments.containsKey("day")) {
return false;
}
if (getDay() != null ? !getDay().equals(that.getDay()) : that.getDay() != null) {
return false;
}
if (arguments.containsKey("description") != that.arguments.containsKey("description")) {
return false;
}
if (getDescription() != null ? !getDescription().equals(that.getDescription()) : that.getDescription() != null) {
return false;
}
if (arguments.containsKey("temp") != that.arguments.containsKey("temp")) {
return false;
}
if (getTemp() != null ? !getTemp().equals(that.getTemp()) : that.getTemp() != null) {
return false;
}
if (arguments.containsKey("icon") != that.arguments.containsKey("icon")) {
return false;
}
if (getIcon() != null ? !getIcon().equals(that.getIcon()) : that.getIcon() != null) {
return false;
}
if (arguments.containsKey("tempMinMax") != that.arguments.containsKey("tempMinMax")) {
return false;
}
if (getTempMinMax() != null ? !getTempMinMax().equals(that.getTempMinMax()) : that.getTempMinMax() != null) {
return false;
}
if (getActionId() != that.getActionId()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + (getDay() != null ? getDay().hashCode() : 0);
result = 31 * result + (getDescription() != null ? getDescription().hashCode() : 0);
result = 31 * result + (getTemp() != null ? getTemp().hashCode() : 0);
result = 31 * result + (getIcon() != null ? getIcon().hashCode() : 0);
result = 31 * result + (getTempMinMax() != null ? getTempMinMax().hashCode() : 0);
result = 31 * result + getActionId();
return result;
}
@Override
public String toString() {
return "ActionDetail(actionId=" + getActionId() + "){"
+ "day=" + getDay()
+ ", description=" + getDescription()
+ ", temp=" + getTemp()
+ ", icon=" + getIcon()
+ ", tempMinMax=" + getTempMinMax()
+ "}";
}
}
}
<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/ui/weather/future/list/FutureListWeatherFragment.kt
package com.anupras.apl.anamika_test.ui.weather.future.list
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.anupras.apl.anamika_test.R
import com.anupras.apl.anamika_test.adapter.ForecastsWeatherAdapter
import com.anupras.apl.anamika_test.constant.CITY_NAME
import com.anupras.apl.anamika_test.constant.NO_OF_DAYS
import com.anupras.apl.anamika_test.constant.UNIT
import com.anupras.apl.anamika_test.data.ForecastDetail
import com.anupras.apl.anamika_test.service.OpenWeatherApiService
import kotlinx.android.synthetic.main.future_list_weather_fragment.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class FutureListWeatherFragment : Fragment() {
companion object {
fun newInstance() =
FutureListWeatherFragment()
}
private lateinit var viewModel: FutureListWeatherViewModel
protected lateinit var rootView: View
lateinit var recyclerView: RecyclerView
var dataList= ArrayList<ForecastDetail> ()
var myAdapter: ForecastsWeatherAdapter? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
rootView = inflater.inflate(R.layout.future_list_weather_fragment, container, false);
initView()
return rootView
}
private fun initView() {
initializeRecyclerView()
}
//Initializing recycler view
private fun initializeRecyclerView() {
recyclerView = rootView.findViewById(R.id.recyclerView) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(activity)
//recyclerView.adapter = adapter
myAdapter = activity?.let { ForecastsWeatherAdapter(dataList, it) }
recyclerView.adapter = myAdapter
myAdapter?.notifyDataSetChanged();
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(FutureListWeatherViewModel::class.java)
// TODO: Use the ViewModel
val apiService = OpenWeatherApiService()
GlobalScope.launch(Dispatchers.Main) {
val futuretWeatherResponse =
apiService.getFutureWeather(CITY_NAME, UNIT, NO_OF_DAYS).await()
if (futuretWeatherResponse != null) {
futuretWeatherResponse.forecast?.let { dataList.addAll(it)
recyclerView.adapter!!.notifyDataSetChanged()
}
Log.d("Response - DataList", "" + dataList)
}
}
}
}<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/ui/weather/current/CurrentWeatherFragment.kt
package com.anupras.apl.anamika_test.ui.weather.current
import android.app.Activity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.anupras.apl.anamika_test.R
import com.anupras.apl.anamika_test.constant.CITY_NAME
import com.anupras.apl.anamika_test.constant.UNIT
import com.anupras.apl.anamika_test.service.OpenWeatherApiService
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.current_weather_fragment.*
import kotlinx.android.synthetic.main.current_weather_fragment.view.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
class CurrentWeatherFragment : Fragment() {
companion object {
fun newInstance() =
CurrentWeatherFragment()
}
private lateinit var viewModel: CurrentWeatherViewModel
lateinit var cityText :String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater!!.inflate(R.layout.current_weather_fragment, container, false)
//Button click to see weather of entered city
view.search_btn_current.setOnClickListener { view ->
//Hide Keyboard
hideSoftKeyboard(activity!!)
//Get city name from EditText
var cityNameEntered = input_city_current.text.toString()
if (cityNameEntered!=""){
CITY_NAME=cityNameEntered
loadApi(CITY_NAME)
}
textView_city_name_current.text= CITY_NAME
}
// Return the fragment view/layout
return view
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(CurrentWeatherViewModel::class.java)
//Load Data of default city
loadApi(CITY_NAME)
// val cityText= input_city_current.text.toString()
// TODO: Use the ViewModel
}
fun hideSoftKeyboard(activity: Activity) {
val inputMethodManager =
activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(activity.currentFocus!!.windowToken, 0)
}
private fun loadApi(CITY_NAME: String) {
val apiService = OpenWeatherApiService()
GlobalScope.launch(Dispatchers.Main) {
val currentWeatherResponse = apiService.getCurrentWeather(CITY_NAME, UNIT).await()
textView_temperature_current.text =
currentWeatherResponse.currentWeatherEntry.temp.toString() + "°C"
textView_min_max_temperature_current.text =
"Min: " + currentWeatherResponse.currentWeatherEntry.tempMin.toString() + "°C" + "," + "Max: " + currentWeatherResponse.currentWeatherEntry.tempMax.toString() + "°C"
//DESCRIPTION
textView_condition_current.text= currentWeatherResponse.weather[0].description.capitalize()
val dateReceived: Long = currentWeatherResponse.dt
//val time = Date(date_received as Long * 1000)
date_to_show_current.text= dateReceived?.let { getData(it) }
textView_city_name_current.text=currentWeatherResponse.name
Glide.with(this@CurrentWeatherFragment)
.load("http://openweathermap.org/img/w/${currentWeatherResponse.weather[0].icon}.png")
.into(imageView_condition_icon_current)
}
}
private fun getData(dt: Long): String? {
val timeFormatter = SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z")
return timeFormatter.format(Date(dt * 1000L))
}
}
<file_sep>/README.md
Use OpenWeatherMap.org to build a simple weather app that can show the weather for a city for the next 7 days.
Has the following features:
*Allow a user to enter a city name,
*App calls
*REST API which returns JSON for weather next for next 7 days.
*Display's day, temp, and description for each day using lists (recycle adapter)
*User can tap a day (or some other way) to see more detail for the current day, including: day, city, temp, min, max description and weather icon (optional).
*Navigation graph to navigate to a detail fragment showing more information
*Using OKHttp3 and Retrofit
*Kotin
*Nav Graph and fragments, only 1 activity
<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/data/FutureWeatherResponse.kt
package com.anupras.apl.anamika_test.data
import com.google.gson.annotations.SerializedName
data class FutureWeatherResponse (
@SerializedName("list")
val forecast : List<ForecastDetail> ? = ArrayList(),
@SerializedName("city") var city : City
)
data class ForecastDetail(
@SerializedName("dt") var date: Long?,
@SerializedName("temp") var temperature : Temperature?,
@SerializedName("weather") var description : List<WeatherDescription>,
@SerializedName("pressure") var pressure : Double?,
@SerializedName("humidity") var humidity :Double?)
data class City(
@SerializedName("name") var cityName : String,
@SerializedName("country") var country : String)
data class Temperature (
@SerializedName("day") var dayTemperature: Double,
@SerializedName("night") var nightTemperature: Double)
data class WeatherDescription(
@SerializedName("main") var main : String,
@SerializedName("description") var description: String,
@SerializedName("icon") var icon: String)
<file_sep>/settings.gradle
include ':app'
rootProject.name = "anamika-test"<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/constant/const.kt
package com.anupras.apl.anamika_test.constant
//const val API_KEY = "<KEY>"
//const val API_KEY = "<KEY>"
var CITY_NAME : String = "Wellington"
const val UNIT = "metric";
const val NO_OF_DAYS = "7";<file_sep>/app/src/main/java/com/anupras/apl/anamika_test/adapter/ForecastsWeatherAdapter.kt
package com.anupras.apl.anamika_test.adapter
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.anupras.apl.anamika_test.R
import com.anupras.apl.anamika_test.data.ForecastDetail
import com.anupras.apl.anamika_test.ui.weather.future.list.FutureListWeatherFragmentDirections
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.item_future_weather.view.*
import java.text.SimpleDateFormat
import java.util.*
class ForecastsWeatherAdapter(
private val dataList: ArrayList<ForecastDetail>,
private val context: Context
) : RecyclerView.Adapter<ForecastsWeatherAdapter.ForecastViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ForecastViewHolder {
val rootView = LayoutInflater.from(parent.context).inflate(
R.layout.item_future_weather,
parent,
false
)
return ForecastViewHolder(rootView)
}
override fun onBindViewHolder(holder: ForecastViewHolder, position: Int) {
dataList[position].let {
holder.bind(forecastElement = it)
}
}
override fun getItemCount(): Int {
return dataList.size
}
class ForecastViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(forecastElement: ForecastDetail) {
val temMinMax: String="Day Temp: ${forecastElement.temperature?.dayTemperature}°C"+","+ " Night Temp: ${forecastElement.temperature?.nightTemperature}°C"
val temperatureVar: String="${forecastElement.temperature?.dayTemperature} °C"
val descriptionVar: String="${forecastElement.description[0].description}"
val imageUrlVar: String="http://openweathermap.org/img/w/${forecastElement.description[0].icon}.png"
val dateVar: String="${forecastElement.date?.let { getData(it)}}"
itemView.setOnClickListener {
Log.d("CHECK....", "position = " + "${forecastElement.temperature?.dayTemperature} °C")
showWeatherDetail(dateVar, descriptionVar,temperatureVar,imageUrlVar,temMinMax, itemView);
}
//Display temperature
itemView.textView_temperature_future.text = temperatureVar
//Display Date
itemView.textView_date_future.text = "${forecastElement.date?.let { getDay(it)}}"
//Display weather icon
Glide.with(itemView.context)
.load(imageUrlVar)
.into(itemView.imageView_condition_icon_future)
//Display condition
itemView.textView_condition_future.text= descriptionVar.capitalize()
}
private fun showWeatherDetail(date:String, descriptionVar: String,temperatureVar: String,imageUrlVar: String,temMinMax: String, view: View) {
val actionDetail = FutureListWeatherFragmentDirections.actionDetail(date, descriptionVar, temperatureVar, imageUrlVar, temMinMax)
Navigation.findNavController(view).navigate(actionDetail)
}
private fun getData(dt: Long): String? {
//val timeFormatter = SimpleDateFormat("\"dd-EEEE, MM, yyyy\"")
val timeFormatter = SimpleDateFormat("E, dd MMM yyyy")
return timeFormatter.format(Date(dt * 1000L))
}
private fun getDay(dt: Long): String? {
//val timeFormatter = SimpleDateFormat("\"dd-EEEE, MM, yyyy\"")
val timeFormatter = SimpleDateFormat("EEEE")
return timeFormatter.format(Date(dt * 1000L))
}
}
}
| 3b9f9460807d8941902e8039c5e3d160c7bd27d1 | [
"Markdown",
"Java",
"Kotlin",
"Gradle"
] | 9 | Kotlin | anamikapainuly/RetrofitAPI-Nav-Graph-Anamika-Test | 143cc3046cc5caa2de8829104f1cd2cd3ef98b93 | beecfcf61f698e7bf9e230df6c565920866ff9f7 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
[Serializable]
public class Review
{
public int ID { get; set; }
public string ReviewBody { get; set; }
public string ReviewByUser { get; set; }
public int Rating { get; set; }
public IList<RouteReview> RouteReviews { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class RouteReview
{
public int ID { get; set; }
public int RouteID { get; set; }
public Route Route { get; set; }
public int ReviewID { get; set; }
public Review Review { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
[Serializable]
public class Route
{
public int ID { get; set; }
public string RouteName { get; set; }
public string Origin { get; set; }
public string Waypoints { get; set; }
public string Destination { get; set; }
public string CreatedByUser { get; set; }
public string BriefDescription { get; set; }
public IList<UserRoute> UserRoutes { get; set; }
public IList<RouteReview> RouteReviews { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class FriendRequest
{
public int ID { get; set; }
public int RequestingUserID { get; set; }
public string RequestingUserScreenName { get; set; }
public int RequestedUserID { get; set; }
public string RequestedUserScreenName { get; set; }
public DateTime CreationTime { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Message
{
public int ID { get; set; }
public DateTime CreationTime { get; set; }
public string Body { get; set; }
public int ReceiverID { get; set; }
public string ReceiverScreenName { get; set; }
public int SendersID { get; set; }
public string SenderScreenName { get; set; }
public bool Viewed { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class Friendships
{
public int ID { get; set; }
public string ScreenNameA { get; set; }
public string ScreenNameB { get; set; }
}
}
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace WebApplication1.Migrations
{
public partial class fs217 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UserIDA",
table: "Friendships");
migrationBuilder.DropColumn(
name: "UserIDB",
table: "Friendships");
migrationBuilder.AddColumn<string>(
name: "ScreenNameA",
table: "Friendships",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ScreenNameB",
table: "Friendships",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "ScreenNameA",
table: "Friendships");
migrationBuilder.DropColumn(
name: "ScreenNameB",
table: "Friendships");
migrationBuilder.AddColumn<int>(
name: "UserIDA",
table: "Friendships",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "UserIDB",
table: "Friendships",
nullable: false,
defaultValue: 0);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication1.Models
{
public class User
{
public int ID { get; set; }
public string ScreenName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string PasswordHash { get; set; }
public string HashCode { get; set; }
public DateTime CreationTime { get; set; }
public DateTime ModificationTime { get; set; }
public int TrailsBlazed { get; set; }
public int ReviewsMade { get; set; }
public IList<UserRoute> UserRoutes { get; set; }
}
}
| 6333b1b58092abf6943b0fae92e822692b3bc931 | [
"C#"
] | 8 | C# | jmlc101/JM.Capstone | abd5dc4d211aa133c402f5c3ef3cb5c27523016b | 7d7b76e35e8638a7c2ca5d8e6858627274863535 | |
refs/heads/master | <file_sep>define('main', [] , function(){
return{
common: function(){},
index: function(){
setTimeout(function(){alert("hello @world@")},3000);
}
};
});
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
render.py
changelog
2013-12-01[00:32:46]:created
2013-12-14[23:52:33]:define TokenRender
2013-12-17[12:13:55]:move removeCssDepsDeclaration out of class
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
from conf import C,log,BASE_DIR
import utils
import os
import re
import json
from timestamp import html_link,html_script,html_img,all_url,all as allt
from deps import DepsFinder
from replace import replace
from jinja2 import Template,Environment,FileSystemLoader,TemplateNotFound,TemplateSyntaxError
_template_dir = C('template_dir')
jinjaenv = Environment(loader = FileSystemLoader(utils.abspath(_template_dir), C('encoding') ), extensions = ["jinja2.ext.do"] , autoescape = True )
build_jinjaenv = Environment( loader = FileSystemLoader( os.path.join( os.getcwd() , C('build_dir'), _template_dir) , C('encoding') ))
mgr_jinjaenv = Environment( loader = FileSystemLoader( os.path.join(BASE_DIR,'tpl') , C('encoding') ))
def render_file(filename,data = None,noEnvironment = False,build = False):
'''
渲染文件
'''
if noEnvironment:
body = mgr_jinjaenv.get_template(filename)#Template(utils.readfile(filename))#这里应为绝对路径
else:
if build:
body = build_jinjaenv.get_template(filename)
else:
body = jinjaenv.get_template(filename)
return body.render(data or {})
def removeCssDepsDeclaration(html):
'''
移除HTML中对CSS的依赖声明
'''
return re.sub(r'<!\-\-[\s\S]*?@require[\s\S]*?\-\->','',html)
class TokenRender(object):
'''
'''
@classmethod
def __init__(self,token):
self.__token = utils.filterPath(token)
df = DepsFinder(token)
self.__deps = df.find()
self.__include_deps = df.findIncludes()
self.__html = None
@classmethod
def getData(self,including_deps = True):
data = {}
if C('disable_deps_search') or not including_deps:
deps = [self.__token+'.'+C('template_ext')]
else:
#复制
deps = self.__deps[0:]
deps.reverse()
deps.insert(len(deps),self.__token+".json")
deps.insert(0,"_ursa.json")
for dep in deps:
try:
json_filepath = utils.abspath(os.path.join(C('data_dir'),re.sub(r'\.%s$'%C('template_ext'),'.json',dep)))
content = utils.readfile(json_filepath)
content = re.sub('\/\*[\s\S]*?\*\/','',content)
json_data = json.loads(content)
data.update(json_data)
except Exception, e:
e#log.warn('[getdata]%s:%s'%(json_filepath,e))
return data
@classmethod
def render(self,build = False):
'''
查找数据文件依赖并渲染模板
'''
#remove '/'s at start
if self.__html is None:
data = self.getData()
multoken = self.__token.split('/')
data.update({'_token': self.__token.replace('/','_')})
data.update({'_folder':multoken[0]})
data.update({'_subtoken':multoken[1] if len(multoken)>1 else ""})
tpl_path = self.__token + "." + C('template_ext')
html = render_file( tpl_path,data,False,build)
if C('server_add_timestamp'):
#html = html_script(html)
#html = html_link(html)
#html = html_img(html)
#html = all_url(html)
html = allt(html)
html = replace(html)
if not build and not re.match(r'[\s\S]*?<html[\s\S]+?<body',html,re.I):
#sub template
css_deps = self.__getDepsCss(html)
for tpl in self.__include_deps:
css = os.path.join('.',C('static_dir'),C('css_dir'),re.sub(r"\.%s"%C('template_ext'),".css",tpl))
css_deps.append(css)
subparent = 'subparent.tpl'# os.path.join(BASE_DIR,"tpl",'subparent.tpl')
html = render_file(subparent,{'name': self.__token,'content': html,'required_css': css_deps},noEnvironment = True)
html = removeCssDepsDeclaration(html)
self.__html = html
return self.__html
@classmethod
def __getDepsCss(self,html):
'''
分析@require xxx.css,获取依赖
'''
ret = []
iters = re.finditer(r'@require\s+?([/\w\-]+?\.css)',html,re.I)
for it in reversed(list(iters)):
css = it.group(1)
css = utils.filterRelPath(css)
ret.append( os.path.join('.',C('static_dir'),C('css_dir'),css) )
return {}.fromkeys(ret).keys()
if __name__ == '__main__':
tr = TokenRender('index')
print tr.render()
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
handler.py
changelog
2013-11-30[22:32:36]:created
2013-12-11[10:51:16]:better error report
2013-12-16[17:16:32]:category of tpls
2013-12-25[15:17:46]:s function supported,showing static resource
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.2
@since 0.0.1
'''
import utils
import mimetypes
from urlparse import urlparse
import os
import sys
import subprocess
import re
import json
from conf import C,log,BASE_DIR
from render import TokenRender,render_file
from replace import replace
from timestamp import html_link,html_script,html_img,all_url
from jinja2 import TemplateNotFound,TemplateSyntaxError
import requests as R
def _token(path):
'''
去除后缀,取得相对于模板目录的相对无扩展名路径
'''
tpl_token = re.sub(r'\.(%s|%s|%s|%s)$'%(C('preview_ext'),'m','data',C('template_ext')),'',path)
tpl_token = utils.filterRelPath(tpl_token)
return tpl_token
def index(req,res):
'''
模板列表
'''
tpl_dir = C('template_dir')
tpl_ext = C('template_ext')
tpls = utils.FileSearcher(r'\.%s$'%tpl_ext,tpl_dir).search()
_tpls = []
_module_tpls = []
_common_tpls = []
for e in tpls:
e = re.sub(r'\.%s'%tpl_ext,'',e)
if C('ignore_parents') and e.endswith('parent'):
continue
#分类输出
if e.startswith(C('module_dir') + '/'):
_module_tpls.append(e)
elif e.startswith(C('common_dir') + '/'):
_common_tpls.append(e)
else:
_tpls.append(e);
index_path ='index.html'
html = render_file(index_path,{"tpls":_tpls,"module_tpls":_module_tpls,"common_tpls":_common_tpls},noEnvironment = True)
res.send(html)
def help(req,res):
'''
加载帮助文件
'''
inner_path = 'help.html'
r = R.get('https://raw.github.com/yanni4night/ursa2/master/README.md')
html = render_file(inner_path,{'content':r.content},noEnvironment = True)
res.send(html)
def rs(req,res):
'''
静态资源列表
'''
static_dir = C('static_dir')
img_dir = os.path.join(static_dir,C('img_dir'))
js_dir = os.path.join(static_dir,C('js_dir'))
css_dir = os.path.join(static_dir,C('css_dir'))
imgs = utils.FileSearcher(r'\.(png|bmp|gif|jpe?g|ico)$',img_dir).search()
csses = utils.FileSearcher(r'\.(css|less)$',css_dir).search()
jses = utils.FileSearcher(r'\.js$',js_dir).search()
static_path = 'static.html'#os.path.join(BASE_DIR,'tpl','static.html')
html = render_file(static_path,{"img":imgs,"css":csses,"js":jses,"img_dir":img_dir,"css_dir":css_dir,"js_dir":js_dir},noEnvironment = True)
res.send(html)
def tpl(req,res):
'''
模板
'''
tpl_token = _token(req.path)
try:
tr =TokenRender(tpl_token)
return res.send(tr.render())
except TemplateNotFound as e:
return res.send(code = 500,content = 'Template %s not found' % (str(e) ,))
except TemplateSyntaxError as e:
return res.send(code = 500,content = 'Template %s:%d Syntax Error:%s' % (e.filename,e.lineno,e.message))
except Exception, e:
return res.send(code = 500,content = '%s'%e)
def data(req,res):
'''
获取对应模板的依赖数据组合
'''
tpl_token = _token(req.path)
tr = TokenRender(tpl_token)
data = tr.getData()
return res.send(json.dumps(data),headers = {'Content-Type':'application/json'})
def m(req,res):
'''
输出对应json数据
'''
tpl_token = _token(req.path)
data = ''
json_path = os.path.join(C('data_dir'),tpl_token+".json")
try:
data = utils.readfile(json_path)
except Exception, e:
log.error('[m]%s:%s'%(json_path,e))
mgr_path = 'mgr.html'# os.path.join(BASE_DIR,'tpl','mgr.html')
html = render_file(mgr_path,{"name":tpl_token,"data":data},noEnvironment = True)
res.send(html)
def so(req,res):
'''
保存json数据
todo
'''
tpl_token = _token(req.param('tpl'))
json_str = req.param('data')
try:
json_obj = json.loads(json_str)
json_path = os.path.join(C('data_dir'),tpl_token+".json")
utils.writeJSON(json_path,json_obj)
res.redirect('/%s.%s'%(tpl_token,C('preview_ext')))
except ValueError, e:
res.send(render_file('json.html',{'json' : json_str,'tpl_token' : tpl_token} , noEnvironment = True))
except Exception,e:
log.error('[so]%s'%e)
res.redirect('/%s.%s'%(tpl_token,C('preview_ext')))
def static(req,res):
'''
static resource
'''
req.path = utils.filterRelPath(req.path)
o = urlparse(req.path)
#取得绝对路径
fd = utils.abspath(o.path)
if fd.endswith('.css'):
less = re.sub(r"\.css",".less",fd)
if os.path.exists(less) and os.path.isfile(less):
try:
subprocess.call('lessc %s %s'%(less,fd),shell=True)
except Exception, e:
log.error('[less]%s'%e)
if os.path.isfile(fd):
mime = mimetypes.guess_type(fd,False)
content_type = mime[0] or 'text/plain'#default text
try:
headers = {}
#todo custom defined
if not utils.isBinary(fd):
content = utils.readfile(fd)
content = replace(content)
if C('server_add_timestamp') :
if content_type.find('css') >= 0:
base_dir = os.path.dirname(fd)
content = all_url(content,base_dir)
elif content_type.find('html') >= 0:
content = html_link(content)
content = html_script(content)
content = html_img(content)
content = all_url(content)
#http encoding header
headers['Content-Encoding'] = C('encoding')
headers['Cache-Control'] = 'nocache'
else:
#binary files
content = utils.readfile(fd,'rb')
headers['Content-Type'] = content_type
res.send(content = content,headers = headers)
except Exception, e:
res.send(code = 500,content = '%s'%e)
log.error("[static]%s"%e)
else:
if os.path.exists(fd):
res.send(code = 403,content = 'Access %s is forbidden'%req.path)
else:
res.send(code = 404,content = "%s not found"%req.path)<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
exception.py
changelog
2013-12-07[12:46:58]:created
custom defined exceptions and errors
@info yinyong,osx-x64,UTF-8,192.168.1.104,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
class ConfigurationError(Exception):
'''
ConfigurationError
'''
@classmethod
def __init__(self, msg):
self.msg=msg
@classmethod
def __str__(self):
return self.msg
class DirectoryError(Exception):
'''
DirectoryError
'''
@classmethod
def __init__(self,msg):
self.msg=msg
@classmethod
def __str__(self):
return self.msg
class FileSizeOverflowError(Exception):
'''
File size overflow Error
'''
@classmethod
def __init__(self,msg):
self.msg=msg
@classmethod
def __str__(self):
return self.msg
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
main.py
changelog
2013-11-30[00:21:29]:created
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/bin
@author yinyong<EMAIL>
@version 0.0.1
@since 0.0.1
'''
from docopt import docopt
from __init__ import __version__ as version
import sys
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
def copyfiles(sourceDir, targetDir):
'''
拷贝文件和目录
'''
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir, file)
targetFile = os.path.join(targetDir, file)
if os.path.isfile(sourceFile):
if not os.path.exists(targetDir):
os.makedirs(targetDir)
if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
open(targetFile, "wb").write(open(sourceFile, "rb").read())
if os.path.isdir(sourceFile):
copyfiles(sourceFile, targetFile)
def run():
'''
ursa2
Usage:
ursa2 init
ursa2 start [<port>]
ursa2 build [<target>] [-chf]
ursa2 help
ursa2 (-v | --version)
Options:
-c --compress compress js and css when building.
-h --html creating HTML when building.
-v --version show version.
-f --force force compile
'''
argv=docopt(run.__doc__,version=version)
if argv.get('init'):
if os.listdir( '.' ):
print "It's not an empty folder.\nContinue may override your existing files.\nStill continue initializing?"
iscontinue = raw_input('(y/n):').lower() in ['y' , 'yes','ok' ]
if not iscontinue:
print ('Initializing canceled.')
sys.exit(1)
print ('Initializing project...')
copyfiles(os.path.join(BASE_DIR,'assets','clo'),'.')
print ('Initializing successfully.Usage:')
print (' start serer:ursa2 start')
print (' build project:ursa2 build')
elif argv.get('start'):
server=__import__('server')
server.run(argv.get('<port>'))
elif argv.get('build'):
build=__import__('build')
builder=build.UrsaBuilder(argv.get('--compress'),argv.get('--html'),argv.get('<target>'),argv.get('--force'))
builder.build();
elif argv.get('help'):
print 'https://github.com/yanni4night/ursa2/wiki'
if __name__=='__main__':
run();<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
timestamp.py
changelog
2013-12-01[15:59:50]:created
2013-12-10[11:17:11]:clean
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
from conf import C,log
import re
import utils
import os
from replace import replace
from urlparse import urlparse,parse_qs
def _addtimestamp(content,reg,base_dir,force_abspath=False):
'''
以base_dir为基础目录,在content中搜寻匹配reg的URL并尝试追加时间戳
reg:匹配URL的正则,其中\3为URL
force_abspath:强制路径为绝对路径,即以WD为base_dir
'''
iters=re.finditer(reg,content,re.I|re.M)
t=C('timestamp_name')
for it in reversed(list(iters)):
start = content[0:it.start(1)]
url = it.group(3)
end = content[it.end(1):]
local_url = replace(url)
parsed_url = urlparse(local_url)
parsed_query = parse_qs(parsed_url.query)
#已经有时间戳的不再添加
#带协议的不再添加
if not local_url or not parsed_url.path:
continue
#具有模板语法的不予添加
elif parsed_url.path.find('{{') >=0 or parsed_url.path.find('{%') >= 0:
log.warn('twig syntax found in %s'%parsed_url.path)
continue
elif re.match(r'^\s*(about:|data:|#)',local_url):
log.warn('%s is an invalid url'%local_url)
continue
elif parsed_query.get(t) is not None:
log.warn("%s has a timestamp"%local_url)
continue
elif parsed_url.scheme or local_url.startswith('//'):
log.warn("%s has a scheme"%local_url)
continue
if os.path.isabs(parsed_url.path) or force_abspath:
#绝对路径,则以当前工程根目录为root
timestamp = utils.get_file_timestamp(utils.abspath(base_dir + parsed_url.path))
else:
#相对目录,则此当前文件目录为root
#应该仅在CSS内使用相对路径
timestamp = utils.get_file_timestamp(os.path.join(base_dir,parsed_url.path))
#计算不到时间戳则忽略
if not timestamp:
continue
parsed_url = urlparse(url)
new_query = parsed_url.query
if '' == new_query:
new_query = t+"="+timestamp
else:
new_query+='&%s=%s'%(t,timestamp)
if '' == parsed_url.fragment:
new_fragment = ''
else:
new_fragment = '#'+parsed_url.fragment
if not parsed_url.scheme:
new_scheme = ''
else:
new_scheme = parsed_url.scheme+"://"
new_url = new_scheme + parsed_url.netloc + parsed_url.path + '?' + new_query + new_fragment
content = start + (it.group(2) or '') + new_url + (it.group(2) or '') + end
return content
def html_link(content,base_dir=".",force_abspath = True):
'''
向<html>中<link>元素添加时间戳
'''
return _addtimestamp(content,r'<link.* href=(([\'"])(.*?\.css.*?)\2)',base_dir,force_abspath)
def html_script(content,base_dir=".",force_abspath = True):
'''
向<html>中<script>元素添加时间戳
'''
return _addtimestamp(content,r'<script.* src=(([\'"])(.*?\.js.*?)\2)',base_dir,force_abspath)
def html_img(content,base_dir='.',force_abspath = True):
'''
向<html>中<img>元素添加时间戳
'''
return _addtimestamp(content,r'<img.* src=(([\'"])(.*?\.(png|gif|jpe?g|bmp|ico).*?)\2)',base_dir,force_abspath)
def all_url(content,base_dir="."):
'''
向HTML、CSS中的url()添加时间戳
'''
return _addtimestamp(content,r'url\((([\'"])?([\S]+?)\2?)\)',base_dir)
def all(content,base_dir='.',force_abspath=True):
'''
添加所有类型的时间戳
'''
content=html_link(content,base_dir,force_abspath)
content=html_script(content,base_dir,force_abspath)
content=html_img(content,base_dir,force_abspath)
content=all_url(content,base_dir)
return content
if __name__ == '__main__':
sample="url(/static/css/font.css?x={{key}}&ty=09&bn==56)"
print sample
print all_url(sample)<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
proxy.py
changelog
2013-12-11[17:23:52]:created
@info yinyong,osx-x64,UTF-8,10.129.164.77,py,/Volumes/yinyong/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
import requests as R
from urlparse import urlparse
import utils
import re
from conf import C,log
def get_proxy_url(req_path,reg,target):
'''
'''
if not utils.isStr(reg) or not utils.isStr(target):
log.warn('%s:%s is an illegal proxy pair'%(reg,target))
return None
if reg.startswith('regex:'):
#正则匹配
reg = reg[6:]
if re.match(r'%s'%reg,req_path):
target_path = re.sub(r'%s'%reg,r'%s'%target,req_path)
return target_path
elif reg.startswith('exact:'):
#精确匹配
reg = reg[6:]
if reg == req_path:
target_path = target
return target_path
else :
#变量输出
s = re.search('\$\{(.+)\}' , target)
target_path= target
if s:
name = s.group(1)
pattern = re.sub( '\{.+\}' , '(.+)' , reg )
m = re.match(pattern, req_path )
if m:
path = m.group(1)
target_path = target_path.replace( '${'+name+'}' , path )
return target_path
return None
def proxy(target_url,req,res):
'''
'''
if not target_url:
return res.send(code = 500,content = 'Empty url not supported')
#二进制资源直接重定向
parsed_url = urlparse(target_url)
if utils.isBinary(parsed_url.path,strict = True):
return res.redirect(target_url)
if 'GET' == req.method:
request = R.get
elif 'POST' == req.method:
request = R.post
try:
#通知远端服务器不要压缩
if req.headers.get('accept-encoding'):
del req.headers['accept-encoding']
if req.headers.get('host'):
del req.headers['host']
log.info('[proxy]requesting %s'%target_url)
r = request(target_url,headers = req.headers)
#本地服务器覆写Date和Server
if r.headers.get('date'):
del r.headers['date']
if r.headers.get('server'):
del r.headers['server']
if r.headers.get('transfer-encoding'):
del r.headers['transfer-encoding']
log.info('[proxy] status=%d'%r.status_code)
return res.send(code = r.status_code,content = r.content or '',headers = r.headers)
except Exception, e:
log.error('[proxy]%s'%e)
return res.send(code = 500,content = '%s'%e)
def __test_content_type(url = False):
r = R.get(url or 'http://www.sogou.com/web?query=k',headers={})
print r.content#.get('Content-Type')
def __test_get_proxy_url():
#print get_proxy_url('/search/xxx/1','regex:/search/(.+?)/(\d)','if you see this (\\1)(\\2)')
#print get_proxy_url('/search/xxx/2','exact:/search/xxx/2','if you see this')
print get_proxy_url('/search/xxx/3/2','/search/xxx/{m/d}','if you see this (${m/d})')
if __name__ == '__main__':
__test_content_type()
__test_content_type('http://www.sogou.com')<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
replace.py
changelog
2013-12-01[11:42:20]:created
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
from conf import C,log
import re
import utils
range_item=0
def replace(content,target=None):
'''
替换@@变量
'''
TM_TOKEN = '@tm:(.+?)@'
DATE_TOKEN = '@date@';
COMMON_TOKEN = r'@([\w\-\/\\]+?)@'
iters = re.finditer( TM_TOKEN , content )
for i in reversed(list(iters)):
file_path = i.group(1)
if file_path.startswith('/'):
file_path=file_path[1:]
file_path=utils.abspath(file_path)
content = content[0:i.start(0)] + utils.get_file_timestamp(file_path) + content[i.end(0):]
iters = re.finditer( DATE_TOKEN , content )
for i in reversed(list(iters)):
content = content[0:i.start(0)] + utils.getDate() + content[i.end(0):]
iters = re.finditer( COMMON_TOKEN , content )
for i in reversed(list(iters)):
name = i.group(1)
value = C(name,target)
if value is not None:
if utils.isStr(value) and value.find('{num}') != -1:
num = int(C('num',target))
num = range(num+1)
substr100 = content[i.end(0):i.end(0)+100]#what
istimestamp = substr100.find('%s='%C('timestamp_name'))
if istimestamp != -1:#has timestamp
try:
tm = int(substr100[istimestamp+2:istimestamp+3])
except ValueError:
continue
if tm >= len(num):
tm = tm - len(num)
value = value.replace( '{num}' , str(tm) )
else:
global range_item
value = value.replace( '{num}' , str(num[range_item]) )
range_item = range_item + 1
if range_item >= len(num):
range_item = 0
content = content[0:i.start(0)] + str(value) + content[i.end(0):]
return content<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
server.py
changelog
2013-11-30[17:37:42]:created
2013-12-11[10:22:12]:https supported
2013-12-25[15:16:44]:static /s supported
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.2
@since 0.0.1
@todo https support,proxy support
'''
from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler
from http import Request,Response
from route import Route
from conf import C,log,BASE_DIR
import utils
import ssl
import os
import socket
from OpenSSL import SSL
from SocketServer import BaseServer
from handler import static,index,tpl,so,m,data,rs,help
ursa_router = Route()
ursa_router.get(r'^/$' , index)
ursa_router.get(r'^/rs$' , rs)
ursa_router.get(r'^/help$' , help)
ursa_router.get(r'\.%s$'%C('preview_ext') , tpl)
ursa_router.post(r'\.so$' , so)
ursa_router.get(r'\.m$' , m)
ursa_router.get(r'\.data$' , data)
ursa_router.get(r'^/.+' , static)
class UrsaHTTPRequestHandler(BaseHTTPRequestHandler):
'''
HTTP请求处理器
'''
def do_GET(self):
'''
处理GET请求
'''
ursa_router.distribute_request(self)
def do_POST(self):
'''
todo:处理POST请求
'''
ursa_router.distribute_request(self)
@classmethod
def version_string(self):
'''
服务器名字
'''
return 'Ursa2'
@classmethod
def log_date_time_string(self):
'''
服务器日志日期格式
'''
return utils.getDate(fmt="%Y/%m/%d %H:%M:%S")
def log_request(self , code , message=''):
'''
服务器日志输出
'''
if C('log_http_request'):
return BaseHTTPRequestHandler.log_request(self,code,message)
else:
return ''
def setup(self):
'''
for https
'''
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
class SecureHTTPServer(HTTPServer):
'''
HTTPS服务器,来自互联网
'''
def __init__(self, server_address, HandlerClass):
BaseServer.__init__(self, server_address, HandlerClass)
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_privatekey_file( os.path.join(BASE_DIR,"assets","privatekey.pem"))
ctx.use_certificate_file( os.path.join(BASE_DIR,"assets","certificate.pem"))
self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
self.server_bind()
self.server_activate()
def get_local_ip():
'''
获取本机IP
'''
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('w3.org',80))
return s.getsockname()[0]
except Exception, e:
return '127.0.0.1'
finally:
try:
s.close()
except Exception, e:
e
def run(port=8000):
'''
服务器启动入口
'''
try:
port=int(port)
except Exception, e:
try:
port=int(C('server_port'))
except Exception, e:
port=8000
server_addr=('',port);
try:
if 'https' == C('protocol'):
httpd=SecureHTTPServer(server_addr,UrsaHTTPRequestHandler)
protocol = 'https'
else:
httpd=HTTPServer(server_addr,UrsaHTTPRequestHandler)
protocol = 'http'
print "Server listen on %s://%s:%d/" % (protocol,get_local_ip(), port)
httpd.serve_forever()
except (KeyboardInterrupt , SystemExit):
print "Shutting down.Goodbye!"
httpd.socket.close()
except socket.error,e:
log.error(e)
sys.exit(1)
if __name__ == '__main__':
run()<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
http.py
changelog
2013-11-30[18:59:59]:created
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
from urlparse import urlparse,parse_qs
from conf import log,C
import utils
import re
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Request(object):
'''
HTTP请求
'''
@classmethod
def __init__(self,http_req_handler):
'''
构造Request对象,
拷贝HTTPRequestHandler的相关值
'''
self.path=urlparse(http_req_handler.path).path
self.method=http_req_handler.command
self.client_port=http_req_handler.client_address[1]
self.client_host=http_req_handler.client_address[0]
self.headers=http_req_handler.headers
if 'GET' == self.method:
#get请求解析url
o=urlparse(http_req_handler.path)
q=parse_qs(o.query)
self.body=q
elif 'POST' == self.method:
#todo,post复杂解析
content_len=int(http_req_handler.headers.get('Content-Length'))
content=http_req_handler.rfile.read(content_len)
q=parse_qs(content)
self.body=q
@classmethod
def param(self,key):
'''
获取参数
'''
o=self.body.get(key)
if o is None:
return None
if len(o) == 1:
return o[0]
else:
return o
class Response(object):
'''
HTTP响应
'''
@classmethod
def __init__(self,http_req_handler):
'''
'''
self.http_req_handler=http_req_handler
@classmethod
def redirect(self,location,code=302):
'''
302重定向
'''
self.http_req_handler.send_response(302)
self.http_req_handler.send_header('Location',location)
self.http_req_handler.end_headers()
self.http_req_handler.wfile.close()
@classmethod
def send(self,content=None,content_len=None,code=200,headers={}):
'''
'''
self.http_req_handler.send_response(code)
headers['connection'] = 'close'
for k in headers.keys():
self.http_req_handler.send_header(k,headers.get(k))
if not headers.get('Content-Type'):
headers['Content-Type']='text/html;charset='+C('encoding')
if content is not None and not re.match(utils.BINARY_CONTENT_TYPE_KEYWORDS,headers['Content-Type'],re.IGNORECASE):
try:
content=unicode(content).encode(C('encoding'),'ignore')
except Exception, e:
log.error('[send]%s'%(e))
#填充Content-Length头
if headers.get('Content-Length') is None and content_len is None and content is not None:
content_len=len(content)
if content_len > 0:
self.http_req_handler.send_header('Content-Length',content_len)
self.http_req_handler.end_headers()
if content is not None:
self.http_req_handler.wfile.write(content)
self.http_req_handler.wfile.close()<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
build.py
changelog
2013-12-07[12:01:09]:created
2013-12-10[22:40:30]:add build time show
2013-12-15[01:04:04]:less supported
2013-12-24[21:04:45]:'ignore_parents' setting
@info yinyong,osx-x64,UTF-8,192.168.1.104,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.2
@since 0.0.1
'''
from conf import C,log,BASE_DIR
import logging
import shutil
import os
import re
import sys
import subprocess
import utils
import time
from render import TokenRender,removeCssDepsDeclaration
from exception import ConfigurationError,DirectoryError
from replace import replace
from timestamp import html_link,html_script,html_img,all_url,all as allt
RJS_PATH = os.path.join(BASE_DIR,'assets','r.js')
RPL_PATH = os.path.join(BASE_DIR,'assets','rpl.js')
#custom defined yuicompressor
__ycpath = C('yuicompressor')
YC_PATH = None
if __ycpath and utils.isStr( __ycpath ):
if not os.path.exists( __ycpath ):
log.warn('%s does not exist'%__ycpath )
elif not os.path.isfile( __ycpath ) or not __ycpath.endswith('.jar'):
log.warn('%s is not valid yuicompressor file')
else:
YC_PATH = __ycpath
if not YC_PATH:
YC_PATH = os.path.join(BASE_DIR,'assets','yuicompressor-2.4.8.jar')
class UrsaBuilder(object):
'''
build project:
copy and handle static resources
generate html with json data
'''
@classmethod
def __init__(self,compress,html,target = None,force = False):
'''
预先计算一些基础路径
'''
log.setLevel(logging.DEBUG)
self._force = force
self._compress = compress
self._generate_html = html
self._target = target
self._tpl_dir = C('template_dir')
self._build_dir = C('build_dir')
self._static_dir = C('static_dir')
self._js_dir = C('js_dir')
self._css_dir = C('css_dir')
self._compile_dir = C('compile_folder') or ''#copy and repalce
#check dunplicated
if os.path.relpath(self._build_dir,self._tpl_dir) == '.':
raise ConfigurationError('template_dir and build_dir are dumplicated')
elif os.path.relpath(self._build_dir,self._static_dir) == '.':
raise ConfigurationError('template_dir and static_dir are dumplicated')
elif self._compile_dir and os.path.relpath(self._compile_dir,self._static_dir) == '.':
raise ConfigurationError('compile_dir and static_dir are dunplicated')
elif self._compile_dir and os.path.relpath(self._compile_dir,self._build_dir) == '.':
raise ConfigurationError('compile_dir and build_dir are dunplicated')
elif self._compile_dir and os.path.relpath(self._compile_dir,self._tpl_dir) == '.':
raise ConfigurationError('compile_dir and tpl_dir are dunplicated')
self._build_static_dir = os.path.join(self._build_dir,self._static_dir)
self._build_css_dir = os.path.join(self._build_static_dir,self._css_dir,C('css_folder') or '')
self._build_js_dir = os.path.join(self._build_static_dir,self._js_dir,C('js_folder') or '')
self._build_tpl_dir = os.path.join(self._build_dir,self._tpl_dir)
if self._compile_dir:
self._build_compile_dir = os.path.join(self._build_dir,self._compile_dir)
self._build_html_dir = os.path.join(self._build_dir,C('html_dir'))
@classmethod
def build(self):
'''
do build
'''
tmbegin = time.time()
self._check();
log.info ('copying directories')
self._dir();
log.info('handling less...');
self._less();
log.info ('handling css...')
self._css();
log.info ('handling javascript...')
self._js();
log.info ('handling template...')
self._tpl();
if self._generate_html:
log.info ('handling html...')
self._html();
log.info ('replacing all token')
self._replace();
log.info ('Time cost %s s.' % (time.time()-tmbegin) )
@classmethod
def _check(self):
'''
检查是否具备一个ursa2工程必备的文件和目录
'''
require_dirs = [self._tpl_dir,self._static_dir];
for d in require_dirs:
if not os.path.exists(d):
raise DirectoryError('Ursas project requires %s directory'%d)
@classmethod
def _dir(self):
'''
handle build dir
'''
shutil.rmtree(self._build_dir,True)
os.mkdir(self._build_dir);
shutil.copytree(self._static_dir,self._build_static_dir)
shutil.copytree(self._tpl_dir,self._build_tpl_dir)
if self._compile_dir:
shutil.copytree(self._compile_dir,self._build_compile_dir)
@classmethod
def _less(self):
'''
handle less files to css
'''
all_less_files = utils.FileSearcher(r'\.less$',self._build_css_dir,relative = False).search()
for less in all_less_files:
try:
subprocess.call('lessc %s %s'%(less,re.sub(r"\.less",".css",less)),shell = True)
os.remove(less)
except Exception,e:
if self._force:
log.error('[less]%s'%e)
else:
raise e
@classmethod
def _css(self):
'''
handle css
r.js会对不同目录下CSS合并时的URL进行修正,因而对于@something@开头的路径会被认为是相对路径,
产生修正错误,解决方案是先对所有CSS文件进行变量替换,时间戳添加,再由r.js合并。这会降低处理速
度但可以解决该问题。
考虑到速度,此过程仅支持在build时进行,开发服务器访问时不能使用。
所有静态资源路径都应该使用绝对路径,避免在CSS中引用相对路径的图像资源。
'''
#搜索所有CSS文件
all_css_files = utils.FileSearcher(r'\.css$',self._build_css_dir,relative = False).search()
#替换和加时间戳
for dst in all_css_files:
try:
content = utils.readfile(dst)
content = all_url(content,os.path.dirname(dst))
content = replace(content,self._target)
utils.writefile(dst,content)
except Exception,e:
if self._force:
log.error('[css]%s'%e)
else:
raise e
#仅对指定的CSS进行r.js合并
css_modules = C('require_css_modules')
if not utils.isList(css_modules):
css_modules = ['main']
for css in css_modules:
try:
if not utils.isStr(css):
continue;
css = re.sub(r'\/*','',css)
if not css.endswith('.css'):
css += '.css'
css_realpath = os.path.join(self._build_css_dir,css)
self.build_css(css_realpath,css_realpath)
continue
except Exception,e:
if self._force:
log.error('[less]%s'%e)
else:
raise e
@classmethod
def build_css(self,src,dst):
'''
handle one css src to dst
合并和按需压缩
'''
subprocess.call('node %s -o cssIn=%s out=%s'%(RJS_PATH,src,dst),shell = True)
if self._compress:
subprocess.call( 'java -jar ' + YC_PATH + ' --type css --charset ' + C('encoding') + ' ' + dst + ' -o ' + dst , shell = True )
@classmethod
def _js(self):
'''
handle js
JS文件不同于CSS,其本身不能引用其它相对路径的静态资源,因此可以实现
先合并再替换、加时间戳,无需预先处理所有js文件。
'''
js_modules = C('require_js_modules')
if not utils.isList(js_modules):
js_modules = C('require_modules')
if not utils.isList(js_modules):
js_modules = ['main']
for js in js_modules:
try:
if not utils.isStr(js):
continue;
js = re.sub(r'^\/+','',js)
if not js.endswith('.js'):
js += '.js'
js_realpath = os.path.join(self._build_js_dir,js)
self.build_js(js_realpath,js_realpath,self._build_js_dir)
except Exception,e:
if self._force:
log.error('[less]%s'%e)
else:
raise e
@classmethod
def build_js(self,src,dst,base_dir):
'''
handle one js src to dst
合并、替换、加时间戳并按需压缩。
'''
js = os.path.relpath(src,base_dir)
subprocess.call( 'node ' + RJS_PATH +' -o name=' + js[0:-3] + ' out='+ dst + ' optimize=none baseUrl='\
+ base_dir , shell = True)
#repalce
content = utils.readfile(dst)
content = replace(content,self._target)
utils.writefile(dst,content)
if C('js_ascii_only'):
subprocess.call( 'node ' + RPL_PATH +' '+dst+' '+dst,shell = True)
if self._compress:
subprocess.call( 'java -jar ' + YC_PATH + ' --type js --charset ' + C('encoding') + ' ' + dst + ' -o ' + dst , shell = True )
@classmethod
def _tpl(self):
'''
handle tempaltes
模板仅需加时间戳和变量替换。
这里需要加入额外的{compile_dir}文件夹下的文本文件。
'''
fs = utils.FileSearcher(r'\.%s$'%C('template_ext'),self._build_tpl_dir,relative = False)
tpls = fs.search()
if self._compile_dir:
nfs = utils.FileSearcher(r'.+',self._build_compile_dir,relative = False)
compile_files = nfs.search()
for f in compile_files:
if not utils.isBinary(f):
tpls.insert(0,f)
for tpl in tpls:
try:
content = utils.readfile(tpl)
#模板的静态资源相对目录应该写死为cwd,即资源路径应该始终是绝对路径
content = allt(content,self._build_dir,force_abspath = False)
content = replace(content,self._target)
content = removeCssDepsDeclaration(content)
utils.writefile(tpl,content)
except Exception,e:
if self._force:
log.error('[tpl]%s'%e)
else:
raise e
@classmethod
def _replace(self):
'''
替换所有文本的变量
'''
files = utils.FileSearcher(r'.+',self._build_dir).search()
for f in files:
f = os.path.join(self._build_dir,f)
if not utils.isBinary(f):
try:
content = utils.readfile(f)
content = replace(content,self._target)
utils.writefile(f,content)
except Exception,e:
if self._force:
log.error('[replace][%s]%s'%(f,e))
else:
e
@classmethod
def _html(self):
'''
generate html
HTML直接以输出好的模板文件做渲染。
由于数据原因个别子模板单独渲染会失败,这里用{html_force_output}变量
可以跳过这类模板。
TODO:考虑支持require_html_modules
'''
fs = utils.FileSearcher(r'\.%s$'%C('template_ext'),self._build_tpl_dir)
tpls = fs.search()
for tpl in tpls:
if C('ignore_parents') and tpl.endswith('parent.'+C('template_ext')):
continue
try:
tr = TokenRender(re.sub(r'\.%s$'%C('template_ext'),'',tpl))
html = tr.render( build = True)
target_dir= os.path.join(self._build_html_dir,os.path.dirname(tpl))
if not os.path.exists(target_dir):
os.makedirs(target_dir)
dst_file = re.sub(r'\.%s$'%C('template_ext'),'.html',os.path.join(self._build_html_dir,tpl))
utils.writefile(dst_file,html)
except Exception,e:
if not C('html_force_output') and not self._force:
raise e
else:
log.error(e)
if __name__ == '__main__':
builder = UrsaBuilder(True,True,'online')
builder._replace()<file_sep>define('main', ["text!./tpl/list.tpl"], function(tpl) {
!window.console && (
window.console = {
log: function() {},
debug: function() {},
error: function() {},
clear: function() {}
}
);
return {
common: function() {}
};
});<file_sep>'''
log.py
changelog
2013-12-11[10:19:52]:copyright
This is from the Internet.
@info yinyong,osx-x64,Undefined,10.129.164.77,py,/Volumes/yinyong/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
import logging
import time
import logging.handlers
try:
import curses
curses.setupterm()
except:
curses = None
#COLOR_BLACK 0
#COLOR_RED 1
#COLOR_GREEN 2
#COLOR_YELLOW 3
#COLOR_BLUE 4
#COLOR_MAGENTA 5
#COLOR_CYAN 6
#COLOR_WHITE 7
class MessageFormatter(logging.Formatter):
def __init__(self, color, *args, **kwargs):
logging.Formatter.__init__(self, *args, **kwargs)
self._color = color
if color and curses:
fg_color = unicode(curses.tigetstr("setaf") or curses.tigetstr("setf") or "", "ascii")
self._colors = {
# GREEN
logging.DEBUG: unicode(curses.tparm(fg_color, 2), "ascii"),
# COLOR_CYAN
logging.INFO: unicode(curses.tparm(fg_color, 6), "ascii"),
# Yellow
logging.WARNING: unicode(curses.tparm(fg_color, 3), "ascii"),
# COLOR_MAGENTA
logging.ERROR: unicode(curses.tparm(fg_color, 5), "ascii"),
# Red
logging.FATAL: unicode(curses.tparm(fg_color, 1), "ascii"),
}
self._normal = unicode(curses.tigetstr("sgr0"), "ascii")
def format(self, record):
try:
record.message = record.getMessage()
except Exception, e:
record.message = "Bad message (%r): %r" % (e, record.__dict__)
record.asctime = time.strftime("%Y/%m/%d %H:%M:%S", self.converter(record.created))
prefix = '[%(levelname)-7s %(asctime)s] ' % record.__dict__
#if self._color and curses:
# prefix = (self._colors.get(record.levelno, self._normal) + prefix + self._normal)
formatted = prefix + record.message#unicode(record.message, 'utf-8', 'ignore')
if record.exc_info:
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
formatted = formatted.rstrip() + "\n" + record.exc_text
if self._color and curses:
formatted = (self._colors.get(record.levelno, self._normal) + formatted + self._normal)
return formatted.replace("\n", "\n ")
class GMessageLog(object):
def __init__(self):
self._LEVE = {1:logging.INFO, 2:logging.WARNING, 3:logging.ERROR, 4:logging.DEBUG, 5:logging.FATAL}
self.loger = logging.getLogger()
self.init()
def init(self):
handler = logging.StreamHandler()
handler.setFormatter(MessageFormatter(color=True))
self.loger.addHandler(handler)
def message(self, msg, leve=1):
if leve == 1: self.loger.info(msg)
elif leve == 2: self.loger.warning(msg)
elif leve == 3: self.loger.error(msg)
elif leve == 4: self.loger.debug(msg)
elif leve == 5: self.loger.fatal(msg)
def setLevel(self,level):
self.loger.setLevel(level)
def info(self,msg):
self.message(msg,1)
def warn(self,msg):
self.message(msg,2)
def debug(self,msg):
self.message(msg,4)
def error(self,msg):
self.message(msg,3)
def fatal(self,msg):
self.message(msg,5)
if __name__ == '__main__':
log=GMessageLog()
log.setLevel(logging.FATAL)
log.fatal("hello word")<file_sep>Ursa2
=====
Enhanced version of [ursa](https://github.com/sogou-ufo/ursa).
ursa2 supports [JSON Auto Combining](https://github.com/yanni4night/ursa2/wiki/JSON-Auto-Combining) ,
[Sub Tpl Preview](https://github.com/yanni4night/ursa2/wiki/Sub-Tpl-Preview)
and more detail features,such as, supporting _url()_ in sub directory of css,
which would bring bugs in previous,required data output in _http://origin/tpl.data_ url path,etc.
Feature
=====
- Local HTTP/HTTPS server
- Custom variables replace
- Jinja2/Twig like template engine
- Web data simulation
- JSON data auto combining
- JS/CSS merge&optimize
- LESS auto translation
- GET/POST(quirk) proxy
- Intelligent timestamp
Install
=====
Checkout from [GitHub](https://github.com/yanni4night/ursa2) and run :
$ python setup.py install
or use Python Package Index:
$ pip install ursa2
Super permission may be required.
Usage
=====
###initialize project
$ ursa2 init
###start server
$ ursa2 start [port]
###view template list
open browser to http://[hostname]:[port]/
###view static resource list
open browser to http://[hostname]:[port]/rs
###build project
$ ursa2 build [target][--compress][--html]
Dependencies
=====
- Unix/Linux/OS X
- Java 1.5+ (for yuicompressor)
- Python 2.6+ (3.x not supported)
- [node](https://github.com/joyent/node) (for less)
- [less](https://github.com/less/less.js)
- [docopt](https://github.com/docopt/docopt) (for log)
- [jinja2](https://github.com/mitsuhiko/jinja2)
- [requests](https://github.com/kennethreitz/requests) (for proxy)
Documents
=====
- [Manifest.json](https://github.com/yanni4night/ursa2/wiki/manifest.json)
- [Ursa2 Specification](https://github.com/yanni4night/ursa2/wiki/Ursa2-Specification)
- [JSON Auto Combining](https://github.com/yanni4night/ursa2/wiki/JSON-Auto-Combining)
- [Sub Tpl Preview](https://github.com/yanni4night/ursa2/wiki/Sub-Tpl-Preview)
- [Upgrade Notes](https://github.com/yanni4night/ursa2/wiki/Upgrade-notes)
Quirk
=====
- Server plugin not supported.
- Mobile project initializing not supported.
- POST data in proxy not supported.
- Relative path of static resource not supported(which you should never do).
LICENCE
=====
The MIT License (MIT)
Copyright (c) 2013 YinYong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
conf.py
changelog
2013-11-29[14 : 38 : 24] : created
2013-11-30[15 : 39 : 31] : finished
2013-12-01[19 : 23 : 17] : empty string supported
@info yinyong,osx-x64,UTF-8,10.129.164.117,py,/Users/yinyong/work/ursa2
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
import os
import json
import re
import logging
from log import GMessageLog
from datetime import datetime
import time
log = GMessageLog()
#配置缓存
_last_read_time = 0
_conf_cache = {}
#配置文件名称
_MANIFEST_FILE = 'manifest.json'
#配置文件的缓存间隔,读取文件后此事件内不再读取,单位s
_MIN_CACHE_INTERVAL = 1
#默认target,用于查找与环境相关的替换变量
_DEFAULT_TARGET = 'local'
#ursa2 Python源文件目录,用于查找assetss
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
#默认配置选项
_DEFAULT_ITEMS = {
'encoding' : ' utf-8',#项目编码,要求所有文件及输出均为此值
'protocol' : ' http',#使用协议,http或https
'server_add_timestamp' : False,#是否在本地调试服务器上追加时间戳
'disable_deps_search' : False,#禁止模拟数据搜索
'enable_proxy' : False,#代理开关
'server_port' : 8000,#http 或https端口
'log_level' : 'debug',#日志级别
'timestamp_name' : 't',#时间戳参数名
'log_http_request' : False,#是否打印HTTP请求日志
'template_dir' : 'template',#模板目录
'data_dir' : '_data',#JSON数据目录
'module_dir' : '_module',#under template_dir
'common_dir' : '_common',#under template_dir
'static_dir' : "static",#静态资源目录
'css_dir' : "css",#under static_dir
'css_folder' : '',#{css_dir}下的子目录
'js_dir' : "js",#under static_dir
'js_folder' : '',#{js_dir}下的子目录
'img_dir':'img',
'compile_folder' : None,#额外的目录,文本文件仅做替换和时间戳处理
'build_dir' : 'build',#生成目录
'html_dir' : 'html',#under build_dir
'template_ext' : 'tpl',#模板文件扩展名
'preview_ext' : 'ut',#实时访问渲染后模板的URL后缀
'num' : 10,#随机变量的最大值
'max_readable_filesize' : 1024*1024,#可读取的最大文件,文件过大会严重迟缓并占用内存
'yuicompressor' : None,#自定义yuicompressor的路径
'js_ascii_only' : False,#转义多字节为ASCII
'ignore_parents':True,#是否忽略对parent模板的处理
};
def _getConf():
'''
获取配置文件中整个json对象
'''
#缓存
global _last_read_time,_MIN_CACHE_INTERVAL,_conf_cache
now = time.time()
if now-_last_read_time<_MIN_CACHE_INTERVAL:
_last_read_time = now
return _conf_cache
ret = None
try:
conffile = os.path.join('.' , _MANIFEST_FILE)
if os.path.exists(conffile):
f = open(conffile)
body = f.read()
f.close()
#去除/**/注释,支持多行
#todo,字符串中应该予以保留
ret = json.loads(re.sub('\/\*[\s\S]*?\*\/','',body))
else:
log.error("%s is required" % _MANIFEST_FILE)
except Exception, e:
log.error("%s" % e)
_conf_cache = ret
return ret
def C(key,target = None,default_val = None):
'''
获取指定key的配置值,顺序为{target : {}},{local : {}},{},_DEFAULT_ITEMS,_default_val
'''
global _DEFAULT_ITEMS,_DEFAULT_TARGET
if type(key) not in (type(''),type(u'')):
return None
conf = _getConf()
if conf is None:
return _DEFAULT_ITEMS.get(key) or default_val
k = target
if target is None:
k = _DEFAULT_TARGET
dic = conf.get(k)
#target 或local存在
if type(dic) == type({}):
if dic.get(key) is not None:
return dic.get(key)
if conf.get(key) is not None:
return conf.get(key)
else:
return _DEFAULT_ITEMS.get(key) or default_val
#日志级别设置
__illegal_log_levels = {'info' : logging.INFO,'debug' : logging.DEBUG,'warn' : logging.WARNING,'error' : logging.ERROR,'critical' : logging.CRITICAL}
__log_level = C('log_level')
if __illegal_log_levels.get(__log_level) is not None:
log.setLevel(__illegal_log_levels.get(__log_level))
else:
log.setLevel(__illegal_log_levels.get('error'))
if __name__ == '__main__':
print C('template_dir');
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
utils.py
changelog
2013-11-30[14:36:11]:created
2013-12-22[21:14:45]:add isBinary function
常用工具
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.2
@since 0.0.1
'''
import time
import os
import json
import re
import hashlib
import codecs
import mimetypes
from conf import C,log
from exception import FileSizeOverflowError
#根据MIME来判断是二进制文件的正则表达式
BINARY_CONTENT_TYPE_KEYWORDS=r'(image|video|flash|audio|powerpoint|msword|octet\-stream)'
mimetypes.init()
def isBinary(fname , strict=False):
'''
判断文件是否是二进制文件
'''
mime = mimetypes.guess_type(fname,False)
content_type = mime[0]
if not content_type and strict:
return False
else:
content_type = content_type or 'application/octet-stream'
return True if re.search(BINARY_CONTENT_TYPE_KEYWORDS,content_type,re.I) else False
def isInt(v):
'''
type int
'''
return type(v) == type(1)
def isStr(s):
'''
type string
'''
return type(s) in (type(u''),type(''))
def isDict(d):
'''
type dict
'''
return type(d) == type({})
def isList(d):
'''
type list
'''
return type(d) == type([])
def isTuple(t):
'''
type tuple
'''
return type(t) == type(())
def abspath(path):
'''
取得WD下文件或目录的绝对路径
path:WD下文件或目录,会被强转成相对路径
'''
if not isStr(path):
raise TypeError('path must be a string')
path = filterRelPath(path)
return os.path.abspath(os.path.join(os.getcwd(),path))
def readfile(filename , mode='r'):
'''
默认以文本方式读取整个文件
'''
try:
if os.path.getsize(filename) > C('max_readable_filesize'):
raise FileSizeOverflowError('%s size overflow %d'%(filename,C('max_readable_filesize')))
if 'b' in mode:#Binary file
f = open( filename , mode )
else:
f = codecs.open(filename , mode ,C('encoding'))
body = f.read()
f.close()
return body
except Exception,e:
raise
def writefile(filename , content):
'''
write conent to a file
'''
try:
f = codecs.open(filename , 'w' , C('encoding'))
f.write(content)
f.close()
except:
log.error("write to %s failed" % filename)
raise
def writeJSON(filename,data):
'''
write file in JSON
'''
writefile(filename, json.dumps(data , sort_keys = True , indent = 4, separators = ( ',' , ': ')) )
def dorepeat(data):
'''
to be checked
'''
if type(data)==type({}):
for item in data.keys():
dorepeat(data[item])
if re.search( '@\d+$' , item ):
name = item.split('@')[0]
times = item.split('@')[1]
if int(times):
for time in range(int(times)):
if not data.get(name):
data[name] = []
data[name].append(data[item])
def md5toInt(md5):
"""将md5得到的字符串变化为6位数字传回。
基本算法是将得到的32位字符串切分成两部分,每部分按16进制得整数后除997,求得的余数相加
最终得到6位
Arguments:
- `md5`:
"""
md5 = [ md5[:16] , md5[16:] ]
result = ''
for item in md5:
num = str( int( item , 16 ) % 997 ).zfill(3)
result = result+num
return result
def get_file_timestamp(fpath):
'''
取得文件时间戳
fpath:绝对路径
'''
try:
f = readfile(fpath , 'rb')
m = hashlib.md5()
m.update(f)
md5 = md5toInt(m.hexdigest())
return md5
except Exception,e:
log.error('[TimeStamp]%s'%e)
return ''
def getDate(fmt = "%Y%m%d%H%M%S"):
'''
获取当前时间的格式化字符串
'''
return time.strftime(fmt or '', time.localtime())
def filterPath(path):
'''
路径中'//'变'/'
'''
return re.sub(r'/+','/',path)
def filterRelPath(path):
'''
同filterPath,但去除开头的'/'
'''
path = filterPath(path)
return re.sub(r'^/+','',path)
class FileSearcher(object):
'''
搜索一个目录下所有符合规定文件名的文件,
默认返回相对于初始目录的相对路径
'''
@classmethod
def __init__(self, pattern = r'.+', start_dir = '.',relative = True,traverse = True):
'''
pattern:文件名的正则过滤表达式;
start_dir:搜索目录;
relative:是否输出相对目录;
traverse:是否遍历目录搜索
'''
self.regexp = re.compile(pattern)
self.start_dir = start_dir
self.result = []
self.relative = relative
self.traverse = traverse
@classmethod
def search(self):
'''
执行搜索输出
'''
if os.path.isdir(self.start_dir):
os.path.walk(self.start_dir,self._visit,None)
else:
log.warn('you are walking a non-dir %s'%self.start_dir)
return self.result
@classmethod
def _visit(self,argv, directoryName,filesInDirectory):
'''
'''
for fname in filesInDirectory:
fpath = os.path.join(directoryName, fname)
if os.path.isfile(fpath) and self.regexp.findall(fname):
if self.relative:
fpath = os.path.relpath(fpath,self.start_dir)
self.result.append(fpath)
if __name__ == '__main__':
print isBinary('f.cur',True)<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
__init__.py
changelog
2013-11-30[00:09:04]:created
2013-12-18[10:19:03]:upgrade to 0.0.3
2013-12-18[21:47:07]:upgrade to 0.0.4
2013-12-19[00:06:07]:upgrade to 0.0.5
2013-12-19[00:08:26]:upgrade to 0.0.6
2013-12-19[00:43:39]:upgrade to 0.0.10 release
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.10
@since 0.0.1
'''
__version__='0.0.12'
<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
route.py
changelog
2013-11-30[18:52:47]:created
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.1
@since 0.0.1
'''
from http import Request,Response
import re
from conf import C,log
from urlparse import urlparse
import utils
from proxy import proxy , get_proxy_url
class Route(object):
'''
路由器
'''
handlers=[];
@classmethod
def distribute_request(self,http_req_handler):
'''
根据URL匹配规则路由请求到相应地处理器
'''
path = urlparse(http_req_handler.path).path
handled = False
#代理支持
if C('enable_proxy') and utils.isDict(C('proxy')):
for reg,target in C('proxy').items():
target_path = get_proxy_url(http_req_handler.path,reg,target)
if target_path:
log.info('[proxy](%s) to (%s)'%(http_req_handler.path,target_path))
return proxy(target_path,Request(http_req_handler),Response(http_req_handler))
for h in self.handlers:
if 'ALL' == h.get('method') or h.get('method') == http_req_handler.command and re.findall(h.get('pattern'),path):
handled = True
ret = (h.get('handler'))(Request(http_req_handler),Response(http_req_handler))
if True == ret:
continue
else:
break
#if not handled by any handlers,405
if not handled:
log.error('%s is not handled'%path)
http_req_handler.send_header(405,'%s not supported'%path)
http_req_handler.end_headers()
self.http_req_handler.wfile.close()
@classmethod
def get(self,pattern,handler):
'''
注册GET请求处理器
'''
self._register(pattern,handler,'GET')
@classmethod
def post(self,pattern,handler):
'''
注册POST请求处理器
'''
self._register(pattern,handler,'POST')
@classmethod
def all(self,pattern,handler):
'''
同时注册POST与GET请求处理器
'''
self._register(pattern,handler,'ALL')
@classmethod
def _register(self,pattern,handler,method):
'''
注册路由控制器
'''
self.handlers.append({'pattern':pattern,'handler':handler,'method':method})<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
setup.py
changelog
2013-11-30[00:06:29]:created
2013-12-16[20:56:26]:upgrade to 0.0.2
@info yinyong,osx-x64,UTF-8,192.168.1.101,py,/Users/yinyong/work/ursa2
@author <EMAIL>
@version 0.0.2
@since 0.0.1
'''
from setuptools import setup, find_packages
from ursa2.__init__ import __version__ as version
setup(
name = "ursa2",
version = version,
packages = ['ursa2'],
install_requires = ['docopt>=0.6.1','jinja2>2.6','requests>=2.0.0'],
include_package_data = True,
package_data = {},
long_description = open('README.md').read(),
author = "<NAME>",
author_email = "<EMAIL>",
description = "Ursa2 is an enhanced version of ursa which is a powerful front web developing environment.",
license = "MIT",
keywords = "ursa,fe,develop,web,jinja2,build",
url = "https://github.com/yanni4night/ursa2",
entry_points = {
'console_scripts':[
'ursa2=ursa2.main:run'
]
}
)<file_sep>#!/usr/bin/env node
var fs = require('fs');
var arg = process.argv.slice(2);
if (arg[0]) {
try {
var content = fs.readFileSync(arg[0], 'utf-8');
content = content.replace(/[^\x00-\xff]/g, function(chinese) {
return escape(chinese).replace(/%u/g, '\\u');
});
fs.writeFileSync(arg[1] || arg[0], content, 'utf-8');
console.log('transfer ' + arg[0] + ' ok');
} catch (e) {
console.log(e);
}
} else {
console.log('are you testing me?');
}<file_sep>#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
deps.py
changelog
2013-12-02[15:48:27]:created
2013-12-14[12:18:46]:include collection supported
2013-12-24[21:00:03]:'ignore_parents' setting
@info yinyong,osx-x64,UTF-8,10.129.173.95,py,/Users/yinyong/work/ursa2/src
@author <EMAIL>
@version 0.0.2
@since 0.0.1
'''
import re
import utils
import os
from conf import C,log
class DepsFinder(object):
'''
递归搜索指定模板文件的依赖模板
'''
@classmethod
def __init__(self,tpl):
'''
tpl:模板,相对于template_dir目录
'''
self._result = []
self._include_result = []
#x=>x.tpl
if not tpl.endswith('.%s'%C('template_ext')):
tpl += '.%s'%C('template_ext')
self._tpl = tpl
self._history = {}
self._done = False
self._pattern = re.compile(r'\{%\s*(include|extends)\s+([\'"])([\w\/\\\.-]+\.'+C('template_ext')+r')\2\s*%\}',re.I|re.M)
@classmethod
def _search(self,tpl):
'''
递归搜索
'''
try:
abspath = utils.abspath(os.path.join(C('template_dir'),tpl))
content = utils.readfile(abspath)
iters = re.finditer(self._pattern,content)
for i in reversed(list(iters)):
tpl = utils.filterRelPath(i.group(3))
if C('ignore_parents') and tpl.endswith('parent.'+C('template_ext')):
continue
if self._history.get(tpl) is None:
self._result.append(tpl)
self._history[tpl] = 1
if 'include' == i.group(1):
self._include_result.append(tpl)
self._search(tpl)
except Exception, e:
log.error('[deps]%s'%e)
@classmethod
def find(self):
'''
获取依赖的接口
'''
if not self._done:
self._search(self._tpl)
self._done = True
return self._result;
@classmethod
def findIncludes(self):
'''
获取依赖的接口
'''
if not self._done:
self.find()
return self._include_result;
@classmethod
def get_tpl():
'''
'''
return self._tpl
@classmethod
def __del__(self):
self._history = {}
self._result = []
if __name__ == '__main__':
df=DepsFinder(u'/template/index')
print df.find()
| d305ab4aa2ea25e74581805464a8bf5b5c59bd60 | [
"JavaScript",
"Python",
"Markdown"
] | 21 | JavaScript | yanni4night/ursa2 | cfcbef52c2d1be2b9bd954a6754cd854645f323c | bef922fa84995f4f22e9736da93adc0e09ee60bb | |
refs/heads/master | <repo_name>Danish903/post_client<file_sep>/src/components/AddPhoto.js
import React from "react";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";
import { GET_EVENTS_QUERY } from "./EventDashboard";
import {
Button,
Form,
Message,
Container,
TextArea,
Checkbox
} from "semantic-ui-react";
import { toast } from "react-semantic-toasts/build/toast";
import { USER_POST_QUERY } from "./UserProfile";
import Dropzone from "./Dropzone";
const styleLoadingImage = { opacity: "0.3", filter: "grayscale(100)" };
const upload = gql`
mutation(
$file: Upload!
$title: String!
$imageURL: String!
$description: String!
$published: Boolean!
$disableComment: Boolean!
$imageURL_ID: String!
) {
singleUpload(
data: {
title: $title
imageURL: $imageURL
description: $description
published: $published
disableComment: $disableComment
imageURL_ID: $imageURL_ID
file: $file
}
) {
success
}
}
`;
const initState = {
title: "",
imageURL: "",
imageURL_ID: "",
description: "",
isPublished: false,
published: true,
disableComment: false,
file: null,
imagePreview: "",
error: ""
};
class AddPhoto extends React.Component {
state = {
title: "",
imageURL: "",
imageURL_ID: "",
description: "",
isPublished: false,
published: true,
disableComment: false,
image: "",
loading: false,
imageUploaded: false,
file: null,
imagePreview: null,
error: ""
};
_onChange = (e, data) => {
const { name, value, checked } = data;
if (name === "published") {
this.setState({
published: !checked,
isPublished: checked
});
} else if (!value) {
this.setState({
[name]: value ? value : checked
});
} else {
this.setState({
[name]: value ? value : checked
});
}
};
onDrop = ([file]) => {
const preview = URL.createObjectURL(file);
this.setState({
file,
image: file,
imagePreview: preview,
imageURL: preview,
imageURL_ID: preview
});
};
imageUploading = () => {
toast({
description: `Image uploading...`,
icon: "warning sign",
type: "success"
});
};
imageUploadedSuccessfully = () => {
toast({
description: `Image uploaded Successfully!`,
icon: "warning sign",
type: "success"
});
};
_onSubmit = async upload => {
if (!this.state.file || !this.state.title || !this.state.description) {
this.setState({ error: "You need to upload an image" });
return;
}
this.setState({ error: "" });
const variables = {
title: this.state.title,
imageURL: this.state.imageURL,
description: this.state.description,
published: this.state.published,
disableComment: this.state.disableComment,
imageURL_ID: this.state.imageURL_ID,
file: this.state.file
};
this.setState({ loading: true });
try {
await upload({ variables });
this.setState({ loading: false, ...initState });
this.imageUploadedSuccessfully();
this.props.history.push("/");
return;
} catch (error) {
console.log(error);
}
this.setState({ loading: false, ...initState });
};
render() {
return (
<Mutation
mutation={upload}
refetchQueries={[
{ query: GET_EVENTS_QUERY },
{
query: USER_POST_QUERY
}
]}
>
{(upload, { data, loading, error }) => {
if (error) return <p>{error.message}</p>;
return (
<Container>
<Message
attached
header="Upload your beautiful pciture !"
content="Fill out the form below to share your photo"
/>
{this.state.imagePreview && (
<img
width="200px"
src={this.state.imagePreview}
alt="imagdde"
style={loading ? styleLoadingImage : null}
/>
)}
<Form
className="attached fluid segment"
onSubmit={() => this._onSubmit(upload)}
>
{!!this.state.error && !this.state.imagePreview && (
<Message negative>
<p>{this.state.error}</p>
</Message>
)}
{!this.state.imagePreview && !loading && (
<Dropzone onDrop={this.onDrop} />
)}
<Form.Field>
<Form.Input
fluid
label="Title"
placeholder="title"
type="text"
name="title"
value={this.state.title}
onChange={this._onChange}
disabled={this.state.loading}
required
/>
</Form.Field>
<Form.Field>
<label
style={
this.state.loading
? { color: "rgba(0,0,0,.25)" }
: null
}
>
Description
</label>
<TextArea
placeholder="Tell us more"
autoHeight
name="description"
onChange={this._onChange}
required
value={this.state.description}
disabled={this.state.loading}
/>
</Form.Field>
<Form.Field>
<Checkbox
type="checkbox"
label="Disable comments for your post"
toggle
name="disableComment"
checked={this.state.disableComment}
onChange={this._onChange}
disabled={this.state.loading}
/>
</Form.Field>
<Form.Field>
<Checkbox
type="checkbox"
label="Make your post private"
toggle
name="published"
checked={this.state.isPublished}
onChange={this._onChange}
disabled={this.state.loading}
/>
</Form.Field>
<Button
basic
color="black"
type="submit"
content="Upload your photo"
disabled={loading}
loading={loading}
/>
</Form>
</Container>
);
}}
</Mutation>
);
}
}
export default AddPhoto;
<file_sep>/README.md
<div align="center"><strong>N</strong>ode <strong>A</strong>pollo <strong>P</strong>risma <strong>E</strong>xpress <strong>R</strong>eact <strong>G</strong>raphQL <strong>P</strong>ostgresql
</div>
<h1 align="center"><strong>Fullstack GraphQL App with React & Prisma</strong></h1>
<h3 align="center">Authentication with roles & permissions. Backend & Frontend</h3>
<h3 align="center">Upload image with expressJs</h3>
<h3 align="center">Messages with GraphQL Subscriptions</h3>
<br />

<div align="center"><strong>🚀 fullstack GraphQL app</strong></div>
### [Online Demo](https://photoups.netlify.com/)
As the Demo Server is hosted on a free Heroku account, the servers its hosted on enter `sleep mode` when not in use. If you notice a delay, please allow a few seconds for the servers to wake and try refreshing a browser.
## Installation
1. Clone project
```
git clone [email protected]:Danish903/post_client.git
```
2. cd into post_client
```
cd web
```
3. Download dependencies
```
npm i
```
4. In `web` create a file called `.env` and add the following line inside: `REACT_APP_SERVER_URL=https://insta-app-server.herokuapp.com` and
`REACT_APP_WS_URL=wss://insta-app-server.herokuapp.com`
5. Start app
```
npm start
```
## Features
- Web login/Signup
- User can post their beautiful pictures
- User can like/comments in real time on their or other user's post
- User can make their post private and can disable comments for their post
- Post owner can delete other user's comments
- Pagination: Infinite scroller is used for paginating pictures and comments
## Made with..
Frontend:
- User interfaces: React https://reactjs.org/
- Design: semantic-ui-react https://react.semantic-ui.com/
- GraphQL tool: Apollo Client https://www.apollographql.com/
Backend:
- Server GraphQL: GraphQL yoga https://github.com/prismagraphql/graphql-yoga
- ORM (object-relational mapping): Prisma https://www.prisma.io/
- Database Postgresql: https://www.postgresql.org/
## App graphql api source
[Server Code](https://github.com/Danish903/post_server)
<file_sep>/src/components/User.js
import React, { Component } from "react";
import { Query } from "react-apollo";
import { gql } from "apollo-boost";
export const ME_QUERY = gql`
query {
me {
id
username
favorites {
id
event {
id
}
}
}
}
`;
export default class User extends Component {
render() {
return (
<Query {...this.props} query={ME_QUERY}>
{payload => this.props.children(payload)}
</Query>
);
}
}
<file_sep>/src/components/DeleteModal.js
import React, { Component } from "react";
import { Button, Header, Image, Modal } from "semantic-ui-react";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";
import { USER_POST_QUERY } from "./UserProfile";
import { toast } from "react-semantic-toasts";
const DELETE_POST_MUTATION = gql`
mutation($id: ID!, $img_ID: String) {
deletePost(id: $id, img_ID: $img_ID) {
id
}
}
`;
class ModalExampleDimmer extends Component {
state = { open: false };
show = dimmer => () => this.setState({ dimmer, open: true });
close = () => {
this.setState({ open: false });
};
deletePost = async deletePost => {
this.setState({ open: false });
deletePost().then(() => {
toast({
description: `Your post is removed.`,
icon: "warning sign",
type: "success"
});
});
};
_update = (cache, { data: { deletePost } }) => {
const data = cache.readQuery({ query: USER_POST_QUERY });
data.userPosts = data.userPosts.filter(post => post.id !== deletePost.id);
cache.writeQuery({ query: USER_POST_QUERY, data });
};
render() {
const { open } = this.state;
const { event } = this.props;
return (
<Mutation
mutation={DELETE_POST_MUTATION}
variables={{ id: event.id, img_ID: event.imageURL_ID }}
update={this._update}
optimisticResponse={{
__typename: "Mutation",
deletePost: {
__typename: "Event",
id: event.id
}
}}
>
{deletePost => (
<>
<Button
basic
color="red"
style={{ width: "100%" }}
onClick={this.show(true)}
>
Delete this post
</Button>
<Modal open={open} onClose={this.close} size="small">
<Modal.Header>Delete This Post </Modal.Header>
<Modal.Content image>
<Image wrapped src={event.imageURL} size="small" />
<Modal.Description>
<Header>{event.title}</Header>
<p>{event.Description}</p>
<p>Do you really want to delete this post?</p>
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<Button color="black" onClick={this.close}>
Nope
</Button>
<Button
icon="checkmark"
labelPosition="right"
content="Delete"
onClick={() => this.deletePost(deletePost)}
color="red"
/>
</Modal.Actions>
</Modal>
</>
)}
</Mutation>
);
}
}
export default ModalExampleDimmer;
<file_sep>/src/components/Login.js
import React from "react";
import { compose, graphql } from "react-apollo";
import { gql } from "apollo-boost";
import { Link } from "react-router-dom";
import {
Button,
Container,
Form,
Header,
Message,
Icon
} from "semantic-ui-react";
import { withFormik, Field } from "formik";
import { validateLoginSchema } from "../utils/formValidationSchema";
import CustomInputComponet from "./CustomInputComponent";
import { ME_QUERY } from "./User";
import Loader from "./Loader";
const LOGIN_MUTATION = gql`
mutation($email: String!, $password: String!) {
login(data: { email: $email, password: $password }) {
token
}
}
`;
const _onSubmit = handleSubmit => {
handleSubmit();
};
const Login = ({
errors,
handleSubmit,
isSubmitting,
data: { me, loading }
}) => {
if (loading) return <Loader />;
return (
<Container fluid={false} text>
{errors && errors.message ? (
<Header as="h4" color="red">
{errors.message}
</Header>
) : null}
<Message
attached
header="Welcome to our site!"
content="Fill out the form below to sign-in"
/>
<Form
className="attached fluid segment"
onSubmit={() => _onSubmit(handleSubmit)}
>
<Field
label="Email"
type="email"
name="email"
placeholder="<EMAIL>"
component={CustomInputComponet}
/>
<Field
label="<PASSWORD>"
type="<PASSWORD>"
name="password"
placeholder="***************"
component={CustomInputComponet}
/>
<Button type="submit" disabled={isSubmitting}>
Login
</Button>
</Form>
<Message attached="bottom" warning>
<Icon name="help" />
Don't have account?
<Link to="/signup">Signup Here</Link>
instead.
</Message>
</Container>
);
};
// export default Login;
export default compose(
graphql(ME_QUERY),
graphql(LOGIN_MUTATION, {
options: ({ values }) => ({
refetchQueries: [
{
query: ME_QUERY
}
],
...values
})
}),
withFormik({
mapPropsToValues: () => ({ email: "", password: "" }),
validationSchema: validateLoginSchema,
handleSubmit: async (
values,
{ props, setErrors, setSubmitting, resetForm }
) => {
try {
const res = await props.mutate({
variables: values
});
localStorage.setItem("token", res.data.login.token);
setSubmitting(false);
await props.data.refetch({
query: ME_QUERY
});
resetForm();
props.history.push("/");
} catch (error) {
setErrors(error);
setSubmitting(false);
}
}
})
)(Login);
<file_sep>/src/components/LikeButton.js
import React, { Component } from "react";
import { Mutation, Query } from "react-apollo";
import { gql } from "apollo-boost";
import { Button } from "semantic-ui-react";
import { toast } from "react-semantic-toasts";
import debounce from "lodash.debounce";
import { ME_QUERY } from "./User";
import { GET_EVENTS_QUERY } from "./EventDashboard";
import _ from "lodash";
import User from "./User";
const LIKE_SUBSCRIPTION = gql`
subscription($eventId: ID!) {
favoriteEvent(eventId: $eventId) {
mutation
node {
id
event {
id
likes {
id
}
}
}
previousValues {
id
}
}
}
`;
const GET_FAVORITES_QUERY = gql`
query($eventId: ID!) {
getFavoriteEvent(eventId: $eventId) {
id
event {
id
likes {
id
}
}
}
}
`;
const LIKE_PHOTO_MUTATION = gql`
mutation($id: ID!) {
likePhoto(id: $id) {
id
event {
id
likes {
id
}
}
}
}
`;
const UNLIKE_PHOTO_MUTATION = gql`
mutation($id: ID!, $favId: ID!) {
unLikePhoto(id: $id, favId: $favId) {
id
}
}
`;
class LikeCount extends Component {
componentDidMount() {
this.props.subscribeToNewLike();
}
disLikePhotoUpdate = (cache, { data: { unLikePhoto } }) => {
const data = cache.readQuery({ query: ME_QUERY });
data.me.favorites = data.me.favorites.filter(
fav => fav.event.id !== this.props.id
);
cache.writeQuery({ query: ME_QUERY, data });
const data2 = cache.readQuery({
query: GET_FAVORITES_QUERY,
variables: { eventId: this.props.id }
});
data2.getFavoriteEvent = data2.getFavoriteEvent.filter(
fav => fav.id !== unLikePhoto.id
);
cache.writeQuery({
query: GET_FAVORITES_QUERY,
variables: { eventId: this.props.id },
data: { ...data2 }
});
};
likePhotoUpdate = (cache, { data: likePhoto }) => {
const data = cache.readQuery({ query: ME_QUERY });
data.me.favorites = [...data.me.favorites, likePhoto.likePhoto];
cache.writeQuery({ query: ME_QUERY, data });
const data2 = cache.readQuery({
query: GET_FAVORITES_QUERY,
variables: { eventId: this.props.id }
});
data2.getFavoriteEvent = [...data2.getFavoriteEvent, likePhoto.likePhoto];
data2.getFavoriteEvent = _.uniqBy(data2.getFavoriteEvent, "id");
cache.writeQuery({
query: GET_FAVORITES_QUERY,
variables: { eventId: this.props.id },
data: { ...data2 }
});
};
handleLike = debounce(async (likePhoto, unLikePhoto, isLiked) => {
if (isLiked) {
try {
await unLikePhoto();
} catch (error) {}
} else {
try {
await likePhoto();
} catch (error) {}
}
}, 200);
render() {
const { id, data, loading, exist, authenticated, isLiked } = this.props;
if (loading) return <p>loading</p>;
return (
<Mutation
mutation={LIKE_PHOTO_MUTATION}
variables={{ id: id }}
optimisticResponse={{
__typename: "Mutation",
likePhoto: {
__typename: "FavoriteEvent",
id: -123243434,
event: {
__typename: "Event",
id,
likes: [
{
__typename: "FavoriteEvent",
id: -123232
}
]
}
}
}}
// refetchQueries={[{ query: ME_QUERY }]}
refetchQueries={[{ query: ME_QUERY }, { query: GET_EVENTS_QUERY }]}
update={this.likePhotoUpdate}
>
{likePhoto => {
return (
<Mutation
mutation={UNLIKE_PHOTO_MUTATION}
variables={{
id,
favId: !!exist ? exist.id : null
}}
optimisticResponse={{
__typename: "Mutation",
unLikePhoto: {
__typename: "FavoriteEvent",
id: !!exist ? exist.id : -123232
}
}}
refetchQueries={[
{ query: ME_QUERY },
{ query: GET_EVENTS_QUERY }
]}
update={this.disLikePhotoUpdate}
>
{(unLikePhoto, { error }) => {
let length;
if (!data) {
length = 0;
}
return (
<Button
as="div"
labelPosition="right"
disabled={!authenticated}
size="mini"
onClick={() =>
this.handleLike(
likePhoto,
unLikePhoto,
isLiked
)
}
>
<Button
content={isLiked ? "Liked" : "Like"}
size="mini"
color={isLiked ? "red" : null}
icon="heart"
label={{
as: "a",
basic: true,
content:
length === 0
? 0
: data.getFavoriteEvent.length
// !!data &&
// data.getFavoriteEvent.length === 0
// ? 0
// : data.getFavoriteEvent.length
}}
labelPosition="right"
/>
</Button>
);
}}
</Mutation>
);
}}
</Mutation>
);
}
}
class LikeButton extends Component {
state = {
like: false
};
handleLike = debounce(async (likePhoto, unLikePhoto, isLiked) => {
if (isLiked) {
try {
await unLikePhoto();
} catch (error) {
toast({
title: "Error",
description: "You already unlike this post",
icon: "warning sign",
type: "error"
});
}
} else {
try {
await likePhoto();
} catch (error) {
toast({
title: "Error",
description: `${error.message}`,
icon: "warning sign",
type: "error"
});
}
}
}, 200);
render() {
const { id } = this.props;
return (
<User>
{({ data, loading }) => {
const authenticated = !!data && !!data.me;
let exist = false;
let isLiked = false;
if (authenticated) {
const { me } = data;
exist = me.favorites.find(fav => fav.event.id === id);
isLiked = !!exist;
}
return (
<Query
query={GET_FAVORITES_QUERY}
variables={{ eventId: id }}
>
{({ subscribeToMore, ...result }) => {
return (
<LikeCount
id={id}
data={data}
exist={exist}
authenticated={authenticated}
isLiked={isLiked}
{...result}
subscribeToNewLike={() => {
subscribeToMore({
document: LIKE_SUBSCRIPTION,
variables: { eventId: id },
updateQuery: (
prev,
{ subscriptionData }
) => {
if (!subscriptionData.data) return prev;
const newLike =
subscriptionData.data.favoriteEvent;
if (newLike.mutation === "DELETED") {
const id = newLike.previousValues.id;
return {
...prev,
getFavoriteEvent: prev.getFavoriteEvent.filter(
fav => fav.id !== id
)
};
}
return {
...prev,
getFavoriteEvent: [
newLike.node,
...prev.getFavoriteEvent
]
};
}
});
}}
/>
);
}}
</Query>
);
}}
</User>
);
}
}
export default LikeButton;
<file_sep>/src/components/UserPostsList.js
import React, { Component } from "react";
import moment from "moment";
import { Link } from "react-router-dom";
import { Grid, Card, Label, Icon, Form, Checkbox } from "semantic-ui-react";
import DeleteModal from "./DeleteModal";
export default class UserPostsList extends Component {
state = {
modalToggle: false
};
componentDidMount() {
this.props.subscribeToUserPosts();
}
toggleModal = () => {
this.setState(prev => ({
...prev,
modalToggle: !prev.modalToggle
}));
};
render() {
const {
data: { userPosts },
loading,
error
} = this.props;
if (loading) return <p>Loading...</p>;
if (error) return <p>Error</p>;
if (userPosts.length === 0) return <p>You don't have any posts.</p>;
return (
<Grid style={{ paddingLeft: "50px" }}>
{userPosts.map((event, i) => (
<Card
key={event.id}
style={{
marginRight: "40px",
marginTop: i === 0 ? "60px !important" : 0,
position: "relative",
marginBottom: userPosts.length - 1 === i ? "14px" : null
}}
>
<Link to={`/photoDetails/${event.id}`}>
<img
src={event.imageURL}
alt={event.name}
className="userPostsImage"
/>
</Link>
{!event.published && (
<Label
as="a"
color="red"
ribbon="right"
style={{ transform: "translateX(-105%)" }}
>
This post is private.
</Label>
)}
<Card.Content>
<Card.Header>{event.title}</Card.Header>
<Card.Meta>
{" "}
created: {moment(event.createdAt).format("LL")}
</Card.Meta>
<Card.Meta>
{" "}
last updated: {moment(event.updatedAt).format("LL")}
</Card.Meta>
<Card.Description>{event.description}</Card.Description>
</Card.Content>
<Card.Content extra className="infoContainer">
<div style={{ marginRight: "auto" }}>
<p>
<Icon name="heart" />
{event.likes.length}
</p>
<Form.Field>
<Checkbox
type="checkbox"
checked={!event.published}
label={event.published ? "Public" : "Private"}
name="published"
/>
</Form.Field>
</div>
<div>
<p>
<Icon name="comment outline" />
{event.comments.length}
</p>
<Icon
name="close"
color="red"
onClick={this.toggleModal}
/>
</div>
</Card.Content>
<DeleteModal
modalToggle={this.state.modalToggle}
event={event}
/>
</Card>
))}
</Grid>
);
}
}
<file_sep>/src/components/EditComment.js
import React, { Component } from "react";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";
import { Form, Input, Comment } from "semantic-ui-react";
import { toast } from "react-semantic-toasts";
import { COMMENT_QUERY } from "./CommentContainer";
const UPDATE_COMMENT_MUTATION = gql`
mutation($id: ID!, $text: String) {
updateComment(id: $id, data: { text: $text }) {
id
text
createdAt
user {
id
username
}
}
}
`;
export default class EditComment extends Component {
state = {
text: this.props.comment.text
};
_onChange = e => {
const { name, value } = e.target;
this.setState(() => ({ [name]: value }));
};
handleUpdateComment = async updateComment => {
if (!!this.state.text) {
const variables = {
id: this.props.comment.id,
text: this.state.text
};
this.props.onCancel();
await updateComment({
variables
}).catch(error => {
toast({
description: `${error.message}`,
icon: "warning sign",
type: "error"
});
});
} else {
toast({
description: `Can't update empty message`,
icon: "info",
type: "info"
});
}
};
updateCache = (cache, { data: { updateComment } }) => {
const { eventId } = this.props;
const data = cache.readQuery({
query: COMMENT_QUERY,
variables: { eventId }
});
data.getComment = data.getComment.map(comment => {
if (comment.id === updateComment.id) {
return {
...comment,
...updateComment
};
}
return comment;
});
cache.writeQuery({
query: COMMENT_QUERY,
variables: { eventId },
data
});
};
render() {
const { onCancel } = this.props;
return (
<Mutation
mutation={UPDATE_COMMENT_MUTATION}
update={this.updateCache}
optimisticResponse={{
__typename: "Mutation",
updateComment: {
__typename: "Comment",
id: this.props.comment.id,
text: this.state.text,
createdAt: this.props.comment.createdAt,
user: {
__typename: "User",
id: this.props.me.id,
username: this.props.me.username
}
}
}}
>
{updateComment => (
<Form onSubmit={() => this.handleUpdateComment(updateComment)}>
<Input
fluid
type="text"
placeholder="update comment"
name="text"
value={this.state.text}
size="mini"
onChange={this._onChange}
>
<input />
</Input>
<Comment.Actions>
<Comment.Action
onClick={() => this.handleUpdateComment(updateComment)}
>
save
</Comment.Action>
<Comment.Action onClick={onCancel}>cancel</Comment.Action>
</Comment.Actions>
</Form>
)}
</Mutation>
);
}
}
<file_sep>/src/components/CommentContainer.js
import React, { Component } from "react";
import { Query } from "react-apollo";
import { gql } from "apollo-boost";
import { Comment, Header } from "semantic-ui-react";
import AddCommentToPhoto from "./AddCommentToPhoto";
import CommentList from "./CommentList";
export const COMMENT_QUERY = gql`
query($eventId: ID!, $after: String) {
getComment(
eventId: $eventId
orderBy: createdAt_DESC
first: 18
after: $after
) {
id
text
createdAt
user {
id
username
}
}
}
`;
const COMMENT_SUBSCRIPTION = gql`
subscription($eventId: ID!) {
comment(eventId: $eventId) {
mutation
node {
id
text
createdAt
user {
id
username
}
}
previousValues {
id
}
}
}
`;
export default class CommentContainer extends Component {
render() {
const { eventId, host } = this.props;
return (
<Comment.Group size="mini">
<Header as="h3" dividing>
Comments
</Header>
<Query query={COMMENT_QUERY} variables={{ eventId }}>
{({ subscribeToMore, ...result }) => (
<CommentList
{...result}
eventId={eventId}
host={host}
subscribeToNewComment={() => {
subscribeToMore({
document: COMMENT_SUBSCRIPTION,
variables: { eventId },
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newComment = subscriptionData.data.comment;
let idExist = false;
if (newComment.mutation === "CREATED") {
idExist =
prev.getComment.filter(
comment =>
comment.id === newComment.node.id
).length > 0;
}
if (idExist) return;
if (newComment.mutation === "DELETED") {
const id = newComment.previousValues.id;
return {
...prev,
getComment: prev.getComment.filter(
comment => comment.id !== id
)
};
}
if (newComment.mutation === "UPDATED") {
return {
...prev,
getComment: prev.getComment.map(comment => {
if (comment.id === newComment.node.id) {
return {
...comment,
...newComment.node
};
}
return comment;
})
};
}
return {
...prev,
getComment: [
newComment.node,
...prev.getComment
]
};
}
});
}}
/>
)}
</Query>
<AddCommentToPhoto eventId={eventId} />
</Comment.Group>
);
}
}
<file_sep>/src/routes/PrivateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";
import jsonwebtoken from "jsonwebtoken";
export const isAuthenticate = () => {
const jwt = localStorage.getItem("token");
if (!jwt) return false;
const decoded = jsonwebtoken.decode(jwt);
if (!decoded) return false;
if (!(Date.now() / 1000 < decoded.exp)) return false;
return true;
};
const PrivateRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props =>
isAuthenticate() ? (
<Component {...props} />
) : (
<Redirect to={"/login"} />
)
}
/>
);
};
export default PrivateRoute;
<file_sep>/src/utils/formValidationSchema.js
import * as yup from "yup";
const validationSchema = yup.object().shape({
username: yup
.string()
.min(5, "Username must be at least 5 characters")
.max(255)
.required(),
email: yup
.string()
.min(3, "Email must be at least 3 characters")
.max(255)
.email("Inavlid email")
.required(),
password: yup
.string()
.min(5, "Password must be at least 5 characters")
.max(255)
.required()
});
export const validateLoginSchema = yup.object().shape({
email: yup
.string()
.min(3, "Email must be at least 3 characters")
.max(255)
.email("Inavlid email")
.required(),
password: yup
.string()
.min(5, "Password must be at least 5 characters")
.max(255)
.required()
});
export { validationSchema as default };
<file_sep>/src/components/EventListItem.js
import React, { PureComponent } from "react";
import { Link } from "react-router-dom";
import { Image, Button, Label, Icon } from "semantic-ui-react";
export default class EventListItem extends PureComponent {
render() {
const { event } = this.props;
return (
<Image.Group>
<Link className="imageContainer" to={`/photoDetails/${event.id}`}>
<img
src={event.imageURL}
style={{
width: "400px",
height: "400px",
objectFit: "cover"
}}
alt={event.title}
/>
<div className="imageAction">
<Button as="div" labelPosition="right">
<Button color="red" icon>
<Icon name="heart" />
</Button>
<Label basic pointing="left">
{event.likes.length}
</Label>
</Button>
<Button as="div" labelPosition="right">
<Button icon>
<Icon name="comment alternate outline" />
</Button>
<Label basic pointing="left">
{event.comments.length}
</Label>
</Button>
</div>
</Link>
</Image.Group>
);
}
}
<file_sep>/src/routes/Routes.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import EventDashboard from "../components/EventDashboard";
import Signup from "../components/Signup";
import Login from "../components/Login";
import Nav from "../components/Nav";
import AddPhoto from "../components/AddPhoto";
import PhotoDetails from "../components/PhotoDetails";
import PageNotFound from "../components/PageNotFound";
import { SemanticToastContainer } from "react-semantic-toasts";
import PrivateRoute from "./PrivateRoute";
import PublicRoute from "./PublicRoute";
import ScrollToTop from "../components/ScrollToTop";
import UserProfile from "../components/UserProfile";
const Routes = () => (
<Router>
<ScrollToTop>
<Nav />
<SemanticToastContainer />
<Switch>
<Route exact path="/" component={EventDashboard} />
<PublicRoute exact path="/signup" component={Signup} />
<PublicRoute path="/login" component={Login} />
<PrivateRoute path="/uploadImage" component={AddPhoto} />
<Route path="/photoDetails/:id" component={PhotoDetails} />
<PrivateRoute path="/userprofile" component={UserProfile} />
<Route component={PageNotFound} />
</Switch>
</ScrollToTop>
</Router>
);
export default Routes;
<file_sep>/src/components/PhotoDetails.js
import React, { Component } from "react";
import { Query } from "react-apollo";
import { gql } from "apollo-boost";
import { Container, Card, Image, Grid, Header } from "semantic-ui-react";
import moment from "moment";
import LikeButton from "./LikeButton";
import CommentContainer from "./CommentContainer";
import Loader from "./Loader";
import PageNotFound from "./PageNotFound";
import DisableComment from "./DisableComment";
export const EVENT_QUERY = gql`
query($id: ID!) {
event(id: $id) {
id
title
description
published
imageURL
disableComment
likes {
id
}
createdAt
host {
id
username
}
}
}
`;
export const SINGLE_EVENT_SUBSCRIPTION = gql`
subscription($id: ID!) {
singleEvent(id: $id) {
mutation
node {
id
title
disableComment
}
}
}
`;
class SubsComponent extends Component {
render() {
const { event } = this.props;
return (
<>
{!event.published && (
<p>This post is private. Only you can see it.</p>
)}
<Grid celled="internally" stackable>
<Grid.Row columns={2}>
<Grid.Column
style={{
display: "flex",
alignItems: "center",
alignContent: "center",
justifyContent: "center"
}}
>
<Image src={event.imageURL} />
</Grid.Column>
<Grid.Column>
<div className="commentContainer">
<Card fluid>
<Card.Content>
<div className="avatar">
<p>
{!!event ? event.host.username[0] : "NA"}
</p>
</div>
<Card.Header>
{!!event ? event.host.username : "test"}
</Card.Header>
<Card.Meta>
{!!event
? moment(event.createdAt).format("LLLL")
: null}
</Card.Meta>
<Card.Description>
{!!event ? event.title : null}
</Card.Description>
</Card.Content>
<Card.Content extra>
<div
style={{
backround: "red",
display: "flex",
justifyContent: "space-between"
}}
>
<LikeButton id={event.id} event={event} />
<DisableComment event={event} />
</div>
</Card.Content>
</Card>
{event.disableComment ? (
<Header as="h4">
Comments are disabled for this post
</Header>
) : (
<CommentContainer
eventId={!!event ? event.id : null}
host={event.host}
/>
)}
</div>
</Grid.Column>
</Grid.Row>
</Grid>
</>
);
}
}
export default class PhotoDetails extends Component {
render() {
const { id } = this.props.match.params;
return (
<Container>
<Query query={EVENT_QUERY} variables={{ id }}>
{({ data, loading, error }) => {
if (loading) return <Loader />;
if (error) return <PageNotFound />;
return <SubsComponent event={!!data ? data.event : null} />;
}}
</Query>
</Container>
);
}
}
<file_sep>/src/components/EventList.js
import React, { Component } from "react";
import { Grid } from "semantic-ui-react";
import InfiniteScroll from "react-infinite-scroller";
import EventListItem from "./EventListItem";
import Loader from "./Loader";
import uuid from "uuid/v4";
export default class EventList extends Component {
state = {
hasMoreItems: true
};
componentDidMount() {
this.unsubscribe = this.props.subscribeToNewEvent();
}
componentWillUnmount() {
this.unsubscribe();
}
handleScroll = () => {
if (this.scroller) {
console.log(this.scroller);
}
};
render() {
const { data, loading, error, fetchMore } = this.props;
if (loading) return <p>Loading...</p>;
if (error) return <p>Error</p>;
if (data.length === 0) return <p>No pictures found currently</p>;
return (
<div>
{!!data && data.events.length > 0 && (
<InfiniteScroll
key={uuid()}
pageStart={0}
loadMore={() =>
fetchMore({
variables: {
after: data.events[data.events.length - 1].id
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
if (fetchMoreResult.events.length < 2) {
this.setState({ hasMoreItems: false });
}
return {
...prev,
events: [
...prev.events,
...fetchMoreResult.events
]
};
}
})
}
hasMore={!loading && this.state.hasMoreItems}
initialLoad={false}
loader={
loading &&
this.state.hasMoreItems && <Loader key={uuid()} />
}
>
<Grid>
{data.events.map(event => (
<EventListItem key={event.id} event={event} />
))}
</Grid>
</InfiniteScroll>
)}
</div>
);
}
}
// OFF SET BASED PAGINATION
// export default class EventList extends Component {
// state = {
// hasMoreItems: true
// };
// componentDidMount() {
// this.querySubscription = this.props.subscribeToNewEvent();
// }
// render() {
// const { data, loading, error, fetchMore } = this.props;
// if (loading) return <p>Loading...</p>;
// if (error) return <p>Error</p>;
// if (data.length === 0) return <p>No pictures found currently</p>;
// return (
// <>
// {this.state.hasMoreItems && (
// <Button
// onClick={() =>
// fetchMore({
// variables: {
// skip: data.events.length
// },
// updateQuery: (prev, { fetchMoreResult }) => {
// if (!fetchMoreResult) return prev;
// if (fetchMoreResult.events.length < 3) {
// this.setState({ hasMoreItems: false });
// }
// return {
// ...prev,
// events: [
// ...fetchMoreResult.events,
// ...prev.events
// ]
// };
// }
// })
// }
// >
// Load More
// </Button>
// )}
// <Grid>
// {data.events.map(event => (
// <EventListItem key={event.id} event={event} />
// ))}
// </Grid>
// </>
// );
// }
// }
<file_sep>/src/components/UserProfile.js
import React, { Component } from "react";
import { Query } from "react-apollo";
import { gql } from "apollo-boost";
import UserPostsList from "./UserPostsList";
export const USER_POST_QUERY = gql`
query {
userPosts(orderBy: createdAt_DESC) {
id
title
imageURL
imageURL_ID
likes {
id
}
description
published
disableComment
createdAt
updatedAt
comments {
id
}
}
}
`;
export const USER_POSTS_SUBSCRIPTION = gql`
subscription {
userPost {
mutation
node {
id
title
imageURL
imageURL_ID
likes {
id
}
description
published
disableComment
createdAt
updatedAt
comments {
id
}
}
previousValues {
id
}
}
}
`;
class UserProfile extends Component {
render() {
return (
<Query query={USER_POST_QUERY}>
{({ subscribeToMore, ...result }) => {
if (result.error)
return <p> {result.error.message}. Try re login again </p>;
return (
<UserPostsList
{...result}
subscribeToUserPosts={() =>
subscribeToMore({
document: USER_POSTS_SUBSCRIPTION,
updateQuery: (prev, { subscriptionData }) => {
if (!subscriptionData.data) return prev;
const newUserPost =
subscriptionData.data.userPost;
if (newUserPost.mutation === "UPDATED") {
return {
...prev,
userPosts: prev.userPosts.map(post => {
if (post.id === newUserPost.node.id) {
return {
...post,
...newUserPost.node
};
}
return post;
})
};
} else if (newUserPost.mutation === "DELETED") {
const id = newUserPost.previousValues.id;
return {
...prev,
userPosts: prev.userPosts.filter(
post => post.id !== id
)
};
}
return {
...prev,
userPosts: [
newUserPost.node,
...prev.userPosts
]
};
}
})
}
/>
);
}}
</Query>
);
}
}
export default UserProfile;
| 14bc860a3603b9369d6d0650aec62f7134b8a3f7 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | Danish903/post_client | e72ccd4e72a4e2d0dde8842d5a6694a58d8b3f8a | 1f96bb40ea2a0b38cb91cb88eba1d3f5adf79391 | |
refs/heads/master | <repo_name>783919/MwAn<file_sep>/README.md
# MwAn
Tools for Malware Analysis automation
Copyright (c) 2020 <NAME> (<EMAIL>)
This simple project is an offline malware scanner for Android. It is made of a module that retrieves installed packages from an Android box, generating an hash list and a module that feeds Virus Total with the hashes to detect possible malware. As package retrieval is decoupled from processing, it can be done in the field, quickly returning the device to the owner, if applicable.
Prerequisites:
- Developer options need to be enabled in the Android box. No root privileges needed.
- A Virus Total API KEY, which, for free accounts, supports 6 queries per minute (see https://www.virustotal.com)
Modules:
- AndroidPullPackages.py (in folder AndroidPullPackages) pulls out the USB connected Android box all the packages allowed and puts them in a chosen folder. As there is no need that the device is rooted, not all the packages can be possibly retrieved, but according to tests performed success rate can range from 90 to 100%. The outcome is a packages sha1 hash list file named packages_sha1.txt. Folder AndroidPullPackages contains also the adb (Android Debug Bridge) server adb.exe with dlls. Once retrieval is done the device can be disconnected.
Usage: python AndroidPullPackages.py "path to package folder"
NOTE: if adb server is not running when AndroidPullPackages.py is launched an error is shown, but server is started automatically. Just relaunch AndroidPullPackages.py and the package pulling process starts.
- AndroidVTProcess.py (in folder AndroidVTProcess) reads file packages_sha1.txt and uploads each sha1 hash to Virus Total. Hash_Android_RDS_v.2.67.txt is a NIST RDS hash set that speeds up verification process avoiding to query VT for known good files. A positive match indicates that at least one VT engine detected the hash as belonging to a malware, a negative indicates that the hash is known but no engine considers it as belonging to a malware, whereas unknown means that hash in not present in VT database. Should the process be interrupted for whatever reason, it will resume from where it left when AndroidVTProcess.py is relaunched.
Usage: python AndroidVTProcess.py "path to hash list file" "Virus Total API Key"
Tested with: Windows 10, Android Debug Bridge version 1.0.41, Python 3.8.1
<file_sep>/AndroidVTProcess/AndroidVTProcess.py
import subprocess
import os
import sys
import ctypes
import winreg
import time
import json
import re
import logging
import hashlib
import requests
BANNER="Android Virus Total Analyzer rel. 0.0.0 by <NAME> (<EMAIL>). Times are in GMT"
#Optional lookup of NIST good files hash list (GFHL)
#First line of file is header:
#"SHA-1","MD5","CRC32","FileName","FileSize","ProductCode","OpSystemCode","SpecialCode"
USE_NIST_GFHL=True
NIST_GFHL_FNAME="Hash_Android_RDS_v.2.67.txt"
NIST_GFHL_DELIM="[',']{1}"
NIST_GFHL_SHA1_POS=0
NIST_GFHL_FNAME_POS=3
NIST_GFHL_ALLOWED_FILE_EXT=("apk")
#Already checked packages (ACP). We keep track of mobile phone packages already checked just not to repeat
#from start if malware analysis process interrupts
ACP_FNAME="checked_packages.txt"
#final report file name
REPORT_FNAME="report.txt"
SHA1_MATCH="^([a-fA-F0-9]{40})$"
VT_API_KEY_MATCH="^([a-fA-F0-9]{64})$"
VT_API_KEY=""
VT_FILE_REPORT_URL="https://www.virustotal.com/vtapi/v2/file/report"
POSITIVE_RES="positive"
NEGATIVE_RES="negative"
UNKNOWN_RES="unknown"
##############################################################################
def send_data_to_vt(url,params):
tx_ok=False
r = requests.get(url,params)
if r.status_code==200:
# extracting data in json format
tx_ok=True
return tx_ok,r.json()
elif r.status_code==204:
logging.warning("Response delayed by VT server")
#set tuple members according to desired retry policy
delay=(60,120,180)# doubling time delay policy
#another example:
#delay=(5,5,5,5,5,5,5,5,5,5,5,5,5)#fixed delay policy
#another example:
#delay=(1,2,4,8,16,32,64)# exponential delay retry policy
for dly in delay:
logging.warning("Retrying after {0} seconds...".format(dly))
time.sleep(dly)
r = requests.get(url,params)
if r.status_code==200:
tx_ok=True
return tx_ok,r.json()
elif r.status_code==204:
logging.warning("Response delayed by VT server")
continue
else:
logging.error("Fatal error while talking to Virus Total. Code:{0}".format(r.status_code))
break
logging.error("Too many tx retries. Virus Total Server too busy")
else:
logging.error("Fatal error while talking to Virus Total. Code:{0}".format(r.status_code))
data={}
return tx_ok,data
###############################################################################
def parse_vt_response(resp):
ismatch=False
isunknown=False
if resp["response_code"]==0:
isunknown=True
logging.info("Hash not present in VT database")
logging.debug("Response: {0}".format(resp["verbose_msg"]))
elif resp["positives"]==0:
logging.info(
"No VT engine detected hash as a malware. Total: {0}, Positives: {1}, Link: {2}".
format(resp["total"],resp["positives"],resp["permalink"]))
else:
ismatch=True
logging.info("Positive MATCH !!! {0} engines out of {1} detected hash as a malware. Link: {2}".format(
resp["positives"],resp["total"],resp["permalink"]))
return ismatch,isunknown
#############################################################################################
def process_android_packages(sha1_list_file,nist_good_file_hash_list,
already_checked_file_hash_list):
processed_hashes=0
pos_matches=0
negatives=0
unknown=0
line_num=0
try:
f = open(sha1_list_file, "r")
for line in f:
line_num+=1
if line_num==1:
continue#skip header
cols=re.split("\t",line.replace('\n', ''))
sha1=cols[0]
package=cols[1]
processed_hashes+=1
if len(already_checked_file_hash_list)>0:
if sha1 in already_checked_file_hash_list:
logging.info("Package {0} already checked. No need to query Virus Total".format(package))
r = open(REPORT_FNAME,"a")
r.write(sha1+"\t"+already_checked_file_hash_list[sha1]+"\t"+"cache\n")
r.close()
res=re.split("\t",already_checked_file_hash_list[sha1].replace('\n', ''))
if res[1]==POSITIVE_RES:
pos_matches+=1
elif res[1]==NEGATIVE_RES:
negatives+=1
else:
unknown+=1
continue
if USE_NIST_GFHL:
if sha1 in nist_good_file_hash_list:
logging.info("Package {0} is in NIST good files hash list. No need to query Virus Total".format(package))
r = open(REPORT_FNAME,"a")
r.write(sha1+"\t"+nist_good_file_hash_list[sha1]+NEGATIVE_RES+"\t"+"good files list\n")
r.close()
negatives+=1
continue
logging.info("Querying Virus Total for package {0} with SHA1 hash: {1}...".format(package,sha1))
PARAMS = {'apikey':VT_API_KEY,'resource':sha1}
tx_ok,data=send_data_to_vt(VT_FILE_REPORT_URL,PARAMS)
if tx_ok:
ismatch,isunknown=parse_vt_response(data)
result=""
if ismatch:
pos_matches+=1#package detected as malware
result=POSITIVE_RES
elif not isunknown:#update list of already checked good packages
result=NEGATIVE_RES
negatives+=1
else:
result=UNKNOWN_RES
unknown+=1
g=open(ACP_FNAME,"a")
g.write(sha1+"\t"+package+"\t"+result+"\n")
g.close()
r = open(REPORT_FNAME,"a")
r.write(sha1+"\t"+package+"\t"+result+"\t"+"online\n")
r.close()
time.sleep(2)
logging.info("Done. Processed packages: {0} . Positives: {1} Negatives: {2} Unknown: {3}".format(
processed_hashes,pos_matches,negatives,unknown))
f.close()
except Exception as ex:
output=logging.error("An error occurred. {0}".format(ex.args))
############################################################################################
def read_nist_good_hl_file():
line_num=0
gfhl={}
f = open(NIST_GFHL_FNAME, "r")
for line in f:
if line_num==0:#ignore header
line_num+=1
continue
if line.startswith("#"):#ignore comments
line_num+=1
continue
cols=re.split(NIST_GFHL_DELIM,line.replace('"', ''))
gfhl_sha1=cols[NIST_GFHL_SHA1_POS]
gfhl_fname=cols[NIST_GFHL_FNAME_POS]
if re.match(SHA1_MATCH,gfhl_sha1) and gfhl_fname.endswith(NIST_GFHL_ALLOWED_FILE_EXT):
gfhl[gfhl_sha1]=gfhl_fname
f.close()
return gfhl
############################################################################################
def read_already_checked_packages_file():
cgphl={}
if os.path.isfile(ACP_FNAME):
f = open(ACP_FNAME, "r")
for line in f:
cols=re.split("\t",line.replace('\n', ''))
cgphl[cols[0]]=cols[1]+"\t"+cols[2]
f.close()
return cgphl
############################################################################################
#main
try:
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('log.txt','a'),#append is default anyway
logging.StreamHandler()
])
logging.Formatter.converter = time.gmtime
logging.info(BANNER)
if len(sys.argv)!=3:
raise Exception("Usage: {0} <path to packages sha1 list file> <Virus Total API key>".
format(sys.argv[0]))
sha1_list_file=sys.argv[1]
if not(os.path.exists(sha1_list_file)):
raise Exception("Path {0} is invalid".format(sha1_list_file))
VT_API_KEY=sys.argv[2]
if not re.match(VT_API_KEY_MATCH,VT_API_KEY):
raise Exception("VT_API_KEY syntax is not valid. Valid Virus Total api keys are 64 hex chars")
if len(NIST_GFHL_ALLOWED_FILE_EXT)==0:
raise Exception("Specify at least one file extension")
r = open(REPORT_FNAME,"w")
r.write("SHA1"+"\t"+"PACKAGE NAME"+"\t"+"RESULT"+"\t"+"SOURCE"+"\n")
r.close()
nist_good_file_hash_list={}
already_checked_files=read_already_checked_packages_file()
if USE_NIST_GFHL:
nist_good_file_hash_list=read_nist_good_hl_file()
process_android_packages(sha1_list_file,nist_good_file_hash_list,already_checked_files)
except Exception as ex:
logging.error("An error occurred. {0}".format(ex.args))
<file_sep>/AndroidPullPackages/AndroidPullPackages.py
import subprocess
import os
import sys
import ctypes
import winreg
import time
import json
import re
import logging
import hashlib
import requests
BANNER="Android Package Pull rel. 0.0.0 by <NAME> (<EMAIL>). Times are in GMT"
PACKAGE_HASH_LIST_FILE="packages_sha1.txt"
#############################################################################################
def pull_android_packages(dest_folder):
processed_packages=0
pulled_packages=0
try:
packages_line=subprocess.run(["adb", "shell", "pm", "list", "packages" ,"-f"],
capture_output=True,text=True)
if len(packages_line.stderr)>0 or not packages_line.stdout.startswith("package:"):
raise Exception("Adb package listing failed. Ensure that phone is in DEBUG mode and debugging is authorized. Error: {0}".format(packages_line.stderr))
packages = packages_line.stdout.splitlines()
for package in packages:
processed_packages+=1
right=package[len("package:"):]
head,sep,pack_name=right.partition(".apk=")
pack_path=head + ".apk"
logging.info("Pulling {0} to destination folder {1}".format(pack_path,dest_folder))
dest_path=os.path.join(dest_folder,pack_name + ".apk")
pull_line=subprocess.run(["adb", "pull", pack_path,dest_path],capture_output=True,text=True)
if "error" in pull_line.stdout or not "1 file pulled" in pull_line.stdout:
logging.error("Cannot copy package {0}. Error: {1}".format(pack_path,pull_line.stdout))
else:
pulled_packages+=1
h=hashlib.sha1()
f = open(dest_path, "rb")
h.update(f.read())
sha1=h.hexdigest()
f.close()
g=open(PACKAGE_HASH_LIST_FILE,"a")
g.write(sha1 + "\t" + pack_name + ".apk" +"\n")
g.close()
logging.info("Done pulling {0} packages out of {1}".format(pulled_packages,processed_packages))
except Exception as ex:
output=logging.error("An error occurred. {0}".format(ex.args))
############################################################################################
#main
try:
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('log.txt','a'),#append is default anyway
logging.StreamHandler()
])
logging.Formatter.converter = time.gmtime
logging.info(BANNER)
if len(sys.argv)!=2:
raise Exception("Usage: {0} <path to folder where storing pulled packages>".format(sys.argv[0]))
dest_folder=sys.argv[1]
if not(os.path.exists(dest_folder)):
os.makedirs(dest_folder)
else:
for filename in os.listdir(dest_folder):
os.remove(os.path.join(dest_folder,filename))
g = open(PACKAGE_HASH_LIST_FILE,"w")
g.write("SHA1"+"\t"+"PACKAGE NAME"+"\n")
g.close()
pull_android_packages(dest_folder)
except Exception as ex:
logging.error("An error occurred. {0}".format(ex.args))
| 3c3055e6304f2764689b6b6664744e27db058bb8 | [
"Markdown",
"Python"
] | 3 | Markdown | 783919/MwAn | 14012303815022c277f9ed7f55d25bef38f6e417 | 04a0221d8a0dafc5297cdafad1c25a334fbe3289 | |
refs/heads/master | <repo_name>pedoch/todo-list<file_sep>/src/Components/TodoItem.js
import React from 'react'
function TodoItem(props){
const completedStyle = {
fontStyle: "italic",
color: "lightgray",
textDecoration: "line-through"
}
return(
<div className="todoList">
<p style={props.todo.completed ? completedStyle : null}><input type="checkbox"
onChange={function(){
props.handleChange(props.todo.id)
}}/>{props.todo.text} <button onClick={function(){
props.handleDelete(props.todo.id)
}} >Delete</button></p>
</div>
)
}
export default TodoItem; | d30cb8f21954a959d86ac5355652a41cdb166d38 | [
"JavaScript"
] | 1 | JavaScript | pedoch/todo-list | 0ba8d47fc6afbdce0b542a86504b2f0a1fb742e3 | 99e1be5897d896e35b0aaee094218a999ad7a583 | |
refs/heads/master | <repo_name>acryboyhyj/Multithread<file_sep>/produce_consume.cpp
#include <memory.h>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
template <class Data>
class Buffer {
private:
int m_capacity;
int m_front;
int m_rear;
int m_size;
Data* m_buffer;
std::mutex m_mutex;
std::condition_variable m_not_full;
std::condition_variable m_not_empty;
public:
explicit Buffer(int capacity)
: m_capacity(capacity),
m_front(0),
m_rear(0),
m_size(0),
m_buffer(new Data[m_capacity]) {}
~Buffer() { delete[] m_buffer; }
Buffer operator=(const Buffer&) = delete;
Buffer(const Buffer&) = delete;
void Deposit(const Data& data) {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_not_full.wait(lock, [this] { return m_size < m_capacity; });
m_buffer[m_rear] = data;
m_rear = (m_rear + 1) % m_capacity;
m_size++;
}
m_not_empty.notify_one();
}
void Fetch(Data& data) {
{
std::unique_lock<std::mutex> lock(m_mutex);
m_not_empty.wait(lock, [this] { return m_size > 0; });
data = std::move(m_buffer[m_front]);
m_front = (m_front + 1) % m_capacity;
m_size--;
}
m_not_full.notify_one();
}
};
template <class Data>
void Consume(Buffer<Data>& buffer) {
for (int i = 0; i < 50; ++i) {
Data data;
buffer.Fetch(data);
std::cout << "consumer "
<< " comsume " << data << '\n';
}
}
template <class Data>
void Produce(Buffer<Data>& buffer) { // NOLINT
for (int i = 0; i < 50; i++) {
buffer.Deposit(i);
std::cout << "product produced " << i << '\n';
}
}
int main() {
std::thread thread_consume[5];
std::thread thread_produce[5];
Buffer<int> buffer(50);
for (int i = 0; i < 5; ++i) {
thread_consume[i] = std::thread(Consume<int>, std::ref(buffer));
thread_produce[i] = std::thread(Produce<int>, std::ref(buffer));
}
for (auto& th_c : thread_consume) th_c.join();
for (auto& th_p : thread_produce) th_p.join();
return 0;
}
| 5246b1993df576e016761910c79e81540cced465 | [
"C++"
] | 1 | C++ | acryboyhyj/Multithread | d8e94055449c4b7f2b9091448eaf376c232b7f88 | 14c0486000a10cf77de2bbb0d1321ebb17b46970 | |
refs/heads/master | <file_sep>import Preloader from "../src/preloader.js";
const preloader = new Preloader(
"http://pic1.win4000.com/wallpaper/f/5876e4b550212.jpg"
);
<file_sep>export async function myLoader(images, callback) {
let loaded = 0;
const total = images.length;
for (const [index, image] of images.entries()) {
loaded = index + 1;
try {
await loadImage(image);
} catch (e) {
console.log(e);
}
callback((100 * loaded) / total);
}
}
const loadImage = (src) =>
new Promise((resolve, reject) => {
const img = new Image();
img.src = src;
if (img.complete) {
resolve();
} else {
img.onload = () => {
resolve();
};
img.onerror = (e) => {
reject(e);
};
}
});
<file_sep>import Preloader from "./preloader.js";
const preloader = new Preloader("123");
const img = new Image();
<file_sep>export default class Preloader {
constructor(resource, option = { mode: "no-cors", method: "GET" }) {
if (typeof resource === "string") {
console.log("string is good");
this.initSingle(resource, option);
} else if (resource instanceof Array) {
console.log("array is good");
} else {
console.log("bad type");
}
// this.test = new Test();
}
initSingle(r, o) {
const option = Object.assign(o, { responseType: "blob" });
fetch(r, option)
.then((response) => {
// if (response.ok) {
// return response.blob();
// }
// throw new Error("Network response was not ok.");
console.log(response);
})
.then((blob) => {
console.log("done", blob);
})
.catch((e) => {
console.log(e);
});
}
}
<file_sep>const http = require("http");
const cp = require("child_process");
const fs = require("fs");
const mime = require("mime");
const url = require("url");
const path = require("path");
const server = http.createServer();
const STATIC_FOLDER = "lib";
server.listen(8080, () => {
console.log("server start at port 8080");
});
server.on("request", (req, res) => {
const rootName = path.join(__dirname, "../");
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
fs.readFile("./test/index.html", "utf-8", (err, data) => {
if (err) {
throw err;
}
res.end(data);
});
} else if (req.url === "/favicon.ico") {
const pathname = url.parse(req.url).pathname;
const favicon = path.join(rootName, pathname);
const ext = path.extname(pathname);
const contentType = mime.getType(ext) || "text/plain";
let raw = fs.createReadStream(favicon);
res.writeHead(200, "ok", {
"Content-Type": contentType,
});
raw.pipe(res);
} else {
const pathname = url.parse(req.url).pathname;
const ext = path.extname(pathname);
const contentType = mime.getType(ext) || "text/plain";
const realPath = path.join(rootName, STATIC_FOLDER, pathname);
console.log(pathname, __dirname, realPath);
let raw = fs.createReadStream(realPath);
res.writeHead(200, "ok", {
"Content-Type": contentType,
});
raw.pipe(res);
}
});
cp.exec("start http://127.0.0.1:8080/");
| 57475bdeab1ce65e5aa06f8d2c1cd56a440ac94d | [
"JavaScript"
] | 5 | JavaScript | flashtintin/preloader | f15139833f45e03fe517192077b6f0d9943a34fd | 80cce69adc4938016fdd6e7f7ce84b60819d269f | |
refs/heads/master | <repo_name>mberkenbrock/PrimeiraTabela<file_sep>/PrimeiraTabela/main.js
function addRow()
{
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var age = document.getElementById('age').value;
var table = document.getElementById('myTable');
var row = table.insertRow(1);
var cell = row.insertCell(0);
var cel2 = row.insertCell(1);
var cel3 = row.insertCell(2);
cell.innerHTML = fname;
cel2.innerHTML = lname;
cel3.innerHTML = age;
}
| 952206bc6168d511d3a070397995bba09719c6d0 | [
"JavaScript"
] | 1 | JavaScript | mberkenbrock/PrimeiraTabela | e0621b2dc1ed109efa47d2692ea141f4d38d08dc | 721a85ceefabebbdff707aa993fcac8435c4c367 | |
refs/heads/master | <repo_name>alisowicz/Form<file_sep>/script/app.js
$(document).ready(function(){
$(".triangle-top").mouseover(function(){
$(".required-top").css("visibility", "visible");
});
$(".triangle-top").mouseout(function(){
$(".required-top").css("visibility", "hidden");
});
$(".triangle-bottom").mouseover(function(){
$(".required-bottom").css("visibility", "visible");
});
$(".triangle-bottom").mouseout(function(){
$(".required-bottom").css("visibility", "hidden");
});
$(".asterisc-top-reset").mouseover(function(){
$(".required-top-reset").css("visibility", "visible");
});
$(".asterisc-top-reset").mouseout(function(){
$(".required-top-reset").css("visibility", "hidden");
});
//validate e-EMAIL
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var $result = $("#result");
var email = $("#email").val();
$result.text("");
if (validateEmail(email)) {
$result.text("");
} else {
$result.text("Invalid email adress");
$result.css("color", "red");
}
return false;
}
$("#validate").bind("click", validate);
const forgottenButton = document.querySelector('.forgotten__button');
const cancelButton = document.querySelector('.form__button-cancel')
const label = document.querySelector('.form_container-reset');
const label2 = document.querySelector('.form_container');
const switchWindows = function(){
label.classList.toggle('invisible')
label2.classList.toggle('invisible')
}
forgottenButton.addEventListener('click', function(event){
event.preventDefault()
switchWindows()
})
cancelButton.addEventListener('click', function(event){
event.preventDefault()
switchWindows()
})
});
| 9db40c495fd7e275755e0bea9c91403e0607d9db | [
"JavaScript"
] | 1 | JavaScript | alisowicz/Form | f3386e178034bd01eccfad1faa4ff3497b081835 | 103262c9703fb64430c0ed00986cfabd6cc30334 | |
refs/heads/master | <repo_name>keyvanm/node-narrator<file_sep>/index.js
require('babel-register')({
presets: [ 'es2015' ]
});
const play = require('./play').default;
console.log(play);
play();
<file_sep>/play.js
import Character from './character';
const player = new Character({ id: "self", name: "Anonymous" });
const ai = new Character({ id: "ai", name: "RE_" });
const play = () => {
ai.says("Greetings!");
player.name = ai.asks(player, "Whats your name?");
ai.says(`Good to meet you ${player.name}`);
player.age = ai.asks(player, "How old are you?");
ai.says(`${player.age} is a good age`);
}
export default play;
<file_sep>/interface.js
// import prompt from 'prompt';
var promptSync = require('prompt-sync')();
// prompt.start();
export function dialog(character, text) {
const message = {
sender: {
id: character.id
},
content: {
type: 'text',
text
}
};
const logText = `> [${character.name}] ${text}`;
console.log(logText);
return logText;
}
export function askText(character, player, text) {
const promptText = dialog(character, text);
// prompt.get(promptText, (err, response) => {
// const message = {
// sender: {
// id: player.id
// },
// content: {
// type: 'text',
// text: response
// }
// };
// console.log(`\$ ${response}`);
// return response;
// });
const response = promptSync("$ ");
const message = {
sender: {
id: player.id
},
content: {
type: 'text',
text: response
}
};
return response;
}
| 1a23cec0d01c37cbb7f099f3fcee5e7b38d1d9ef | [
"JavaScript"
] | 3 | JavaScript | keyvanm/node-narrator | 9a3c4444803c2df7b954760a934054039f0cdf04 | 1800d2e2c370d441c8a50fefd138fcc562506019 | |
refs/heads/master | <file_sep>/*
* Copyright (C) 2023 Amazon Inc. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#ifndef _WASM_SUSPEND_FLAGS_H
#define _WASM_SUSPEND_FLAGS_H
#include "bh_platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Need to terminate */
#define WASM_SUSPEND_FLAG_TERMINATE 0x1
/* Need to suspend */
#define WASM_SUSPEND_FLAG_SUSPEND 0x2
/* Need to go into breakpoint */
#define WASM_SUSPEND_FLAG_BREAKPOINT 0x4
/* Return from pthread_exit */
#define WASM_SUSPEND_FLAG_EXIT 0x8
typedef union WASMSuspendFlags {
uint32 flags;
uintptr_t __padding__;
} WASMSuspendFlags;
#if defined(__GNUC_PREREQ)
#if __GNUC_PREREQ(4, 7)
#define CLANG_GCC_HAS_ATOMIC_BUILTIN
#endif
#elif defined(__clang__)
#if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 0)
#define CLANG_GCC_HAS_ATOMIC_BUILTIN
#endif
#endif
#if defined(CLANG_GCC_HAS_ATOMIC_BUILTIN)
#define WASM_SUSPEND_FLAGS_IS_ATOMIC 1
#define WASM_SUSPEND_FLAGS_GET(s_flags) \
__atomic_load_n(&s_flags.flags, __ATOMIC_SEQ_CST)
#define WASM_SUSPEND_FLAGS_FETCH_OR(s_flags, val) \
__atomic_fetch_or(&s_flags.flags, val, __ATOMIC_SEQ_CST)
#define WASM_SUSPEND_FLAGS_FETCH_AND(s_flags, val) \
__atomic_fetch_and(&s_flags.flags, val, __ATOMIC_SEQ_CST)
#else /* else of defined(CLANG_GCC_HAS_ATOMIC_BUILTIN) */
#define WASM_SUSPEND_FLAGS_GET(s_flags) (s_flags.flags)
#define WASM_SUSPEND_FLAGS_FETCH_OR(s_flags, val) (s_flags.flags |= val)
#define WASM_SUSPEND_FLAGS_FETCH_AND(s_flags, val) (s_flags.flags &= val)
/* The flag can be defined by the user if the platform
supports atomic access to uint32 aligned memory. */
#ifdef WASM_UINT32_IS_ATOMIC
#define WASM_SUSPEND_FLAGS_IS_ATOMIC 1
#else /* else of WASM_UINT32_IS_ATOMIC */
#define WASM_SUSPEND_FLAGS_IS_ATOMIC 0
#endif /* WASM_UINT32_IS_ATOMIC */
#endif
#if WASM_SUSPEND_FLAGS_IS_ATOMIC != 0
#define WASM_SUSPEND_FLAGS_LOCK(lock) (void)0
#define WASM_SUSPEND_FLAGS_UNLOCK(lock) (void)0
#else /* else of WASM_SUSPEND_FLAGS_IS_ATOMIC */
#define WASM_SUSPEND_FLAGS_LOCK(lock) os_mutex_lock(&lock)
#define WASM_SUSPEND_FLAGS_UNLOCK(lock) os_mutex_unlock(&lock);
#endif /* WASM_SUSPEND_FLAGS_IS_ATOMIC */
#ifdef __cplusplus
}
#endif
#endif /* end of _WASM_SUSPEND_FLAGS_H */ | b09f0e5f7cde366720c1ae4d561acdfbafe4880c | [
"C"
] | 1 | C | hoangpq/wasm-micro-runtime | 0f4edf97359d8005fc2eb092a4fe908ffddcfd04 | d9ebfddd7ee3f019cc7b8150f2538babc917b587 | |
refs/heads/master | <repo_name>Blednykh/focusStartProject<file_sep>/app/js/renderBasketModule.js
function renderBasketTableContent(table, basket) {
let {goodsList} = basket;
if (goodsList !== null && goodsList.length !== 0) {
goodsList.forEach(item => {
let temp = document.getElementById("temp_type_basket-item");
let clon = temp.content.cloneNode(true);
let productImg = clon.querySelector(".product__img");
productImg.src = item.img;
let descriptionProductName = clon.querySelector(".description__product-name");
descriptionProductName.innerText = item.prod;
let descriptionSupplierName = clon.querySelector(".description__supplier-name");
descriptionSupplierName.innerText = item.supp;
let basketItemPrice = clon.querySelector(".basket-item__price");
basketItemPrice.innerText = `$${parseFloat(item.price).toFixed(3)}`;
let basketItemInput = clon.querySelector(".basket-item__input");
basketItemInput.placeholder = item.count;
let basketItemTotalPrice = clon.querySelector(".basket-item__total-price");
basketItemTotalPrice.innerText = "$" + (parseFloat(item.price) * item.count).toFixed(2);
basketItemInput.addEventListener("keyup", (e) => {
if (Object.is(parseInt(basketItemInput.value), NaN)) {
basketItemInput.value = "";
} else {
if (parseInt(basketItemInput.value) === 0) {
let basketItems = document.querySelectorAll(".basket__basket-item");
basket.removeGoods(item);
basketItems.forEach(item => item.remove());
renderBasketTableContent(table, basket);
} else {
basket.changeItemCount(item, basketItemInput.value);
basketItemTotalPrice.innerText = "$" + (item.price * basketItemInput.value).toFixed(3);
basketItemInput.placeholder = basketItemInput.value;
}
renderTotalPrice(basket.sum)
}
});
//Удаление из корзины
let productLogoCross = clon.querySelector(".product__logo-cross");
productLogoCross.addEventListener("click", () => {
basket.removeGoods(item);
let basketItems = document.querySelectorAll(".basket__basket-item");
basketItems.forEach(item => item.remove());
renderBasketTableContent(table, basket);
renderTotalPrice(basket.sum)
});
table.appendChild(clon);
})
}
else {
//Пустая корзина
let totalPriceBoxPrice = document.querySelector(".total-price-box__price");
let totalPriceBoxButton = document.querySelector(".total-price-box__button");
totalPriceBoxPrice.innerText = "$0.00";
totalPriceBoxButton.disabled = true;
let h2 = document.createElement("h2");
h2.innerText = "No Goods in Cart!";
table.replaceWith(h2);
}
}
//рендер подтабличных данных
function renderTotalPrice(sum) {
let mainElement = document.querySelector(".l-main");
let priceCount = mainElement.querySelector(".price__count");
let priceItem = priceCount.querySelector(".price__item");
priceItem.innerText = "$" + Math.round(parseFloat(sum) * 10 * 10) / 100;
let totalPriceBoxPrice = mainElement.querySelector(".total-price-box__price");
totalPriceBoxPrice.innerText = "$" + Math.round((parseFloat(sum) + 5) * 10 * 10) / 100;
}
export function renderBasket(basket) {
let mainElement = document.querySelector(".l-main");
let mainContent = mainElement.querySelector(".l-main-content");
mainElement.removeChild(mainContent);
mainElement.className = `l-main main_type_basket`;
let temp = document.getElementById("temp_type_basket");
let basketClon = temp.content.cloneNode(true);
mainElement.appendChild(basketClon);
let table = mainElement.querySelector(".basket__basket-table");
renderTotalPrice(basket.sum);
renderBasketTableContent(table, basket);
}<file_sep>/app/js/setHomeContentModule.js
import {sendRequest} from "./apiModule.js";
const HOME_ITEMS_URL_LIST = [
"http://localhost:3000/data/home-items/homeItemsA.json",
"http://localhost:3000/data/home-items/homeItemsB.json"
];
function createMenuItem(basket, marketItem, priority, size) {
let temp = document.getElementById("temp_type_home-item");
let clone = temp.content.cloneNode(true);
let section = clone.querySelector(".c-menu-item");
let img = clone.querySelector(".c-menu-item__img");
let supp = clone.querySelector(".c-menu-item__supp");
let prod = clone.querySelector(".c-menu-item__prod");
let price = clone.querySelector(".c-menu-item__price");
let svg = clone.querySelector(".c-menu-item__logo");
section.className = "c-menu-item";
section.className += (priority === "top") ? " home-menu-top-item" : " home-menu-bottom-item";
section.className += (size === "large") ? " t-size-large" : "";
img.className = "c-menu-item__img";
img.src = marketItem.img;
supp.innerText = marketItem.supp;
prod.innerText = marketItem.prod;
price.innerText = "$" + marketItem.price;
svg.addEventListener("click", () => {
basket.addGood(marketItem);
});
return clone;
}
export function setHomeContent(menuTopElements, menuBottomLeftElements, menuBottomRightElements, basket) {
let url = HOME_ITEMS_URL_LIST[Math.floor(Math.random() * HOME_ITEMS_URL_LIST.length)];
sendRequest('GET', url)
.then(response => {
let marketItems = response;
marketItems
.filter(item => item.type === "top")
.forEach(item => {
menuTopElements.appendChild(createMenuItem(basket, item, "top"))
});
marketItems
.filter(item => {
return item.type !== "top"
}).forEach((item, i) => {
if (i === 0) {
menuBottomLeftElements.appendChild(createMenuItem(basket, item, "", "large"));
return;
}
if (i === 9) {
menuBottomRightElements.appendChild(createMenuItem(basket, item, "", "large"));
return;
}
if (i % 2 === 0) {
menuBottomLeftElements.appendChild(createMenuItem(basket, item));
} else {
menuBottomRightElements.appendChild(createMenuItem(basket, item));
}
});
});
}<file_sep>/app/js/renderSubcategoryPageModule.js
import {sendRequest} from "./apiModule.js";
function renderPage(basket, title, item) {
let pathItem = document.querySelectorAll(".o-path__item");
pathItem[0].innerText = title;
pathItem[1].innerText = item;
let h2 = document.querySelector(".main_type_menu__h2");
h2.innerText = item;
let pathPart = item.split(" ").join("-").toLowerCase();
let HOME_SUB_URL_LIST = [
`http://localhost:3000/data/subcategory-items/${pathPart}/${pathPart}ItemsA.json`,
`http://localhost:3000/data/subcategory-items/${pathPart}/${pathPart}ItemsB.json`
];
let url = HOME_SUB_URL_LIST[Math.floor(Math.random() * HOME_SUB_URL_LIST.length)];
sendRequest('GET', url)
.then(response => {
let marketItem = response;
let menuBox = document.querySelector(".menu-box");
marketItem
.forEach(item => {
let temp = document.getElementById("temp_type_subcategory-list");
let clon = temp.content.cloneNode(true);
let productImg = clon.querySelector(".c-menu-item__img");
productImg.src = item.img;
let productName = clon.querySelector(".c-menu-item__prod");
productName.innerText = item.prod;
let supplierName = clon.querySelector(".c-menu-item__supp");
supplierName.innerText = item.supp;
let productPice = clon.querySelector(".c-menu-item__price");
productPice.innerText = `$${item.price}`;
let svg = clon.querySelector(".o-shape-logo");
svg.addEventListener("click", () => {
basket.addGood(item);
});
menuBox.appendChild(clon);
});
})
}
export function renderSubcategoryPage(basket, title, item) {
let mainElement = document.querySelector(".l-main");
let mainContent = mainElement.querySelector(".l-main-content");
mainElement.removeChild(mainContent);
mainElement.className = `l-main main_type_menu`;
let temp = document.getElementById("temp_type_subcategory");
let pageClon = temp.content.cloneNode(true);
mainElement.appendChild(pageClon);
renderPage(basket, title, item);
}<file_sep>/app/js/script.js
import {setHeaderSubcategoriesContent} from "./setHeaderSubcategoriesContentModule.js";
import {sendRequest} from "./apiModule.js";
import {Basket} from "./Basket.js";
import {createBasketBox} from "./basketBoxCreateModule.js";
import {renderHome} from "./renderHomeModule.js";
import {renderBasket} from "./renderBasketModule.js";
import {renderOrderAddress} from "./renderOrderAddressModule.js";
import {renderOrderPayment} from "./renderOrderPaymentModule.js";
import {renderOrderEnd} from "./renderOrderEndModule.js";
import {Address} from "./Address.js";
import {Router} from "./Router.js";
import {renderSubcategoryPage} from "./renderSubcategoryPageModule.js";
//Инициализация роутинга
let router = new Router();
//Инициализация корзины
let basket = new Basket();
//Инициализация объекта с данными об адресе покупателя
let address = new Address();
//Заполнение мини-корзины в шапке
createBasketBox(basket);
//Создание подкатегорий в шапке
let categoryListLi = document.querySelectorAll(".category-list__li");
sendRequest('GET', "http://localhost:3000/data/goods-categories/categories.json")
.then(response => {
let HeaderBottomItems = response;
categoryListLi.forEach((item, i) => setHeaderSubcategoriesContent(item, i, HeaderBottomItems, basket, router));
});
//Рендер необходимой страницы
locationHashChanged();
function locationHashChanged() {
switch (location.hash) {
case "#basket": {
renderBasket(basket, address);
break;
}
case "": {
renderHome(basket);
break;
}
case "#order-address": {
renderOrderAddress(basket, address);
break;
}
case "#order-payment": {
renderOrderPayment(basket, address);
break;
}
case "#order-end": {
renderOrderEnd();
break;
}
default: {
let findOpenedSubcategoryIndex = router.findIndexByHash(location.hash);
if (findOpenedSubcategoryIndex !== -1) {
renderSubcategoryPage(
basket,
router.subcategoryData[findOpenedSubcategoryIndex].title,
router.subcategoryData[findOpenedSubcategoryIndex].subcategoryItem
);
} else {
location.href = "";
}
}
}
}
window.onhashchange = locationHashChanged;<file_sep>/app/js/setHeaderSubcategoriesContentModule.js
import {sendRequest} from "./apiModule.js";
export function setHeaderSubcategoriesContent(element, number, HeaderBottomItems, basket, router) {
let title, losung, count, subcategoriesList;
let temp = document.getElementById("temp_type_nav-item-container");
let clon = temp.content.cloneNode(true);
element.appendChild(clon);
let h1__title = element.querySelector(".nav-item-container__title");
h1__title.innerText = "Loading...";
let categoriesListItem = element.querySelector(".categories-list__item");
element.addEventListener("mouseover", (e) => {
if (e.target === element || e.target === categoriesListItem) {
let pathPart = HeaderBottomItems[number].split(" ").join("-").toLowerCase();
sendRequest('GET', `http://localhost:3000/data/goods-categories/${pathPart}.json`)
.then(response => {
title = response.title;
losung = response.losung;
count = response.count;
subcategoriesList = response.subcategoriesList;
let navItemContainerContent = element.querySelector(".nav-item-container__content");
navItemContainerContent.remove();
navItemContainerContent = document.createElement("div");
navItemContainerContent.className = "nav-item-container__content subcategories-list";
let el = element.querySelector(".nav-item-container");
let h1__title = element.querySelector(".nav-item-container__title");
h1__title.innerText = title;
let h1__losung = element.querySelector(".nav-item-container__losung");
h1__losung.innerText = losung;
let p = element.querySelector(".nav-item-container__count");
p.innerText = count + " items";
subcategoriesList.forEach(column => {
let ul = document.createElement("ul");
ul.className = "subcategories-list__column";
column.forEach(item => {
let li = document.createElement("li");
let a = document.createElement("a");
li.className = "subcategories-list__li";
a.innerText = item;
a.href = `#${item.replace(/\s+/g, '')}`;
li.appendChild(a);
ul.appendChild(li);
li.addEventListener("click", () => {
router.addHash(title, item);
})
});
navItemContainerContent.appendChild(ul);
});
el.appendChild(navItemContainerContent);
});
}
});
}<file_sep>/app/js/apiModule.js
export function sendRequest(method, url) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
resolve((JSON.parse(xhr.responseText)));
};
xhr.onerror = function (e) {
console.log("xhr-status", xhr.statusText, this.status);
reject(this.status);
};
xhr.readystatechange = function (e) {
console.log("target", e.target);
console.log("readyState", xhr.readyState);
};
xhr.send();
});
}<file_sep>/app/js/Address.js
export class Address {
constructor() {
this.firstName = "";
this.lastName = "";
this.companyName = "";
this.country = "";
this.town = "";
this.postcode = "";
this.address = "";
this.email = "";
this.phone = "";
}
getAddress() {
return {
firstName: this.firstName,
lastName: this.lastName,
companyName: this.companyName,
country: this.country,
town: this.town,
postcode: this.postcode,
address: this.address,
email: this.email,
phone: this.phone
}
}
}<file_sep>/app/js/Basket.js
export class Basket {
constructor() {
let localStorageSum = localStorage.getItem("sum");
let localStorageGoodsList = JSON.parse(localStorage.getItem("goodsList"));
this.sum = localStorageSum === null ? 0 : parseFloat(localStorageSum);
this.goodsList = localStorageGoodsList === null ? [] : localStorageGoodsList;
}
addGood(goods) {
this.sum += parseFloat(goods.price);
let findIndex = this.goodsList.findIndex(item => item.id === goods.id);
if (findIndex !== -1) {
this.goodsList[findIndex].count++;
} else {
this.goodsList.push({...goods, count: 1});
}
this.writeToLocalStorage()
}
removeGoods(goods) {
this.sum = parseFloat((this.sum - goods.price * goods.count).toFixed(2));
this.goodsList = this.goodsList.filter(item => item.id !== goods.id);
this.writeToLocalStorage()
}
getCount() {
return this.goodsList.reduce((prev, item) => prev + item.count, 0);
}
getBasket() {
return {
sum: this.sum,
goodsList: this.goodsList
}
}
changeItemCount(goods, newCount) {
if(!isNaN(newCount)){
let changeItemId = this.goodsList.findIndex(item => item.id === goods.id);
this.sum = Number((this.sum - goods.price * goods.count).toFixed(2));
this.goodsList[changeItemId].count = parseInt(newCount);
this.sum += Number((goods.price * newCount).toFixed(5));
this.writeToLocalStorage()
}
}
clear() {
this.sum = 0;
this.goodsList = [];
this.writeToLocalStorage()
}
writeToLocalStorage() {
localStorage.setItem("sum", this.sum);
localStorage.setItem("goodsList", JSON.stringify(this.goodsList));
}
/* equal(goodsList){
return goodsList.length === this.goodsList.length && goodsList.every((item,i)=>{
return item === this.goodsList[i] && item.count === this.goodsList[i].count;
});
}*/
} | 170a141ed079043667ba0eb29d83f42bd0edac66 | [
"JavaScript"
] | 8 | JavaScript | Blednykh/focusStartProject | 6fc742cad5848d03ef51013bf7fa7adbb793d790 | cec2b9a4479c2fdef3c57352e7b340cd612c1912 | |
refs/heads/master | <repo_name>aigis1/gridbf<file_sep>/app/models/main_summon.rb
class MainSummon < ActiveHash::Base
self.data = [
{ id: 1, name: '神石' },
{ id: 2, name: 'マグナ' },
{ id: 3, name: '属性石' }
]
include ActiveHash::Associations
has_many :fagrids
end
<file_sep>/app/controllers/fagrids_controller.rb
class FagridsController < ApplicationController
def index
@fagrids = Fagrid.order(id: "DESC")
end
def new
@fullauto_member = FagridMember.new
end
def create
@fullauto_member = FullautoMember.new(fagrid_params)
if @fullauto_member.valid?
@fullauto_member.save
redirect_to root_path
else
render :new
end
end
def show
@fagrid = Fagrid.find(params[:id])
@fagrids = Fagrid.all
end
def search
search_grid
@fagrids = Fagrid.order(id: "DESC")
end
def sort
search_grid
@result = @g.result # 検索条件にマッチした商品の情報を取得
end
# メンバー検索用
def msearch
members = Member.where(['member LIKE ?', "%#{params[:keyword]}%"]).pluck(:member)
render json: members
end
private
def fagrid_params
params.require(:fagrid_member).permit(:image, :quest_id, :attr_id, :job_id, :ex_ability_id, :ex_ability2_id, :limit_ability_id, :limit_ability2_id,
:member, :member2, :member3, :member4, :member5, :main_summon_id, :seraphic_id, :atk_arculm_id, :hp_arculm_id, :difficulty_id, :time_about_id, :remark)
end
def search_grid
@g = Fagrid.ransack(params[:q]) # 検索オブジェクトを生成
end
end
<file_sep>/app/models/job.rb
class Job < ActiveHash::Base
self.data = [
{ id: 1, name: 'アプサラス' },
{ id: 2, name: 'ウォーロック' },
{ id: 3, name: 'エリュシオン' },
{ id: 4, name: '義賊' },
{ id: 5, name: 'カオスルーダー' },
{ id: 6, name: 'キャバルリー' },
{ id: 7, name: 'クリュサオル' },
{ id: 8, name: 'スパルタ' },
{ id: 9, name: 'セージ' },
{ id: 10, name: 'ハウンドドッグ' },
{ id: 11, name: 'ベルセルク' },
{ id: 12, name: 'モンク' },
{ id: 13, name: 'ランバージャック' },
{ id: 14, name: 'レスラー' },
{ id: 15, name: 'ロビンフッド' },
{ id: 16, name: '-' },
{ id: 17, name: '剣豪' },
{ id: 18, name: '黒猫道士' },
{ id: 19, name: 'ザ・グローリー' },
{ id: 20, name: 'ソルジャー' },
{ id: 21, name: 'ドクター' },
{ id: 22, name: '魔法戦士' },
{ id: 23, name: 'ライジングフォース' }
]
include ActiveHash::Associations
has_many :fagrids
end<file_sep>/app/javascript/packs/grid/application.js
require('grid/ability.js')
require('grid/preview.js')
require('grid/member.js')
require('grid/subAbility.js')<file_sep>/app/models/fagrid_member.rb
class FagridMember < ApplicationRecord
belongs_to :fagrid
belongs_to :member
end
<file_sep>/app/forms/fullauto_member.rb
class FullautoMember
include ActiveModel::Model
attr_accessor :image, :quest_id, :attr_id, :job_id, :ex_ability_id, :ex_ability2_id, :limit_ability_id, :limit_ability2_id, :main_summon_id,
:seraphic_id, :atk_arculm_id, :hp_arculm_id, :difficulty_id, :time_about_id, :remark, :member, :member2, :member3, :member4, :member5
with_options presence:true do
validates :image
end
with_options numericality: { other_than: 0, message: 'Select' } do
validates :quest_id
validates :attr_id
validates :job_id
validates :ex_ability_id
validates :limit_ability_id
validates :main_summon_id
validates :seraphic_id
validates :atk_arculm_id
validates :hp_arculm_id
validates :difficulty_id
validates :time_about_id
end
def save
fagrid = Fagrid.create(quest_id: quest_id, attr_id: attr_id, job_id: job_id, ex_ability_id: ex_ability_id, ex_ability2_id: ex_ability2_id,limit_ability_id: limit_ability_id,limit_ability2_id: limit_ability2_id, main_summon_id: main_summon_id,
seraphic_id: seraphic_id, atk_arculm_id: atk_arculm_id, hp_arculm_id: hp_arculm_id, difficulty_id: difficulty_id, time_about_id: time_about_id, remark: remark, image: image)
membername1 = Member.where(member: member).first_or_create if member
membername2 = Member.where(member: member2).first_or_create if member2
membername3 = Member.where(member: member3).first_or_create if member3
membername4 = Member.where(member: member4).first_or_create if member4
membername5 = Member.where(member: member5).first_or_create if member5
FagridMember.create(fagrid_id: fagrid.id, member_id: membername1.id) if membername1
FagridMember.create(fagrid_id: fagrid.id, member_id: membername2.id) if membername2
FagridMember.create(fagrid_id: fagrid.id, member_id: membername3.id) if membername3
FagridMember.create(fagrid_id: fagrid.id, member_id: membername4.id) if membername4
FagridMember.create(fagrid_id: fagrid.id, member_id: membername5.id) if membername5
end
end<file_sep>/app/models/hp_arculm.rb
class HpArculm < ActiveHash::Base
self.data = [
{ id: 1, name: '4凸〜' },
{ id: 2, name: 'SSR' },
{ id: 3, name: 'SR' },
{ id: 4, name: '無し'}
]
include ActiveHash::Associations
has_many :fagrids
end<file_sep>/db/migrate/20201201085553_create_fagrids.rb
class CreateFagrids < ActiveRecord::Migration[6.0]
def change
create_table :fagrids do |t|
t.integer :quest_id, null: false
t.integer :attr_id, null: false
t.integer :job_id, null: false
t.integer :ex_ability_id, null: false
t.integer :ex_ability2_id
t.integer :limit_ability_id, null: false
t.integer :limit_ability2_id
t.integer :main_summon_id, null: false
t.integer :seraphic_id, null: false
t.integer :atk_arculm_id, null: false
t.integer :hp_arculm_id, null: false
t.integer :difficulty_id, null: false
t.integer :time_about_id, null: false
t.text :remark
t.timestamps
end
end
end
<file_sep>/app/javascript/grid/subAbility.js
if (document.URL.match( /new/ )) {
window.addEventListener('DOMContentLoaded', function(){
const $exAbility = document.getElementById('ex-ability')
const $exAbility2 = document.getElementById('ex-ability2')
const $limitAbility = document.getElementById('limit-ability')
const $limitAbility2 = document.getElementById('limit-ability2')
$exAbility.addEventListener('change', function(){
if ($exAbility.value.length > 0) {
if ($limitAbility2.value.length == 0){
$exAbility2.removeAttribute('style')
};
} else {
$exAbility2.setAttribute("style", "display: none;")
$exAbility2.value = ""
}
});
$limitAbility.addEventListener('change', function(){
if ($limitAbility.value.length > 0) {
if ($limitAbility2.value.length == 0){
$limitAbility2.removeAttribute('style')
};
} else {
$limitAbility2.setAttribute("style", "display: none;")
$limitAbility2.value = ""
}
});
$exAbility2.addEventListener('change', function(){
if ($exAbility2.value.length > 0) {
$limitAbility2.setAttribute("style", "display: none;")
$limitAbility2.value = ""
}
});
$limitAbility2.addEventListener('change', function(){
if ($limitAbility2.value.length > 0) {
$exAbility2.setAttribute("style", "display: none;")
$exAbility2.value = ""
}
});
});
};<file_sep>/app/models/ex_ability.rb
class ExAbility < ActiveHash::Base
self.data = [
{ id: 1, name: 'ミゼラブルミスト' },
{ id: 2, name: 'アーマーブレイク' },
{ id: 3, name: 'グラビティ' },
{ id: 4, name: 'ブラインド' },
{ id: 5, name: 'ディスペル' },
{ id: 6, name: 'アローレイン' },
{ id: 7, name: 'ソウルピルファー' },
{ id: 8, name: 'チャームボイス' },
{ id: 9, name: 'デュアルインパルス' },
{ id: 10, name: 'トレジャーハント' },
{ id: 11, name: 'レイジ' },
{ id: 12, name: 'オーラ' },
{ id: 13, name: 'リヴァイブ' },
{ id: 14, name: 'その他強化アビリティ' },
{ id: 15, name: 'その他弱体アビリティ' },
{ id: 16, name: 'その他ダメージアビリティ' },
{ id: 17, name: 'その他回復アビリティ' }
]
include ActiveHash::Associations
has_many :fagrids
end<file_sep>/app/models/limit_ability.rb
class LimitAbility < ActiveHash::Base
self.data = [
{ id: 1, name: 'その他, もしくは無し' },
{ id: 2, name: '霹靂閃電' },
{ id: 3, name: '曼珠沙華' },
{ id: 4, name: '水鳥の歌詠' },
{ id: 5, name: 'ランドグリース' },
{ id: 6, name: 'チョーク' },
{ id: 7, name: 'チェイサー' },
{ id: 8, name: 'ブラックヘイズ' },
{ id: 9, name: 'レプリケーションキャスト' },
{ id: 10, name: 'オラトリオ' },
{ id: 11, name: 'コール・オブ・アビス' },
{ id: 12, name: 'ソング・トゥ・ザ・デッド' },
{ id: 13, name: 'ひつじのうた' },
{ id: 14, name: '解放の歌声' },
{ id: 15, name: '桜門五三桐' },
{ id: 16, name: 'トレジャーハントIV' },
{ id: 17, name: 'フォーススナッチ' },
{ id: 18, name: 'ブレイクキープ' },
{ id: 19, name: 'ホワイトスモーク' },
{ id: 20, name: 'アンプレディクト' },
{ id: 21, name: 'アブソーブ' },
{ id: 22, name: 'クイックダウン' },
{ id: 23, name: 'ブラッドソード' },
{ id: 24, name: 'カオス' },
{ id: 25, name: 'ドラグラクト' },
{ id: 26, name: 'ハイ・コマンド' },
{ id: 27, name: 'バタリング・ラム' },
{ id: 28, name: 'アーセガル' },
{ id: 29, name: 'クロスガード' },
{ id: 30, name: 'チェイスブレード' },
{ id: 31, name: 'デュアルアーツ' },
{ id: 32, name: 'ディプティク' },
{ id: 33, name: 'シールドワイア' },
{ id: 34, name: 'ガーディアン' },
{ id: 35, name: 'テストゥド' },
{ id: 36, name: 'リフレクション' },
{ id: 37, name: 'シャイニングII' },
{ id: 38, name: 'ディスペル・シージ' },
{ id: 39, name: 'ベール' },
{ id: 40, name: 'ホワイトウォール' },
{ id: 41, name: 'ジャミング' },
{ id: 42, name: 'スタディエイム' },
{ id: 43, name: 'タイム・オン・ターゲット' },
{ id: 44, name: 'タクティクスコマンド' },
{ id: 45, name: 'トワイライト・ゾーン' },
{ id: 46, name: 'レイショナルショット' },
{ id: 47, name: 'アーマーブレイクII' },
{ id: 48, name: 'ウールヴヘジン' },
{ id: 49, name: 'ブレイブソウル' },
{ id: 50, name: 'ランページII' },
{ id: 51, name: 'レイジIV' },
{ id: 52, name: '岩崩拳' },
{ id: 53, name: '剛耐の型' },
{ id: 54, name: '武操術' },
{ id: 55, name: '落葉焚き' },
{ id: 56, name: '大伐断' },
{ id: 57, name: '安らぎの木漏れ日' },
{ id: 58, name: '一字構え' },
{ id: 59, name: 'ツープラトン' },
{ id: 60, name: 'ファイティングスピリット' },
{ id: 61, name: 'マイクパフォーマンス' },
{ id: 62, name: 'アクロバットヴォレイ' },
{ id: 63, name: 'エメラルドフォグ' },
{ id: 64, name: 'フォックス・リターンズ' },
{ id: 65, name: '雲散霧消' },
{ id: 66, name: '大鷲返し' },
{ id: 67, name: '無明斬' },
{ id: 68, name: '烈刀一閃' },
{ id: 69, name: 'スペシャルボム' },
{ id: 70, name: 'テネブラエ' },
{ id: 71, name: 'ムーンライト' },
{ id: 72, name: 'コルミロス' },
{ id: 73, name: 'ドゥプレクス' },
{ id: 74, name: 'エスパーダ' },
{ id: 75, name: 'ゲリーリャ' },
{ id: 76, name: 'フォーティチュード' },
{ id: 77, name: 'ブリッツバースト' },
{ id: 78, name: 'フルファイア' },
{ id: 79, name: 'アドレナリンラッシュ' },
{ id: 80, name: '鬼神の丸薬' },
{ id: 81, name: 'ニュートリエント' },
{ id: 82, name: 'マッドバイタリティ' },
{ id: 83, name: 'スペルブースト' },
{ id: 84, name: 'ドラゴンブレイク' },
{ id: 85, name: '焙烙玉' },
{ id: 86, name: 'マナバースト' },
{ id: 87, name: 'アンリーシュザフューリー' },
{ id: 88, name: 'ジェット・トゥ・ジェット' },
{ id: 89, name: 'モッシュピット' },
{ id: 90, name: '律動共振' }
]
include ActiveHash::Associations
has_many :fagrids
end<file_sep>/config/routes.rb
Rails.application.routes.draw do
root to: 'fagrids#index'
get 'fagrids/search'
get 'fagrids/sort'
resources :fagrids, only: [:index, :new, :create, :show] do
collection do
get 'msearch'
end
end
end
<file_sep>/app/models/difficulty.rb
class Difficulty < ActiveHash::Base
self.data = [
{ id: 1, name: '5凸' },
{ id: 2, name: '4凸' },
{ id: 3, name: 'ドラポン' },
{ id: 4, name: '無し' }
]
include ActiveHash::Associations
has_many :fagrids
end
<file_sep>/app/models/member.rb
class Member < ApplicationRecord
has_many :fagrid_member
has_many :fagrids, through: :fagrid_member
end
<file_sep>/app/models/fagrid.rb
class Fagrid < ApplicationRecord
has_one_attached :image
has_many :fagrid_member
has_many :members, through: :fagrid_member
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :quest
belongs_to :attr
belongs_to :job
belongs_to :ex_ability
belongs_to :limit_ability
belongs_to :main_summon
belongs_to :seraphic
belongs_to :atk_arculm
belongs_to :hp_arculm
belongs_to :difficulty
belongs_to :time_about
end
<file_sep>/app/models/seraphic.rb
class Seraphic < ActiveHash::Base
self.data = [
{ id: 1, name: '3凸' },
{ id: 2, name: '無凸' },
{ id: 3, name: '無し' }
]
include ActiveHash::Associations
has_many :fagrids
end
<file_sep>/app/models/attr.rb
class Attr < ActiveHash::Base
self.data = [
{ id: 1, name: '火' },
{ id: 2, name: '水' },
{ id: 3, name: '土' },
{ id: 4, name: '風' },
{ id: 5, name: '光' },
{ id: 6, name: '闇' }
]
include ActiveHash::Associations
has_many :fagrids
end
<file_sep>/app/javascript/grid/ability.js
if (document.URL.match( /new/ )) {
window.addEventListener('DOMContentLoaded', function(){
document.getElementById('job').addEventListener('change', function(){
$('#limit-ability').html(abilityBlank)
$('#limit-ability2').html(abilityBlank)
var $jobId = document.getElementById('job').value
if ($jobId == 1) {
$('#limit-ability').append(job1Ability);
$('#limit-ability2').append(job1Ability);
} else if ($jobId == 2) {
$('#limit-ability').append(job2Ability);
$('#limit-ability2').append(job2Ability);
} else if ($jobId == 3) {
$('#limit-ability').append(job3Ability);
$('#limit-ability2').append(job3Ability);
} else if ($jobId == 4) {
$('#limit-ability').append(job4Ability);
$('#limit-ability2').append(job4Ability);
} else if ($jobId == 5) {
$('#limit-ability').append(job5Ability);
$('#limit-ability2').append(job5Ability);
} else if ($jobId == 6) {
$('#limit-ability').append(job6Ability);
$('#limit-ability2').append(job6Ability);
} else if ($jobId == 7) {
$('#limit-ability').append(job7Ability);
$('#limit-ability2').append(job7Ability);
} else if ($jobId == 8) {
$('#limit-ability').append(job8Ability);
$('#limit-ability2').append(job8Ability);
} else if ($jobId == 9) {
$('#limit-ability').append(job9Ability);
$('#limit-ability2').append(job9Ability);
} else if ($jobId == 10) {
$('#limit-ability').append(job10Ability);
$('#limit-ability2').append(job10Ability);
} else if ($jobId == 11) {
$('#limit-ability').append(job11Ability);
$('#limit-ability2').append(job11Ability);
} else if ($jobId == 12) {
$('#limit-ability').append(job12Ability);
$('#limit-ability2').append(job12Ability);
} else if ($jobId == 13) {
$('#limit-ability').append(job13Ability);
$('#limit-ability2').append(job13Ability);
} else if ($jobId == 14) {
$('#limit-ability').append(job14Ability);
$('#limit-ability2').append(job14Ability);
} else if ($jobId == 15) {
$('#limit-ability').append(job15Ability);
$('#limit-ability2').append(job15Ability);
} else if ($jobId == 17) {
$('#limit-ability').append(job17Ability);
$('#limit-ability2').append(job17Ability);
} else if ($jobId == 18) {
$('#limit-ability').append(job18Ability);
$('#limit-ability2').append(job18Ability);
} else if ($jobId == 19) {
$('#limit-ability').append(job19Ability);
$('#limit-ability2').append(job19Ability);
} else if ($jobId == 20) {
$('#limit-ability').append(job20Ability);
$('#limit-ability2').append(job20Ability);
} else if ($jobId == 21) {
$('#limit-ability').append(job21Ability);
$('#limit-ability2').append(job21Ability);
} else if ($jobId == 22) {
$('#limit-ability').append(job22Ability);
$('#limit-ability2').append(job22Ability);
} else if ($jobId == 23) {
$('#limit-ability').append(job23Ability);
$('#limit-ability2').append(job23Ability);
};
$('#limit-ability').append(otherAbility)
$('#limit-ability2').append(otherAbility)
});
const abilityBlank = `<option value="">---</option>`
const otherAbility = `<option value="1">その他, もしくは無し</option>`
const job1Ability = '<option value="2">霹靂閃電</option> <option value="3">曼珠沙華</option> <option value="4">水鳥の歌詠</option> <option value="5">ランドグリース</option>'
const job2Ability = '<option value="6">チョーク</option> <option value="7">チェイサー</option> <option value="8">ブラックヘイズ</option> <option value="9">レプリケーションキャスト</option>'
const job3Ability = '<option value="10">オラトリオ</option> <option value="11">コール・オブ・アビス</option> <option value="12">ソング・トゥ・ザ・デッド</option> <option value="13">ひつじのうた</option> <option value="14">解放の歌声</option>'
const job4Ability = '<option value="15">桜門五三桐</option> <option value="16">トレジャーハントIV</option> <option value="17">フォーススナッチ</option> <option value="18">ブレイクキープ</option> <option value="19">ホワイトスモーク</option>'
const job5Ability = '<option value="20">アンプレディクト</option> <option value="21">アブソーブ</option> <option value="22">クイックダウン</option> <option value="23">ブラッドソード</option> <option value="24">カオス</option>'
const job6Ability = '<option value="25">ドラグラクト</option> <option value="26">ハイ・コマンド</option> <option value="27">バタリング・ラム</option>'
const job7Ability = '<option value="28">アーセガル</option> <option value="29">クロスガード</option> <option value="30">チェイスブレード</option> <option value="31">デュアルアーツ</option> <option value="32">ディプティク</option>'
const job8Ability = '<option value="33">シールドワイア</option> <option value="34">ガーディアン</option> <option value="35">テストゥド</option> <option value="36">リフレクション</option>'
const job9Ability = '<option value="37">シャイニングII</option> <option value="38">ディスペル・シージ</option> <option value="39">ベール</option> <option value="40">ホワイトウォール</option>'
const job10Ability = '<option value="41">ジャミング</option> <option value="42">スタディエイム</option> <option value="43">タイム・オン・ターゲット</option> <option value="44">タクティクスコマンド</option> <option value="45">トワイライト・ゾーン</option> <option value="46">レイショナルショット</option>'
const job11Ability = '<option value="47">アーマーブレイクII</option> <option value="48">ウールヴヘジン</option> <option value="49">ブレイブソウル</option> <option value="50">ランページII</option> <option value="51">レイジIV</option>'
const job12Ability = '<option value="52">岩崩拳</option> <option value="53">剛耐の型</option> <option value="54">武操術</option>'
const job13Ability = '<option value="55">落葉焚き</option> <option value="56">大伐断</option> <option value="57">安らぎの木漏れ日</option>'
const job14Ability = '<option value="58">一字構え</option> <option value="59">ツープラトン</option> <option value="60">ファイティングスピリット</option> <option value="61">マイクパフォーマンス</option>'
const job15Ability = '<option value="62">アクロバットヴォレイ</option> <option value="63">エメラルドフォグ</option> <option value="64">フォックス・リターンズ</option>'
const job17Ability = '<option value="65">雲散霧消</option> <option value="66">大鷲返し</option> <option value="67">無明斬</option> <option value="68">烈刀一閃</option>'
const job18Ability = '<option value="69">スペシャルボム</option> <option value="70">テネブラエ</option> <option value="71">ムーンライト</option>'
const job19Ability = '<option value="72">コルミロス</option> <option value="73">ドゥプレクス</option> <option value="74">エスパーダ</option>'
const job20Ability = '<option value="75">ゲリーリャ</option> <option value="76">フォーティチュード</option> <option value="77">ブリッツバースト</option> <option value="78">フルファイア</option>'
const job21Ability = '<option value="79">アドレナリンラッシュ</option> <option value="80">鬼神の丸薬</option> <option value="81">ニュートリエント</option> <option value="82">マッドバイタリティ</option>'
const job22Ability = '<option value="83">スペルブースト</option> <option value="84">ドラゴンブレイク</option> <option value="85">焙烙玉</option> <option value="86">マナバースト</option>'
const job23Ability = '<option value="87">アンリーシュザフューリー</option> <option value="88">ジェット・トゥ・ジェット</option> <option value="89">モッシュピット</option> <option value="90">律動共振</option>'
});
};<file_sep>/README.md
# グリッドブルーファンタジー
## グランブルーファンタジーで使っている編成を投稿しあうことで、自分手持ちの資源と照らし合わせて効率的な攻略ができるように
http://3.115.251.182/
`$ git clone https://github.com/aigis1/gridbf.git`
<!-- テスト用アカウント ログイン機能等を実装した場合は、記述しましょう。またBasic認証等を設けている場合は、そのID/Passも記述しましょう。 -->
## 利用方法
ページを訪れると、投稿されている編成が一覧できます。
条件で絞り込みたい場合は検索するボタンを、投稿するボタンを押すと投稿フォームに飛びます。
また、表示されている画像をクリックすると詳細情報を見ることができます。
## 作成理由
ゲームがリリースされてからそろそろ7年が経つゲームなので、できること、やることがどんどん増えてきています。
トライ&エラーをして攻略をするのに良い編成を探すのですが、状況は着々と変わっていきます。特に武器編成においては初心者だけでなく長年プレイしているユーザーでもしっかり把握できている人は少ないほど複雑です。
そんな中で良い編成が知りたいとなった時に調べられるところがあればいいなと思って作成しました。数十万人を超えるアクティブユーザがおり、あらゆる状況のプレイヤーの情報が有効な知識となるはずです。
いい編成ができたらそれを共有しあってより快適なプレイができればと思っています
## 機能一覧
- 編成の投稿

- 投稿された編成の一覧

- 投稿内容詳細の閲覧

- 投稿の検索機能

- 投稿時間での並び替え機能(未実装)
- 評価機能(未実装)
- 日課チェックシート(未実装)
- 目標覚書(未実装)
- ユーザー機能(未実装)
<!-- 実装した機能についてのGIFと説明 実装した機能について、それぞれどのような特徴があるのか列挙しましょう。GIFを添えることで、イメージがしやすくなります。 -->
## これから実装したい機能
- 評価機能
- 実装することで投稿数が増えた時に選択する際の一つの指針となる
- 日課チェックシート
- 項目を各自で編集して、それをセッションを利用して個人でカスタマイズできると良い
- 目標覚書
- 強化に必要な素材などをまとめておいたり、目指す編成を保存しておくなどができると良い
- ユーザー機能
- 自分の状況を公開することで団活に役立つのではないか
[データベースER図](https://user-images.githubusercontent.com/69403974/101803932-6738cf00-3b54-11eb-929f-a6b603eaf073.png)
<file_sep>/app/views/fagrids/test.rb
def search
def kenssaku
if search != ""
Origin.where(LIKE=?,params)
elsif category_id != ""
@category = Origin.where(['category_id = ?, params[:category_id'])
else
Origin.all
end
end
def category_search
@category = Origin.where(['category_id = ?, params[:category_id'])
end
end
view.rb
<%= f.label :quest_id_eq, 'バトル' %>
<%= f.collection_select :quest_id, Quest.all, :id, :name, include_blank: '指定なし' %>
members = Member.where(['member LIKE ?', "%#{params[:keyword]}%"]).pluck(:member)
<file_sep>/app/models/time_about.rb
class TimeAbout < ActiveHash::Base
self.data = [
{ id: 1, name: '〜1分' },
{ id: 2, name: '〜2分' },
{ id: 3, name: '〜3分' },
{ id: 4, name: '〜4分' },
{ id: 5, name: '〜5分' },
{ id: 6, name: '〜6分' },
{ id: 7, name: '〜7分' },
{ id: 8, name: '〜8分' },
{ id: 9, name: '〜9分' },
{ id: 10, name: '〜10分' },
{ id: 11, name: '10分〜' },
]
include ActiveHash::Associations
has_many :fagrids
end
| a7cc0fd217df35229ec0a4fa3b44c29bfa69e5f0 | [
"JavaScript",
"Ruby",
"Markdown"
] | 21 | Ruby | aigis1/gridbf | 2cac1b75c31e4e558a0cf4b98779bd6cdb28e278 | 21e2659b8b1b1d3196b3c589b89e05e403302d9d | |
refs/heads/master | <file_sep><?php
$menu00 = '';
$menu01 = '';
$menu02 = '';
if ($menu != null){
if ($menu == 'dashboard') $menu00 = 'active';
if ($menu == 'company') $menu01 = 'active';
if ($menu == 'user') $menu02 = 'active';
}
?><file_sep><!doctype html>
<html>
<head>
<title><?php echo $title; ?></title>
<link rel="stylesheet" href="<?php echo base_url().'/css/bootstrap.css'?>" />
</head>
<body>
<center>
<div class="row">
<div class="col-sm-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Ratwareid</a></li>
<li class="breadcrumb-item active" aria-current="page"> <?php echo $judul; ?></li>
</ol>
</nav>
</div>
</div>
<div class="col-sm-12">
<h2>Selamat datang di <span class="badge badge-secondary">Ratwareid - HRMS</span></h2></br>
</div>
</center>
<div class="row">
<file_sep>
<div class="col-sm-12 col-md-6">
<div class="row">
<a href="<?php echo base_url() ?>user/tambah" class="btn btn-primary" role="button" aria-pressed="true">Tambah User</a>
</div>
<div class="row">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Username</th>
<th scope="col">Password</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php
$nourut = 1;
foreach ($rows as $row) {
?>
<tr>
<th scope="row"><?php echo $nourut++; ?></th>
<td><?php echo $row->username; ?></td>
<td><?php echo $row->password; ?></td>
<td>
<a href="<?php echo base_url() ?>user/ubah/<?php echo $row->id; ?>">Edit</a>
<a href="<?php echo base_url() ?>user/delete/<?php echo $row->id; ?>">Delete</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<file_sep><?php
/**
* Created by IntelliJ IDEA.
* User: jerry
* Date: 25/01/19
* Time: 11:17
*/
class Admin_model extends CI_Model {
// nama tabel dan primary key
private $table = 'userdata';
private $pk = 'id';
public function showall() {
$q = $this->db->order_by($this->pk);
$q = $this->db->get($this->table);
return $q;
}
}
?><file_sep><style>
.border{
height: 700px;
}
</style>
<div class="border">
<div class="content-wrapper">
<?php $this->load->view('user/signpost'); ?>
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $heading ?></div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post">
<input type="hidden" name="userid" value="<?php echo $userid; ?>" />
<div class="form-group">
<label for="LabelName">Username</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username" value="<?php echo $username; ?>">
</div>
<div class="form-group">
<label for="LabelPassword">Fullname</label>
<input type="text" class="form-control" name="fullname" id="fullname" placeholder="Fullname" value="<?php echo $fullname; ?>">
</div>
<div class="form-group">
<label for="Label">Email</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Email" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<label for="Label">Password</label>
<input type="<PASSWORD>" class="form-control" name="password" id="password" placeholder="<PASSWORD>" value="<?php echo $password; ?>">
</div>
<button type="submit" class="btn btn-default">
Submit
</button>
<a href="<?php echo base_url() ?>user/">
<button type="button" class="btn btn-default">
Cancel
</button>
</a>
</form>
<?php if ($error != ''){ ?>
<br/>
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
<?php echo $error; ?>
</div>
<?php }?>
</div>
</div>
</div>
</div>
</div><file_sep><style>
.border{
height: 700px;
}
</style>
<div class="border">
<div class="col-lg-12">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">User List</div>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">No.</th>
<th scope="col">Username</th>
<th scope="col">Full Name</th>
<th scope="col">Email</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php
$nourut = 1;
foreach ($rows as $row) {
?>
<tr>
<th scope="row"><?php echo $nourut++; ?></th>
<td><?php echo $row->username; ?></td>
<td><?php echo $row->fullname; ?></td>
<td><?php echo $row->email; ?></td>
<td>
<a href="<?php echo base_url() ?>user/edit/<?php echo $row->userid; ?>">Edit</a>
<a href="<?php echo base_url() ?>user/delete/<?php echo $row->userid; ?>">Delete</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div><!-- /.col-lg-6 -->
</div>
</div><file_sep><!-- jQuery 3 -->
<script src="<?php echo base_url().'bower_components/jquery/dist/jquery.min.js'?>"></script>
<!-- jQuery UI 1.11.4 -->
<script src="<?php echo base_url().'bower_components/jquery-ui/jquery-ui.min.js'?>"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Bootstrap 3.3.7 -->
<script src="<?php echo base_url().'bower_components/bootstrap/dist/js/bootstrap.min.js'?>"></script>
<!-- Morris.js charts -->
<script src="<?php echo base_url().'bower_components/raphael/raphael.min.js'?>"></script>
<script src="<?php echo base_url().'bower_components/morris.js/morris.min.js'?>"></script>
<!-- Sparkline -->
<script src="<?php echo base_url().'bower_components/jquery-sparkline/dist/jquery.sparkline.min.js'?>"></script>
<!-- jvectormap -->
<script src="<?php echo base_url().'plugins/jvectormap/jquery-jvectormap-1.2.2.min.js'?>"></script>
<script src="<?php echo base_url().'plugins/jvectormap/jquery-jvectormap-world-mill-en.js'?>"></script>
<!-- jQuery Knob Chart -->
<script src="<?php echo base_url().'bower_components/jquery-knob/dist/jquery.knob.min.js'?>"></script>
<!-- daterangepicker -->
<script src="<?php echo base_url().'bower_components/moment/min/moment.min.js'?>"></script>
<script src="<?php echo base_url().'bower_components/bootstrap-daterangepicker/daterangepicker.js'?>"></script>
<!-- datepicker -->
<script src="<?php echo base_url().'bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js'?>"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="<?php echo base_url().'plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js'?>"></script>
<!-- Slimscroll -->
<script src="<?php echo base_url().'bower_components/jquery-slimscroll/jquery.slimscroll.min.js'?>"></script>
<!-- FastClick -->
<script src="<?php echo base_url().'bower_components/fastclick/lib/fastclick.js'?>"></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url().'dist/js/adminlte.min.js'?>"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="<?php echo base_url().'dist/js/pages/dashboard.js'?>"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo base_url().'dist/js/demo.js'?>"></script>
<script src="<?php echo base_url().'bower_components/chart.js/Chart.js'?>"></script>
<script>
$(function () {
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//BAR CHART
var bar = new Morris.Bar({
element: 'bar-chart',
resize: true,
data: [
{y: '2006', a: 100, b: 90},
{y: '2007', a: 75, b: 65},
{y: '2008', a: 50, b: 40},
{y: '2009', a: 75, b: 65},
{y: '2010', a: 50, b: 40},
{y: '2011', a: 75, b: 65},
{y: '2012', a: 100, b: 90}
],
barColors: ['#00a65a', '#f56954'],
xkey: 'y',
ykeys: ['a', 'b'],
labels: ['CPU', 'DISK'],
hideHover: 'auto'
});
})
</script>
</body>
</html>
<file_sep><style>
.border{
height: 700px;
}
</style>
<div class="border">
<div class="col-lg-12">
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">Company List</div>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">No.</th>
<th scope="col">Company Name</th>
<th scope="col">Address</th>
<th scope="col">Phone Number</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<?php
$nourut = 1;
if ($page != null) $nourut = $nourut + $page;
foreach ($data->result() as $row) {
?>
<tr>
<th scope="row"><?php echo $nourut++; ?></th>
<td><?php echo $row->company_name; ?></td>
<td><?php echo $row->company_address; ?></td>
<td><?php echo $row->company_phone; ?></td>
<td>
<a href="<?php echo base_url() ?>company/edit/<?php echo $row->company_id; ?>">Edit</a>
<a href="<?php echo base_url() ?>company/delete/<?php echo $row->company_id; ?>">Delete</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div><!-- /.col-lg-6 -->
</div>
</div><file_sep><?php
class User_model extends CI_Model {
// nama tabel dan primary key
private $table = 'm_user';
private $pk = 'userid';
// tampilkan semua data
public function tampilkanSemua() {
$q = $this->db->order_by($this->pk);
$q = $this->db->get($this->table);
return $q;
}
public function getById($userid) {
$q = $this->db->where($this->pk,$userid);
$q = $this->db->get($this->table);
return $q;
}
public function tambah($data) {
$this->db->insert($this->table, $data);
}
public function ubah($userid,$data) {
$this->db->where($this->pk, $userid);
$this->db->update($this->table, $data);
}
public function hapus($userid) {
$this->db->where($this->pk, $userid);
$this->db->delete($this->table);
}
}
<file_sep><style>
.border{
height: 700px;
}
</style>
<div class="border">
<div class="content-wrapper">
<?php $this->load->view('company/signpost'); ?>
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $heading ?></div>
<div class="panel-body">
<form action="<?php echo $action; ?>" method="post">
<input type="hidden" name="company_id" value="<?php echo $company_id; ?>" />
<div class="form-group">
<label for="LabelName">Company Name</label>
<input type="text" class="form-control" name="company_name" id="company_name" placeholder="Company Name" value="<?php echo $company_name; ?>">
</div>
<div class="form-group">
<label for="LabelPassword">Company Address</label>
<input type="text" class="form-control" name="company_address" id="company_address" placeholder="Address" value="<?php echo $company_address; ?>">
</div>
<div class="form-group">
<label for="Label">Number Contact</label>
<input type="number" class="form-control" name="company_phone" id="company_phone" placeholder="Phone Number" value="<?php echo $company_phone; ?>">
</div>
<button type="submit" class="btn btn-default">
Submit
</button>
<a href="<?php echo base_url() ?>company/">
<button type="button" class="btn btn-default">
Cancel
</button>
</a>
</form>
<?php if ($error != ''){ ?>
<br/>
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
<?php echo $error; ?>
</div>
<?php }?>
</div>
</div>
</div>
</div>
</div><file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Auth extends CI_Controller {
public function index($error = NULL) {
$data = array(
'title' => 'Welcome to Ratwareid Networks',
'action' => site_url('auth/login'),
'error' => $error,
'judul' => 'Login Panel'
);
$this->load->view('login', $data);
}
public function login() {
$this->load->model('auth_model');
$login = $this->auth_model->login($this->input->post('username'),md5($this->input->post('password')));
if ($login == 1) {
// ambil detail data
$row = $this->auth_model->data_login($this->input->post('username'), md5($this->input->post('password')));
// daftarkan session
$data = array(
'logged' => TRUE,
'username' => $row->username
);
$this->session->set_userdata($data);
// redirect ke halaman sukses
redirect(site_url('home'));
} else {
// tampilkan pesan error
$error = 'username / password salah';
$this->index($error);
redirect(site_url(''));
}
}
function logout() {
// destroy session
$this->session->sess_destroy();
// redirect ke halaman login
redirect(site_url('auth'));
}
}
/* End of file auth.php */
/* Location: ./application/controllers/auth.php */
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Admin extends CI_Controller
{
function __construct()
{
parent::__construct();
// jika belum login redirect ke login
if ($this->session->userdata('logged') <> 1) {
redirect(site_url('auth'));
}
}
public function index()
{
$this->load->model('admin_model');
$rows = $this->admin_model->showall()->result();
$data = array(
'title' => 'Ratwareid.com',
'judul' => 'Halaman Admin',
'content' => 'admin/index',
'rows' => $rows
);
$this->load->view('admin',$data);
}
}<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Company extends CI_Controller {
function __construct()
{
parent::__construct();
// jika belum login redirect ke login
if ($this->session->userdata('logged')<>1) {
redirect(site_url('auth'));
}
//load libary pagination
$this->load->library('pagination');
$this->load->model('company_model');
}
public function index()
{
$config['base_url'] = site_url('company/index'); //site url
$config['total_rows'] = $this->db->count_all('m_company'); //total row
$config['per_page'] = 10; //show record per halaman
$config["uri_segment"] = 3; // uri parameter
$choice = $config["total_rows"] / $config["per_page"];
$config["num_links"] = floor($choice);
// Membuat Style pagination untuk BootStrap v4
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['full_tag_open'] = '<div class="pagging text-center"><nav><ul class="pagination justify-content-center">';
$config['full_tag_close'] = '</ul></nav></div>';
$config['num_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['num_tag_close'] = '</span></li>';
$config['cur_tag_open'] = '<li class="page-item active"><span class="page-link">';
$config['cur_tag_close'] = '<span class="sr-only">(current)</span></span></li>';
$config['next_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['next_tagl_close'] = '<span aria-hidden="true">»</span></span></li>';
$config['prev_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['prev_tagl_close'] = '</span>Next</li>';
$config['first_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['first_tagl_close'] = '</span></li>';
$config['last_tag_open'] = '<li class="page-item"><span class="page-link">';
$config['last_tagl_close'] = '</span></li>';
$this->pagination->initialize($config);
$data['page'] = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
//panggil function get_mahasiswa_list yang ada pada mmodel mahasiswa_model.
$data['data'] = $this->company_model->getlist_paging($config["per_page"], $data['page']);
$data['pagination'] = $this->pagination->create_links();
$data['content'] = 'company/content';
$data['menu'] = 'company';
//load view mahasiswa view
$this->load->view('company',$data);
}
public function create() {
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'company',
'heading' => 'Company / Add New Company',
'error' => '',
'action' => base_url().'company/docreate',
'content' => 'company/form-input',
'company_id' => '',
'company_name' => '',
'company_address' => '',
'company_phone' => '',
'button' => 'Create'
);
$this->load->view('company',$data);
}
public function docreate() {
$data = array(
'company_name' => $this->input->post('company_name'),
'company_address' => $this->input->post('company_address'),
'company_phone' => $this->input->post('company_phone')
);
if ($data['company_name'] != null && $data['company_address'] != null){
$this->load->model('company_model');
$this->company_model->create($data);
redirect(base_url().'company');
}else{
$data = array(
'error' => 'Please fill all empty field',
'action' => base_url().'company/docreate',
'content' => 'company/form-input',
'company_name' => '',
'company_address' => '',
'company_phone' => '',
'button' => 'Create'
);
$this->load->view('company',$data);
}
}
public function edit($company_id) {
$this->load->model('user_model');
$row = $this->company_model->getById($company_id)->row();
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'company',
'heading' => 'Edit Company',
'error' => '',
'action' => base_url().'company/doedit',
'content' => 'company/form-input',
'company_id' => $row->company_id,
'company_name' => $row->company_name,
'company_address' => $row->company_address,
'company_phone' => $row->company_phone,
'button' => 'Change Data'
);
$this->load->view('company',$data);
}
public function doedit() {
//
$data = array(
'company_name' => $this->input->post('company_name'),
'company_address' => $this->input->post('company_address'),
'company_phone' => $this->input->post('company_phone')
);
$this->load->model('company_model');
$this->company_model->edit($this->input->post('company_id'),$data);
redirect(base_url().'company');
}
public function delete($company_id) {
$this->load->model('company_model');
$this->company_model->delete($company_id);
redirect(base_url().'company');
}
}
<file_sep># HRMS
Human Resource Management System <br/>
Supported and Thanks to : Codeigniter, Bootstrap , PHP , MYSQLI , AdminLTE <br/>
How to Install :<br/>
- Please open <a href="https://github.com/ratwareid/hrms/blob/master/hrms.sql">hrms.sql</a> and use that for creating table<br/>
- Please setup database on file database.php (application/config/database.php) <br/>
- Please setup config.php (application/config/config.php) change $config['base_url'] = ''; into $config['base_url'] = 'http://localhost/hrms/'; or change hrms into your project folder name <br/>
- Do Login using username : admin , password : <PASSWORD>
<br/>/////////////////////////////////////////////////////////////// <br/>
#Version : 0.0.1 <br/>
Date Commit : 13/2/2019 <br/>
Notes : <br/>
- First Commit <br/>
- Please setup database on file database.php (application/config/database.php) <br/>
- Please open hrms.sql and use that for creating table<br/>
Best Regards Ratwareid <br/>
<br/>///////////////////////////////////////////////////////////////<br/>
<br/>///////////////////////////////////////////////////////////////<br/>
#Version : 0.0.2 <br/>
Date Commit : 15/2/2019 <br/>
Notes : <br/>
- Fixing Menu <br/>
- Added Master Company <br/>
<br/>///////////////////////////////////////////////////////////////<br/>
<br/>///////////////////////////////////////////////////////////////<br/>
#Version : 0.0.3 <br/>
Date Commit : 29/4/2019 <br/>
Notes : <br/>
- Remove unused file <br/>
- Add Pagination master company <br/>
- Added Master User <br/>
<br/>///////////////////////////////////////////////////////////////<br/>
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
function __construct()
{
parent::__construct();
// jika belum login redirect ke login
if ($this->session->userdata('logged')<>1) {
redirect(site_url('auth'));
}
}
public function index()
{
$this->load->model('user_model');
$rows = $this->user_model->tampilkanSemua()->result();
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'user',
'judul' => 'Halaman User',
'content' => 'user/content',
'rows' => $rows
);
// echo 'ini adalah controller user';
$this->load->view('user',$data);
}
public function create() {
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'user',
'heading' => 'User / Add New User',
'action' => base_url().'user/docreate',
'content' => 'user/form-input',
'userid' => '',
'username' => '',
'fullname' => '',
'email' => '',
'password' => '',
'error' => ''
);
$this->load->view('user',$data);
}
public function docreate() {
// warning : aksi ini tanpa ada validasi form
$data = array(
'username' => $this->input->post('username'),
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password'))
);
$this->load->model('user_model');
$this->user_model->tambah($data);
redirect(base_url().'user');
}
public function edit($userid) {
$this->load->model('user_model');
$row = $this->user_model->getById($userid)->row();
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'company',
'heading' => 'Edit Company',
'error' => '',
'action' => base_url().'user/doedit',
'content' => 'user/form-input',
'username' => $row->username,
'fullname' => $row->fullname,
'email' => $row->email,
'password' => '',
'userid' => $row->userid,
);
$this->load->view('user',$data);
}
public function doedit() {
// warning : aksi ini tanpa ada validasi form
$updatepassword = array(
'username' => $this->input->post('username'),
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'password' => md5($this->input->post('password'))
);
$tidakupdatepassword = array(
'username' => $this->input->post('username'),
'fullname' => $this->input->post('fullname'),
'email' => $this->input->post('email'),
'username' => $this->input->post('username'),
);
$data = trim($this->input->post('password'))<>''?$updatepassword:$tid<PASSWORD>password;
$this->load->model('user_model');
$this->user_model->ubah($this->input->post('userid'),$data);
redirect(base_url().'user');
}
public function delete($userid) {
$this->load->model('user_model');
$this->user_model->hapus($userid);
redirect(base_url().'user');
}
}
/* End of file user.php */
/* Location: ./application/controllers/user.php */
<file_sep><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
// jika belum login redirect ke login
if ($this->session->userdata('logged')<>1) {
redirect(site_url('auth'));
}
}
public function index()
{
$this->load->model('user_model');
$rows = $this->user_model->tampilkanSemua()->result();
$data = array(
'title' => 'Ratwareid.com',
'menu' => 'dashboard',
'judul' => 'Halaman Home',
'content' => 'home/content',
'rows' => $rows
);
// echo 'ini adalah controller user';
$this->load->view('home',$data);
}
}
<file_sep><?php
$this->load->view('resource/ratwareid/v1/header');
$this->load->view('resource/ratwareid/v1/footer');
?>
<center>
<div class="col-sm-4 " align="left">
<form method="post" action="<?php echo $action ?>">
<div class="form-group">
<label for="exampleInputuserid1">Your username</label>
<input type="username" class="form-control" name="username" aria-describedby="usernameHelp" placeholder="Enter Username">
<small id="usernameHelp" class="form-text text-muted">We'll never share your data with anyone else.</small>
</div>
<div class="form-group" method="post" action="">
<label for="exampleInputPassword1">Password</label>
<input type="<PASSWORD>" class="form-control" name="password" placeholder="<PASSWORD>">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="remember">Remember me</label>
</div>
<button name="submit" type="submit" value="Login" class="btn btn-primary">Login</button>
</form>
<? echo $error; ?>
</div>
</center>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.6.6
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: 02 Mei 2019 pada 10.30
-- Versi Server: 5.7.17-log
-- PHP Version: 5.6.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 */;
--
-- Database: `hrms`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `m_company`
--
CREATE TABLE `m_company` (
`company_id` int(20) NOT NULL,
`company_name` varchar(40) NOT NULL,
`company_address` varchar(40) NOT NULL,
`company_phone` varchar(20) NOT NULL,
`company_logo` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data untuk tabel `m_company`
--
INSERT INTO `m_company` (`company_id`, `company_name`, `company_address`, `company_phone`, `company_logo`) VALUES
(4, 'PT. Mustibisa Corp', 'Jl. <NAME>', '0213213213', ''),
(5, 'PT Apapun Jadi', 'Jalan Cipinang Raya', '08123123123123', ''),
(6, 'PT. Sumber Makmur', 'Jl. Jatinegara timur IV ', '0', ''),
(10, 'PT Apapun Jadiin Kuy', 'Jl. merdeka 6', '0', ''),
(11, 'PT. Sumber berkah', 'Jl. jatinegara timur 3', '2147483647', ''),
(12, 'PT. Tembang kenangan', 'Jl. tubagus angke ', '2147483647', ''),
(13, 'PT. Berkahilah', 'Jl. Kebembeng 3', '089984343434', '');
-- --------------------------------------------------------
--
-- Struktur dari tabel `m_library`
--
CREATE TABLE `m_library` (
`lib_id` int(11) NOT NULL,
`lib_name` varchar(255) NOT NULL,
`lib_header` varchar(255) NOT NULL,
`lib_detail` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- Struktur dari tabel `m_user`
--
CREATE TABLE `m_user` (
`userid` int(20) NOT NULL,
`username` varchar(10) NOT NULL,
`fullname` varchar(40) NOT NULL,
`email` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`f_active` tinyint(1) DEFAULT NULL,
`f_delete` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `m_user`
--
INSERT INTO `m_user` (`userid`, `username`, `fullname`, `email`, `password`, `f_active`, `f_delete`) VALUES
(21, 'admin', 'Administrator', '<EMAIL>', '<PASSWORD>', NULL, NULL);
/*!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><div class="content-wrapper">
<?php $this->load->view('user/signpost'); ?>
<?php $this->load->view('resource/search-bar'); ?>
<div class="col-lg-12">
<a href="<?php echo base_url() ?>user/create">
<button type="button" class="btn btn-default">
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
Create
</button>
</a>
</div><br/><br/>
<?php $this->load->view('user/list_box'); ?>
<center>
<div class="col-lg-12">
<div class="col">
<!--Tampilkan pagination-->
</div>
</div>
</center>
</div>
</div>
<file_sep><div class="content-wrapper">
<?php $this->load->view('home/signpost'); ?>
<?php $this->load->view('home/alert'); ?>
<div class="panel panel-default">
<div class="panel-body">
<?php $this->load->view('home/chart_bar'); ?>
<?php $this->load->view('home/announce'); ?>
</div>
</div>
</div>
<file_sep><?php
class Company_model extends CI_Model {
// nama tabel dan primary key
private $table = 'm_company';
private $pk = 'company_id';
// tampilkan semua data
// public function getlist() {
// $q = $this->db->order_by($this->pk);
// $q = $this->db->get($this->table);
// return $q;
// }
public function getlist_paging($limit, $start){
$q = $this->db->get('m_company', $limit, $start);
return $q;
}
public function getById($company_id) {
$q = $this->db->where($this->pk,$company_id);
$q = $this->db->get($this->table);
return $q;
}
public function create($data) {
$this->db->insert($this->table, $data);
}
public function edit($company_id,$data) {
$this->db->where($this->pk, $company_id);
$this->db->update($this->table, $data);
}
public function delete($company_id) {
$this->db->where($this->pk, $company_id);
$this->db->delete($this->table);
}
}
<file_sep><div class="content-wrapper">
<?php $this->load->view('admin/signpost'); ?>
</div>
<file_sep><?php
if ($this->session->userdata('logged')<>1) {
redirect(site_url('auth'));
}
//header
$this->load->view('resource/ratwareid/v2/header_admin');
$this->load->view('resource/ratwareid/v2/sidepanel');
//body
//$this->load->view($content);
$this->load->view('resource/ratwareid/v2/example_admin');
//$this->load->view('resource/ratwareid/v2/example_main');
//$this->load->view('resource/ratwareid/v2/example_blank');
//footer
$this->load->view('resource/ratwareid/v2/copyright');
$this->load->view('resource/ratwareid/v2/sidebar_setting');
$this->load->view('resource/ratwareid/v2/footer_admin');
?>
<file_sep><?php
if ($this->session->userdata('logged')<>1) {
redirect(site_url('auth'));
}
//header
$this->load->view('resource/header_admin');
$this->load->view('resource/sidepanel-header');
$this->load->view('resource/sidepanel-menu');
//body
$this->load->view($content);
//footer
$this->load->view('resource/copyright');
$this->load->view('resource/sidebar_setting');
$this->load->view('home/footer_home');
?>
| 82f76bee06b9e203d153c7b386e9c1eefa028b3b | [
"Markdown",
"SQL",
"PHP"
] | 24 | PHP | ratwareid/hrms | d38fecb6c7c5c3dbe4f39f2d6f2a53c3063a46a1 | 5477e8a7b5bb2c99bfe45dc533ecb87d28ebe972 | |
refs/heads/master | <file_sep>//
// ViewController.swift
// Hangman
//
// Created by <NAME> on 10/13/15.
// Copyright © 2015 cs198-ios. All rights reserved.
//
import UIKit
class HangmanViewController: UIViewController {
@IBOutlet weak var hangmanState: UIImageView!
@IBOutlet weak var newGameButton: UIButton!
@IBOutlet weak var guessField: UITextField!
@IBOutlet weak var guessButton: UIButton!
@IBOutlet weak var guessesLabel: UILabel!
@IBOutlet weak var wordLabel: UILabel!
var game: Hangman!
override func viewDidLoad() {
game = Hangman()
game.start()
hangmanState.image = UIImage(named: "hangman1")
wordLabel.text = game.knownString
hangmanState.accessibilityHint = "0 incorrect guesses"
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func newGame(sender: AnyObject) {
game = Hangman()
game.start()
hangmanState.image = UIImage(named: "hangman1")
wordLabel.text = game.knownString
game.incorrectGuesses = 0
guessesLabel.text = ""
hangmanState.accessibilityHint = "0 incorrect guesses"
}
func displayAlert(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {}
}
@IBAction func makeGuess(sender: AnyObject) {
if game.incorrectGuesses >= 6 {
displayAlert("Game Over", message: "You've reached the maximum number of guesses. Please press New Game")
return
}
if guessField.text!.characters.count != 1 {
displayAlert("Invalid Entry", message: "Please only entred one character")
return
}
if game.guessLetter((guessField.text?.uppercaseString)!) {
guessesLabel.text = game.guesses()
wordLabel.text = game.knownString
if !game.knownString!.containsString("_") {
displayAlert("You Won!", message: "To start a new game, press New Game")
}
} else {
guessesLabel.text = game.guesses()
var imageTitle = "hangman" + (game.incorrectGuesses+1).description
hangmanState.accessibilityHint = game.incorrectGuesses.description + " incorrect guesses"
if game.incorrectGuesses >= 6 {
displayAlert("Game Over", message: "You've reached the maximum number of guesses. Please press New Game")
imageTitle = "hangman7"
hangmanState.accessibilityHint = "6 incorrect guesses"
}
hangmanState.image = UIImage(named: imageTitle)
}
}
}
| 20e6208edd947a6ad94631c00d37069997c7edb1 | [
"Swift"
] | 1 | Swift | dan-golden/ios-decal-proj2 | c59254c293f43ce2ca153fa65f6da267ca45f333 | 6c11a5a728f8d78802e8dbe7b8a34761f7a39521 | |
refs/heads/master | <repo_name>sudeep0901/raviraj-laravel-api<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/customers', function () {
return view('welcome');
});
Route::get('/admin', function () {
return view('admin.index');
});
Route::group(['middleware'=>'cors','prefix'=>'api'], function (){
Route::get('book', 'BookController@index');
Route::post('book', 'BookController@createBook');
});
Route::resource('customer', 'CustomerController');
Auth::routes();
Route::get('/home', 'HomeController@index');
// Route::put('users/{id}', 'AdminUsersController@update');
Route::group(['prefix'=>'view'], function (){
Route::resource('admin/users', 'AdminUsersController');
});
Route::group(['prefix'=>'api'], function (){
Route::resource('admin/users', 'AdminUsersController');
Route::resource('role', 'RolesController');
Route::resource('customer', 'CustomerController');
});
// Route::put('admin/users/{id}/edit', 'AdminUsersController@update');
// Route::group(['middleware'=>'cors','prefix'=>'api'], function (){
// Route::get('admin/users', 'AdminUsersController@index');
// Route::get('admin/users', 'AdminUsersController@edit');
// Route::post('admin/users', 'AdminUsersController@create');
// });
<file_sep>/app/Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Address;
class Customer extends Model
{
//
}
| 56288f61d2b062664bcb35f79858a41969ec8335 | [
"PHP"
] | 2 | PHP | sudeep0901/raviraj-laravel-api | bf337b0a94714cd2ac3b130243b8f684c110790c | 77cf51e67ad4e199ad8b89a939ce1a29a649d142 | |
refs/heads/master | <repo_name>jamesdesigns/Unit13-HotelBooking<file_sep>/Unit13-HotelBooking/js/main.js
// COLLAPSIBLE MENU
var acc = document.getElementsByClassName("accordion");
var m;
for (m = 0; m < acc.length; m++) {
acc[m].onclick = function(){
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
}
}
// JavaScript Document
var hotelInfo;
var details;
var xhr = new XMLHttpRequest();
xhr.open('GET', "data.json", true);
xhr.responseType = 'text';
xhr.send();
xhr.onload = function() {
if(xhr.status === 200) {
hotelInfo = JSON.parse(xhr.responseText);
// console.log(hotelInfo);
display(0, 0);
} // end if
} // end function
function display(x, roomIndex){
// console.log(x);
// document.getElementById('name').innerHTML = hotelInfo[x].name;
document.getElementById('name').innerHTML = hotelInfo.hotel[x].room[roomIndex].name;
document.getElementById('desc').innerHTML = hotelInfo.hotel[x].room[roomIndex].description;
document.getElementById('photo').src = hotelInfo.hotel[x].room[roomIndex].photo;
document.getElementById('weekday').innerHTML = hotelInfo.hotel[x].room[roomIndex].cost.weekday;
document.getElementById('weekend').innerHTML = hotelInfo.hotel[x].room[roomIndex].cost.weekend;
details = "";
for(i=0; i<hotelInfo.hotel[x].room[roomIndex].details.length; i++){
// console.log(hotelInfo.hotel[x].room[roomIndex].details[i]);
details += "<p>"+hotelInfo.hotel[x].room[roomIndex].details[i]+"</p>";
} // End of Loop
document.getElementById('details').innerHTML = details;
} // End of Function
| 2fca7e98621618c6f92ff029c522fbddc59e6092 | [
"JavaScript"
] | 1 | JavaScript | jamesdesigns/Unit13-HotelBooking | 35a885f14ac1dba0f248a31afcbf44c6bf467d4e | 6b46c34fc4983e8f985ff0651d5be7fa3ab5f40f | |
refs/heads/master | <repo_name>chiaoyaaaaa/DrBC<file_sep>/BetLearn.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: fanchangjun
"""
from __future__ import print_function, division
import tensorflow as tf
import networkx as nx
import time
import sys
import numpy as np
from tqdm import tqdm
import graph
import utils
import PrepareBatchGraph
import metrics
import pickle as cp
import os
EMBEDDING_SIZE = 128 # embedding dimension
LEARNING_RATE = 0.0001
BATCH_SIZE = 16
max_bp_iter = 5 # neighbor propagation steps
REG_HIDDEN = (int)(EMBEDDING_SIZE / 2) # hidden dimension in the MLP decoder
initialization_stddev = 0.01
NUM_MIN = 100 # minimum training scale (node set size)
NUM_MAX = 200 # maximum training scale (node set size)
MAX_ITERATION = 10000 # training iterations
n_valid = 100 # number of validation graphs
aggregatorID = 2 # how to aggregate node neighbors, 0:sum; 1:mean; 2:GCN(weighted sum)
combineID = 1 # how to combine self embedding and neighbor embedding,
# 0:structure2vec(add node feature and neighbor embedding)
#1:graphsage(concatenation); 2:gru
JK = 1 # layer aggregation, #0: do not use each layer's embedding;
#aggregate each layer's embedding with:
# 1:max_pooling; 2:min_pooling;
# 3:mean_pooling; 4:LSTM with attention
node_feat_dim = 3 # initial node features, [Dc,1,1]
aux_feat_dim = 4 # extra node features in the hidden layer in the decoder, [Dc,CI1,CI2,1]
INF = 100000000000
class BetLearn:
def __init__(self):
# init some parameters
self.g_type = 'powerlaw' #'erdos_renyi', 'powerlaw', 'small-world', 'barabasi_albert'
self.embedding_size = EMBEDDING_SIZE
self.learning_rate = LEARNING_RATE
self.reg_hidden = REG_HIDDEN
self.TrainSet = graph.py_GSet()
self.TestSet = graph.py_GSet()
self.utils = utils.py_Utils()
self.TrainBetwList = []
self.TestBetwList = []
self.metrics = metrics.py_Metrics()
self.inputs = dict()
self.activation = tf.nn.leaky_relu #leaky_relu relu selu elu
self.ngraph_train = 0
self.ngraph_test = 0
# [node_cnt, node_feat_dim]
self.node_feat = tf.placeholder(tf.float32, name="node_feat")
# [node_cnt, aux_feat_dim]
self.aux_feat = tf.placeholder(tf.float32, name="aux_feat")
# [node_cnt, node_cnt]
self.n2nsum_param = tf.sparse_placeholder(tf.float64, name="n2nsum_param")
# [node_cnt,1]
self.label = tf.placeholder(tf.float32, shape=[None,1], name="label")
# sample node pairs to compute the ranking loss
self.pair_ids_src = tf.placeholder(tf.int32, shape=[1,None], name='pair_ids_src')
self.pair_ids_tgt = tf.placeholder(tf.int32, shape=[1,None], name='pair_ids_tgt')
self.loss, self.trainStep, self.betw_pred, self.node_embedding, self.param_list = self.BuildNet()
self.saver = tf.train.Saver(max_to_keep=None)
config = tf.ConfigProto(device_count={"CPU": 8}, # limit to num_cpu_core CPU usage
inter_op_parallelism_threads=100,
intra_op_parallelism_threads=100,
log_device_placement=False)
config.gpu_options.allow_growth = True
self.session = tf.Session(config=config)
self.session.run(tf.global_variables_initializer())
def BuildNet(self):
# [node_feat_dim, embed_dim]
w_n2l = tf.Variable(tf.truncated_normal([node_feat_dim, self.embedding_size], stddev=initialization_stddev), tf.float32, name="w_n2l")
# [embed_dim, embed_dim]
p_node_conv = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="p_node_conv")
if combineID == 1: # 'graphsage'
# [embed_dim, embed_dim]
p_node_conv2 = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="p_node_conv2")
# [2*embed_dim, embed_dim]
p_node_conv3 = tf.Variable(tf.truncated_normal([2 * self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="p_node_conv3")
elif combineID ==2: #GRU
w_r = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w_r")
u_r = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u_r")
w_z = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w_z")
u_z = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u_z")
w = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w")
u = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u")
# [embed_dim, reg_hidden]
h1_weight = tf.Variable(tf.truncated_normal([self.embedding_size, self.reg_hidden], stddev=initialization_stddev), tf.float32,name="h1_weight")
# [reg_hidden+aux_feat_dim, 1]
h2_weight = tf.Variable(tf.truncated_normal([self.reg_hidden+aux_feat_dim, 1], stddev=initialization_stddev), tf.float32,name="h2_weight")
# [reg_hidden, 1]
last_w = h2_weight
# [node_cnt, node_feat_dim]
node_size = tf.shape(self.n2nsum_param)[0]
node_input = self.node_feat
#[node_cnt, embed_dim]
input_message = tf.matmul(tf.cast(node_input, tf.float32), w_n2l)
lv = 0
# [node_cnt, embed_dim], no sparse
cur_message_layer = self.activation(input_message)
cur_message_layer = tf.nn.l2_normalize(cur_message_layer, axis=1)
if JK: # # 1:max_pooling; 2:min_pooling; 3:mean_pooling; 4:LSTM with attention
cur_message_layer_JK = cur_message_layer
if JK == 4: #LSTM init hidden layer
w_r_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w_r_JK")
u_r_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u_r_JK")
w_z_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w_z_JK")
u_z_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u_z_JK")
w_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="w_JK")
u_JK = tf.Variable(tf.truncated_normal([self.embedding_size, self.embedding_size], stddev=initialization_stddev), tf.float32,name="u_JK")
#attention matrix
JK_attention = tf.Variable(tf.truncated_normal([self.embedding_size, 1], stddev=initialization_stddev), tf.float32,name="JK_attention")
#attention list
JK_attention_list =[]
JK_Hidden_list=[]
cur_message_layer_list = []
cur_message_layer_list.append(cur_message_layer)
JK_Hidden = tf.truncated_normal(tf.shape(cur_message_layer), stddev=initialization_stddev)
# max_bp_iter steps of neighbor propagation
while lv < max_bp_iter:
lv = lv + 1
# [node_cnt, node_cnt]*[node_cnt, embed_dim] = [node_cnt, embed_dim]
n2npool = tf.sparse_tensor_dense_matmul(tf.cast(self.n2nsum_param, tf.float64), tf.cast(cur_message_layer, tf.float64))
n2npool = tf.cast(n2npool, tf.float32)
# [node_cnt, embed_dim] * [embedding, embedding] = [node_cnt, embed_dim], dense
node_linear = tf.matmul(n2npool, p_node_conv)
if combineID == 0: # 'structure2vec'
# [node_cnt, embed_dim] + [node_cnt, embed_dim] = [node_cnt, embed_dim], return tensed matrix
merged_linear = tf.add(node_linear, input_message)
# [node_cnt, embed_dim]
cur_message_layer = self.activation(merged_linear)
if JK==1:
cur_message_layer_JK = tf.maximum(cur_message_layer_JK,cur_message_layer)
elif JK==2:
cur_message_layer_JK = tf.minimum(cur_message_layer_JK, cur_message_layer)
elif JK==3:
cur_message_layer_JK = tf.add(cur_message_layer_JK, cur_message_layer)
elif JK == 4:
cur_message_layer_list.append(cur_message_layer)
elif combineID == 1: # 'graphsage'
# [node_cnt, embed_dim] * [embed_dim, embed_dim] = [node_cnt, embed_dim], dense
cur_message_layer_linear = tf.matmul(tf.cast(cur_message_layer, tf.float32), p_node_conv2)
# [[node_cnt, embed_dim] [node_cnt, embed_dim]] = [node_cnt, 2*embed_dim], return tensed matrix
merged_linear = tf.concat([node_linear, cur_message_layer_linear], 1)
# [node_cnt, 2*embed_dim]*[2*embed_dim, embed_dim] = [node_cnt, embed_dim]
cur_message_layer = self.activation(tf.matmul(merged_linear, p_node_conv3))
if JK == 1:
cur_message_layer_JK = tf.maximum(cur_message_layer_JK,cur_message_layer)
elif JK == 2:
cur_message_layer_JK = tf.minimum(cur_message_layer_JK, cur_message_layer)
elif JK == 3:
cur_message_layer_JK = tf.add(cur_message_layer_JK, cur_message_layer)
elif JK == 4:
cur_message_layer_list.append(cur_message_layer)
elif combineID==2: #gru
r_t = tf.nn.relu(tf.add(tf.matmul(node_linear,w_r), tf.matmul(cur_message_layer,u_r)))
z_t = tf.nn.relu(tf.add(tf.matmul(node_linear,w_z), tf.matmul(cur_message_layer,u_z)))
h_t = tf.nn.tanh(tf.add(tf.matmul(node_linear,w), tf.matmul(r_t*cur_message_layer,u)))
cur_message_layer = (1-z_t)*cur_message_layer + z_t*h_t
cur_message_layer = tf.nn.l2_normalize(cur_message_layer, axis=1)
if JK == 1:
cur_message_layer_JK = tf.maximum(cur_message_layer_JK,cur_message_layer)
elif JK == 2:
cur_message_layer_JK = tf.minimum(cur_message_layer_JK, cur_message_layer)
elif JK == 3:
cur_message_layer_JK = tf.add(cur_message_layer_JK, cur_message_layer)
elif JK == 4:
cur_message_layer_list.append(cur_message_layer)
cur_message_layer = tf.nn.l2_normalize(cur_message_layer, axis=1)
if JK == 1 or JK == 2:
cur_message_layer = cur_message_layer_JK
elif JK == 3:
cur_message_layer = cur_message_layer_JK / (max_bp_iter+1)
elif JK == 4:
for X_value in cur_message_layer_list:
#[node_cnt,embed_size]
r_t_JK = tf.nn.relu(tf.add(tf.matmul(X_value, w_r_JK), tf.matmul(JK_Hidden, u_r_JK)))
z_t_JK = tf.nn.relu(tf.add(tf.matmul(X_value, w_z_JK), tf.matmul(JK_Hidden, u_z_JK)))
h_t_JK = tf.nn.tanh(tf.add(tf.matmul(X_value, w_JK), tf.matmul(r_t_JK * JK_Hidden, u_JK)))
JK_Hidden = (1 - z_t_JK) * h_t_JK + z_t_JK * JK_Hidden
JK_Hidden = tf.nn.l2_normalize(JK_Hidden, axis=1)
#[max_bp_iter+1,node_cnt,embed_size]
JK_Hidden_list.append(JK_Hidden)
# [max_bp_iter+1,node_cnt,1] = [node_cnt,embed_size]*[embed_size,1]=[node_cnt,1]
attention = tf.nn.tanh(tf.matmul(JK_Hidden, JK_attention))
JK_attention_list.append(attention)
cur_message_layer = JK_Hidden
# [max_bp_iter+1,node_cnt,1]
JK_attentions = tf.reshape(JK_attention_list, [max_bp_iter + 1, node_size, 1])
cofficient = tf.nn.softmax(JK_attentions, axis=0)
JK_Hidden_list = tf.reshape(JK_Hidden_list, [max_bp_iter + 1, node_size, self.embedding_size])
# [max_bpr_iter+1,node_cnt,1]* [max_bp_iter + 1,node_cnt,embed_size] = [max_bp_iter + 1,node_cnt,embed_size]
#[max_bp_iter + 1,node_cnt,embed_size]
result = cofficient * JK_Hidden_list
cur_message_layer = tf.reduce_sum(result, 0)
cur_message_layer = tf.reshape(cur_message_layer, [node_size, self.embedding_size])
cur_message_layer = tf.nn.l2_normalize(cur_message_layer, axis=1)
# node embedding, [node_cnt, embed_dim]
embed_s_a = cur_message_layer
# decoder, two-layer MLP
hidden = tf.matmul(embed_s_a, h1_weight)
last_output = self.activation(hidden)
last_output = tf.concat([last_output, self.aux_feat], axis=1)
betw_pred = tf.matmul(last_output, last_w)
# [pair_size, 1]
labels = tf.nn.embedding_lookup(self.label, self.pair_ids_src) - tf.nn.embedding_lookup(self.label, self.pair_ids_tgt)
preds = tf.nn.embedding_lookup(betw_pred, self.pair_ids_src) - tf.nn.embedding_lookup(betw_pred, self.pair_ids_tgt)
loss = self.pairwise_ranking_loss(preds, labels)
trainStep = tf.train.AdamOptimizer(self.learning_rate).minimize(loss)
return loss, trainStep, betw_pred,embed_s_a,tf.trainable_variables()
def pairwise_ranking_loss(self, preds, labels):
"""Logit cross-entropy loss with masking."""
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=tf.sigmoid(labels))
loss = tf.reduce_sum(loss, axis=1)
return tf.reduce_mean(loss)
def gen_graph(self, num_min, num_max):
cur_n = np.random.randint(num_max - num_min + 1) + num_min
if self.g_type == 'erdos_renyi':
g = nx.erdos_renyi_graph(n=cur_n, p=0.15)
elif self.g_type == 'small-world':
g = nx.connected_watts_strogatz_graph(n=cur_n, k=8, p=0.1)
elif self.g_type == 'barabasi_albert':
g = nx.barabasi_albert_graph(n=cur_n, m=4)
elif self.g_type == 'powerlaw':
g = nx.powerlaw_cluster_graph(n=cur_n, m=4, p=0.05)
return g
def gen_new_graphs(self, num_min, num_max):
print('\ngenerating new training graphs...')
self.ClearTrainGraphs()
for i in tqdm(range(1000)):
g = self.gen_graph(num_min, num_max)
self.InsertGraph(g, is_test=False)
bc = self.utils.Betweenness(self.GenNetwork(g))
bc_log = self.utils.bc_log
self.TrainBetwList.append(bc_log)
def ClearTrainGraphs(self):
self.ngraph_train = 0
self.TrainSet.Clear()
self.TrainBetwList = []
self.TrainBetwRankList = []
def ClearTestGraphs(self):
self.ngraph_test = 0
self.TestSet.Clear()
self.TestBetwList = []
def InsertGraph(self, g, is_test):
if is_test:
t = self.ngraph_test
self.ngraph_test += 1
self.TestSet.InsertGraph(t, self.GenNetwork(g))
else:
t = self.ngraph_train
self.ngraph_train += 1
self.TrainSet.InsertGraph(t, self.GenNetwork(g))
def PrepareValidData(self):
print('\ngenerating validation graphs...')
sys.stdout.flush()
self.ClearTestGraphs()
for i in tqdm(range(n_valid)):
g = self.gen_graph(NUM_MIN, NUM_MAX)
self.InsertGraph(g, is_test=True)
bc = self.utils.Betweenness(self.GenNetwork(g))
self.TestBetwList.append(bc)
def SetupBatchGraph(self,g_list):
prepareBatchGraph = PrepareBatchGraph.py_PrepareBatchGraph(aggregatorID)
prepareBatchGraph.SetupBatchGraph(g_list)
self.inputs['n2nsum_param'] = prepareBatchGraph.n2nsum_param
self.inputs['node_feat'] = prepareBatchGraph.node_feat
self.inputs['aux_feat'] = prepareBatchGraph.aux_feat
self.inputs['pair_ids_src'] = prepareBatchGraph.pair_ids_src
self.inputs['pair_ids_tgt'] = prepareBatchGraph.pair_ids_tgt
assert (len(prepareBatchGraph.pair_ids_src) == len(prepareBatchGraph.pair_ids_tgt))
return prepareBatchGraph.idx_map_list
def SetupTrain(self, g_list, label_log):
self.inputs['label'] = label_log
self.SetupBatchGraph(g_list)
def SetupPred(self, g_list):
idx_map_list = self.SetupBatchGraph(g_list)
return idx_map_list
def Predict(self, g_list):
idx_map_list = self.SetupPred(g_list)
my_dict=dict()
my_dict[self.n2nsum_param]=self.inputs['n2nsum_param']
my_dict[self.aux_feat] = self.inputs['aux_feat']
my_dict[self.node_feat] = self.inputs['node_feat']
result = self.session.run([self.betw_pred], feed_dict=my_dict)
idx_map = idx_map_list[0]
result_output = []
result_data = result[0]
for i in range(len(result_data)):
if idx_map[i] >= 0: # corresponds to nodes with 0.0 betw_log value
result_output.append(np.power(10,-result_data[i][0]))
else:
result_output.append(0.0)
return result_output
def Fit(self):
g_list, id_list = self.TrainSet.Sample_Batch(BATCH_SIZE)
Betw_Label_List = []
for id in id_list:
Betw_Label_List += self.TrainBetwList[id]
label = np.resize(Betw_Label_List, [len(Betw_Label_List), 1])
self.SetupTrain(g_list, label)
my_dict=dict()
my_dict[self.n2nsum_param]=self.inputs['n2nsum_param']
my_dict[self.aux_feat] = self.inputs['aux_feat']
my_dict[self.node_feat] = self.inputs['node_feat']
my_dict[self.label] = self.inputs['label']
my_dict[self.pair_ids_src] = np.reshape(self.inputs['pair_ids_src'], [1, len(self.inputs['pair_ids_src'])])
my_dict[self.pair_ids_tgt] = np.reshape(self.inputs['pair_ids_tgt'], [1, len(self.inputs['pair_ids_tgt'])])
result = self.session.run([self.loss, self.trainStep], feed_dict=my_dict)
loss = result[0]
return loss / len(g_list)
def Train(self):
self.PrepareValidData()
self.gen_new_graphs(NUM_MIN, NUM_MAX)
save_dir = './models'
VCFile = '%s/ValidValue.csv' % (save_dir)
f_out = open(VCFile, 'w')
for iter in range(MAX_ITERATION):
TrainLoss = self.Fit()
start = time.clock()
if iter and iter % 5000 == 0:
self.gen_new_graphs(NUM_MIN, NUM_MAX)
if iter % 500 == 0:
if (iter == 0):
N_start = start
else:
N_start = N_end
frac_topk, frac_kendal = 0.0, 0.0
test_start = time.time()
for idx in range(n_valid):
run_time, temp_topk, temp_kendal = self.Test(idx)
frac_topk += temp_topk / n_valid
frac_kendal += temp_kendal / n_valid
test_end = time.time()
f_out.write('%.6f, %.6f\n' %(frac_topk, frac_kendal)) # write vc into the file
f_out.flush()
print('\niter %d, Top0.01: %.6f, kendal: %.6f'%(iter, frac_topk, frac_kendal))
print('testing %d graphs time: %.2fs' % (n_valid, test_end - test_start))
N_end = time.clock()
print('500 iterations total time: %.2fs' % (N_end - N_start))
print('Training loss is %.4f' % TrainLoss)
sys.stdout.flush()
model_path = '%s/nrange_iter_%d_%d_%d.ckpt' % (save_dir, NUM_MIN, NUM_MAX,iter)
self.SaveModel(model_path)
f_out.close()
def Test(self, gid):
g_list = [self.TestSet.Get(gid)]
start = time.time()
betw_predict = self.Predict(g_list)
end = time.time()
betw_label = self.TestBetwList[gid]
run_time = end - start
topk = self.metrics.RankTopK(betw_label,betw_predict, 0.01)
kendal = self.metrics.RankKendal(betw_label,betw_predict)
return run_time, topk, kendal
def findModel(self):
VCFile = './models/ValidValue.csv'
vc_list = []
EarlyStop_start = 2
EarlyStop_length = 1
num_line = 0
for line in open(VCFile):
data = float(line.split(',')[0].strip(',')) #0:topK; 1:kendal
vc_list.append(data)
num_line += 1
if num_line > EarlyStop_start and data < np.mean(vc_list[-(EarlyStop_length+1):-1]):
best_vc = num_line
break
best_model_iter = 500 * best_vc
best_model = './models/nrange_iter_%d.ckpt' % (best_model_iter)
return best_model
def EvaluateSynData(self, data_test, model_file=None): # test synthetic data
if model_file == None: # if user do not specify the model_file
model_file = self.findModel()
print('The best model is :%s' % (model_file))
sys.stdout.flush()
self.LoadModel(model_file)
n_test = 100
frac_run_time, frac_topk, frac_kendal = 0.0, 0.0, 0.0
self.ClearTestGraphs()
f = open(data_test, 'rb')
ValidData = cp.load(f)
TestGraphList = ValidData[0]
self.TestBetwList = ValidData[1]
for i in tqdm(range(n_test)):
g = TestGraphList[i]
self.InsertGraph(g, is_test=True)
run_time, topk, kendal = self.test(i)
frac_run_time += run_time/n_test
frac_topk += topk/n_test
frac_kendal += kendal/n_test
print('\nRun_time, Top1%, Kendall tau: %.6f, %.6f, %.6f'% (frac_run_time, frac_topk, frac_kendal))
return frac_run_time, frac_topk, frac_kendal
def EvaluateRealData(self, model_file, data_test, label_file): # test real data
g = nx.read_weighted_edgelist(data_test)
sys.stdout.flush()
self.LoadModel(model_file)
betw_label = []
for line in open(label_file):
betw_label.append(float(line.strip().split()[1]))
self.TestBetwList.append(betw_label)
start = time.time()
self.InsertGraph(g, is_test=True)
end = time.time()
run_time = end - start
g_list = [self.TestSet.Get(0)]
start1 = time.time()
betw_predict = self.Predict(g_list)
end1 = time.time()
betw_label = self.TestBetwList[0]
run_time += end1 - start1
top001 = self.metrics.RankTopK(betw_label, betw_predict, 0.01)
top005 = self.metrics.RankTopK(betw_label, betw_predict, 0.05)
top01 = self.metrics.RankTopK(betw_label, betw_predict, 0.1)
kendal = self.metrics.RankKendal(betw_label, betw_predict)
self.ClearTestGraphs()
return top001, top005, top01, kendal, run_time
def SaveModel(self, model_path):
self.saver.save(self.session, model_path)
print('model has been saved success!')
def LoadModel(self, model_path):
self.saver.restore(self.session, model_path)
print('restore model from file successfully')
def GenNetwork(self, g): # networkx2four
edges = g.edges()
if len(edges) > 0:
a, b = zip(*edges)
A = np.array(a)
B = np.array(b)
else:
A = np.array([0])
B = np.array([0])
return graph.py_Graph(len(g.nodes()), len(edges), A, B) | e80eaa5db2eb8ef0b0ac986dd7fbdba6848e30c1 | [
"Python"
] | 1 | Python | chiaoyaaaaa/DrBC | b8a84db280e941d27484e338cbfc736774f6a5a6 | d4393c20aeece6fca944d85778196405bee21b76 | |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 15:11:35 2021
@author: Hania
"""
import os
import time
import logging
import sys
import shutil
import numpy as np
import json
import pickle
from sklearn.calibration import CalibratedClassifierCV
def save_configs(cfgs_list, directory):
# stores config files in the experiment dir
timestamp = time.strftime('%Y-%m-%d-%H-%M')
for config_file in cfgs_list:
filename = f"{timestamp}-{os.path.basename(config_file)}"
shutil.copyfile(config_file, os.path.join(directory, filename))
def save_as_json(obj, saving_dir, filename, nexp=None):
# saves with json but uses a timestamp
## nexp = optional neptune experiment
timestamp = time.strftime('%Y-%m-%d-%H-%M')
if isinstance(obj, dict):
for key in obj.keys():
if isinstance(obj[key], np.ndarray):
obj[key] = obj[key].tolist()
with open(os.path.join(saving_dir, f'{timestamp}-{filename}'), 'w') as f:
json.dump(obj, f, indent=2)
if nexp:
nexp.log_artifact(os.path.join(saving_dir, f'{timestamp}-{filename}'))
def pickle_and_log_artifact(obj, saving_dir, filename, nexp=None):
timestamp = time.strftime('%Y-%m-%d-%H-%M')
with open(os.path.join(saving_dir, f'{timestamp}-{filename}.pickle'), 'wb') as f:
pickle.dump(obj, f)
if nexp is not None:
nexp.log_artifact(os.path.join(saving_dir, f'{timestamp}-{filename}.pickle'))
def save_predictions(x, y, cv_split, test_x, test_y, model, saving_dir):
timestamp = time.strftime('%Y-%m-%d-%H-%M')
def _save_to_file(true_label, predicted_probabilities, filename):
# if predicted_probabilities is None:
# predicted_probabilities = [None, ] * len(smiles)
try:
os.makedirs(saving_dir)
except FileExistsError:
pass
with open(os.path.join(saving_dir, f"{timestamp}-{filename}"), 'w') as fid:
fid.write('has_bird\tbird_probability\n')
# print((predicted_probabilities))
# print(np.shape(predicted_probabilities))
if np.shape(predicted_probabilities)[1]==1:
pp = predicted_probabilities[:,0];
else:
pp = predicted_probabilities[:,1];
for true, proba in zip(true_label, pp): #predicted_probabilities[:,1]
fid.write(f"{true}\t{proba}\n")
# test data
# predicted = model.predict(test_x)
try:
proba = model.predict_proba(test_x)
except (AttributeError, RuntimeError):
#proba = None
clf = CalibratedClassifierCV(model.fitted_pipeline_) # !!! zmiana dla LinearSVC. to samo jak dla SVC probability=True
clf.fit(x,y)
proba = clf.predict_proba(test_x)
_save_to_file(test_y, proba, f'test.predictions')
# training data
for idx, (_, indices) in enumerate(cv_split):
this_x = x[indices]
this_y = y[indices]
# this_smiles = smiles[indices]
# predicted = model.predict(this_x) # klasy mnie nie interesują
try:
proba = model.predict_proba(this_x)
except (AttributeError, RuntimeError):
#proba = None
proba = clf.predict_proba(this_x)
_save_to_file(this_y, proba, f'train-valid-{idx}.predictions')
# moje
def my_save_to_file(true_label, predicted_probabilities, filename, saving_dir):
#timestamp = saving_dir[-16:] #time.strftime('%Y-%m-%d-%H-%M')
#print(timestamp)
try:
os.makedirs(saving_dir)
except FileExistsError:
pass
with open(os.path.join(saving_dir, f"{filename}"), 'w') as fid: #{timestamp}-
fid.write('has_bird\tbird_probability\n')
# print((predicted_probabilities))
# print(np.shape(predicted_probabilities))
for true, proba in zip(true_label, predicted_probabilities):
fid.write(f"{true}\t{proba}\n")
class LoggerWrapper:
def __init__(self, path='.'):
"""
Wrapper for logging.
Allows to replace sys.stderr.write so that error massages are redirected do sys.stdout and also saved in a file.
use: logger = LoggerWrapper(); sys.stderr.write = logger.log_errors
:param: path: directory to create log file
"""
# count spaces so that the output is nicely indented
self.trailing_spaces = 0
# create the log file
timestamp = time.strftime('%Y-%m-%d-%H-%M')
self.filename = os.path.join(path, f'{timestamp}.log')
try:
# os.mknod(self.filename)
with open(self.filename,"w") as f:
pass
except FileExistsError:
pass
# configure logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-6s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=self.filename,
filemode='w')
formatter = logging.Formatter('%(name)-6s: %(levelname)-8s %(message)s')
# make a handler to redirect stuff to std.out
self.logger = logging.getLogger('')
self.logger.setLevel(logging.INFO) # bacause matplotlib throws lots of debug messages
self.console = logging.StreamHandler(sys.stdout)
self.console.setLevel(logging.INFO)
self.console.setFormatter(formatter)
self.logger.addHandler(self.console)
def log_errors(self, msg):
msg = msg.strip('\n') # don't add extra enters
if msg == ' ' * len(msg): # if you only get spaces: don't print them, but do remember
self.trailing_spaces += len(msg)
elif len(msg) > 1:
self.logger.error(' ' * self.trailing_spaces + msg)
self.trailing_spaces = 0
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 13:29:58 2021
@author: Hania
"""
# IMPORTY
import joblib
import os
import numpy as np
import librosa
import time
def funkcja_reprezentacja(path_wav, data_settype, representation_type, if_scaler, repr_1d_summary, summary_1d, sr, chunk_length_ms, \
n_fft, win_length, hop_length, window, f_min, f_max, n_mels, N, step, Np, K, tm, flock, tlock, nr_nagr_pocz, wielkosc_batcha):
'''
Jest to funkcja zawierająca cały potrzebny kod z pliku 'reprezentacja śmieci/Untitled1', bez zbędnych printów, komentarzy itd.
Args:
te wszystkie parametry wejściowe co powyżej, opisane w miarę w mainie
Returns:
file_names_train_set - nazwy nagrań wchodzące w skład zbioru
indices - indeksy chunksów wybrane z poszczególnych nagrań
info_chunksy - informacje o wybranych chunksach - te dane co wcześniej w dataframe, ale tylko dla wybranych chunksów
['chunk_ids', 'chunk_start', 'chunk_end', 'has_bird', 'chunks_species', 'call_id', 'has_unknown', 'has_noise']
representation_type - - to co na wejściu było, jaki jeden z pięciu typów reprezentacji
repr_full - wybrana reprezentacja dla każdego z wybranych chunksów z nagrań. Rozmiary:
spektrogram: 1 nagranie - chunksy x 63 x 148
mel-spektrogram: 1 nagranie - chunksy x 60 x 148
multitaper: 1 nagranie - chunksy x 64 x 149
8_classic: 1 nagranie - chunksy x 1-4 x 8
8_classic_plus_MIR: 1 nagranie - chunksy x 1-4 x 39
'''
## FUNKCJE
def my_spektrogram(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, scaler = None):
stft = librosa.stft(y, n_fft=n_fft, win_length=win_length, hop_length=hop_length, window= window) # krótkoczasowa transformata fouriera STFT
stft1 = librosa.amplitude_to_db(np.abs(stft)**2) # kwadrat wartości bezwzględnej plus przerzucenie na skalę decybelową
freqs = librosa.core.fft_frequencies(n_fft=n_fft, sr=sr) # wyznaczenie częstotliwości
x, = np.where( freqs >= min(freqs[(freqs >= f_min)]))
j, = np.where( freqs <= max(freqs[(freqs <= f_max)]))
stft1 = stft1[min(x):max(j),] # stft tylko w wybranym zakresie
#repr1_spectro = stft1
if np.shape(stft1)[1]!= 148:
stft1 = np.pad(stft1, ((0, 0), (0, 148 - np.shape(stft1)[1])), 'constant', constant_values=(-100))
print("padding do ",np.shape(stft1))
if (scaler!=None):
return scaler.transform(stft1) #repr1_spectro
else:
return stft1
def my_melspektrogram(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, n_mels, scaler = None):
stft = librosa.stft(np.array(y), n_fft=n_fft, win_length=win_length, hop_length= hop_length, window=window)
abs2_stft = (stft.real*stft.real) + (stft.imag*stft.imag)
melspect = librosa.feature.melspectrogram(y=None, S=abs2_stft, sr=sr, n_mels= n_mels, fmin = f_min, fmax=f_max, hop_length=hop_length, n_fft=n_fft)
repr2_melspec = 0.5 * librosa.amplitude_to_db(melspect, ref=1.0)
if np.shape(repr2_melspec)[1]!= 148:
repr2_melspec = np.pad(repr2_melspec, ((0, 0), (0, 148 - np.shape(repr2_melspec)[1])), 'constant', constant_values=(-50))
if (scaler!=None):
return scaler.transform(repr2_melspec) #repr1_spectro
else:
return repr2_melspec
'''
def my_multitaper(y, N, step, Np, K, tm, flock, tlock, f_min, f_max, scaler = None):
result5b = libtfr.tfr_spec(y, N = N, step = step, Np = Np, K = 2, tm = tm, flock = flock, tlock = tlock)
freqs, ind = libtfr.fgrid(sr, N, fpass=(f_min,f_max))
repr3_multitaper = librosa.amplitude_to_db(result5b[ind,]); # tylko interesujące nas pasmo, w log
#stft1 = librosa.amplitude_to_db(np.abs(stft)**2)
if np.shape(repr3_multitaper)[1]!= 149:
repr3_multitaper = np.pad(repr3_multitaper, ((0, 0), (0, 149 - np.shape(repr3_multitaper)[1])), 'constant', constant_values=(-100))
if (scaler!=None):
return scaler.transform(repr3_multitaper ) #repr1_spectro
else:
return repr3_multitaper
'''
def FeatureSpectralFlux(X): #https://www.audiocontentanalysis.org/code/audio-features/spectral-flux-2/
# difference spectrum (set first diff to zero)
X = np.c_[X[:, 0], X]
afDeltaX = np.diff(X, 1, axis=1)
# flux
vsf = np.sqrt((afDeltaX**2).sum(axis=0)) / X.shape[0]
return vsf[1:] # pozbycie się pierwszego elementu, który zawsze jest zerem , np.squeeze(vsf[1:]) if isSpectrum else
def classic_base(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, scaler4 = None):
S1 = np.abs(librosa.stft(np.array(y), n_fft=n_fft, win_length=win_length, hop_length= hop_length, window=window))
freqs = librosa.core.fft_frequencies(n_fft=n_fft, sr=sr)
o, = np.where( freqs >= min(freqs[(freqs >= f_min)]))
j, = np.where( freqs <= max(freqs[(freqs <= f_max)]))
freqs1 = freqs[min(o):max(j),]
S = S1[min(o):max(j),]
param_0 = np.sum(S, axis=0) #librosa.feature.spectral_bandwidth(S=S, p = 1) # moc sygnału. Ale z wartości absolutnej spektorgramu, bez tego kwadratu jeszcz
param_1 = librosa.feature.spectral_centroid(S=S, freq=freqs1) # centroid https://www.mathworks.com/help/audio/ref/spectralcentroid.html
param_2 = np.power(librosa.feature.spectral_bandwidth(S=S, freq=freqs1, p = 2),2) # 2 rzędu
param_3 = np.power(librosa.feature.spectral_bandwidth(S=S, freq=freqs1, p = 3),3) # 3 rzędu
param_4 = np.power(librosa.feature.spectral_bandwidth(S=S, freq=freqs1, p = 4),4) # 4 rzędu
skosnosc = param_3[0] / np.power(param_2[0],1.5) # https://www.mathworks.com/help/audio/ref/spectralskewness.html #skosnosc2 = skew(S, axis=0)
kurtoza = param_4[0]/ np.power(param_2[0],2) - 3 #kurtoza2 = kurtosis(S, axis=0)
plaskosc = librosa.feature.spectral_flatness(S=S) #gmean(S_squared)/np.mean(S_squared)
return param_0, param_1, param_2, param_3, param_4, skosnosc, kurtoza, plaskosc, S
def my_8_classic(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, summary_1d, scaler4 = None): ## TO DO scalers
param_0, param_1, param_2, param_3, param_4, skosnosc, kurtoza, plaskosc, _ = classic_base(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, scaler4)
nb_summary = np.sum(summary_1d)
paramsy = [[[] for _ in range(8)] for _ in range(nb_summary)]
idx = 0
for m in range(np.shape(summary_1d)[0]):
if summary_1d[m]:
f = getattr(np, repr_1d_summary[m])
paramsy[idx]=[f(param_0), f(param_1), f(param_2), f(param_3), f(param_4), f(skosnosc), f(kurtoza), f(plaskosc)]
idx += 1
if (scaler4!=None):
return scaler4.transform(paramsy)
else:
return paramsy
def my_8_classic_plus_MIR(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, summary_1d, scaler5 = None): ## TO DO scalers
param_0, param_1, param_2, param_3, param_4, skosnosc, kurtoza, plaskosc, S = classic_base(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, scaler4)
nb_summary = np.sum(summary_1d)
stft = librosa.stft(np.array(y), n_fft=n_fft, win_length=win_length, hop_length= hop_length, window=window)
abs2_stft = (stft.real*stft.real) + (stft.imag*stft.imag)
melspect = librosa.feature.melspectrogram(y=None, S=abs2_stft, sr=sr, n_mels= n_mels, fmin = f_min, fmax=f_max, hop_length=hop_length, n_fft=n_fft)
mfccs =librosa.feature.mfcc(S=librosa.power_to_db(melspect), n_mfcc=12)
mfcc_delta = librosa.feature.delta(mfccs)
zcr = sum(librosa.feature.zero_crossing_rate(y, frame_length=win_length, hop_length= hop_length)) # ZCR can be interpreted as a measure of the noisiness of a signal. For example, it usually exhibits higher values in the case of noisy signals. It is also known to reflect, in a rather coarse manner, the spectral characteristics of a signal. std to recognize speech vs music
contrast = librosa.feature.spectral_contrast(S=S, hop_length=hop_length, n_fft=n_fft, n_bands = 2, fmin = f_min)
rolloff = librosa.feature.spectral_rolloff(S=S, hop_length=hop_length, n_fft=n_fft, roll_percent=0.85)
rms = librosa.feature.rms(S=S, hop_length=hop_length, frame_length = 124)
spectral_flux = FeatureSpectralFlux(S)
np.shape(rms)
paramsy = [[[] for _ in range(39)] for _ in range(nb_summary)]
idx = 0
for m in range(np.shape(summary_1d)[0]):
if summary_1d[m]:
f = getattr(np, repr_1d_summary[m]) # która statystyka wybrana repr_1d_summary = ['min', 'max', 'mean', 'std']
paramsy_mir = [f(param_0), f(param_1), f(param_2), f(param_3), f(param_4), f(skosnosc), f(kurtoza), f(plaskosc)]
paramsy_mir.extend(f(mfccs, axis = 1).tolist())
paramsy_mir.extend(f(mfcc_delta, axis = 1).tolist())
paramsy_mir.extend([f(zcr)])
paramsy_mir.extend(f(contrast, axis = 1).tolist())
paramsy_mir.extend([f(rolloff), f(rms), f(spectral_flux)])
paramsy[idx]= paramsy_mir
idx += 1
if (scaler5!=None):
return scaler5.transform(paramsy)
else:
return paramsy
# nie powinno mieć to wszystko train w nazwie, no ale już trudno. Chodzi o dowolny dataset który będzie na wejściu
# z funkcji wczytanie:
file_names_train_set = data_settype[0]
indices = data_settype[1]
result_dataframe_train = data_settype[2] # trzeba powyciągać tylko interesujące nas chunksy
df_to_np = result_dataframe_train.to_numpy() # bo nie umiem sobie poradiś jak jest to df, wiele funkcji które chcę użyć nie działa
repr_full = [[] for _ in range(np.shape(file_names_train_set)[0])]
#repr_full1, repr_full2, repr_full3 = [[] for _ in range(np.shape(file_names_train_set)[0])],[[] for _ in range(np.shape(file_names_train_set)[0])],[[] for _ in range(np.shape(file_names_train_set)[0])]
#repr_full4, repr_full5 = [[] for _ in range(np.shape(file_names_train_set)[0])], [[] for _ in range(np.shape(file_names_train_set)[0])]
info_chunksy = [[[] for _ in range(8)] for _ in range(np.shape(file_names_train_set)[0])] # 8 kolumn w dataframie było
print(file_names_train_set)
# by nie wczytywać scalerów przy każdym chunku albo nagraniu. True - mamy już wyznaczone scalery, i będziemy wszystko normalizować scalerami z traina. Jeśli false, to bez normalizacji:
path_main = os.path.join('C:\\','Users','szaro','Desktop','jupyter')
scaler1 = joblib.load(os.path.join(path_main,'scaler','scaler_spektrogram')) if if_scaler==True else None
scaler2 = joblib.load(os.path.join(path_main,'scaler','scaler_mel_spektrogram')) if if_scaler==True else None
'''scaler3 = joblib.load('scaler_multitaper') if if_scaler==True else None '''
scaler4 = joblib.load(os.path.join(path_main,'scaler','scaler_8_classic')) if if_scaler==True else None
scaler5 = joblib.load(os.path.join(path_main,'scaler','scaler_8_classic_plus_MIR')) if if_scaler==True else None
# k - kolejne nagrania w zbiorze
for k in range(nr_nagr_pocz, nr_nagr_pocz+ wielkosc_batcha): #np.shape(file_names_train_set)[0]): #np.shape(file_names_train_set)[0]): #np.shape(file_names_train_set)[0]): # 87 dla zbioru train len(file_names_train_set)
##### pętla do wycięgnięcia info o interesujących chunksach
empty_list = np.array([[] for _ in range(np.shape(indices[k])[0])]) #np.array([[] for _ in range(np.shape(indices[k])[0])])
# warunki: bo może się zdarzyć że macierz tablica pustych elementów będzie w tych dwóch 'chunks_species', 'call_id', i wtedy np.take nie działa
if not any(df_to_np[k][4]) and not any(df_to_np[k][5]):
info_chunksy[k] = [np.take(df_to_np[k][i],indices[k]) for i in [0,1,2,3]] + [empty_list, empty_list] + [np.take(df_to_np[k][i],indices[k]) for i in [6, 7]]
print(np.shape(info_chunksy[k][5]), 'no calls at all')
elif not any(df_to_np[k][5]):
info_chunksy[k] = [np.take(df_to_np[k][i],indices[k]) for i in [0,1,2,3,4]] + [empty_list] + [np.take(df_to_np[k][i],indices[k]) for i in [6, 7]]
print(np.shape(info_chunksy[k][5]), 'no calls of interest')
else:
info_chunksy[k] = [np.take(df_to_np[k][i],indices[k]) for i in [0,1,2,3,4,5,6,7]]
start_time = time.time()
if representation_type=='spektrogram':
representation = np.empty([np.shape(indices[k])[0], 63, 148])
if representation_type=='mel-spektrogram':
representation = np.empty([np.shape(indices[k])[0], 60, 148])
'''representation3 = np.empty([np.shape(indices[k])[0], 64, 149])'''
if representation_type=='8_classic':
representation = np.empty([np.shape(indices[k])[0], np.sum(summary_1d), 8])
if representation_type=='8_classic_plus_MIR':
representation = np.empty([np.shape(indices[k])[0], np.sum(summary_1d), 39])
##### a to już pętla do reprezentacji, pojedyncze chunksy
for num, i in enumerate(indices[k]): # przykładowo 262 dla pierwszego nagrania w zbiorze train, bo tyle mamy tam chunksów
# wczytanie chunka naszego półsekundowego:
y, sr = librosa.load(path_wav + '/'+ file_names_train_set[k], sr = 44100, offset = result_dataframe_train['chunk_start'][k][i]/sr, duration = chunk_length_ms/1000)
if representation_type=='spektrogram':
####### reprezentacja 1 ------- 63 x 148 ------ SPEKTROGRAM
representation[num] = my_spektrogram(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, scaler1)
if representation_type=='mel-spektrogram':
####### reprezentacja 2 (3 V3) - mel spektrogram ------- 60 x 148 ------
representation[num] = my_melspektrogram(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, n_mels, scaler2)
####### reprezentacja 3 (5b) - multitaper o większej rozdzielczości ------- 64 x 149 ------
# Ale tak naprawdę to nie jest multitaper, ale coś innego, nie wiem w sumie do końca co. Multitaper + Time-frequency reassignement spectrogram
'''representation3[num] = my_multitaper(y, N, step, Np, K, tm, flock, tlock, f_min, f_max, scaler3) '''
if representation_type=='8_classic':
representation[num] = my_8_classic(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, summary_1d, scaler4)
if representation_type=='8_classic_plus_MIR':
representation[num] = my_8_classic_plus_MIR(y, n_fft, win_length, hop_length, window, sr, f_min, f_max, summary_1d, scaler5)
repr_full[k] = representation
print(k,'-', file_names_train_set[k], '- chunks:', np.shape(indices[k])[0], '- time:', time.time()-start_time)
return [file_names_train_set , indices, info_chunksy, repr_full] # repr_full3, representation_type
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue May 25 12:59:30 2021
@author: Hania
z best_model_from_random.py
do sprawdzenia modelu wybranego z random searcha. Fit na trainie, early stopping dzięki walidowi.
"""
import config
import numpy as np
from keras import backend as K
from keras.wrappers.scikit_learn import KerasClassifier
K.set_image_data_format('channels_last')
from sklearn.metrics import average_precision_score, make_scorer
from sklearn.metrics import roc_auc_score, average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
#from config_agi import parse_model_config
from saving_utils import save_predictions, save_as_json, LoggerWrapper
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from useful_func_cnn import wczyt_dane_moje, make_cnn_model1, av_precision2, av_precision, make_cnn_bulbul, make_cnn_github2019, make_cnn_grid_corr, wczytaj_testy
#chosen_repr = 'spektrogram'
#chosen_cnn = 'bulbul'
import os
import pickle
import time
import sys
import tensorflow as tf
import json
#import tensorflow as tf
from tensorflow.compat.v1.keras.backend import set_session
config2 = tf.compat.v1.ConfigProto()
config2.gpu_options.per_process_gpu_memory_fraction = 0.5
set_session(tf.compat.v1.Session(config=config2))
# python best_model_from_random.py reprezentacja link_najlepsze_par ile_epok
# python best_model_check.py spektrogram ..\results\grid\spektrogram\2021-05-13-00-05\best_params.json 50
# python best_model_check.py spektrogram ..\results\grid\spektrogram\2021-05-19-23-05\best_params.json 100
if __name__=='__main__':
# Load configs
chosen_repr = sys.argv[1] # 'spektrogram' #
with open(sys.argv[2], 'r') as fp:
best_params = json.load(fp)
epochs = int(sys.argv[3] )
exp_dir = os.path.join("..","results","PR", f"{chosen_repr}", time.strftime('%Y-%m-%d-%H-%M'))
try:
os.makedirs(exp_dir)
except FileExistsError:
pass
start_time = time.time()
logger_wrapper = LoggerWrapper(exp_dir)
sys.stderr.write = logger_wrapper.log_errors
logger_wrapper.logger.info(f'Running {sys.argv}')
cv_split, dX, dy, di, dX_test, dy_test, di_test, cv, X_val, y_val, train_X, train_y = wczyt_dane_moje(chosen_repr, config, 'wlasc')
print(chosen_repr)
if chosen_repr=="spektrogram":
in_shape = (63, 148, 1)
if chosen_repr=="mel-spektrogram":
in_shape = (60, 148, 1)
dX_resh = dX.reshape(dX.shape[0], in_shape[0], in_shape[1], 1).astype('float32') # trzeba wrócić z liniowego, które miało isć do podst. klasyf -> do obrazka 2d
input_shape = (np.shape(dX_resh)[1], np.shape(dX_resh)[2], np.shape(dX_resh)[3]) # wielkoc obrazka, 1 kanał, na końcu podawany
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
print("Fit model on training data")
y_val = y_val.astype(int)
train_y = train_y.astype(int)
X_val_resh = X_val.reshape(X_val.shape[0],in_shape[0], in_shape[1], 1).astype('float32')
train_X_resh = train_X.reshape(train_X.shape[0], in_shape[0], in_shape[1], 1).astype('float32')
model = make_cnn_grid_corr(input_shape = best_params['input_shape'],
lr = best_params['lr'],
filters = best_params['filters'],
drop_out = best_params['drop_out'],
layers = best_params['layers'],
if_dropout = best_params['if_dropout'],
dense_layer_sizes = best_params['dense_layer_sizes']
# activation_function = best_params['activation_function']
) #input_shape = best_params['input_shape'])
my_callbacks = [
tf.keras.callbacks.EarlyStopping(monitor="val_auc", mode="max", patience=3, restore_best_weights = True),
]
result = model.fit(train_X_resh, train_y, validation_data = (X_val_resh,y_val), epochs=best_params['epochs'],
batch_size=best_params['batch_size'],callbacks = my_callbacks, verbose = 1)
# %%
# wczytanie testu
testing_features, testing_target = wczytaj_testy(chosen_repr)
testing_features_resh = testing_features.reshape(testing_features.shape[0], in_shape[0], in_shape[1], 1).astype('float32')
# zapis predykcji
save_predictions(dX_resh, dy, cv_split, testing_features_resh, testing_target, model, exp_dir)
y_preds = model.predict_proba(testing_features_resh)
# %%
# serialize weights to HDF5
model.save(os.path.join(exp_dir,"my-model.h5"))
print("Saved model to disk")
all_scores = {}
all_scores['test_AUC_PR'] = average_precision_score(testing_target, y_preds) #scorer(model, dX_test, dy_test)
all_scores['test_AUC_ROC'] = roc_auc_score(testing_target, y_preds)
print('Z GRIDA: ',all_scores)
logger_wrapper.logger.info('z grida')
logger_wrapper.logger.info(all_scores)
# zapisanie historii, by dało się wyrysować krzywe uczenia w przyszłosci , loss i pr_auc
with open(os.path.join(exp_dir,'history.pckl'), 'wb') as file_pi:
pickle.dump(result.history, file_pi)
# jak wczytać:
#f = open('history.pckl', 'rb')
# = pickle.load(f)
#f.close()
model_json = (model.to_json(indent=0))
with open(os.path.join(exp_dir,"architecture-only-refit.json"), "w") as json_file:
json_file.write(model_json)
# wyrys krzywych roc auc i pr auc
prec_nb, recall_nb, _ = precision_recall_curve(testing_target, y_preds)
fpr_nb, tpr_nb, _ = roc_curve(testing_target, y_preds)
fig = plt.figure(figsize=(10,10))
plt.rcParams.update({'font.size': 22})
plt.title('AUC PR')
plt.plot(recall_nb, prec_nb, 'b', label = 'CNN AUC = %0.2f%% ' % (100*average_precision_score(testing_target, y_preds)))
plt.legend(loc = 'upper right')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('Precyzja (Precision)')
plt.xlabel('Czułość (Recall)')
#plt.show()
fig.savefig(os.path.join(exp_dir,'AUC-PR-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
fig = plt.figure(figsize=(10,10))
plt.rcParams.update({'font.size': 22})
plt.title('AUC ROC')
plt.plot(fpr_nb, tpr_nb, 'b', label = 'CNN AUC = %0.2f%%' % (100*roc_auc_score(testing_target, y_preds)))
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('Wskaźnik czułości (True Positive Rate)')
plt.xlabel('Odsetek fałszywie pozytywnych alarmów (False Positive Rate)')
#plt.show()
fig.savefig(os.path.join(exp_dir,'AUC-ROC-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
# wyrys krzywych uczenia dla loss i pr auc
# summarize history for loss
fig = plt.figure(figsize=(10,10))
plt.plot(result.history['loss'])
plt.plot(result.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Koszt (loss)')
plt.xlabel('Liczba epok')
plt.legend(['trening','walidacja'], loc='upper right')
# plt.show()
fig.savefig(os.path.join(exp_dir,'uczenie-loss-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
#auc_nr = 'auc_'+str(int(n_iter) + 1)
fig = plt.figure(figsize=(10,10))
plt.plot(result.history['auc'])
plt.plot(result.history['val_auc'])
plt.title('Model PR AUC')
plt.ylabel('Pole pod krzywą PR')
plt.xlabel('Liczba epok')
plt.legend(['trening','walidacja'], loc='lower right')
#plt.show()
fig.savefig(os.path.join(exp_dir,'uczenie-PR-AUC-refit' + time.strftime('%Y-%m-%d-%H-%M')))
<file_sep>folder na pliki lokalne pythonowe
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Apr 22 13:54:13 2021
@author: Hania
"""
from sklearn.metrics import average_precision_score
from keras import backend as K
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten #Activation,
from keras.layers import Conv2D, MaxPooling2D
from sklearn.model_selection import PredefinedSplit
import keras
def av_precision(y_true, y_pred, normalize = False):
#return tf.py_function(average_precision_score, (y_true, y_pred), tf.float64)
#return tf.convert_to_tensor(average_precision_score(y_true, y_pred), dtype=tf.float32)
#def sk_pr_auc(y_true, y_pred):
return tf.py_function(average_precision_score, (y_true, y_pred), tf.float64)
# =============================================================================
# def av_precision3(y_true, y_pred, normalize = False):
#
# y_true = y_true.reshape((-1))
# y_pred = y_pred.reshape((-1))
# return tf.py_function(average_precision_score, (y_true, y_pred), tf.float64)
#
# =============================================================================
def av_precision2(y_true, y_pred, normalize = False):
return average_precision_score(y_true, y_pred)
def make_cnn_model1(input_shape = (63, 148, 1), dense_layer_sizes=128, filters=10, kernel_size=(3,3),
pool_size=(2,2), drop_out=0.5):
# =============================================================================
# dense_layer_sizes=128
# filters=10
# kernel_size=(3,3) #(3,3)
# pool_size= (2,2)
# lr=0.0001
# drop_out = 0.5
# =============================================================================
#import tensorflow
#from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten #Activation,
from keras.layers import Conv2D, MaxPooling2D
model = Sequential()
model.add(Conv2D(filters, kernel_size,input_shape=input_shape, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Conv2D(filters, kernel_size, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(dense_layer_sizes, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(32, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=[tf.keras.metrics.AUC(curve='PR')])# [av_precision]
return model
def make_cnn_grid(input_shape = (63, 148, 1), lr=0.001, filters = 10, drop_out = 0.5, layers = 3,
dense_layer_sizes=256, activation_function = 'relu' ):
# =============================================================================
# 'lr': [0.0005, 0.001, 0.01, 0.1],
# 'decay': [0, 0.01],
# 'filters': [10, 16, 20],
# #kernel_size = [(3,3), (5,5)]
# #pool_size = [(2,2), (3,3)]
# 'dropout': [0, 0.1, 0.35, 0.5],
# 'batch_size': [32, 64, 128],
# 'epochs': [10, 20, 30, 50],
# 'dense_layer_sizes': [128, 256],
# 'activation_function': ['LeakyReLU', 'ReLU']
#
# =============================================================================
kernel_size = (3,3)
pool_size = (2,2)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten #Activation,
from keras.layers import Conv2D, MaxPooling2D
model = Sequential()
model.add(Conv2D(filters, kernel_size,input_shape=input_shape, activation=activation_function))
model.add(MaxPooling2D(pool_size=pool_size))
for i in range(layers-1):
model.add(Conv2D(filters, kernel_size, activation=activation_function))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(dense_layer_sizes, activation=activation_function))
model.add(Dropout(drop_out))
model.add(Dense(32, activation=activation_function))
model.add(Dropout(drop_out))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.Adam(learning_rate = lr),
metrics=[tf.keras.metrics.AUC(curve='PR')])# [av_precision]
return model
def make_cnn_grid_corr(input_shape = (63, 148, 1), lr=0.001, filters = 10, drop_out = 0.5, layers = 3,
dense_layer_sizes=256, activation_function = 'relu', if_dropout = 0 ): # , if_scheduler = 0
# =============================================================================
# 'lr': [0.0005, 0.001, 0.01, 0.1],
# 'decay': [0, 0.01],
# 'filters': [10, 16, 20],
# #kernel_size = [(3,3), (5,5)]
# #pool_size = [(2,2), (3,3)]
# 'dropout': [0, 0.1, 0.35, 0.5],
# 'batch_size': [32, 64, 128],
# 'epochs': [10, 20, 30, 50],
# 'dense_layer_sizes': [128, 256],
# 'activation_function': ['LeakyReLU', 'ReLU']
#
# =============================================================================
kernel_size = (3,3)
pool_size = (2,2)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten #Activation,
from keras.layers import Conv2D, MaxPooling2D, SpatialDropout2D
model = Sequential()
model.add(Conv2D(filters, kernel_size,input_shape=input_shape, activation=activation_function))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(SpatialDropout2D(if_dropout))
for i in range(layers-1):
model.add(Conv2D(filters, kernel_size, activation=activation_function))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(SpatialDropout2D(if_dropout))
model.add(Flatten())
model.add(Dense(dense_layer_sizes, activation=activation_function))
model.add(Dropout(drop_out))
model.add(Dense(32, activation=activation_function))
model.add(Dropout(drop_out))
model.add(Dense(1, activation='sigmoid'))
# =============================================================================
# if if_scheduler==1:
# step = tf.Variable(0, trainable=False)
# boundaries = [160000]
# values = [lr, lr*0.1]
# learning_rate_fn = keras.optimizers.schedules.PiecewiseConstantDecay(
# boundaries, values)
#
# # Later, whenever we perform an optimization step, we pass in the step.
# #learning_rate = learning_rate_fn(step)
# optimizer=keras.optimizers.Adam(learning_rate = learning_rate_fn)
# else:
# optimizer=keras.optimizers.Adam(learning_rate = lr)
#
# =============================================================================
model.compile(loss='binary_crossentropy',
optimizer=keras.optimizers.Adam(learning_rate = lr),
metrics=[tf.keras.metrics.AUC(curve='PR')])# [av_precision]
return model
def make_cnn_bulbul(input_shape = (63, 148, 1), drop_out=0.5):
# dense_layer_sizes=128, filters=10, kernel_size=(3,3), pool_size=(2,2),
# =============================================================================
# dense_layer_sizes=128
# filters=10
# kernel_size=(3,3) #(3,3)
# pool_size= (2,2)
# lr=0.0001
# drop_out = 0.5
# =============================================================================
#import tensorflow
#from tensorflow import keras
model = Sequential()
model.add(Conv2D(16, kernel_size=(3,3),input_shape=input_shape, activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))
model.add(Conv2D(16, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(3,3)))
model.add(Conv2D(16, kernel_size=(1,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(1,3)))
#model.add(Conv2D(16, kernel_size=(1,3), activation='relu'))
#model.add(MaxPooling2D(pool_size=(1,3)))
model.add(Flatten())
model.add(Dropout(drop_out))
model.add(Dense(256, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(32, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=[tf.keras.metrics.AUC(curve='PR')])# [av_precision] daje nany w validzie
return model
def make_cnn_github2019(input_shape = (63, 148, 1), dense_layer_sizes=128, filters=10, kernel_size=(3,3),
pool_size=(2,2), drop_out=0.5):
# https://github.com/hannape/CNN-second/blob/master/CNN_for_new_data.ipynb
import functools
from functools import partial, update_wrapper
dense_layer_sizes=128
filters=10
kernel_size=(3,3) #(3,3)
pool_size= (2,2)
#lr=0.0001
drop_out = 0.5
# ========= nie działa, jakie stare wersje kerasów, tfów i pythonów =================================
def wrapped_partial(func, *args, **kwargs):
partial_func = partial(func, *args, **kwargs)
update_wrapper(partial_func, func)
return partial_func
def binary_crossentropy_weigted(y_true, y_pred, class_weights):
y_pred = K.clip(y_pred, K.epsilon(), 1.0 - K.epsilon())
loss = K.mean(class_weights*(-y_true * K.log(y_pred) - (1.0 - y_true) * K.log(1.0 - y_pred)),axis=-1)
return loss
custom_loss = wrapped_partial(binary_crossentropy_weigted, class_weights=np.array([0.02, 0.98])) ## scoring for model.compile
# =====https://datascience.stackexchange.com/questions/58735/weighted-binary-cross-entropy-loss-keras-implementation
def weighted_bce(y_true, y_pred):
weights = (y_true * 49) + 1
bce = K.binary_crossentropy(y_true, y_pred)
weighted_bce = K.mean(bce * weights)
return weighted_bce
model = Sequential()
model.add(Conv2D(filters, kernel_size,input_shape=input_shape, activation='relu'))
# model.add(Conv2D(16, (3, 3), input_shape=input_shape ))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Conv2D(filters, kernel_size, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Conv2D(filters, kernel_size, activation='relu'))
model.add(MaxPooling2D(pool_size=pool_size))
model.add(Flatten())
model.add(Dense(dense_layer_sizes, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(32, activation='relu'))
model.add(Dropout(drop_out))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss= 'binary_crossentropy', #weighted_bce, #'binary_crossentropy',
optimizer='adam',#keras.optimizers.Adam(lr),#'adam',
metrics=['accuracy', tf.keras.metrics.AUC(curve='PR'), av_precision])
return model
def wczyt_dane_moje(chosen_repr, config, set_type):
import pandas as pd
import os
from useful_stuff import make_test
if set_type == 'wlasc':
print("dane wlasciwe")
df1 = pd.read_hdf(os.path.join('..','..','jupyter','data','df_train_'+ str(chosen_repr) +'_norm.h5'),'repr' + \
str((config.representation_2d + [''] + config.representation_1d).index(chosen_repr)+1))
df2 = pd.read_hdf(os.path.join('..','..','jupyter','data','df_valid_norm.h5'),'df')
all_repr = config.representation_1d + config.representation_2d
all_repr.remove(chosen_repr)
df2 = df2.drop(all_repr, axis=1)
cv_split, dX, dy, di, cv = make_cv_split_cnn(df1, df2, chosen_repr)
print("Własciwy train+walid wczytany")
valid = df2.loc[:,['rec_name', 'chunk_ids', chosen_repr, 'has_bird']].values
train = df1.loc[:,['rec_name', 'chunk_ids', chosen_repr, 'has_bird']].values
#valid_identifiers = valid[:, 0:2]
valid_X = np.stack(valid[:, 2])
valid_y = valid[:, 3]
train_X = np.stack(train[:, 2])
train_y = train[:, 3]
if set_type == 'testy':
print("dane mini, do testow")
df = pd.read_hdf(os.path.join('..','..','jupyter','data','df_val300_norm.h5'),'val')
all_repr = config.representation_1d + config.representation_2d
all_repr.remove(chosen_repr)
df = df.drop(all_repr, axis=1)
df1 = df[50:300]#df.sample(n=250, random_state = 667)
df2 = df[0:50]#df.sample(n=50, random_state = 667)
cv_split, dX, dy, di, cv = make_cv_split_cnn(df1, df2, chosen_repr)
print("Testowy train+walid wczytany")
valid_X = []
valid_y = []
df3 = pd.read_hdf(os.path.join('..','..','jupyter','data','df_test_3rec_'+ str(chosen_repr) +'_norm.h5'),'df')
dX_test, dy_test, di_test = make_test(df3, chosen_repr)
#print("Test wczytany")
return cv_split, dX, dy, di, dX_test, dy_test, di_test, cv, valid_X, valid_y, train_X, train_y
def make_cv_split_cnn(train, valid, chosen_repr, classifier=False):
#
train = train.loc[:,['rec_name', 'chunk_ids', chosen_repr, 'has_bird']].values
train_identifiers = train[:, 0:2]
train_X = np.stack(train[:, 2])
train_y = train[:, 3]
valid = valid.loc[:,['rec_name', 'chunk_ids', chosen_repr, 'has_bird']].values
valid_identifiers = valid[:, 0:2]
valid_X = np.stack(valid[:, 2])
valid_y = valid[:, 3]
dX = np.vstack((train_X, valid_X))
print('min train+walid: ', np.amin(dX))
dy = np.hstack((train_y, valid_y))
di = np.vstack((train_identifiers, valid_identifiers))
train_indices = np.array(range(0, train_X.shape[0]))
val_indices = np.array(range(train_X.shape[0], dX.shape[0]))
cv_split = [(train_indices, val_indices)] # ,(train_indices, val_indices)
dX = np.reshape(dX, newshape=(dX.shape[0],-1))
dy = dy.astype(int)
# http://www.wellformedness.com/blog/using-a-fixed-training-development-test-split-in-sklearn/
test_fold = np.concatenate([
# The training data.
np.full( train_X.shape[0],-1, dtype=np.int8),
# The development data.
np.zeros(valid_X.shape[0], dtype=np.int8)
])
cv = PredefinedSplit(test_fold)
print(test_fold)
return cv_split, dX, dy, di, cv
def wczytaj_testy(chosen_repr):
# najpierw wczyt podziału całosci
from useful_stuff import make_cv_split, make_test
from useful_stuff import read_best_models_8_classic, read_best_models_8_classic_plus_MIR
import pandas as pd
import os
import config
from sklearn.metrics import roc_auc_score, average_precision_score
from wczytanie_danych import funkcja_wczytanie_danych
from reprezentacje import funkcja_reprezentacja
import numpy as np
import pandas as pd
import json
import glob
import time
start_time = time.time()
print(config.path_test1618_txt)
path_main = os.path.join('C:\\','Users','szaro','Desktop','jupyter')
print(path_main)
path_test1618_txt = os.path.join(path_main, config.path_test1618_txt)
path_train161718_txt = os.path.join(path_main, config.path_train161718_txt)
path_test1618_wav = os.path.join(path_main, config.path_test1618_wav)
path_train161718_wav = os.path.join(path_main, config.path_train161718_wav)
test_new_only = 1
_,_,_, data_test_new = funkcja_wczytanie_danych(path_test1618_txt, path_train161718_txt, path_test1618_wav,\
path_train161718_wav, config.balance_types, config.balance_ratios, config.chunk_length_ms,\
config.chunk_overlap, config.calls_0, config.calls_1, config.calls_unknown, config.tolerance, config.valid_set,\
config.test_rec_to_cut, config.columns_dataframe, test_new_only)
print("--- Funkcja wczytanie danych: %s sekund ---" % (time.time() - start_time))
# Wczytanie testowych reprezentacji
import numpy as np
start_time = time.time()
np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
## !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if_scaler = True
#chosen_repr = '8_classic'
nr_nagr_pocz = 0
wielkosc_batcha = 18
## !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
## repr_full3,
file_names, indices, info_chunksy, repr_full_scaled = funkcja_reprezentacja(path_test1618_wav, data_test_new, chosen_repr, if_scaler, \
config.repr_1d_summary, config.summary_1d, config.sr, config.chunk_length_ms, \
config.n_fft, config.win_length, config.hop_length, config.window, config.f_min, config.f_max,\
config.n_mels, config.N, config.step, config.Np, config.K, config.tm, \
config.flock, config.tlock, nr_nagr_pocz, wielkosc_batcha)
#file_names, indices, info_chunksy, representation_type, repr_full = funkcja_reprezentacje(path_train161718_wav, data_train, '8_classic', repr_1d_summary, summary_1d, sr, chunk_length_ms, \
# n_fft, win_length, hop_length, window, f_min, f_max, n_mels, N, step, Np, K, tm, flock, tlock)
print("--- Funkcja reprezentacja danych: %s minut ---" % ((time.time() - start_time)/60))
file_names_list, chunk_ids_list, has_bird_list, representation_list = [],[],[],[]
for num,i in enumerate(indices[nr_nagr_pocz:nr_nagr_pocz+wielkosc_batcha]):
file_names_list.extend([file_names[num] for i in range(len(i))])
chunk_ids_list.extend((info_chunksy[num][0])) #.tolist()
has_bird_list.extend((info_chunksy[num][3]))
representation_list.extend([repr_full_scaled[num][i] for i in range(len(i))]) # cała reprezentacja1
testing_features = np.array(representation_list) #pd.DataFrame(data = representation_list, columns =str(chosen_repr))
testing_target = has_bird_list
testing_features = np.reshape(testing_features, newshape=(testing_features.shape[0],-1))
print("Test wczytany 18 nagran")
return testing_features, testing_target
"""This file is part of the TPOT library.
TPOT was primarily developed at the University of Pennsylvania by:
- <NAME> (<EMAIL>)
- <NAME> (<EMAIL>)
- <NAME> (<EMAIL>)
- and many more generous open source contributors
TPOT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
TPOT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with TPOT. If not, see <http://www.gnu.org/licenses/>.
"""
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_array
class ZeroCount(BaseEstimator, TransformerMixin):
"""Adds the count of zeros and count of non-zeros per sample as features."""
def fit(self, X, y=None):
"""Dummy function to fit in with the sklearn API."""
return self
def transform(self, X, y=None):
"""Transform data by adding two virtual features.
Parameters
----------
X: numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples and n_components
is the number of components.
y: None
Unused
Returns
-------
X_transformed: array-like, shape (n_samples, n_features)
The transformed feature set
"""
X = check_array(X)
n_features = X.shape[1]
X_transformed = np.copy(X)
non_zero_vector = np.count_nonzero(X_transformed, axis=1)
non_zero = np.reshape(non_zero_vector, (-1, 1))
zero_col = np.reshape(n_features - non_zero_vector, (-1, 1))
X_transformed = np.hstack((non_zero, X_transformed))
X_transformed = np.hstack((zero_col, X_transformed))
return X_transformed<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue May 18 11:55:04 2021
@author: Hania
"""
# -*- coding: utf-8 -*-
"""
Created on Thu May 6 15:58:03 2021
@author: Hania
Sprawdzenie grida, zmiany po rozmowie z Agą 13.05.21
"""
import config
import numpy as np
from keras import backend as K
from keras.wrappers.scikit_learn import KerasClassifier
K.set_image_data_format('channels_last')
from sklearn.metrics import average_precision_score, make_scorer
from sklearn.metrics import roc_auc_score, average_precision_score
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
#from config_agi import parse_model_config
from saving_utils import save_predictions, save_as_json, LoggerWrapper
from sklearn.model_selection import RandomizedSearchCV, GridSearchCV
from useful_func_cnn import wczyt_dane_moje, make_cnn_model1, av_precision2, av_precision, make_cnn_grid_corr, wczytaj_testy
#chosen_repr = 'spektrogram'
#chosen_cnn = 'bulbul'
import os
import pickle
import time
import sys
import tensorflow as tf
import json
import pandas as pd
# cos żeby się GPU nie dławiło:
# =============================================================================
from tensorflow.compat.v1.keras.backend import set_session
config2 = tf.compat.v1.ConfigProto()
config2.gpu_options.per_process_gpu_memory_fraction = 0.3 #0.5
set_session(tf.compat.v1.Session(config=config2))
# =============================================================================
# =============================================================================
# config3 = tf.compat.v1.ConfigProto()
# config3.gpu_options.allow_growth=True
# set_session(tf.compat.v1.Session(config=config3))
# =============================================================================
#%%
# python main_04052021_cnny.py spektrogram bulbul batch_size epochs
# python main_06052021_grid_cnny_corr.py spektrogram 100
if __name__=='__main__':
# Load configs
chosen_repr = sys.argv[1] # 'spektrogram' #
n_iter = sys.argv[2]
exp_dir = os.path.join("..","results","grid", f"{chosen_repr}", time.strftime('%Y-%m-%d-%H-%M'))
try:
os.makedirs(exp_dir)
except FileExistsError:
pass
start_time = time.time()
logger_wrapper = LoggerWrapper(exp_dir)
sys.stderr.write = logger_wrapper.log_errors
logger_wrapper.logger.info(f'Running {sys.argv}')
# cv - podział do randomizedsearcha, by nie robił mi CV. dX - train + valid. Oprócz tego są też osobno jako X_val i train_X
cv_split, dX, dy, di, dX_test, dy_test, di_test, cv, X_val, y_val, train_X, train_y = wczyt_dane_moje(chosen_repr, config, 'wlasc')
print(chosen_repr)
if chosen_repr=="spektrogram":
in_shape = (63, 148, 1)
if chosen_repr=="mel-spektrogram":
in_shape = (60, 148, 1)
dX_resh = dX.reshape(dX.shape[0], in_shape[0], in_shape[1], 1).astype('float32') # trzeba wrócić z liniowego, które miało isć do podst. klasyf -> do obrazka 2d
input_shape = (np.shape(dX_resh)[1], np.shape(dX_resh)[2], np.shape(dX_resh)[3]) # wielkoc obrazka, 1 kanał, na końcu podawany
X_val_resh = X_val.reshape(X_val.shape[0], in_shape[0], in_shape[1], 1).astype('float32')
# upewnienie sie że działam na GPU
#from tensorflow.python.client import device_lib
#print(device_lib.list_local_devices())
params = {
'lr': [0.0001, 0.0005, 0.001, 0.005], # początkowy LR do Adama 0.01 za duży jest
'input_shape': [in_shape],
'filters': [10, 25, 50, 100, 150],
'layers': [3, 4], # ilosć warstw [konwolucja +pooling] 3, 4, 5,
'drop_out': [0, 0.1, 0.2, 0.3, 0.4, 0.5], # dropout po dwóch warstwach gęstych
'if_dropout': [0, 0.1, 0.2], # parametry do spatialDropout2D. dropout po poolingach.
# Internety mówią że rzadziej się daje dropout po conv,a jesli już to małe wartoci
'batch_size': [16, 32, 64, 128],
'epochs': [100],#[5, 8, 10, 15, 20, 30, 50],
#'padding': ["same"], # "valid", "same" - nie ma sensu, bo to pooling najbardziej zmniejsza reprezentację, nie conv i padding.
# Trzeba by zmienić archotekturę i wrzucać więcj conv, anie na przemian conv i pool
'dense_layer_sizes': [128, 256], # rozmiar pierwszej warstwy gęstej
#'if_scheduler': [0, 1]
}
model = KerasClassifier(build_fn = make_cnn_grid_corr, verbose=1)
logger_wrapper.logger.info('macierz badanych parametrów')
logger_wrapper.logger.info(params)
with open(os.path.join(exp_dir,"matrix_params.json"), "w") as json_file:
json.dump(params, json_file) # json_file.write(params.to_json(indent=2))
my_callbacks = [
tf.keras.callbacks.EarlyStopping(monitor="val_loss",patience=5, restore_best_weights = True),
]
grid = RandomizedSearchCV(estimator=model, param_distributions=params, scoring = make_scorer(average_precision_score),
cv = cv, n_jobs=1, n_iter=int(n_iter), verbose = 3, random_state =667, refit = False) #
# nie refitujemy, bo wtedy valid będzie i w treningu i w walidzie, więć early stopping nie będzie miał sensu
grid_result = grid.fit(dX_resh, dy, validation_data=(X_val_resh, y_val.astype(np.float32)), callbacks = my_callbacks)
print(grid_result.best_params_)
# =============================================================================
# Tak było wczesniej, bez early stoppingu.
# grid = RandomizedSearchCV(estimator=model, param_distributions=params, scoring = make_scorer(average_precision_score),
# cv = cv, n_jobs=1, n_iter=int(n_iter), verbose = 3, random_state =667) #
# grid_result = grid.fit(dX_resh, dy)
#
# =============================================================================
logger_wrapper.logger.info('grid search trwał (s): ')
logger_wrapper.logger.info(time.time() - start_time)
best_params = grid_result.best_params_
with open(os.path.join(exp_dir,"best_params.json"), "w") as json_file:
json.dump(best_params, json_file, indent=1)
pd.DataFrame(grid_result.cv_results_['params']).to_pickle(os.path.join(exp_dir,"all_models.pkl"))
pd.DataFrame(grid_result.cv_results_['split0_test_score']).to_pickle(os.path.join(exp_dir,"all_models_scores.pkl") )
def display_cv_results(search_results):
print('Best score = {:.4f} using {}'.format(search_results.best_score_, search_results.best_params_))
means = search_results.cv_results_['mean_test_score']
stds = search_results.cv_results_['std_test_score']
params = search_results.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print('mean test accuracy +/- std = {:.4f} +/- {:.4f} with: {}'.format(mean, stdev, param))
display_cv_results(grid_result)
# odczyt: pd.read_pickle("best20.pkl")
logger_wrapper.logger.info('All params:')
logger_wrapper.logger.info(params)
logger_wrapper.logger.info('Best params:', best_params)
logger_wrapper.logger.info( best_params)
logger_wrapper.logger.info(grid_result.cv_results_)
# trzeba zrefitować na najlepszym zestawie, bo
#" This RandomizedSearchCV instance was initialized with refit=False. predict_proba is available only after refitting on the best parameters.
# You can refit an estimator manually using the ``best_params_`` attribute"
# refit - ale trening dalej na trainie, a nie na całosci train + walid
train_X_resh = train_X.reshape(train_X.shape[0], in_shape[0], in_shape[1], 1).astype('float32')
model_refit = make_cnn_grid_corr(input_shape = best_params['input_shape'],
lr = best_params['lr'],
filters = best_params['filters'],
drop_out = best_params['drop_out'],
layers = best_params['layers'],
if_dropout = best_params['if_dropout'],
dense_layer_sizes = best_params['dense_layer_sizes']
)
hist = model_refit.fit(train_X_resh, train_y.astype(np.float32), validation_data=(X_val_resh, y_val.astype(np.float32)), callbacks = my_callbacks,
epochs=best_params['epochs'], batch_size=best_params['batch_size'])
# zapisz model
model_refit.save(os.path.join(exp_dir,"my-model.h5"))
#grid_result.best_estimator_.model.save(os.path.join(exp_dir,"my-model.h5"))
print("Saved model to disk")
# wczytanie testu
testing_features, testing_target = wczytaj_testy(chosen_repr)
testing_features_resh = testing_features.reshape(testing_features.shape[0], in_shape[0], in_shape[1], 1).astype('float32')
# zapis predykcji
save_predictions(dX_resh, dy, cv_split, testing_features_resh, testing_target, model_refit, exp_dir)
y_preds = model_refit.predict_proba(testing_features_resh)
# zapisanie historii, by dało się wyrysować krzywe uczenia w przyszłosci , loss i pr_auc
with open(os.path.join(exp_dir,'history-z-refita.pckl'), 'wb') as file_pi:
pickle.dump(hist.history, file_pi)
# jak wczytać:
#f = open('history.pckl', 'rb')
# = pickle.load(f)
#f.close()
# %%
model_json = (model_refit.to_json(indent=2))
with open(os.path.join(exp_dir,"architecture-only-refit.json"), "w") as json_file:
json_file.write(model_json)
# %%
prec_nb, recall_nb, _ = precision_recall_curve(testing_target, y_preds)
fpr_nb, tpr_nb, _ = roc_curve(testing_target, y_preds)
print('AUC PR: ', average_precision_score(testing_target, y_preds))
fig = plt.figure(figsize=(10,10))
plt.rcParams.update({'font.size': 22})
plt.title('AUC PR')
plt.plot(recall_nb, prec_nb, 'b', label = 'CNN AUC = %0.2f%% ' % (100*average_precision_score(testing_target, y_preds)))
plt.legend(loc = 'upper right')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('Precyzja (Precision)')
plt.xlabel('Czułość (Recall)')
#plt.show()
fig.savefig(os.path.join(exp_dir,'AUC-PR-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
fig = plt.figure(figsize=(10,10))
plt.rcParams.update({'font.size': 22})
plt.title('AUC ROC')
plt.plot(fpr_nb, tpr_nb, 'b', label = 'CNN AUC = %0.2f%%' % (100*roc_auc_score(testing_target, y_preds)))
plt.legend(loc = 'lower right')
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('Wskaźnik czułości (True Positive Rate)')
plt.xlabel('Odsetek fałszywie pozytywnych alarmów (False Positive Rate)')
#plt.show()
fig.savefig(os.path.join(exp_dir,'AUC-ROC-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
# summarize history for loss
fig = plt.figure(figsize=(10,10))
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Koszt (loss)')
plt.xlabel('Liczba epok')
plt.legend(['trening','walid'], loc='upper right')
# plt.show()
fig.savefig(os.path.join(exp_dir,'uczenie-loss-refit'+ time.strftime('%Y-%m-%d-%H-%M')))
auc_nr = 'auc_'+str(int(n_iter) )
val_auc_nr = 'val_auc_'+str(int(n_iter) )
fig = plt.figure(figsize=(10,10))
plt.plot(hist.history[auc_nr])
plt.plot(hist.history[val_auc_nr])
plt.title('Model PR AUC')
plt.ylabel('Pole pod krzywą PR')
plt.xlabel('Liczba epok')
plt.legend(['trening','walid'], loc='lower right')
#plt.show()
fig.savefig(os.path.join(exp_dir,'uczenie-PR-AUC-refit' + time.strftime('%Y-%m-%d-%H-%M')))
<file_sep># Gruba-kreska
Zebranie wszystkiego porządnie.
1. Poprawienie danych
2. Wczytanie danych
3. Main wczytanie i reprezentacje
...
| 314042390aff52241f9a499fda5a3a791ecba152 | [
"Markdown",
"Python"
] | 7 | Python | hannape/Gruba-kreska | 9d911001a31f42a6ab4e798fab5289ecf3b8cfc1 | 80444f2f74d5533f11d53f05fbd0af9b8c268c28 | |
refs/heads/master | <repo_name>Jnoel94410/Mak-it<file_sep>/makit/js/script.js
$(function() {
$('.logo_claire').hide();
$('.socialhover_claire').hover(
function () {
$('.logo_claire').fadeIn();
}, function () {
$('.logo_claire').fadeOut();
});
if ($(window).width() <= 1024) {
$(".logo_claire").show();
};
$('.logo_franck').hide();
$('.socialhover_franck').hover(
function () {
$('.logo_franck').fadeIn();
}, function () {
$('.logo_franck').fadeOut();
});
if ($(window).width() <= 1024) {
$(".logo_franck").show();
};
}); | 8fb93a15dd1d0e979803b392d40c8f6ff37b0373 | [
"JavaScript"
] | 1 | JavaScript | Jnoel94410/Mak-it | e7dde19c0a339c55cc156e43bfecfe4f230ebb85 | cadbbaf1cc62c4059164c4f345e4d37d28b1487f | |
refs/heads/master | <repo_name>netososilva/car-pooling<file_sep>/CarPooling.Domain/Business/Groups.cs
using System.Collections.Generic;
using System.Linq;
using CarPooling.Domain.Models;
namespace CarPooling.Domain.Business
{
public class Groups
{
private Dictionary<int, Group> WaitingGroups { get; set; }
public Groups()
{
WaitingGroups = new Dictionary<int, Group>();
}
public void Clear()
{
this.WaitingGroups.Clear();
}
public void Add(Group group)
{
this.WaitingGroups.Add(group.Id, group);
}
public bool ExistsGroup(int groupId)
{
return this.WaitingGroups.ContainsKey(groupId);
}
public List<int> GetGroupsId()
{
return WaitingGroups.Keys.ToList();
}
public Group GetGroup(int groupId)
{
return WaitingGroups[groupId];
}
public void Remove(int groupId)
{
WaitingGroups.Remove(groupId);
}
}
}<file_sep>/CarPooling.Domain/Business/Cars.cs
using System.Collections.Generic;
using System.Linq;
using CarPooling.Domain.Models;
namespace CarPooling.Domain.Business
{
public class Cars
{
private Dictionary<int, List<Car>> AvailableCars;
public Cars()
{
AvailableCars = new Dictionary<int, List<Car>>();
}
public void UpdateCars(IEnumerable<Car> cars)
{
this.AvailableCars = cars.
GroupBy(car => car.Seats).
ToDictionary(car => car.Key, car => car.ToList());
}
public void Add(Car car)
{
if (!AvailableCars.ContainsKey(car.Seats))
AvailableCars.Add(car.Seats, new List<Car>());
AvailableCars[car.Seats].Add(car);
}
public bool IsAvailable(int seats)
{
if (!AvailableCars.ContainsKey(seats))
return false;
if (AvailableCars[seats].Any())
return true;
return false;
}
public Car GetCarBySeats(int seats)
{
return AvailableCars[seats].FirstOrDefault();
}
public void Remove(Car car)
{
AvailableCars[car.Seats].Remove(car);
if (!AvailableCars[car.Seats].Any())
AvailableCars.Remove(car.Seats);
}
}
}<file_sep>/CarPooling.Domain/Business/Journeys.cs
using System.Collections.Generic;
using CarPooling.Domain.Models;
namespace CarPooling.Domain.Business
{
public class Journeys
{
public Dictionary<int, Journey> ActiveJourneys { get; set; }
public Journeys()
{
ActiveJourneys = new Dictionary<int, Journey>();
}
public void Clear()
{
ActiveJourneys = new Dictionary<int, Journey>();
}
public Car DropOff(int groupId)
{
var journey = Locate(groupId);
journey.DropOff(journey.Group);
ActiveJourneys.Remove(groupId);
return journey.Car;
}
public void CreateJourney(Car car, Group group)
{
var journey = new Journey
{
Car = car,
Group = group
};
ActiveJourneys.Add(group.Id, journey);
}
public Journey Locate(int groupId)
{
return ActiveJourneys[groupId];
}
public bool ExistsJourney(int groupId)
{
return ActiveJourneys.ContainsKey(groupId);
}
}
}<file_sep>/CarPooling.Api/Controllers/CarsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using CarPooling.Api.Filters;
using CarPooling.Domain.Business;
using CarPooling.Domain.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CarPooling.Api.Controllers
{
public class CarsController : ControllerBase
{
private readonly Pooling carPooling = new Pooling();
// PUT: cars
[Route("cars")]
[ServiceFilter(typeof(PutFilter))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Consumes("application/json")]
public IActionResult Cars([FromBody] IEnumerable<Car> cars)
{
if (cars == null || cars.Count() == 0) return BadRequest();
try
{
carPooling.UpdateCars(cars);
return Ok();
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
// POST: journey
[Route("journey")]
[ServiceFilter(typeof(PostFilter))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[Consumes("application/json")]
public IActionResult Journey([FromBody] Group group)
{
if (group == null || group.Invalid) return BadRequest();
try
{
carPooling.AlocateGroup(group);
return Ok();
}
catch(Exception ex)
{
return BadRequest(ex);
}
}
// POST: dropoff
[Route("dropoff")]
[ServiceFilter(typeof(PostFilter))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult DropOff([FromForm] string ID)
{
if (string.IsNullOrWhiteSpace(ID)) return BadRequest();
if (!int.TryParse(ID, out var groupId)) return BadRequest();
try
{
if (!carPooling.ExistsGroup(groupId)) return NotFound();
carPooling.DropOff(groupId);
return Ok();
}
catch(Exception ex)
{
return BadRequest(ex);
}
}
// POST: locate
[Route("locate")]
[ServiceFilter(typeof(PostFilter))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult Locate([FromForm] string ID)
{
if (string.IsNullOrWhiteSpace(ID)) return BadRequest();
if (!int.TryParse(ID, out var groupId)) return BadRequest();
try
{
if (carPooling.ExistsGroup(groupId)) return NotFound();
var journey = carPooling.Locate(groupId);
if (journey == null) return NoContent();
return Ok(journey.Car);
}
catch(Exception ex)
{
return BadRequest(ex);
}
}
}
}<file_sep>/CarPooling.Domain/Business/Pooling.cs
using System.Collections.Generic;
using CarPooling.Domain.Models;
namespace CarPooling.Domain.Business
{
public class Pooling
{
private Cars Cars { get; set; }
private Groups Groups { get; set; }
private Journeys Journeys { get; set; }
public Pooling()
{
Cars = new Cars();
Groups = new Groups();
Journeys = new Journeys();
}
/// <summary>
/// Clean the list of cars, groups and journeys
/// Replaces a list of cars with a list passed by parameter
/// </summary>
/// <param name="cars"></param>
public void UpdateCars(IEnumerable<Car> cars)
{
this.Cars.UpdateCars(cars);
this.Groups.Clear();
this.Journeys.Clear();
}
/// <summary>
/// Alocate a group
/// </summary>
/// <param name="group"></param>
public void AlocateGroup(Group group)
{
this.Groups.Add(group);
MatchJourneys();
}
/// <summary>
/// Drop off a journey
/// </summary>
/// <param name="group"></param>
public void DropOff(int groupId)
{
var car = Journeys.DropOff(groupId);
Cars.Add(car);
MatchJourneys();
}
public bool ExistsGroup(int groupId)
{
return Groups.ExistsGroup(groupId) ||
Journeys.ExistsJourney(groupId);
}
public Journey Locate(int groupId)
{
if (!Journeys.ExistsJourney(groupId)) return null;
return Journeys.Locate(groupId);
}
private void MatchJourneys()
{
var seatsRequested = 0;
var group = new Group();
foreach (var groupId in Groups.GetGroupsId())
{
group = Groups.GetGroup(groupId);
seatsRequested = group.People;
while (seatsRequested <= 6)
{
if (Cars.IsAvailable(seatsRequested))
{
var car = Cars.GetCarBySeats(seatsRequested);
CreateJourney(car, group);
break;
}
seatsRequested++;
}
}
}
private void CreateJourney(Car car, Group group)
{
Journeys.CreateJourney(car, group);
Cars.Remove(car);
Groups.Remove(group.Id);
}
}
}<file_sep>/CarPooling.Domain/Models/Car.cs
namespace CarPooling.Domain.Models
{
public class Car
{
public int Id { get; set; }
public int Seats { get; set; }
public bool Valid => Validate();
public bool Invalid => !Valid;
private bool Validate() {
if (Seats <= 0 || Seats >= 6)
return false;
return true;
}
}
}<file_sep>/CarPooling.Domain/Models/Journey.cs
namespace CarPooling.Domain.Models
{
public class Journey
{
public Car Car { get; set; }
public Group Group { get; set; }
public void DropOff(Group group)
{
Car.Seats += group.People;
}
}
}<file_sep>/Dockerfile
FROM microsoft/dotnet:2.1-sdk
WORKDIR /app
EXPOSE 9091
COPY . .
RUN dotnet publish "./CarPooling.Api/CarPooling.Api.csproj" -c Release -o "../dist"
ENTRYPOINT ["dotnet", "dist/CarPooling.Api.dll"] <file_sep>/CarPooling.Api/Filters/PutFilter.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CarPooling.Api.Filters
{
public class PutFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
var requestType = context.HttpContext.Request.Method;
if (HttpMethods.IsPut(requestType))
return;
context.Result = new BadRequestObjectResult("Method is invalid.");
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Do something after the action executes.
}
}
} | df9de7d98daa318b914ce2a0c62ba433db6a51a0 | [
"C#",
"Dockerfile"
] | 9 | C# | netososilva/car-pooling | 143ab9cdaddc53b5ca776c8f355651c61019ca5b | 793453fe134faaa45d86d4e5987e3e236174ba9d | |
refs/heads/master | <repo_name>Omybot/GoBot<file_sep>/GoBot/GoBot/BoardContext/GameBoard.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using AStarFolder;
using Geometry.Shapes;
using GoBot.Strategies;
using GoBot.GameElements;
using GoBot.Devices;
using GoBot.Threading;
namespace GoBot.BoardContext
{
public class GameBoard
{
private static Obstacles _obstacles;
private static Color _myColor = ColorRightYellow;
private static int _score;
private static int _initialOpponentRadius { get; set; }
private static int _currentOpponentRadius { get; set; }
private static int _startZoneCounter = 0;
private static bool _startZonePresence = false;
private static bool _startZoneSizeReduction = false;
private static ThreadLink _linkStartZone;
private static Strategy _currentStrategy;
private static AllGameElements _elements;
private static List<IShape> _detections;
private static Polygon _bounds;
public GameBoard()
{
if (!Execution.DesignMode)
{
_elements = new AllGameElements();
_initialOpponentRadius = 200;
_currentOpponentRadius = _initialOpponentRadius;
_obstacles = new Obstacles(Elements);
CreateGraph(75);
//Balise.PositionEnnemisActualisee += Balise_PositionEnnemisActualisee;
Robots.MainRobot.UpdateGraph(_obstacles.FromAllExceptBoard);
// TODOEACHYEAR Définir ici la zone correspondant au plateau où les detections d'adversaire sont autorisées (enlever les pentes par exemple)
_bounds = new PolygonRectangle(new RealPoint(0, 0), 3000, 2000);
StartDetection();
if (Config.CurrentConfig.IsMiniRobot)
{
_currentStrategy = new StrategyMini();
}
else
{
_currentStrategy = new StrategyMatch();
}
}
}
public static Strategy Strategy
{
//TODO2020 gérer un démarrage de stratégie mieux défini (avec une publique ?)
get { return _currentStrategy; }
set { _currentStrategy = value; }
}
public static void AddObstacle(IShape shape)
{
_obstacles.AddObstacle(shape);
}
public static AllGameElements Elements
{
get { return _elements; }
}
public static List<IShape> Detections
{
get { return _detections; }
set { _detections = value; }
}
public static Color MyColor
{
get { return _myColor; }
set
{
if (_myColor != value)
{
_myColor = value;
MyColorChange?.Invoke(null, null);
if (_obstacles != null) Robots.MainRobot.UpdateGraph(_obstacles.FromAllExceptBoard);
if (Config.CurrentConfig.IsMiniRobot)
{
_currentStrategy = new StrategyMini();
}
else
{
_currentStrategy = new StrategyMatch();
}
}
}
}
public static event EventHandler MyColorChange;
public static int Score
{
get { return _score; }
set { _score = value; ScoreChange?.Invoke(_score); }
}
public delegate void ScoreChangeDelegate(int score);
public static event ScoreChangeDelegate ScoreChange;
public static Color ColorLeftBlue { get { return Color.FromArgb(0, 91, 140); } }
public static Color ColorRightYellow { get { return Color.FromArgb(247, 181, 0); } }
public static Color ColorNeutral { get { return Color.White; } }
/// <summary>
/// Largeur de la table (mm)
/// </summary>
public static int Width { get { return 3000; } }
/// <summary>
/// Hauteur de la table (mm)
/// </summary>
public static int Height { get { return 2000; } }
/// <summary>
/// Largeur de la bordure de la table (mm)
/// </summary>
public static int BorderSize { get { return 22; } }
/// <summary>
/// Diamètre actuellement considéré pour un adversaire
/// </summary>
public static int OpponentRadius
{
get { return _currentOpponentRadius; }
set { _currentOpponentRadius = value; } // TODO2020 une publique non ? Reduce...
}
/// <summary>
/// Diamètre initiallement considéré pour un adversaire
/// </summary>
public static int OpponentRadiusInitial
{
get { return _initialOpponentRadius; }
}
/// <summary>
/// Liste complète des obstacles fixes et temporaires
/// </summary>
public static IEnumerable<IShape> ObstaclesAll
{
get
{
return _obstacles.FromAll.ToList(); // Pour concretiser la liste
}
}
/// <summary>
/// Liste complète des obstacles fixes et temporaires
/// </summary>
public static IEnumerable<IShape> ObstaclesBoardConstruction
{
get
{
return _obstacles.FromBoardConstruction.ToList(); // Pour concretiser la liste
}
}
/// <summary>
/// Liste complète des obstacles vus par un lidart au niveau du sol
/// </summary>
public static IEnumerable<IShape> ObstaclesLidarGround
{
get
{
return _obstacles.FromBoard.Concat(Elements.AsVisibleObstacles).ToList(); // Pour concretiser la liste
}
}
public static IEnumerable<IShape> ObstaclesOpponents
{
get
{
return _obstacles.FromDetection.ToList();
}
}
public static bool IsInside(RealPoint p, int securityDistance = 0)
{
bool inside = _bounds.Contains(p);
if (inside && securityDistance > 0)
inside = !_bounds.Sides.Exists(o => o.Distance(p) < securityDistance);
return inside;
}
public static void StartMatch()
{
_linkStartZone = ThreadManager.CreateThread(link => CheckStartZonePresence());
_linkStartZone.StartInfiniteLoop(1000);
_linkStartZone.Name = "Check zone départ";
}
private static void CheckStartZonePresence()
{
if (_startZonePresence)
_startZoneCounter++;
else
{
_startZoneCounter = 0;
_startZoneSizeReduction = false;
}
_startZonePresence = false;
if (_startZoneCounter >= 5)
_startZoneSizeReduction = true;
}
public static void StartDetection()
{
if (AllDevices.LidarAvoid != null)
{
AllDevices.LidarAvoid.StartLoopMeasure();
AllDevices.LidarAvoid.NewMeasure += LidarAvoid_NewMeasure;
}
}
public static void SetOpponents(List<RealPoint> positions)
{
if (_obstacles != null && Strategy != null && Strategy.IsRunning)
{
// Positions ennemies signalées par la balise
// TODOEACHYEAR Tester ICI si on veut devenir aveugle à la présence d'aversaire dans notre zone de départ au début du match
if (Strategy != null && Strategy.TimeSinceBegin.TotalSeconds < 20)
positions = positions.Where(o => !StartZoneMe().Contains(o)).ToList();
if (GameBoard.Strategy == null)
{
// TODOEACHYEAR Tester ICI ce qu'il y a à tester en fonction de la position de l'ennemi AVANT de lancer le match
}
else
{
// TODOEACHYEAR Tester ICI ce qu'il y a à tester en fonction de la position de l'ennemi PENDANT le match
Elements.SetOpponents(positions);
if (Robots.MainRobot.IsSpeedAdvAdaptable && positions.Count > 0)
{
double minOpponentDist = positions.Min(p => p.Distance(Robots.MainRobot.Position.Coordinates));
Robots.MainRobot.SpeedConfig.LineSpeed = SpeedWithOpponent(minOpponentDist, Config.CurrentConfig.ConfigRapide.LineSpeed);
}
}
_obstacles.SetDetections(positions.Select(p =>
{
// TODOEACHYEAR C'est ICI qu'on s'amuse à rédurie le périmètre d'un robot adverse qui n'est pas sorti de sa zone de départ
if (StartZoneOpponent().Contains(p))
{
_startZonePresence = true;
if (_startZoneSizeReduction)
return new Circle(p, _currentOpponentRadius / 2);
else
return new Circle(p, _currentOpponentRadius);
}
return new Circle(p, _currentOpponentRadius);
}).ToList());
//_obstacles.SetDetections(positions.Select(p => new Circle(p, RayonAdversaire)).ToList());
// TODO2020 : faudrait pouvoir mettre à jour le graph sans refaire les zones interdites de couleur (sauvegarder un résultat après application de la couleur ?)
// parce que les carrés c'est beaucoup plus long que les ronds...
Robots.MainRobot.UpdateGraph(_obstacles.FromAllExceptBoard);
Robots.MainRobot.OpponentsTrajectoryCollision(_obstacles.FromDetection);
}
}
public static IShape StartZoneMe()
{
if (GameBoard.MyColor == GameBoard.ColorRightYellow)
return StartZoneRight();
else
return StartZoneLeft();
}
public static IShape StartZoneOpponent()
{
if (GameBoard.MyColor == GameBoard.ColorRightYellow)
return StartZoneLeft();
else
return StartZoneRight();
}
private static IShape StartZoneLeft()
{
return new PolygonRectangle(new RealPoint(0, 300), 400, 900);
}
private static IShape StartZoneRight()
{
return new PolygonRectangle(new RealPoint(2550, 300), 400, 900);
}
public static void Init()
{
}
private static void LidarAvoid_NewMeasure(List<RealPoint> measure)
{
List<RealPoint> pts = measure.Where(o => IsInside(o, 100)).ToList();
pts = pts.Where(o => o.Distance(Robots.MainRobot.Position.Coordinates) > 300).ToList();
List<List<RealPoint>> groups = pts.GroupByDistance(50);
List<RealPoint> obstacles = new List<RealPoint>();
foreach (List<RealPoint> group in groups)
{
if (DetectionIsOpponent(group))
{
RealPoint center = group.GetBarycenter();
if (!obstacles.Exists(o => o.Distance(center) < 150))
obstacles.Add(center);
}
}
SetOpponents(obstacles);
}
private static bool DetectionIsOpponent(List<RealPoint> group)
{
return group.Count > 2;// && group.GetContainingCircle().Radius < 100; // On pourrai ignorer les murs avec la contrainte de taille, mais c'est pratique de ne pas rentrer dans les murs finallement...
}
/// <summary>
/// Teste si on point est contenu dans la table
/// </summary>
/// <param name="croisement">Point à tester</param>
/// <returns></returns>
public static bool Contains(RealPoint point)
{
return new PolygonRectangle(new RealPoint(0, 0), Height, Width).Contains(point);
}
/// <summary>
/// Crée le graph du pathfinding.
/// </summary>
/// <param name="resolution">Distance (mm) entre chaque noeud du graph en X et Y</param>
/// <param name="distanceLiaison">Distance (mm) jusqu'à laquelle les noeuds sont reliés par un arc. Par défaut on crée un graph minimal (liaison aux 8 points alentours : N/S/E/O/NE/NO/SE/SO)</param>
private void CreateGraph(int resolution, double distanceLiaison = -1)
{
if (distanceLiaison == -1)
distanceLiaison = Math.Sqrt((resolution * resolution) * 2) * 1.05; //+5% pour prendre large
Robots.MainRobot.Graph = new Graph(resolution, distanceLiaison);
// Création des noeuds
for (int x = resolution / 2; x < Width; x += resolution)
for (int y = resolution / 2; y < Height; y += resolution)
Robots.MainRobot.Graph.AddNode(new Node(x, y), _obstacles.FromBoard, Robots.MainRobot.Radius, true);
}
/// <summary>
/// Retourne la vitesse à adopter en fonction de la proximité de l'adversaire
/// </summary>
/// <param name="opponentDist">DIstance de l'adveraire</param>
/// <param name="maxSpeed">Vitesse de pointe maximum</param>
/// <returns>Vitese maximale prenant en compte la proximité de l'adversaire</returns>
private static int SpeedWithOpponent(double opponentDist, int maxSpeed)
{
double minPower = 0.20;
double minDist = 250;
double maxPowerDist = 600;
double factor;
if (opponentDist < minDist)
factor = minPower;
else
{
factor = Math.Min((Math.Pow(opponentDist - minDist, 2) / Math.Pow((maxPowerDist - minDist), 2)) * (1 - minPower) + minPower, 1);
if (factor < 0.6)
factor = 0.6;
else
factor = 1;
}
return (int)(factor * maxSpeed);
}
public static void RemoveVirtualBuoy(RealPoint center)
{
Buoy b = _elements.FindBuoy(center);
if (b.IsVirtual)_elements.RemoveBuoy(b);
}
}
}
<file_sep>/GoBot/GoBot/EventsReplay.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Windows.Forms;
using System.Threading;
namespace GoBot
{
/// <summary>
/// Permet de sauvegarder l'historique des trames reçue ainsi que leur heure d'arrivée
/// </summary>
[Serializable]
public class EventsReplay
{
/// <summary>
/// Liste des trames
/// </summary>
public List<HistoLigne> Events { get; private set; }
public EventsReplay()
{
Events = new List<HistoLigne>();
}
/// <summary>
/// Ajoute une trame reçue avec l'heure définie
/// </summary>
public void AjouterEvent(HistoLigne _event)
{
lock (Events)
Events.Add(_event);
}
/// <summary>
/// Charge une sauvegarde de Replay
/// </summary>
/// <param name="nomFichier">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde a été correctement chargée</returns>
public bool Charger(String nomFichier)
{
try
{
XmlSerializer mySerializer = new XmlSerializer(typeof(List<HistoLigne>));
using (FileStream myFileStream = new FileStream(nomFichier, FileMode.Open))
Events = (List<HistoLigne>)mySerializer.Deserialize(myFileStream);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Sauvegarde l'ensemble des trames dans un fichier
/// </summary>
/// <param name="nomFichier">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde s'est correctement déroulée</returns>
public bool Sauvegarder(String nomFichier)
{
try
{
XmlSerializer mySerializer = new XmlSerializer(typeof(List<HistoLigne>));
using (StreamWriter myWriter = new StreamWriter(nomFichier))
mySerializer.Serialize(myWriter, Events);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Permet de simuler la réception des trames enregistrées en respectant les intervalles de temps entre chaque trame
/// </summary>
public void Rejouer()
{
for (int i = Events.Count - 1; i >= 0; i--)
{
Robots.DicRobots[Events[i].Robot].Historique.Log(Events[i].Message, Events[i].Type);
if (i - 1 > 0)
Thread.Sleep(Events[i].Heure - Events[i - 1].Heure);
}
}
public void Trier()
{
Events.Sort();
}
}
}<file_sep>/GoBot/GoBot/IHM/Panels/PanelActuatorsOnOff.cs
using System;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class PanelActuatorsOnOff : UserControl
{
public PanelActuatorsOnOff()
{
InitializeComponent();
}
private void PanelActuatorsOnOff_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
int y = 20;
foreach (ActuatorOnOffID actuator in Enum.GetValues(typeof(ActuatorOnOffID)))
{
PanelActuatorOnOff panel = new PanelActuatorOnOff();
panel.SetBounds(5, y, grpActuatorsOnOff.Width - 10, panel.Height);
panel.SetActuator(actuator);
y += panel.Height;
grpActuatorsOnOff.Controls.Add(panel);
}
grpActuatorsOnOff.Height = y + 5;
this.Height = grpActuatorsOnOff.Bottom + 3;
}
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyRoundTrip.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
namespace GoBot.Strategies
{
/// <summary>
/// Stratégie qui consiste à faire des aller-retours sur la piste (pour homologuation d'évitement par exemple)
/// </summary>
class StrategyRoundTrip : Strategy
{
public override bool AvoidElements => false;
protected override void SequenceBegin()
{
Robots.MainRobot.UpdateGraph(GameBoard.ObstaclesAll);
//Plateau.Balise.VitesseRotation(250);
// Sortir ICI de la zone de départ pour commencer
Robots.MainRobot.MoveForward(200);
}
protected override void SequenceCore()
{
while (IsRunning)
{
while (!Robots.MainRobot.GoToPosition(new Position(0, new RealPoint(700, 1250)))) ;
while (!Robots.MainRobot.GoToPosition(new Position(180, new RealPoint(3000 - 700, 1250)))) ;
}
}
}
}
<file_sep>/GoBot/Composants/SwitchButton.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace Composants
{
public partial class SwitchButton : UserControl
{
public SwitchButton()
{
InitializeComponent();
_value = false;
_isMirrored = true;
Invalidate();
}
public delegate void ValueChangedDelegate(object sender, bool value);
/// <summary>
/// Se produit lorsque l'état du bouton change
/// </summary>
public event ValueChangedDelegate ValueChanged;
private bool _value;
private bool _isMirrored;
private bool _isFocus;
/// <summary>
/// Retourne vrai ou faux selon l'état du composant
/// </summary>
public bool Value
{
get
{
return _value;
}
set
{
if (this._value != value)
{
this._value = value;
Invalidate();
OnValueChanged();
}
}
}
/// <summary>
/// Mettre à vrai pour activer le contrôle de droite à gauche au lieu de gauche à droite
/// </summary>
public bool Mirrored
{
get
{
return _isMirrored;
}
set
{
_isMirrored = value;
Invalidate();
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
Value = (!Value);
}
protected override void OnEnter(EventArgs e)
{
_isFocus = true;
Invalidate();
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
_isFocus = false;
Invalidate();
base.OnLeave(e);
}
protected void OnValueChanged()
{
ValueChanged?.Invoke(this, _value);
}
protected override void OnPaint(PaintEventArgs e)
{
GraphicsPath path = new GraphicsPath();
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
int w, h;
bool ballOnLeft;
w = Width - 1;
h = Height - 1;
path.AddLine(h / 2 + 1, 1, w - h / 2 - 1, 1);
path.AddArc(new Rectangle(w - h - 1, 1, h - 2, h - 2), -90, 180);
path.AddLine(w - h / 2 - 1, h - 1, h / 2 + 1, h - 1);
path.AddArc(new Rectangle(1, 1, h - 2, h - 2), 90, 180);
Rectangle rBall;
if (_value)
{
Brush b = new LinearGradientBrush(new Rectangle(1, 1, w - 2, h - 2), Color.FromArgb(43, 226, 75), Color.FromArgb(36, 209, 68), 12);
e.Graphics.FillPath(b, path);
b.Dispose();
Pen p = new Pen(Color.FromArgb(22, 126, 40));
e.Graphics.DrawPath(p, path);
p.Dispose();
ballOnLeft = _isMirrored;
}
else
{
e.Graphics.FillPath(Brushes.WhiteSmoke, path);
ballOnLeft = !_isMirrored;
e.Graphics.DrawPath(Pens.LightGray, path);
}
if (ballOnLeft)
rBall = new Rectangle(0, 0, h, h);
else
rBall = new Rectangle(w - h, 0, h, h);
Brush bBall = new LinearGradientBrush(rBall, Color.WhiteSmoke, Color.LightGray, 100);
e.Graphics.FillEllipse(bBall, rBall);
bBall.Dispose();
e.Graphics.DrawEllipse(_isFocus ? Pens.DodgerBlue : Pens.Gray, rBall);
path.Dispose();
//base.OnPaint(e);
}
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
}
private void SwitchButton_MouseClick(object sender, MouseEventArgs e)
{
Focus();
Value = !Value;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/RealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Geometry.Shapes.ShapesInteractions;
namespace Geometry.Shapes
{
public class RealPoint : IShape, IShapeModifiable<RealPoint>
{
public const double PRECISION = 0.01;
#region Attributs
private double _x;
private double _y;
#endregion
#region Constructeurs
/// <summary>
/// Constructeur par défaut, les coordonnées seront (0, 0)
/// </summary>
public RealPoint()
{
_x = 0;
_y = 0;
}
/// <summary>
/// Constructeur par copie
/// </summary>
public RealPoint(RealPoint other)
{
_x = other._x;
_y = other._y;
}
/// <summary>
/// Construit des coordonnées selon x et y
/// </summary>
/// <param name="x">Abscisse</param>
/// <param name="y">Ordonnée</param>
public RealPoint(double x, double y)
{
_x = x;
_y = y;
}
#endregion
#region Propriétés
/// <summary>
/// Obtient ou définit la position sur l'axe des abscisses
/// </summary>
public double X { get { return _x; } set { _x = value; } }
/// <summary>
/// Obtient ou définit la coordonnée sur l'axe des ordonnées
/// </summary>
public double Y { get { return _y; } set { _y = value; } }
/// <summary>
/// Obtient la surface du point (toujours 0)
/// </summary>
public double Surface { get { return 0; } }
/// <summary>
/// Obtient le barycentre du point (toujours lui même)
/// </summary>
public RealPoint Barycenter { get { return new RealPoint(this); } }
#endregion
#region Opérateurs & Surcharges
public static bool operator ==(RealPoint a, RealPoint b)
{
if (a is null || b is null)
return (a is null && b is null);
else
return (Math.Abs(a.X - b.X) < PRECISION && Math.Abs(a.Y - b.Y) < PRECISION);
}
public static bool operator !=(RealPoint a, RealPoint b)
{
return !(a == b);
}
public static RealPoint operator -(RealPoint a, RealPoint b)
{
return new RealPoint(a.X - b.X, a.Y - b.Y);
}
public static RealPoint operator +(RealPoint a, RealPoint b)
{
return new RealPoint(a.X + b.X, a.Y + b.Y);
}
public override string ToString()
{
return "{" + X.ToString("0.00") + " : " + Y.ToString("0.00") + "}";
}
public override bool Equals(object o)
{
RealPoint p = o as RealPoint;
return (p != null) && (p == this);
}
public override int GetHashCode()
{
//return (int)X ^ (int)Y;
return (int)(_x * _y);
//return (int)(_x*10000 + _y);
}
public static implicit operator Point(RealPoint point)
{
return new Point((int)point.X, (int)point.Y);
}
public static implicit operator RealPoint(Point point)
{
return new RealPoint(point.X, point.Y);
}
public static implicit operator PointF(RealPoint point)
{
return new PointF((float)point.X, (float)point.Y);
}
public static implicit operator RealPoint(PointF point)
{
return new RealPoint(point.X, point.Y);
}
#endregion
#region Distance
/// <summary>
/// Retourne la distance minimale entre le PointReel courant et la IForme donnée
/// </summary>
/// <param name="shape">IForme testée</param>
/// <returns>Distance minimale</returns>
public double Distance(IShape shape)
{
double output = 0;
if (shape is RealPoint) output = RealPointWithRealPoint.Distance(this, shape as RealPoint);
else if (shape is Segment) output = RealPointWithSegment.Distance(this, shape as Segment);
else if (shape is Polygon) output = RealPointWithPolygon.Distance(this, shape as Polygon);
else if(shape is Circle) output = RealPointWithCircle.Distance(this, shape as Circle);
else if (shape is Line) output = RealPointWithLine.Distance(this, shape as Line);
return output;
}
#endregion
#region Contient
/// <summary>
/// Teste si le PointReel contient la IForme donnée
/// </summary>
/// <param name="shape">IForme testée</param>
/// <returns>Vrai si le PointReel contient la IForme testée</returns>
public bool Contains(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = RealPointWithRealPoint.Contains(this, shape as RealPoint);
else if (shape is Segment) output = RealPointWithSegment.Contains(this, shape as Segment);
else if (shape is Polygon) output = RealPointWithPolygon.Contains(this, shape as Polygon);
else if (shape is Circle) output = RealPointWithCircle.Contains(this, shape as Circle);
else if (shape is Line) output = RealPointWithLine.Contains(this, shape as Line);
return output;
}
#endregion
#region Croisement
/// <summary>
/// Teste si le PointReel courant croise la IForme donnée
/// Pour un PointReel, on dit qu'il croise s'il se trouve sur le contour de la forme avec une marge de <c>PRECISION</c>
/// </summary>
/// <param name="shape">IForme testés</param>
/// <returns>Vrai si le PointReel courant croise la IForme donnée</returns>
public bool Cross(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = RealPointWithRealPoint.Cross(this, shape as RealPoint);
else if (shape is Segment) output = RealPointWithSegment.Cross(this, shape as Segment);
else if (shape is Polygon) output = RealPointWithPolygon.Cross(this, shape as Polygon);
else if (shape is Circle) output = RealPointWithCircle.Cross(this, shape as Circle);
else if (shape is Line) output = RealPointWithLine.Cross(this, shape as Line);
return output;
}
/// <summary>
/// Retourne les points de croisements entre ce point et la forme donnée. Le croisement ne peut au mieux qu'être le point lui même.
/// </summary>
/// <param name="shape">Forme avec laquelle tester les croisements</param>
/// <returns>Points de croisement</returns>
public List<RealPoint> GetCrossingPoints(IShape shape)
{
List<RealPoint> output = new List<RealPoint>();
if (shape is RealPoint) output = RealPointWithRealPoint.GetCrossingPoints(this, shape as RealPoint);
else if (shape is Segment) output = RealPointWithSegment.GetCrossingPoints(this, shape as Segment);
else if (shape is Polygon) output = RealPointWithPolygon.GetCrossingPoints(this, shape as Polygon);
else if (shape is Circle) output = RealPointWithCircle.GetCrossingPoints(this, shape as Circle);
else if (shape is Line) output = RealPointWithLine.GetCrossingPoints(this, shape as Line);
return output;
}
#endregion
#region Transformations
/// <summary>
/// Affecte les coordonnées passées en paramètre
/// </summary>
/// <param name="x">Abscisse</param>
/// <param name="y">Ordonnée</param>
public void Set(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// Affecte les coordonnées passées en paramètre
/// </summary>
/// <param name="x">Abscisse</param>
/// <param name="y">Ordonnée</param>
public void Set(RealPoint pos)
{
_x = pos.X;
_y = pos.Y;
}
/// <summary>
/// Retourne un point translaté des distances données
/// </summary>
/// <param name="dx">Déplacement sur l'axe X</param>
/// <param name="dy">Déplacement sur l'axe Y</param>
/// <returns>Point translaté</returns>
public RealPoint Translation(double dx, double dy)
{
return new RealPoint(_x + dx, _y + dy);
}
/// <summary>
/// Retourne un point qui a subit une rotation selon l'angle et le centre donné
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de la rotation</param>
/// <returns>Point ayant subit la rotation donnée</returns>
public RealPoint Rotation(AngleDelta angle, RealPoint rotationCenter)
{
RealPoint newPoint = new RealPoint();
newPoint.X = rotationCenter.X + angle.Cos * (this.X - rotationCenter.X) - angle.Sin * (this.Y - rotationCenter.Y);
newPoint.Y = rotationCenter.Y + angle.Cos * (this.Y - rotationCenter.Y) + angle.Sin * (this.X - rotationCenter.X);
return newPoint;
}
#endregion
#region Peinture
/// <summary>
/// Dessine le point sur un Graphic
/// </summary>
/// <param name="g">Graphic sur lequel dessiner</param>
/// <param name="outline">Pen pour dessiner le contour du point</param>
/// <param name="fill">Brush pour le remplissage du point</param>
/// <param name="scale">Echelle de conversion</param>
public void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale)
{
Point screenPosition = scale.RealToScreenPosition(this);
Rectangle rect = new Rectangle(screenPosition.X - (int)outline.Width, screenPosition.Y - (int)outline.Width, (int)outline.Width * 2, (int)outline.Width * 2);
if (fill != null)
g.FillEllipse(fill, rect);
if (outline != null)
{
Pen tmp = new Pen(outline.Color);
g.DrawEllipse(tmp, rect);
tmp.Dispose();
}
}
#endregion
#region Statiques
public static RealPoint Shift(RealPoint realPoint, double dx, double dy)
{
return new RealPoint(realPoint.X + dx, realPoint.Y + dy);
}
#endregion
}
}
<file_sep>/GoBot/GeometryTester/TestCircle.cs
using Geometry.Shapes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeometryTester
{
[TestClass]
public class TestCircle
{
[TestMethod]
public void TestConstructorStandard()
{
Circle c = new Circle(new RealPoint(10, 20), 30);
Assert.AreEqual(10, c.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestConstructorZero()
{
Circle c = new Circle(new RealPoint(0, 0), 0);
Assert.AreEqual(0, c.Center.X, RealPoint.PRECISION);
Assert.AreEqual(0, c.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(0, c.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestConstructorPositionNeg()
{
Circle c = new Circle(new RealPoint(-10, -20), 5);
Assert.AreEqual(-10, c.Center.X, RealPoint.PRECISION);
Assert.AreEqual(-20, c.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(5, c.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestConstructorRadiusNeg()
{
Assert.ThrowsException<ArgumentException>(() => new Circle(new RealPoint(0, 0), -5));
}
[TestMethod]
public void TestConstructorCopy()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(c1);
Assert.AreEqual(10, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestTranslationStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Translation(25, 35);
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(10 + 25, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20 + 35, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestTranslationZero()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Translation(0, 0);
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(10, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestTranslationNeg()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Translation(-10, -20);
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(0, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(0, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestSurfaceStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(new RealPoint(0, 0), 30);
Circle c3 = new Circle(new RealPoint(50, 150), 45);
Assert.AreEqual(2827.43, c1.Surface, RealPoint.PRECISION);
Assert.AreEqual(2827.43, c2.Surface, RealPoint.PRECISION);
Assert.AreEqual(6361.73, c3.Surface, RealPoint.PRECISION);
}
[TestMethod]
public void TestSurfaceZero()
{
Circle c = new Circle(new RealPoint(10, 20), 0);
Assert.AreEqual(0, c.Surface, RealPoint.PRECISION);
}
[TestMethod]
public void TestBarycenterStandard()
{
Circle c = new Circle(new RealPoint(10, 20), 10);
Assert.AreEqual(10, c.Barycenter.X, RealPoint.PRECISION);
Assert.AreEqual(20, c.Barycenter.Y, RealPoint.PRECISION);
}
[TestMethod]
public void TestBarycenterZero()
{
Circle c = new Circle(new RealPoint(0, 0), 10);
Assert.AreEqual(0, c.Barycenter.X, RealPoint.PRECISION);
Assert.AreEqual(0, c.Barycenter.Y, RealPoint.PRECISION);
}
[TestMethod]
public void TestBarycenterNeg()
{
Circle c = new Circle(new RealPoint(-10, -20), 10);
Assert.AreEqual(-10, c.Barycenter.X, RealPoint.PRECISION);
Assert.AreEqual(-20, c.Barycenter.Y, RealPoint.PRECISION);
}
[TestMethod]
public void TestRotationFromBarycenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Rotation(90);
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(10, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestRotationFromZero()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Rotation(90, new RealPoint(0, 0));
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(-20, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(10, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
[TestMethod]
public void TestRotationFromStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = c1.Rotation(-90, new RealPoint(5, 5));
Assert.AreEqual(10, c1.Center.X, RealPoint.PRECISION);
Assert.AreEqual(20, c1.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c1.Radius, RealPoint.PRECISION);
Assert.AreEqual(20, c2.Center.X, RealPoint.PRECISION);
Assert.AreEqual(0, c2.Center.Y, RealPoint.PRECISION);
Assert.AreEqual(30, c2.Radius, RealPoint.PRECISION);
}
}
}<file_sep>/GoBot/Geometry/VolatileResult.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry
{
/// <summary>
/// Classe de stockage d'un résultat qui n'est calculé que quand nécessaire et stocké pour une future utilisation.
/// </summary>
/// <typeparam name="T"></typeparam>
public class VolatileResult<T>
{
private T _result;
private CalculDelegate _calcul;
private bool _computed;
public delegate T CalculDelegate();
/// <summary>
/// Crée la valeur volatile en spécifiant la fonction de calcul pour obtenir le résultat
/// </summary>
/// <param name="calcul"></param>
public VolatileResult(CalculDelegate calcul)
{
_calcul = calcul;
_computed = false;
}
/// <summary>
/// Obtient la valeur en la calculant automatiquement si c'est le premier appel depuis l'initialisation ou définit la valeur résultat.
/// </summary>
public T Value
{
get
{
if (!_computed)
{
_result = _calcul.Invoke();
_computed = true;
}
return _result;
}
set
{
_result = value;
_computed = true;
}
}
/// <summary>
/// Obtient si la valeur est actuellement définie ou non.
/// </summary>
public bool Computed
{
get
{
return _computed;
}
}
/// <summary>
/// Réinitialise la valeur calculée. La prochaine demande de valeur forcera le calcul.
/// </summary>
public void Reset()
{
_computed = false;
}
}
}
<file_sep>/GoBot/Geometry/AnglePosition.cs
using System;
namespace Geometry
{
public enum AngleType
{
Radian,
Degre
}
public struct AnglePosition
{
#region Constantes
public const double PRECISION = 0.01;
#endregion
#region Attributs
private double _angle;
#endregion
#region Constructeurs
/// <summary>
/// Construit un angle avec la valeur passée en paramètre
/// </summary>
/// <param name="angle">Angle de départ</param>
public AnglePosition(double angle, AngleType type = AngleType.Degre)
{
if (type == AngleType.Degre)
_angle = angle;
else
_angle = (double)(180 * angle / Math.PI);
_angle = _angle % 360;
if (_angle > 180)
_angle = _angle - 360;
if (_angle < -180)
_angle = _angle + 360;
}
#endregion
#region Trigonometrie
public double Cos
{
get
{
return Math.Cos(InRadians);
}
}
public double Sin
{
get
{
return Math.Sin(InRadians);
}
}
public double Tan
{
get
{
return Math.Tan(InRadians);
}
}
#endregion
#region Proprietes
/// <summary>
/// Retourne l'angle en radians (-PI à +PI)
/// </summary>
public double InRadians
{
get
{
return (double)(_angle / 180 * Math.PI);
}
}
/// <summary>
/// Retourne l'angle en degrés (-180 à +180)
/// </summary>
public double InDegrees
{
get
{
return _angle;
}
}
/// <summary>
/// Retourne l'angle en degrés positif (0 à 360)
/// </summary>
public double InPositiveDegrees
{
get
{
if (_angle < 0)
return 360 + _angle;
else
return _angle;
}
}
/// <summary>
/// Retourne l'angle en radians positif (0 à 2PI)
/// </summary>
public double InPositiveRadians
{
get
{
return InPositiveDegrees / 180 * Math.PI;
}
}
#endregion
#region Centre de l'arc
public static AnglePosition Center(AnglePosition startAngle, AnglePosition endAngle)
{
AnglePosition a;
if (startAngle.InPositiveDegrees < endAngle.InPositiveDegrees)
a = new AnglePosition((startAngle.InPositiveDegrees + endAngle.InPositiveDegrees) / 2);
else
a = new AnglePosition((startAngle.InPositiveDegrees + endAngle.InPositiveDegrees) / 2 + 180);
return a;
}
public static AnglePosition CenterSmallArc(AnglePosition a1, AnglePosition a2)
{
AnglePosition a;
if (Math.Abs(a1.InPositiveDegrees - a2.InPositiveDegrees) < 180)
return new AnglePosition((a1.InPositiveDegrees + a2.InPositiveDegrees) / 2);
else
a = new AnglePosition((a1.InPositiveDegrees + a2.InPositiveDegrees) / 2 + 180);
return a;
}
public static AnglePosition CenterLongArc(AnglePosition a1, AnglePosition a2)
{
AnglePosition a;
if (Math.Abs(a1.InPositiveDegrees - a2.InPositiveDegrees) > 180)
a = new AnglePosition((a1.InPositiveDegrees + a2.InPositiveDegrees) / 2);
else
a = new AnglePosition((a1.InPositiveDegrees + a2.InPositiveDegrees) / 2 + 180);
return a;
}
#endregion
#region Autres calculs
/// <summary>
/// Retourne si l'angle est compris entre les angles données, c'est à dire qu'il se situe dans l'arc de cercle partant de startAngle vers endAngle
/// Exemples :
/// 150° est entre 130° et 160° mais pas entre 160° et 130°
/// 10° est entre 350° et 50° mais pas entre 50° et 350°
/// </summary>
/// <param name="startAngle">Angle de départ</param>
/// <param name="endAngle">Angle d'arrivée</param>
/// <returns>Vrai si l'angle est compris entre les deux angles</returns>
public bool IsOnArc(AnglePosition startAngle, AnglePosition endAngle)
{
bool ok;
if (startAngle.InPositiveDegrees < endAngle.InPositiveDegrees)
ok = this.InPositiveDegrees >= startAngle.InPositiveDegrees && this.InPositiveDegrees <= endAngle.InPositiveDegrees;
else
ok = this.InPositiveDegrees == startAngle.InPositiveDegrees || this.InPositiveDegrees == endAngle.InPositiveDegrees || !this.IsOnArc(endAngle, startAngle);
return ok;
}
#endregion
#region Operateurs
public static AnglePosition operator +(AnglePosition a1, AngleDelta a2)
{
return new AnglePosition(a1.InPositiveDegrees + a2.InDegrees, AngleType.Degre);
}
public static AnglePosition operator -(AnglePosition a1, AngleDelta a2)
{
return new AnglePosition(a1.InPositiveDegrees - a2.InDegrees, AngleType.Degre);
}
public static AngleDelta operator -(AnglePosition start, AnglePosition end)
{
double a = start.InDegrees - end.InDegrees;
if (a > 180)
a = -(360 - a);
if (a < -180)
a = 360 + a;
return new AngleDelta(a);
}
public static bool operator ==(AnglePosition a1, AnglePosition a2)
{
return Math.Abs((a1 - a2).InDegrees) <= PRECISION;
}
public static bool operator !=(AnglePosition a1, AnglePosition a2)
{
return !(a1 == a2);
}
public static implicit operator AnglePosition(double angle)
{
return new AnglePosition(angle);
}
public static implicit operator double(AnglePosition angle)
{
return angle.InDegrees;
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
try
{
return Math.Abs(((AnglePosition)obj)._angle - _angle) < PRECISION;
}
catch
{
return false;
}
}
public override int GetHashCode()
{
return (int)(_angle * (1 / PRECISION));
}
public override string ToString()
{
return _angle.ToString("0.00") + "°";
}
#endregion
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelActionneurGeneric.cs
using System;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
namespace GoBot.IHM
{
public partial class PanelActionneurGeneric : UserControl
{
private object obj;
public PanelActionneurGeneric()
{
InitializeComponent();
}
public void SetObject(Object o)
{
Type t = o.GetType();
obj = o;
int i = 25;
lblName.Text = t.Name;
foreach (MethodInfo method in t.GetMethods().Where(m => m.Name.StartsWith("Do")).OrderBy(s => s.Name))
{
Button b = new Button();
b.SetBounds(5, i, 120, 22);
b.Tag = method;
b.Text = method.Name.Substring(2);
b.Click += b_Click;
Controls.Add(b);
i += 26;
}
}
void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
Color oldColor = b.BackColor;
b.BackColor = Color.LightGreen;
Threading.ThreadManager.CreateThread(link =>
{
link.Name = b.Text;
MethodInfo method = ((MethodInfo)((Button)sender).Tag);
object[] parameters = method.GetParameters().Count() > 0 ? new Object[] { false } : null;
method.Invoke(obj, parameters);
b.InvokeAuto(() => b.BackColor = oldColor);
}).StartThread();
}
private void PanelActionneurGeneric_Load(object sender, EventArgs e)
{
BorderStyle = BorderStyle.None;
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/Arc.cs
using System;
namespace AStarFolder
{
public class Arc
{
private Node _startNode;
private Node _endNode;
private bool _passable;
private double _length;
public Arc(Node Start, Node End)
{
StartNode = Start;
EndNode = End;
_length = _startNode.Position.Distance(_endNode.Position);
_passable = true;
}
public Node StartNode
{
set
{
if(_startNode != null) _startNode.OutgoingArcs.Remove(this);
_startNode = value;
_startNode.OutgoingArcs.Add(this);
}
get { return _startNode; }
}
public Node EndNode
{
set
{
if (_endNode != null) _endNode.IncomingArcs.Remove(this);
_endNode = value;
_endNode.IncomingArcs.Add(this);
}
get { return _endNode; }
}
public bool Passable
{
set { _passable = value; }
get { return _passable; }
}
public double Length
{
get
{
return _length;
}
}
virtual public double Cost
{
get { return Math.Sqrt(_length); }
}
public override string ToString()
{
return _startNode.ToString() + "-->" + _endNode.ToString();
}
public override bool Equals(object o)
{
Arc arc = (Arc)o;
return arc != null && _startNode.Equals(arc._startNode) && _endNode.Equals(arc._endNode);
}
public override int GetHashCode()
{
return _startNode.GetHashCode() + _endNode.GetHashCode();
}
}
}
<file_sep>/GoBot/GoBot/Robots/Robot.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using AStarFolder;
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.Actions;
using GoBot.BoardContext;
using GoBot.PathFinding;
using GoBot.Threading;
namespace GoBot
{
public abstract class Robot
{
// Communication
public Board AsservBoard { get; protected set; }
public Historique Historique { get; protected set; }
public double BatterieVoltage { get; set; }
public double BatterieIntensity { get; set; }
// Constitution
public IDRobot IDRobot { get; private set; }
public string Name { get; private set; }
public Robot(IDRobot id, string name)
{
IDRobot = id;
Name = name;
SpeedConfig = new SpeedConfig(500, 1000, 1000, 500, 1000, 1000);
AsserStats = new AsserStats();
IsSpeedAdvAdaptable = true;
foreach (MotorID moteur in Enum.GetValues(typeof(MotorID)))
MotorState.Add(moteur, false);
foreach (SensorOnOffID o in Enum.GetValues(typeof(SensorOnOffID)))
SensorsOnOffValue.Add(o, false);
foreach (ActuatorOnOffID o in Enum.GetValues(typeof(ActuatorOnOffID)))
ActuatorOnOffState.Add(o, false);
foreach (SensorColorID o in Enum.GetValues(typeof(SensorColorID)))
SensorsColorValue.Add(o, Color.Black);
AnalogicPinsValue = new Dictionary<Board, List<double>>();
AnalogicPinsValue.Add(Board.RecIO, new List<double>());
AnalogicPinsValue.Add(Board.RecMove, new List<double>());
for (int i = 0; i < 9; i++)
{
AnalogicPinsValue[Board.RecIO].Add(0);
AnalogicPinsValue[Board.RecMove].Add(0);
}
NumericPinsValue = new Dictionary<Board, List<Byte>>();
NumericPinsValue.Add(Board.RecIO, new List<byte>());
NumericPinsValue.Add(Board.RecMove, new List<byte>());
for (int i = 0; i < 3 * 2; i++)
{
NumericPinsValue[Board.RecIO].Add(0);
NumericPinsValue[Board.RecMove].Add(0);
}
BatterieVoltage = 0;
Graph = null;
TrajectoryFailed = false;
TrajectoryCutOff = false;
TrajectoryRunning = null;
}
public virtual void ShowMessage(String message1, String message2)
{
}
public override string ToString()
{
return Name;
}
#region Pinout
public Dictionary<Board, List<double>> AnalogicPinsValue { get; protected set; }
public Dictionary<Board, List<byte>> NumericPinsValue { get; protected set; }
public abstract void ReadAnalogicPins(Board board, bool waitEnd = true);
public abstract void ReadNumericPins(Board board, bool waitEnd = true);
#endregion
#region Management
public abstract void Init();
public abstract void DeInit();
public abstract void EnablePower(bool on);
public abstract List<double>[] DiagnosticCpuPwm(int valuesCount);
public abstract List<int>[] DiagnosticPID(int steps, SensAR sens, int valuesCount);
public abstract List<int>[] DiagnosticLine(int distance, SensAR sens);
#endregion
#region Moves
public SpeedConfig SpeedConfig { get; protected set; }
public List<Position> PositionsHistorical { get; protected set; }
public AsserStats AsserStats { get; protected set; }
public bool AsserEnable { get; protected set; }
public abstract Position Position { get; protected set; }
public RealPoint PositionTarget { get; protected set; }
public bool IsInLineMove { get; protected set; }
public bool IsSpeedAdvAdaptable { get; protected set; }
public delegate void PositionChangedDelegate(Position position);
public event PositionChangedDelegate PositionChanged;
protected void OnPositionChanged(Position position)
{
PositionChanged?.Invoke(position);
}
public virtual void MoveForward(int distance, bool waitEnd = true)
{
if (distance > 0)
AsserStats.ForwardMoves.Add(distance);
else
AsserStats.BackwardMoves.Add(-distance);
}
public virtual void MoveBackward(int distance, bool waitEnd = true)
{
if (distance < 0)
AsserStats.ForwardMoves.Add(distance);
else
AsserStats.BackwardMoves.Add(-distance);
}
public void Move(int distance, bool waitEnd = true)
{
if (distance > 0)
MoveForward(distance, waitEnd);
else
MoveBackward(-distance, waitEnd);
}
public virtual void PivotLeft(AngleDelta angle, bool waitEnd = true)
{
AsserStats.LeftRotations.Add(angle);
}
public virtual void Pivot(AngleDelta angle, bool waitEnd = true)
{
if (angle > 0)
PivotLeft(angle, waitEnd);
else
PivotRight(-angle, waitEnd);
}
public virtual void PivotRight(AngleDelta angle, bool waitEnd = true)
{
AsserStats.RightsRotations.Add(angle);
}
public void SetSpeedSlow()
{
SpeedConfig.SetParams(Config.CurrentConfig.ConfigLent);
IsSpeedAdvAdaptable = false;
}
public void SetSpeedVerySlow()
{
SpeedConfig.SetParams(100, 500, 500, 100, 500, 500);
IsSpeedAdvAdaptable = false;
}
public void SetSpeedVeryFast()
{
SpeedConfig.SetParams(800, 2500, 2500, 800, 2500, 2500);
IsSpeedAdvAdaptable = false;
}
public void SetSpeedFast()
{
SpeedConfig.SetParams(Config.CurrentConfig.ConfigRapide);
IsSpeedAdvAdaptable = true;
}
public void GoToAngle(AnglePosition angle, double marge = 0)
{
AngleDelta diff = angle - Position.Angle;
if (Math.Abs(diff.InDegrees) > marge)
{
if (diff.InDegrees > 0)
PivotRight(diff.InDegrees);
else
PivotLeft(-diff.InDegrees);
}
}
public bool GoToPosition(Position dest)
{
Historique.Log("Lancement pathfinding pour aller en " + dest.ToString(), TypeLog.PathFinding);
Trajectory traj = PathFinder.ChercheTrajectoire(Graph, GameBoard.ObstaclesAll, GameBoard.ObstaclesOpponents, Position, dest, Radius, Robots.MainRobot.Width / 2);
if (traj == null)
return false;
RunTrajectory(traj);
return !TrajectoryCutOff && !TrajectoryFailed;
}
public abstract void PolarTrajectory(SensAR sens, List<RealPoint> points, bool waitEnd = true);
public abstract void Stop(StopMode mode = StopMode.Smooth);
public abstract void Turn(SensAR sensAr, SensGD sensGd, int radius, AngleDelta angle, bool waitEnd = true);
public abstract void SetAsservOffset(Position newPosition);
public virtual void Recalibration(SensAR sens, bool waitEnd = true, bool sendOffset = false)
{
int angle = 0;
double toleranceXY = 30;
double toleranceTheta = 3;
double dist = (sens == SensAR.Avant ? Robots.MainRobot.LenghtFront : Robots.MainRobot.LenghtBack);
if (waitEnd && sendOffset)
{
if (Position.Angle.IsOnArc(0 - toleranceTheta, 0 + toleranceTheta))
angle = 0;
else if (Position.Angle.IsOnArc(90 - toleranceTheta, 90 + toleranceTheta))
angle = 90;
else if (Position.Angle.IsOnArc(180 - toleranceTheta, 180 + toleranceTheta))
angle = 180;
else if (Position.Angle.IsOnArc(270 - toleranceTheta, 270 + toleranceTheta))
angle = 270;
if (Position.Coordinates.X < dist + toleranceXY && Position.Coordinates.X > dist - toleranceTheta)
SetAsservOffset(new Position(angle, new RealPoint(dist, Position.Coordinates.Y)));
else if (Position.Coordinates.X > 3000 - dist)
SetAsservOffset(new Position(angle, new RealPoint(3000 - dist, Position.Coordinates.Y)));
else if (Position.Coordinates.Y < dist)
SetAsservOffset(new Position(angle, new RealPoint(Position.Coordinates.X, dist)));
else if (Position.Coordinates.Y > 2000 - dist)
SetAsservOffset(new Position(angle, new RealPoint(Position.Coordinates.X, 2000 - dist)));
}
}
public abstract void SendPID(int p, int i, int d);
public abstract void SendPIDCap(int p, int i, int d);
public abstract void SendPIDSpeed(int p, int i, int d);
#endregion
#region PathFinding
public Graph Graph { get; set; }
public bool TrajectoryFailed { get; protected set; }
public bool TrajectoryCutOff { get; protected set; }
public Trajectory TrajectoryRunning { get; protected set; }
public bool IsFarEnough(IShape target, IShape toAvoid, int margin = 0)
{
Type typeForme1 = target.GetType();
Type typeForme2 = toAvoid.GetType();
bool can;
if (typeForme1.IsAssignableFrom(typeof(Segment)))
if (typeForme2.IsAssignableFrom(typeof(Segment)))
can = ((Segment)target).Distance((Segment)toAvoid) > Radius + margin;
else
can = ((Segment)target).Distance(toAvoid) > Radius + margin;
else if (typeForme1.IsAssignableFrom(typeof(Circle)) && typeForme1.IsAssignableFrom(typeof(RealPoint)))
{
// très opportuniste
RealPoint c = ((Circle)target).Center;
RealPoint p = (RealPoint)toAvoid;
double dx = c.X - p.X;
double dy = c.Y - p.Y;
can = dx * dx + dy * dy > margin * margin;
}
else
can = target.Distance(toAvoid) > Radius + margin;
return can;
}
public bool OpponentsTrajectoryCollision(IEnumerable<IShape> opponents)
{
bool ok = true;
if (TrajectoryCutOff)
ok = false;
if (ok)
{
try
{
// Teste si le chemin en cours de parcours est toujours franchissable
if (TrajectoryRunning != null && TrajectoryRunning.Lines.Count > 0)
{
List<Segment> segmentsTrajectoire = new List<Segment>();
// Calcule le segment entre nous et notre destination (permet de ne pas considérer un obstacle sur un tronçon déjà franchi)
Segment toNextPoint = new Segment(Position.Coordinates, new RealPoint(TrajectoryRunning.Lines[0].EndPoint));
segmentsTrajectoire.Add(toNextPoint);
for (int iSegment = 1; iSegment < TrajectoryRunning.Lines.Count; iSegment++)
{
segmentsTrajectoire.Add(TrajectoryRunning.Lines[iSegment]);
}
foreach (IShape opponent in opponents)
{
foreach (Segment segment in segmentsTrajectoire)
{
// Marge de 30mm pour être plus permissif sur le passage et ne pas s'arreter dès que l'adversaire approche
if (!IsFarEnough(toNextPoint, opponent, -30))
{
// Demande de génération d'une nouvelle trajectoire
Historique.Log("Trajectoire coupée, annulation", TypeLog.PathFinding);
TrajectoryCutOff = true;
TrajectoryRunning = null;
if (IsInLineMove)
Stop();
ok = false;
break;
}
}
if (!ok)
break;
}
}
}
catch (Exception)
{
ok = false;
}
}
return ok;
}
public void UpdateGraph(IEnumerable<IShape> obstacles)
{
lock (Graph)
{
foreach (Arc arc in Graph.Arcs)
arc.Passable = true;
foreach (Node node in Graph.Nodes)
node.Passable = true;
foreach (IShape obstacle in obstacles)
{
// On ne désactive pas les arcs unitairement parce qu'on considère qu'ils sont trop courts pour qu'un arc non franchissable raccord 2 points franchissables
// Donc on ne teste que les noeuds non franchissables
for (int i = 0; i < Graph.Nodes.Count; i++)
{
Node n = Graph.Nodes[i];
if (n.Passable)
{
if (!IsFarEnough(obstacle, n.Position))
{
n.Passable = false;
// Désactivation des arcs connectés aux noeuds désactivés = 10 fois plus rapide que tester les arcs
foreach (Arc a in n.IncomingArcs) a.Passable = false;
foreach (Arc a in n.OutgoingArcs) a.Passable = false;
}
}
}
}
}
}
public bool RunTrajectory(Trajectory traj)
{
TrajectoryRunning = traj;
TimeSpan estimatedDuration = traj.GetDuration(this);
Stopwatch sw = Stopwatch.StartNew();
TrajectoryCutOff = false;
TrajectoryFailed = false;
foreach (IAction action in traj.ConvertToActions(this))
{
if (!Execution.Shutdown)
{
action.Executer();
if (TrajectoryCutOff || TrajectoryFailed)
break;
if (action is ActionAvance || action is ActionRecule)
{
Historique.Log("Noeud atteint " + TrajectoryRunning.Points[0].X.ToString("0") + ":" + TrajectoryRunning.Points[0].Y.ToString("0"), TypeLog.PathFinding);
TrajectoryRunning.RemovePoint(0);
}
}
}
if (!Execution.Shutdown)
{
TrajectoryRunning = null;
if (!TrajectoryCutOff && !TrajectoryFailed)
{
Historique.Log("Trajectoire parcourue en " + (sw.ElapsedMilliseconds / 1000.0).ToString("0.0") + "s (durée théorique : " + (estimatedDuration.TotalSeconds).ToString("0.0") + "s)", TypeLog.PathFinding);
return true;
}
if (TrajectoryFailed)
{
Historique.Log("Echec du parcours de la trajectoire (dérapage, blocage...)", TypeLog.PathFinding);
return false;
}
}
return false;
}
#endregion
#region Sensors
public bool StartTriggerEnable { get; protected set; } = false;
public Dictionary<SensorOnOffID, bool> SensorsOnOffValue { get; } = new Dictionary<SensorOnOffID, bool>();
public Dictionary<SensorColorID, Color> SensorsColorValue { get; } = new Dictionary<SensorColorID, Color>();
public delegate void SensorOnOffChangedDelegate(SensorOnOffID sensor, bool state);
public event SensorOnOffChangedDelegate SensorOnOffChanged;
public delegate void SensorColorChangedDelegate(SensorColorID sensor, Color color);
public event SensorColorChangedDelegate SensorColorChanged;
protected void OnSensorOnOffChanged(SensorOnOffID sensor, bool state)
{
SensorsOnOffValue[sensor] = state;
SensorOnOffChanged?.Invoke(sensor, state);
}
protected void OnSensorColorChanged(SensorColorID sensor, Color color)
{
SensorsColorValue[sensor] = color;
SensorColorChanged?.Invoke(sensor, color);
}
public abstract bool ReadSensorOnOff(SensorOnOffID sensor, bool waitEnd = true);
public abstract Color ReadSensorColor(SensorColorID sensor, bool waitEnd = true);
public abstract String ReadLidarMeasure(LidarID lidar, int timeout, out Position refPosition);
public abstract bool ReadStartTrigger();
public void EnableStartTrigger()
{
StartTriggerEnable = true;
}
#endregion
#region Actuators
public Dictionary<ActuatorOnOffID, bool> ActuatorOnOffState { get; } = new Dictionary<ActuatorOnOffID, bool>();
public Dictionary<MotorID, bool> MotorState { get; } = new Dictionary<MotorID, bool>();
public abstract void SetActuatorOnOffValue(ActuatorOnOffID actuator, bool on);
public virtual void SetMotorAtPosition(MotorID motor, int position, bool waitEnd = false)
{
//Historique.AjouterAction(new ActionMoteur(this, position, motor));
}
public virtual void SetMotorAtOrigin(MotorID motor, bool waitEnd = false)
{
//TODO historique ?
}
public virtual void MotorWaitEnd(MotorID moteur)
{
}
public virtual void SetMotorSpeed(MotorID moteur, SensGD sens, int vitesse)
{
if (MotorState.ContainsKey(moteur))
MotorState[moteur] = vitesse == 0 ? false : true;
Historique.AjouterAction(new ActionMoteur(this, vitesse, moteur));
}
public virtual void SetMotorReset(MotorID moteur)
{
}
public virtual void SetMotorStop(MotorID moteur, StopMode mode)
{
}
public virtual void SetMotorAcceleration(MotorID moteur, int acceleration)
{
Historique.AjouterAction(new ActionMoteur(this, acceleration, moteur));
}
public void ActuatorsStore()
{
Robots.MainRobot.SetAsservOffset(new Position(0, new RealPoint(1500, 1000)));
// TODOEACHYEAR Lister les actionneurs à ranger pour préparer un match
ThreadManager.CreateThread(link => { Actionneur.ElevatorLeft.DoStoreActuators(); }).StartThread();
ThreadManager.CreateThread(link => { Actionneur.ElevatorRight.DoStoreActuators(); }).StartThread();
Actionneur.FingerLeft.DoPositionHide();
Actionneur.FingerRight.DoPositionHide();
Actionneur.ElevatorLeft.DoGrabHide();
Actionneur.ElevatorRight.DoGrabHide();
Actionneur.Flags.DoCloseLeft();
Actionneur.Flags.DoCloseRight();
Actionneur.Lifter.DoStoreAll();
Actionneur.Lifter.DoLifterPositionStore();
Thread.Sleep(150);
Actionneur.Lifter.DoTilterPositionStore();
Thread.Sleep(1000);
Devices.AllDevices.CanServos.DisableAll();
}
public void ActuatorsDeploy()
{
// TODOEACHYEAR Lister les actionneurs à déployer
}
#endregion
#region Shape
public double LenghtFront { get; private set; }
public double LenghtBack { get; private set; }
public double LenghtTotal => LenghtBack + LenghtFront;
public double LenghtSquare => Math.Max(LenghtBack, LenghtFront) * 2;
public double Width { get; private set; }
public double Radius { get; private set; }
public double Diameter => Radius * 2;
public double WheelSpacing { get; private set; }
public void SetDimensions(double width, double lenghtFront, double lenghtBack, double wheelSpacing, double diameter)
{
LenghtFront = lenghtFront;
LenghtBack = lenghtBack;
Width = width;
WheelSpacing = wheelSpacing;
Radius = diameter / 2;
}
public IShape GetBounds()
{
IShape contact = new PolygonRectangle(new RealPoint(Position.Coordinates.X - LenghtBack / 2, Position.Coordinates.Y - Width / 2), LenghtBack + LenghtFront, Width);
contact = contact.Rotation(new AngleDelta(Position.Angle));
return contact;
}
#endregion
}
}
<file_sep>/TestShapes/MainForm.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace TestShapes
{
public partial class MainForm : Form
{
private enum ShapeMode
{
None,
Rectangle,
Circle,
CircleFromCenter,
Segment,
Line,
Zoom
}
private List<IShape> _shapes;
private WorldScale _worldScale;
private bool _barycenterVisible = true;
private bool _crossingPointsVisible = true;
private bool _crossingColorVisible = true;
private bool _containedColorVisible = true;
private bool _gridVisible = true;
private bool _axesVisible = false;
private ShapeMode _shapeMode;
private RealPoint _startPoint;
private IShape _currentShape;
private PolygonRectangle _rectZoomOrg, _rectZoomFinal;
ThreadLink _moveLoop;
double _moveVertical, _moveHorizontal;
double _moveZoom;
public MainForm()
{
InitializeComponent();
ThreadManager.Init();
_shapeMode = ShapeMode.Rectangle;
_shapes = new List<IShape>();
_shapes.Add(new Line(new RealPoint(10, 10), new RealPoint(10, 100)));
_shapes.Add(new Line(new RealPoint(20, 20), new RealPoint(100, 20)));
//_shapes.Add(new Segment(new RealPoint(66.5, 9.9), new RealPoint(13.5, 84.2)));
//_shapes.Add(new Segment(new RealPoint(46.6, 44), new RealPoint(30, 44)));
//_shapes.Add(new Circle(new RealPoint(200, 200), 30));
//_shapes.Add(new Circle(new RealPoint(250, 180), 30));
//_shapes.Add(new Segment(new RealPoint(10, 10), new RealPoint(300, 300)));
//_shapes.Add(new PolygonRectangle(new RealPoint(250, 250), 300, 50));
//_shapes.Add(new Circle(new RealPoint(260, 500), 30));
//_shapes.Add(new PolygonRectangle(new RealPoint(230, 400), 300, 40));
//_shapes.Add(new Circle(new RealPoint(320, 420), 15));
//_shapes.Add(new Circle(new RealPoint(100, 200), 15));
//_shapes.Add(new Circle(new RealPoint(100, 200), 30));
//_shapes.Add(new Circle(new RealPoint(100, 200), 45));
//_shapes.Add(new Circle(new RealPoint(100, 200), 60));
//_shapes.Add(new Circle(new RealPoint(80, 350), 15));
//_shapes.Add(new Circle(new RealPoint(80 + 14, 350), 30));
//_shapes.Add(new Circle(new RealPoint(80 + 14 + 14, 350), 45));
//_shapes.Add(new Circle(new RealPoint(80 + 14 + 14 + 14, 350), 60));
//_shapes.Add(new Circle(new RealPoint(80, 500), 15));
//_shapes.Add(new Circle(new RealPoint(80 + 14, 500), 30));
//_shapes.Add(new Circle(new RealPoint(80 + 14 + 14, 500), 45));
//_shapes.Add(new Circle(new RealPoint(80 + 14 + 14 + 14, 500), 60));
//_shapes.Add(new Segment(new RealPoint(80, 500), new RealPoint(180, 500)));
//_shapes.Add(new PolygonRectangle(new RealPoint(230, 400), 300, 40).Rotation(45));
}
#region Peinture
private void picWorld_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TranslateTransform(0, +picWorld.Height);
e.Graphics.ScaleTransform(1, -1);
DrawGrid(e.Graphics);
DrawAxes(e.Graphics);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
List<IShape> allShapes = new List<IShape>(_shapes);
if (_currentShape != null) allShapes.Add(_currentShape);
foreach (IShape shape in allShapes)
{
bool isContained = false;
bool isCrossed = false;
foreach (IShape otherShape in allShapes)
{
if (otherShape != shape)
{
if (shape.Cross(otherShape))
{
isCrossed = true;
shape.GetCrossingPoints(otherShape).ForEach(p => DrawCrossingPoint(p, e.Graphics));
}
isContained = isContained || otherShape.Contains(shape);
}
}
DrawShape(shape, isCrossed, isContained, e.Graphics);
DrawBarycenter(shape.Barycenter, e.Graphics);
}
if (_shapeMode == ShapeMode.Zoom && _rectZoomOrg != null)
{
if (_rectZoomOrg != null)
{
Pen pen = new Pen(Color.Black);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
_rectZoomOrg.Paint(e.Graphics, Color.LightGray, 1, Color.Transparent, _worldScale);
pen.Dispose();
}
if (_rectZoomFinal != null)
{
Pen pen = new Pen(Color.Black);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
_rectZoomFinal.Paint(e.Graphics, Color.DarkGray, 1, Color.Transparent, _worldScale);
pen.Dispose();
}
}
}
private void DrawAxes(Graphics g)
{
if (_axesVisible)
{
new Segment(new RealPoint(0, 0), new RealPoint(0, 150)).Paint(g, Color.Black, 3, Color.Transparent, _worldScale);
new Segment(new RealPoint(0, 150), new RealPoint(5, 145)).Paint(g, Color.Black, 2, Color.Transparent, _worldScale);
new Segment(new RealPoint(0, 150), new RealPoint(-5, 145)).Paint(g, Color.Black, 2, Color.Transparent, _worldScale);
new Segment(new RealPoint(0, 0), new RealPoint(150, 0)).Paint(g, Color.Black, 3, Color.Transparent, _worldScale);
new Segment(new RealPoint(150, 0), new RealPoint(145, 5)).Paint(g, Color.Black, 2, Color.Transparent, _worldScale);
new Segment(new RealPoint(150, 0), new RealPoint(145, -5)).Paint(g, Color.Black, 2, Color.Transparent, _worldScale);
RealPoint arc1 = _worldScale.RealToScreenPosition(new RealPoint(-80, -80));
RealPoint arc2 = _worldScale.RealToScreenPosition(new RealPoint(80, 80));
Rectangle r = new Rectangle((int)arc1.X, (int)arc1.Y, (int)(arc2.X - arc1.X), (int)(arc2.Y - arc1.Y));
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.DrawArc(Pens.Black, r, 0, 90);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
RealPoint arrow1 = new RealPoint(1, 80);
RealPoint arrow2 = new RealPoint(6, 85);
RealPoint arrow3 = new RealPoint(6, 75);
new Segment(arrow1, arrow2).Paint(g, Color.Black, 1, Color.Black, _worldScale);
new Segment(arrow1, arrow3).Paint(g, Color.Black, 1, Color.Black, _worldScale);
new RealPoint(0, 0).Paint(g, Color.Black, 3, Color.Black, _worldScale);
}
}
private void DrawBarycenter(RealPoint pt, Graphics g)
{
if (_barycenterVisible)
{
pt?.Paint(g, Color.Black, 3, Color.Blue, _worldScale);
}
}
private void DrawCrossingPoint(RealPoint pt, Graphics g)
{
if (_crossingPointsVisible)
{
pt.Paint(g, Color.Black, 5, Color.Red, _worldScale);
}
}
private void DrawShape(IShape shape, bool isCrossed, bool isContained, Graphics g)
{
Color outlineColor = Color.Black;
Color fillColor = Color.Transparent;
if (_crossingColorVisible)
{
if (isCrossed)
outlineColor = Color.Red;
else
outlineColor = Color.Green;
}
if (_containedColorVisible)
{
if (isContained)
fillColor = Color.FromArgb(100, Color.Green);
}
shape.Paint(g, outlineColor, 1, fillColor, _worldScale);
}
private void DrawGrid(Graphics g)
{
if (_gridVisible)
{
for (int i = -_worldScale.OffsetX / 10 * 10; i < picWorld.Width + _worldScale.OffsetX; i += 10)
new Segment(new RealPoint(i, -10000), new RealPoint(i, 10000)).Paint(g, Color.WhiteSmoke, 1, Color.Transparent, _worldScale);
for (int i = -_worldScale.OffsetY / 10 * 10; i < picWorld.Height + _worldScale.OffsetY; i += 10)
new Segment(new RealPoint(-10000, i), new RealPoint(10000, i)).Paint(g, Color.WhiteSmoke, 1, Color.Transparent, _worldScale);
new Segment(new RealPoint(0, -10000), new RealPoint(0, 10000)).Paint(g, Color.Black, 1, Color.Transparent, _worldScale);
new Segment(new RealPoint(-10000, 0), new RealPoint(10000, 0)).Paint(g, Color.Black, 1, Color.Transparent, _worldScale);
//for (int i = 0; i < picWorld.Width; i += 10)
// g.DrawLine(Pens.WhiteSmoke, i, 0, i, picWorld.Height);
//for (int i = 0; i < picWorld.Height; i += 10)
// g.DrawLine(Pens.WhiteSmoke, 0, i, picWorld.Width, i);
//for (int i = 0; i < picWorld.Width; i += 100)
// g.DrawLine(Pens.LightGray, i, 0, i, picWorld.Height);
//for (int i = 0; i < picWorld.Height; i += 100)
// g.DrawLine(Pens.LightGray, 0, i, picWorld.Width, i);
}
}
#endregion
#region Actions IHM
private void btnBarycenter_ValueChanged(object sender, bool value)
{
_barycenterVisible = value;
picWorld.Invalidate();
}
private void btnCrossing_ValueChanged(object sender, bool value)
{
_crossingColorVisible = value;
picWorld.Invalidate();
}
private void btnCrossingPoints_ValueChanged(object sender, bool value)
{
_crossingPointsVisible = value;
picWorld.Invalidate();
}
private void btnContained_ValueChanged(object sender, bool value)
{
_containedColorVisible = value;
picWorld.Invalidate();
}
private void btnGrid_ValueChanged(object sender, bool value)
{
_gridVisible = value;
picWorld.Invalidate();
}
#endregion
private RealPoint PicCoordinates()
{
RealPoint pt = picWorld.PointToClient(Cursor.Position);
RealPoint output = new RealPoint();
output.X = (-_worldScale.OffsetX + pt.X) * _worldScale.Factor;
output.Y = ( + (picWorld.Height - pt.Y) - _worldScale.OffsetY) * _worldScale.Factor;
Console.WriteLine(_worldScale.OffsetY + " / " + pt.Y);
return output;
}
private void picWorld_MouseDown(object sender, MouseEventArgs e)
{
_startPoint = PicCoordinates();
if (_shapeMode == ShapeMode.Zoom)
{
_rectZoomOrg = new PolygonRectangle(_startPoint, 1, 1);
}
else
{
_currentShape = BuildCurrentShape(_shapeMode, _startPoint, _startPoint);
}
picWorld.Invalidate();
}
private void picWorld_MouseMove(object sender, MouseEventArgs e)
{
RealPoint pos = PicCoordinates();
lblPosition.Text = "X = " + pos.X.ToString().PadLeft(4) + ": Y = " + pos.Y.ToString().PadLeft(4);
if (_startPoint != null)
{
if (_shapeMode == ShapeMode.Zoom)
{
double dx = pos.X - _startPoint.X;
double dy = pos.Y - _startPoint.Y;
double finalDx = dx;
double finalDy = dy;
_rectZoomOrg = new PolygonRectangle(_startPoint, dx, dy);
if (Math.Abs(dx / dy) > Math.Abs(picWorld.Width / picWorld.Height))
finalDx = Math.Sign(dx) * (picWorld.Width * (Math.Abs(dy) / picWorld.Height));
else
finalDy = Math.Sign(dy) * (picWorld.Height * (Math.Abs(dx) / picWorld.Width));
_rectZoomFinal = new PolygonRectangle(RealPoint.Shift(_startPoint, -(finalDx - dx) / 2, -(finalDy - dy) / 2), finalDx, finalDy);
}
else if (_shapeMode != ShapeMode.None)
{
_currentShape = BuildCurrentShape(_shapeMode, _startPoint, pos);
lblItem.Text = _currentShape.GetType().Name + " : " + _currentShape.ToString();
}
picWorld.Invalidate();
}
}
private void picWorld_MouseUp(object sender, MouseEventArgs e)
{
if (_startPoint != null)
{
if (_shapeMode == ShapeMode.Zoom)
{
double dx = _rectZoomFinal.Points.Max(pt => pt.X) - _rectZoomFinal.Points.Min(pt => pt.X);
//dx = _worldScale.RealToScreenDistance(dx);
WorldScale finalScale = CreateWorldScale(dx / picWorld.Width, _rectZoomFinal.Barycenter);
_moveZoom = (_worldScale.Factor - finalScale.Factor) / 20;
_moveHorizontal = -finalScale.ScreenToRealDistance((finalScale.OffsetX - _worldScale.OffsetX) / 20);
_moveVertical = -finalScale.ScreenToRealDistance((finalScale.OffsetY - _worldScale.OffsetY) / 20);
_step = 0;
ThreadManager.CreateThread(o => ZoomStepParam()).StartLoop(20, 40);
//_worldScale = finalScale;
_startPoint = null;
_rectZoomFinal = null;
_rectZoomOrg = null;
_shapeMode = ShapeMode.None;
btnZoom.Checked = false;
}
else if (_shapeMode != ShapeMode.None)
{
_shapes.Add(BuildCurrentShape(_shapeMode, _startPoint, PicCoordinates()));
lblItem.Text = "";
_currentShape = null;
_startPoint = null;
}
picWorld.Invalidate();
}
}
private static IShape BuildCurrentShape(ShapeMode mode, RealPoint startPoint, RealPoint endPoint)
{
IShape output = null;
switch (mode)
{
case ShapeMode.Rectangle:
output = new PolygonRectangle(startPoint, endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
break;
case ShapeMode.Circle:
output = new Circle(new Segment(startPoint, endPoint).Barycenter, startPoint.Distance(endPoint) / 2);
break;
case ShapeMode.CircleFromCenter:
output = new Circle(startPoint, startPoint.Distance(endPoint));
break;
case ShapeMode.Segment:
output = new Segment(startPoint, endPoint);
break;
case ShapeMode.Line:
output = new Line(startPoint, endPoint);
break;
}
return output;
}
private void btnRectangle_CheckedChanged(object sender, EventArgs e)
{
if (btnRectangle.Checked) _shapeMode = ShapeMode.Rectangle;
}
private void btnCircle_CheckedChanged(object sender, EventArgs e)
{
if (btnCircle.Checked) _shapeMode = ShapeMode.Circle;
}
private void btnCircleFromCenter_CheckedChanged(object sender, EventArgs e)
{
if (btnCircleFromCenter.Checked) _shapeMode = ShapeMode.CircleFromCenter;
}
private void btnSegment_CheckedChanged(object sender, EventArgs e)
{
if (btnSegment.Checked) _shapeMode = ShapeMode.Segment;
}
private void btnLine_CheckedChanged(object sender, EventArgs e)
{
if (btnLine.Checked) _shapeMode = ShapeMode.Line;
}
private void btnErase_Click(object sender, EventArgs e)
{
_shapes.Clear();
picWorld.Invalidate();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (_shapes.Count > 0)
{
_shapes.RemoveAt(_shapes.Count - 1);
picWorld.Invalidate();
}
}
private void MainForm_Load(object sender, EventArgs e)
{
_worldScale = new WorldScale(1, picWorld.Width / 2, picWorld.Height / 2);
}
private void picWorld_SizeChanged(object sender, EventArgs e)
{
_worldScale = new WorldScale(1, picWorld.Width / 2, picWorld.Height / 2);
//SetScreenSize(picWorld.Size);
picWorld.Invalidate();
}
private void btnAxes_ValueChanged(object sender, bool value)
{
_axesVisible = value;
picWorld.Invalidate();
}
private void btnZoomPlus_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomPlus()).StartLoop(20, 20);
}
private void btnZoomMinus_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomMinus()).StartLoop(20, 20);
}
private void btnZoom_CheckedChanged(object sender, EventArgs e)
{
if (btnZoom.Checked) _shapeMode = ShapeMode.Zoom;
}
private WorldScale CreateWorldScale(double mmPerPixel, RealPoint center)
{
Console.WriteLine(center.ToString());
int x = (int)(picWorld.Width / 2 - center.X / mmPerPixel);
int y = (int)(picWorld.Height / 2 - center.Y / mmPerPixel);
return new WorldScale(mmPerPixel, x, y);
}
private RealPoint GetCenter()
{
return _worldScale.ScreenToRealPosition(new RealPoint(picWorld.Width / 2, picWorld.Height / 2));
}
private void btnUp_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomUp()).StartLoop(20, 20);
}
private void btnDown_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomDown()).StartLoop(20, 20);
}
private void btnRight_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomRight()).StartLoop(20, 20);
}
private void btnLeft_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(o => ZoomLeft()).StartLoop(20, 20);
}
private void ZoomPlus()
{
_worldScale = CreateWorldScale(_worldScale.Factor * 0.97, GetCenter());
picWorld.Invalidate();
}
private void ZoomMinus()
{
_worldScale = CreateWorldScale(_worldScale.Factor * (1 / 0.97), GetCenter());
picWorld.Invalidate();
}
private void ZoomUp()
{
double dx = 0;
double dy = _worldScale.ScreenToRealDistance(picWorld.Height / 60f);
_worldScale = CreateWorldScale(_worldScale.Factor, RealPoint.Shift(GetCenter(), dx, dy));
picWorld.Invalidate();
}
private void ZoomDown()
{
double dx = 0;
double dy = -_worldScale.ScreenToRealDistance(picWorld.Height / 60f);
_worldScale = CreateWorldScale(_worldScale.Factor, RealPoint.Shift(GetCenter(), dx, dy));
picWorld.Invalidate();
}
private void ZoomLeft()
{
double dx = -_worldScale.ScreenToRealDistance(picWorld.Height / 60f);
double dy = 0;
_worldScale = CreateWorldScale(_worldScale.Factor, RealPoint.Shift(GetCenter(), dx, dy));
picWorld.Invalidate();
}
private void ZoomRight()
{
double dx = _worldScale.ScreenToRealDistance(picWorld.Height / 60f);
double dy = 0;
_worldScale = CreateWorldScale(_worldScale.Factor, RealPoint.Shift(GetCenter(), dx, dy));
picWorld.Invalidate();
}
private void ZoomStep()
{
double dx = _worldScale.ScreenToRealDistance(picWorld.Height / 60f) * _moveHorizontal;
double dy = _worldScale.ScreenToRealDistance(picWorld.Height / 60f) * _moveVertical;
_worldScale = CreateWorldScale(_worldScale.Factor + _moveZoom, RealPoint.Shift(GetCenter(), dx, dy));
//_worldScale = CreateWorldScale(_worldScale.Factor + _moveZoom, GetCenter());
picWorld.Invalidate();
}
int _step;
private void ZoomStepParam()
{
if(_step < 20)
_worldScale = CreateWorldScale(_worldScale.Factor, RealPoint.Shift(GetCenter(), _moveHorizontal, _moveVertical));
else if(_step < 40)
_worldScale = CreateWorldScale(_worldScale.Factor - _moveZoom, GetCenter());
_step++;
if(_step == 40)
{
_moveHorizontal = 0;
_moveVertical = 0;
_moveZoom = 0;
}
picWorld.Invalidate();
}
private void MainForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
_moveVertical = 0;
}
else if (e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
_moveHorizontal = 0;
}
if (_moveVertical == 0 && _moveHorizontal == 0 && _moveLoop != null)
{
_moveLoop.Cancel();
_moveLoop.WaitEnd();
_moveLoop = null;
}
}
private void btnOrigin_Click(object sender, EventArgs e)
{
_worldScale = CreateWorldScale(_worldScale.Factor, new RealPoint());
picWorld.Invalidate();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Down)
_moveVertical = -1;
else if (keyData == Keys.Up)
_moveVertical = 1;
else if (keyData == Keys.Left)
_moveHorizontal = -1;
else if (keyData == Keys.Right)
_moveHorizontal = 1;
if ((_moveVertical != 0 || _moveHorizontal != 0) && _moveLoop == null)
{
_moveLoop = ThreadManager.CreateThread(o => ZoomStep());
_moveLoop.StartInfiniteLoop(20);
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/RealPointWithLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class RealPointWithLine
{
public static bool Contains(RealPoint containingPoint, Line containedLine)
{
// Un point fini ne peut pas contenir une droite infinie
return false;
}
public static bool Cross(RealPoint point, Line line)
{
return LineWithRealPoint.Cross(line, point);
}
public static double Distance(RealPoint point, Line line)
{
return LineWithRealPoint.Distance(line, point);
}
public static List<RealPoint> GetCrossingPoints(RealPoint point, Line line)
{
return LineWithRealPoint.GetCrossingPoints(line, point);
}
}
}
<file_sep>/GoBot/Composants/TextBoxPlus.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class TextBoxPlus : TextBox
{
// Fonctionnalités supplémentaires :
// - Texte par défaut affiché en gris si aucun texte, disparition au focus
// DefaultText = "Exemple";
// - Mode erreur pour afficher le TextBox en rouge clair et police rouge. Disparition au focus.
// ErrorMode = true;
// - Mode numérique : n'accepte que les entiers
// TextMode = TextModeEnum.Numeric;
// - Mode décimal : n'accepte que les nombres décimaux
// TextMode = TextModeEnum.Decimal;
private String defaultText = "";
private bool errorMode = false;
public TextModeEnum TextMode { get; set; } = TextModeEnum.Text;
public enum TextModeEnum
{
Text,
Numeric,
Decimal
}
/// <summary>
/// Texte affiché par défaut si aucun autre texte n'est saisi
/// </summary>
public String DefaultText
{
get
{
return defaultText;
}
set
{
defaultText = value;
if (Text == "")
{
Text = defaultText;
ForeColor = Color.LightGray;
}
}
}
public TextBoxPlus()
{
InitializeComponent();
}
/// <summary>
/// Obtient ou définit si le mode erreur est activé
/// </summary>
public bool ErrorMode
{
get
{
return errorMode;
}
set
{
errorMode = value;
if (errorMode)
{
ForeColor = Color.Red;
BackColor = Color.Salmon;
}
else
{
BackColor = Color.White;
if (Text == DefaultText)
ForeColor = Color.LightGray;
else
ForeColor = Color.Black;
}
}
}
private void TextBoxPlus_Enter(object sender, EventArgs e)
{
ErrorMode = false;
if (Text == DefaultText)
{
ForeColor = Color.Black;
Text = "";
}
}
private void TextBoxPlus_Leave(object sender, EventArgs e)
{
if (Text == "")
{
ForeColor = Color.LightGray;
Text = DefaultText;
}
}
private void TextBoxPlus_KeyPress(object sender, KeyPressEventArgs e)
{
if (TextMode == TextModeEnum.Text)
return;
// Si la caractère tapé est numérique
if (char.IsNumber(e.KeyChar))
if (e.KeyChar == '²')
e.Handled = true; // Si c'est un '²', on gère l'evenement.
else
return;
// Si le caractère tapé est un caractère de "controle" (Enter, backspace, ...), on laisse passer
else if (char.IsControl(e.KeyChar) || (e.KeyChar == '.' && this.TextMode != TextModeEnum.Numeric))
e.Handled = false;
else
e.Handled = true;
}
}
}
<file_sep>/GoBot/GoBot/Communications/UDP/UdpFrameDecoder.cs
using System;
using System.Collections.Generic;
namespace GoBot.Communications.UDP
{
static class UdpFrameDecoder
{
public static String Decode(Frame trame)
{
return GetMessage(trame);
}
/// <summary>
/// Récupère le message explicite associé à une fonction du protocole.
/// Les paramètres sont signalés par des accolades indiquant la position dans la trame des octets correspondant à la valeur du paramètre.
/// Si les paramètres sont fournis, leur valeur remplacent les paramètres entre accolades.
/// </summary>
/// <param name="function"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static String GetMessage(UdpFrameFunction function, List<uint> parameters = null)
{
String output = "";
switch (function)
{
case UdpFrameFunction.DemandeTension:
output = "Demande tension";
break;
case UdpFrameFunction.RetourTension:
output = "Retour tension {0-1}V";
if (parameters != null)
{
output = ReplaceParam(output, (parameters[0] / 100f).ToString("0.00"));
}
break;
case UdpFrameFunction.DemandeLidar:
output = "Demande LIDAR";
break;
case UdpFrameFunction.ReponseLidar:
output = "Reponse LIDAR";
break;
case UdpFrameFunction.EnvoiUart2:
output = "Envoi UART2";
break;
case UdpFrameFunction.RetourUart2:
output = "Retour UART2";
break;
case UdpFrameFunction.DemandeValeursNumeriques:
output = "Demande valeurs des ports numériques";
break;
case UdpFrameFunction.RetourValeursNumeriques:
output = "Retour ports numériques : {0}_{1} / {2}_{3} / {4}_{5}";
if (parameters != null)
{
for (int i = 0; i < 6; i++)
output = ReplaceParam(output, Convert.ToString(parameters[i], 2).PadLeft(8, '0'));
}
break;
case UdpFrameFunction.Debug:
output = "Debug {0}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.TestConnexion:
output = "Test connexion";
break;
case UdpFrameFunction.DemandeCapteurOnOff:
output = "Demande capteur {0}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((SensorOnOffID)parameters[0]));
}
break;
case UdpFrameFunction.RetourCapteurOnOff:
output = "Retour capteur {0} : {1}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((SensorOnOffID)parameters[0]));
output = ReplaceParam(output, NameFinder.GetName(parameters[1] > 0));
}
break;
case UdpFrameFunction.DemandeValeursAnalogiques:
output = "Demande valeurs analogiques";
break;
case UdpFrameFunction.RetourValeursAnalogiques:
output = "Retour valeurs analogiques : {0}V / {1}V / {2}V / {3}V / {4}V / {5}V / {6}V / {7}V / {8}V";
if (parameters != null)
{
for (int i = 0; i < 8; i++)
{
output = ReplaceParam(output, (parameters[i] * 0.0008056640625).ToString("0.0000") + "V");
}
}
break;
case UdpFrameFunction.DemandeCapteurCouleur:
output = "Demande capteur couleur {0}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((SensorColorID)parameters[0]));
}
break;
case UdpFrameFunction.RetourCapteurCouleur:
output = "Retour capteur couleur {0} : {1}-{2}-{3}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((SensorColorID)parameters[0]));
output = ReplaceParam(output, parameters[1].ToString("000"));
output = ReplaceParam(output, parameters[2].ToString("000"));
output = ReplaceParam(output, parameters[3].ToString("000"));
}
break;
case UdpFrameFunction.DemandePositionCodeur:
output = "Demande position codeur {0}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((CodeurID)parameters[0]));
}
break;
case UdpFrameFunction.RetourPositionCodeur:
output = "Retour position codeur {0} : {1-2-3-4}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((CodeurID)parameters[0]));
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.PilotageOnOff:
output = "Pilote actionneur on off {0} : {1}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((ActuatorOnOffID)parameters[0]));
output = ReplaceParam(output, NameFinder.GetName(parameters[1] > 0));
}
break;
case UdpFrameFunction.MoteurPosition:
output = "Pilote moteur {0} position {1-2}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.MoteurVitesse:
output = "Pilote moteur {0} vitesse {2-3} vers la {1}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
output = ReplaceParam(output, parameters[1].ToString());
output = ReplaceParam(output, ((SensGD)parameters[2]).ToString().ToLower());
}
break;
case UdpFrameFunction.MoteurAccel:
output = "Pilote moteur {0} accélération {1-2}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.MoteurStop:
output = "Moteur {0} stoppé {1}";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
output = ReplaceParam(output, ((StopMode)parameters[1]).ToString());
}
break;
case UdpFrameFunction.MoteurOrigin:
output = "Envoi du moteur {0} à l'origine";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
}
break;
case UdpFrameFunction.MoteurResetPosition:
output = "Moteur {0} réintialisé à 0";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
}
break;
case UdpFrameFunction.MoteurFin:
output = "Moteur {0} arrivé à destination";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
}
break;
case UdpFrameFunction.MoteurBlocage:
output = "Moteur {0} bloqué";
if (parameters != null)
{
output = ReplaceParam(output, NameFinder.GetName((MotorID)parameters[0]));
}
break;
case UdpFrameFunction.Deplace:
output = "{0} sur {1-2} mm";
if (parameters != null)
{
output = ReplaceParam(output, (SensAR)parameters[0] == SensAR.Avant ? "Avance" : "Recule");
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.Pivot:
output = "Pivot {0} sur {1-2}°";
if (parameters != null)
{
output = ReplaceParam(output, ((SensGD)parameters[0]).ToString().ToLower());
output = ReplaceParam(output, (parameters[1] / 100.0).ToString());
}
break;
case UdpFrameFunction.Virage:
output = "Virage {0} {1} de {4-5}° sur un rayon de {2-3}mm";
if (parameters != null)
{
output = ReplaceParam(output, ((SensAR)parameters[0]).ToString().ToLower());
output = ReplaceParam(output, ((SensGD)parameters[1]).ToString().ToLower());
output = ReplaceParam(output, (parameters[2] / 100.0).ToString());
output = ReplaceParam(output, parameters[3].ToString());
}
break;
case UdpFrameFunction.Stop:
output = "Stop {0}";
if (parameters != null)
{
output = ReplaceParam(output, ((StopMode)parameters[0]).ToString().ToLower());
}
break;
case UdpFrameFunction.Recallage:
output = "Recallage {0}";
if (parameters != null)
{
output = ReplaceParam(output, ((SensAR)parameters[0]).ToString().ToLower());
}
break;
case UdpFrameFunction.TrajectoirePolaire:
output = "Trajectoire polaire {0} sur {1-2} points";
if (parameters != null)
{
output = ReplaceParam(output, ((SensAR)parameters[0]).ToString().ToLower());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.FinRecallage:
output = "Fin de recallage";
break;
case UdpFrameFunction.FinDeplacement:
output = "Fin de déplacement";
break;
case UdpFrameFunction.Blocage:
output = "Blocage !!!";
break;
case UdpFrameFunction.AsserDemandePositionCodeurs:
output = "Demande position codeurs déplacement";
break;
case UdpFrameFunction.AsserRetourPositionCodeurs:
output = "Retour position codeurs déplacement : {0} valeurs";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserEnvoiConsigneBrutePosition:
output = "Envoi consigne brute : {1-2} pas en {0}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, ((SensAR)parameters[0]).ToString().ToLower());
}
break;
case UdpFrameFunction.DemandeChargeCPU_PWM:
output = "Demande charge CPU PWM";
break;
case UdpFrameFunction.RetourChargeCPU_PWM:
output = "Retour charge CPU PWM : {0} valeurs";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserIntervalleRetourPosition:
output = "Intervalle de retour de la position : {0}ms";
if (parameters != null)
{
output = ReplaceParam(output, (parameters[0] * 10).ToString());
}
break;
case UdpFrameFunction.AsserDemandePositionXYTeta:
output = "Demande position X Y Teta";
break;
case UdpFrameFunction.AsserRetourPositionXYTeta:
output = "Retour position X = {0-1}mm Y = {2-3}mm Teta = {4-5}°";
if (parameters != null)
{
output = ReplaceParam(output, (parameters[0] / 10.0).ToString());
output = ReplaceParam(output, (parameters[1] / 10.0).ToString());
output = ReplaceParam(output, (parameters[2] / 100.0).ToString());
}
break;
case UdpFrameFunction.AsserVitesseDeplacement:
output = "Vitesse ligne : {0-1}mm/s";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserAccelerationDeplacement:
output = "Accélération ligne : {0-1}mm/s² au début, {2-3}mm/s² à la fin";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserVitessePivot:
output = "Vitesse pivot : {0-1}mm/s";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserAccelerationPivot:
output = "Accélération pivot : {0-1}mm/s²";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.AsserPID:
output = "Asservissement P={0-1} I={2-3} D={4-5}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, parameters[1].ToString());
output = ReplaceParam(output, parameters[2].ToString());
}
break;
case UdpFrameFunction.AsserEnvoiPositionAbsolue:
output = "Envoi position absolue : X={0-1}mm Y={2-3}mm Teta={4-5}°";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, parameters[1].ToString());
output = ReplaceParam(output, (parameters[2] / 100.0).ToString());
}
break;
case UdpFrameFunction.AsserPIDCap:
output = "Asservissement cap P={0-1} I={2-3} D={4-5}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, parameters[1].ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.AsserPIDVitesse:
output = "Asservissement vitesse P={0-1} I={2-3} D={4-5}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
output = ReplaceParam(output, parameters[1].ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case UdpFrameFunction.EnvoiUart1:
output = "Envoi UART {0} caractères";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.RetourUart1:
output = "Réception UART {0} caractères";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
case UdpFrameFunction.EnvoiCAN:
output = "Envoi message CAN";
break;
case UdpFrameFunction.ReponseCAN:
output = "Reception message CAN";
break;
case UdpFrameFunction.DemandeCouleurEquipe:
output = "Demande couleur équipe";
break;
case UdpFrameFunction.RetourCouleurEquipe:
output = "Retour couleur équipe : {0}";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString());
}
break;
default:
output = "Inconnu";
break;
}
return output;
}
/// <summary>
/// Retourne le message contenu dans une trame dans un texte explicite avec les paramètres décodés
/// </summary>
/// <param name="trame">Trame à décoder</param>
/// <returns>Message sur le contnu de la trame</returns>
public static String GetMessage(Frame trame)
{
String output = "";
output = GetMessage((UdpFrameFunction)trame[1]);
output = GetMessage((UdpFrameFunction)trame[1], GetParameters(output, trame));
return output;
}
/// <summary>
/// Retourne la liste des valeurs des paramètres d'une trame selon le format donné
/// </summary>
/// <param name="format">Format du décodage sous la forme "Message valeur = {0-1}" équivaut à un paramètre situé sur les 1er et 2eme octets.</param>
/// <param name="frame">Trame dans laquelle lire les valeurs</param>
/// <returns>Liste des valeurs brutes des paramètres</returns>
private static List<uint> GetParameters(String format, Frame frame)
{
List<uint> parameters = new List<uint>();
String subParameter;
for (int iChar = 0; iChar < format.Length; iChar++)
{
if (format[iChar] == '{')
{
iChar++;
parameters.Add(0);
while (format[iChar] != '}')
{
subParameter = "";
while (format[iChar] != '-' && format[iChar] != '}')
{
subParameter += format[iChar];
iChar++;
}
parameters[parameters.Count - 1] = parameters[parameters.Count - 1] * 256 + frame[int.Parse(subParameter) + 2];
if (format[iChar] == '-')
iChar++;
}
}
}
return parameters;
}
/// <summary>
/// Remplace le premier paramètre entre accolades par le message donné
/// </summary>
/// <param name="input">Chaine contenant le message entier paramétré</param>
/// <param name="msg">Message à écrire à la place du premier paramètre</param>
/// <returns>Chaine contenant le message avec le paramètre remplacé</returns>
private static String ReplaceParam(String input, String msg)
{
int iStart = input.IndexOf("{");
int iEnd = input.IndexOf("}");
String param = input.Substring(iStart, iEnd - iStart + 1);
String output = input.Replace(param, msg);
return output;
}
}
}
<file_sep>/GoBot/GoBot/Robots/RobotSimu.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Geometry;
using System.Timers;
using Geometry.Shapes;
using System.Threading;
using GoBot.Actions;
using System.Drawing;
using System.Diagnostics;
using GoBot.Threading;
using GoBot.BoardContext;
namespace GoBot
{
class RobotSimu : Robot
{
private Random _rand;
private Semaphore _lockMove;
private bool _highResolutionAsservissement;
private Position _destination;
private double _currentSpeed;
private SensGD _sensPivot;
private SensAR _sensMove;
private bool _inRecalibration;
private ThreadLink _linkAsserv, _linkLogPositions;
private Position _currentPosition;
private Stopwatch _asserChrono;
private int _currentPolarPoint;
private List<RealPoint> _polarTrajectory;
private long _lastTimerTick;
public override Position Position
{
get { return _currentPosition; }
protected set { _currentPosition = value; _destination = value; }
}
public RobotSimu(IDRobot idRobot) : base(idRobot, "Robot Simu")
{
_highResolutionAsservissement = true;
_rand = new Random();
_linkAsserv = ThreadManager.CreateThread(link => Asservissement());
_linkLogPositions = ThreadManager.CreateThread(link => LogPosition());
_lockMove = new Semaphore(1, 1);
_sensMove = SensAR.Avant;
_inRecalibration = false;
_asserChrono = null;
_currentPolarPoint = -1;
BatterieVoltage = 25;
}
public override void Init()
{
Historique = new Historique(IDRobot);
PositionsHistorical = new List<Position>();
Position = new Position(GoBot.Recalibration.StartPosition);
PositionTarget = null;
_linkAsserv.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, _highResolutionAsservissement ? 1 : 16));
_linkLogPositions.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 100));
}
public override void DeInit()
{
_linkAsserv.Cancel();
_linkLogPositions.Cancel();
_linkAsserv.WaitEnd();
_linkLogPositions.WaitEnd();
}
public override string ReadLidarMeasure(LidarID lidar, int timeout, out Position refPosition)
{
refPosition = new Position(_currentPosition);
// Pas de simulation de LIDAR
return "";
}
private void LogPosition()
{
_linkLogPositions.RegisterName();
lock (PositionsHistorical)
{
PositionsHistorical.Add(new Position(Position.Angle, new RealPoint(Position.Coordinates.X, Position.Coordinates.Y)));
while (PositionsHistorical.Count > 1200)
PositionsHistorical.RemoveAt(0);
}
}
private double GetCurrentLineBreakDistance()
{
return (_currentSpeed * _currentSpeed) / (2 * SpeedConfig.LineDeceleration);
}
private double GetCurrentAngleBreakDistance()
{
return (_currentSpeed * _currentSpeed) / (2 * SpeedConfig.PivotDeceleration);
}
private double DistanceBetween(List<RealPoint> points, int from, int to)
{
double distance = 0;
for (int i = from + 1; i <= to; i++)
distance += points[i - 1].Distance(points[i]);
return distance;
}
private void Asservissement()
{
_linkAsserv.RegisterName();
// Calcul du temps écoulé depuis la dernière mise à jour de la position
double interval = 0;
if (_asserChrono != null)
{
long currentTick = _asserChrono.ElapsedMilliseconds;
interval = currentTick - _lastTimerTick;
_lastTimerTick = currentTick;
}
else
_asserChrono = Stopwatch.StartNew();
if (interval > 0)
{
_lockMove.WaitOne();
if (_currentPolarPoint >= 0)
{
double distanceBeforeNext = Position.Coordinates.Distance(_polarTrajectory[_currentPolarPoint]);
double distanceBeforeEnd = distanceBeforeNext;
distanceBeforeEnd += DistanceBetween(_polarTrajectory, _currentPolarPoint, _polarTrajectory.Count - 1);
if (distanceBeforeEnd > GetCurrentAngleBreakDistance())
_currentSpeed = Math.Min(SpeedConfig.LineSpeed, _currentSpeed + SpeedConfig.LineAcceleration / (1000.0 / interval));
else
_currentSpeed = _currentSpeed - SpeedConfig.LineDeceleration / (1000.0 / interval);
double distanceToRun = _currentSpeed / (1000.0 / interval);
double distanceTested = distanceBeforeNext;
bool changePoint = false;
while (distanceTested < distanceToRun && _currentPolarPoint < _polarTrajectory.Count - 1)
{
_currentPolarPoint++;
distanceTested += _polarTrajectory[_currentPolarPoint - 1].Distance(_polarTrajectory[_currentPolarPoint]);
changePoint = true;
}
Segment segment;
Circle circle;
if (changePoint)
{
segment = new Segment(_polarTrajectory[_currentPolarPoint - 1], _polarTrajectory[_currentPolarPoint]);
circle = new Circle(_polarTrajectory[_currentPolarPoint - 1], distanceToRun - (distanceTested - _polarTrajectory[_currentPolarPoint - 1].Distance(_polarTrajectory[_currentPolarPoint])));
}
else
{
segment = new Segment(Position.Coordinates, _polarTrajectory[_currentPolarPoint]);
circle = new Circle(Position.Coordinates, distanceToRun);
}
RealPoint newPos = segment.GetCrossingPoints(circle)[0];
AngleDelta a = -Maths.GetDirection(newPos, _polarTrajectory[_currentPolarPoint]).angle;
_currentPosition = new Position(new AnglePosition(a), newPos);
OnPositionChanged(Position);
if (_currentPolarPoint == _polarTrajectory.Count - 1)
{
_currentPolarPoint = -1;
_destination.Copy(Position);
}
}
else
{
bool needLine = _destination.Coordinates.Distance(Position.Coordinates) > 0;
bool needAngle = Math.Abs(_destination.Angle - Position.Angle) > 0.01;
if (needAngle)
{
AngleDelta diff = Math.Abs(_destination.Angle - Position.Angle);
double speedWithAcceleration = Math.Min(SpeedConfig.PivotSpeed, _currentSpeed + SpeedConfig.PivotAcceleration / (1000.0 / interval));
double remainingDistanceWithAcceleration = CircleArcLenght(WheelSpacing, diff) - (_currentSpeed + speedWithAcceleration) / 2 / (1000.0 / interval);
if (remainingDistanceWithAcceleration > DistanceFreinage(speedWithAcceleration))
{
double distParcourue = (_currentSpeed + speedWithAcceleration) / 2 / (1000.0 / interval);
AngleDelta angleParcouru = (360 * distParcourue) / (Math.PI * WheelSpacing);
_currentSpeed = speedWithAcceleration;
Position.Angle += (_sensPivot.Factor() * angleParcouru);
}
else if (_currentSpeed > 0)
{
double speedWithDeceleration = Math.Max(0, _currentSpeed - SpeedConfig.PivotDeceleration / (1000.0 / interval));
double distParcourue = (_currentSpeed + speedWithDeceleration) / 2 / (1000.0 / interval);
AngleDelta angleParcouru = (360 * distParcourue) / (Math.PI * WheelSpacing);
_currentSpeed = speedWithDeceleration;
Position.Angle += (_sensPivot.Factor() * angleParcouru);
}
else
{
Position.Copy(_destination);
}
OnPositionChanged(Position);
}
else if (needLine)
{
double speedWithAcceleration = Math.Min(SpeedConfig.LineSpeed, _currentSpeed + SpeedConfig.LineAcceleration / (1000.0 / interval));
double remainingDistanceWithAcceleration = Position.Coordinates.Distance(_destination.Coordinates) - (_currentSpeed + speedWithAcceleration) / 2 / (1000.0 / interval);
// Phase accélération ou déccélération
if (remainingDistanceWithAcceleration > DistanceFreinage(speedWithAcceleration))
{
double distance = (_currentSpeed + speedWithAcceleration) / 2 / (1000.0 / interval);
_currentSpeed = speedWithAcceleration;
Position.Move(distance * _sensMove.Factor());
}
else if (_currentSpeed > 0)
{
double speedWithDeceleration = Math.Max(0, _currentSpeed - SpeedConfig.LineDeceleration / (1000.0 / interval));
double distance = Math.Min(_destination.Coordinates.Distance(Position.Coordinates), (_currentSpeed + speedWithDeceleration) / 2 / (1000.0 / interval));
_currentSpeed = speedWithDeceleration;
Position.Move(distance * _sensMove.Factor());
}
else
{
// Si on est déjà à l'arrêt on force l'équivalence de la position avec la destination.
Position.Copy(_destination);
IsInLineMove = false;
}
OnPositionChanged(Position);
}
}
_lockMove.Release();
}
}
private double DistanceFreinage(Double speed)
{
return (speed * speed) / (2 * SpeedConfig.LineDeceleration);
}
private double CircleArcLenght(double diameter, AngleDelta arc)
{
return Math.Abs(arc.InDegrees) / 360 * Math.PI * diameter;
}
public override void MoveForward(int distance, bool wait = true)
{
base.MoveForward(distance, wait);
IsInLineMove = true;
if (distance > 0)
{
if (!_inRecalibration)
Historique.AjouterAction(new ActionAvance(this, distance));
_sensMove = SensAR.Avant;
}
else
{
if (!_inRecalibration)
Historique.AjouterAction(new ActionRecule(this, -distance));
_sensMove = SensAR.Arriere;
}
_destination = new Position(Position.Angle, new RealPoint(Position.Coordinates.X + distance * Position.Angle.Cos, Position.Coordinates.Y + distance * Position.Angle.Sin));
// TODO2018 attente avec un sémaphore ?
if (wait)
while ((Position.Coordinates.X != _destination.Coordinates.X ||
Position.Coordinates.Y != _destination.Coordinates.Y) && !Execution.Shutdown)
Thread.Sleep(10);
}
public override void MoveBackward(int distance, bool wait = true)
{
MoveForward(-distance, wait);
}
public override void PivotLeft(AngleDelta angle, bool wait = true)
{
base.PivotLeft(angle, wait);
angle = Math.Round(angle, 2);
Historique.AjouterAction(new ActionPivot(this, angle, SensGD.Gauche));
_destination = new Position(Position.Angle - angle, new RealPoint(Position.Coordinates.X, Position.Coordinates.Y));
_sensPivot = SensGD.Gauche;
if (wait)
while (Position.Angle != _destination.Angle)
Thread.Sleep(10);
}
public override void PivotRight(AngleDelta angle, bool wait = true)
{
base.PivotRight(angle, wait);
angle = Math.Round(angle, 2);
Historique.AjouterAction(new ActionPivot(this, angle, SensGD.Droite));
_destination = new Position(Position.Angle + angle, new RealPoint(Position.Coordinates.X, Position.Coordinates.Y));
_sensPivot = SensGD.Droite;
if (wait)
while (Position.Angle != _destination.Angle)
Thread.Sleep(10);
}
public override void Stop(StopMode mode)
{
Historique.AjouterAction(new ActionStop(this, mode));
_lockMove.WaitOne();
if (mode == StopMode.Smooth)
{
Position nouvelleDestination = new Position(Position.Angle, new RealPoint(_currentPosition.Coordinates.X, _currentPosition.Coordinates.Y));
if (IsInLineMove)
{
if (_sensMove == SensAR.Avant)
nouvelleDestination.Move(GetCurrentLineBreakDistance());
else
nouvelleDestination.Move(-GetCurrentLineBreakDistance());
}
_destination = nouvelleDestination;
}
else if (mode == StopMode.Abrupt)
{
_currentSpeed = 0;
_destination = Position;
}
_lockMove.Release();
}
public override void Turn(SensAR sensAr, SensGD sensGd, int rayon, AngleDelta angle, bool wait = true)
{
// TODO2018
}
public override void PolarTrajectory(SensAR sens, List<RealPoint> points, bool wait = true)
{
_polarTrajectory = points;
_currentPolarPoint = 0;
while (wait && _currentPolarPoint != -1)
Thread.Sleep(10);
}
public override void SetAsservOffset(Position newPosition)
{
Position = new Position(newPosition.Angle, newPosition.Coordinates);
PositionTarget?.Set(Position.Coordinates);
OnPositionChanged(Position);
}
public override void Recalibration(SensAR sens, bool wait = true, bool sendOffset = false)
{
_inRecalibration = true;
Historique.AjouterAction(new ActionRecallage(this, sens));
if (wait)
RecalProcedure(sens);
else
ThreadManager.CreateThread(link => RecalProcedure(sens)).StartThread();
base.Recalibration(sens, wait, sendOffset);
}
private void RecalProcedure(SensAR sens)
{
int realAccel = SpeedConfig.LineAcceleration;
int realDecel = SpeedConfig.LineAcceleration;
SpeedConfig.LineAcceleration = 50000;
SpeedConfig.LineDeceleration = 50000;
IShape contact = GetBounds();
double lenght = sens == SensAR.Arriere ? LenghtBack : LenghtFront;
while (Position.Coordinates.X - lenght > 0 &&
Position.Coordinates.X + lenght < GameBoard.Width &&
Position.Coordinates.Y - lenght > 0 &&
Position.Coordinates.Y + lenght < GameBoard.Height)// &&
//!GameBoard.ObstaclesAll.ToList().Exists(o => o.Cross(contact))) // TODO ça marche pas on dirait le test de recallage sur les obstacles
{
if (sens == SensAR.Arriere)
MoveBackward(1);
else
MoveForward(1);
contact = GetBounds();
}
SpeedConfig.LineAcceleration = realAccel;
SpeedConfig.LineDeceleration = realDecel;
_inRecalibration = false;
}
public override bool ReadSensorOnOff(SensorOnOffID sensor, bool wait = true)
{
// TODO
return true;
}
public override Color ReadSensorColor(SensorColorID sensor, bool wait = true)
{
ColorPlus c = Color.White;
int i = DateTime.Now.Millisecond + DateTime.Now.Second * 1000 + DateTime.Now.Minute * 60 * 1000 + DateTime.Now.Hour * 60 * 60 * 1000;
int max = 999 + 59 * 1000 + 59 * 60 * 1000 + 23 * 60 * 60 * 1000;
i %= (15 * 1000);
max %= (15 * 1000);
int steps = 10;
int maxColor = 255 * steps;
i = (int)Math.Floor(i / (max / (float)maxColor));
switch (i / 255)
{
case 0:
c = ColorPlus.FromRgb(255, i % 255, 0); break;
case 1:
c = ColorPlus.FromRgb(255 - i % 255, 255, 0); break;
case 2:
c = ColorPlus.FromRgb(0, 255, i % 255); break;
case 3:
c = ColorPlus.FromRgb(0, 255 - i % 255, 255); break;
case 4:
c = ColorPlus.FromRgb(i % 255, 0, 255); break;
case 5:
c = ColorPlus.FromRgb(255, 0, 255 - i % 255); break;
case 6:
c = ColorPlus.FromRgb(255 - i % 255, 0, 0); break;
case 7:
c = ColorPlus.FromRgb(i % 255, i % 255, i % 255); break;
case 8:
c = ColorPlus.FromRgb(255 - i % 255 / 2, 255 - i % 255 / 2, 255 - i % 255 / 2); break;
case 9:
c = ColorPlus.FromHsl(0, i % 255 / 255f, 0.5); break;
}
OnSensorColorChanged(sensor, c);
return SensorsColorValue[sensor];
}
public override void SendPID(int p, int i, int d)
{
// TODO
}
public override void SendPIDCap(int p, int i, int d)
{
// TODO
}
public override void SendPIDSpeed(int p, int i, int d)
{
// TODO
}
public override void SetActuatorOnOffValue(ActuatorOnOffID actuator, bool on)
{
// TODO
Historique.AjouterAction(new ActionOnOff(this, actuator, on));
}
public override void SetMotorAtPosition(MotorID motor, int vitesse, bool wait)
{
base.SetMotorAtPosition(motor, vitesse);
}
public override void SetMotorSpeed(MotorID motor, SensGD sens, int speed)
{
base.SetMotorSpeed(motor, sens, speed);
}
public override void SetMotorAcceleration(MotorID motor, int acceleration)
{
base.SetMotorAcceleration(motor, acceleration);
}
public override void EnablePower(bool on)
{
// TODO
if (!on)
{
/*VitesseDeplacement = 0;
AccelerationDeplacement = 0;
VitessePivot = 0;
AccelerationPivot = 0;*/
}
}
public override bool ReadStartTrigger()
{
return true;
}
public override List<int>[] DiagnosticPID(int steps, SensAR sens, int pointsCount)
{
List<int>[] output = new List<int>[2];
output[0] = new List<int>();
output[1] = new List<int>();
for (double i = 0; i < pointsCount; i++)
{
output[0].Add((int)(Math.Sin((i + DateTime.Now.Millisecond) / 100.0 * Math.PI) * steps * 10000000 / (i * i * i)));
output[1].Add((int)(Math.Sin((i + DateTime.Now.Millisecond) / 100.0 * Math.PI) * steps * 10000000 / (i * i * i) + 10));
}
return output;
}
public override List<int>[] DiagnosticLine(int distance, SensAR sens)
{
List<int>[] output = new List<int>[2];
output[0] = new List<int>();
output[1] = new List<int>();
RealPoint startPos = new RealPoint(Position.Coordinates);
MoveForward(distance, false);
while ((Position.Coordinates.X != _destination.Coordinates.X ||
Position.Coordinates.Y != _destination.Coordinates.Y) && !Execution.Shutdown)
{
double dist = startPos.Distance(Position.Coordinates);
output[0].Add((int)(dist * 1000));
output[1].Add((int)(dist * 1000));
Thread.Sleep(1);
}
return output;
}
public override List<double>[] DiagnosticCpuPwm(int pointsCount)
{
List<double> cpuLoad, pwmLeft, pwmRight;
cpuLoad = new List<double>();
pwmLeft = new List<double>();
pwmRight = new List<double>();
for (int i = 0; i < pointsCount; i++)
{
cpuLoad.Add((Math.Sin(i / (double)pointsCount * Math.PI * 2) / 2 + 0.5) * 0.2 + _rand.NextDouble() * 0.2 + 0.3);
pwmLeft.Add(Math.Sin((DateTime.Now.Millisecond + i + DateTime.Now.Second * 1000) % 1500 / (double)1500 * Math.PI * 2) * 3800 + (_rand.NextDouble() - 0.5) * 400);
pwmRight.Add(Math.Sin((DateTime.Now.Millisecond + i + DateTime.Now.Second * 1000) % 5000 / (double)5000 * Math.PI * 2) * 3800 + (_rand.NextDouble() - 0.5) * 400);
}
Thread.Sleep(pointsCount);
return new List<double>[3] { cpuLoad, pwmLeft, pwmRight };
}
public override void ReadAnalogicPins(Board board, bool wait)
{
List<double> values = Enumerable.Range(1, 9).Select(o => o + _rand.NextDouble()).ToList();
AnalogicPinsValue[board] = values;
}
public override void ReadNumericPins(Board board, bool wait)
{
for (int i = 0; i < 3 * 2; i++)
NumericPinsValue[board][i] = (byte)((DateTime.Now.Second * 1000 + DateTime.Now.Millisecond) / 60000.0 * 255);
}
}
}
<file_sep>/GoBot/GoBot/Communications/FramesLog.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Serialization;
namespace GoBot.Communications
{
/// <summary>
/// Association d'une trame et de son heure de réception
/// </summary>
public class TimedFrame : IComparable
{
/// <summary>
/// Trame contenant les données
/// </summary>
public Frame Frame { get; set; }
/// <summary>
/// Date de la trame
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Vrai si la trame a été reçue, faux si elle a été envoyée
/// </summary>
public bool IsInputFrame { get; set; }
public TimedFrame(Frame frame, DateTime date, bool input = true)
{
Frame = frame;
Date = date;
IsInputFrame = input;
}
int IComparable.CompareTo(object obj)
{
return Date.CompareTo(((TimedFrame)obj).Date);
}
public void Export(StreamWriter writer)
{
writer.WriteLine(Date.ToString("dd/MM/yyyy hh:mm:ss.fff"));
writer.WriteLine(Frame);
writer.WriteLine(IsInputFrame);
}
public static TimedFrame Import(StreamReader reader)
{
DateTime date = DateTime.ParseExact(reader.ReadLine(), "dd/MM/yyyy hh:mm:ss.fff", null);
Frame frame = new Frame(reader.ReadLine());
Boolean isInput = Boolean.Parse(reader.ReadLine());
return new TimedFrame(frame, date, isInput);
}
}
/// <summary>
/// Permet de sauvegarder l'historique des trames reçue ainsi que leur heure d'arrivée
/// </summary>
public class FramesLog
{
/// <summary>
/// Extension du fichier de sauvegarde
/// </summary>
public static String FileExtension { get; } = ".tlog";
/// <summary>
/// Liste des trames
/// </summary>
public List<TimedFrame> Frames { get; private set; }
public FramesLog()
{
Frames = new List<TimedFrame>();
}
/// <summary>
/// Ajoute une trame reçue avec l'heure actuelle
/// </summary>
/// <param name="frame">Trame à ajouter</param>
public void AddFrame(Frame frame, bool isInput, DateTime? date = null)
{
if (!date.HasValue)
date = DateTime.Now;
lock (Frames)
{
Frames.Add(new TimedFrame(frame, date.Value, isInput));
}
}
/// <summary>
/// Charge une sauvegarde de Replay
/// </summary>
/// <param name="fileName">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde a été correctement chargée</returns>
public bool Import(String fileName)
{
try
{
StreamReader reader = new StreamReader(fileName);
int version = int.Parse(reader.ReadLine().Split(':')[1]);
lock (Frames)
{
while (!reader.EndOfStream)
Frames.Add(TimedFrame.Import(reader));
}
reader.Close();
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine("Erreur lors de la lecture de " + this.GetType().Name + " : " + ex.Message);
return false;
}
}
/// <summary>
/// Sauvegarde l'ensemble des trames dans un fichier
/// </summary>
/// <param name="fileName">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde s'est correctement déroulée</returns>
public bool Export(String fileName)
{
try
{
StreamWriter writer = new StreamWriter(fileName);
writer.WriteLine("Format:1");
lock (Frames)
{
foreach (TimedFrame frame in Frames)
frame.Export(writer);
}
writer.Close();
return true;
}
catch (Exception ex)
{
Console.Error.WriteLine("Erreur lors de l'enregistrement de " + this.GetType().Name + " : " + ex.Message);
return false;
}
}
/// <summary>
/// Permet de simuler la réception des trames enregistrées en respectant les intervalles de temps entre chaque trame
/// </summary>
public void ReplayInputFrames()
{
// Attention ça ne marche que pour l'UDP !
for (int i = 0; i < Frames.Count;i++)
{
if (Frames[i].IsInputFrame)
Connections.UDPBoardConnection[UDP.UdpFrameFactory.ExtractBoard(Frames[i].Frame)].OnFrameReceived(Frames[i].Frame);
if (i - 1 > 0)
Thread.Sleep(Frames[i].Date - Frames[i - 1].Date);
}
}
/// <summary>
/// Trie les trames par heure de réception
/// </summary>
public void Sort()
{
lock (Frames)
{
Frames.Sort();
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/ConnectionDetails.cs
using GoBot.Communications;
using GoBot.Communications.UDP;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class ConnectionDetails : UserControl
{
private UDPConnection _connection;
public ConnectionDetails()
{
InitializeComponent();
}
public UDPConnection Connection
{
get
{
return _connection;
}
set
{
_connection = value;
if(_connection != null)
{
_grpConnection.Text = Connections.GetUDPBoardByConnection(_connection).ToString();
_lblIP.Text = _connection.IPAddress.ToString();
_lblInputPort.Text = _connection.InputPort.ToString();
_lblOutputPort.Text = _connection.OutputPort.ToString();
}
}
}
}
}
<file_sep>/GoBot/Composants/FocusablePanel.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class FocusablePanel : UserControl
{
private bool Listening { get; set; }
public delegate void KeyPressedDelegate(PreviewKeyDownEventArgs e);
/// <summary>
/// Se produit lorsque qu'une touche est appuyée
/// </summary>
public event KeyPressedDelegate KeyPressed;
public FocusablePanel()
{
BackColor = Color.LightGray;
InitializeComponent();
Listening = true;
}
protected override void OnEnter(EventArgs e)
{
BackColor = Color.FromArgb(72, 216, 251);
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
BackColor = Color.LightGray;
base.OnLeave(e);
}
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
e.IsInputKey = true;
if (Listening)
{
Listening = false;
KeyPressed(e);
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
Listening = true;
base.OnKeyUp(e);
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementFlags.cs
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.Movements
{
class MovementFlags : Movement
{
public override bool CanExecute => true;
public override int Score => 10;
public override double Value => 0;
public override GameElement Element => null;
public override Robot Robot => Robots.MainRobot;
public override Color Color => GameBoard.ColorNeutral;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
Actionneur.Flags.DoOpenLeft();
Actionneur.Flags.DoOpenRight();
return true;
}
protected override void MovementEnd()
{
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/Fenetre.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class Fenetre : Form
{
public Fenetre(Control control)
{
Control = control;
Controls.Add(control);
control.SetBounds(0, 0, control.Width, control.Height);
InitializeComponent();
this.Width = control.Width + 10;
this.Height = control.Height + 30;
}
public Control Control
{
get;
private set;
}
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionAvance.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionAvance : ITimeableAction
{
private int distance;
private Robot robot;
public ActionAvance(Robot r, int dist)
{
robot = r;
distance = dist;
}
public override String ToString()
{
return robot.Name + " avance de " + distance + "mm";
}
void IAction.Executer()
{
robot.MoveForward(distance);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.UpGreen16;
}
}
public TimeSpan Duration
{
get
{
return robot.SpeedConfig.LineDuration(distance);
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/PolygonTriangle.cs
using System;
using System.Collections.Generic;
namespace Geometry.Shapes
{
/// <summary>
/// Polygone à 3 côtés.
/// </summary>
public class PolygonTriangle : Polygon
{
/// <summary>
/// Construit un triangle à partir de ses 3 sommets
/// </summary>
/// <param name="p1">Sommet 1</param>
/// <param name="p2">Sommet 2</param>
/// <param name="p3">Sommet 3</param>
public PolygonTriangle(RealPoint p1, RealPoint p2, RealPoint p3)
: base(new List<RealPoint>() { p1, p2, p3 })
{
// L'interet du triangle c'est qu'il est simple de calculer son aire et son barycentre et qu'on s'en sert pour calculer ceux de polygones quelconques
}
/// <summary>
/// COnstruit un triangle à partir de ses 3 cotés
/// </summary>
/// <param name="p1">Coté 1</param>
/// <param name="p2">Coté 2</param>
/// <param name="p3">Coté 3</param>
public PolygonTriangle(Segment s1, Segment s2, Segment s3)
: base(new List<Segment>() { s1, s2, s3 })
{
if (s1.EndPoint != s2.StartPoint || s2.EndPoint != s3.StartPoint || s3.EndPoint != s1.StartPoint)
throw new Exception("Triangle mal formé");
}
public PolygonTriangle(PolygonTriangle other) : base(other)
{
}
protected override double ComputeSurface()
{
Segment seg = new Segment(Points[0], Points[1]);
double height = seg.Distance(Points[2]);
double width = seg.Length;
return height * width / 2;
}
protected override RealPoint ComputeBarycenter()
{
RealPoint output = null;
if (Points[0] == Points[1] && Points[0] == Points[2])
output = new RealPoint(Points[0]);
else if (Points[0] == Points[1])
output = new Segment(Points[0], Points[2]).Barycenter;
else if (Points[0] == Points[2])
output = new Segment(Points[1], Points[2]).Barycenter;
else if (Points[1] == Points[2])
output = new Segment(Points[0], Points[1]).Barycenter;
else
{
Line d1 = new Line(new Segment(Points[0], Points[1]).Barycenter, Points[2]);
Line d2 = new Line(new Segment(Points[1], Points[2]).Barycenter, Points[0]);
output = d1.GetCrossingPoints(d2)[0];
}
return output;
}
}
}
<file_sep>/GoBot/Geometry/Matrix.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry
{
public static class Matrix
{
public static T[,] Transpose<T>(T[,] source)
{
int rowsCount = source.GetLength(0);
int colsCount = source.GetLength(1);
T[,] target = new T[colsCount, rowsCount];
for (int iRow = 0; iRow < rowsCount; iRow++)
for (int iCol = 0; iCol < colsCount; iCol++)
target[iCol, iRow] = source[iRow, iCol];
return target;
}
public static double[,] Multiply(double[,] m1, double[,] m2)
{
int rowsCount1 = m1.GetLength(0);
int colsCount1 = m1.GetLength(1);
int colsCount2 = m2.GetLength(1);
double[,] res = new double[rowsCount1, rowsCount1];
for (int iRow = 0; iRow < rowsCount1; iRow++)
for (int iCol2 = 0; iCol2 < colsCount2; iCol2++)
for (int iCol1 = 0; iCol1 < colsCount1; iCol1++)
res[iRow, iCol2] += m1[iRow, iCol1] * m2[iCol1, iCol2];
return res;
}
public static double[] Multiply(double[,] m1, double[] m2)
{
double[] res = new double[m1.GetLength(0)];
for (int iRow = 0; iRow < res.Length; iRow++)
for (int iCol = 0; iCol < m2.Length; iCol++)
res[iRow] += m1[iRow, iCol] * m2[iCol];
return res;
}
public static double Determinant2x2(double m00, double m01, double m10, double m11)
{
return ((m00 * m11) - (m10 * m01));
}
public static double Determinant2x2(double[,] m)
{
return Determinant2x2(m[0, 0], m[0, 1], m[1, 0], m[1, 1]);
}
public static double Determinant3x3(double[,] m)
{
var a = m[0, 0] * Determinant2x2(m[1, 1], m[1, 2], m[2, 1], m[2, 2]);
var b = m[0, 1] * Determinant2x2(m[1, 0], m[1, 2], m[2, 0], m[2, 2]);
var c = m[0, 2] * Determinant2x2(m[1, 0], m[1, 1], m[2, 0], m[2, 1]);
return a - b + c;
}
public static double[,] Inverse3x3(double[,] m)
{
double d = (1 / Determinant3x3(m));
return new double[3, 3]
{
{
+Determinant2x2(m[1,1], m[1,2], m[2,1], m[2,2]) * d,//[0,0]
-Determinant2x2(m[0,1], m[0,2], m[2,1], m[2,2]) * d,//[1,0]
+Determinant2x2(m[0,1], m[0,2], m[1,1], m[1,2]) * d,//[2,0]
},
{
-Determinant2x2(m[1,0], m[1,2], m[2,0], m[2,2]) * d,//[0,1]
+Determinant2x2(m[0,0], m[0,2], m[2,0], m[2,2]) * d,//[1,1]
-Determinant2x2(m[0,0], m[0,2], m[1,0], m[1,2]) * d,//[2,1]
},
{
+Determinant2x2(m[1,0], m[1,1], m[2,0], m[2,1]) * d,//[0,2]
-Determinant2x2(m[0,0], m[0,1], m[2,0], m[2,1]) * d,//[1,2]
+Determinant2x2(m[0,0], m[0,1], m[1,0], m[1,1]) * d,//[2,2]
}
};
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementLightHouse.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
namespace GoBot.Movements
{
class MovementLightHouse : Movement
{
LightHouse _lightHouse;
public MovementLightHouse(LightHouse lighthouse)
{
_lightHouse = lighthouse;
Positions.Add(new Position(-90, new RealPoint(_lightHouse.Position.X, 275)));
}
public override bool CanExecute
{ get
{
Buoy b = _lightHouse.Position.X < 1500 ? GameBoard.Elements.FindBuoy(new Geometry.Shapes.RealPoint(300, 400)) : GameBoard.Elements.FindBuoy(new Geometry.Shapes.RealPoint(2700, 400));
return !_lightHouse.Enable && !b.IsAvailable;
}
}
public override int Score => (10 + 3);
public override double Value => 1.2;
public override GameElement Element => _lightHouse;
public override Robot Robot => Robots.MainRobot;
public override Color Color => _lightHouse.Owner;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
Robot.SetSpeedVerySlow();
Robot.Recalibration(SensAR.Avant, true, true);
Actionneur.ElevatorLeft.DoPushLight();
Actionneur.ElevatorRight.DoPushLight();
Thread.Sleep(750);
_lightHouse.Enable = true;
Actionneur.ElevatorLeft.DoPushInsideFast();
Actionneur.ElevatorRight.DoPushInsideFast();
Robot.SetSpeedFast();
Robots.MainRobot.MoveBackward(100);
return true;
}
protected override void MovementEnd()
{
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/CircleWithPolygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class CircleWithPolygon
{
public static bool Contains(Circle circleContaining, Polygon polygonContained)
{
// Pour contenir un polygone il suffit de contenir tous ses cotés
return polygonContained.Sides.TrueForAll(s => circleContaining.Contains(s));
}
public static double Distance(Circle circle, Polygon polygon)
{
// Si une des forme contient l'autre ou qu'elles se croisent, la distance est de 0.
// Sinon c'est la distance minimale à tous les segments.
double distance;
if (circle.Cross(polygon) || polygon.Contains(circle) || circle.Contains(polygon))
distance = 0;
else
distance = polygon.Sides.Min(s => s.Distance(circle));
return distance;
}
public static bool Cross(Circle circle, Polygon polygon)
{
// Pour croiser un polygone il suffit de croiser un de ses cotés
return polygon.Sides.Exists(s => circle.Cross(s));
}
public static List<RealPoint> GetCrossingPoints(Circle circle, Polygon polygon)
{
// Croisement du cercle avec tous les segments du polygone
return polygon.Sides.SelectMany(s => s.GetCrossingPoints(circle)).Distinct().ToList();
}
}
}
<file_sep>/GoBot/GoBot/AsserStats.cs
using Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot
{
public class AsserStats
{
/// <summary>
/// Liste des distances parcourures en marche avant
/// </summary>
public List<int> ForwardMoves { get; protected set; }
/// <summary>
/// Liste des distances parcourures en marche arrière
/// </summary>
public List<int> BackwardMoves { get; protected set; }
/// <summary>
/// Liste des angle parcourus en pivot gauche
/// </summary>
public List<AngleDelta> LeftRotations { get; protected set; }
/// <summary>
/// Liste des angle parcourus en pivot droit
/// </summary>
public List<AngleDelta> RightsRotations { get; protected set; }
public AsserStats()
{
ForwardMoves = new List<int>();
BackwardMoves = new List<int>();
LeftRotations = new List<AngleDelta>();
RightsRotations = new List<AngleDelta>();
}
public TimeSpan CalculDuration(SpeedConfig config, Robot robot)
{
TimeSpan totalDuration = new TimeSpan();
foreach (int dist in ForwardMoves.Union(BackwardMoves))
totalDuration += config.LineDuration(dist);
foreach (AngleDelta ang in LeftRotations.Union(RightsRotations))
totalDuration += config.PivotDuration(ang, robot.WheelSpacing);
return totalDuration;
}
}
}
<file_sep>/GoBot/GoBot/Actions/ActionOnOff.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionOnOff : IAction
{
private bool on;
ActuatorOnOffID actionneur;
private Robot robot;
public ActionOnOff(Robot r, ActuatorOnOffID ac, bool _on)
{
robot = r;
on = _on;
actionneur = ac;
}
public override String ToString()
{
return robot + " change " + NameFinder.GetName(actionneur) + " à " + (on ? "on" : "off");
}
void IAction.Executer()
{
robot.SetActuatorOnOffValue(actionneur, on);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Motor16;
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaActuators.cs
using GoBot.Actionneurs;
using GoBot.GameElements;
using GoBot.Threading;
using System;
using System.Threading;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PagePandaActuators : UserControl
{
private ThreadLink _linkFingerRight, _linkFingerLeft;
private bool _flagRight, _flagLeft;
private bool _clamp1, _clamp2, _clamp3, _clamp4, _clamp5;
private bool _grabberLeft, _grabberRight;
public PagePandaActuators()
{
InitializeComponent();
_grabberLeft = true;
_grabberRight = true;
}
private void PagePandaActuators_Load(object sender, System.EventArgs e)
{
if (!Execution.DesignMode)
{
btnTrap.Focus();
}
}
private void btnFingerRight_Click(object sender, EventArgs e)
{
if (_linkFingerRight == null)
{
_linkFingerRight = Threading.ThreadManager.CreateThread(link => Actionneurs.Actionneur.FingerRight.DoDemoGrab(link));
_linkFingerRight.StartThread();
}
else
{
_linkFingerRight.Cancel();
_linkFingerRight.WaitEnd();
_linkFingerRight = null;
}
}
private void btnFingerLeft_Click(object sender, EventArgs e)
{
if (_linkFingerLeft == null)
{
_linkFingerLeft = Threading.ThreadManager.CreateThread(link => Actionneurs.Actionneur.FingerLeft.DoDemoGrab(link));
_linkFingerLeft.StartThread();
}
else
{
_linkFingerLeft.Cancel();
_linkFingerLeft.WaitEnd();
_linkFingerLeft = null;
}
}
private void btnFlagLeft_Click(object sender, EventArgs e)
{
if (!_flagLeft)
Actionneur.Flags.DoOpenLeft();
else
Actionneur.Flags.DoCloseLeft();
_flagLeft = !_flagLeft;
}
private void btnLeftPickup_Click(object sender, EventArgs e)
{
Actionneur.ElevatorLeft.DoDemoPickup();
}
private void btnLeftDropoff_Click(object sender, EventArgs e)
{
Actionneur.ElevatorRight.DoDemoDropoff();
}
private void btnRightPickup_Click(object sender, EventArgs e)
{
Actionneur.ElevatorRight.DoDemoPickup();
}
private void btnRightDropoff_Click(object sender, EventArgs e)
{
Actionneur.ElevatorRight.DoDemoDropoff();
}
private void btnSearchGreen_Click(object sender, EventArgs e)
{
Actionneur.ElevatorRight.DoSearchBuoy(Buoy.Green);
}
private void btnSearchRed_Click(object sender, EventArgs e)
{
Actionneur.ElevatorLeft.DoSearchBuoy(Buoy.Red);
}
private void btnGrabberRight_Click(object sender, EventArgs e)
{
_grabberRight = !_grabberRight;
if (_grabberRight)
{
Actionneur.ElevatorRight.DoGrabOpen();
Actionneur.ElevatorRight.Armed = true;
btnGrabberRight.Image = Properties.Resources.GrabberRightOpened;
}
else
{
Actionneur.ElevatorRight.DoGrabClose();
btnGrabberRight.Image = Properties.Resources.GrabberRightClosed;
}
}
private void btnGrabberLeft_Click(object sender, EventArgs e)
{
_grabberLeft = !_grabberLeft;
if (_grabberLeft)
{
Actionneur.ElevatorLeft.DoGrabOpen();
btnGrabberLeft.Image = Properties.Resources.GrabberLeftOpened;
}
else
{
Actionneur.ElevatorLeft.DoGrabClose();
btnGrabberLeft.Image = Properties.Resources.GrabberLeftClosed;
}
}
private void btnClamp1_Click(object sender, EventArgs e)
{
_clamp1 = !_clamp1;
if (_clamp1)
{
Config.CurrentConfig.ServoClamp1.SendPosition(Config.CurrentConfig.ServoClamp1.PositionOpen);
btnClamp1.Image = Properties.Resources.Unlock64;
}
else
{
Config.CurrentConfig.ServoClamp1.SendPosition(Config.CurrentConfig.ServoClamp1.PositionClose);
btnClamp1.Image = Properties.Resources.Lock64;
}
}
private void btnClamp2_Click(object sender, EventArgs e)
{
_clamp2 = !_clamp2;
if (_clamp2)
{
Config.CurrentConfig.ServoClamp2.SendPosition(Config.CurrentConfig.ServoClamp2.PositionOpen);
btnClamp2.Image = Properties.Resources.Unlock64;
}
else
{
Config.CurrentConfig.ServoClamp2.SendPosition(Config.CurrentConfig.ServoClamp2.PositionClose);
btnClamp2.Image = Properties.Resources.Lock64;
}
}
private void btnClamp3_Click(object sender, EventArgs e)
{
_clamp3 = !_clamp3;
if (_clamp3)
{
Config.CurrentConfig.ServoClamp3.SendPosition(Config.CurrentConfig.ServoClamp3.PositionOpen);
btnClamp3.Image = Properties.Resources.Unlock64;
}
else
{
Config.CurrentConfig.ServoClamp3.SendPosition(Config.CurrentConfig.ServoClamp3.PositionClose);
btnClamp3.Image = Properties.Resources.Lock64;
}
}
private void btnClamp4_Click(object sender, EventArgs e)
{
_clamp4 = !_clamp4;
if (_clamp4)
{
Config.CurrentConfig.ServoClamp4.SendPosition(Config.CurrentConfig.ServoClamp4.PositionOpen);
btnClamp4.Image = Properties.Resources.Unlock64;
}
else
{
Config.CurrentConfig.ServoClamp4.SendPosition(Config.CurrentConfig.ServoClamp4.PositionClose);
btnClamp4.Image = Properties.Resources.Lock64;
}
}
private void btnClamp5_Click(object sender, EventArgs e)
{
_clamp5 = !_clamp5;
if (_clamp5)
{
Config.CurrentConfig.ServoClamp5.SendPosition(Config.CurrentConfig.ServoClamp5.PositionOpen);
btnClamp5.Image = Properties.Resources.Unlock64;
}
else
{
Config.CurrentConfig.ServoClamp5.SendPosition(Config.CurrentConfig.ServoClamp5.PositionClose);
btnClamp5.Image = Properties.Resources.Lock64;
}
}
private void btnFlagRight_Click(object sender, EventArgs e)
{
if (!_flagRight)
Actionneur.Flags.DoOpenRight();
else
Actionneur.Flags.DoCloseRight();
_flagRight = !_flagRight;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelPositionables.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;
using GoBot.Actionneurs;
namespace GoBot.IHM
{
public partial class PanelPositionables : UserControl
{
public Dictionary<String, PropertyInfo> _dicProperties;
public PanelPositionables()
{
InitializeComponent();
}
private void PanelPositionables_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
cboPositionables.Items.AddRange(Config.Positionnables.ToArray());
}
}
private void cboPositionables_SelectedValueChanged(object sender, EventArgs e)
{
Positionable positionnable = (Positionable)cboPositionables.SelectedItem;
PropertyInfo[] properties = positionnable.GetType().GetProperties();
List<String> positionsName = new List<string>();
_dicProperties = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo property in properties)
{
if (property.Name != "ID")
{
positionsName.Add(Config.PropertyNameToScreen(property) + " : " + property.GetValue(positionnable, null));
_dicProperties.Add(positionsName[positionsName.Count - 1], property);
}
}
cboPositions.Items.Clear();
cboPositions.Items.AddRange(positionsName.ToArray());
trkPosition.Min = positionnable.Minimum;
trkPosition.Max = positionnable.Maximum;
btnSend.Enabled = true;
btnSave.Enabled = false;
}
private void cboPositions_SelectedValueChanged(object sender, EventArgs e)
{
String[] tab = ((String)(cboPositions.SelectedItem)).Split(new char[]{':'});
String position = tab[0].Trim();
int valeur = Convert.ToInt32(tab[1].Trim());
numPosition.Value = valeur;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
String[] tab = ((String)(cboPositions.SelectedItem)).Split(new char[] { ':' });
String position = tab[0].Trim().ToLower();
int valeur = Convert.ToInt32(tab[1].Trim());
if (MessageBox.Show(this, "Êtes vous certain de vouloir sauvegarder la position " + position + " de l'actionneur " + cboPositionables.Text.ToLower() + " à " + numPosition.Value + " (anciennement " + valeur + ") ?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
int index = cboPositions.SelectedIndex;
_dicProperties[(String)cboPositions.SelectedItem].SetValue((Positionable)cboPositionables.SelectedItem, (int)numPosition.Value, null);
cboPositionables_SelectedValueChanged(null, null);
cboPositions.SelectedIndex = index;
Config.Save();
}
}
private void trkPosition_TickValueChanged(object sender, double value)
{
numPosition.Value = (decimal)value;
SendPosition();
}
private void btnSend_Click(object sender, EventArgs e)
{
SendPosition();
}
private void SendPosition()
{
Positionable positionnable = (Positionable)cboPositionables.SelectedItem;
positionnable?.SendPosition((int)numPosition.Value);
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementGroundedZone.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
namespace GoBot.Movements
{
class MovementGroundedZone : Movement
{
GroundedZone _zone;
public override bool CanExecute => !Actionneur.Lifter.Loaded && Element.IsAvailable;
public override int Score => 0;
public override double Value => 1;
public override GameElement Element => _zone;
public override Robot Robot => Robots.MainRobot;
public override Color Color => Element.Owner;
public MovementGroundedZone(GroundedZone zone) : base()
{
_zone = zone;
Positions.Add(new Position(180, new RealPoint(_zone.Position.X - 70 - 225, zone.Position.Y)));
Positions.Add(new Position(0, new RealPoint(_zone.Position.X + 70 + 225, zone.Position.Y)));
Positions.Add(new Position(90, new RealPoint(_zone.Position.X, zone.Position.Y + 70 + 225)));
}
protected override void MovementBegin()
{
// rien
}
protected override bool MovementCore()
{
Actionneur.Lifter.DoSequencePickup();
Actionneur.Lifter.Load = _zone.Buoys.Select(b => b.Color).ToList();
_zone.IsAvailable = false;
_zone.Buoys.ForEach(b => b.IsAvailable = false);
Robots.MainRobot.MoveForward(100);
return true;
}
protected override void MovementEnd()
{
// rien
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PagePower.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Timers;
namespace GoBot.IHM.Pages
{
public partial class PagePower : UserControl
{
private System.Timers.Timer _timerVoltage;
private bool _loaded;
public PagePower()
{
InitializeComponent();
_loaded = false;
}
public void StartGraph()
{
ctrlGraphic.NamesVisible = true;
ctrlGraphic.MinLimit = 20;
ctrlGraphic.MaxLimit = 26;
ctrlGraphic.ScaleMode = Composants.GraphPanel.ScaleType.FixedIfEnough;
ctrlGraphic.LimitsVisible = true;
_timerVoltage = new System.Timers.Timer(1000);
_timerVoltage.Elapsed += new ElapsedEventHandler(timerTension_Elapsed);
_timerVoltage.Start();
}
private void PanelAlimentation_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
numBatHighToAverage.Value = (decimal)Config.CurrentConfig.BatterieRobotVert;
numBatAverageToLow.Value = (decimal)Config.CurrentConfig.BatterieRobotOrange;
numBatLowToVeryLow.Value = (decimal)Config.CurrentConfig.BatterieRobotRouge;
numBatVeryLowToAbsent.Value = (decimal)Config.CurrentConfig.BatterieRobotCritique;
batAbsent.CurrentState = Composants.Battery.State.Absent;
batVeryLow.CurrentState = Composants.Battery.State.VeryLow;
batLow.CurrentState = Composants.Battery.State.Low;
batAverage.CurrentState = Composants.Battery.State.Average;
batHigh.CurrentState = Composants.Battery.State.High;
_loaded = true;
}
}
void timerTension_Elapsed(object sender, ElapsedEventArgs e)
{
if (Execution.Shutdown)
return;
this.InvokeAuto(() =>
{
ctrlGraphic.AddPoint("Tension", Robots.MainRobot.BatterieVoltage, Color.DodgerBlue, true);
ctrlGraphic.AddPoint("High", Config.CurrentConfig.BatterieRobotVert, Color.LimeGreen);
ctrlGraphic.AddPoint("Average", Config.CurrentConfig.BatterieRobotOrange, Color.Orange);
ctrlGraphic.AddPoint("Low", Config.CurrentConfig.BatterieRobotRouge, Color.Firebrick);
ctrlGraphic.AddPoint("VeryLow", Config.CurrentConfig.BatterieRobotCritique, Color.Black);
ctrlGraphic.DrawCurves();
});
}
private void numBat_ValueChanged(object sender, EventArgs e)
{
if (_loaded)
{
Config.CurrentConfig.BatterieRobotVert = (double)numBatHighToAverage.Value;
Config.CurrentConfig.BatterieRobotOrange = (double)numBatAverageToLow.Value;
Config.CurrentConfig.BatterieRobotRouge = (double)numBatLowToVeryLow.Value;
Config.CurrentConfig.BatterieRobotCritique = (double)numBatVeryLowToAbsent.Value;
Config.Save();
}
}
}
}
<file_sep>/GoBot/GoBot/Utils/LimitedQueue.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoBot.Utils
{
class LimitedQueue<T> : Queue<T>
{
private int _limit;
public LimitedQueue(int limit)
{
_limit = limit;
}
public int Limit
{
get
{
return _limit;
}
set
{
_limit = value;
}
}
public new void Enqueue(T val)
{
base.Enqueue(val);
while (this.Count > _limit) base.Dequeue();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/PanelSensorOnOff.cs
using System.Drawing;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM
{
public partial class PanelSensorOnOff : UserControl
{
private SensorOnOffID _sensor;
private ThreadLink _linkPolling;
public PanelSensorOnOff()
{
InitializeComponent();
}
private void PanelSensorOnOff_Load(object sender, System.EventArgs e)
{
if (!Execution.DesignMode)
{
Robots.MainRobot.SensorOnOffChanged += MainRobot_SensorOnOffChanged;
}
}
private void MainRobot_SensorOnOffChanged(SensorOnOffID sensor, bool state)
{
if (sensor == _sensor && _linkPolling != null) ledState.Color = state ? Color.LimeGreen : Color.Red;
}
public void SetSensor(SensorOnOffID sensor)
{
_sensor = sensor;
lblName.Text = NameFinder.GetName(sensor).Substring(0, 1).ToUpper() + NameFinder.GetName(sensor).Substring(1);
}
private void btnOnOff_ValueChanged(object sender, bool value)
{
if(value)
{
ledState.Color = Robots.MainRobot.ReadSensorOnOff(_sensor) ? Color.LimeGreen : Color.Red;
_linkPolling = ThreadManager.CreateThread(link => PollingSensor());
_linkPolling.RegisterName(nameof(PollingSensor) + " " + lblName.Text);
_linkPolling.StartInfiniteLoop(50);
}
else
{
_linkPolling.Cancel();
_linkPolling.WaitEnd();
_linkPolling = null;
ledState.Color = Color.Gray;
}
}
private void PollingSensor()
{
Robots.MainRobot.ReadSensorOnOff(_sensor, false);
}
}
}
<file_sep>/GoBot/GoBot/Logs/LogConsole.cs
using System;
using System.IO;
namespace GoBot.Logs
{
public class LogConsole : ILog
{
public LogConsole()
{
Console.WriteLine("Begin of log");
}
public void Write(String message)
{
Console.WriteLine(DateTime.Now.ToString("dd:MM:yyyy hh:mm:ss:ffff\t") + message);
}
public void Close()
{
Console.WriteLine("End of log");
}
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionVirage.cs
using Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionVirage : IAction
{
private int distance;
private AngleDelta angle;
private Robot robot;
private SensGD sensGD;
private SensAR sensAR;
public ActionVirage(Robot r, int dist, AngleDelta a, SensAR ar, SensGD gd)
{
robot = r;
distance = dist;
angle = a;
sensAR = ar;
sensGD = gd;
}
public override String ToString()
{
return robot.Name + " tourne " + distance + "mm " + angle + "° " + sensAR.ToString().ToLower() + " " + sensGD.ToString().ToLower();
}
void IAction.Executer()
{
robot.Turn(sensAR, sensGD, distance, angle);
}
public System.Drawing.Image Image
{
get
{
if (sensAR == SensAR.Avant)
{
if (sensGD == SensGD.Droite)
return GoBot.Properties.Resources.BottomToRigth16;
else
return GoBot.Properties.Resources.BottomToLeft16;
}
else
{
if (sensGD == SensGD.Droite)
return GoBot.Properties.Resources.TopToRigth16;
else
return GoBot.Properties.Resources.TopToLeft16;
}
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageEnvoiUdp.cs
using System;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Net;
using GoBot.Communications;
using GoBot.Communications.UDP;
using GoBot.Communications.CAN;
using GoBot.Actionneurs;
using System.Diagnostics;
namespace GoBot.IHM.Pages
{
public partial class PageEnvoiUdp : UserControl
{
public PageEnvoiUdp()
{
InitializeComponent();
}
private void btnEnvoyer_Click(object sender, EventArgs e)
{
Frame trame = null;
try
{
trame = new Frame(txtTrame.Text);
}
catch (Exception)
{
txtTrame.ErrorMode = true;
return;
}
if (boxMove.Checked)
Connections.ConnectionMove.SendMessage(trame);
if (boxIO.Checked)
Connections.ConnectionIO.SendMessage(trame);
if (boxCan.Checked)
Connections.ConnectionCan.SendMessage(trame);
}
private void PanelEnvoiUdp_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
switchBoutonMove.Value = true;
switchBoutonIO.Value = true;
foreach (UDPConnection conn in Connections.AllConnections.OfType<UDPConnection>())
{
ConnectionDetails details = new ConnectionDetails();
details.Connection = conn;
_pnlConnections.Controls.Add(details);
}
IPAddress[] adresses = Dns.GetHostAddresses(Dns.GetHostName());
bool ipTrouvee = false;
foreach (IPAddress ip in adresses)
{
if (ip.ToString().Length > 7)
{
String ipString = ip.ToString().Substring(0, 7);
if (ipString == "10.1.0.")
{
lblMonIP.Text = ip.ToString();
ipTrouvee = true;
}
}
}
if (!ipTrouvee)
{
lblMonIP.Text = "Incorrecte";
lblMonIP.ForeColor = Color.Red;
}
}
}
private void btnDebug_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
int val = Convert.ToInt16(btn.Tag);
if (boxMove.Checked)
{
Frame trame = UdpFrameFactory.Debug(Board.RecMove, val);
Connections.ConnectionMove.SendMessage(trame);
}
if (boxIO.Checked)
{
Frame trame = UdpFrameFactory.Debug(Board.RecIO, val);
Connections.ConnectionIO.SendMessage(trame);
}
}
private System.Windows.Forms.Timer timerTestConnexion;
private void btnSendTest_Click(object sender, EventArgs e)
{
if (btnSendTest.Text == "Envoyer")
{
btnSendTest.Text = "Stop";
timerTestConnexion = new System.Windows.Forms.Timer();
timerTestConnexion.Interval = (int)numIntervalleTest.Value;
timerTestConnexion.Tick += new EventHandler(timerTestConnexion_Tick);
timerTestConnexion.Start();
}
else
{
btnSendTest.Text = "Envoyer";
timerTestConnexion.Stop();
}
}
void timerTestConnexion_Tick(object sender, EventArgs e)
{
if (boxMove.Checked)
{
Frame trame = UdpFrameFactory.TestConnexion(Board.RecMove);
Connections.ConnectionMove.SendMessage(trame);
}
if (boxIO.Checked)
{
Frame trame = UdpFrameFactory.TestConnexion(Board.RecIO);
Connections.ConnectionIO.SendMessage(trame);
}
}
private void switchBoutonConnexion_ValueChanged(object sender, bool value)
{
Connections.EnableConnection[Board.RecMove] = switchBoutonMove.Value;
Connections.EnableConnection[Board.RecIO] = switchBoutonIO.Value;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/LineWithLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
public static class LineWithLine
{
public static bool Contains(Line containingLine, Line containedLine)
{
// Contenir une droite revient à avoir la même équation
return (containingLine == containedLine);
}
public static bool Cross(Line line1, Line line2)
{
// Deux droites se croisent forcément si elles n'ont pas la même pente ou qu'elles sont toutes les deux verticales
return !line1.IsParallel(line2);
}
public static double Distance(Line line1, Line line2)
{
double distance;
if (!line1.IsParallel(line2))
{
// Si les droites se croisent la distance est de 0
distance = 0;
}
else
{
// Sinon elles sont parrallèles donc on trace une perdendiculaire et une mesure la distance entre les croisements avec les 2 droites
Line perpendicular = line1.GetPerpendicular(new RealPoint(0, 0));
RealPoint p1 = line1.GetCrossingPoints(perpendicular)[0];
RealPoint p2 = line2.GetCrossingPoints(perpendicular)[0];
distance = p1.Distance(p2);
}
return distance;
}
public static List<RealPoint> GetCrossingPoints(Line line1, Line line2)
{
List<RealPoint> output = new List<RealPoint>();
if (!line1.IsParallel(line2))
{
// Résolution de l'équation line1 = line2
output.Add(new RealPoint
{
X = (line2.B * line1.C - line2.C * line1.B) / (line2.C * line1.A - line2.A * line1.C),
Y = (line2.A * line1.B - line2.B * line1.A) / (line2.A * line1.C - line2.C * line1.A),
});
}
return output;
}
}
}
<file_sep>/GoBot/GoBot/Communications/ConnectionChecker.cs
using System;
using System.Timers;
namespace GoBot.Communications
{
public class ConnectionChecker
{
/// <summary>
/// Date de la dernière notification de connexion établie
/// </summary>
protected DateTime LastAliveDate { get; set; }
/// <summary>
/// Date du dernier envoi de test de connexion
/// </summary>
protected DateTime LastTestDate { get; set; }
/// <summary>
/// Timer qui envoie les tests de connexion et vérifie l'état de la connexion
/// </summary>
protected Timer CheckTimer { get; set; }
/// <summary>
/// Vrai si le timer de vérification est lancé
/// </summary>
public bool Started { get; protected set; }
/// <summary>
/// Connexion surveillée
/// </summary>
public Connection AttachedConnection { get; protected set; }
/// <summary>
/// Vrai si la connexion est actuellement établie
/// </summary>
public bool Connected { get; protected set; }
/// <summary>
/// Intervalle de vérification de la connexion
/// </summary>
public int Interval
{
get { return (int)CheckTimer.Interval; }
set { CheckTimer.Interval = value; }
}
public delegate void ConnectionChangeDelegate(Connection sender, bool connected);
/// <summary>
/// Event appelé quand la connexion est trouvée ou perdue.
/// </summary>
public event ConnectionChangeDelegate ConnectionStatusChange;
public delegate void SendConnectionTestDelegate(Connection sender);
/// <summary>
/// Event appelé à chaque tick pour actualiser la connexion. Abonner à cet event une fonction qui aura pour conséquence un appel à NotifyAlive si la connexion est établie.
/// </summary>
public event SendConnectionTestDelegate SendConnectionTest;
/// <summary>
/// Crée un ConnectionChecker en spécifiant la connexion surveillée et l'intervalle entre chaque vérification.
/// </summary>
public ConnectionChecker(Connection conn, int interval = 2000)
{
AttachedConnection = conn;
LastAliveDate = DateTime.Now - new TimeSpan(0, 1, 0);
LastTestDate = DateTime.Now;
Started = false;
CheckTimer = new Timer();
CheckTimer.Interval = interval;
CheckTimer.Elapsed += new ElapsedEventHandler(CheckTimer_Elapsed);
Connected = false;
}
/// <summary>
/// Démarre la surveillance.
/// </summary>
public void Start()
{
Started = true;
CheckConnection();
CheckTimer.Start();
}
/// <summary>
/// Permet d'effectuer une vérification de la connexion en mettant à jour par rapport au dernier test de connexion puis en en envoyant un nouveau.
/// Cette fonction est appelée périodiquement par le timer et peut également être appelée manuellement.
/// </summary>
public void CheckConnection()
{
UpdateStatus();
SendConnectionTest?.Invoke(AttachedConnection);
}
/// <summary>
/// Mets à jour l'état de la connexion en fonction du dernier test effectué et de la dernière notification de retour reçue.
/// </summary>
public void UpdateStatus()
{
TimeSpan authorizedDelay = new TimeSpan(0, 0, 0, 0, (int)(CheckTimer.Interval * 0.5));
TimeSpan effectiveDelay = LastTestDate - LastAliveDate;
if (Connected && effectiveDelay > authorizedDelay)
{
Connected = false;
ConnectionStatusChange?.Invoke(AttachedConnection, Connected);
}
else if (!Connected && effectiveDelay < authorizedDelay)
{
Connected = true;
ConnectionStatusChange?.Invoke(AttachedConnection, Connected);
}
LastTestDate = DateTime.Now;
}
/// <summary>
/// Spécifie que la connexion est bien établie à la date actuelle.
/// </summary>
public void NotifyAlive()
{
LastAliveDate = DateTime.Now;
UpdateStatus();
}
/// <summary>
/// Fonction appelée à chaque tick du timer.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void CheckTimer_Elapsed(object sender, ElapsedEventArgs e)
{
CheckConnection();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Forms/FormConfirm.cs
using System;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Forms
{
public partial class FormConfirm : Form
{
ThreadLink _link;
int _countdown;
public FormConfirm()
{
InitializeComponent();
}
private void btnStay_Click(object sender, EventArgs e)
{
_link.Cancel();
DialogResult = DialogResult.No;
Close();
}
private void btnQuit_Click(object sender, EventArgs e)
{
_link.Cancel();
DialogResult = DialogResult.Yes;
Close();
}
private void FormConfirm_Shown(object sender, EventArgs e)
{
btnTrap.Focus();
_countdown = 3;
btnStay.Text = "Rester (" + _countdown + ")";
_link = ThreadManager.CreateThread(link => Countdown());
_link.StartLoop(1000, _countdown + 2);
}
private void Countdown()
{
if (!_link.Cancelled)
{
if (_countdown < 0)
{
_link.Cancel();
btnStay.InvokeAuto(() => btnStay.PerformClick());
}
else
{
btnStay.InvokeAuto(() => btnStay.Text = "Rester (" + _countdown + ")");
}
_countdown -= 1;
}
}
private void FormConfirm_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
if (Screen.PrimaryScreen.Bounds.Width > 1024)
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.WindowState = FormWindowState.Normal;
}
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/CircleWithLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
public static class CircleWithLine
{
public static bool Contains(Circle containingCircle, Line containedLine)
{
// Un cercle ne peut pas contenir une droite...
return false;
}
public static double Distance(Circle circle, Line line)
{
// Distance de la ligne jusqu'au centre du cercle - son rayon (Si négatif c'est que ça croise, donc distance 0)
return Math.Max(0, line.Distance(circle.Center) - circle.Radius);
}
public static bool Cross(Circle circle, Line line)
{
// Si une droite croise le cercle, c'est que le point de la droite le plus proche du centre du cercle est éloigné d'une distance inférieure au rayon
return line.Distance(circle.Center) <= circle.Radius;
}
public static List<RealPoint> GetCrossingPoints(Circle circle, Line line)
{
List<RealPoint> intersectsPoints = new List<RealPoint>();
double x1, y1, x2, y2;
if (line.IsVertical)
{
y1 = 0;
x1 = -line.B;
y2 = 100;
x2 = -line.B;
}
else
{
x1 = 0;
y1 = line.A * x1 + line.B;
x2 = 100;
y2 = line.A * x2 + line.B;
}
double dx = x2 - x1;
double dy = y2 - y1;
double Ox = x1 - circle.Center.X;
double Oy = y1 - circle.Center.Y;
double A = dx * dx + dy * dy;
double B = 2 * (dx * Ox + dy * Oy);
double C = Ox * Ox + Oy * Oy - circle.Radius * circle.Radius;
double delta = B * B - 4 * A * C;
if (delta < 0 + double.Epsilon && delta > 0 - double.Epsilon)
{
double t = -B / (2 * A);
intersectsPoints.Add(new RealPoint(x1 + t * dx, y1 + t * dy));
}
if (delta > 0)
{
double t1 = (double)((-B - Math.Sqrt(delta)) / (2 * A));
double t2 = (double)((-B + Math.Sqrt(delta)) / (2 * A));
intersectsPoints.Add(new RealPoint(x1 + t1 * dx, y1 + t1 * dy));
intersectsPoints.Add(new RealPoint(x1 + t2 * dx, y1 + t2 * dy));
}
return intersectsPoints;
}
}
}
<file_sep>/GoBot/GoBot/CameraIP.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;
namespace GoBot
{
class CameraIP
{
public String URLImage { get; set; }
public CameraIP(String url)
{
URLImage = url;
}
public CameraIP()
{
URLImage = "http://10.1.0.10/snapshot.jpg";
}
public Bitmap GetImage()
{
try
{
// Récupération de l'image
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URLImage);
Stream stream = req.GetResponse().GetResponseStream();
Bitmap img = (Bitmap)Bitmap.FromStream(stream);
return img;
}
catch (Exception)
{
return null;
}
}
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionStop.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionStop : IAction
{
private StopMode mode;
private Robot robot;
public ActionStop(Robot r, StopMode m)
{
robot = r;
mode = m;
}
public override string ToString()
{
return robot.Name + " stop " + mode;
}
void IAction.Executer()
{
robot.Stop(mode);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Stop16;
}
}
}
}
<file_sep>/GoBot/GeometryTester/TestAngles.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Geometry;
namespace GeometryTester
{
[TestClass]
public class TestAngles
{
[TestMethod]
public void TestAngleDeltaDegRad()
{
AngleDelta deg = new AngleDelta(720, AngleType.Degre);
AngleDelta rad = new AngleDelta(Math.PI * 4, AngleType.Radian);
Assert.AreEqual(deg, rad);
Assert.AreEqual(deg, 720, AngleDelta.PRECISION);
}
[TestMethod]
public void TestAngleDeltaTrigo()
{
double a = Math.PI / 2.54; // Arbitraire
AngleDelta deg = new AngleDelta(a, AngleType.Radian);
Assert.AreEqual(Math.Cos(a), deg.Cos, AngleDelta.PRECISION);
Assert.AreEqual(Math.Sin(a), deg.Sin, AngleDelta.PRECISION);
Assert.AreEqual(Math.Tan(a), deg.Tan, AngleDelta.PRECISION);
}
[TestMethod]
public void TestAngleDeltaModulo()
{
Assert.AreEqual(10, new AngleDelta(10).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(10, new AngleDelta(370).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(0, new AngleDelta(0).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(180, new AngleDelta(180).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(-180, new AngleDelta(-180).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(0, new AngleDelta(360).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(-10, new AngleDelta(-10).Modulo(), AngleDelta.PRECISION);
Assert.AreEqual(170, new AngleDelta(-190).Modulo(), AngleDelta.PRECISION);
}
[TestMethod]
public void TestAnglePositionDegRad()
{
AnglePosition deg = new AnglePosition(90, AngleType.Degre);
AnglePosition rad = new AnglePosition(Math.PI / 2, AngleType.Radian);
Assert.AreEqual(deg, rad);
Assert.AreEqual(deg, 90, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionModulo()
{
AnglePosition a800 = new AnglePosition(800, AngleType.Degre);
AnglePosition a80 = new AnglePosition(80, AngleType.Degre);
Assert.AreEqual(a800, a80);
Assert.AreEqual(80, a800.InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(80, a800.InPositiveDegrees, AnglePosition.PRECISION);
Assert.AreEqual(80.0 / 180.0 * Math.PI, a800.InRadians, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionNeg()
{
AnglePosition a = new AnglePosition(-50, AngleType.Degre);
Assert.AreEqual(-50, a.InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(310, a.InPositiveDegrees, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionAdd()
{
AnglePosition a10 = new AnglePosition(10);
AnglePosition a190 = new AnglePosition(190);
AnglePosition a350 = new AnglePosition(350);
AngleDelta da10 = new AngleDelta(10);
AngleDelta da80 = new AngleDelta(80);
AngleDelta da20 = new AngleDelta(20);
Assert.AreEqual(0, (a350 + da10).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(10, (a350 + da20).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(-90, (a190 + da80).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(20, (a10 + da10).InDegrees, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionSub1()
{
AnglePosition a30 = new AnglePosition(30);
AnglePosition a350 = new AnglePosition(350);
AngleDelta da30 = new AngleDelta(30);
AngleDelta da350 = new AngleDelta(350);
Assert.AreEqual(40, (a30 - da350).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(-40, (a350 - da30).InDegrees, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionSub2()
{
AnglePosition a0 = new AnglePosition(0);
AnglePosition a30 = new AnglePosition(30);
AnglePosition a60 = new AnglePosition(60);
AnglePosition a89 = new AnglePosition(89);
AnglePosition a90 = new AnglePosition(90);
AnglePosition a91 = new AnglePosition(91);
AnglePosition a270 = new AnglePosition(270);
AnglePosition a350 = new AnglePosition(350);
AnglePosition a360 = new AnglePosition(360);
Assert.AreEqual(-40, (a350 - a30).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(40, (a30 - a350).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(30, (a90 - a60).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(-30, (a60 - a90).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(0, (a0 - a360).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(180, (a90 - a270).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(-179, (a91 - a270).InDegrees, AnglePosition.PRECISION);
Assert.AreEqual(179, (a89 - a270).InDegrees, AnglePosition.PRECISION);
}
[TestMethod]
public void TestAnglePositionEqual()
{
AnglePosition a1, a2;
a1 = new AnglePosition(90);
a2 = new AnglePosition(90);
Assert.AreEqual(a1, a2);
a1 = new AnglePosition(0);
a2 = new AnglePosition(0);
Assert.AreEqual(a1, a2);
a1 = new AnglePosition(-10);
a2 = new AnglePosition(350);
Assert.AreEqual(a1, a2);
a1 = new AnglePosition(0);
a2 = new AnglePosition(360);
Assert.AreEqual(a1, a2);
a1 = new AnglePosition(90);
a2 = new AnglePosition(-270);
Assert.AreEqual(a1, a2);
}
[TestMethod]
public void TestAnglePositionNotEqual()
{
AnglePosition a1, a2;
a1 = new AnglePosition(85);
a2 = new AnglePosition(86);
Assert.AreNotEqual(a1, a2);
a1 = new AnglePosition(0);
a2 = new AnglePosition(359);
Assert.AreNotEqual(a1, a2);
}
[TestMethod]
public void TestAnglePositionCenter()
{
Assert.AreEqual(45, AnglePosition.Center(0, 90));
Assert.AreEqual(45 + 180, AnglePosition.CenterLongArc(0, 90));
Assert.AreEqual(45, AnglePosition.CenterSmallArc(0, 90));
Assert.AreEqual(45 + 180, AnglePosition.Center(90, 0));
Assert.AreEqual(45 + 180, AnglePosition.CenterLongArc(90, 0));
Assert.AreEqual(45, AnglePosition.CenterSmallArc(90, 0));
Assert.AreEqual(30, AnglePosition.Center(-20, 80));
Assert.AreEqual(30 + 180, AnglePosition.CenterLongArc(-20, 80));
Assert.AreEqual(30, AnglePosition.CenterSmallArc(-20, 80));
Assert.AreEqual(30 + 180, AnglePosition.Center(80, -20));
Assert.AreEqual(30 + 180, AnglePosition.CenterLongArc(80, -20));
Assert.AreEqual(30, AnglePosition.CenterSmallArc(80, -20));
Assert.AreEqual(175, AnglePosition.Center(80, 270));
Assert.AreEqual(175, AnglePosition.CenterLongArc(80, 270));
Assert.AreEqual(175 + 180, AnglePosition.CenterSmallArc(80, 270));
Assert.AreEqual(175 + 180, AnglePosition.Center(270, 80));
Assert.AreEqual(175, AnglePosition.CenterLongArc(270, 80));
Assert.AreEqual(175 + 180, AnglePosition.CenterSmallArc(270, 80));
}
[TestMethod]
public void TestAnglePositionIsOnArc()
{
Assert.IsTrue(((AnglePosition)45).IsOnArc(0, 90));
Assert.IsTrue(((AnglePosition)0).IsOnArc(0, 90));
Assert.IsTrue(((AnglePosition)90).IsOnArc(0, 90));
Assert.IsFalse(((AnglePosition)91).IsOnArc(0, 90));
Assert.IsFalse(((AnglePosition)(-50)).IsOnArc(0, 90));
Assert.IsFalse(((AnglePosition)45).IsOnArc(90, 0));
Assert.IsTrue(((AnglePosition)0).IsOnArc(90, 0));
Assert.IsTrue(((AnglePosition)90).IsOnArc(90, 0));
Assert.IsTrue(((AnglePosition)91).IsOnArc(90, 0));
Assert.IsTrue(((AnglePosition)(-50)).IsOnArc(90, 0));
Assert.IsTrue(((AnglePosition)0).IsOnArc(-20, 20));
Assert.IsFalse(((AnglePosition)(-40)).IsOnArc(-20, 20));
Assert.IsFalse(((AnglePosition)0).IsOnArc(20, -20));
Assert.IsTrue(((AnglePosition)(-40)).IsOnArc(20, -20));
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/PanelActuatorOnOff.cs
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class PanelActuatorOnOff : UserControl
{
private ActuatorOnOffID _actuator;
public PanelActuatorOnOff()
{
InitializeComponent();
}
public void SetActuator(ActuatorOnOffID actuator)
{
_actuator = actuator;
lblName.Text = NameFinder.GetName(actuator).Substring(0, 1).ToUpper() + NameFinder.GetName(actuator).Substring(1);
}
private void btnOnOff_ValueChanged(object sender, bool value)
{
Robots.MainRobot.SetActuatorOnOffValue(_actuator, value);
}
}
}
<file_sep>/GoBot/GoBot/Communications/Connection.cs
namespace GoBot.Communications
{
public abstract class Connection
{
/// <summary>
/// Sauvegarde des trames transitées par la connexion
/// </summary>
public FramesLog Archives { get; protected set; }
/// <summary>
/// Verificateur de connexion
/// </summary>
public ConnectionChecker ConnectionChecker { get; set; }
/// <summary>
/// Vrai si le client est connecté (dans le sens où la liaison est établie, mais pas forcément que le protocole répond)
/// </summary>
public bool Connected { get; set; }
/// <summary>
/// Envoi le message au client actuellement connecté
/// </summary>
/// <param name="message">Message à envoyer au client</param>
/// <returns>Nombre de caractères envoyés</returns>
abstract public bool SendMessage(Frame message);
//Déclaration du délégué pour l’évènement réception ou émission de message
public delegate void NewFrameDelegate(Frame frame);
//Déclaration de l’évènement utilisant le délégué pour la réception d'une trame
public event NewFrameDelegate FrameReceived;
//Déclaration de l’évènement utilisant le délégué pour l'émission d'une trame
public event NewFrameDelegate FrameSend;
public Connection()
{
Archives = new FramesLog();
}
/// <summary>
/// Lance la réception de trames sur la configuration actuelle
/// </summary>
abstract public void StartReception();
abstract public string Name { get; set; }
/// <summary>
/// Libère la connexion vers le client
/// </summary>
abstract public void Close();
/// <summary>
/// Ajoute une trame reçue
/// </summary>
/// <param name="frame">Trame reçue</param>
public void OnFrameReceived(Frame frame)
{
Archives.AddFrame(frame, true);
FrameReceived?.Invoke(frame);
}
/// <summary>
/// Ajoute une trame envoyée
/// </summary>
/// <param name="frame">Trame envoyée</param>
public void OnFrameSend(Frame frame)
{
Archives.AddFrame(frame, false);
FrameSend?.Invoke(frame);
}
}
}
<file_sep>/GoBot/GoBot/Communications/CAN/CanFrameFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Communications.CAN
{
static class CanFrameFactory
{
public static CanFrameFunction ExtractFunction(Frame frame)
{
return (CanFrameFunction)frame[2];
}
public static CanBoard ExtractBoard(Frame frame)
{
return (CanBoard)(frame[0] * 256 + frame[1]);
}
public static CanBoard ExtractSender(Frame frame, bool isInput)
{
return isInput ? ExtractBoard(frame) : CanBoard.PC;
}
public static CanBoard ExtractReceiver(Frame frame, bool isInput)
{
return isInput ? CanBoard.PC : ExtractBoard(frame);
}
public static ServomoteurID ExtractServomoteurID(Frame frame)
{
if (Config.CurrentConfig.IsMiniRobot)
return (ServomoteurID)((int)(ExtractBoard(frame) - 1) * 4 + frame[3]);
else
return (ServomoteurID)((int)(ExtractBoard(frame) - 1) * 4 + frame[3]);
}
public static int ExtractValue(Frame frame, int paramNo = 0)
{
return frame[4 + paramNo * 2] * 256 + frame[5 + paramNo * 2];
}
public static Frame BuildGetPosition(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetPositionMin(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionMinAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetPositionMax(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionMaxAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetSpeedMax(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.SpeedMaxAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetAcceleration(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.AccelerationAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetTorqueCurrent(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.TorqueCurrentAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildGetTorqueMax(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.TorqueMaxAsk;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildSetAcceleration(ServomoteurID id, int acceleration)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.AccelerationSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(acceleration, true);
tab[5] = ByteDivide(acceleration, false);
return new Frame(tab);
}
public static Frame BuildSetPosition(ServomoteurID id, int position)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(position, true);
tab[5] = ByteDivide(position, false);
return new Frame(tab);
}
public static Frame BuildSetPositionMax(ServomoteurID id, int position)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionMaxSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(position, true);
tab[5] = ByteDivide(position, false);
return new Frame(tab);
}
public static Frame BuildSetPositionMin(ServomoteurID id, int position)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.PositionMinSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(position, true);
tab[5] = ByteDivide(position, false);
return new Frame(tab);
}
public static Frame BuildSetSpeedMax(ServomoteurID id, int speed)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.SpeedMaxSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(speed, true);
tab[5] = ByteDivide(speed, false);
return new Frame(tab);
}
public static Frame BuildSetTorqueMax(ServomoteurID id, int torque)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.TorqueMaxSet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(torque, true);
tab[5] = ByteDivide(torque, false);
return new Frame(tab);
}
public static Frame BuildSetTrajectory(ServomoteurID id, int position, int speed, int accel)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.TrajectorySet;
tab[3] = GlobalIdToServoNo(id);
tab[4] = ByteDivide(position, true);
tab[5] = ByteDivide(position, false);
tab[6] = ByteDivide(speed, true);
tab[7] = ByteDivide(speed, false);
tab[8] = ByteDivide(accel, true);
tab[9] = ByteDivide(accel, false);
return new Frame(tab);
}
public static Frame BuildDisableOutput(ServomoteurID id)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)GlobalIdToCanBoard(id);
tab[2] = (byte)CanFrameFunction.DisableOutput;
tab[3] = GlobalIdToServoNo(id);
return new Frame(tab);
}
public static Frame BuildTestConnection(CanBoard board)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)board;
tab[2] = (byte)CanFrameFunction.TestConnection;
return new Frame(tab);
}
public static Frame BuildBeep(CanBoard board, int freqHz, int durationMs)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)board;
tab[2] = (byte)CanFrameFunction.Buzzer;
tab[3] = ByteDivide(freqHz, true);
tab[4] = ByteDivide(freqHz, false);
tab[5] = ByteDivide(durationMs, true);
tab[6] = ByteDivide(durationMs, false);
return new Frame(tab);
}
public static Frame BuildDebug(CanBoard board)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)board;
tab[2] = (byte)CanFrameFunction.Debug;
return new Frame(tab);
}
public static Frame BuildDebugAsk(CanBoard board)
{
byte[] tab = new byte[10];
tab[0] = 0x00;
tab[1] = (byte)board;
tab[2] = (byte)CanFrameFunction.DebugAsk;
return new Frame(tab);
}
private static byte ByteDivide(int valeur, bool mostSignifiantBit)
{
byte b;
if (mostSignifiantBit)
b = (byte)(valeur >> 8);
else
b = (byte)(valeur & 0x00FF);
return b;
}
private static CanBoard GlobalIdToCanBoard(ServomoteurID servoGlobalId)
{
return (CanBoard)((int)servoGlobalId / 4 + 1);
}
private static byte GlobalIdToServoNo(ServomoteurID servoGlobalId)
{
return (byte)((int)servoGlobalId % 4);
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaScore.cs
using GoBot.Threading;
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PagePandaScore : UserControl
{
public PagePandaScore()
{
InitializeComponent();
}
private void picLogo_MouseDown(object sender, MouseEventArgs e)
{
picLogo.Location = new Point(picLogo.Location.X + 2, picLogo.Location.Y + 2);
}
private void picLogo_MouseUp(object sender, MouseEventArgs e)
{
picLogo.Location = new Point(picLogo.Location.X - 2, picLogo.Location.Y - 2);
}
private void picLogo_MouseClick(object sender, MouseEventArgs e)
{
picLogo.Visible = false;
pnlDetails.Location = new Point(pnlDetails.Left, this.Height);
pnlDetails.Visible = true;
//lblSlogan.Visible = false;
//lblSubSlogan.Visible = false;
ThreadManager.CreateThread(link => ScoreAnimation(link)).StartThread();
}
private void ScoreAnimation(ThreadLink link)
{
link.RegisterName();
double progress = 0;
int startYScore = 600;
int endYScore = 241;
int startYSlogan = 507;
int endYSlogan = startYSlogan + (startYScore - endYScore);
int startYSubSlogan = 555;
int endYSubSlogan = startYSubSlogan + (startYScore - endYScore);
int startYLogo = 301;
int endYLogo = startYLogo + (startYScore - endYScore);
int animDuration = 1000;
int fps = 30;
do
{
progress += 1f / fps;
progress = Math.Min(1, progress);
this.InvokeAuto(() =>
{
Font f = new Font(lblScore.Font.Name, (float)(172 - (172 - 124) * Math.Max(0, (progress - 0.5) * 2)));
lblScore.Font = f;
pnlDetails.Location = new Point(pnlDetails.Left, (int)(startYScore - progress * (startYScore - endYScore)));
lblSlogan.Location = new Point(lblSlogan.Left, (int)(startYSlogan - progress * (startYSlogan - endYSlogan)));
lblSubSlogan.Location = new Point(lblSubSlogan.Left, (int)(startYSubSlogan - progress * (startYSubSlogan - endYSubSlogan)));
});
Thread.Sleep(animDuration / fps);
} while (progress < 1);
}
}
}
<file_sep>/GoBot/GoBot/Devices/Buzzer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoBot.Communications.CAN;
namespace GoBot.Devices
{
public class Buzzer
{
private iCanSpeakable _communication;
public Buzzer(iCanSpeakable comm)
{
_communication = comm;
}
public void Buzz(int freqHz, int durationMs)
{
_communication.SendFrame(CanFrameFactory.BuildBeep(CanBoard.CanAlim, freqHz, durationMs));
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/RobotPositionables.cs
using System;
using GoBot.Actionneurs;
namespace GoBot
{
public partial class Config
{
public ServoFlagLeft ServoFlagLeft { get; set; } = new ServoFlagLeft();
public ServoFlagRight ServoFlagRight { get; set; } = new ServoFlagRight();
public ServoPushArmRight ServoPushArmRight { get; set; } = new ServoPushArmRight();
public ServoPushArmLeft ServoPushArmLeft { get; set; } = new ServoPushArmLeft();
public ServoGrabberRight ServoGrabberRight { get; set; } = new ServoGrabberRight();
public ServoGrabberLeft ServoGrabberLeft { get; set; } = new ServoGrabberLeft();
public ServoFingerRight ServoFingerRight { get; set; } = new ServoFingerRight();
public ServoFingerLeft ServoFingerLeft { get; set; } = new ServoFingerLeft();
public ServoLockerRight ServoLockerRight { get; set; } = new ServoLockerRight();
public ServoLockerLeft ServoLockerLeft { get; set; } = new ServoLockerLeft();
public MotorElevatorRight MotorElevatorRight { get; set; } = new MotorElevatorRight();
public MotorElevatorLeft MotorElevatorLeft { get; set; } = new MotorElevatorLeft();
public ServoClamp1 ServoClamp1 { get; set; } = new ServoClamp1();
public ServoClamp2 ServoClamp2 { get; set; } = new ServoClamp2();
public ServoClamp3 ServoClamp3 { get; set; } = new ServoClamp3();
public ServoClamp4 ServoClamp4 { get; set; } = new ServoClamp4();
public ServoClamp5 ServoClamp5 { get; set; } = new ServoClamp5();
public ServoLifter ServoLifter { get; set; } = new ServoLifter();
public ServoTilter ServoTilter { get; set; } = new ServoTilter();
// Peit robot
public SmallElevatorLeft SmallElevatorLeft { get; set; } = new SmallElevatorLeft();
public SmallElevatorRight SmallElevatorRight { get; set; } = new SmallElevatorRight();
public SmallElevatorBack SmallElevatorBack { get; set; } = new SmallElevatorBack();
public ArmLeft ArmLeft { get; set; } = new ArmLeft();
public ArmRight ArmRight { get; set; } = new ArmRight();
public Selector Selector { get; set; } = new Selector();
public Retractor Retractor { get; set; } = new Retractor();
}
}
namespace GoBot.Actionneurs
{
#region PositionableServo
public abstract class ServoFlag : PositionableServo
{
public int PositionOpen { get; set; }
public int PositionClose { get; set; }
}
public class ServoFlagLeft : ServoFlag
{
public override ServomoteurID ID => ServomoteurID.FlagLeft;
}
public class ServoFlagRight : ServoFlag
{
public override ServomoteurID ID => ServomoteurID.FlagRight;
}
public abstract class ServoPushArm : PositionableServo
{
public int PositionOpen { get; set; }
public int PositionClose { get; set; }
public int PositionLight { get; set; }
}
public class ServoPushArmLeft : ServoPushArm
{
public override ServomoteurID ID => ServomoteurID.PushArmLeft;
}
public class ServoPushArmRight : ServoPushArm
{
public override ServomoteurID ID => ServomoteurID.PushArmRight;
}
public abstract class ServoFinger : PositionableServo
{
public int PositionHide { get; set; }
public int PositionKeep { get; set; }
public int PositionGrab { get; set; }
}
public class ServoFingerLeft : ServoFinger
{
public override ServomoteurID ID => ServomoteurID.FingerLeft;
}
public class ServoFingerRight : ServoFinger
{
public override ServomoteurID ID => ServomoteurID.FingerRight;
}
public abstract class ServoGrabber : PositionableServo
{
public int PositionOpen { get; set; }
public int PositionClose { get; set; }
public int PositionHide { get; set; }
public int PositionRelease { get; set; }
}
public class ServoGrabberRight : ServoGrabber
{
public override ServomoteurID ID => ServomoteurID.GrabberRight;
}
public class ServoGrabberLeft : ServoGrabber
{
public override ServomoteurID ID => ServomoteurID.GrabberLeft;
}
public abstract class ServoLocker : PositionableServo
{
public int PositionEngage { get; set; }
public int PositionDisengage { get; set; }
public int PositionMaintain { get; set; }
}
public class ServoLockerRight : ServoLocker
{
public override ServomoteurID ID => ServomoteurID.LockerRight;
}
public class ServoLockerLeft : ServoLocker
{
public override ServomoteurID ID => ServomoteurID.LockerLeft;
}
public abstract class ServoClamp : PositionableServo
{
public int PositionOpen { get; set; }
public int PositionMaintain { get; set; }
public int PositionClose { get; set; }
public int PositionStore { get; set; }
}
public class ServoClamp1 : ServoClamp
{
public override ServomoteurID ID => ServomoteurID.Clamp1;
}
public class ServoClamp2 : ServoClamp
{
public override ServomoteurID ID => ServomoteurID.Clamp2;
}
public class ServoClamp3 : ServoClamp
{
public override ServomoteurID ID => ServomoteurID.Clamp3;
}
public class ServoClamp4 : ServoClamp
{
public override ServomoteurID ID => ServomoteurID.Clamp4;
}
public class ServoClamp5 : ServoClamp
{
public override ServomoteurID ID => ServomoteurID.Clamp5;
}
public class ServoLifter : PositionableServo
{
public override ServomoteurID ID => ServomoteurID.Lifter;
public int PositionStore { get; set; }
public int PositionExtract { get; set; }
}
public class ServoTilter : PositionableServo
{
public override ServomoteurID ID => ServomoteurID.Tilter;
public int PositionStore { get; set; }
public int PositionPickup { get; set; }
public int PositionExtract { get; set; }
public int PositionDropoff { get; set; }
}
#endregion
#region PositionableMotorSpeed
#endregion
#region PositionableMotorPosition
public abstract class MotorElevator : PositionableMotorPosition
{
public int PositionFloor0 { get; set; }
public int PositionFloor1 { get; set; }
public int PositionFloor2 { get; set; }
public int PositionFloor3 { get; set; }
}
public class MotorElevatorRight : MotorElevator
{
public override MotorID ID => MotorID.ElevatorRight;
}
public class MotorElevatorLeft : MotorElevator
{
public override MotorID ID => MotorID.ElevatorLeft;
}
#endregion
// Petit robot
public abstract class Arm : PositionableServo
{
public int PositionClose { get; set; }
public int PositionOpen { get; set; }
}
public class ArmLeft : Arm
{
public override ServomoteurID ID => ServomoteurID.ArmLeft;
}
public class ArmRight : Arm
{
public override ServomoteurID ID => ServomoteurID.ArmRight;
}
public abstract class SmallElevator : PositionableServo
{
public int PositionBottom { get; set; }
public int PositionMiddle { get; set; }
public int PositionTop { get; set; }
public int PositionGrab { get; set; }
}
public class SmallElevatorLeft : SmallElevator
{
public override ServomoteurID ID => ServomoteurID.ElevatorLeft;
}
public class SmallElevatorRight : SmallElevator
{
public override ServomoteurID ID => ServomoteurID.ElevatorRight;
}
public class SmallElevatorBack : SmallElevator
{
public override ServomoteurID ID => ServomoteurID.ElevatorBack;
}
public class Selector : PositionableServo
{
public override ServomoteurID ID => ServomoteurID.Selector;
public int PositionLeft { get; set; }
public int PositionMiddle { get; set; }
public int PositionRight { get; set; }
}
public class Retractor : PositionableServo
{
public override ServomoteurID ID => ServomoteurID.Retractor;
public int PositionEngage { get; set; }
public int PositionDisengage { get; set; }
}
}
<file_sep>/GoBot/Composants/GroupBoxPlus.cs
using System;
using System.Windows.Forms;
namespace Composants
{
public partial class GroupBoxPlus : GroupBox
{
private Button ButtonArrow { get; set; }
private Timer TimerAnimation { get; set; }
private int OriginalHeight { get; set; }
private int ReducedHeight { get; set; }
/// <summary>
/// Vrai si le panel est actuellement ouvert
/// </summary>
public bool Deployed { get; private set; }
public delegate void DeployedChangedDelegate(bool deployed);
/// <summary>
/// Se produit lorsque le déploiement du panel change
/// </summary>
public event DeployedChangedDelegate DeployedChanged;
public GroupBoxPlus()
{
InitializeComponent();
ButtonArrow = new Button();
ButtonArrow.Visible = true;
ButtonArrow.Image = Properties.Resources.ArrowUp;
ButtonArrow.SetBounds(this.Width - 23 - 5, 10, 23, 23);
ButtonArrow.Anchor = AnchorStyles.Right | AnchorStyles.Top;
ButtonArrow.Click += new EventHandler(ButtonArrow_Click);
Controls.Add(ButtonArrow);
ReducedHeight = 37;
OriginalHeight = 0;
Deployed = true;
this.SizeChanged += new EventHandler(GroupBoxPlus_SizeChanged);
this.DoubleBuffered = true;
}
/// <summary>
/// Ouvre ou ferme le panel
/// </summary>
/// <param name="open">Ouvre le panel si vrai, sinon le ferme</param>
/// <param name="animation">Vrai si l'animation smooth doit être utilisée, faux si l'action doit être instantanée</param>
public void Deploy(bool open = true, bool animation = false)
{
if (open)
Open(animation);
else
Close(animation);
}
void GroupBoxPlus_SizeChanged(object sender, EventArgs e)
{
ButtonArrow.SetBounds(this.Width - ButtonArrow.Width - 5, 10, ButtonArrow.Width, ButtonArrow.Height);
}
void ButtonArrow_Click(object sender, EventArgs e)
{
Deploy(!Deployed, true);
}
private void Open(bool animation = false)
{
Deployed = true;
if (OriginalHeight == 0)
return;
foreach (Control c in Controls)
c.Visible = true;
ButtonArrow.Image = Properties.Resources.ArrowUp;
Deployed = true;
if (animation)
{
TimerAnimation = new Timer();
TimerAnimation.Interval = 20;
TimerAnimation.Tick += new EventHandler(TimerAnimation_Tick);
TimerAnimation.Start();
}
else
{
this.Height = OriginalHeight;
}
DeployedChanged?.Invoke(true);
}
private void Close(bool animation = false)
{
Deployed = false;
if(OriginalHeight == 0)
OriginalHeight = this.Height;
ButtonArrow.Image = Properties.Resources.ArrowBottom;
Deployed = false;
if (animation)
{
TimerAnimation = new Timer();
TimerAnimation.Interval = 20;
TimerAnimation.Tick += new EventHandler(TimerAnimation_Tick);
TimerAnimation.Start();
}
else
{
this.Height = ReducedHeight;
foreach (Control c in Controls)
c.Visible = false;
ButtonArrow.Visible = true;
}
DeployedChanged?.Invoke(false);
}
void TimerAnimation_Tick(object sender, EventArgs e)
{
if (Deployed)
{
if (OriginalHeight - this.Height == 1)
{
this.Height = OriginalHeight;
TimerAnimation.Stop();
}
else
{
this.Height += (int)Math.Ceiling((OriginalHeight - this.Height) / 5.0);
}
}
else
{
if (this.Height - ReducedHeight == 1)
{
this.Height = ReducedHeight;
TimerAnimation.Stop();
foreach (Control c in Controls)
c.Visible = false;
ButtonArrow.Visible = true;
ButtonArrow.Focus();
}
else
{
this.Height -= (int)Math.Ceiling((this.Height - ReducedHeight) / 5.0);
}
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/RealPointWithRealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class RealPointWithRealPoint
{
public static bool Contains(RealPoint containingPoint, RealPoint containedPoint)
{
return containingPoint == containedPoint;
}
public static bool Cross(RealPoint point1, RealPoint point2)
{
return point1 == point2;
}
public static double Distance(RealPoint point1, RealPoint point2)
{
return Maths.Hypothenuse((point2.X - point1.X), (point2.Y - point1.Y)); ;
}
public static List<RealPoint> GetCrossingPoints(RealPoint point1, RealPoint point2)
{
List<RealPoint> output = new List<RealPoint>();
if (point1 == point2)
output.Add(new RealPoint(point1));
return output;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/IShape.cs
using System.Collections.Generic;
using System.Drawing;
namespace Geometry.Shapes
{
public interface IShape
{
/// <summary>
/// Teste si la forme courante croise la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si la forme courante croise la forme donnée</returns>
bool Cross(IShape shape);
/// <summary>
/// Teste si la forme courante contient la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si la forme courante contient la forme donnée</returns>
bool Contains(IShape shape);
/// <summary>
/// Retourne la distance minimum entre la forme courante et la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Distance entre la forme actuelle et la forme testée. Si les deux formes se croisent la distance est de 0</returns>
double Distance(IShape shape);
/// <summary>
/// Retourne les points de croisement entre la forme courante et la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Liste des points de croisements entre la forme courante et la forme donnée</returns>
List<RealPoint> GetCrossingPoints(IShape shape);
/// <summary>
/// Obtient la surface de la forme
/// </summary>
double Surface { get; }
/// <summary>
/// Obtient le barycentre de la forme
/// </summary>
RealPoint Barycenter { get; }
/// <summary>
/// Peint la forme sur le Graphic donné
/// </summary>
/// <param name="g">Graphic sur lequel peindre</param>
/// <param name="outline">Pen utilisé pour peindre le contour de la forme (null pour aucun contour)</param>
/// <param name="fillColor">Brush pour de remplissag de la forme (null pour aucun remplissage)</param>
/// <param name="scale">Echelle de conversion</param>
void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale);
}
public static class IShapeExtensions
{
/// <summary>
/// Retourne une copie de la forme ayant subit une translation
/// </summary>
/// <param name="shape">Forme à translater</param>
/// <param name="dx">Distance de translation en X</param>
/// <param name="dy">Distance de translation en Y</param>
/// <returns>Nouvelle forme ayant subit la translation</returns>
public static IShape Translation(this IShape shape, double dx, double dy)
{
return ((IShapeModifiable<IShape>)shape).Translation(dx, dy);
}
/// <summary>
/// Retourne une copie de la forme ayant subit une rotation
/// </summary>
/// <param name="shape">Forme à tourner</param>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation. Si null alors le barycentre est utilisé.</param>
/// <returns>Nouvelle forme ayant subit la rotation</returns>
public static IShape Rotation(this IShape shape, AngleDelta angle, RealPoint rotationCenter = null)
{
return ((IShapeModifiable<IShape>)shape).Rotation(angle, rotationCenter);
}
public static void Paint(this IShape shape, Graphics g, Color outline, int outlineWidth, Color fill, WorldScale scale)
{
Pen p = new Pen(outline, outlineWidth);
Brush b = new SolidBrush(fill);
shape.Paint(g, p, b, scale);
p.Dispose();
b.Dispose();
}
}
public interface IShapeModifiable<out T>
{
/// <summary>
/// Retourne une copie de la forme ayant subit une translation
/// </summary>
/// <param name="dx">Distance de translation en X</param>
/// <param name="dy">Distance de translation en Y</param>
/// <returns>Nouvelle forme ayant subit la trabslation</returns>
T Translation(double dx, double dy);
/// <summary>
/// Retourne une copie de la forme ayant subit une rotation
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation. Si null alors le barycentre est utilisé.</param>
/// <returns>Nouvelle forme ayant subit la rotation</returns>
T Rotation(AngleDelta angle, RealPoint rotationCenter = null);
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelSpeedConfig.cs
using System;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class PanelSpeedConfig : UserControl
{
private bool _loaded;
public PanelSpeedConfig()
{
InitializeComponent();
_loaded = false;
}
private void PanelSpeedConfig_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
numSlowLineAcceleration.Value = Config.CurrentConfig.ConfigLent.LineAcceleration;
numSlowLineDeceleration.Value = Config.CurrentConfig.ConfigLent.LineDeceleration;
numSlowLineSpeed.Value = Config.CurrentConfig.ConfigLent.LineSpeed;
numSlowPivotAcceleration.Value = Config.CurrentConfig.ConfigLent.PivotAcceleration;
numSlowPivotDeceleration.Value = Config.CurrentConfig.ConfigLent.PivotDeceleration;
numSlowPivotSpeed.Value = Config.CurrentConfig.ConfigLent.PivotSpeed;
numFastLineAcceleration.Value = Config.CurrentConfig.ConfigRapide.LineAcceleration;
numFastLineDeceleration.Value = Config.CurrentConfig.ConfigRapide.LineDeceleration;
numFastLineSpeed.Value = Config.CurrentConfig.ConfigRapide.LineSpeed;
numFastPivotAcceleration.Value = Config.CurrentConfig.ConfigRapide.PivotAcceleration;
numFastPivotDeceleration.Value = Config.CurrentConfig.ConfigRapide.PivotDeceleration;
numFastPivotSpeed.Value = Config.CurrentConfig.ConfigRapide.PivotSpeed;
_loaded = true;
}
}
private void num_ValueChanged(object sender, EventArgs e)
{
if (_loaded)
{
Config.CurrentConfig.ConfigRapide.SetParams(
(int)numFastLineSpeed.Value,
(int)numFastLineAcceleration.Value,
(int)numFastLineDeceleration.Value,
(int)numFastPivotSpeed.Value,
(int)numFastPivotAcceleration.Value,
(int)numFastPivotDeceleration.Value);
Config.CurrentConfig.ConfigLent.SetParams(
(int)numSlowLineSpeed.Value,
(int)numSlowLineAcceleration.Value,
(int)numSlowLineDeceleration.Value,
(int)numSlowPivotSpeed.Value,
(int)numSlowPivotAcceleration.Value,
(int)numSlowPivotDeceleration.Value);
Config.Save();
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/CircleWithCircle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class CircleWithCircle
{
public static bool Contains(Circle circleContaining, Circle circleContained)
{
// Pour contenir un cercle il faut que son rayon + la distance entre les centres des deux cercles soit inférieure à notre rayon
return circleContained.Radius + circleContained.Center.Distance(circleContaining.Center) < circleContaining.Radius;
}
public static double Distance(Circle circle1, Circle circle2)
{
// C'est la distance entre les deux centres - la somme des deux rayons
return Math.Max(0, circle1.Center.Distance(circle2.Center) - circle2.Radius - circle1.Radius);
}
public static bool Cross(Circle circle1, Circle circle2)
{
// 2 cercles identiques se croisent
// Pour croiser un cercle il suffit que son centre soit éloigné de notre centre de moins que la somme de nos 2 rayons
// Et que les cercles ne se contiennent pas l'un l'autre
bool output;
if (circle1.Center == circle2.Center && Math.Abs(circle1.Radius - circle2.Radius) < RealPoint.PRECISION)
output = true;
else if (circle1.Center.Distance(circle2.Center) <= circle1.Radius + circle2.Radius)
output = (!circle2.Contains(circle1)) && (!circle1.Contains(circle2));
else
output = false;
return output;
}
public static List<RealPoint> GetCrossingPoints(Circle circle1, Circle circle2)
{
// Résolution du système d'équation à deux inconnues des deux équations de cercle
List<RealPoint> output = new List<RealPoint>();
if (circle1.Radius == 0 && circle2.Radius == 0 && circle1.Center == circle2.Center)
{
// Cas particulier où les deux cercles ont un rayon de 0 et sont au même endroit : le croisement c'est ce point.
output.Add(new RealPoint(circle1.Center));
}
else if (circle1.Center == circle2.Center)
{
// Cas particulier où les deux cercles ont un rayon > 0 et sont au même endroit : on ne calcule pas les points de croisement, même s'ils se superposent (une autre idée est la bienvenue ?)
}
else
{
bool aligned = Math.Abs(circle1.Center.Y - circle2.Center.Y) < RealPoint.PRECISION;
if (aligned)// Cercles non alignés horizontalement (on pivote pour les calculs, sinon division par 0)
circle1 = circle1.Rotation(90, circle2.Center);
RealPoint oc1 = new RealPoint(circle1.Center), oc2 = new RealPoint(circle2.Center);
double b = circle1.Radius, c = circle2.Radius;
double a = (-(Math.Pow(oc1.X, 2)) - (Math.Pow(oc1.Y, 2)) + Math.Pow(oc2.X, 2) + Math.Pow(oc2.Y, 2) + Math.Pow(b, 2) - Math.Pow(c, 2)) / (2 * (oc2.Y - oc1.Y));
double d = ((oc2.X - oc1.X) / (oc2.Y - oc1.Y));
double A = Math.Pow(d, 2) + 1;
double B = -2 * oc1.X + 2 * oc1.Y * d - 2 * a * d;
double C = Math.Pow(oc1.X, 2) + Math.Pow(oc1.Y, 2) - 2 * oc1.Y * a + Math.Pow(a, 2) - Math.Pow(b, 2);
double delta = Math.Pow(B, 2) - 4 * A * C;
if (delta >= 0)
{
double x1 = (-B + Math.Sqrt(delta)) / (2 * A);
double y1 = a - x1 * d;
output.Add(new RealPoint(x1, y1));
if (delta > 0)
{
double x2 = (-B - Math.Sqrt(delta)) / (2 * A);
double y2 = a - x2 * d;
output.Add(new RealPoint(x2, y2));
}
}
if (aligned)
output = output.ConvertAll(p => p.Rotation(-90, circle2.Center));
}
return output;
}
}
}
<file_sep>/GoBot/Composants/LabelPlus.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace Composants
{
public partial class LabelPlus : Label
{
// Fonctionnalités supplémentaires :
//
// - Afficher un texte pendant une certaine durée
// Fonction TextDuring(texte, durée)
private Timer TimerDisplay { get; set; }
private Color PreviousColor { get; set; }
private String PreviousText { get; set; }
public LabelPlus()
{
InitializeComponent();
}
/// <summary>
/// Permet d'afficher un texte donné dans une couleur donnée pendant un temps donné. Après quoi le texte et la couelru d'origine seront rétablis.
/// </summary>
/// <param name="text">Texte à afficher momentanément</param>
/// <param name="during">Durée d'affichage du texte (ms)</param>
/// <param name="color">Couleur du texte affiché momentanément</param>
public void ShowText(String text, int during = 2000, Color? color = null)
{
PreviousColor = ForeColor;
PreviousText = Text;
if (color.HasValue)
ForeColor = color.Value;
Text = text;
if (TimerDisplay != null)
{
if (TimerDisplay.Enabled)
{
TimerDisplay.Stop();
}
TimerDisplay.Dispose();
}
TimerDisplay = new Timer();
TimerDisplay.Interval = during;
TimerDisplay.Tick += new EventHandler(TimerDisplay_Tick);
TimerDisplay.Enabled = true;
TimerDisplay.Start();
}
void TimerDisplay_Tick(object sender, EventArgs e)
{
ForeColor = PreviousColor;
Text = PreviousText;
TimerDisplay.Stop();
Text = "";
}
}
}
<file_sep>/GoBot/Geometry/WorldScale.cs
using System.Drawing;
using Geometry.Shapes;
namespace Geometry
{
/// <summary>
/// Classe permettant de convertir des coordonnées réelles (sur l'aire de jeu) en coordonnées écran (sur l'image de l'aire de jeu)
/// </summary>
public class WorldScale
{
public double Factor { get; protected set; }
public int OffsetX { get; protected set; }
public int OffsetY { get; protected set; }
/// <summary>
/// Crée un PaintScale à partir des mesures fournies
/// </summary>
/// <param name="mmPerPixel">Nombre de mm par pixels</param>
/// <param name="offsetX">Position en pixels de l'abscisse 0</param>
/// <param name="offsetY">Position en pixels de l'ordonnéee 0</param>
public WorldScale(double mmPerPixel, int offsetX, int offsetY)
{
Factor = mmPerPixel;
OffsetX = offsetX;
OffsetY = offsetY;
}
public WorldScale(WorldScale other)
{
Factor = other.Factor;
OffsetX = other.OffsetX;
OffsetY = other.OffsetY;
}
/// <summary>
/// Retourne une échelle par défaut (par de transformation)
/// </summary>
/// <returns></returns>
public static WorldScale Default()
{
return new WorldScale(1, 0, 0);
}
// Ecran vers réel
public int ScreenToRealDistance(double value)
{
return (int)(value * Factor);
}
public RealPoint ScreenToRealPosition(Point value)
{
return new RealPoint(ScreenToRealDistance(value.X - OffsetX), ScreenToRealDistance(value.Y - OffsetY));
}
public SizeF ScreenToRealSize(Size sz)
{
return new SizeF(ScreenToRealDistance(sz.Width), ScreenToRealDistance(sz.Height));
}
public RectangleF ScreenToRealRect(Rectangle rect)
{
return new RectangleF(ScreenToRealPosition(rect.Location), ScreenToRealSize(rect.Size));
}
// Réel vers écran
public int RealToScreenDistance(double value)
{
return (int)System.Math.Round(value / Factor, 0);
}
public Point RealToScreenPosition(RealPoint value)
{
return new Point(RealToScreenDistance(value.X) + OffsetX, RealToScreenDistance(value.Y) + OffsetY);
}
public Size RealToScreenSize(SizeF sz)
{
return new Size(RealToScreenDistance(sz.Width), RealToScreenDistance(sz.Height));
}
public Rectangle RealToScreenRect(RectangleF rect)
{
return new Rectangle(RealToScreenPosition(rect.Location), RealToScreenSize(rect.Size));
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/PolygonWithLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class PolygonWithLine
{
public static bool Contains(Polygon containingPolygon, Line containedLine)
{
// Un polygon fini ne peut pas contenir une droite infinie.
return false;
}
public static bool Cross(Polygon polygon, Line line)
{
return LineWithPolygon.Cross(line, polygon);
}
public static double Distance(Polygon polygon, Line line)
{
return LineWithPolygon.Distance(line, polygon);
}
public static List<RealPoint> GetCrossingPoints(Polygon polygon, Line line)
{
return LineWithPolygon.GetCrossingPoints(line, polygon);
}
}
}
<file_sep>/GoBot/GoBot/Logs/ILog.cs
using System;
namespace GoBot.Logs
{
public interface ILog
{
/// <summary>
/// Ecrit un message dans le log
/// </summary>
/// <param name="message"></param>
void Write(String message);
/// <summary>
/// Ferme le log
/// </summary>
void Close();
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageLogsEvents.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PageLogsEvents : UserControl
{
private Dictionary<IDRobot, Color> couleurRobot;
private Dictionary<TypeLog, Color> couleurTypeLog;
private Dictionary<IDRobot, bool> dicRobotsAutorises;
private Dictionary<TypeLog, bool> dicTypesAutorises;
private DateTime dateDebut;
private DateTime datePrec;
private DateTime datePrecAff;
private System.Windows.Forms.Timer timerAffichage;
private bool affichageTempsReel = false;
private int compteur = 0;
private EventsReplay Replay { get; set; }
public PageLogsEvents()
{
InitializeComponent();
dataGridViewLog.Columns.Add("Id", "Id");
dataGridViewLog.Columns[0].Width = 50;
dataGridViewLog.Columns.Add("Heure", "Heure");
dataGridViewLog.Columns[1].Width = 80;
dataGridViewLog.Columns.Add("Robot", "Robot");
dataGridViewLog.Columns[2].Width = 80;
dataGridViewLog.Columns.Add("Type", "Type");
dataGridViewLog.Columns[3].Width = 80;
dataGridViewLog.Columns.Add("Message", "Message");
dataGridViewLog.Columns[4].Width = 520;
couleurRobot = new Dictionary<IDRobot, Color>();
couleurRobot.Add(IDRobot.GrosRobot, Color.LightBlue);
couleurTypeLog = new Dictionary<TypeLog, Color>();
couleurTypeLog.Add(TypeLog.Action, Color.Lavender);
couleurTypeLog.Add(TypeLog.PathFinding, Color.Khaki);
couleurTypeLog.Add(TypeLog.Strat, Color.IndianRed);
dicRobotsAutorises = new Dictionary<IDRobot, bool>();
dicTypesAutorises = new Dictionary<TypeLog, bool>();
// L'ajout de champs déclenche le SetCheck event qui ajoute les éléments automatiquement dans le dictionnaire
foreach (TypeLog type in Enum.GetValues(typeof(TypeLog)))
{
checkedListBoxEvents.Items.Add(type.ToString(), true);
}
foreach (IDRobot robot in Enum.GetValues(typeof(IDRobot)))
{
checkedListBoxRobots.Items.Add(robot.ToString(), true);
}
Replay = new EventsReplay();
}
private void btnCharger_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Fichiers replay events (*.elog)|*.elog";
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
foreach(String fichier in open.FileNames)
{
ChargerLog(fichier);
}
Replay.Trier();
Afficher();
}
}
public void Clear()
{
Replay = new EventsReplay();
}
public void ChargerLog(String fichier)
{
EventsReplay replayTemp = new EventsReplay();
replayTemp.Charger(fichier);
foreach (HistoLigne t in replayTemp.Events)
Replay.Events.Add(t);
}
public void Afficher()
{
try
{
dataGridViewLog.Rows.Clear();
if (Replay.Events.Count > 0)
{
dateDebut = Replay.Events[0].Heure;
datePrec = Replay.Events[0].Heure;
datePrecAff = Replay.Events[0].Heure;
compteur = 0;
for (int iTrame = 0; iTrame < Replay.Events.Count; iTrame++)
AfficherEvent(Replay.Events[iTrame]);
}
}
catch (Exception)
{
MessageBox.Show("Impossible de décoder tous les events contenus dans ce fichier.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnRefresh_Click(object sender, EventArgs e)
{
Afficher();
}
private void checkedListBoxRobots_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode)
{
String robotString = (String)checkedListBoxRobots.Items[e.Index];
IDRobot robot = (IDRobot)Enum.Parse(typeof(IDRobot), robotString);
dicRobotsAutorises[robot] = (e.NewValue == CheckState.Checked);
}
}
private void checkedListBoxEvents_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode)
{
String typeString = (String)checkedListBoxEvents.Items[e.Index];
TypeLog type = (TypeLog)Enum.Parse(typeof(TypeLog), typeString);
dicTypesAutorises[type] = (e.NewValue == CheckState.Checked);
}
}
private void dataGridViewLog_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex > 0 && e.ColumnIndex > 0)
dataGridViewLog.CurrentCell = dataGridViewLog.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
private void btnAfficher_Click(object sender, EventArgs e)
{
if (!affichageTempsReel)
{
Replay = new EventsReplay();
timerAffichage = new System.Windows.Forms.Timer();
timerAffichage.Interval = 1000;
timerAffichage.Tick += timerAffichage_Tick;
timerAffichage.Start();
Robots.MainRobot.Historique.NouveauLog += Replay.AjouterEvent;
btnCharger.Enabled = false;
btnAfficher.Text = "Arrêter l'affichage";
btnAfficher.Image = Properties.Resources.Pause16;
affichageTempsReel = true;
}
else
{
timerAffichage.Stop();
Robots.MainRobot.Historique.NouveauLog -= Replay.AjouterEvent;
btnCharger.Enabled = true;
btnAfficher.Text = "Afficher temps réel";
btnAfficher.Image = Properties.Resources.Play16;
affichageTempsReel = false;
}
}
void timerAffichage_Tick(object sender, EventArgs e)
{
int nbEvents = Replay.Events.Count;
for (int i = compteur; i < nbEvents; i++)
AfficherEvent(Replay.Events[i]);
if(boxScroll.Checked && dataGridViewLog.Rows.Count > 10)
dataGridViewLog.FirstDisplayedScrollingRowIndex = dataGridViewLog.RowCount - 1;
}
private void AfficherEvent(HistoLigne eventReplay)
{
String heure = "";
if (rdoHeure.Checked)
heure = eventReplay.Heure.ToString("hh:mm:ss:fff");
if (rdoTempsDebut.Checked)
heure = (eventReplay.Heure - dateDebut).ToString(@"hh\:mm\:ss\:fff");
if (rdoTempsPrec.Checked)
heure = (eventReplay.Heure - datePrec).ToString(@"hh\:mm\:ss\:fff");
if (rdoTempsPrecAff.Checked)
heure = (eventReplay.Heure - datePrecAff).ToString(@"hh\:mm\:ss\:fff");
if (dicRobotsAutorises[eventReplay.Robot] && dicTypesAutorises[eventReplay.Type])
{
dataGridViewLog.Rows.Add(compteur, heure, eventReplay.Robot.ToString(), eventReplay.Type.ToString(), eventReplay.Message);
datePrecAff = eventReplay.Heure;
if (rdoRobot.Checked)
dataGridViewLog.Rows[dataGridViewLog.Rows.Count - 1].DefaultCellStyle.BackColor = couleurRobot[eventReplay.Robot];
else if (rdoType.Checked)
dataGridViewLog.Rows[dataGridViewLog.Rows.Count - 1].DefaultCellStyle.BackColor = couleurTypeLog[eventReplay.Type];
}
compteur++;
datePrec = eventReplay.Heure;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/PolygonRectangle.cs
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Geometry.Shapes
{
public class PolygonRectangle : Polygon
{
/// <summary>
/// Construit un rectangle à partir du point en haut à gauche, de la largeur et de la hauteur
/// </summary>
/// <param name="topLeft">Point en haut à gauche du rectangle</param>
/// <param name="width">Largeur du rectangle</param>
/// <param name="heigth">Hauteur du rectangle</param>
public PolygonRectangle(RealPoint topLeft, double width, double heigth) : base()
{
List<Segment> rectSides = new List<Segment>();
if (topLeft == null)
throw new ArgumentOutOfRangeException();
topLeft = new RealPoint(topLeft);
if (width < 0)
{
topLeft.X += width;
width = -width;
}
if(heigth < 0)
{
topLeft.Y += heigth;
heigth = -heigth;
}
List<RealPoint> points = new List<RealPoint>
{
new RealPoint(topLeft.X, topLeft.Y),
new RealPoint(topLeft.X + width, topLeft.Y),
new RealPoint(topLeft.X + width, topLeft.Y + heigth),
new RealPoint(topLeft.X, topLeft.Y + heigth)
};
for (int i = 1; i < points.Count; i++)
rectSides.Add(new Segment(points[i - 1], points[i]));
rectSides.Add(new Segment(points[points.Count - 1], points[0]));
BuildPolygon(rectSides, false);
}
public PolygonRectangle(PolygonRectangle other) : base(other)
{
}
public PolygonRectangle(RectangleF other) : this(new RealPoint(other.Left, other.Top), other.Width, other.Height)
{
}
public override string ToString()
{
return _sides[0].StartPoint.ToString() + "; " +
"W = " + (_sides[1].StartPoint.X - _sides[0].StartPoint.X).ToString("0.00") + "; " +
"H = " + (_sides[3].StartPoint.Y - _sides[0].StartPoint.Y).ToString("0.00");
}
}
}
<file_sep>/GoBot/GoBot/Communications/CAN/CanSubConnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Communications.CAN
{
class CanSubConnection : Connection
{
private CanConnection _baseConnection;
private CanBoard _board;
private String _name;
public CanSubConnection(CanConnection baseConnection, CanBoard board)
{
_baseConnection = baseConnection;
_board = board;
ConnectionChecker = new ConnectionChecker(this, 500);
ConnectionChecker.SendConnectionTest += ConnectionChecker_SendConnectionTest;
_baseConnection.FrameReceived += _baseConnection_FrameReceived;
_name = board.ToString();
}
public override string Name { get => _name; set => _name = value; }
private void _baseConnection_FrameReceived(Frame frame)
{
if ((CanBoard) frame[1] == _board)
ConnectionChecker.NotifyAlive();
}
private void ConnectionChecker_SendConnectionTest(Connection sender)
{
_baseConnection.SendMessage(CanFrameFactory.BuildTestConnection(_board));
}
public override void Close()
{
}
public override bool SendMessage(Frame message)
{
return _baseConnection.SendMessage(new Frame(new byte[] { 0, (byte)_board }.Concat(message.ToBytes())));
}
public override void StartReception()
{
}
}
}
<file_sep>/GoBot/GoBot/Robots/RobotReel.cs
using GoBot.Actions;
using Geometry;
using Geometry.Shapes;
using GoBot.Communications;
using GoBot.Devices;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using GoBot.Threading;
using GoBot.Communications.UDP;
using GoBot.BoardContext;
using GoBot.Communications.CAN;
using GoBot.Strategies;
using GoBot.Actionneurs;
using GoBot.GameElements;
namespace GoBot
{
class RobotReel : Robot
{
private Dictionary<SensorOnOffID, Semaphore> _lockSensorOnOff;
private Dictionary<SensorColorID, Semaphore> _lockSensorColor;
private Dictionary<UdpFrameFunction, Semaphore> _lockFrame;
private Dictionary<MotorID, Semaphore> _lockMotor;
private Dictionary<SensorColorID, Board> _boardSensorColor;
private Dictionary<SensorOnOffID, Board> _boardSensorOnOff;
private Dictionary<ActuatorOnOffID, Board> _boardActuatorOnOff;
private Dictionary<MotorID, Board> _boardMotor;
private Connection _asserConnection;
private bool _positionReceived;
private List<double> _lastRecMoveLoad, _lastPwmLeft, _lastPwmRight;
List<int>[] _lastPidTest;
private string _lastLidarMeasure;
private Position _lastLidarPosition;
public override Position Position { get; protected set; }
public RobotReel(IDRobot id, Board asserBoard) : base(id, "Robot")
{
AsserEnable = true;
AsservBoard = asserBoard;
_asserConnection = Connections.UDPBoardConnection[AsservBoard];
_positionReceived = false;
_lockFrame = new Dictionary<UdpFrameFunction, Semaphore>();
foreach (UdpFrameFunction o in Enum.GetValues(typeof(UdpFrameFunction)))
_lockFrame.Add(o, new Semaphore(0, int.MaxValue));
_lockMotor = new Dictionary<MotorID, Semaphore>();
foreach (MotorID o in Enum.GetValues(typeof(MotorID)))
_lockMotor.Add(o, new Semaphore(0, int.MaxValue));
_lockSensorOnOff = new Dictionary<SensorOnOffID, Semaphore>();
foreach (SensorOnOffID o in Enum.GetValues(typeof(SensorOnOffID)))
_lockSensorOnOff.Add(o, new Semaphore(0, int.MaxValue));
_lockSensorColor = new Dictionary<SensorColorID, Semaphore>();
foreach (SensorColorID o in Enum.GetValues(typeof(SensorColorID)))
_lockSensorColor.Add(o, new Semaphore(0, int.MaxValue));
_boardSensorColor = new Dictionary<SensorColorID, Board>();
_boardSensorColor.Add(SensorColorID.BuoyRight, Board.RecMove);
_boardSensorColor.Add(SensorColorID.BuoyLeft, Board.RecIO);
_boardSensorOnOff = new Dictionary<SensorOnOffID, Board>();
_boardSensorOnOff.Add(SensorOnOffID.StartTrigger, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorLeftBack, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorLeftFront, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorRightBack, Board.RecIO);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorRightFront, Board.RecIO);
_boardSensorOnOff.Add(SensorOnOffID.PresenceBuoyRight, Board.RecIO);
_boardActuatorOnOff = new Dictionary<ActuatorOnOffID, Board>();
_boardActuatorOnOff.Add(ActuatorOnOffID.PowerSensorColorBuoyRight, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumLeftBack, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumLeftFront, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumLeftBack, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumLeftFront, Board.RecIO);
_boardActuatorOnOff.Add(ActuatorOnOffID.PowerSensorColorBuoyLeft, Board.RecIO);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumRightBack, Board.RecIO);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumRightFront, Board.RecIO);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumRightBack, Board.RecIO);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumRightFront, Board.RecMove);
// Petit robot
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumLeft, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumRight, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.OpenVacuumBack, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumLeft, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumRight, Board.RecMove);
_boardActuatorOnOff.Add(ActuatorOnOffID.MakeVacuumBack, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorLeft, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorRight, Board.RecMove);
_boardSensorOnOff.Add(SensorOnOffID.PressureSensorBack, Board.RecMove);
_boardMotor = new Dictionary<MotorID, Board>();
_boardMotor.Add(MotorID.ElevatorLeft, Board.RecIO);
_boardMotor.Add(MotorID.ElevatorRight, Board.RecIO);
SpeedConfig.ParamChange += SpeedConfig_ParamChange;
}
public override void DeInit()
{
}
public override void ShowMessage(string message1, String message2)
{
Pepperl display = ((Pepperl)AllDevices.LidarAvoid);
display.ShowMessage(message1, message2);
display.SetFrequency(PepperlFreq.Hz50);
}
private void SpeedConfig_ParamChange(bool lineAccelChange, bool lineDecelChange, bool lineSpeedChange, bool pivotAccelChange, bool pivotDecelChange, bool pivotSpeedChange)
{
if (lineSpeedChange)
{
Frame frame = UdpFrameFactory.VitesseLigne(SpeedConfig.LineSpeed, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionVitesseLigne(this, SpeedConfig.LineSpeed));
}
if (lineAccelChange || lineDecelChange)
{
Frame frame = UdpFrameFactory.AccelLigne(SpeedConfig.LineAcceleration, SpeedConfig.LineDeceleration, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionAccelerationLigne(this, SpeedConfig.LineAcceleration, SpeedConfig.LineDeceleration));
}
if (pivotSpeedChange)
{
Frame frame = UdpFrameFactory.VitessePivot(SpeedConfig.PivotSpeed, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionVitessePivot(this, SpeedConfig.PivotSpeed));
}
if (pivotAccelChange || pivotDecelChange)
{
Frame frame = UdpFrameFactory.AccelPivot(SpeedConfig.PivotAcceleration, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionAccelerationPivot(this, SpeedConfig.PivotAcceleration, SpeedConfig.PivotDeceleration));
}
}
private void SetStartTrigger(bool state)
{
if (!state && StartTriggerEnable)
{
StartTriggerEnable = false;
if (GameBoard.Strategy == null)
{
if (Config.CurrentConfig.IsMiniRobot)
GameBoard.Strategy = new StrategyMini();
else
GameBoard.Strategy = new StrategyMatch();
}
GameBoard.Strategy.ExecuteMatch();
}
}
public override void Init()
{
Historique = new Historique(IDRobot);
Connections.ConnectionCan.FrameReceived += ReceptionCanMessage;
_asserConnection.FrameReceived += ReceptionUdpMessage;
if (this == Robots.MainRobot)
Connections.ConnectionIO.FrameReceived += ReceptionUdpMessage;
//Connections.ConnectionsCan[CanBoard.CanAlim].FrameReceived += ReceptionCanMessage;
if (this == Robots.MainRobot)
{
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
Position = new Position(0, new RealPoint(240, 1000));
else
Position = new Position(180, new RealPoint(3000 - 240, 1000));
}
else
{
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
Position = new Position(0, new RealPoint(480, 1000));
else
Position = new Position(180, new RealPoint(3000 - 480, 1000));
}
PositionTarget = null; //TODO2018 Init commun à la simu
PositionsHistorical = new List<Position>();
_asserConnection.SendMessage(UdpFrameFactory.DemandePositionContinue(50, this));
}
public override Color ReadSensorColor(SensorColorID sensor, bool wait = true)
{
if (wait) _lockSensorColor[sensor] = new Semaphore(0, int.MaxValue);
Frame t = UdpFrameFactory.DemandeCapteurCouleur(_boardSensorColor[sensor], sensor);
Connections.UDPBoardConnection[_boardSensorColor[sensor]].SendMessage(t);
if (wait) _lockSensorColor[sensor].WaitOne(100);
return SensorsColorValue[sensor];
}
public override bool ReadSensorOnOff(SensorOnOffID sensor, bool wait = true)
{
if (wait) _lockSensorOnOff[sensor] = new Semaphore(0, int.MaxValue);
Frame t = UdpFrameFactory.DemandeCapteurOnOff(_boardSensorOnOff[sensor], sensor);
Connections.UDPBoardConnection[_boardSensorOnOff[sensor]].SendMessage(t);
if (wait) _lockSensorOnOff[sensor].WaitOne(100);
return SensorsOnOffValue[sensor];
}
public void AsyncAsserEnable(ThreadLink link)
{
link.RegisterName();
//TODO2020AllDevices.RecGoBot.Buzz(7000, 200);
Thread.Sleep(500);
TrajectoryFailed = true;
Stop(StopMode.Abrupt);
_lockFrame[UdpFrameFunction.FinDeplacement]?.Release();
//TODO2020AllDevices.RecGoBot.Buzz(0, 200);
}
public void ReceptionCanMessage(Frame frame)
{
switch (CanFrameFactory.ExtractFunction(frame))
{
case CanFrameFunction.BatterieVoltage:
BatterieVoltage = (frame[3] * 256 + frame[4]) / 1000f;
BatterieIntensity = (frame[5] * 256 + frame[6]) / 1000f;
break;
}
}
public void ReceptionUdpMessage(Frame frame)
{
// Analyser la trame reçue
//Console.WriteLine(trameRecue.ToString());
switch ((UdpFrameFunction)frame[1])
{
case UdpFrameFunction.RetourTension:
//BatterieVoltage = (frame[2] * 256 + frame[3]) / 100f;
break;
case UdpFrameFunction.MoteurFin:
_lockMotor[(MotorID)frame[2]]?.Release();
break;
case UdpFrameFunction.MoteurBlocage: // Idem avec bip
_lockMotor[(MotorID)frame[2]]?.Release();
//TODO2020AllDevices.RecGoBot.Buzz("..");
break;
case UdpFrameFunction.Blocage:
ThreadManager.CreateThread(AsyncAsserEnable).StartThread();
break;
case UdpFrameFunction.FinDeplacement:
case UdpFrameFunction.FinRecallage: // Idem
Thread.Sleep(40); // TODO2018 ceci est une tempo ajoutée au pif de pwet parce qu'on avant envie alors voilà
IsInLineMove = false;
_lockFrame[UdpFrameFunction.FinDeplacement]?.Release();
break;
case UdpFrameFunction.AsserRetourPositionXYTeta:
// Réception de la position mesurée par l'asservissement
try
{
double y = (double)((short)(frame[2] << 8 | frame[3]) / 10.0);
double x = (double)((short)(frame[4] << 8 | frame[5]) / 10.0);
double teta = (frame[6] << 8 | frame[7]) / 100.0 - 180;
teta = (-teta);
y = -y;
x = -x;
Position nouvellePosition = new Position(teta, new RealPoint(x, y));
if (Position.Coordinates.Distance(nouvellePosition.Coordinates) < 300 || !_positionReceived)
{
// On reçoit la position du robot
// On la prend si elle est pas très éloignée de la position précédente ou si je n'ai jamais reçu de position
Position = nouvellePosition;
}
else
{
// On pense avoir une meilleure position à lui redonner parce que la position reçue est loin de celle qu'on connait alors qu'on l'avait reçue du robot
SetAsservOffset(Position);
}
_positionReceived = true;
_lockFrame[UdpFrameFunction.AsserDemandePositionXYTeta]?.Release();
lock (PositionsHistorical)
{
PositionsHistorical.Add(new Position(teta, new RealPoint(x, y)));
while (PositionsHistorical.Count > 1200)
PositionsHistorical.RemoveAt(0);
}
OnPositionChanged(Position);
}
catch (Exception)
{
Console.WriteLine("Erreur dans le retour de position asservissement.");
}
break;
case UdpFrameFunction.AsserRetourPositionCodeurs:
int nbPositions = frame[2];
for (int i = 0; i < nbPositions; i++)
{
// TODO2018 peut mieux faire, décaller les bits
int gauche1 = frame[3 + i * 8];
int gauche2 = frame[4 + i * 8];
int gauche3 = frame[5 + i * 8];
int gauche4 = frame[6 + i * 8];
int codeurGauche = gauche1 * 256 * 256 * 256 + gauche2 * 256 * 256 + gauche3 * 256 + gauche4;
int droite1 = frame[7 + i * 8];
int droite2 = frame[8 + i * 8];
int droite3 = frame[9 + i * 8];
int droite4 = frame[10 + i * 8];
int codeurDroit = droite1 * 256 * 256 * 256 + droite2 * 256 * 256 + droite3 * 256 + droite4;
_lastPidTest[0].Add(codeurGauche);
_lastPidTest[1].Add(codeurDroit);
}
break;
case UdpFrameFunction.RetourChargeCPU_PWM:
int valsCount = frame[2];
for (int i = 0; i < valsCount; i++)
{
double cpuLoad = (frame[3 + i * 6] * 256 + frame[4 + i * 6]) / 5000.0;
double pwmLeft = frame[5 + i * 6] * 256 + frame[6 + i * 6] - 4000;
double pwmRight = frame[7 + i * 6] * 256 + frame[8 + i * 6] - 4000;
_lastRecMoveLoad.Add(cpuLoad);
_lastPwmLeft.Add(pwmLeft);
_lastPwmRight.Add(pwmRight);
}
break;
case UdpFrameFunction.RetourCapteurCouleur:
//TODO2018 : multiplier par 2 pour obtenir de belles couleurs ?
SensorColorID sensorColor = (SensorColorID)frame[2];
Color newColor = Color.FromArgb(Math.Min(255, frame[3] * 1), Math.Min(255, frame[4] * 1), Math.Min(255, frame[5] * 1));
if (newColor != SensorsColorValue[sensorColor])
OnSensorColorChanged(sensorColor, newColor);
_lockSensorColor[(SensorColorID)frame[2]]?.Release();
break;
case UdpFrameFunction.RetourCapteurOnOff:
SensorOnOffID sensorOnOff = (SensorOnOffID)frame[2];
bool newState = frame[3] > 0 ? true : false;
if (sensorOnOff == SensorOnOffID.StartTrigger)
SetStartTrigger(newState);
if (sensorOnOff == SensorOnOffID.PresenceBuoyRight && newState && Actionneur.ElevatorRight.Armed)
{
Actionneur.ElevatorRight.Armed = false;
Actionneur.ElevatorRight.DoSequencePickupColorThread(Buoy.Red);
}
if (newState != SensorsOnOffValue[sensorOnOff])
OnSensorOnOffChanged(sensorOnOff, newState);
_lockSensorOnOff[sensorOnOff]?.Release();
break;
case UdpFrameFunction.RetourValeursNumeriques:
Board numericBoard = (Board)frame[0];
lock (NumericPinsValue)
{
NumericPinsValue[numericBoard][0] = (Byte)frame[2];
NumericPinsValue[numericBoard][1] = (Byte)frame[3];
NumericPinsValue[numericBoard][2] = (Byte)frame[4];
NumericPinsValue[numericBoard][3] = (Byte)frame[5];
NumericPinsValue[numericBoard][4] = (Byte)frame[6];
NumericPinsValue[numericBoard][5] = (Byte)frame[7];
}
_lockFrame[UdpFrameFunction.RetourValeursNumeriques]?.Release();
break;
case UdpFrameFunction.RetourValeursAnalogiques:
Board analogBoard = (Board)frame[0];
const double toVolts = 0.0008056640625;
List<double> values = new List<double>();
AnalogicPinsValue[analogBoard][0] = ((frame[2] * 256 + frame[3]) * toVolts);
AnalogicPinsValue[analogBoard][1] = ((frame[4] * 256 + frame[5]) * toVolts);
AnalogicPinsValue[analogBoard][2] = ((frame[6] * 256 + frame[7]) * toVolts);
AnalogicPinsValue[analogBoard][3] = ((frame[8] * 256 + frame[9]) * toVolts);
AnalogicPinsValue[analogBoard][4] = ((frame[10] * 256 + frame[11]) * toVolts);
AnalogicPinsValue[analogBoard][5] = ((frame[12] * 256 + frame[13]) * toVolts);
AnalogicPinsValue[analogBoard][6] = ((frame[14] * 256 + frame[15]) * toVolts);
AnalogicPinsValue[analogBoard][7] = ((frame[16] * 256 + frame[17]) * toVolts);
AnalogicPinsValue[analogBoard][8] = ((frame[18] * 256 + frame[19]) * toVolts);
_lockFrame[UdpFrameFunction.RetourValeursAnalogiques]?.Release();
break;
case UdpFrameFunction.ReponseLidar:
int lidarID = frame[2];
if (_lastLidarMeasure == null)
_lastLidarMeasure = "";
string mess = "";
int decallageEntete = 3;
if (_lastLidarMeasure.Length == 0)
{
// C'est le début de la trame à recomposer, et au début y'a la position de la prise de mesure à lire !
double y = (double)((short)(frame[3] << 8 | frame[4]) / 10.0);
double x = (double)((short)(frame[5] << 8 | frame[6]) / 10.0);
double teta = (frame[7] << 8 | frame[8]) / 100.0 - 180;
_lastLidarPosition = new Position(-teta, new RealPoint(-x, -y));
decallageEntete += 6;
}
for (int i = decallageEntete; i < frame.Length; i++)
{
_lastLidarMeasure += (char)frame[i];
mess += (char)frame[i];
}
if (Regex.Matches(_lastLidarMeasure, "\n\n").Count == 2)
{
_lockFrame[UdpFrameFunction.ReponseLidar]?.Release();
}
break;
case UdpFrameFunction.RetourCouleurEquipe:
GameBoard.MyColor = frame[2] == 0 ? GameBoard.ColorLeftBlue : GameBoard.ColorRightYellow;
if (Config.CurrentConfig.IsMiniRobot) StartTriggerEnable = true;
break;
}
}
#region Déplacements
public override void SetAsservOffset(Position newPosition)
{
Position.Copy(newPosition);
newPosition.Angle = -newPosition.Angle; // Repère angulaire du robot inversé
Frame frame = UdpFrameFactory.OffsetPos(newPosition, this);
_asserConnection.SendMessage(frame);
OnPositionChanged(Position);
}
public override void MoveForward(int distance, bool wait = true)
{
//TODO2018 : FOnction de déplacement communes avec Simu sur l'historique etc, à voir, le recallage de Simu se fait en avancant...
base.MoveForward(distance, wait);
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
IsInLineMove = true;
Frame frame;
if (distance < 0)
frame = UdpFrameFactory.Deplacer(SensAR.Arriere, -distance, this);
else
frame = UdpFrameFactory.Deplacer(SensAR.Avant, distance, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionAvance(this, distance));
if (wait)
{
//if (!SemaphoresTrame[FrameFunction.FinDeplacement].WaitOne((int)SpeedConfig.LineDuration(distance).TotalMilliseconds))
// Thread.Sleep(1000); // Tempo de secours, on a jamais reçu la fin de trajectoire après la fin du délai théorique
_lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
}
public override void MoveBackward(int distance, bool wait = true)
{
base.MoveBackward(distance, wait);
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
IsInLineMove = true;
Frame frame;
if (distance < 0)
frame = UdpFrameFactory.Deplacer(SensAR.Avant, -distance, this);
else
frame = UdpFrameFactory.Deplacer(SensAR.Arriere, distance, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionRecule(this, distance));
if (wait)
{
//if (!SemaphoresTrame[FrameFunction.FinDeplacement].WaitOne((int)SpeedConfig.LineDuration(distance).TotalMilliseconds))
// Thread.Sleep(1000); // Tempo de secours, on a jamais reçu la fin de trajectoire après la fin du délai théorique
_lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
}
public override void PivotLeft(AngleDelta angle, bool wait = true)
{
base.PivotLeft(angle, wait);
angle = Math.Round(angle, 2);
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.Pivot(SensGD.Gauche, angle, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionPivot(this, angle, SensGD.Gauche));
if (wait)
{
//if (!SemaphoresTrame[FrameFunction.FinDeplacement].WaitOne((int)SpeedConfig.PivotDuration(angle, Entraxe).TotalMilliseconds))
// Thread.Sleep(1000); // Tempo de secours, on a jamais reçu la fin de trajectoire après la fin du délai théorique
_lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
}
public override void PivotRight(AngleDelta angle, bool wait = true)
{
base.PivotRight(angle, wait);
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.Pivot(SensGD.Droite, angle, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionPivot(this, angle, SensGD.Droite));
if (wait)
{
//if (!SemaphoresTrame[FrameFunction.FinDeplacement].WaitOne((int)SpeedConfig.PivotDuration(angle, Entraxe).TotalMilliseconds))
// Thread.Sleep(1000); // Tempo de secours, on a jamais reçu la fin de trajectoire après la fin du délai théorique
_lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
}
public override void Stop(StopMode mode = StopMode.Smooth)
{
AsserEnable = (mode != StopMode.Freely);
IsInLineMove = false;
Frame frame = UdpFrameFactory.Stop(mode, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionStop(this, mode));
}
public override void Turn(SensAR sensAr, SensGD sensGd, int radius, AngleDelta angle, bool wait = true)
{
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.Virage(sensAr, sensGd, radius, angle, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionVirage(this, radius, angle, sensAr, sensGd));
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
public override void PolarTrajectory(SensAR sens, List<RealPoint> points, bool wait = true)
{
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.TrajectoirePolaire(sens, points, this);
_asserConnection.SendMessage(frame);
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
}
public override void Recalibration(SensAR sens, bool wait = true, bool sendOffset = false)
{
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.Recallage(sens, this);
_asserConnection.SendMessage(frame);
Historique.AjouterAction(new ActionRecallage(this, sens));
if (wait) _lockFrame[UdpFrameFunction.FinDeplacement].WaitOne();
base.Recalibration(sens, wait, sendOffset);
}
#endregion
public override void SendPID(int p, int i, int d)
{
Frame frame = UdpFrameFactory.CoeffAsserv(p, i, d, this);
_asserConnection.SendMessage(frame);
}
public override void SendPIDCap(int p, int i, int d)
{
Frame frame = UdpFrameFactory.CoeffAsservCap(p, i, d, this);
_asserConnection.SendMessage(frame);
}
public override void SendPIDSpeed(int p, int i, int d)
{
Frame frame = UdpFrameFactory.CoeffAsservVitesse(p, i, d, this);
_asserConnection.SendMessage(frame);
}
public Position ReadPosition()
{
_lockFrame[UdpFrameFunction.AsserRetourPositionCodeurs] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.DemandePosition(this);
_asserConnection.SendMessage(frame);
_lockFrame[UdpFrameFunction.AsserRetourPositionXYTeta].WaitOne(100);
return Position;
}
public override void ReadAnalogicPins(Board board, bool wait = true)
{
if (wait) _lockFrame[UdpFrameFunction.RetourValeursAnalogiques] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.DemandeValeursAnalogiques(board);
Connections.UDPBoardConnection[board].SendMessage(frame);
if (wait) _lockFrame[UdpFrameFunction.RetourValeursAnalogiques].WaitOne(100);
}
public override void ReadNumericPins(Board board, bool wait = true)
{
if (wait) _lockFrame[UdpFrameFunction.RetourValeursNumeriques] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.DemandeValeursNumeriques(board);
Connections.UDPBoardConnection[board].SendMessage(frame);
if (wait) _lockFrame[UdpFrameFunction.RetourValeursNumeriques].WaitOne(100);
}
public override void SetActuatorOnOffValue(ActuatorOnOffID actuator, bool on)
{
ActuatorOnOffState[actuator] = on;
Frame frame = UdpFrameFactory.ActionneurOnOff(_boardActuatorOnOff[actuator], actuator, on);
Connections.UDPBoardConnection[_boardActuatorOnOff[actuator]].SendMessage(frame);
Historique.AjouterAction(new ActionOnOff(this, actuator, on));
}
public override void SetMotorAtPosition(MotorID motor, int position, bool wait)
{
base.SetMotorAtPosition(motor, position);
if (wait) _lockMotor[motor] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.MoteurPosition(_boardMotor[motor], motor, position);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(frame);
if (wait) _lockMotor[motor].WaitOne(5000);
}
public override void MotorWaitEnd(MotorID motor)
{
base.MotorWaitEnd(motor);
_lockMotor[motor].WaitOne(5000);
}
public override void SetMotorAtOrigin(MotorID motor, bool wait)
{
base.SetMotorAtOrigin(motor);
if (wait) _lockMotor[motor] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.MoteurOrigin(_boardMotor[motor], motor);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(frame);
if (wait) _lockMotor[motor].WaitOne(30000);
}
public override void SetMotorSpeed(MotorID motor, SensGD sens, int speed)
{
base.SetMotorSpeed(motor, sens, speed);
Frame trame = UdpFrameFactory.MoteurVitesse(_boardMotor[motor], motor, sens, speed);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(trame);
}
public override void SetMotorReset(MotorID motor)
{
base.SetMotorReset(motor);
Frame trame = UdpFrameFactory.MoteurResetPosition(_boardMotor[motor], motor);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(trame);
}
public override void SetMotorStop(MotorID motor, StopMode mode)
{
base.SetMotorStop(motor, mode);
Frame trame = UdpFrameFactory.MoteurStop(_boardMotor[motor], motor, mode);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(trame);
}
public override void SetMotorAcceleration(MotorID motor, int acceleration)
{
base.SetMotorAcceleration(motor, acceleration);
Frame trame = UdpFrameFactory.MoteurAcceleration(_boardMotor[motor], motor, acceleration);
Connections.UDPBoardConnection[_boardMotor[motor]].SendMessage(trame);
}
public override void EnablePower(bool on)
{
// TODOEACHYEAR : couper tout manuellement
Stop(StopMode.Freely);
}
public override bool ReadStartTrigger()
{
return ReadSensorOnOff(SensorOnOffID.StartTrigger, true);
}
public override List<int>[] DiagnosticPID(int steps, SensAR sens, int pointsCount)
{
_lastPidTest = new List<int>[2];
_lastPidTest[0] = new List<int>();
_lastPidTest[1] = new List<int>();
Frame frame = UdpFrameFactory.EnvoiConsigneBrute(steps, sens, this);
_asserConnection.SendMessage(frame);
frame = UdpFrameFactory.DemandePositionsCodeurs(this);
while (_lastPidTest[0].Count < pointsCount)
{
_asserConnection.SendMessage(frame);
Thread.Sleep(30);
}
List<int>[] output = new List<int>[2];
output[0] = _lastPidTest[0].GetRange(0, pointsCount);
output[1] = _lastPidTest[1].GetRange(0, pointsCount);
return output;
}
public override List<int>[] DiagnosticLine(int distance, SensAR sens)
{
_lastPidTest = new List<int>[2];
_lastPidTest[0] = new List<int>();
_lastPidTest[1] = new List<int>();
_lockFrame[UdpFrameFunction.FinDeplacement] = new Semaphore(0, int.MaxValue);
Frame frame = UdpFrameFactory.Deplacer(sens, distance, this);
_asserConnection.SendMessage(frame);
frame = UdpFrameFactory.DemandePositionsCodeurs(this);
while (!_lockFrame[UdpFrameFunction.FinDeplacement].WaitOne(0))
{
_asserConnection.SendMessage(frame);
Thread.Sleep(30);
}
List<int>[] output = new List<int>[2];
output[0] = new List<int>(_lastPidTest[0]);
output[1] = new List<int>(_lastPidTest[1]);
return output;
}
public override List<double>[] DiagnosticCpuPwm(int pointsCount)
{
_lastRecMoveLoad = new List<double>();
_lastPwmLeft = new List<double>();
_lastPwmRight = new List<double>();
Frame frame = UdpFrameFactory.DemandeCpuPwm(this);
while (_lastRecMoveLoad.Count <= pointsCount)
{
_asserConnection.SendMessage(frame);
Thread.Sleep(30);
}
// Supprime d'éventuelles valeurs supplémentaires
while (_lastRecMoveLoad.Count > pointsCount)
_lastRecMoveLoad.RemoveAt(_lastRecMoveLoad.Count - 1);
while (_lastPwmLeft.Count > pointsCount)
_lastPwmLeft.RemoveAt(_lastPwmLeft.Count - 1);
while (_lastPwmRight.Count > pointsCount)
_lastPwmRight.RemoveAt(_lastPwmRight.Count - 1);
return new List<double>[3] { _lastRecMoveLoad, _lastPwmLeft, _lastPwmRight };
}
public void EnvoyerUart(Board byBoard, Frame frame)
{
Frame frameUdp = UdpFrameFactory.EnvoyerUart1(byBoard, frame);
Connections.UDPBoardConnection[byBoard].SendMessage(frameUdp);
}
public override String ReadLidarMeasure(LidarID lidar, int timeout, out Position refPosition)
{
_lastLidarMeasure = "";
_lockFrame[UdpFrameFunction.ReponseLidar] = new Semaphore(0, int.MaxValue);
Connections.ConnectionMove.SendMessage(UdpFrameFactory.DemandeMesureLidar(lidar));
_lockFrame[UdpFrameFunction.ReponseLidar].WaitOne(timeout);
refPosition = _lastLidarPosition;
return _lastLidarMeasure;
}
}
}
<file_sep>/GoBot/GoBot/GameElements/AllGameElements.cs
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using GoBot.BoardContext;
using Geometry.Shapes;
using System.Drawing;
using Geometry;
using System;
namespace GoBot.GameElements
{
public class AllGameElements : IEnumerable<GameElement>
{
public delegate void ObstaclesChangedDelegate();
public event ObstaclesChangedDelegate ObstaclesChanged;
private List<Buoy> _buoys;
private List<GroundedZone> _groundedZones;
private List<RandomDropOff> _randomDropoff;
private List<ColorDropOff> _colorDropoff;
private List<LightHouse> _lightHouses;
private GameElementZone _randomPickup;
public AllGameElements()
{
// TODOEACHYEAR Ajouter ici tous les éléments dans les listes
_buoys = new List<Buoy>();
_buoys.Add(new Buoy(new RealPoint(-67, 1450), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(-67, 1525), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(-67, 1600), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(-67, 1675), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(-67, 1750), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 700, -67), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 775, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(3000 - 850, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(3000 - 925, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(3000 - 1000, -67), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(700, -67), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(775, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(850, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(925, -67), GameBoard.ColorLeftBlue, Color.LightGray));
_buoys.Add(new Buoy(new RealPoint(1000, -67), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3067, 1450), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3067, 1525), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3067, 1600), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3067, 1675), GameBoard.ColorLeftBlue, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3067, 1750), GameBoard.ColorLeftBlue, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(300, 400), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(300, 1200), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(450, 510), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(450, 1080), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(670, 100), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(950, 400), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(1100, 800), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(1270, 1200), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(1005, 1955), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(1065, 1650), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(1335, 1650), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(1395, 1955), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 300, 400), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 300, 1200), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 450, 510), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 450, 1080), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 670, 100), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 950, 400), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 1100, 800), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 1270, 1200), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 1005, 1955), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 1065, 1650), GameBoard.ColorNeutral, Buoy.Red));
_buoys.Add(new Buoy(new RealPoint(3000 - 1335, 1650), GameBoard.ColorNeutral, Buoy.Green));
_buoys.Add(new Buoy(new RealPoint(3000 - 1395, 1955), GameBoard.ColorNeutral, Buoy.Red));
_groundedZones = new List<GroundedZone>();
_groundedZones.Add(new GroundedZone(new RealPoint(-70, 1600), Color.White, _buoys.GetRange(0, 5)));
_groundedZones.Add(new GroundedZone(new RealPoint(3000 - 850, -70), Color.White, _buoys.GetRange(5, 5)));
_groundedZones.Add(new GroundedZone(new RealPoint(850, -70), Color.White, _buoys.GetRange(10, 5)));
_groundedZones.Add(new GroundedZone(new RealPoint(3000 + 70, 1600), Color.White, _buoys.GetRange(15, 5)));
_randomDropoff = new List<RandomDropOff>();
_randomDropoff.Add(new RandomDropOff(new RealPoint(200, 800), GameBoard.ColorLeftBlue));
_randomDropoff.Add(new RandomDropOff(new RealPoint(3000 - 200, 800), GameBoard.ColorRightYellow));
_colorDropoff = new List<ColorDropOff>();
_colorDropoff.Add(new ColorDropOff(new RealPoint(1200, 2000 - 150), GameBoard.ColorRightYellow,
_buoys.Find(b => b.Position.Distance(new RealPoint(1065, 1650)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(1335, 1650)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(1005, 1955)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(1395, 1955)) < 1)));
_colorDropoff.Add(new ColorDropOff(new RealPoint(1800, 2000 - 150), GameBoard.ColorLeftBlue,
_buoys.Find(b => b.Position.Distance(new RealPoint(3000 - 1065, 1650)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(3000 - 1335, 1650)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(3000 - 1005, 1955)) < 1),
_buoys.Find(b => b.Position.Distance(new RealPoint(3000 - 1395, 1955)) < 1)));
_lightHouses = new List<LightHouse>();
_lightHouses.Add(new LightHouse(new RealPoint(325, -122), GameBoard.ColorLeftBlue));
_lightHouses.Add(new LightHouse(new RealPoint(3000 - 325, -122), GameBoard.ColorRightYellow));
_randomPickup = new GameElementZone(new RealPoint(1500, 0), Color.White, 500);
GenerateRandomBuoys();
}
private void GenerateRandomBuoys()
{
Circle zone = new Circle(new RealPoint(1500, 0), 500);
List<Circle> randoms = new List<Circle>();
Random r = new Random();
for (int i = 0; i < 6; i++)
{
RealPoint random = new RealPoint(r.Next(1000, 1500) + (i < 3 ? 0 : 500), r.Next(36, 500-36));
Circle c = new Circle(random, 36);
if (zone.Contains(c) && !randoms.Exists(o => random.Distance(o) < 36+2))
{
_buoys.Add(new Buoy(random, Color.White, i % 2 == 0 ? Buoy.Green : Buoy.Red, true));
randoms.Add(c);
}
else
i -= 1;
}
}
public IEnumerable<GameElement> AllElements
{
get
{
IEnumerable<GameElement> elements = Enumerable.Empty<GameElement>();
// TODOEACHYEAR Concaténer ici les listes d'éléments
elements = elements.Concat(_buoys);
elements = elements.Concat(_groundedZones);
elements = elements.Concat(_randomDropoff);
elements = elements.Concat(_colorDropoff);
elements = elements.Concat(_lightHouses);
elements = elements.Concat(new List<GameElement>() { _randomPickup });
return elements;
}
}
public Buoy FindBuoy(RealPoint pos)
{
return _buoys.OrderBy(b => b.Position.Distance(pos)).First();
}
public void RemoveBuoy(Buoy b)
{
_buoys.Remove(b);
}
public List<Buoy> Buoys => _buoys;
public List<Buoy> BuoysForLeft => _buoys.Where(b => b.Position.X < 1800 && b.Position.Y < 1500 && !RandomPickup.Contains(b.Position)).ToList();
public List<Buoy> BuoysForRight => _buoys.Where(b => b.Position.X > 1200 && b.Position.Y < 1500 && !RandomPickup.Contains(b.Position)).ToList();
public List<GroundedZone> GroundedZones => _groundedZones;
public List<RandomDropOff> RandomDropoffs => _randomDropoff;
public List<ColorDropOff> ColorDropoffs => _colorDropoff;
public List<LightHouse> LightHouses => _lightHouses;
public GameElementZone RandomPickup => _randomPickup;
public IEnumerator<GameElement> GetEnumerator()
{
return AllElements.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return AllElements.GetEnumerator();
}
public IEnumerable<IShape> AsObstacles
{
get
{
List<IShape> obstacles = new List<IShape>();
if (GameBoard.Strategy != null && GameBoard.Strategy.AvoidElements)
{
// TODOEACHYEAR Ici ajouter à obstacles les elements à contourner
}
return obstacles;
}
}
public IEnumerable<IShape> AsVisibleObstacles
{
get
{
List<IShape> obstacles = new List<IShape>();
if (GameBoard.Strategy != null && GameBoard.Strategy.AvoidElements)
{
}
obstacles.AddRange(_buoys.Select(b => new Circle(b.Position, b.HoverRadius)));
return obstacles;
}
}
public void SetOpponents(List<RealPoint> positions)
{
// TODOEACHYEAR Mettre à jour ICI les éléments en fonction de la position des adversaires
int opponentRadius = 150;
//foreach (Buoy b in _buoys)
//{
// if (positions.Exists(p => p.Distance(b.Position) < opponentRadius))
// b.IsAvailable = false;
//}
}
}
}
<file_sep>/GoBot/GoBot/Communications/CAN/CanFrameFunction.cs
namespace GoBot.Communications.CAN
{
public enum CanFrameFunction
{
PositionAsk = 0x01,
PositionResponse = 0x02,
PositionSet = 0x03,
PositionMinAsk = 0x04,
PositionMinResponse = 0x05,
PositionMinSet = 0x06,
PositionMaxAsk = 0x07,
PositionMaxResponse = 0x08,
PositionMaxSet = 0x09,
SpeedMaxAsk = 0x0A,
SpeedMaxResponse = 0x0B,
SpeedMaxSet = 0x0C,
TorqueMaxAsk = 0x0D,
TorqueMaxResponse = 0x0E,
TorqueMaxSet = 0x0F,
TorqueCurrentAsk = 0x10,
TorqueCurrentResponse = 0x11,
AccelerationAsk = 0x12,
AccelerationResponse = 0x13,
AccelerationSet = 0x14,
TargetSet = 0x15,
TrajectorySet = 0x16,
DisableOutput = 0x17,
TorqueAlert = 0x18,
TestConnection = 0x19,
Debug = 0xF0,
DebugAsk = 0xF1,
DebugResponse = 0xF2,
Buffer = 0xF3, // TODO2020
BatterieVoltage = 0xF5,
Buzzer = 0xF6
}
public enum CanBoard
{
PC = 0x00,
CanServo1 = 0x01,
CanServo2 = 0x02,
CanServo3 = 0x03,
CanServo4 = 0x04,
CanServo5 = 0x05,
CanServo6 = 0x06,
CanAlim = 0x0A
}
}
<file_sep>/GoBot/GoBot/Logs/logFile.cs
using System;
using System.IO;
namespace GoBot.Logs
{
public class LogFile : ILog
{
private String FileName { get; set; }
private StreamWriter Writer { get; set; }
public LogFile(String fileName)
{
FileName = fileName;
if (!Directory.Exists(Path.GetDirectoryName(FileName))) Directory.CreateDirectory(Path.GetDirectoryName(FileName));
Writer = new StreamWriter(FileName);
Writer.AutoFlush = true;
}
public void Write(String message)
{
Writer.WriteLine(DateTime.Now.ToString("dd:MM:yyyy hh:mm:ss:ffff\t") + message);
}
public void Close()
{
Writer.Close();
}
}
}
<file_sep>/GoBot/GoBot/Devices/LidarSimu.cs
using Geometry;
using Geometry.Shapes;
using GoBot.BoardContext;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
namespace GoBot.Devices
{
class LidarSimu : Lidar
{
private List<double> _distances;
private Threading.ThreadLink _link;
private AngleDelta _scanRange;
private int _pointsCount;
private double _noise;
private Random _rand;
public override bool Activated => _link != null && _link.Running;
public LidarSimu() : base()
{
_distances = Enumerable.Repeat(1500d, 360 * 3).ToList();
_scanRange = 360;
_pointsCount = 360 * 3;
_noise = 5;
_rand = new Random();
}
public override AngleDelta DeadAngle => 0;
protected override bool StartLoop()
{
_link = Threading.ThreadManager.CreateThread(link => UpdateDetection());
_link.StartInfiniteLoop(50);
return true;
}
protected override void StopLoop()
{
_link.Cancel();
_link.WaitEnd();
_link = null;
}
protected void UpdateDetection()
{
//List<RealPoint> measures = ValuesToPositions(_distances, false, 50, 5000, _position);
List<RealPoint> measures = Detection(_position);
this.OnNewMeasure(measures);
Random r = new Random();
for (int i = 0; i < _distances.Count; i++)
_distances[i] = (_distances[(i - 1 + _distances.Count) % _distances.Count] + _distances[i] + _distances[(i + 1) % _distances.Count]) / 3 + r.NextDouble() * 3 - 1.5;
}
private List<RealPoint> ValuesToPositions(List<double> measures, bool limitOnTable, int minDistance, int maxDistance, Position refPosition)
{
List<RealPoint> positions = new List<RealPoint>();
AngleDelta resolution = _scanRange / _pointsCount;
for (int i = 0; i < measures.Count; i++)
{
AnglePosition angle = resolution * i;
if (measures[i] > minDistance && (measures[i] < maxDistance || maxDistance == -1))
{
AnglePosition anglePoint = new AnglePosition(angle.InPositiveRadians - refPosition.Angle.InPositiveRadians - _scanRange.InRadians / 2 - Math.PI / 2, AngleType.Radian);
RealPoint pos = new RealPoint(refPosition.Coordinates.X - anglePoint.Sin * measures[i], refPosition.Coordinates.Y - anglePoint.Cos * measures[i]);
int marge = 20; // Marge en mm de distance de detection à l'exterieur de la table (pour ne pas jeter les mesures de la bordure qui ne collent pas parfaitement)
if (!limitOnTable || (pos.X > -marge && pos.X < GameBoard.Width + marge && pos.Y > -marge && pos.Y < GameBoard.Height + marge))
positions.Add(pos);
}
}
return positions;
}
public override List<RealPoint> GetPoints()
{
return Detection(_position);
}
private List<RealPoint> Detection(Position refPosition)
{
List<RealPoint> positions = new List<RealPoint>();
AngleDelta resolution = _scanRange / _pointsCount;
int dist = 10000;
List<IShape> obstacles = new List<IShape>();
obstacles.AddRange(GameBoard.ObstaclesLidarGround);
for (int i = 0; i < _pointsCount; i++)
{
AnglePosition angle = resolution * i;
AnglePosition anglePoint = new AnglePosition(angle.InPositiveRadians - refPosition.Angle.InPositiveRadians - _scanRange.InRadians / 2 - Math.PI / 2, AngleType.Radian);
RealPoint pos = new RealPoint(refPosition.Coordinates.X - anglePoint.Sin * dist, refPosition.Coordinates.Y - anglePoint.Cos * dist);
positions.Add(GetDetectionLinePoint(new Segment(refPosition.Coordinates, pos), obstacles));
}
return positions;
}
private RealPoint GetDetectionLinePoint(Segment seg, IEnumerable<IShape> obstacles)
{
RealPoint closest = null;
double minDistance = double.MaxValue;
foreach (IShape s in obstacles)
{
List<RealPoint> pts = s.GetCrossingPoints(seg);
foreach (RealPoint p in pts)
{
double newDistance = seg.StartPoint.Distance(p);
if (newDistance < minDistance)
{
minDistance = newDistance;
closest = p;
}
}
}
Direction d = Maths.GetDirection(seg.StartPoint, closest);
d.distance += (_rand.NextDouble() * _noise * 2 - _noise);
closest = Maths.GetDestination(seg.StartPoint, d);
return closest;
}
}
}
<file_sep>/GoBot/Geometry/BezierCurve.cs
using System;
using System.Collections.Generic;
using Geometry.Shapes;
namespace Geometry
{
public class BezierCurve
{
private static double[] _factorial;
/// <summary>
/// Retourne une liste de points correspondant à une courbe de Bézier suivant des points donnés en entrée
/// </summary>
/// <param name="points">Points à suivre pour créer la courbe de Bézier</param>
/// <param name="pointsCnt">Nombre de points à générer</param>
/// <returns>Liste de points suivant la courbe de Bezier générée</returns>
public static List<RealPoint> GetPoints(List<RealPoint> points, int pointsCnt)
{
List<RealPoint> pts = new List<RealPoint>();
double[] ptsIn = new double[points.Count * 2];
double[] ptsOut = new double[pointsCnt * 2];
for (int i = 0; i < points.Count; i++)
{
ptsIn[i * 2] = points[i].X;
ptsIn[i * 2 + 1] = points[i].Y;
}
Bezier2D(ptsIn, pointsCnt, ptsOut);
for (int i = 0; i < pointsCnt * 2; i += 2)
{
pts.Add(new RealPoint(ptsOut[i], ptsOut[i + 1]));
}
return pts;
}
private static double factorial(int n)
{
if (_factorial is null)
CreateFactorialTable();
// Just check if n is appropriate, then return the result
if (n < 0) { throw new Exception("n is less than 0"); }
if (n > 32) { throw new Exception("n is greater than 32"); }
return _factorial[n]; /* returns the value n! as a SUMORealing point number */
}
private static void CreateFactorialTable()
{
// Create lookup table for fast factorial calculation
// Fill untill n=32. The rest is too high to represent
_factorial = new double[33];
_factorial[0] = 1.0;
_factorial[1] = 1.0;
_factorial[2] = 2.0;
_factorial[3] = 6.0;
_factorial[4] = 24.0;
_factorial[5] = 120.0;
_factorial[6] = 720.0;
_factorial[7] = 5040.0;
_factorial[8] = 40320.0;
_factorial[9] = 362880.0;
_factorial[10] = 3628800.0;
_factorial[11] = 39916800.0;
_factorial[12] = 479001600.0;
_factorial[13] = 6227020800.0;
_factorial[14] = 87178291200.0;
_factorial[15] = 1307674368000.0;
_factorial[16] = 20922789888000.0;
_factorial[17] = 355687428096000.0;
_factorial[18] = 6402373705728000.0;
_factorial[19] = 121645100408832000.0;
_factorial[20] = 2432902008176640000.0;
_factorial[21] = 51090942171709440000.0;
_factorial[22] = 1124000727777607680000.0;
_factorial[23] = 25852016738884976640000.0;
_factorial[24] = 620448401733239439360000.0;
_factorial[25] = 15511210043330985984000000.0;
_factorial[26] = 403291461126605635584000000.0;
_factorial[27] = 10888869450418352160768000000.0;
_factorial[28] = 304888344611713860501504000000.0;
_factorial[29] = 8841761993739701954543616000000.0;
_factorial[30] = 265252859812191058636308480000000.0;
_factorial[31] = 8222838654177922817725562880000000.0;
_factorial[32] = 263130836933693530167218012160000000.0;
}
private static double Ni(int n, int i)
{
double ni;
double a1 = factorial(n);
double a2 = factorial(i);
double a3 = factorial(n - i);
ni = a1 / (a2 * a3);
return ni;
}
private static double Bernstein(int n, int i, double t)
{
// Calculate Bernstein basis
double basis;
double ti; /* t^i */
double tni; /* (1 - t)^i */
/* Prevent problems with pow */
if (t == 0.0 && i == 0)
ti = 1.0;
else
ti = Math.Pow(t, i);
if (n == i && t == 1.0)
tni = 1.0;
else
tni = Math.Pow((1 - t), (n - i));
//Bernstein basis
basis = Ni(n, i) * ti * tni;
return basis;
}
private static void Bezier2D(double[] b, int cpts, double[] p)
{
int npts = (b.Length) / 2;
int icount, jcount;
double step, t;
// Calculate points on curve
icount = 0;
t = 0;
step = (double)1.0 / (cpts - 1);
for (int i1 = 0; i1 != cpts; i1++)
{
if ((1.0 - t) < 5e-6)
t = 1.0;
jcount = 0;
p[icount] = 0.0;
p[icount + 1] = 0.0;
for (int i = 0; i != npts; i++)
{
double basis = Bernstein(npts - 1, i, t);
p[icount] += basis * b[jcount];
p[icount + 1] += basis * b[jcount + 1];
jcount = jcount + 2;
}
icount += 2;
t += step;
}
}
}
}
<file_sep>/GoBot/GoBot/GameElements/Buoy.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Geometry;
using Geometry.Shapes;
namespace GoBot.GameElements
{
public class Buoy : GameElement
{
public static Color Red = Color.FromArgb(187, 30, 16);
public static Color Green = Color.FromArgb(0, 111, 61);
private Color _color;
private bool _virtual;
public Buoy(RealPoint position, Color owner, Color color, bool isVirtual = false) : base(position, owner, 36)
{
_color = color;
_virtual = isVirtual;
}
public Color Color => _color;
public bool IsVirtual => _virtual;
public override void Paint(Graphics g, WorldScale scale)
{
if (_isAvailable)
{
Circle c = new Circle(_position, _hoverRadius);
c.Paint(g, _isHover ? Color.White : Color.Black, 1, _color, scale);
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PagePepperl.cs
using System;
using System.Windows.Forms;
using System.Threading;
using GoBot.Devices;
namespace GoBot.IHM.Pages
{
public partial class PagePepperl : UserControl
{
Pepperl _lidar;
private void btnText_Click(object sender, EventArgs e)
{
_lidar.ShowMessage(txtText1.Text, txtText2.Text);
}
public PagePepperl()
{
InitializeComponent();
}
private void PagePepperl_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
_lidar = (Pepperl)AllDevices.LidarAvoid;
foreach (PepperlFreq f in Enum.GetValues(typeof(PepperlFreq)))
cboFreq.Items.Add(f);
foreach (PepperlFilter f in Enum.GetValues(typeof(PepperlFilter)))
cboFilter.Items.Add(f);
UpdateInfos();
}
}
private void btnReboot_Click(object sender, EventArgs e)
{
_lidar.Reboot();
}
private void cboFreq_SelectedValueChanged(object sender, EventArgs e)
{
PepperlFreq value = (PepperlFreq)cboFreq.SelectedItem;
if (_lidar.Frequency != value)
{
_lidar.SetFrequency(value);
UpdateInfos();
}
}
private void numFilter_ValueChanged(object sender, EventArgs e)
{
int value = (int)numFilter.Value;
if (_lidar.FilterWidth != value)
{
_lidar.SetFilter(_lidar.Filter, value);
UpdateInfos();
}
}
private void cboFilter_SelectedValueChanged(object sender, EventArgs e)
{
PepperlFilter value = (PepperlFilter)cboFilter.SelectedItem;
if (_lidar.Filter != value)
{
_lidar.SetFilter(value, _lidar.FilterWidth);
UpdateInfos();
}
}
private void UpdateInfos()
{
cboFilter.SelectedItem = _lidar.Filter;
cboFreq.SelectedItem = _lidar.Frequency;
lblPoints.Text = _lidar.PointsPerScan.ToString();
lblResolution.Text = _lidar.Resolution.ToString();
lblDistPoints.Text = _lidar.PointsDistanceAt(3000).ToString("0.0") + " mm";
numFilter.Visible = (_lidar.Filter != PepperlFilter.None);
lblFilterPoints.Visible = numFilter.Visible;
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementRandomDropoff.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
namespace GoBot.Movements
{
class MovementRandomDropoff : Movement
{
private RandomDropOff _dropoff;
public override bool CanExecute => Actionneur.Lifter.Loaded;
public override int Score => 5;
public override double Value => 3;
public override GameElement Element => _dropoff;
public override Robot Robot => Robots.MainRobot;
public override Color Color => _dropoff.Owner;
public MovementRandomDropoff(RandomDropOff dropoff)
{
_dropoff = dropoff;
Positions.Add(new Position(0, new RealPoint(_dropoff.Position.X + 300 + 40, _dropoff.Position.Y)));
Positions.Add(new Position(180, new RealPoint(_dropoff.Position.X - 300 - 40, _dropoff.Position.Y)));
}
protected override void MovementBegin()
{
// rien
}
protected override bool MovementCore()
{
Robots.MainRobot.SetSpeedSlow();
Stopwatch sw = Stopwatch.StartNew();
Actionneur.Lifter.DoTilterPositionDropoff();
Robots.MainRobot.Move(-(270 - 85 * _dropoff.LoadsCount));
int waitMs = 500 - (int)sw.ElapsedMilliseconds;
if (waitMs > 0) Thread.Sleep(waitMs);
Actionneur.Lifter.DoOpenAll();
Thread.Sleep(100);
Actionneur.Lifter.DoTilterPositionStore();
_dropoff.AddLoad(Actionneur.Lifter.Load);
Actionneur.Lifter.Load = null;
Thread.Sleep(150);
Actionneur.Lifter.DoStoreAll();
Robots.MainRobot.Move(200);
Robots.MainRobot.SetSpeedFast();
Actionneur.Lifter.DoDisableAll();
return true;
}
protected override void MovementEnd()
{
// rien
}
}
}
<file_sep>/GoBot/GoBot/Devices/Lidar.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Communications;
using System.Collections.Generic;
namespace GoBot.Devices
{
public abstract class Lidar
{
private TicksPerSecond _measuresTicker;
protected Position _position;
protected bool _started;
protected ConnectionChecker _checker;
public delegate void NewMeasureHandler(List<RealPoint> measure);
public delegate void FrequencyChangeHandler(double value);
public event NewMeasureHandler NewMeasure;
public event FrequencyChangeHandler FrequencyChange;
public Lidar()
{
_measuresTicker = new TicksPerSecond();
_measuresTicker.ValueChange += OnFrequencyChange;
_position = new Position();
_started = false;
_checker = new ConnectionChecker(null);
_checker.Start();
}
public Position Position { get { return _position; } set { _position = new Position(value); } }
public abstract AngleDelta DeadAngle { get; }
public ConnectionChecker ConnectionChecker { get { return _checker; } }
public abstract bool Activated { get; }
public void StartLoopMeasure()
{
if (!_started)
{
_measuresTicker.Start();
_started = true;
StartLoop();
}
}
public void StopLoopMeasure()
{
if (_started)
{
_measuresTicker.Stop();
_started = false;
StopLoop();
}
}
protected abstract bool StartLoop();
protected abstract void StopLoop();
public abstract List<RealPoint> GetPoints();
protected void OnNewMeasure(List<RealPoint> measure)
{
_measuresTicker.AddTick();
_checker.NotifyAlive();
NewMeasure?.Invoke(measure);
}
protected void OnFrequencyChange(double freq)
{
FrequencyChange?.Invoke(freq);
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyMini.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using GoBot.Movements;
using GoBot.BoardContext;
using Geometry;
using Geometry.Shapes;
namespace GoBot.Strategies
{
class StrategyMini : Strategy
{
public override bool AvoidElements => true;
protected override void SequenceBegin()
{
Robots.MainRobot.UpdateGraph(GameBoard.ObstaclesAll);
// Sortir de la zonde de départ dès le début sans détection
Robots.MainRobot.MoveForward(500);
Position positionCale = new Position(50, new RealPoint(1800, 1800));
Position positionInit = new Position(0, new RealPoint(500, 500));
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
{
int tries = 0;
bool succeed = false;
do
{
tries++;
succeed = Robots.MainRobot.GoToPosition(positionCale);
} while (!succeed && tries < 3 && Robots.MainRobot.TrajectoryCutOff);// On reessaie, maximum 3 fois si la trajectoire a échoué parce qu'on m'a coupé la route
if (succeed)
{
// Je suis dans la cale !
Robots.MainRobot.PivotLeft(360);
}
else
{
// On m'a empeché d'y aller, je vais ailleurs
succeed = Robots.MainRobot.GoToPosition(positionInit);
}
}
else
{
}
}
protected override void SequenceCore()
{
// Le petit robot ne fait plus rien après la séquence initiale
while (IsRunning)
{
Robots.MainRobot.Historique.Log("Aucune action à effectuer");
Thread.Sleep(500);
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/SegmentWithRealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class SegmentWithRealPoint
{
public static bool Contains(Segment containingSegment, RealPoint containedPoint)
{
// Vérifie que le point est situé sur la droite
if (!LineWithRealPoint.Contains((Line)containingSegment, containedPoint))
return false;
// Puis qu'il est entre les deux extrémités
if (containedPoint.X - RealPoint.PRECISION > Math.Max(containingSegment.StartPoint.X, containingSegment.EndPoint.X) ||
containedPoint.X + RealPoint.PRECISION < Math.Min(containingSegment.StartPoint.X, containingSegment.EndPoint.X) ||
containedPoint.Y - RealPoint.PRECISION > Math.Max(containingSegment.StartPoint.Y, containingSegment.EndPoint.Y) ||
containedPoint.Y + RealPoint.PRECISION < Math.Min(containingSegment.StartPoint.Y, containingSegment.EndPoint.Y))
return false;
return true;
}
public static bool Cross(Segment segment, RealPoint point)
{
return Contains(segment, point);
}
public static double Distance(Segment segment, RealPoint point)
{
// Le raisonnement est le même que pour la droite cf Droite.Distance
Line perpendicular = segment.GetPerpendicular(point);
List<RealPoint> cross = segment.GetCrossingPoints(perpendicular);
double distance;
// Seule différence : on teste si l'intersection appartient bien au segment, sinon on retourne la distance avec l'extrémité la plus proche
if (cross.Count > 0 && segment.Contains(cross[0]))
{
distance = point.Distance(cross[0]);
}
else
{
double distanceDebut = point.Distance(segment.StartPoint);
double distanceFin = point.Distance(segment.EndPoint);
distance = Math.Min(distanceDebut, distanceFin);
}
return distance;
}
public static List<RealPoint> GetCrossingPoints(Segment segment, RealPoint point)
{
List<RealPoint> output = new List<RealPoint>();
if (segment.Contains(point)) output.Add(new RealPoint(point));
return output;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/CircleWithSegment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class CircleWithSegment
{
public static bool Contains(Circle containingCircle, Segment containedSegment)
{
// Pour contenir un Segment il suffit de contenir ses 2 extremités
return containingCircle.Contains(containedSegment.StartPoint) && containingCircle.Contains(containedSegment.EndPoint);
}
public static double Distance(Circle circle, Segment segment)
{
// Distance jusqu'au centre du cercle - son rayon (si négatif c'est que ça croise, donc distance 0)
return Math.Max(0, segment.Distance(circle.Center) - circle.Radius);
}
public static bool Cross(Circle circle, Segment segment)
{
// Si un segment croise le cercle, c'est que le point de segment le plus proche du centre du cercle est éloigné d'une distance inférieure au rayon
return segment.Distance(circle.Center) <= circle.Radius && !circle.Contains(segment);
}
public static List<RealPoint> GetCrossingPoints(Circle circle, Segment segment)
{
// Equation du second degré
List<RealPoint> intersectsPoints = new List<RealPoint>();
double dx = segment.EndPoint.X - segment.StartPoint.X;
double dy = segment.EndPoint.Y - segment.StartPoint.Y;
double Ox = segment.StartPoint.X - circle.Center.X;
double Oy = segment.StartPoint.Y - circle.Center.Y;
double A = dx * dx + dy * dy;
double B = 2 * (dx * Ox + dy * Oy);
double C = Ox * Ox + Oy * Oy - circle.Radius * circle.Radius;
double delta = B * B - 4 * A * C;
if (delta < 0 + double.Epsilon && delta > 0 - double.Epsilon)
{
double t = -B / (2 * A);
if (t >= 0 && t <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t * dx, segment.StartPoint.Y + t * dy));
}
else if (delta > 0)
{
double t1 = ((-B - Math.Sqrt(delta)) / (2 * A));
double t2 = ((-B + Math.Sqrt(delta)) / (2 * A));
if (t1 >= 0 && t1 <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t1 * dx, segment.StartPoint.Y + t1 * dy));
if (t2 >= 0 && t2 <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t2 * dx, segment.StartPoint.Y + t2 * dy));
}
return intersectsPoints;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/RealPointWithPolygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class RealPointWithPolygon
{
public static bool Contains(RealPoint containingPoint, Polygon containedPolygon)
{
return containedPolygon.Points.TrueForAll(p => p == containingPoint);
}
public static bool Cross(RealPoint point, Polygon polygon)
{
return polygon.Sides.Exists(s => s.Cross(point));
}
public static double Distance(RealPoint point, Polygon polygon)
{
if (polygon is PolygonRectangle)
{
// Plus rapide que la méthode des polygones
RealPoint topLeft = polygon.Sides[0].StartPoint;
RealPoint topRight = polygon.Sides[1].StartPoint;
RealPoint bottomRight = polygon.Sides[2].StartPoint;
RealPoint bottomLeft = polygon.Sides[3].StartPoint;
double distance;
if (point.X < topLeft.X)
{
if (point.Y < topLeft.Y)
distance = point.Distance(topLeft);
else if (point.Y > bottomRight.Y)
distance = point.Distance(bottomLeft);
else
distance = topLeft.X - point.X;
}
else if (point.X > bottomRight.X)
{
if (point.Y < topLeft.Y)
distance = point.Distance(topRight);
else if (point.Y > bottomRight.Y)
distance = point.Distance(bottomRight);
else
distance = point.X - topRight.X;
}
else
{
if (point.Y < topLeft.Y)
distance = topLeft.Y - point.Y;
else if (point.Y > bottomRight.Y)
distance = point.Y - bottomLeft.Y;
else
distance = 0;
}
return distance;
}
// Distance jusqu'au segment le plus proche
double minDistance = double.MaxValue;
foreach (Segment s in polygon.Sides)
minDistance = Math.Min(s.Distance(point), minDistance);
return minDistance;
}
public static List<RealPoint> GetCrossingPoints(RealPoint point, Polygon polygon)
{
List<RealPoint> output = new List<RealPoint>();
if (Cross(point, polygon))
output.Add(new RealPoint(point));
return output;
}
}
}
<file_sep>/GoBot/GoBot/Communications/CAN/CanFrameDecoder.cs
using System;
using System.Collections.Generic;
namespace GoBot.Communications.CAN
{
static class CanFrameDecoder
{
public static String Decode(Frame trame)
{
return GetMessage(trame);
}
/// <summary>
/// Récupère le message explicite associé à une fonction du protocole.
/// Les paramètres sont signalés par des accolades indiquant la position dans la trame des octets correspondant à la valeur du paramètre.
/// Si les paramètres sont fournis, leur valeur remplacent les paramètres entre accolades.
/// </summary>
/// <param name="function"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static String GetMessage(CanFrameFunction function, List<uint> parameters = null)
{
String output = "";
switch (function)
{
case CanFrameFunction.PositionAsk:
output = "Demande de position servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.PositionResponse:
output = "Retour de position servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.PositionSet:
output = "Envoi de position servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.PositionMinAsk:
output = "Demande de position min servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.PositionMinResponse:
output = "Retour de position min servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.PositionMinSet:
output = "Envoi de position min servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.PositionMaxAsk:
output = "Demande de position max servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.PositionMaxResponse:
output = "Retour de position max servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.PositionMaxSet:
output = "Envoi de position max servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.SpeedMaxAsk:
output = "Demande de vitesse servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.SpeedMaxResponse:
output = "Retour de vitesse servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.SpeedMaxSet:
output = "Envoi de vitesse servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TorqueMaxAsk:
output = "Demande de couple max servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.TorqueMaxResponse:
output = "Retour de couple max servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TorqueMaxSet:
output = "Envoi de couple max servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TorqueCurrentAsk:
output = "Demande de couple actuel servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TorqueCurrentResponse:
output = "Retour de couple actuel servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.AccelerationAsk:
output = "Demande de l'acceleration servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.AccelerationResponse:
output = "Retour de l'acceleration servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.AccelerationSet:
output = "Envoi de l'acceleration servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TargetSet:
output = "Déplacement servo {ServoID} : {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.TrajectorySet:
output = "Déplacement servo {ServoID} : Pos = {4-5}; Vit = {6-7}; Accel = {8-9}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.DisableOutput:
output = "Disable servo {ServoID}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
}
break;
case CanFrameFunction.TorqueAlert:
output = "Alerte couple dépassé (1sec) {ServoID} : Couple = {4-5}";
if (parameters != null)
{
output = ReplaceParam(output, ((ServomoteurID)parameters[0]).ToString());
output = ReplaceParam(output, parameters[1].ToString());
}
break;
case CanFrameFunction.Debug:
output = "Debug";
break;
case CanFrameFunction.DebugAsk:
output = "Demande valeur debug";
break;
case CanFrameFunction.DebugResponse:
output = "Retour valeur debug";
break;
case CanFrameFunction.TestConnection:
output = "Test connexion";
break;
case CanFrameFunction.BatterieVoltage:
output = "Retour alimentation : {3-4}V {5-6}A";
if (parameters != null)
{
output = ReplaceParam(output, (parameters[0] / 1000.0).ToString("0.00"));
output = ReplaceParam(output, (parameters[1] / 1000.0).ToString("0.00"));
}
break;
case CanFrameFunction.Buzzer:
output = "Buzzer : {3-4}Hz {5-6}mS";
if (parameters != null)
{
output = ReplaceParam(output, parameters[0].ToString("0"));
output = ReplaceParam(output, parameters[1].ToString("0"));
}
break;
default:
output = "Inconnu";
break;
}
return output;
}
/// <summary>
/// Retourne le message contenu dans une trame dans un texte explicite avec les paramètres décodés
/// </summary>
/// <param name="frame">Trame à décoder</param>
/// <returns>Message sur le contnu de la trame</returns>
public static String GetMessage(Frame frame)
{
String output = "";
output = GetMessage(CanFrameFactory.ExtractFunction(frame));
output = GetMessage(CanFrameFactory.ExtractFunction(frame), GetParameters(output, frame));
return output;
}
/// <summary>
/// Retourne la liste des valeurs des paramètres d'une trame selon le format donné
/// </summary>
/// <param name="format">Format du décodage sous la forme "Message valeur = {0-1}" équivaut à un paramètre situé sur les 1er et 2eme octets.</param>
/// <param name="frame">Trame dans laquelle lire les valeurs</param>
/// <returns>Liste des valeurs brutes des paramètres</returns>
private static List<uint> GetParameters(String format, Frame frame)
{
List<uint> parameters = new List<uint>();
String subParameter;
if (format.Contains("{ServoID}"))
{
parameters.Add((uint)CanFrameFactory.ExtractServomoteurID(frame));
format = format.Replace("{ServoID}", "");
}
for (int iChar = 0; iChar < format.Length; iChar++)
{
if (format[iChar] == '{')
{
iChar++;
parameters.Add(0);
while (format[iChar] != '}')
{
subParameter = "";
while (format[iChar] != '-' && format[iChar] != '}')
{
subParameter += format[iChar];
iChar++;
}
parameters[parameters.Count - 1] = parameters[parameters.Count - 1] * 256 + frame[int.Parse(subParameter)];
if (format[iChar] == '-')
iChar++;
}
}
}
return parameters;
}
/// <summary>
/// Remplace le premier paramètre entre accolades par le message donné
/// </summary>
/// <param name="input">Chaine contenant le message entier paramétré</param>
/// <param name="msg">Message à écrire à la place du premier paramètre</param>
/// <returns>Chaine contenant le message avec le paramètre remplacé</returns>
private static String ReplaceParam(String input, String msg)
{
int iStart = input.IndexOf("{");
int iEnd = input.IndexOf("}");
String param = input.Substring(iStart, iEnd - iStart + 1);
String output = input.Replace(param, msg);
return output;
}
}
}
<file_sep>/GoBot/GoBot/Utils/DetectionAnalyzer.cs
using Geometry.Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Utils
{
class DetectionAnalyzer
{
private List<IShape> _obstacles;
private IShape _bounds;
private double _precision;
public DetectionAnalyzer()
{
_obstacles = new List<IShape>();
_bounds = new PolygonRectangle(new RealPoint(0, 0), 3000, 2000);
_precision = 10;
}
public List<RealPoint> KeepInsideBounds(List<RealPoint> detection)
{
return detection.GetPointsInside(_bounds).ToList();
}
public List<RealPoint> RemoveObstacles(List<RealPoint> detection)
{
return detection.Where(o => _obstacles.Min(s => s.Distance(o)) < _precision).ToList();
}
}
}
<file_sep>/GoBot/GeometryTester/TestCircleWithCircle.cs
using Geometry.Shapes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeometryTester
{
[TestClass]
public class TestCircleWithCircle
{
#region Contains
[TestMethod]
public void TestContainsStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(new RealPoint(20, 5), 80);
Circle c3 = new Circle(new RealPoint(100, 220), 20);
Assert.IsFalse(c1.Contains(c2));
Assert.IsFalse(c1.Contains(c3));
Assert.IsTrue(c2.Contains(c1));
Assert.IsFalse(c2.Contains(c3));
Assert.IsFalse(c3.Contains(c1));
Assert.IsFalse(c3.Contains(c2));
}
[TestMethod]
public void TestContainsPositionZero()
{
Circle c1 = new Circle(new RealPoint(0, 0), 30);
Circle c2 = new Circle(new RealPoint(0, 0), 80);
Circle c3 = new Circle(new RealPoint(100, 220), 20);
Assert.IsFalse(c1.Contains(c2));
Assert.IsFalse(c1.Contains(c3));
Assert.IsTrue(c2.Contains(c1));
Assert.IsFalse(c2.Contains(c3));
Assert.IsFalse(c3.Contains(c1));
Assert.IsFalse(c3.Contains(c2));
}
[TestMethod]
public void TestContainsRadiusZero()
{
Circle c1 = new Circle(new RealPoint(10, 20), 0);
Circle c2 = new Circle(new RealPoint(20, 5), 80);
Circle c3 = new Circle(new RealPoint(100, 220), 20);
Assert.IsFalse(c1.Contains(c2));
Assert.IsFalse(c1.Contains(c3));
Assert.IsTrue(c2.Contains(c1));
Assert.IsFalse(c3.Contains(c1));
}
[TestMethod]
public void TestContainsPositionNeg()
{
Circle c1 = new Circle(new RealPoint(-10, -20), 30);
Circle c2 = new Circle(new RealPoint(-20, -5), 80);
Circle c3 = new Circle(new RealPoint(-100, -220), 20);
Assert.IsFalse(c1.Contains(c2));
Assert.IsFalse(c1.Contains(c3));
Assert.IsTrue(c2.Contains(c1));
Assert.IsFalse(c2.Contains(c3));
Assert.IsFalse(c3.Contains(c1));
Assert.IsFalse(c3.Contains(c2));
}
[TestMethod]
public void TestContainsSameX()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(new RealPoint(10, 5), 80);
Assert.IsFalse(c1.Contains(c2));
Assert.IsTrue(c2.Contains(c1));
}
[TestMethod]
public void TestContainsSameY()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(new RealPoint(20, 20), 80);
Assert.IsFalse(c1.Contains(c2));
Assert.IsTrue(c2.Contains(c1));
}
[TestMethod]
public void TestContainsSameCenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
Circle c2 = new Circle(new RealPoint(10, 20), 80);
Assert.IsFalse(c1.Contains(c2));
Assert.IsTrue(c2.Contains(c1));
}
[TestMethod]
public void TestContainsSameCenterZero()
{
Circle c1 = new Circle(new RealPoint(0, 0), 30);
Circle c2 = new Circle(new RealPoint(0, 0), 80);
Assert.IsFalse(c1.Contains(c2));
Assert.IsTrue(c2.Contains(c1));
}
#endregion
#region Cross
[TestMethod]
public void TestCrossStandard()
{
Circle c1 = new Circle(new RealPoint(20, 30), 50);
Circle c2 = new Circle(new RealPoint(55, 35), 40);
Circle c3 = new Circle(new RealPoint(150, 20), 25);
Assert.IsTrue(c1.Cross(c2));
Assert.IsFalse(c1.Cross(c3));
Assert.IsTrue(c2.Cross(c1));
Assert.IsFalse(c2.Cross(c3));
Assert.IsFalse(c3.Cross(c1));
Assert.IsFalse(c3.Cross(c2));
}
[TestMethod]
public void TestCrossSameX()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(20, 35), 15);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossSameY()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(35, 30), 15);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossAdjacentX()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(60, 30), 20);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossAdjacentY()
{
Circle c1 = new Circle(new RealPoint(30, 20), 20);
Circle c2 = new Circle(new RealPoint(30, 60), 20);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossAdjacent()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 2.5);
Circle c2 = new Circle(new RealPoint(13, 14), 2.5);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossRadiusZeroBoth()
{
Circle c1 = new Circle(new RealPoint(10, 10), 0);
Circle c2 = new Circle(new RealPoint(10, 10), 0);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossRadiusZeroOnCircle()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 5);
Circle c2 = new Circle(new RealPoint(13, 14), 0);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossRadiusZeroOnCenter()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(3, 4), 5);
Circle c2 = new Circle(new RealPoint(0, 0), 0);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossSuperposed()
{
Circle c1 = new Circle(new RealPoint(5, 5), 5);
Circle c2 = new Circle(new RealPoint(5, 5), 5);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
}
[TestMethod]
public void TestCrossPrecision()
{
Circle c1 = new Circle(new RealPoint(5, 5), 5);
Circle c2 = new Circle(new RealPoint(5, 15), 5 + RealPoint.PRECISION);
Circle c3 = new Circle(new RealPoint(5, 15), 5 - RealPoint.PRECISION);
Assert.IsTrue(c1.Cross(c2));
Assert.IsTrue(c2.Cross(c1));
Assert.IsFalse(c1.Cross(c3));
Assert.IsFalse(c3.Cross(c1));
}
[TestMethod]
public void TestCrossNeg()
{
Circle c1 = new Circle(new RealPoint(-20, -30), 50);
Circle c2 = new Circle(new RealPoint(-55, -35), 40);
Circle c3 = new Circle(new RealPoint(-150, -20), 25);
Circle c4 = new Circle(new RealPoint(150, 20), 25);
Assert.IsTrue(c1.Cross(c2));
Assert.IsFalse(c1.Cross(c3));
Assert.IsFalse(c4.Cross(c3));
Assert.IsTrue(c2.Cross(c1));
Assert.IsFalse(c2.Cross(c3));
Assert.IsFalse(c4.Cross(c3));
Assert.IsFalse(c3.Cross(c1));
Assert.IsFalse(c3.Cross(c2));
Assert.IsFalse(c3.Cross(c4));
}
#endregion
#region Distance
[TestMethod]
public void TestDistanceStandard()
{
Circle c1 = new Circle(new RealPoint(3, 4), 1);
Circle c2 = new Circle(new RealPoint(6, 10), 1);
Assert.AreEqual(4.71, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceSame()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(20, 30), 20);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceAdjacent()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 2.5);
Circle c2 = new Circle(new RealPoint(13, 14), 2.5);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceRadiusZeroBoth()
{
Circle c1 = new Circle(new RealPoint(10, 10), 0);
Circle c2 = new Circle(new RealPoint(10, 10), 0);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceRadiusZeroOnCircle()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 5);
Circle c2 = new Circle(new RealPoint(13, 14), 0);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceRadiusZeroOnCenter()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(3, 4), 5);
Circle c2 = new Circle(new RealPoint(0, 0), 0);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceCrossing()
{
Circle c1 = new Circle(new RealPoint(5, 6), 5);
Circle c2 = new Circle(new RealPoint(6, 8), 5);
Assert.AreEqual(0, c1.Distance(c2), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceCenterNeg()
{
Circle c1 = new Circle(new RealPoint(-20, -30), 5);
Circle c2 = new Circle(new RealPoint(-55, -35), 4);
Assert.AreEqual(26.35, c1.Distance(c2), RealPoint.PRECISION);
}
#endregion
#region CrossingPoints
[TestMethod]
public void TestCrossingPointsStandard()
{
Circle c1 = new Circle(new RealPoint(20, 30), 50);
Circle c2 = new Circle(new RealPoint(55, 35), 40);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(2, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(55.71, -4.99)));
Assert.IsTrue(pts.Contains(new RealPoint(44.49, 73.59)));
}
[TestMethod]
public void TestCrossingPointsSameX()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(20, 35), 20);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(2, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(39.84, 32.5)));
Assert.IsTrue(pts.Contains(new RealPoint(0.16, 32.5)));
}
[TestMethod]
public void TestCrossingPointsSameY()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(35, 30), 15);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(2, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(33.33, 15.09)));
Assert.IsTrue(pts.Contains(new RealPoint(33.33, 44.91)));
}
[TestMethod]
public void TestCrossingPointsAdjacentX()
{
Circle c1 = new Circle(new RealPoint(20, 30), 20);
Circle c2 = new Circle(new RealPoint(60, 30), 20);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(40,30)));
}
[TestMethod]
public void TestCrossingPointsAdjacentY()
{
Circle c1 = new Circle(new RealPoint(30, 20), 20);
Circle c2 = new Circle(new RealPoint(30, 60), 20);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(30, 40)));
}
[TestMethod]
public void TestCrossingPointsAdjacent()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 2.5);
Circle c2 = new Circle(new RealPoint(13, 14), 2.5);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(11.5,12)));
}
[TestMethod]
public void TestCrossingPointsRadiusZeroBoth()
{
Circle c1 = new Circle(new RealPoint(10, 10), 0);
Circle c2 = new Circle(new RealPoint(10, 10), 0);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(10,10)));
}
[TestMethod]
public void TestCrossingPointsRadiusZeroOnCircle()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(10, 10), 5);
Circle c2 = new Circle(new RealPoint(13, 14), 0);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(13, 14)));
}
[TestMethod]
public void TestCrossingPointsRadiusZeroOnCenter()
{
// 3² + 4² = 5², très pratique
Circle c1 = new Circle(new RealPoint(3, 4), 5);
Circle c2 = new Circle(new RealPoint(0, 0), 0);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(1, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(0, 0)));
}
[TestMethod]
public void TestCrossingPointsSuperposed()
{
// Cas un peu particulier, les cercles se superposent donc se croisent, mais on ne calcule pas de points de croisement car il y en une infinité
Circle c1 = new Circle(new RealPoint(5, 5), 5);
Circle c2 = new Circle(new RealPoint(5, 5), 5);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(0, pts.Count);
}
[TestMethod]
public void TestCrossingPointsNeg()
{
Circle c1 = new Circle(new RealPoint(-20, -30), 50);
Circle c2 = new Circle(new RealPoint(-55, -35), 40);
List<RealPoint> pts = c1.GetCrossingPoints(c2);
Assert.AreEqual(2, pts.Count);
Assert.IsTrue(pts.Contains(new RealPoint(-44.49, -73.59)));
Assert.IsTrue(pts.Contains(new RealPoint(-55.71, 4.99)));
}
#endregion
}
}<file_sep>/GoBot/Extensions/ControlExtensions.cs
using System;
using System.Windows.Forms;
internal static class ControlExtensions
{
public static void InvokeAuto(this Control control, Action action)
{
if (control.InvokeRequired)
control.Invoke((MethodInvoker)(() => action()));
else
action.Invoke();
}
public static void InvokeAuto(this UserControl control, Action action)
{
if (control.InvokeRequired)
control.Invoke((MethodInvoker)(() => action()));
else
action.Invoke();
}
}<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/PolygonWithPolygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class PolygonWithPolygon
{
public static bool Contains(Polygon containingPolygon, Polygon containedPolygon)
{
// Il suffit de contenir tous les segments du polygone testé
return containedPolygon.Sides.TrueForAll(s => PolygonWithSegment.Contains(containingPolygon, s));
}
public static bool Cross(Polygon polygon1, Polygon polygon2)
{
// Si un des segments du premier polygone croise le second
return polygon1.Sides.Exists(s => SegmentWithPolygon.Cross(s, polygon2));
}
public static double Distance(Polygon polygon1, Polygon polygon2)
{
double minDistance = 0;
// Si les polygones se croisent ou se contiennent, la distance est nulle
if (!PolygonWithPolygon.Cross(polygon1, polygon2) && !PolygonWithPolygon.Contains(polygon1, polygon2) && !PolygonWithPolygon.Contains(polygon2, polygon1))
{
minDistance = double.MaxValue;
foreach (Segment s1 in polygon1.Sides)
foreach (Segment s2 in polygon2.Sides)
minDistance = Math.Min(minDistance, s1.Distance(s2));
}
return minDistance;
}
public static List<RealPoint> GetCrossingPoints(Polygon polygon1, Polygon polygon2)
{
// Croisement des segments du premier polygone avec le second
return polygon1.Sides.SelectMany(s => SegmentWithPolygon.GetCrossingPoints(s, polygon2)).ToList();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Forms/FenGoBot.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using GoBot.IHM;
using GoBot.Communications;
using System.IO;
using GoBot.Threading;
using GoBot.Devices;
using GoBot.BoardContext;
using System.Diagnostics;
using Geometry.Shapes;
using GoBot.Communications.UDP;
using GoBot.IHM.Forms;
namespace GoBot
{
public partial class FenGoBot : Form
{
public static FenGoBot Instance { get; private set; }
private System.Windows.Forms.Timer timerSauvegarde;
private List<TabPage> _pagesInWindow;
/// <summary>
/// Anti scintillement
/// </summary>
//protected override CreateParams CreateParams
//{
// get
// {
// CreateParams cp = base.CreateParams;
// cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED
// return cp;
// }
//}
public FenGoBot(string[] args)
{
InitializeComponent();
timerSauvegarde = new Timer();
timerSauvegarde.Interval = 10000;
timerSauvegarde.Tick += timerSauvegarde_Tick;
timerSauvegarde.Start();
if (!Execution.DesignMode)
{
panelGrosRobot.Init();
if (Screen.PrimaryScreen.Bounds.Width <= 1024)
{
WindowState = FormWindowState.Maximized;
FormBorderStyle = FormBorderStyle.None;
tabControl.SelectedTab = tabPandaNew;
tabControl.Location = new Point(-14, -50);
tabControl.Width += 100;
tabControl.Height += 100;
panelConnexions.Visible = false;
lblSimulation.Visible = false;
switchBoutonSimu.Visible = false;
btnFenetre.Visible = false;
}
else
{
WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.FixedSingle;
}
switchBoutonSimu.Value = Robots.Simulation;
tabPrecedent = new Dictionary<TabPage, TabPage>();
tabPrecedent.Add(tabControl.TabPages[0], null);
for (int i = 1; i < tabControl.Controls.Count; i++)
tabPrecedent.Add(tabControl.TabPages[i], (tabControl.TabPages[i - 1]));
List<String> fichiersElog = new List<string>();
List<String> fichiersTlog = new List<string>();
foreach (String chaine in args)
{
if (Path.GetExtension(chaine) == ".elog")
fichiersElog.Add(chaine);
if (Path.GetExtension(chaine) == FramesLog.FileExtension)
fichiersTlog.Add(chaine);
}
if (fichiersElog.Count > 0)
{
foreach (String fichier in fichiersElog)
panelLogsEvents.ChargerLog(fichier);
panelLogsEvents.Afficher();
if (fichiersTlog.Count == 0)
{
tabControl.SelectedTab = tabLogs;
tabControlLogs.SelectedTab = tabLogEvent;
}
}
if (fichiersTlog.Count > 0)
{
foreach (String fichier in fichiersTlog)
pnlLogFrames.LoadLog(fichier);
pnlLogFrames.DisplayLog();
tabControl.SelectedTab = tabLogs;
tabControlLogs.SelectedTab = tabLogUDP;
}
Instance = this;
GameBoard.MyColor = GameBoard.ColorLeftBlue;
Connections.ConnectionMove.SendMessage(UdpFrameFactory.DemandeCouleurEquipe());
}
Connections.StartConnections();
SplashScreen.CloseSplash(-1);
pnlPower.StartGraph();
pnlNumericIO.SetBoard(Board.RecIO);
pnlNumericMove.SetBoard(Board.RecMove);
panelTable.StartDisplay();
_pagesInWindow = new List<TabPage>();
this.Text = "GoBot 2020 - Beta";
}
public void ChargerReplay(String fichier)
{
if (Path.GetExtension(fichier) == FramesLog.FileExtension)
{
pnlLogFrames.Clear();
pnlLogFrames.LoadLog(fichier);
pnlLogFrames.DisplayLog();
tabControl.SelectedTab = tabLogs;
tabControlLogs.SelectedTab = tabLogUDP;
}
else if (Path.GetExtension(fichier) == ".elog")
{
panelLogsEvents.Clear();
panelLogsEvents.ChargerLog(fichier);
panelLogsEvents.Afficher();
tabControl.SelectedTab = tabLogs;
tabControlLogs.SelectedTab = tabLogEvent;
}
}
void timerSauvegarde_Tick(object sender, EventArgs e)
{
SauverLogs();
}
protected override void OnClosing(CancelEventArgs e)
{
this.Hide();
if (!ThreadManager.ExitAll())
{
Console.WriteLine("Tous les threads ne se sont pas terminés : suicide de l'application.");
Environment.Exit(0);
}
Execution.Shutdown = true;
Config.Save();
SauverLogs();
if (GameBoard.Strategy != null && GameBoard.Strategy.IsRunning)
GameBoard.Strategy.Stop();
AllDevices.Close();
base.OnClosing(e);
}
private void SauverLogs()
{
DateTime debut = DateTime.Now;
foreach (Connection conn in Connections.AllConnections)
conn.Archives.Export(Config.PathData + "/Logs/" + Execution.LaunchStartString + "/" + Connections.GetUDPBoardByConnection(conn).ToString() + FramesLog.FileExtension);
Robots.MainRobot.Historique.Sauvegarder(Config.PathData + "/Logs/" + Execution.LaunchStartString + "/ActionsGros.elog");
}
private void FenGoBot_Load(object sender, EventArgs e)
{
this.Activate();
}
private void switchBoutonSimu_ValueChanged(object sender, bool value)
{
Robots.EnableSimulation(value);
panelGrosRobot.Init();
if (value)
AllDevices.InitSimu();
else
AllDevices.Init();
AllDevices.SetRobotPosition(Robots.MainRobot.Position);
}
private void buttonFenetre_Click(object sender, EventArgs e)
{
TabControl tab = new TabControl();
tab.Height = tabControl.Height;
tab.Width = tabControl.Width;
_pagesInWindow.Add(tabControl.SelectedTab);
tab.TabPages.Add(tabControl.SelectedTab);
Fenetre fen = new Fenetre(tab);
fen.Show();
fen.FormClosing += fen_FormClosing;
}
private Dictionary<TabPage, TabPage> tabPrecedent;
void fen_FormClosing(object sender, FormClosingEventArgs e)
{
Fenetre fen = (Fenetre)sender;
TabControl tab = (TabControl)fen.Control;
TabPage page = tab.TabPages[0];
_pagesInWindow.Remove(page);
TabPage tabPrec = tabPrecedent[page];
bool trouve = false;
if (tabPrec == null)
tabControl.TabPages.Insert(0, page);
else
{
while (!trouve && tabPrec != null)
{
for (int i = 0; i < tabControl.TabPages.Count; i++)
if (tabControl.TabPages[i] == tabPrec)
{
trouve = true;
tabControl.TabPages.Insert(i + 1, page);
break;
}
if (!trouve)
tabPrec = tabPrecedent[tabPrec];
if (tabPrec == null)
tabControl.TabPages.Insert(0, page);
}
}
}
private void btnDebug_Click(object sender, EventArgs e)
{
DebugLidar fen = new DebugLidar();
fen.ShowDialog();
}
private void pageCheckSpeed1_Load(object sender, EventArgs e)
{
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/CircleWithRealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
public static class CircleWithRealPoint
{
public static bool Contains(Circle containingCircle, RealPoint containedPoint)
{
// Pour contenir un point, celui si se trouve à une distance inférieure au rayon du centre
return containedPoint.Distance(containingCircle.Center) <= containingCircle.Radius;
}
public static double Distance(Circle circle, RealPoint point)
{
// C'est la distance entre le centre du cercle et le point moins le rayon du cercle
return Math.Max(0, point.Distance(circle.Center) - circle.Radius);
}
public static bool Cross(Circle circle, RealPoint point)
{
// Pour qu'un cercle croise un point en c'est que le point est sur son contour donc à une distance égale au rayon de son centre.
return Math.Abs(circle.Center.Distance(point) - circle.Radius) < RealPoint.PRECISION;
}
public static List<RealPoint> GetCrossingPoints(Circle circle, RealPoint point)
{
// Le seul point de croisement d'un point et d'un cercle, c'est le point lui même si il croise le cercle.
return circle.Cross(point) ? new List<RealPoint>(){ new RealPoint(point) } : new List<RealPoint>();
}
}
}
<file_sep>/GoBot/GeometryTester/TestCircleWithRealPoint.cs
using Geometry.Shapes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeometryTester
{
[TestClass]
public class TestCircleWithRealPoint
{
#region Contains
[TestMethod]
public void TestContainsStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(11, 21);
RealPoint p2 = new RealPoint(11, 60);
RealPoint p3 = new RealPoint(11, -60);
Assert.IsTrue(c1.Contains(p1));
Assert.IsFalse(c1.Contains(p2));
Assert.IsFalse(c1.Contains(p3));
}
[TestMethod]
public void TestContainsCenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 20);
Assert.IsTrue(c1.Contains(p1));
}
[TestMethod]
public void TestContainsBorderOrtho()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 50);
RealPoint p2 = new RealPoint(10, -10);
RealPoint p3 = new RealPoint(-20, 20);
RealPoint p4 = new RealPoint(40, 20);
Assert.IsTrue(c1.Contains(p1));
Assert.IsTrue(c1.Contains(p2));
Assert.IsTrue(c1.Contains(p3));
Assert.IsTrue(c1.Contains(p4));
}
[TestMethod]
public void TestContainsBorderDiagonal()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10 + Math.Sin(Math.PI / 3) * 30, 20 + Math.Cos(Math.PI / 3) * 30);
Assert.IsTrue(c1.Contains(p1));
}
[TestMethod]
public void TestContainsOrigin()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
Assert.IsTrue(c1.Contains(p1));
}
[TestMethod]
public void TestContainsOriginDot()
{
Circle c1 = new Circle(new RealPoint(0, 0), 0);
RealPoint p1 = c1.Center;
Assert.IsTrue(p1.Contains(c1));
}
[TestMethod]
public void TestContainsDot()
{
Circle c1 = new Circle(new RealPoint(42, 42), 0);
RealPoint p1 = c1.Center;
Assert.IsTrue(p1.Contains(c1));
}
[TestMethod]
public void TestContainsCircle()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
Assert.IsFalse(p1.Contains(c1));
}
#endregion
#region Cross
[TestMethod]
public void TestCrossCenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 20);
Assert.IsFalse(c1.Cross(p1));
}
[TestMethod]
public void TestCrossBorderOrtho()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 50);
RealPoint p2 = new RealPoint(10, -10);
RealPoint p3 = new RealPoint(-20, 20);
RealPoint p4 = new RealPoint(40, 20);
Assert.IsTrue(c1.Cross(p1));
Assert.IsTrue(c1.Cross(p2));
Assert.IsTrue(c1.Cross(p3));
Assert.IsTrue(c1.Cross(p4));
}
[TestMethod]
public void TestCrossBorderDiagonal()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10 + Math.Sin(Math.PI / 3) * 30, 20 + Math.Cos(Math.PI / 3) * 30);
Assert.IsTrue(c1.Cross(p1));
}
[TestMethod]
public void TestCrossOrigin()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
Assert.IsFalse(c1.Cross(p1));
}
[TestMethod]
public void TestCrossOriginDot()
{
Circle c1 = new Circle(new RealPoint(0, 0), 0);
RealPoint p1 = c1.Center;
Assert.IsTrue(p1.Cross(c1));
}
[TestMethod]
public void TestCrossDot()
{
Circle c1 = new Circle(new RealPoint(42, 42), 0);
RealPoint p1 = c1.Center;
Assert.IsTrue(p1.Cross(c1));
}
[TestMethod]
public void TestCrossCircle()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
Assert.IsFalse(p1.Cross(c1));
}
#endregion
#region CrossingPoints
[TestMethod]
public void TestCrossingPointsCenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 20);
List<RealPoint> points = c1.GetCrossingPoints(p1);
Assert.AreEqual(0, points.Count);
}
[TestMethod]
public void TestCrossingPointsBorderOrtho()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 50);
RealPoint p2 = new RealPoint(10, -10);
RealPoint p3 = new RealPoint(-20, 20);
RealPoint p4 = new RealPoint(40, 20);
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
List<RealPoint> points2 = c1.GetCrossingPoints(p2);
List<RealPoint> points3 = c1.GetCrossingPoints(p3);
List<RealPoint> points4 = c1.GetCrossingPoints(p4);
Assert.AreEqual(1, points1.Count);
Assert.AreEqual(1, points2.Count);
Assert.AreEqual(1, points3.Count);
Assert.AreEqual(1, points4.Count);
Assert.AreEqual(points1[0], p1);
Assert.AreEqual(points2[0], p2);
Assert.AreEqual(points3[0], p3);
Assert.AreEqual(points4[0], p4);
}
[TestMethod]
public void TestCrossingPointsBorderDiagonal()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10 + Math.Sin(Math.PI / 3) * 30, 20 + Math.Cos(Math.PI / 3) * 30);
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
Assert.AreEqual(1, points1.Count);
Assert.AreEqual(points1[0], p1);
}
[TestMethod]
public void TestCrossingPointsOrigin()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
Assert.AreEqual(0, points1.Count);
}
[TestMethod]
public void TestCrossingPointsOriginDot()
{
Circle c1 = new Circle(new RealPoint(0, 0), 0);
RealPoint p1 = c1.Center;
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
Assert.AreEqual(1, points1.Count);
Assert.AreEqual(points1[0], p1);
}
[TestMethod]
public void TestCrossingPointsDot()
{
Circle c1 = new Circle(new RealPoint(42, 42), 0);
RealPoint p1 = c1.Center;
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
Assert.AreEqual(1, points1.Count);
Assert.AreEqual(points1[0], p1);
}
[TestMethod]
public void TestCrossingPointsCircle()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
List<RealPoint> points1 = c1.GetCrossingPoints(p1);
Assert.AreEqual(0, points1.Count);
}
#endregion
#region Distance
[TestMethod]
public void TestDistanceStandard()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(11, 21);
RealPoint p2 = new RealPoint(11, 60);
RealPoint p3 = new RealPoint(11, -60);
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
Assert.AreEqual(10.0125, c1.Distance(p2), RealPoint.PRECISION);
Assert.AreEqual(50.0062, c1.Distance(p3), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceCenter()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 20);
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceBorderOrtho()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10, 50);
RealPoint p2 = new RealPoint(10, -10);
RealPoint p3 = new RealPoint(-20, 20);
RealPoint p4 = new RealPoint(40, 20);
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
Assert.AreEqual(0, c1.Distance(p2), RealPoint.PRECISION);
Assert.AreEqual(0, c1.Distance(p3), RealPoint.PRECISION);
Assert.AreEqual(0, c1.Distance(p4), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceBorderDiagonal()
{
Circle c1 = new Circle(new RealPoint(10, 20), 30);
RealPoint p1 = new RealPoint(10 + Math.Sin(Math.PI / 3) * 30, 20 + Math.Cos(Math.PI / 3) * 30);
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceOrigin()
{
Circle c1 = new Circle(new RealPoint(0, 0), 1);
RealPoint p1 = c1.Center;
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceOriginDot()
{
Circle c1 = new Circle(new RealPoint(0, 0), 0);
RealPoint p1 = c1.Center;
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
}
[TestMethod]
public void TestDistanceDot()
{
Circle c1 = new Circle(new RealPoint(42, 42), 0);
RealPoint p1 = c1.Center;
Assert.AreEqual(0, c1.Distance(p1), RealPoint.PRECISION);
}
#endregion
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/PanelGenerics.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace GoBot.IHM
{
public partial class PanelGenerics : UserControl
{
public PanelGenerics()
{
InitializeComponent();
AutoSize = true;
}
private void PanelGenerics_Load(object sender, EventArgs e)
{
int x = 0;
if (!Execution.DesignMode)
{
Type t = typeof(Actionneurs.Actionneur);
foreach (PropertyInfo prop in t.GetProperties())
{
PanelActionneurGeneric panel = new PanelActionneurGeneric();
Object item = prop.GetValue(null, null);
if (item != null)
{
panel.SetObject(item);
panel.SetBounds(x, 0, panel.Width, this.Height);
this.Controls.Add(panel);
x += 135;
}
}
}
}
}
}
<file_sep>/GoBot/Composants/Led.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class Led : PictureBox
{
private Color _color;
private Timer _blinkTimer;
private int _blinkCounter;
private static Dictionary<Color, Bitmap> _bitmaps { get; set; } // Images déjà créées, inutile de les recaculer à chaque fois
public Led()
{
if(_bitmaps is null)
{
_bitmaps = new Dictionary<Color, Bitmap>();
_bitmaps.Add(Color.Red, Properties.Resources.RedLed);
}
InitializeComponent();
BackColor = Color.Transparent;
_blinkTimer = new Timer();
_blinkTimer.Interval = 100;
_blinkTimer.Tick += new EventHandler(timer_Tick);
_blinkCounter = 0;
Color = Color.Red;
}
/// <summary>
/// Permet d'obtenir ou de définir la couleur de la LED
/// </summary>
public Color Color
{
get { return _color; }
set
{
_color = value;
lock (_bitmaps)
{
if (!_bitmaps.ContainsKey(_color))
GenerateLed(_color);
this.Image = (Image)_bitmaps[_color].Clone();
}
}
}
/// <summary>
/// Fait clignoter la LED 7 fois
/// </summary>
/// <param name="shutdown">Vrai si la LED doit rester éteinte à la fin du clignotement</param>
public void Blink(bool shutdown = false)
{
_blinkTimer.Stop();
Visible = true;
_blinkCounter = 0;
if (shutdown)
_blinkCounter = 1;
_blinkTimer.Start();
}
/// <summary>
/// Change la couleur de la led et la fait clignoter 7 fois si la couleur est différente à la précédente.
/// </summary>
/// <param name="color"></param>
public void BlinkColor(Color color)
{
if(_color != color)
{
Color = color;
Blink();
}
}
void timer_Tick(object sender, EventArgs e)
{
if (Visible)
Visible = false;
else
Visible = true;
_blinkCounter++;
if (_blinkCounter > 7)
_blinkTimer.Stop();
}
private void GenerateLed(Color col)
{
Bitmap bmp;
Color ex;
// Création des LEDs de différentes couleurs à partir du modèle rouge
bmp = new Bitmap(Properties.Resources.RedLed);
for (int i = 0; i <= bmp.Width - 1; i++)
{
for (int j = 0; j <= bmp.Height - 1; j++)
{
ex = bmp.GetPixel(i, j);
bmp.SetPixel(i, j, Color.FromArgb(ex.A, (int)(ex.B + (ex.R - ex.B) / 255.0 * col.R), (int)(ex.B + (ex.R - ex.B) / 255.0 * col.G), (int)(ex.B + (ex.R - ex.B) / 255.0 * col.B)));
}
}
_bitmaps.Add(col, bmp);
}
}
}
<file_sep>/GoBot/GoBot/Actions/IAction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace GoBot.Actions
{
public interface IAction
{
Image Image { get; }
void Executer();
}
}
<file_sep>/GoBot/GoBot/Movements/MovementColorDropoff.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
namespace GoBot.Movements
{
public class MovementColorDropoff : Movement
{
ColorDropOff _zone;
public MovementColorDropoff(ColorDropOff zone)
{
_zone = zone;
Positions.Add(new Position(90, new RealPoint(_zone.Position.X, _zone.Position.Y - 450)));
}
public override bool CanExecute =>
_zone.Owner == GameBoard.MyColor &&
Math.Max(_zone.LoadsOnRed, _zone.LoadsOnRed) < 4 &&
!Actionneur.Lifter.Loaded &&
_zone.HasInsideBuoys &&
Actionneur.ElevatorLeft.CountTotal + Actionneur.ElevatorRight.CountTotal > 0;
public override int Score => 0; // On va compter les points de ménière plus précise
public override double Value => GameBoard.Strategy.TimeBeforeEnd.TotalSeconds > 25 ? 0.3 : 5;
public override GameElement Element => _zone;
public override Robot Robot => Robots.MainRobot;
public override Color Color => _zone.Owner;
protected override void MovementBegin()
{
// Rien, mais on peut envisager de pré-décharger SI y'a pas de gobelet à attraper à l'arrivée ?
Actionneur.ElevatorLeft.DoGrabOpen();
Actionneur.ElevatorRight.DoGrabOpen();
}
protected override bool MovementCore()
{
// TODO : Attrapage (avec test) des bouées exterieures, d'ailleurs prévoir de la place pour les attraper
ThreadLink link1 = ThreadManager.CreateThread(link => Actionneur.ElevatorRight.DoSequencePickupColor(GameBoard.MyColor == GameBoard.ColorLeftBlue ? Buoy.Green : Buoy.Red));
ThreadLink link2 = ThreadManager.CreateThread(link => Actionneur.ElevatorLeft.DoSequencePickupColor(GameBoard.MyColor == GameBoard.ColorLeftBlue ? Buoy.Red : Buoy.Green));
link1.StartThread();
link2.StartThread();
link1.WaitEnd();
link2.WaitEnd();
if (_zone.HasOutsideBuoys)
{
Robot.SetSpeedSlow();
Actionneur.ElevatorLeft.DoGrabOpen();
Actionneur.ElevatorRight.DoGrabOpen();
Robot.Move(250);
Robot.SetSpeedFast();
//ThreadManager.CreateThread(link => { Actionneur.ElevatorLeft.DoSequencePickupColor(Buoy.Red); }).StartThread();
//ThreadManager.CreateThread(link => { Actionneur.ElevatorRight.DoSequencePickupColor(Buoy.Green); }).StartThread();
Actionneur.ElevatorLeft.DoTakeLevel0(Buoy.Red);
Actionneur.ElevatorRight.DoTakeLevel0(Buoy.Green);
_zone.TakeOutsideBuoys();
Thread.Sleep(500);
Robot.PivotRight(180);
Robot.Move(-150);
}
else
{
Robot.Move(-400);
}
Robot.SetSpeedSlow();
if (_zone.HasInsideBuoys)
{
Robot.Recalibration(SensAR.Arriere, true, true);
// TODO recallage X et Y tant qu'à faire ?
DoFingersGrab(); // Attrapage des bouées initialement contre la bordure avec les fingers
_zone.TakeInsideBuoys();
Robot.SetSpeedFast();
Robot.Move(150);
Robot.PivotLeft(180);
Robot.Move(125);
Robot.SetSpeedSlow();
DoElevatorsDropoff(0);
}
else
{
// TODO, y'a surement des bouées posées, donc pas de recallage et avancer moins
}
bool hasLeft = Actionneur.FingerLeft.Loaded;
bool hasRight = Actionneur.FingerRight.Loaded;
if (hasLeft || hasRight)
{
Color cLeft = Actionneur.FingerLeft.Load;
Color cRight = Actionneur.FingerRight.Load;
Robot.MoveBackward(90);
Robot.PivotLeft(82);
_zone.SetPendingRight(cRight, new RealPoint(Robot.Position.Coordinates.X + 193.5, Robot.Position.Coordinates.Y + 86.5).Rotation(Robot.Position.Angle.InPositiveDegrees + 90, Robot.Position.Coordinates));
Actionneur.FingerRight.DoRelease();
Robot.PivotRight(164);
_zone.SetPendingLeft(cLeft, new RealPoint(Robot.Position.Coordinates.X - 193.5, Robot.Position.Coordinates.Y + 86.5).Rotation(Robot.Position.Angle.InPositiveDegrees + 90, Robot.Position.Coordinates));
Actionneur.FingerLeft.DoRelease();
Robot.PivotLeft(82);
int score = 0;
int level = _zone.GetAvailableLevel();
if (hasLeft)
{
_zone.SetBuoyOnGreen(cRight, level);
score += 2;
}
if (hasRight)
{
_zone.SetBuoyOnRed(cLeft, level);
score += 2;
}
_zone.RemovePending();
if (hasLeft && hasRight)
score += 2;
GameBoard.Score += score;
}
if (_zone.LoadsOnGreen > 4 || _zone.LoadsOnRed > 4)
{
Actionneur.ElevatorLeft.DoGrabOpen();
Actionneur.ElevatorRight.DoGrabOpen();
Thread.Sleep(150);
Robot.SetSpeedVerySlow();
Robot.MoveForward(170);
Robot.SetSpeedFast();
Robot.MoveBackward(170);
}
else
{
Robot.MoveBackward(100);
}
Actionneur.ElevatorLeft.DoGrabClose();
Actionneur.ElevatorRight.DoGrabClose();
Robot.SetSpeedFast();
return true;
}
private void DoFingersGrab()
{
ThreadLink left = ThreadManager.CreateThread(link => Actionneur.FingerLeft.DoGrabColor(Buoy.Red));
ThreadLink right = ThreadManager.CreateThread(link => Actionneur.FingerRight.DoGrabColor(Buoy.Green));
left.StartThread();
right.StartThread();
left.WaitEnd();
right.WaitEnd();
}
private void DoElevatorsDropoff(int level)
{
Color colorLeft = Color.Transparent, colorRight = Color.Transparent;
bool okColorLeft, okColorRight;
ThreadLink left = ThreadManager.CreateThread(link => colorLeft = Actionneur.ElevatorLeft.DoSequenceDropOff());
ThreadLink right = ThreadManager.CreateThread(link => colorRight = Actionneur.ElevatorRight.DoSequenceDropOff());
while (_zone.LoadsOnGreen < 4 && _zone.LoadsOnRed < 4 && Actionneur.ElevatorLeft.CountTotal > 0 && Actionneur.ElevatorRight.CountTotal > 0)
{
left.StartThread();
right.StartThread();
left.WaitEnd();
right.WaitEnd();
if (colorLeft != Color.Transparent)
{
_zone.SetBuoyOnRed(colorLeft, level);
okColorLeft = (colorLeft == Buoy.Red);
GameBoard.Score += (1 + (okColorLeft ? 1 : 0));
}
else
{
okColorLeft = false;
}
if (colorRight != Color.Transparent)
{
_zone.SetBuoyOnGreen(colorRight, level);
okColorRight = (colorRight == Buoy.Green);
GameBoard.Score += (1 + (okColorRight ? 1 : 0));
}
else
{
okColorRight = false;
}
if (okColorLeft && okColorRight)
GameBoard.Score += 2;
level++;
Robot.Move(-85);
}
// Pour ranger à la fin :
Actionneur.ElevatorLeft.DoPushInsideFast();
Actionneur.ElevatorRight.DoPushInsideFast();
}
protected override void MovementEnd()
{
// rien ?
Actionneur.ElevatorLeft.DoGrabClose();
Actionneur.ElevatorRight.DoGrabClose();
}
}
}
<file_sep>/GoBot/Geometry/Position.cs
using System;
using Geometry.Shapes;
namespace Geometry
{
public class Position
{
public RealPoint Coordinates { get; set; }
public AnglePosition Angle { get; set; }
/// <summary>
/// Constructeur par défaut
/// Angle de 0° et Coordonnées (0, 0)
/// </summary>
public Position()
{
Angle = new AnglePosition();
Coordinates = new RealPoint();
}
/// <summary>
/// Constructeur par copie
/// </summary>
/// <param name="other">Position à copier</param>
public Position(Position other)
{
Angle = other.Angle;
Coordinates = new RealPoint(other.Coordinates);
}
/// <summary>
/// Construit une position selon les paramètres
/// </summary>
/// <param name="angle">Angle de départ</param>
/// <param name="coordinates">Coordonnées de départ</param>
public Position(AnglePosition angle, RealPoint coordinates)
{
Angle = angle;
Coordinates = new RealPoint(coordinates);
}
/// <summary>
/// Déplace les coordonnées par rapport aux anciennes coordonnées
/// </summary>
/// <param name="x">Déplacement sur l'axe des abscisses</param>
/// <param name="y">Déplacement sur l'axe des ordonnées</param>
public void Shift(double x, double y)
{
Coordinates = Coordinates.Translation(x, y);
}
/// <summary>
/// Fait tourner l'angle de l'angle choisi
/// </summary>
/// <param name="angle">Angle à tourner</param>
public void Turn(AngleDelta angle)
{
Angle += angle;
}
/// <summary>
/// Avance de la distance spécifiée suivant l'angle actuel
/// </summary>
/// <param name="distance">Distance à avancer</param>
public void Move(double distance)
{
double depX = distance * Math.Cos(Angle.InRadians);
double depY = distance * Math.Sin(Angle.InRadians);
Coordinates = Coordinates.Translation(depX, depY);
}
/// <summary>
/// Copie une autre position
/// </summary>
/// <param name="position">Position à copier</param>
public void Copy(Position position)
{
Angle = position.Angle;
Coordinates.Set(position.Coordinates.X, position.Coordinates.Y);
}
public override string ToString()
{
return Coordinates.ToString() + " " + Angle.ToString();
}
}
}
<file_sep>/GoBot/GoBot/Communications/UDP/UdpFrameFunction.cs
namespace GoBot.Communications.UDP
{
public enum UdpFrameFunction
{
Debug = 0xEE,
TestConnexion = 0xF0,
DemandeTension = 0xF1,
RetourTension = 0xF2,
DemandeCapteurOnOff = 0x74,
RetourCapteurOnOff = 0x75,
DemandeValeursAnalogiques = 0x76,
RetourValeursAnalogiques = 0x77,
DemandeValeursNumeriques = 0x78,
RetourValeursNumeriques = 0x79,
DemandeCapteurCouleur = 0x52,
RetourCapteurCouleur = 0x53,
DemandePositionCodeur = 0x21,
RetourPositionCodeur = 0x22,
MoteurOrigin = 0x63,
MoteurResetPosition = 0x64,
PilotageOnOff = 0x65,
MoteurPosition = 0x66,
MoteurVitesse = 0x67,
MoteurAccel = 0x68,
MoteurStop = 0x69,
MoteurFin = 0x70,
MoteurBlocage = 0x71,
Deplace = 0x01,
Pivot = 0x03,
Virage = 0x04,
Stop = 0x05,
Recallage = 0x10,
TrajectoirePolaire = 0x20,
FinRecallage = 0x11,
FinDeplacement = 0x12,
Blocage = 0x13,
AsserDemandePositionCodeurs = 0x43,
AsserRetourPositionCodeurs = 0x44,
AsserEnvoiConsigneBrutePosition = 0x45,
DemandeChargeCPU_PWM = 0x46,
RetourChargeCPU_PWM = 0x47,
AsserIntervalleRetourPosition = 0x48,
AsserDemandePositionXYTeta = 0x30,
AsserRetourPositionXYTeta = 0x31,
AsserVitesseDeplacement = 0x32,
AsserAccelerationDeplacement = 0x33,
AsserVitessePivot = 0x34,
AsserAccelerationPivot = 0x35,
AsserPID = 0x36,
AsserEnvoiPositionAbsolue = 0x37,
AsserPIDCap = 0x38,
AsserPIDVitesse = 0x39,
EnvoiUart1 = 0xA0,
RetourUart1 = 0xA1,
DemandeLidar = 0xA2,
ReponseLidar = 0xA3,
EnvoiUart2 = 0xA4,
RetourUart2 = 0xA5,
EnvoiCAN = 0xC0,
ReponseCAN = 0xC1,
DemandeCouleurEquipe = 0x72,
RetourCouleurEquipe = 0x73
}
public enum ServoFunction
{
DemandePositionCible = 0x01,
RetourPositionCible = 0x02,
EnvoiPositionCible = 0x03,
EnvoiBaudrate = 0x06,
DemandeVitesseMax = 0x07,
RetourVitesseMax = 0x08,
EnvoiVitesseMax = 0x09,
DemandeAllIn = 0x10,
RetourAllIn = 0x11,
EnvoiId = 0x12,
Reset = 0x13,
DemandeCoupleMaximum = 0x14,
RetourCoupleMaximum = 0x15,
EnvoiCoupleMaximum = 0x16,
DemandeCoupleActive = 0x17,
RetourCoupleActive = 0x18,
EnvoiCoupleActive = 0x19,
DemandeTension = 0x20,
RetourTension = 0x21,
DemandeTemperature = 0x22,
RetourTemperature = 0x23,
DemandeMouvement = 0x24,
RetourMouvement = 0x25,
DemandePositionMinimum = 0x26,
RetourPositionMinimum = 0x27,
EnvoiPositionMinimum = 0x28,
DemandePositionMaximum = 0x29,
RetourPositionMaximum = 0x30,
EnvoiPositionMaximum = 0x31,
DemandeNumeroModele = 0x32,
RetourNumeroModele = 0x33,
DemandeVersionFirmware = 0x34,
RetourVersionFirmware = 0x35,
DemandeLed = 0x36,
RetourLed = 0x37,
EnvoiLed = 0x38,
DemandeConfigAlarmeLED = 0x42,
RetourConfigAlarmeLED = 0x43,
EnvoiConfigAlarmeLED = 0x44,
DemandeConfigAlarmeShutdown = 0x45,
RetourConfigAlarmeShutdown = 0x46,
EnvoiConfigAlarmeShutdown = 0x47,
DemandeConfigEcho = 0x48,
RetourConfigEcho = 0x49,
EnvoiConfigEcho = 0x50,
DemandeComplianceParams = 0x51,
RetourComplianceParams = 0x52,
EnvoiComplianceParams = 0x53,
DemandePositionActuelle = 0x54,
RetourPositionActuelle = 0x55,
DemandeVitesseActuelle = 0x56,
RetourVitesseActuelle = 0x57,
DemandeErreurs = 0x58,
RetourErreurs = 0x59,
DemandeCoupleCourant = 0x60,
RetourCoupleCourant = 0x61,
DemandeStatusLevel = 0x62,
RetourStatusLevel = 0x63,
EnvoiTensionMax = 0x64,
DemandeTensionMax = 0x65,
RetourTensionMax = 0x66,
EnvoiTensionMin = 0x67,
DemandeTensionMin = 0x68,
RetourTensionMin = 0x69,
EnvoiTemperatureMax = 0x70,
DemandeTemperatureMax = 0x71,
RetourTemperatureMax = 0x72,
EnvoiCoupleLimite = 0x73,
DemandeCoupleLimite = 0x74,
RetourCoupleLimite = 0x75
}
}
<file_sep>/GoBot/GoBot/Communications/CAN/CanConnection.cs
using GoBot.Communications;
using GoBot.Communications.UDP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace GoBot.Communications.CAN
{
/// <summary>
/// Définit un objet capable d'envoyer des messages CAN
/// </summary>
public interface iCanSpeakable
{
bool SendFrame(Frame frame);
int GetNextFrameID();
}
public class CanConnection : Connection, iCanSpeakable
{
//TODO : CanConnection, héritier de Connection et transfert de la classe dans ../../Communications
private int _framesCount;
private Board _board;
private List<byte> _receivedBuffer;
private String _name;
public CanConnection(Board board)
{
_board = board;
_framesCount = 0;
_receivedBuffer = new List<byte>();
_name = board.ToString();
}
public override string Name { get => _name; set => _name = value; }
private void board_FrameReceived(Frame frame)
{
if (frame[1] == (byte)UdpFrameFunction.ReponseCAN)
{
for (int i = 3; i < frame.Length; i++)
_receivedBuffer.Add(frame[i]);
}
if (_receivedBuffer.Count >= 10)
{
Frame canFrame = new Frame(_receivedBuffer.GetRange(0, 10));
_receivedBuffer.RemoveRange(0, 10);
OnFrameReceived(canFrame);
}
}
bool iCanSpeakable.SendFrame(Frame frame)
{
return this.SendMessage(frame);
}
int iCanSpeakable.GetNextFrameID()
{
_framesCount = (_framesCount + 1) % 255;
return _framesCount;
}
public override bool SendMessage(Frame f)
{
bool ok = true;
Connections.UDPBoardConnection[_board].SendMessage(UdpFrameFactory.EnvoyerCAN(_board, f));
OnFrameSend(f);
_framesCount = (_framesCount + 1) % 255;
return ok;
}
public override void StartReception()
{
Connections.UDPBoardConnection[_board].StartReception();
Connections.UDPBoardConnection[_board].FrameReceived += board_FrameReceived;
}
public override void Close()
{
Connections.UDPBoardConnection[_board].FrameReceived -= board_FrameReceived;
}
}
}
<file_sep>/GoBot/GoBot/Threading/ThreadManager.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace GoBot.Threading
{
/// <summary>
/// Gestion de threads supervisés
/// </summary>
static class ThreadManager
{
#region Fields
private static List<ThreadLink> _threadsLink;
private static ThreadLink _linkCleanDeads;
#endregion
#region Properties
/// <summary>
/// Obtient une copie de la liste des threads actuellements suivis.
/// </summary>
public static ReadOnlyCollection<ThreadLink> ThreadsLink
{
get
{
return new List<ThreadLink>(_threadsLink).AsReadOnly();
}
}
#endregion
#region Constructors
public static void Init()
{
_threadsLink = new List<ThreadLink>();
_linkCleanDeads = CreateThread(link => CleanDeads());
_linkCleanDeads.Name = "Nettoyage des threads terminés";
_linkCleanDeads.StartInfiniteLoop(new TimeSpan(0, 0, 1));
}
#endregion
#region Public methods
/// <summary>
/// Crée un thread et retourne le lien.
/// </summary>
/// <param name="call">Appel à executer par le thread.</param>
/// <returns>Lien vers le thread créé.</returns>
public static ThreadLink CreateThread(ThreadLink.CallBack call)
{
ThreadLink link = new ThreadLink(call);
_threadsLink.Add(link);
return link;
}
///// <summary>
///// Lance un thread sur un appel unique.
///// </summary>
///// <param name="call">Appel à executer.</param>
///// <returns>Lien vers le thread d'execution.</returns>
//public static ThreadLink StartThread(ThreadLink.CallBack call)
//{
// ThreadLink link = new ThreadLink(call);
// _threadsLink.Add(link);
// link.StartThread();
// return link;
//}
///// <summary>
///// Lance un thread sur un nombre déterminé d'appels en boucle.
///// </summary>
///// <param name="call">Appel à executer.</param>
///// <param name="interval">Intervalle passif entre chaque appel.</param>
///// <param name="executions">Nombre d'executions à effectuer.</param>
///// <returns>Lien vers le thread d'execution.</returns>
//public static ThreadLink StartLoop(ThreadLink.CallBack call, TimeSpan interval, int executions)
//{
// ThreadLink link = new ThreadLink(call);
// _threadsLink.Add(link);
// link.StartLoop(interval, executions);
// return link;
//}
///// <summary>
///// Lance un thread sur un nombre indéterminé d'appels en boucle.
///// </summary>
///// <param name="call">Appel à executer.</param>
///// <param name="interval">Intervalle passif entre chaque appel.</param>
///// <returns>Lien vers le thread d'execution.</returns>
//public static ThreadLink StartInfiniteLoop(ThreadLink.CallBack call, TimeSpan interval)
//{
// ThreadLink link = new ThreadLink(call);
// _threadsLink.Add(link);
// link.StartInfiniteLoop(interval);
// return link;
//}
/// <summary>
/// Demande à chaque thread de se couper. L'extinction doit être réalisée par la méthode appellée en testant si le lien vers le thread a été annulé.
/// Patiente jusqu'à la fin d'execution de tous les threads pendant un certain temps.
/// Cette durée représente la durée totale d'attente et donc représente la cumul d'attente de fin de chaque thread.
/// </summary>
/// <param name="timeout">Nombre de millisecondes maximum à attendre.</param>
/// <returns>Retourne vrai si tous les threads ont correctement été terminés avant le timeout.</returns>
public static bool ExitAll(int timeout = 5000)
{
_threadsLink.ForEach(t => t.Cancel());
// Le timeout est global, donc tout le monde doit avoir terminé avant la fin
Stopwatch sw = Stopwatch.StartNew();
bool ended = true;
_threadsLink.ForEach(t => ended = ended && t.WaitEnd((int)Math.Max(0, timeout - sw.ElapsedMilliseconds)));
return ended;
}
#endregion
#region Private methods
/// <summary>
/// Permet de supprimer les liens vers les threads terminés depuis un certain temps.
/// </summary>
private static void CleanDeads()
{
_threadsLink.RemoveAll(t => t.Ended && t.EndDate < (DateTime.Now - new TimeSpan(0, 1, 0)));
}
private static void PrintThreads()
{
Console.WriteLine("--------------------------------------------");
foreach (ThreadLink l in ThreadManager.ThreadsLink)
{
Console.WriteLine(l.ToString());
}
}
#endregion
}
}<file_sep>/GoBot/GoBot/IHM/Pages/PageReglageAsserv.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PageReglageAsserv : UserControl
{
private Robot Robot { get; set; }
public PageReglageAsserv()
{
InitializeComponent();
numCoeffP.Value = Config.CurrentConfig.GRCoeffP;
numCoeffI.Value = Config.CurrentConfig.GRCoeffI;
numCoeffD.Value = Config.CurrentConfig.GRCoeffD;
this.numCoeffD.ValueChanged += new System.EventHandler(this.btnOk_Click);
this.numCoeffI.ValueChanged += new System.EventHandler(this.btnOk_Click);
this.numCoeffP.ValueChanged += new System.EventHandler(this.btnOk_Click);
Robot = Robots.MainRobot;
}
private void btnOk_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link => EnvoiTestPid(link)).StartThread();
}
private void EnvoiTestPid(ThreadLink link)
{
link.RegisterName();
Robot.SendPID((int)numCoeffP.Value, (int)numCoeffI.Value, (int)numCoeffD.Value);
List<int>[] mesures = Robot.DiagnosticPID((int)numPasCodeurs.Value, SensAR.Avant, (int)numNbPoints.Value);
// Afficher les courbes
int derniereValeurGauche = mesures[0][mesures[0].Count - 1];
int derniereValeurDroite = mesures[1][mesures[1].Count - 1];
int premiereValeurGauche = mesures[0][0];
int premiereValeurDroite = mesures[1][0];
for (int i = 0; i < mesures[0].Count; i++)
mesures[0][i] = mesures[0][i] - premiereValeurGauche;
for (int i = 0; i < mesures[1].Count; i++)
mesures[1][i] = mesures[1][i] - premiereValeurDroite;
if (derniereValeurGauche == 0)
derniereValeurGauche = 1;
if (derniereValeurDroite == 0)
derniereValeurDroite = 1;
double depassementGauchePositif = (mesures[0].Max() - (int)numPasCodeurs.Value) / (double)numPasCodeurs.Value * 100;
double depassementDroitePositif = (mesures[1].Max() - (int)numPasCodeurs.Value) / (double)numPasCodeurs.Value * 100;
int tempsGaucheStable = mesures[0].Count - 1;
while (tempsGaucheStable > 0 && mesures[0][tempsGaucheStable] < mesures[0][mesures[0].Count - 1] * 1.05 && mesures[0][tempsGaucheStable] > mesures[0][mesures[0].Count - 1] * 0.95)
tempsGaucheStable--;
int tempsDroiteStable = mesures[1].Count - 1;
while (tempsDroiteStable > 0 && mesures[1][tempsDroiteStable] < mesures[1][mesures[1].Count - 1] * 1.05 && mesures[1][tempsDroiteStable] > mesures[1][mesures[1].Count - 1] * 0.95)
tempsDroiteStable--;
this.InvokeAuto(() =>
{
lblTpsStabilisationGauche.Text = tempsGaucheStable + "ms";
lblTpsStabilisationDroite.Text = tempsDroiteStable + "ms";
lblOvershootGauche.Text = depassementGauchePositif.ToString("0.00") + "%";
lblOvershootDroite.Text = depassementDroitePositif.ToString("0.00") + "%";
lblValeurFinGauche.Text = mesures[0][mesures[0].Count - 1].ToString();
lblValeurFinDroite.Text = mesures[1][mesures[1].Count - 1].ToString();
ctrlGraphique.DeleteCurve("Roue droite");
ctrlGraphique.DeleteCurve("Roue gauche");
for (int i = 0; i < mesures[0].Count; i++)
{
if (boxMoyenne.Checked && i > 1 && i < mesures[0].Count - 2)
{
double valeur = (mesures[0][i - 2] + mesures[0][i - 1] + mesures[0][i] + mesures[0][i + 1] + mesures[0][i + 2]) / 5.0;
ctrlGraphique.AddPoint("Roue gauche", valeur, Color.Blue);
}
else
ctrlGraphique.AddPoint("Roue gauche", mesures[0][i], Color.Blue);
}
for (int i = 0; i < mesures[1].Count; i++)
{
if (boxMoyenne.Checked && i > 1 && i < mesures[1].Count - 2)
{
double valeur = (mesures[1][i - 2] + mesures[1][i - 1] + mesures[1][i] + mesures[1][i + 1] + mesures[1][i + 2]) / 5.0;
ctrlGraphique.AddPoint("Roue droite", valeur, Color.Green);
}
else
ctrlGraphique.AddPoint("Roue droite", mesures[1][i], Color.Green);
}
ctrlGraphique.DrawCurves();
});
Robot.DiagnosticPID((int)numPasCodeurs.Value, SensAR.Arriere, (int)numNbPoints.Value);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Forms/FenNomArchivage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class FenNomArchivage : Form
{
public String Nom { get; set; }
public bool OK { get; set; }
public FenNomArchivage()
{
InitializeComponent();
OK = false;
}
private void FenNomArchivage_Load(object sender, EventArgs e)
{
lblDate.Text = Nom;
}
private void btnOk_Click(object sender, EventArgs e)
{
Nom = txtNom.Text;
OK = true;
this.Close();
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Arms.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actionneurs
{
class Arms
{
protected ArmLeft _leftArm;
protected ArmRight _rightArm;
public Arms()
{
_leftArm = new ArmLeft();
_rightArm = new ArmRight();
}
public void DoOpenLeft()
{
_leftArm.SendPosition(_leftArm.PositionOpen);
}
public void DoCloseLeft()
{
_leftArm.SendPosition(_leftArm.PositionClose);
}
public void DoOpenRight()
{
_rightArm.SendPosition(_rightArm.PositionOpen);
}
public void DoCloseRight()
{
_rightArm.SendPosition(_rightArm.PositionClose);
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Elevators.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using Geometry;
using Geometry.Shapes;
using GoBot.BoardContext;
using GoBot.Devices;
using GoBot.GameElements;
using GoBot.Threading;
namespace GoBot.Actionneurs
{
class ElevatorRight : Elevator
{
public ElevatorRight()
{
_servoPush = Config.CurrentConfig.ServoPushArmRight;
_servoLocker = Config.CurrentConfig.ServoLockerRight;
_servoGraber = Config.CurrentConfig.ServoGrabberRight;
_makeVacuum = ActuatorOnOffID.MakeVacuumRightFront;
_openVacuum = ActuatorOnOffID.OpenVacuumRightFront;
_pressure = SensorOnOffID.PressureSensorRightFront;
_elevator = Config.CurrentConfig.MotorElevatorRight;
_sensor = SensorOnOffID.PresenceBuoyRight;
}
protected override RealPoint GetEntryFrontPoint()
{
return new RealPoint(Robots.MainRobot.Position.Coordinates.X + 100, Robots.MainRobot.Position.Coordinates.Y + 90).Rotation(new AngleDelta(Robots.MainRobot.Position.Angle), Robots.MainRobot.Position.Coordinates);
}
protected override RealPoint GetEntryBackPoint()
{
return new RealPoint(Robots.MainRobot.Position.Coordinates.X - 100, Robots.MainRobot.Position.Coordinates.Y + 90).Rotation(new AngleDelta(Robots.MainRobot.Position.Angle), Robots.MainRobot.Position.Coordinates);
}
}
class ElevatorLeft : Elevator
{
public ElevatorLeft()
{
_servoPush = Config.CurrentConfig.ServoPushArmLeft;
_servoLocker = Config.CurrentConfig.ServoLockerLeft;
_servoGraber = Config.CurrentConfig.ServoGrabberLeft;
_makeVacuum = ActuatorOnOffID.MakeVacuumLeftFront;
_openVacuum = ActuatorOnOffID.OpenVacuumLeftFront;
_pressure = SensorOnOffID.PressureSensorLeftFront;
_elevator = Config.CurrentConfig.MotorElevatorLeft;
_sensor = SensorOnOffID.PresenceBuoyRight;
}
protected override RealPoint GetEntryFrontPoint()
{
return new RealPoint(Robots.MainRobot.Position.Coordinates.X + 100, Robots.MainRobot.Position.Coordinates.Y - 90).Rotation(new AngleDelta(Robots.MainRobot.Position.Angle), Robots.MainRobot.Position.Coordinates);
}
protected override RealPoint GetEntryBackPoint()
{
return new RealPoint(Robots.MainRobot.Position.Coordinates.X - 100, Robots.MainRobot.Position.Coordinates.Y - 90).Rotation(new AngleDelta(Robots.MainRobot.Position.Angle), Robots.MainRobot.Position.Coordinates);
}
}
abstract class Elevator
{
protected bool _isInitialized;
protected ServoPushArm _servoPush;
protected ServoLocker _servoLocker;
protected ServoGrabber _servoGraber;
protected ActuatorOnOffID _makeVacuum, _openVacuum;
protected SensorOnOffID _pressure;
protected MotorElevator _elevator;
protected SensorOnOffID _sensor;
protected List<Color> _buoysSecond; // 0 = en haut...1...2 = étages inférieurs
protected List<Color> _buoysFirst; // 0 = en haut...1...2...3 = En bas, non monté
protected List<Tuple<PositionLoad, PositionFloor>> _pickupOrder;
protected List<Tuple<PositionLoad, PositionFloor>> _dropoffOrder;
protected bool _isBusy;
protected bool _grabberOpened;
protected bool _armed;
protected enum PositionLoad
{
First,
Second
}
protected enum PositionFloor
{
Floor3 = 0,
Floor2,
Floor1,
Ground
}
public Elevator()
{
_isInitialized = false;
_grabberOpened = false;
_armed = false;
_buoysSecond = Enumerable.Repeat(Color.Transparent, 3).ToList();
_buoysFirst = Enumerable.Repeat(Color.Transparent, 4).ToList();
_pickupOrder = new List<Tuple<PositionLoad, PositionFloor>>();
_pickupOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor3));
_pickupOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor2));
_pickupOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor1));
_pickupOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor3));
_pickupOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor2));
_pickupOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor1));
_pickupOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Ground));
_dropoffOrder = new List<Tuple<PositionLoad, PositionFloor>>();
_dropoffOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Ground));
_dropoffOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor1));
_dropoffOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor2));
_dropoffOrder.Add(Tuple.Create(PositionLoad.First, PositionFloor.Floor3));
_dropoffOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor1));
_dropoffOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor2));
_dropoffOrder.Add(Tuple.Create(PositionLoad.Second, PositionFloor.Floor3));
}
public List<Color> LoadFirst => _buoysFirst;
public List<Color> LoadSecond => _buoysSecond;
public bool GrabberOpened => _grabberOpened;
public bool Armed
{
get { return _armed; }
set { _armed = value; }
}
public void FillWith(Color c)
{
_buoysFirst[(int)PositionFloor.Floor3] = c;
_buoysFirst[(int)PositionFloor.Floor2] = c;
_buoysFirst[(int)PositionFloor.Floor1] = c;
_buoysFirst[(int)PositionFloor.Ground] = c;
_buoysSecond[(int)PositionFloor.Floor3] = c;
_buoysSecond[(int)PositionFloor.Floor2] = c;
_buoysSecond[(int)PositionFloor.Floor1] = c;
}
public bool CanStoreMore => CountTotal < 7;
public int CountTotal => _buoysSecond.Concat(_buoysFirst).Where(b => b != Color.Transparent).Count();
public int CountSecond => _buoysSecond.Where(b => b != Color.Transparent).Count();
public int CountFirst => _buoysFirst.Where(b => b != Color.Transparent).Count();
public int CountRed => _buoysFirst.Where(b => b == Buoy.Red).Count();
public int CountGreen => _buoysFirst.Where(b => b == Buoy.Green).Count();
public static int MaxLoad => 7;
public void DoGrabOpen()
{
_servoGraber.SendPosition(_servoGraber.PositionOpen);
_grabberOpened = true;
}
public void DoTakeLevel0(Color c)
{
DoAirLock();
DoGrabClose();
BuoySet(Tuple.Create(PositionLoad.First, PositionFloor.Ground), c);
}
public void DoStoreBack(Color c)
{
DoAirLock();
DoGrabClose();
if (WaitSomething())
{
DoStoreBackColor(c);
}
else
{
DoAirUnlock();
}
DoGrabClose();
}
public void DoGrabRelease()
{
_servoGraber.SendPosition(_servoGraber.PositionRelease);
_grabberOpened = false;
}
public void DoGrabClose()
{
_servoGraber.SendPosition(_servoGraber.PositionClose);
_grabberOpened = false;
}
public void DoGrabHide()
{
_servoGraber.SendPosition(_servoGraber.PositionHide);
_grabberOpened = false;
}
public void DoLockerEngage()
{
_servoLocker.SendPosition(_servoLocker.PositionEngage);
}
public void DoStoreActuators()
{
DoLockerEngage();
DoElevatorInit();
DoElevatorGround();
DoLockerDisengage();
DoPushInside();
}
public void DoLockerDisengage()
{
_servoLocker.SendPosition(_servoLocker.PositionDisengage);
}
public void DoLockerMaintain()
{
_servoLocker.SendPosition(_servoLocker.PositionMaintain);
}
public void DoPushInside()
{
_servoPush.SendPosition(_servoPush.PositionClose);
Thread.Sleep(750); // TODO régler la tempo
}
public void DoPushInsideFast()
{
_servoPush.SendPosition(_servoPush.PositionClose);
}
public void DoPushLight()
{
_servoPush.SendPosition(_servoPush.PositionLight);
}
public void DoPushOutside()
{
_servoPush.SendPosition(_servoPush.PositionOpen);
Thread.Sleep(750); // TODO régler la tempo
}
public void DoPushOutsideFast()
{
_servoPush.SendPosition(_servoPush.PositionOpen);
}
public void DoAirLock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, true);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, false);
_servoLocker.SendPosition(_servoLocker.PositionEngage);
}
public void DoAirUnlock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, false);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, true);
_servoLocker.SendPosition(_servoLocker.PositionDisengage);
}
public void DoAirUnlockDropoff()
{
_servoLocker.SendPosition(_servoLocker.PositionEngage);
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, false);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, true);
Thread.Sleep(100);
_servoLocker.SendPosition(_servoLocker.PositionDisengage);
}
public void DoElevatorInit()
{
_elevator.OriginInit();
_isInitialized = true;
}
public bool HasSomething()
{
return Robots.MainRobot.ReadSensorOnOff(_pressure);
}
public void DoElevatorStop()
{
_elevator.Stop(StopMode.Abrupt);
}
public void DoElevatorFree()
{
_elevator.Stop(StopMode.Freely);
}
public void DoElevatorGround()
{
if (!_isInitialized) DoElevatorInit();
_elevator.SendPosition(_elevator.PositionFloor0);
}
public void DoElevatorFloor1()
{
if (!_isInitialized) DoElevatorInit();
_elevator.SendPosition(_elevator.PositionFloor1);
}
public void DoElevatorFloor2()
{
if (!_isInitialized) DoElevatorInit();
_elevator.SendPosition(_elevator.PositionFloor2);
}
public void DoElevatorFloor3()
{
if (!_isInitialized) DoElevatorInit();
_elevator.SendPosition(_elevator.PositionFloor3);
}
public void DoDemoLoad3()
{
ThreadLink left, right;
Robots.MainRobot.SetSpeedSlow();
while (CountFirst < 3)
{
Robots.MainRobot.Move(85);
Actionneur.ElevatorLeft.DoElevatorGround();
Actionneur.ElevatorRight.DoElevatorGround();
left = ThreadManager.CreateThread(link => Actionneur.ElevatorLeft.DoSequencePickup());
right = ThreadManager.CreateThread(link => Actionneur.ElevatorRight.DoSequencePickup());
left.StartThread();
right.StartThread();
left.WaitEnd();
right.WaitEnd();
}
Robots.MainRobot.SetSpeedFast();
}
public void DoDemoLoad7()
{
ThreadLink left, right;
while (CountTotal < 7)
{
Actionneur.ElevatorLeft.DoGrabOpen();
Actionneur.ElevatorRight.DoGrabOpen();
Robots.MainRobot.Move(85);
Actionneur.ElevatorLeft.DoElevatorGround();
Actionneur.ElevatorRight.DoElevatorGround();
left = ThreadManager.CreateThread(link => Actionneur.ElevatorLeft.DoSequencePickup());
right = ThreadManager.CreateThread(link => Actionneur.ElevatorRight.DoSequencePickup());
left.StartThread();
right.StartThread();
left.WaitEnd();
right.WaitEnd();
}
}
public void DoDemoPickup()
{
Robots.MainRobot.SetSpeedSlow();
DoGrabOpen();
Thread.Sleep(200);
Robots.MainRobot.MoveForward(85);
DoSequencePickupColorThread(Buoy.Red);
Thread.Sleep(350);
Robots.MainRobot.MoveBackward(85);
Robots.MainRobot.SetSpeedFast();
}
public void DoDemoUnload7()
{
ThreadLink left, right;
while (CountTotal > 0)
{
Robots.MainRobot.Move(-85);
left = ThreadManager.CreateThread(link => Actionneur.ElevatorLeft.DoSequenceDropOff());
right = ThreadManager.CreateThread(link => Actionneur.ElevatorRight.DoSequenceDropOff());
left.StartThread();
right.StartThread();
left.WaitEnd();
right.WaitEnd();
}
}
public void DoSequencePickupColor(Color c)
{
DoAirLock();
DoGrabClose();
if (WaitSomething())
{
DoLockerMaintain();
DoStoreColor(c);
DoGrabClose();
}
else
{
DoAirUnlock();
}
}
public void DoSequencePickupColorThread(Color c)
{
DoAirLock();
DoGrabClose();
Thread.Sleep(250);
ThreadManager.CreateThread(link =>
{
while (_isBusy) ;
_isBusy = true;
if (WaitSomething())
{
DoLockerMaintain();
DoStoreColor(c);
DoGrabClose();
}
else
{
DoAirUnlock();
}
_isBusy = false;
}).StartThread();
}
public void DoSequencePickup()
{
DoAirLock();
DoGrabClose();
if (WaitSomething())
{
DoLockerMaintain();
DoStoreColor(Buoy.Red); // TODO détecter la couleur avec le capteur de couleur
}
else
{
Console.WriteLine("Fin de l'attente, pas de gobelet détecté");
DoAirUnlock();
}
DoGrabClose();
}
private void BuoySet(Tuple<PositionLoad, PositionFloor> place, Color c)
{
if (place.Item1 == PositionLoad.First)
_buoysFirst[(int)place.Item2] = c;
else
_buoysSecond[(int)place.Item2] = c;
}
private void BuoyRemove(Tuple<PositionLoad, PositionFloor> place)
{
if (place.Item1 == PositionLoad.First)
_buoysFirst[(int)place.Item2] = Color.Transparent;
else
_buoysSecond[(int)place.Item2] = Color.Transparent;
}
private bool IsPositionLoadSecond()
{
return _servoPush.GetLastPosition() == _servoPush.PositionOpen;
}
public void DoStoreColor(Color c)
{
DoElevatorStop();
DoGrabRelease();
Tuple<PositionLoad, PositionFloor> place = PlaceToPickup();
DoPlaceLoad(place.Item1, true);
DoPlaceFloor(place.Item2);
DoAirUnlock();
BuoySet(place, c);
DoElevatorGround();
DoPlaceLoad(PositionLoad.First, false);
}
public void DoStoreBackColor(Color c)
{
DoElevatorStop();
DoGrabRelease();
Tuple<PositionLoad, PositionFloor> place = PlaceToPickupBack();
DoPlaceLoad(place.Item1, true);
DoPlaceFloor(place.Item2);
DoAirUnlock();
BuoySet(place, c);
DoElevatorGround();
DoPlaceLoad(PositionLoad.First, false);
}
public void DoStorageReset()
{
_buoysSecond = Enumerable.Repeat(Color.Transparent, 3).ToList();
_buoysFirst = Enumerable.Repeat(Color.Transparent, 4).ToList();
}
public bool WaitSomething(int timeout = 1000)
{
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeout && !HasSomething())
Thread.Sleep(50);
return HasSomething();
}
public bool DoSearchBuoy(Color color, IShape containerZone = null)
{
List<RealPoint> pts = AllDevices.LidarGround.GetPoints();
pts = pts.Where(o => GameBoard.IsInside(o, 50)).ToList();
if (containerZone != null)
{
pts = pts.Where(o => containerZone.Contains(o)).ToList();
}
List<List<RealPoint>> groups = pts.GroupByDistance(80);
List<Tuple<Circle, Color>> buoys = new List<Tuple<Circle, Color>>();
bool output = false;
for (int i = 0; i < groups.Count; i++)
{
if (groups[i].Count > 4)
{
RealPoint center = groups[i].GetBarycenter();
double var = Math.Sqrt(groups[i].Average(p => p.Distance(center) * p.Distance(center))) * 2;
buoys.Add(Tuple.Create(new Circle(center, var), var > 35 ? Buoy.Green : Buoy.Red));
}
}
if (buoys.Count > 0 && buoys.Exists(b => b.Item2 == color))
{
Circle buoy = buoys.OrderBy(b => b.Item1.Distance(Robots.MainRobot.Position.Coordinates)).First(b => b.Item2 == color).Item1;
RealPoint entryFrontPoint = GetEntryFrontPoint();
RealPoint entryBackPoint = GetEntryBackPoint();
AngleDelta bestAngle = 0;
double bestError = int.MaxValue;
for (AngleDelta i = 0; i < 360; i++)
{
Segment inter = new Segment(entryBackPoint.Rotation(i, Robots.MainRobot.Position.Coordinates), buoy.Center);
double error = inter.Distance(entryFrontPoint.Rotation(i, Robots.MainRobot.Position.Coordinates));
if (error < bestError)
{
bestError = error;
bestAngle = i;
}
}
bestAngle = -bestAngle.Modulo();
if (bestAngle < 0)
Robots.MainRobot.PivotRight(-bestAngle);
else
Robots.MainRobot.PivotLeft(bestAngle);
DoGrabOpen();
int dist = (int)GetEntryFrontPoint().Distance(buoy.Center) + 50;
Robots.MainRobot.Move(dist);
DoSequencePickupColor(color); // TODO Détecter la couleur au lidar ?
//DoSequencePickup();// ... ou pas...
DoGrabClose();
Robots.MainRobot.Move(-dist);
//DoSearchBuoy();
output = true;
if (Robots.Simulation)
GameBoard.RemoveVirtualBuoy(buoy.Center);
}
else
{
output = false;
}
return output;
}
protected abstract RealPoint GetEntryFrontPoint();
protected abstract RealPoint GetEntryBackPoint();
public bool DetectSomething()
{
return Robots.MainRobot.ReadSensorOnOff(_sensor);
}
public void DoDemoGrabLoop()
{
int delay = 220;
DoGrabOpen();
Thread.Sleep(delay);
DoGrabClose();
Thread.Sleep(delay);
DoGrabOpen();
Thread.Sleep(delay);
DoGrabClose();
Thread.Sleep(delay);
}
public void DoDemoDropoff()
{
Robots.MainRobot.SetSpeedSlow();
DoSequenceDropOff();
DoGrabRelease();
Robots.MainRobot.MoveForward(85);
Robots.MainRobot.MoveBackward(85);
Robots.MainRobot.SetSpeedFast();
}
public Color DoSequenceDropOff()
{
DoElevatorStop();
DoGrabRelease();
Tuple<PositionLoad, PositionFloor> place = PlaceToDropoff();
Color c = GetColor(place);
DoPlaceLoad(place.Item1, true);
DoPlaceFloor(place.Item2);
if (place.Item2 != PositionFloor.Ground)
{
DoAirLock();
WaitSomething(500);
DoLockerMaintain();
Robots.MainRobot.SetMotorAtPosition(_elevator.ID, _elevator.PositionFloor0, true);
}
DoAirUnlockDropoff();
BuoyRemove(place);
return c;
}
private void DoPlaceLoad(PositionLoad load, bool wait)
{
if (IsPositionLoadSecond())
{
if (load == PositionLoad.First)
{
DoElevatorGround();
DoPushInside();
if (wait) Thread.Sleep(750); // TODO régler la tempo
}
}
else
{
if (load == PositionLoad.Second)
{
DoElevatorGround();
DoPushOutside();
if (wait) Thread.Sleep(750); // TODO régler la tempo
}
}
}
private void DoPlaceFloor(PositionFloor floor)
{
switch (floor)
{
case PositionFloor.Ground:
DoElevatorGround();
break;
case PositionFloor.Floor1:
DoElevatorFloor1();
break;
case PositionFloor.Floor2:
DoElevatorFloor2();
break;
case PositionFloor.Floor3:
DoElevatorFloor3();
break;
}
}
public void DoSequenceDropOff3()
{
Robots.MainRobot.SetSpeedSlow();
DoSequenceDropOff();
Robots.MainRobot.Move(-85, false);
DoSequenceDropOff();
Robots.MainRobot.Move(-85, false);
DoSequenceDropOff();
Robots.MainRobot.Move(-85, false);
Robots.MainRobot.SetSpeedFast();
}
private Tuple<PositionLoad, PositionFloor> PlaceToPickup()
{
return _pickupOrder.Find(o => (o.Item1 == PositionLoad.First ? _buoysFirst[(int)o.Item2] : _buoysSecond[(int)o.Item2]) == Color.Transparent);
}
private Tuple<PositionLoad, PositionFloor> PlaceToPickupBack()
{
return _pickupOrder.Find(o => o.Item1 == PositionLoad.Second && _buoysSecond[(int)o.Item2] == Color.Transparent);
}
private Tuple<PositionLoad, PositionFloor> PlaceToDropoff()
{
return _dropoffOrder.Find(o => (o.Item1 == PositionLoad.First ? _buoysFirst[(int)o.Item2] : _buoysSecond[(int)o.Item2]) != Color.Transparent);
}
private Color GetColor(Tuple<PositionLoad, PositionFloor> place)
{
if (place.Item1 == PositionLoad.First)
return _buoysFirst[(int)place.Item2];
else
return _buoysSecond[(int)place.Item2];
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyRandomMoves.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Geometry;
using Geometry.Shapes;
using AStarFolder;
namespace GoBot.Strategies
{
/// <summary>
/// Stratégie qui consiste à se déplacer alétoirement sur la piste
/// </summary>
class StrategyRandomMoves : Strategy
{
Random rand = new Random();
public override bool AvoidElements => false;
protected override void SequenceBegin()
{
Robots.MainRobot.SpeedConfig.SetParams(500, 2000, 2000, 800, 2000, 2000);
// Sortir ICI de la zone de départ pour commencer
}
protected override void SequenceCore()
{
while (IsRunning)
{
int next = rand.Next(Robots.MainRobot.Graph.Nodes.Count);
if (!((Node)Robots.MainRobot.Graph.Nodes[next]).Passable)
continue;
Position destination = new Position(rand.Next(360), ((Node)Robots.MainRobot.Graph.Nodes[next]).Position);
Robots.MainRobot.Historique.Log("Nouvelle destination " + destination.ToString());
Robots.MainRobot.GoToPosition(destination);
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/RealPointWithSegment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class RealPointWithSegment
{
public static bool Contains(RealPoint containingPoint, Segment containedSegment)
{
// Un point qui contient un segment c'est que les deux extremités du segment sont ce même point...
return (containingPoint == containedSegment.StartPoint) && (containingPoint == containedSegment.EndPoint);
}
public static bool Cross(RealPoint point, Segment segment)
{
return SegmentWithRealPoint.Cross(segment, point);
}
public static double Distance(RealPoint point, Segment segment)
{
return SegmentWithRealPoint.Distance(segment, point);
}
public static List<RealPoint> GetCrossingPoints(RealPoint point, Segment segment)
{
return SegmentWithRealPoint.GetCrossingPoints(segment, point);
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Lifter.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Devices;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GoBot.Actionneurs
{
class Lifter
{
private List<ServoClamp> _clamps;
private ServoLifter _lifter;
private ServoTilter _tilter;
private List<Color> _load;
private bool _tilterStored, _lifterStored;
public Lifter()
{
_clamps = new List<ServoClamp> { Config.CurrentConfig.ServoClamp1, Config.CurrentConfig.ServoClamp2, Config.CurrentConfig.ServoClamp3, Config.CurrentConfig.ServoClamp4, Config.CurrentConfig.ServoClamp5 };
_lifter = Config.CurrentConfig.ServoLifter;
_tilter = Config.CurrentConfig.ServoTilter;
_tilterStored = true;
_lifterStored = true;
}
public bool Loaded => _load != null;
public bool Opened => !_tilterStored || !_lifterStored;
public List<Color> Load
{
get { return _load; }
set { _load = value; }
}
public void DoOpenAll()
{
_clamps.ForEach(o => o.SendPosition(o.PositionOpen));
}
public void DoMaintainAll()
{
_clamps.ForEach(o => o.SendPosition(o.PositionMaintain));
}
public void DoCloseAll()
{
_clamps.ForEach(o => o.SendPosition(o.PositionClose));
}
public void DoStoreAll()
{
_clamps.ForEach(o => o.SendPosition(o.PositionStore));
}
public void DoDisableAll()
{
_clamps.ForEach(o => o.DisableTorque());
}
public void DoLoop()
{
for (int i = 0; i < 10; i++)
{
_clamps.ForEach(o =>
{
o.SendPosition(o.PositionOpen);
Thread.Sleep(100);
});
_clamps.ForEach(o =>
{
o.SendPosition(o.PositionStore);
Thread.Sleep(100);
});
}
}
public void DoLifterPositionExtract()
{
_lifterStored = false;
_lifter.SendPosition(_lifter.PositionExtract);
}
public void DoLifterPositionStore()
{
_lifterStored = true;
_lifter.SendPosition(_lifter.PositionStore);
}
public void DoTilterPositionStore()
{
_tilterStored = true;
_tilter.SendPosition(_tilter.PositionStore);
}
public void DoTilterPositionPickup()
{
_tilterStored = false;
_tilter.SendPosition(_tilter.PositionPickup);
}
public void DoTilterPositionExtract()
{
_tilterStored = false;
_tilter.SendPosition(_tilter.PositionExtract);
}
public void DoTilterPositionDropoff()
{
_tilterStored = false;
_tilter.SendPosition(_tilter.PositionDropoff);
}
public void DoSequencePickup()
{
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.Recalibration(SensAR.Arriere, true, true);
Robots.MainRobot.SetSpeedSlow();
Robots.MainRobot.Move(20);
DoOpenAll();
DoTilterPositionPickup();
Thread.Sleep(500);
DoCloseAll();
Thread.Sleep(400);
DoLifterPositionExtract();
Thread.Sleep(450);
Robots.MainRobot.Move(100);
DoLifterPositionStore();
Thread.Sleep(150);
DoTilterPositionStore();
Robots.MainRobot.SetSpeedFast();
}
public void DoSequenceDropOff()
{
DoTilterPositionDropoff();
Thread.Sleep(500);
DoOpenAll();
DoTilterPositionStore();
Thread.Sleep(150);
DoStoreAll();
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Flags.cs
namespace GoBot.Actionneurs
{
class Flags
{
bool _leftOpened, _rightOpened;
public bool LeftOpened => _leftOpened;
public bool RightOpened => _rightOpened;
public Flags()
{
_leftOpened = false;
_rightOpened = false;
}
public void DoCloseRight()
{
Config.CurrentConfig.ServoFlagRight.SendPosition(Config.CurrentConfig.ServoFlagRight.PositionClose);
_rightOpened = false;
}
public void DoOpenRight()
{
Config.CurrentConfig.ServoFlagRight.SendPosition(Config.CurrentConfig.ServoFlagRight.PositionOpen);
_rightOpened = true;
}
public void DoCloseLeft()
{
Config.CurrentConfig.ServoFlagLeft.SendPosition(Config.CurrentConfig.ServoFlagLeft.PositionClose);
_leftOpened = false;
}
public void DoOpenLeft()
{
Config.CurrentConfig.ServoFlagLeft.SendPosition(Config.CurrentConfig.ServoFlagLeft.PositionOpen);
_leftOpened = true;
}
}
}
<file_sep>/GoBot/Extensions/ColorPlus.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
internal struct ColorPlus
{
#region Fields
private Color _innerColor;
#endregion
#region Properties
/// <summary>
/// Obtient ou définit la couleur selon sa valeur 32 bits.
/// </summary>
public int ARGB
{
get
{
return _innerColor.ToArgb();
}
set
{
_innerColor = Color.FromArgb(value);
}
}
/// <summary>
/// Obtient ou définit la transparence de la couleur (0 = Transparent, 255 = Opaque).
/// </summary>
public byte Alpha
{
get
{
return _innerColor.A;
}
set
{
_innerColor = Color.FromArgb(value, _innerColor.R, _innerColor.G, _innerColor.B);
}
}
/// <summary>
/// Obtient ou définit la composante rouge de la couleur.
/// </summary>
public byte Red
{
get
{
return _innerColor.R;
}
set
{
_innerColor = Color.FromArgb(_innerColor.A, value, _innerColor.G, _innerColor.B);
}
}
/// <summary>
/// Obtient ou définit la composante verte de la couleur.
/// </summary>
public byte Green
{
get
{
return _innerColor.G;
}
set
{
_innerColor = Color.FromArgb(_innerColor.A, _innerColor.R, value, _innerColor.B);
}
}
/// <summary>
/// Obtient ou définit la composante bleue de la couleur.
/// </summary>
public byte Blue
{
get
{
return _innerColor.B;
}
set
{
_innerColor = Color.FromArgb(_innerColor.A, _innerColor.R, _innerColor.G, value);
}
}
/// <summary>
/// Obtient ou définit la teinte de la couleur (0° à 360°).
/// </summary>
public double Hue
{
get
{
return _innerColor.GetHue();
}
set
{
_innerColor = ColorPlus.FromAhsl(_innerColor.A, value, _innerColor.GetSaturation(), _innerColor.GetBrightness());
}
}
/// <summary>
/// Obtient ou définit la saturation de la couleur (0 = Terne, 1 = Vive).
/// </summary>
public double Saturation
{
get
{
return _innerColor.GetSaturation();
}
set
{
_innerColor = ColorPlus.FromAhsl(_innerColor.A, _innerColor.GetHue(), value, _innerColor.GetBrightness());
}
}
/// <summary>
/// Obtient ou définit la luminosité de la couleur (0 = Sombre, 1 = Claire)
/// </summary>
public double Lightness
{
get
{
return _innerColor.GetBrightness();
}
set
{
_innerColor = ColorPlus.FromAhsl(_innerColor.A, _innerColor.GetHue(), _innerColor.GetSaturation(), value);
}
}
#endregion
#region Factory
/// <summary>
/// Créée une couleur depuis les paramètres de rouge, bleu et vert.
/// </summary>
/// <param name="r">Composante rouge, de 0 à 255.</param>
/// <param name="g">Composante verte, de 0 à 255.</param>
/// <param name="b">Composante bleue, de 0 à 255.</param>
/// <returns>Couleur correspondante.</returns>
public static ColorPlus FromRgb(int r, int g, int b)
{
return FromArgb(255, r, g, b);
}
/// <summary>
/// Créée une couleur depuis les paramètres de transparence, rouge, bleu et vert.
/// </summary>
/// <param name="alpha">Transparence, de 0 à 255.</param>
/// <param name="r">Composante rouge, de 0 à 255.</param>
/// <param name="g">Composante verte, de 0 à 255.</param>
/// <param name="b">Composante bleue, de 0 à 255.</param>
/// <returns>Couleur correspondante.</returns>
public static ColorPlus FromArgb(int alpha, int r, int g, int b)
{
if (0 > alpha || 255 < alpha)
throw new ArgumentOutOfRangeException(nameof(alpha));
if (0 > r || 255 < r)
throw new ArgumentOutOfRangeException(nameof(r));
if (0 > g || 255 < g)
throw new ArgumentOutOfRangeException(nameof(g));
if (0 > b || 255 < b)
throw new ArgumentOutOfRangeException(nameof(b));
ColorPlus color = new ColorPlus();
color._innerColor = Color.FromArgb(alpha, r, g, b);
return color;
}
/// <summary>
/// Créée une couleur depuis les paramètres de teinte, saturation et luminosité.
/// </summary>
/// <param name="hue">Teinte de 0° à 360°.</param>
/// <param name="saturation">Saturation de 0 à 1.</param>
/// <param name="lighting">Luminosité de 0 à 1.</param>
/// <returns>Couleur correspondante.</returns>
public static ColorPlus FromHsl(double hue, double saturation, double lighting)
{
return FromAhsl(255, hue, saturation, lighting);
}
/// <summary>
/// Créée une couleur depuis les paramètres de transparence, teinte, saturation et luminosité.
/// </summary>
/// <param name="alpha">Transparence, de 0 à 255.</param>
/// <param name="hue">Teinte de 0° à 360°.</param>
/// <param name="saturation">Saturation de 0 à 1.</param>
/// <param name="lighting">Luminosité de 0 à 1.</param>
/// <returns>Couleur correspondante.</returns>
public static ColorPlus FromAhsl(int alpha, double hue, double saturation, double lighting)
{
if (0 > alpha || 255 < alpha)
throw new ArgumentOutOfRangeException(nameof(alpha));
if (0f > hue || 360f < hue)
throw new ArgumentOutOfRangeException(nameof(hue));
if (0f > saturation || 1f < saturation)
throw new ArgumentOutOfRangeException(nameof(saturation));
if (0f > lighting || 1f < lighting)
throw new ArgumentOutOfRangeException(nameof(lighting));
if (0 == saturation)
{
return Color.FromArgb(alpha, Convert.ToInt32(lighting * 255), Convert.ToInt32(lighting * 255), Convert.ToInt32(lighting * 255));
}
double fMax, fMid, fMin;
int sextant, iMax, iMid, iMin;
if (0.5 < lighting)
{
fMax = lighting - (lighting * saturation) + saturation;
fMin = lighting + (lighting * saturation) - saturation;
}
else
{
fMax = lighting + (lighting * saturation);
fMin = lighting - (lighting * saturation);
}
sextant = (int)Math.Floor(hue / 60f);
if (300f <= hue)
hue -= 360f;
hue /= 60f;
hue -= 2f * (double)Math.Floor(((sextant + 1f) % 6f) / 2f);
if (0 == sextant % 2)
fMid = hue * (fMax - fMin) + fMin;
else
fMid = fMin - hue * (fMax - fMin);
iMax = Convert.ToInt32(fMax * 255);
iMid = Convert.ToInt32(fMid * 255);
iMin = Convert.ToInt32(fMin * 255);
ColorPlus color = new ColorPlus();
switch (sextant)
{
case 1:
color._innerColor = Color.FromArgb(alpha, iMid, iMax, iMin);
break;
case 2:
color._innerColor = Color.FromArgb(alpha, iMin, iMax, iMid);
break;
case 3:
color._innerColor = Color.FromArgb(alpha, iMin, iMid, iMax);
break;
case 4:
color._innerColor = Color.FromArgb(alpha, iMid, iMin, iMax);
break;
case 5:
color._innerColor = Color.FromArgb(alpha, iMax, iMin, iMid);
break;
default:
color._innerColor = Color.FromArgb(alpha, iMax, iMid, iMin);
break;
}
return color;
}
/// <summary>
/// Retourne la couleur fluo équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur fluo.</returns>
public static ColorPlus GetFluo(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 1, 0.6);
}
/// <summary>
/// Retourne la couleur intense équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur intense.</returns>
public static ColorPlus GetIntense(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 1, 0.4);
}
/// <summary>
/// Retourne la couleur pastel équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur pastel.</returns>
public static ColorPlus GetPastel(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 1, 0.85);
}
/// <summary>
/// Retourne la couleur très estompée équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur très estompée.</returns>
public static ColorPlus GetVeryLight(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 1, 0.93);
}
/// <summary>
/// Retourne la couleur sombre équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur sombre.</returns>
public static ColorPlus GetDark(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 1, 0.3);
}
/// <summary>
/// Retourne la couleur terne équivalente.
/// </summary>
/// <param name="color">Couleur d'origine.</param>
/// <returns>Couleur terne.</returns>
public static ColorPlus GetDull(ColorPlus color)
{
return ColorPlus.FromHsl(color.Hue, 0.2, 0.75);
}
/// <summary>
/// Retourne la couleur connue la plus similaire à la couleur inconnue.
/// </summary>
/// <param name="unknown">Couleur inconnue.</param>
/// <param name="knowns">Couleurs connues.</param>
/// <returns>Couleur connue la plus proche de la couleur inconnue.</returns>
public static ColorPlus GuessColor(ColorPlus unknown, IEnumerable<ColorPlus> knowns)
{
return knowns.OrderBy(known => HueDelta(unknown, known)).First();
}
#endregion
#region Public methods
/// <summary>
/// Calcule la différence angulaire en degrés de la teinte entre deux couleurs.
/// </summary>
/// <param name="c1">Première couleur.</param>
/// <param name="c2">Deuxième couleur.</param>
/// <returns>Différence angulaire.</returns>
public static double HueDelta(ColorPlus c1, ColorPlus c2)
{
double d1 = Math.Abs(c1.Hue - c2.Hue);
double d2 = Math.Abs(c1.Hue - (c2.Hue - 360));
double d3 = Math.Abs(c1.Hue - (c2.Hue + 360));
return new double[] { d1, d2, d3 }.Min();
}
#endregion
#region Operators
public static implicit operator ColorPlus(Color color)
{
return new ColorPlus { _innerColor = color };
}
public static implicit operator Color(ColorPlus color)
{
return Color.FromArgb(color.Alpha, color.Red, color.Green, color.Blue);
}
public static implicit operator ColorPlus(int color)
{
return new ColorPlus { ARGB = color };
}
public static implicit operator int(ColorPlus color)
{
return color.ARGB;
}
public override string ToString()
{
return "{R = " + this.Red.ToString() + ", G = " + this.Green.ToString() + ", B = " + this.Blue.ToString() + "} - {H = " + this.Hue.ToString("0") + "°, S = " + (this.Saturation * 100).ToString("0") + "%, L = " + (this.Lightness * 100).ToString("0") + "%}";
}
#endregion
}
<file_sep>/GoBot/Geometry/README.txt
Le précision des calculs (et principalement pour valider une proximité ou comparer des données très proches) est volontairement bridée.
La constante RealPoint.PRECISION est à utiliser partout où on veut utiliser cette marge de précision. (Tests d'égalité, Tests unitaires, etc)
IShape.GetCrossingPoints
- Retourne une liste exhaustive et non dupliquée des croisements entre les deux formes.
- Si les formes ne se croisent pas, le résultat attendu est une liste vide.
- En cas de forme identique, le comportement est à définir par le concepteur, mais la liste doit contenir au minimum un point.
IShape.Contains
- Une forme contient forcément une forme identique
IShape.Cross
- Doit être utilisé plutôt que de tester si GetCrossingPoints retourne une liste vide
- Est implémenté le plus simplement possible, pour être moins couteux à l'appel que GetCrossingPoints
IShape.Distance
- Retourne la distance entre les deux points les plus proches du contour des deux formes concernées
- Retourne 0 si les formes se croisent
- Retourne 0 si les formes se contiennent<file_sep>/GoBot/GoBot/Movements/MovementRedDropoff.cs
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.Movements
{
class MovementRedDropoff : Movement
{
private RandomDropOff _randomDropOff;
public MovementRedDropoff(RandomDropOff dropoff)
{
_randomDropOff = dropoff;
Positions.Add(new Geometry.Position(90, new RealPoint(_randomDropOff.Position.X + (_randomDropOff.Position.X < 1500 ? 50 : -50), 730 + 600 - 30)));
}
public override bool CanExecute => !_randomDropOff.HasLoadOnBottom && Actionneur.Lifter.Loaded;
public override int Score
{
get
{
if (!_randomDropOff.HasLoadOnTop)
return 8;
else
return 22 - 8;
}
}
public override double Value => 2;
public override GameElement Element => _randomDropOff;
public override Robot Robot => Robots.MainRobot;
public override Color Color => _randomDropOff.Owner;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
Actionneur.Lifter.DoSequenceDropOff();
_randomDropOff.SetLoadBottom(Actionneur.Lifter.Load);
Actionneur.Lifter.Load = null;
GameBoard.AddObstacle(new Segment(new RealPoint(_randomDropOff.Position.X - 200, 525 + 600 - 30), new RealPoint(_randomDropOff.Position.X + 200, 525 + 600 - 30)));
if (_randomDropOff.Owner == GameBoard.ColorLeftBlue)
{
GameBoard.Elements.FindBuoy(new RealPoint(300, 1200)).IsAvailable = false;
GameBoard.Elements.FindBuoy(new RealPoint(450, 1100)).IsAvailable = false;
}
else
{
GameBoard.Elements.FindBuoy(new RealPoint(3000 - 300, 1200)).IsAvailable = false;
GameBoard.Elements.FindBuoy(new RealPoint(3000 - 450, 1100)).IsAvailable = false;
}
return true;
}
protected override void MovementEnd()
{
}
}
}
<file_sep>/GoBot/GoBot/BoardContext/Obstacles.cs
using Geometry.Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoBot.GameElements;
namespace GoBot.BoardContext
{
public class Obstacles
{
private List<IShape> _boardObstacles;
private Dictionary<ColorPlus, IEnumerable<IShape>> _colorObstacles;
private IEnumerable<IShape> _detectionObstacles;
private AllGameElements _elements;
public delegate void ObstaclesChangedDelegate();
public event ObstaclesChangedDelegate ObstaclesChanged;
public Obstacles(AllGameElements elements)
{
_boardObstacles = CreateBoardObstacles();
_colorObstacles = CreateColorObstacles();
_elements = elements;
_elements.ObstaclesChanged += _elements_ObstaclesChanged;
_detectionObstacles = new List<IShape>();
}
public IEnumerable<IShape> FromAll
{
get
{
IEnumerable<IShape> all = _boardObstacles;
all = all.Concat(_elements.AsObstacles);
if (_colorObstacles.ContainsKey(GameBoard.MyColor)) all = all.Concat(_colorObstacles[GameBoard.MyColor]);
if (_detectionObstacles != null) all = all.Concat(_detectionObstacles);
return all.ToList();
}
}
public IEnumerable<IShape> FromAllExceptBoard
{
get
{
IEnumerable<IShape> all = _elements.AsObstacles;
if (_colorObstacles.ContainsKey(GameBoard.MyColor)) all = all.Concat(_colorObstacles[GameBoard.MyColor]);
if (_detectionObstacles != null) all = all.Concat(_detectionObstacles);
return all.ToList();
}
}
public IEnumerable<IShape> FromBoardConstruction
{
get
{
return _boardObstacles.Skip(4).ToList(); // 4 = les 4 contours
}
}
public IEnumerable<IShape> FromBoard
{
get
{
return _boardObstacles;
}
}
public IEnumerable<IShape> FromColor
{
get
{
return _colorObstacles[GameBoard.MyColor];
}
}
public IEnumerable<IShape> FromDetection
{
get
{
return _detectionObstacles;
}
}
public IEnumerable<IShape> FromElements
{
get
{
return GameBoard.Elements.AsObstacles;
}
}
public void AddObstacle(IShape shape)
{
_boardObstacles.Add(shape);
}
public void SetDetections(IEnumerable<IShape> detections)
{
_detectionObstacles = detections;
this.OnObstaclesChanged();
}
protected void OnObstaclesChanged()
{
ObstaclesChanged?.Invoke();
}
private List<IShape> CreateBoardObstacles()
{
List<IShape> obstacles = new List<IShape>();
// Contours du plateau
obstacles.Add(new Segment(new RealPoint(0, 0), new RealPoint(GameBoard.Width - 4, 0)));
obstacles.Add(new Segment(new RealPoint(GameBoard.Width - 4, 0), new RealPoint(GameBoard.Width - 4, GameBoard.Height - 4)));
obstacles.Add(new Segment(new RealPoint(GameBoard.Width - 4, GameBoard.Height - 4), new RealPoint(0, GameBoard.Height - 4)));
obstacles.Add(new Segment(new RealPoint(0, GameBoard.Height - 4), new RealPoint(0, 0)));
// TODOEACHYEAR : créer les obstacles fixes du plateau
// Récifs
obstacles.Add(new PolygonRectangle(new RealPoint(889, 1850), 22, 150));
obstacles.Add(new PolygonRectangle(new RealPoint(1489, 1700), 22, 300));
obstacles.Add(new PolygonRectangle(new RealPoint(2089, 1850), 22, 150));
//Boussole
obstacles.Add(new PolygonRectangle(new RealPoint(3000/2-300/2, 0), 300, 30));
return obstacles;
}
private Dictionary<ColorPlus, IEnumerable<IShape>> CreateColorObstacles()
{
Dictionary<ColorPlus, IEnumerable<IShape>> obstacles = new Dictionary<ColorPlus, IEnumerable<IShape>>();
// TODOEACHYEAR : créer les obstacles fixes en fonction de la couleur (genre zones réservées à l'adversaire)
List<IShape> obsLeft = new List<IShape>();
List<IShape> obsRight = new List<IShape>();
//Bande de droite (zone de départ etc)
obsLeft.Add(new PolygonRectangle(new RealPoint(2550, 0), 450, 2000));
//Port secondaire
obsLeft.Add(new Circle(new RealPoint(1200, 1800), 150));
//Bande de gauche (zone de départ etc)
obsRight.Add(new PolygonRectangle(new RealPoint(0, 0), 450, 2000));
//Port secondaire
obsRight.Add(new Circle(new RealPoint(1800, 1800), 150));
obstacles.Add(GameBoard.ColorLeftBlue, obsLeft);
obstacles.Add(GameBoard.ColorRightYellow, obsRight);
return obstacles;
}
private void _elements_ObstaclesChanged()
{
this.OnObstaclesChanged();
}
}
}
<file_sep>/GoBot/GoBot/GameElements/GameElementZone.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Geometry.Shapes;
using System.Drawing;
using Geometry;
namespace GoBot.GameElements
{
public class GameElementZone : GameElement
{
/// <summary>
/// Construit une zone de jeu à partir de sa position et de son rayon
/// </summary>
/// <param name="position">Position du centre de la zone de jeu</param>
/// <param name="color">Couleur d'appartenance de la zone</param>
/// <param name="radius">Rayon de la zone</param>
public GameElementZone(RealPoint position, Color color, int radius)
: base(position, color, radius)
{
IsHover = false;
Owner = color;
}
/// <summary>
/// Peint l'élément sur le Graphic donné à l'échelle donnée
/// </summary>
/// <param name="g">Graphic sur lequel peindre</param>
/// <param name="scale">Echelle de peinture</param>
public override void Paint(Graphics g, WorldScale scale)
{
Pen pBlack = new Pen(Color.Black);
Pen pWhite = new Pen(Color.White);
Pen pWhiteBold = new Pen(Color.White);
pWhite.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
pWhiteBold.Width = 3;
Rectangle rect = new Rectangle(scale.RealToScreenPosition(Position.Translation(-HoverRadius, -HoverRadius)), scale.RealToScreenSize(new SizeF(HoverRadius * 2, HoverRadius * 2)));
if (IsHover)
{
g.DrawEllipse(pWhiteBold, rect);
}
else
{
//g.DrawEllipse(pBlack, rect);
//g.DrawEllipse(pWhite, rect);
}
pBlack.Dispose();
pWhite.Dispose();
pWhiteBold.Dispose();
}
public bool Contains(RealPoint p)
{
return new Circle(_position, _hoverRadius).Contains(p);
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/Node.cs
using Geometry.Shapes;
using System;
using System.Collections.Generic;
namespace AStarFolder
{
public class Node
{
RealPoint _pos;
bool _passable;
List<Arc> _incomingArcs;
List<Arc> _outgoingArcs;
public Node()
{
_pos = new RealPoint();
_passable = true;
_incomingArcs = new List<Arc>();
_outgoingArcs = new List<Arc>();
}
public Node(RealPoint pos) : this()
{
_pos = new RealPoint(pos);
}
public Node(double x, double y) : this(new RealPoint(x, y))
{
}
public List<Arc> IncomingArcs { get { return _incomingArcs; } }
public List<Arc> OutgoingArcs { get { return _outgoingArcs; } }
public bool Passable
{
set
{
foreach (Arc A in _incomingArcs) A.Passable = value;
foreach (Arc A in _outgoingArcs) A.Passable = value;
_passable = value;
}
get
{
return _passable;
}
}
public double X { get { return _pos.X; } }
public double Y { get { return _pos.Y; } }
public RealPoint Position { get { return _pos; } }
public override string ToString()
{
return _pos.ToString();
}
public override bool Equals(object o)
{
Node other = (Node)o;
return (other != null) && (_pos == other.Position);
}
public override int GetHashCode()
{
return _pos.GetHashCode();
}
public static double EuclidianDistance(Node n1, Node n2)
{
return n1.Position.Distance(n2.Position);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageLogThreads.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PageLogThreads : UserControl
{
private System.Windows.Forms.Timer _timerDisplay;
public PageLogThreads()
{
InitializeComponent();
}
private void PanelLogThreads_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
dataGridViewLog.Columns.Add("Id", "Id");
dataGridViewLog.Columns[0].Width = 30;
dataGridViewLog.Columns.Add("Nom", "Nom");
dataGridViewLog.Columns[1].Width = 200;
dataGridViewLog.Columns.Add("Etat", "Etat");
dataGridViewLog.Columns[2].Width = 140;
dataGridViewLog.Columns.Add("Début", "Début");
dataGridViewLog.Columns[3].Width = 50;
dataGridViewLog.Columns.Add("Fin", "Fin");
dataGridViewLog.Columns[4].Width = 50;
dataGridViewLog.Columns.Add("Durée", "Durée");
dataGridViewLog.Columns[5].Width = 75;
dataGridViewLog.Columns.Add("Executions", "Executions");
dataGridViewLog.Columns[6].Width = 65;
}
}
private void _timerDisplay_Tick(object sender, EventArgs e)
{
dataGridViewLog.Rows.Clear();
foreach (ThreadLink link in ThreadManager.ThreadsLink)
{
int row = dataGridViewLog.Rows.Add(
link.Id.ToString(),
link.Name,
GetLinkState(link),
link.Started ? link.StartDate.ToString("HH:mm:ss") : "",
link.Ended ? link.EndDate.ToString("HH:mm:ss") : "",
link.Duration.ToString(@"hh\:mm\:ss\.fff"),
(link.LoopsCount > 0 ? link.LoopsCount.ToString() : "") + (link.LoopsTarget > 0 ? " / " + link.LoopsTarget.ToString() : ""));
dataGridViewLog.Rows[row].DefaultCellStyle.BackColor = GetLinkColor(link);
}
}
private string GetLinkState(ThreadLink link)
{
String state = "";
if (!link.Started)
state = "Initialisé";
else if (link.Ended)
state = "Terminé";
else if (link.Cancelled)
state = "Annulé";
else if (link.LoopPaused)
state = "En pause";
else
state = "En cours d'execution";
return state;
}
private ColorPlus GetLinkColor(ThreadLink link)
{
ColorPlus color;
if (!link.Started)
color = ColorPlus.GetVeryLight(Color.Purple);
else if (link.Ended)
color = Color.LightGray;
else if (link.Cancelled)
color = ColorPlus.GetVeryLight(Color.Red);
else if (link.LoopPaused)
color = ColorPlus.GetVeryLight(Color.Orange);
else
color = ColorPlus.GetVeryLight(Color.Green);
return color;
}
private void btnStart_Click(object sender, EventArgs e)
{
if(_timerDisplay == null || _timerDisplay.Enabled == false)
{
_timerDisplay = new Timer();
_timerDisplay.Interval = 1000;
_timerDisplay.Tick += _timerDisplay_Tick;
_timerDisplay.Start();
btnStart.Text = "Stop";
btnStart.Image = Properties.Resources.Pause16;
}
else
{
_timerDisplay.Stop();
btnStart.Text = "Afficher";
btnStart.Image = Properties.Resources.Play16;
}
}
}
}
<file_sep>/GoBot/GoBot/Recalibration.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Devices;
using GoBot.BoardContext;
using System;
namespace GoBot
{
public static class Recalibration
{
private static Position PositionLeft { get; set; }
private static Position PositionRight { get; set; }
public static Position StartPosition
{
get
{
return GameBoard.MyColor == GameBoard.ColorLeftBlue ? PositionLeft : PositionRight;
}
}
public static void Init()
{
if (Config.CurrentConfig.IsMiniRobot)
{
PositionLeft = new Position(0, new RealPoint(Robots.MainRobot.LenghtTotal / 2, Robots.MainRobot.Width / 2 + 530 + 10 + 250));
PositionRight = new Position(180, new RealPoint(3000 - PositionLeft.Coordinates.X, PositionLeft.Coordinates.Y + 250));
}
else
{
PositionLeft = new Position(0, new RealPoint(250, 690));
PositionRight = new Position(180, new RealPoint(3000 - PositionLeft.Coordinates.X, PositionLeft.Coordinates.Y));
}
}
public static bool GoToCalibration()
{
if (Config.CurrentConfig.IsMiniRobot)
{
if (GameBoard.ColorLeftBlue == GameBoard.MyColor)
return Robots.MainRobot.GoToPosition(new Position(90, new RealPoint(Robots.MainRobot.Width, Robots.MainRobot.Width)));
else
return Robots.MainRobot.GoToPosition(new Position(90, new RealPoint(3000 - Robots.MainRobot.Width, Robots.MainRobot.Width)));
}
else
{
if (GameBoard.ColorLeftBlue == GameBoard.MyColor)
return Robots.MainRobot.GoToPosition(new Position(90, new RealPoint(Robots.MainRobot.Width, Robots.MainRobot.Width)));
else
return Robots.MainRobot.GoToPosition(new Position(90, new RealPoint(3000 - Robots.MainRobot.Width, Robots.MainRobot.Width)));
}
}
public static void Calibration()
{
if (Config.CurrentConfig.IsMiniRobot)
{
Robots.MainRobot.SendPID(Config.CurrentConfig.GRCoeffP, Config.CurrentConfig.GRCoeffI, Config.CurrentConfig.GRCoeffD);
Robots.MainRobot.Stop();
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.MoveForward(10);
Robots.MainRobot.Recalibration(SensAR.Arriere);
Robots.MainRobot.SetSpeedFast();
Robots.MainRobot.SetAsservOffset(new Position(Math.Round(Robots.MainRobot.Position.Angle.InPositiveDegrees / 90) * 90,
new RealPoint(Robots.MainRobot.Position.Coordinates.X, Robots.MainRobot.LenghtBack)));
Robots.MainRobot.MoveForward((int)(StartPosition.Coordinates.Y - Robots.MainRobot.LenghtBack));
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
Robots.MainRobot.PivotRight(90);
else
Robots.MainRobot.PivotLeft(90);
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.Recalibration(SensAR.Arriere);
Robots.MainRobot.SetAsservOffset(StartPosition);
Robots.MainRobot.EnableStartTrigger();
Robots.MainRobot.SetSpeedFast();
}
else
{
Robots.MainRobot.SetAsservOffset(new Position(92, new RealPoint(GameBoard.MyColor == GameBoard.ColorLeftBlue ? 500 : 2500, 500)));
Robots.MainRobot.SendPID(Config.CurrentConfig.GRCoeffP, Config.CurrentConfig.GRCoeffI, Config.CurrentConfig.GRCoeffD);
Robots.MainRobot.Stop();
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.MoveForward(10);
Robots.MainRobot.Recalibration(SensAR.Arriere, true, true);
Robots.MainRobot.SetSpeedSlow();
Robots.MainRobot.MoveForward((int)(StartPosition.Coordinates.Y - Robots.MainRobot.LenghtBack));
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
Robots.MainRobot.PivotLeft(90);
else
Robots.MainRobot.PivotRight(90);
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.Recalibration(SensAR.Arriere, true, true);
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
Robots.MainRobot.Move((int)Math.Abs(StartPosition.Coordinates.X - Robots.MainRobot.LenghtBack));
else
Robots.MainRobot.Move((int)Math.Abs((3000 - StartPosition.Coordinates.X) - Robots.MainRobot.LenghtBack));
Robots.MainRobot.SetAsservOffset(StartPosition);
Robots.MainRobot.EnableStartTrigger();
Robots.MainRobot.SetSpeedFast();
}
}
}
}
<file_sep>/GoBot/Composants/ConnectionIndicator.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class ConnectionIndicator : PictureBox
{
private Timer BlinkTimer { get; set; }
private int BlinkCounter { get; set; } = 0;
/// <summary>
/// Obtient l'état actuel de la connexion entrante
/// </summary>
public bool StateIn { get; protected set; }
/// <summary>
/// Obtient l'état actuel de la connexion sortante
/// </summary>
public bool StateOut { get; protected set; }
public ConnectionIndicator()
{
InitializeComponent();
BlinkTimer = new Timer();
BlinkTimer.Interval = 100;
BlinkTimer.Tick += new EventHandler(timer_Tick);
SetConnectionState(false, false);
}
void timer_Tick(object sender, EventArgs e)
{
Visible = !Visible;
BlinkCounter++;
if (BlinkCounter > 7)
BlinkTimer.Stop();
}
/// <summary>
/// Permet de déterminer l'état des connexions
/// </summary>
/// <param name="stateIn">Etat de la connexion entrante</param>
/// <param name="stateOut">Etat de la connexion sortante</param>
/// <param name="blink">Si vrai, clignotement si changement d'état</param>
public void SetConnectionState(bool stateIn, bool stateOut, bool blink = false)
{
if (stateIn != StateIn || stateOut != StateOut)
{
StateIn = stateIn;
StateOut = stateOut;
if (StateIn && StateOut)
SetImage(Properties.Resources.ConnectionOk, blink);
else if (!StateIn && !StateOut)
SetImage(Properties.Resources.ConnectionNok, blink);
else
SetImage(Properties.Resources.ConnectionHalf, blink);
}
}
private void SetImage(Image img, bool blink = false)
{
BlinkTimer.Stop();
Visible = true;
BlinkCounter = 0;
Image = img;
if (blink)
BlinkTimer.Start();
}
}
}
<file_sep>/GoBot/GoBot/Devices/AllDevices.cs
using Geometry;
using GoBot.Communications;
using GoBot.Devices.CAN;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace GoBot.Devices
{
static class AllDevices
{
private static CanServos _canServos;
private static Lidar _lidarGround, _lidarAvoid;
private static Buzzer _buzzer;
public static void Init()
{
_canServos = new CanServos(Connections.ConnectionCan);
_buzzer = new Buzzer(Connections.ConnectionCan);
try
{
_lidarGround = new HokuyoRec(LidarID.Ground);
if (Config.CurrentConfig.IsMiniRobot)
{
_lidarAvoid = new Hokuyo(LidarID.Avoid, "COM3");
}
else
{
_lidarAvoid = new Pepperl(IPAddress.Parse("10.1.0.50"));
((Pepperl)_lidarAvoid).SetFrequency(PepperlFreq.Hz20);
((Pepperl)_lidarAvoid).SetFilter(PepperlFilter.Average, 3);
}
}
catch (Exception ex)
{
MessageBox.Show("ERREUR INIT LIDAR : " + ex.Message);
}
}
public static void InitSimu()
{
_canServos = new CanServos(Connections.ConnectionCan);
_lidarGround = new LidarSimu();
_lidarAvoid = new LidarSimu();
}
public static void Close()
{
_lidarAvoid?.StopLoopMeasure();
_lidarGround?.StopLoopMeasure();
}
public static CanServos CanServos
{
get
{
return _canServos;
}
}
public static Buzzer Buzzer => _buzzer;
public static Lidar LidarGround
{
get { return _lidarGround; }
set { _lidarGround = value; }
}
public static Lidar LidarAvoid
{
get { return _lidarAvoid; }
set { _lidarAvoid = value; }
}
private static Hokuyo CreateHokuyo(String portCom, LidarID id)
{
Hokuyo hok = null;
try
{
hok = new Hokuyo(id, portCom);
}
catch (Exception)
{
}
return hok;
}
public static void SetRobotPosition(Position pos)
{
if (Config.CurrentConfig.IsMiniRobot)
{
if (_lidarAvoid != null)
_lidarAvoid.Position = new Position(pos.Angle - new AngleDelta(90), pos.Coordinates);
}
else
{
if (_lidarAvoid != null)
_lidarAvoid.Position = new Position(pos.Angle - new AngleDelta(180), pos.Coordinates);
if (_lidarGround != null)
{
_lidarGround.Position.Coordinates = new Geometry.Shapes.RealPoint(pos.Coordinates.X + Math.Cos(pos.Angle) * 109, pos.Coordinates.Y + Math.Sin(pos.Angle) * 109);
_lidarGround.Position.Angle = pos.Angle;
}
}
}
}
}
<file_sep>/GoBot/GoBot/Robots/Robots.cs
using AStarFolder;
using GoBot.Communications;
using GoBot.Devices;
using System;
using System.Collections.Generic;
namespace GoBot
{
[Serializable]
public enum IDRobot
{
GrosRobot
}
static class Robots
{
public static Dictionary<IDRobot, Robot> DicRobots { get; set; }
public static Robot MainRobot { get; set; }
public static bool Simulation { get; set; }
public static void Init()
{
Simulation = false;
CreateRobots();
}
private static void CreateRobots()
{
Graph graphBackup = null;
if (Robots.MainRobot != null) graphBackup = Robots.MainRobot.Graph;
Robots.MainRobot?.DeInit();
if (!Simulation)
MainRobot = new RobotReel(IDRobot.GrosRobot, Board.RecMove);
else
MainRobot = new RobotSimu(IDRobot.GrosRobot);
if (Config.CurrentConfig.IsMiniRobot)
{
MainRobot.SetDimensions(220, 160, 160, 143.8, 346);
}
else
{
MainRobot.SetDimensions(335, 135, 130.5, 295, 420);
}
MainRobot.PositionChanged += MainRobot_PositionChanged;
DicRobots = new Dictionary<IDRobot, Robot>();
DicRobots.Add(IDRobot.GrosRobot, MainRobot);
MainRobot.Init();
if (graphBackup != null) Robots.MainRobot.Graph = graphBackup;
MainRobot.SetSpeedFast();
}
private static void MainRobot_PositionChanged(Geometry.Position position)
{
AllDevices.SetRobotPosition(position);
}
public static void EnableSimulation(bool isSimulation)
{
if (Simulation == isSimulation)
return;
Simulation = isSimulation;
CreateRobots();
}
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionRecallage.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionRecallage : IAction
{
private SensAR sens;
private Robot robot;
public ActionRecallage(Robot r, SensAR s)
{
robot = r;
sens = s;
}
public override String ToString()
{
return robot.Name + " recallage " + sens.ToString().ToLower();
}
void IAction.Executer()
{
robot.Recalibration(sens);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.BottomLine16;
}
}
}
}
<file_sep>/GoBot/GoBot/Communications/UDP/UDPConnection.cs
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace GoBot.Communications.UDP
{
public class UDPConnection : Connection
{
private String _name;
private class UdpState
{
public UdpClient Client { get; set; }
public IPEndPoint EndPoint { get; set; }
public UdpState(UdpClient client, IPEndPoint endPoint)
{
Client = client;
EndPoint = endPoint;
}
}
public override string Name { get => _name; set => _name = value; }
public enum ConnectionState
{
Ok,
Error
}
/// <summary>
/// Adresse IP du client
/// </summary>
public IPAddress IPAddress { get; private set; }
/// <summary>
/// Port écouté par le PC pour la réception de messages
/// </summary>
public int InputPort { get; private set; }
/// <summary>
/// Port du client sur lequel envoyer les messages
/// </summary>
public int OutputPort { get; private set; }
/// <summary>
/// Client connecté
/// </summary>
private UdpClient Client { get; set; }
IPEndPoint e;
UdpClient u;
public UDPConnection()
{
ConnectionChecker = new ConnectionChecker(this, 500);
}
/// <summary>
/// Initialise la connexion vers le client pour l'envoi de données
/// </summary>
/// <param name="ipAddress">Adresse Ip du client</param>
/// <param name="inputPort">Port à écouter</param>
/// <param name="outputPort">Port sur lequel envoyer les messages</param>
/// <returns>Etat de la connexion</returns>
public ConnectionState Connect(IPAddress ipAddress, int inputPort, int outputPort)
{
ConnectionState state = ConnectionState.Error;
IPAddress = ipAddress;
OutputPort = outputPort;
InputPort = inputPort;
lock (this)
{
try
{
Client = new UdpClient();
Client.Connect(IPAddress, OutputPort);
Connected = true;
state = ConnectionState.Ok;
}
catch (Exception)
{
Connected = false;
}
}
return state;
}
/// <summary>
/// Envoi le message au client actuellement connecté
/// </summary>
/// <param name="frame">Message à envoyer au client</param>
/// <returns>Nombre de caractères envoyés</returns>
public override bool SendMessage(Frame frame)
{
bool ok = false;
//if (Connections.EnableConnection[frame.Board])
{
try
{
if (!Connected)
if (Connect(IPAddress, OutputPort, InputPort) != ConnectionState.Ok)
return false;
byte[] envoi = frame.ToBytes();
ok = Client.Send(envoi, envoi.Length) > 0;
OnFrameSend(frame);
}
catch (SocketException)
{
Connected = false;
ok = false;
}
}
return ok;
}
/// <summary>
/// Lance la réception de trames sur le port actuel
/// </summary>
public override void StartReception()
{
e = new IPEndPoint(IPAddress.Any, InputPort);
if (u != null)
u.Close();
u = new UdpClient(e);
u.BeginReceive(new AsyncCallback(ReceptionCallback), new UdpState(u, e));
}
/// <summary>
/// Libère la connexion vers le client
/// </summary>
public override void Close()
{
Client.Close();
}
/// <summary>
/// Callback appelée par la disponibilité d'une trame
/// </summary>
/// <param name="ar"></param>
private void ReceptionCallback(IAsyncResult ar)
{
try
{
UdpClient u = ((UdpState)(ar.AsyncState)).Client;
IPEndPoint e = new IPEndPoint(IPAddress.Any, InputPort);
Byte[] receiveBytes = u.EndReceive(ar, ref e);
Frame trameRecue = new Frame(receiveBytes);
ConnectionChecker.NotifyAlive();
try
{
OnFrameReceived(trameRecue);
}
catch (Exception e1)
{
if (Debugger.IsAttached) MessageBox.Show("Trame reçue buguée : " + trameRecue.ToString() + Environment.NewLine + e1.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
u.BeginReceive(ReceptionCallback, new UdpState(u, e));
}
catch (Exception e)
{
Console.WriteLine("ERREUR UDP : " + e.ToString());
}
}
}
}<file_sep>/GoBot/GoBot/Devices/CAN/CanServos.cs
using GoBot.Communications;
using GoBot.Communications.CAN;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GoBot.Devices.CAN
{
/// <summary>
/// Dictionnaire à servomoteurs en bus CAN
/// </summary>
class CanServos
{
private Dictionary<ServomoteurID, CanServo> _servos;
private CanConnection _communication;
private List<CanBoard> _canBoards;
public CanServos(CanConnection comm)
{
_communication = comm;
_communication.FrameReceived += _communication_FrameReceived;
_servos = new Dictionary<ServomoteurID, CanServo>();
_canBoards = new List<CanBoard> { CanBoard.CanServo1, CanBoard.CanServo2, CanBoard.CanServo3, CanBoard.CanServo4, CanBoard.CanServo5, CanBoard.CanServo6 };
Enum.GetValues(typeof(ServomoteurID)).Cast<ServomoteurID>().ToList().ForEach(id => _servos.Add(id, new CanServo(id, _communication)));
}
public CanServo this[ServomoteurID servoGlobalId]
{
get
{
return _servos[servoGlobalId];
}
}
private void _communication_FrameReceived(Frame frame)
{
try
{
CanBoard idCan = CanFrameFactory.ExtractBoard(frame);
if (_canBoards.Contains(idCan))
{
ServomoteurID servoGlobalId = CanFrameFactory.ExtractServomoteurID(frame);
_servos[servoGlobalId].FrameReceived(frame);
}
}
catch (Exception e)
{
Console.WriteLine("ERREUR CAN : " + frame.ToString() + " - " + e.Message);
}
}
public void DisableAll()
{
_servos.Values.ToList().ForEach(o => o.DisableOutput());
}
}
}
<file_sep>/GoBot/Composants/GraphPanel.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Drawing.Drawing2D;
namespace Composants
{
public partial class GraphPanel : UserControl
{
public enum ScaleType
{
DynamicGlobal, // Le min et le max sont fixés par la courbe la plus haute et la courbe la plus basse
DynamicPerCurve, // Le min et le max sont propre à chaque courbe qui a donc sa propre échelle. Min et max ne sont pas affichés dans ce cas
Fixed, // Le min et le max sont fixés par MinLimit et MaxLimit
FixedIfEnough // Le min et le max sont fixés par MinLimit et MaxLimit mais sont outrepassés si insufisants pour couvrir la dynamique
}
private Dictionary<String, List<double>> CurvesData { get; set; }
private Dictionary<String, bool> CurvesDisplayed { get; set; }
private Dictionary<String, Pen> CurvesPen { get; set; }
private Dictionary<String, bool> CurvesFilled { get; set; }
/// <summary>
/// Définit le type d'échelle utilisée par le graph
/// </summary>
public ScaleType ScaleMode { get; set; }
/// <summary>
/// Définit la limite inférieur du graph dans le cas où l'échelle est fixe
/// </summary>
public double MinLimit { get; set; }
/// <summary>
/// Définit la limite supérieure du graph dans le cas où l'échelle est fixe
/// </summary>
public double MaxLimit { get; set; }
/// <summary>
/// Définit si le nom des courbes est affiché
/// </summary>
public bool NamesVisible { get; set; }
/// <summary>
/// Définit l'endroit où sont affichés les noms des courbes
/// </summary>
public ContentAlignment NamesAlignment { get; set; } = ContentAlignment.BottomLeft;
/// <summary>
/// Définit si les limites de l'échelle sont affichées dans le cas où l'échelle est commune
/// </summary>
public bool LimitsVisible { get; set; }
/// <summary>
/// Définit la couleur de la bordure du graph et de la bordure des libellés
/// </summary>
public Color BorderColor { get; set; }
/// <summary>
/// Définit si le contour du graph est visible
/// </summary>
public bool BorderVisible { get; set; }
public GraphPanel()
{
InitializeComponent();
CurvesData = new Dictionary<string, List<double>>();
CurvesDisplayed = new Dictionary<string, bool>();
CurvesFilled = new Dictionary<string, bool>();
CurvesPen = new Dictionary<string, Pen>();
ScaleMode = ScaleType.DynamicGlobal;
BackColor = Color.White;
BorderColor = Color.LightGray;
BorderVisible = false;
MaxLimit = 1;
MinLimit = 0;
}
/// <summary>
/// Ajouter un point à la courbe spécifiée
/// Ajoute la courbe si elle n'existe pas encore
/// </summary>
/// <param name="curveName">Nom de la courbe auquel ajouter un point</param>
/// <param name="value">Valeur à ajouter à la courbe</param>
/// <param name="col">Couleur à associer à la courbe (null pour ne pas changer la couleur)</param>
public void AddPoint(String curveName, double value, Color? col = null, bool fill = false)
{
lock (CurvesData)
{
List<double> data;
if (CurvesData.ContainsKey(curveName))
{
data = CurvesData[curveName];
if (col != null)
CurvesPen[curveName] = new Pen(col.Value);
CurvesFilled[curveName] = fill;
}
else
{
data = new List<double>();
CurvesData.Add(curveName, data);
CurvesDisplayed.Add(curveName, true);
if (col != null)
CurvesPen.Add(curveName, new Pen(col.Value));
else
CurvesPen.Add(curveName, new Pen(Color.Black));
CurvesFilled.Add(curveName, fill);
}
data.Add(value);
while (data.Count > pictureBox.Width)
data.RemoveAt(0);
}
}
/// <summary>
/// Met à jour l'affichage des courbes
/// </summary>
public void DrawCurves()
{
lock (CurvesData)
{
Bitmap bmp = new Bitmap(Width, Height);
Graphics gTemp = Graphics.FromImage(bmp);
gTemp.SmoothingMode = SmoothingMode.AntiAlias;
gTemp.Clear(BackColor);
double min = double.MaxValue;
double max = double.MinValue;
if (ScaleMode == ScaleType.Fixed)
{
min = MinLimit;
max = MaxLimit;
}
else if (ScaleMode == ScaleType.DynamicGlobal)
{
foreach (KeyValuePair<String, List<double>> courbe in CurvesData)
{
if (CurvesDisplayed[courbe.Key] && courbe.Value.Count > 1)
{
min = Math.Min(min, courbe.Value.Min());
max = Math.Max(max, courbe.Value.Max());
}
}
}
else if (ScaleMode == ScaleType.FixedIfEnough)
{
foreach (KeyValuePair<String, List<double>> courbe in CurvesData)
{
if (CurvesDisplayed[courbe.Key] && courbe.Value.Count > 1)
{
min = Math.Min(min, courbe.Value.Min());
max = Math.Max(max, courbe.Value.Max());
}
}
min = Math.Min(min, MinLimit);
max = Math.Max(max, MaxLimit);
}
double coef = max == min ? 1 : (float)(pictureBox.Height - 1) / (max - min);
foreach (KeyValuePair<String, List<double>> courbe in CurvesData)
{
if (CurvesDisplayed[courbe.Key] && courbe.Value.Count > 1)
{
if (ScaleMode == ScaleType.DynamicPerCurve)
{
coef = courbe.Value.Max() == courbe.Value.Min() ? 1 : (float)(pictureBox.Height - 1) / (courbe.Value.Max() - courbe.Value.Min());
min = courbe.Value.Min();
}
ColorPlus startCol, endCol;
startCol = CurvesPen[courbe.Key].Color;
endCol = startCol;
endCol.Lightness = 0.95;
List<Point> pts = new List<Point>();
for (int i = 0; i < courbe.Value.Count; i++)
{
pts.Add(new Point(i, (int)((pictureBox.Height - 1) - coef * (courbe.Value[i] - min))));
//gTemp.DrawLine(CurvesPen[courbe.Key], new Point(i - 1, (int)((pictureBox.Height - 1) - coef * (courbe.Value[i - 1] - min))), new Point(i, (int)((pictureBox.Height - 1) - coef * (courbe.Value[i] - min))));
}
if (CurvesFilled[courbe.Key])
{
List<Point> ptsFill = new List<Point>(pts);
ptsFill.Insert(0, new Point(0, (int)((pictureBox.Height - 1) - coef * (0 - min))));
ptsFill.Add(new Point(pts[pts.Count - 1].X, (int)((pictureBox.Height - 1) - coef * (0 - min))));
Brush b = new LinearGradientBrush(new PointF(0, 0), new PointF(0, pictureBox.Height), endCol, startCol);
gTemp.FillPolygon(b, ptsFill.ToArray());
b.Dispose();
}
gTemp.DrawLines(CurvesPen[courbe.Key], pts.ToArray());
}
}
gTemp.SmoothingMode = SmoothingMode.None;
Font myFont = new Font("Calibri", 9);
List<String> namesVisible = CurvesDisplayed.Where(o => CurvesDisplayed[o.Key]).Select(o => o.Key).ToList();
if (NamesVisible && namesVisible.Count > 0)
{
int maxWidth = namesVisible.Max(c => (int)gTemp.MeasureString(c, myFont).Width);
int margin = 5, hPerRow = 10;
Rectangle txtRect;
Size sz = new Size(maxWidth + margin, (namesVisible.Count * hPerRow) + margin - 1);
switch (NamesAlignment)
{
case ContentAlignment.BottomLeft:
txtRect = new Rectangle(0, pictureBox.Height - hPerRow * namesVisible.Count - margin, sz.Width, sz.Height);
break;
case ContentAlignment.TopLeft:
txtRect = new Rectangle(0, 0, sz.Width, sz.Height);
break;
case ContentAlignment.MiddleLeft:
txtRect = new Rectangle(0, pictureBox.Height / 2 - sz.Height / 2, sz.Width, sz.Height);
break;
default:
txtRect = new Rectangle(0, 0, pictureBox.Width, pictureBox.Height);
break;
}
Brush backBsh = new SolidBrush(Color.FromArgb(200, BackColor));
gTemp.FillRectangle(backBsh, new Rectangle(txtRect.X, txtRect.Y, txtRect.Width + 1, txtRect.Height + 1));
backBsh.Dispose();
Pen backPen = new Pen(BorderColor);
backPen.DashStyle = DashStyle.Dot;
gTemp.DrawRectangle(backPen, txtRect);
backPen.Dispose();
Point p = new Point(txtRect.X, txtRect.Y);
foreach (String courbe in namesVisible)
{
if (CurvesDisplayed[courbe])
{
Brush b = new SolidBrush(CurvesPen[courbe].Color);
gTemp.DrawString(courbe, myFont, b, 0, p.Y);
p.Y += 10;
b.Dispose();
}
}
}
if (ScaleMode != ScaleType.DynamicPerCurve && LimitsVisible)
{
String minText = min.ToString("G3");
String maxText = max.ToString("G3");
SizeF minSize = gTemp.MeasureString(minText, myFont);
SizeF maxSize = gTemp.MeasureString(maxText, myFont);
gTemp.DrawString(minText, myFont, Brushes.Black, this.Width - 2 - minSize.Width, Height - maxSize.Height - 2);
gTemp.DrawString(maxText, myFont, Brushes.Black, this.Width - 2 - maxSize.Width, 2);
}
if (BorderVisible)
{
Pen borderPen = new Pen(BorderColor);
gTemp.DrawRectangle(borderPen, new Rectangle(0, 0, Width - 1, Height - 1));
borderPen.Dispose();
}
myFont.Dispose();
pictureBox.Image = bmp;
}
}
/// <summary>
/// Supprimer une courbe
/// </summary>
/// <param name="curveName">Nom de la courbe à supprimer</param>
public void DeleteCurve(String curveName)
{
if (CurvesData.ContainsKey(curveName))
{
CurvesData.Remove(curveName);
CurvesFilled.Remove(curveName);
CurvesPen.Remove(curveName);
}
if (CurvesDisplayed.ContainsKey(curveName))
{
CurvesDisplayed.Remove(curveName);
}
}
/// <summary>
/// Masque ou affiche une courbe
/// </summary>
/// <param name="curveName">Nom de la courbe à masquer ou afficher</param>
public void ShowCurve(String curveName, bool showed = true)
{
if (CurvesDisplayed.ContainsKey(curveName))
{
CurvesDisplayed[curveName] = showed;
}
}
}
}
<file_sep>/GoBot/GoBot/GameElements/LightHouse.cs
using System.Drawing;
using Geometry;
using Geometry.Shapes;
namespace GoBot.GameElements
{
public class LightHouse : GameElement
{
private bool _enable;
public bool Enable
{
get { return _enable; }
set { _enable = value; }
}
public LightHouse(RealPoint position, Color owner) : base(position, owner, 100)
{
_enable = false;
}
public override void Paint(Graphics g, WorldScale scale)
{
new Circle(new RealPoint(Position.X, Position.Y), _hoverRadius).Paint(g, Pens.Black, _enable ? Brushes.LimeGreen : Brushes.WhiteSmoke, scale);
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/LineWithPolygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class LineWithPolygon
{
public static bool Contains(Line containingLine, Polygon containedPolygon)
{
// Contenir un polygone revient à contenir tous les cotés du polygone
return containedPolygon.Sides.TrueForAll(s => containingLine.Contains(s));
}
public static bool Cross(Line line, Polygon polygon)
{
// On teste si la ligne croise un des cotés du polygone
return polygon.Sides.Exists(s => s.Cross(line));
}
public static double Distance(Line line, Polygon polygon)
{
// Distance jusqu'au segment le plus proche
return polygon.Sides.Min(s => s.Distance(line));
}
public static List<RealPoint> GetCrossingPoints(Line line, Polygon polygon)
{
// Croisements avec tous les segments du polygone
return polygon.Sides.SelectMany(s => s.GetCrossingPoints(line)).ToList();
}
}
}
<file_sep>/GoBot/GoBot/NameFinder.cs
using System;
using System.Reflection;
using GoBot.Actionneurs;
using GoBot.Communications;
using GoBot.Communications.UDP;
namespace GoBot
{
static class NameFinder
{
/// <summary>
/// Nomme à partir d'un type inconnu en recherchant la meilleure surcharge
/// </summary>
/// <param name="o">Objet à nommer</param>
/// <returns>Nom de l'objet si trouvé, sinon chaine vide</returns>
public static String GetNameUnknow(object o)
{
return GetName(ToRealType(o));
}
private static dynamic ToRealType(Object o)
{
Type type = o.GetType();
dynamic pp = Convert.ChangeType(o, type);
return pp;
}
/// <summary>
/// Nommage d'un objet pour lequel on n'a à priori pas de surcharge adaptée, donc retourne une chaine vide
/// Fonction privée car aucun intêret de l'appeler depuis l'exterieur
/// </summary>
/// <param name="o">Objet à nommer qui n'a pas trouvé de surcharge</param>
/// <returns>Chaine vide</returns>
private static String GetName(object o)
{
return "";
}
/// <summary>
/// Retourne le nom usuel du servomoteur
/// </summary>
/// <param name="servo">Servomoteur recherché</param>
/// <returns>Nom usuel</returns>
public static String GetName(ServomoteurID servo)
{
switch (servo)
{
case ServomoteurID.Clamp1:
return "crochet gauche";
case ServomoteurID.Clamp2:
return "crochet milieu gauche";
case ServomoteurID.Clamp3:
return "crochet milieu";
case ServomoteurID.Clamp4:
return "crochet milieu droite";
case ServomoteurID.Clamp5:
return "crochet droite";
case ServomoteurID.FingerLeft:
return "doigt gauche";
case ServomoteurID.FingerRight:
return "doigt droite";
case ServomoteurID.FlagLeft:
return "drapeau gauche";
case ServomoteurID.FlagRight:
return "drapeau droite";
case ServomoteurID.GrabberLeft:
return "rabatteur gauche";
case ServomoteurID.GrabberRight:
return "rabatteur droite";
case ServomoteurID.Lifter:
return "monteur crochets";
case ServomoteurID.LockerLeft:
return "verrouilleur gauche";
case ServomoteurID.LockerRight:
return "verrouilleur droite";
case ServomoteurID.PushArmLeft:
return "bras sortie gauche";
case ServomoteurID.PushArmRight:
return "bras sortie droite";
case ServomoteurID.Tilter:
return "rotationneur crochets";
default:
return servo.ToString();
}
}
/// <summary>
/// Retourne le nom de la position en fonction du servomoteur (Ouvert, fermé, etc...)
/// </summary>
/// <param name="position">Position du servomoteur</param>
/// <param name="servo">Servomoteur</param>
/// <returns>Nom de la position</returns>
public static String GetName(int position, ServomoteurID servo)
{
PropertyInfo[] properties = typeof(Config).GetProperties();
foreach (PropertyInfo p in properties)
{
if (p.PropertyType.IsSubclassOf(typeof(PositionableServo)))
{
PositionableServo positionnableServo = (PositionableServo)(p.GetValue(Config.CurrentConfig, null));
if (positionnableServo.ID == servo)
{
PropertyInfo[] proprietesServo = positionnableServo.GetType().GetProperties();
foreach (PropertyInfo ps in proprietesServo)
{
if (ps.Name.StartsWith("Position") && ((int)(ps.GetValue(positionnableServo, null)) == position))
return Config.PropertyNameToScreen(ps) + " (" + position + ")";
}
}
}
}
return position.ToString();
}
/// <summary>
/// Retourne le nom de la position en fonction du moteur (Haut, Bas, etc...)
/// </summary>
/// <param name="position">Position du moteur</param>
/// <param name="moteur">Moteur</param>
/// <returns>Nom de la position</returns>
public static String GetName(int position, MotorID moteur)
{
PropertyInfo[] properties = typeof(Config).GetProperties();
foreach (PropertyInfo p in properties)
{
if (p.PropertyType.IsSubclassOf(typeof(PositionableMotorPosition)))
{
PositionableMotorPosition positionnableMoteur = (PositionableMotorPosition)(p.GetValue(Config.CurrentConfig, null));
if (positionnableMoteur.ID == moteur)
{
PropertyInfo[] proprietesMoteur = positionnableMoteur.GetType().GetProperties();
foreach (PropertyInfo ps in proprietesMoteur)
{
if (ps.Name.StartsWith("Position") && ((int)(ps.GetValue(positionnableMoteur, null)) == position))
return Config.PropertyNameToScreen(ps) + " (" + position + ")";
}
}
}
}
return position.ToString();
}
/// <summary>
/// Retourne le nom usuel d'un capteur on off
/// </summary>
/// <param name="sensor">Capteur on off à nommer</param>
/// <returns>Nom du capteur on off</returns>
public static String GetName(SensorOnOffID sensor)
{
switch (sensor)
{
case SensorOnOffID.StartTrigger:
return "jack";
case SensorOnOffID.PressureSensorLeftBack:
return "pression arrière gauche";
case SensorOnOffID.PressureSensorLeftFront:
return "pression avant gauche";
case SensorOnOffID.PressureSensorRightBack:
return "pression arrière droit";
case SensorOnOffID.PressureSensorRightFront:
return "pression avant droit";
default:
return sensor.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'un codeur
/// </summary>
/// <param name="capteur">Codeur à nommer</param>
/// <returns>Nom du codeur</returns>
public static String GetName(CodeurID encoder)
{
switch (encoder)
{
case CodeurID.Manuel:
return "manuel";
default:
return encoder.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'un bolléen On/Off
/// </summary>
/// <param name="capteur">Valeur à nommer</param>
/// <returns>"On" ou "Off"</returns>
public static String GetName(bool val)
{
return val ? "On" : "Off";
}
/// <summary>
/// Retourne le nom usuel d'un moteur
/// </summary>
/// <param name="capteur">Moteur à nommer</param>
/// <returns>Nom du Moteur</returns>
public static String GetName(MotorID motor)
{
switch (motor)
{
case MotorID.ElevatorLeft:
return "ascenseur gauche";
case MotorID.ElevatorRight:
return "ascenseur droite";
case MotorID.AvailableOnRecIO2:
return "RecIO 2";
case MotorID.AvailableOnRecIO3:
return "RecIO 3";
case MotorID.AvailableOnRecMove11:
return "RecMove 1";
case MotorID.AvailableOnRecMove12:
return "RecMove 2";
default:
return motor.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'un actionneur On/Off
/// </summary>
/// <param name="capteur">Actionneur à nommer</param>
/// <returns>Nom de l'actionneur</returns>
public static String GetName(ActuatorOnOffID actuator)
{
switch (actuator)
{
case ActuatorOnOffID.PowerSensorColorBuoyRight:
return "alimentation capteur couleur bouée droite";
case ActuatorOnOffID.PowerSensorColorBuoyLeft:
return "alimentation capteur couleur bouée gauche";
case ActuatorOnOffID.MakeVacuumLeftBack:
return "aspiration arrière gauche";
case ActuatorOnOffID.MakeVacuumRightBack:
return "aspiration arrière droite";
case ActuatorOnOffID.MakeVacuumLeftFront:
return "aspiration avant gauche";
case ActuatorOnOffID.MakeVacuumRightFront:
return "aspiration avant droite";
case ActuatorOnOffID.OpenVacuumLeftBack:
return "electrovanne arrière gauche";
case ActuatorOnOffID.OpenVacuumRightBack:
return "electrovanne arrière droite";
case ActuatorOnOffID.OpenVacuumLeftFront:
return "electrovanne avant gauche";
case ActuatorOnOffID.OpenVacuumRightFront:
return "electrovanne avant droite";
default:
return actuator.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'un capteur couleur
/// </summary>
/// <param name="sensor">Capteur couleur à nommer</param>
/// <returns>Nom du capteur couleur</returns>
public static String GetName(SensorColorID sensor)
{
switch (sensor)
{
case SensorColorID.BuoyRight:
return "bouée droite";
case SensorColorID.BuoyLeft:
return "bouée gauche";
default:
return sensor.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'une balise
/// </summary>
/// <param name="capteur">Balise à nommer</param>
/// <returns>Nom de la balise</returns>
public static String GetName(BaliseID balise)
{
switch (balise)
{
case BaliseID.Principale:
return "principale";
default:
return balise.ToString();
}
}
/// <summary>
/// Retourne le nom usuel d'un Lidar
/// </summary>
/// <param name="capteur">Lidar à nommer</param>
/// <returns>Nom du Lidar</returns>
public static String GetName(LidarID lidar)
{
switch (lidar)
{
case LidarID.Ground:
return "scan sol";
case LidarID.Avoid:
return "évitement";
default:
return lidar.ToString();
}
}
/// <summary>
/// Retourne le template de décodage d'une fonction dans le protocole de communication UDP
/// </summary>
/// <param name="capteur">Fonction à décoder</param>
/// <returns>Template de décodage</returns>
public static String GetName(UdpFrameFunction frame)
{
return UdpFrameDecoder.GetMessage(frame);
}
}
}
<file_sep>/GoBot/GoBot/Util.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot
{
public static class Util
{
public static dynamic ToRealType(Object o)
{
Type type = o.GetType();
dynamic pp = Convert.ChangeType(o, type);
return pp;
}
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/PepperlEnums.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace GoBot.Devices
{
public enum PepperlCmd
{
[Description(PepperlConst.CmdReboot)]
Reboot,
[Description(PepperlConst.CmfFactoryReset)]
FactoryReset,
[Description(PepperlConst.CmdHandleUdp)]
CreateChannelUDP,
[Description(PepperlConst.CmdHandleTcp)]
CreateChannelTCP,
[Description(PepperlConst.CmdProtocolInfo)]
ProtocolInfo,
[Description(PepperlConst.CmdFeedWatchdog)]
FeedWatchdog,
[Description(PepperlConst.CmdListParameters)]
ListParameters,
[Description(PepperlConst.CmdGetParameter)]
GetParameters,
[Description(PepperlConst.CmdSetParameter)]
SetParameters,
[Description(PepperlConst.CmdResetParameter)]
ResetParameters,
[Description(PepperlConst.CmdReleaseHandle)]
CloseChannel,
[Description(PepperlConst.CmdStartScan)]
ScanStart,
[Description(PepperlConst.CmdStopScan)]
ScanStop,
[Description(PepperlConst.CmdGetScanConfig)]
GetScanConfig,
[Description(PepperlConst.CmdSetScanConfig)]
SetScanConfig
}
public enum PepperlFreq
{
Hz10,
Hz11,
Hz13,
Hz15,
Hz16,
Hz20,
Hz23,
Hz26,
Hz30,
Hz33,
Hz35,
Hz40,
Hz46,
Hz50
}
public enum PepperlFilter
{
[Description(PepperlConst.ValueFilterTypeNone)]
None,
[Description(PepperlConst.ValueFilterTypeAverage)]
Average,
[Description(PepperlConst.ValueFilterTypeMedian)]
Median,
[Description(PepperlConst.ValueFilterTypeMaximum)]
Maximum,
[Description(PepperlConst.ValueFilterTypeRemission)]
Remission
}
public static class PepperEnumExtensions
{
public static string GetText(this PepperlCmd val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
public static string GetText(this PepperlFilter val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
public static int SamplesPerScan(this PepperlFreq freq)
{
switch (freq)
{
case PepperlFreq.Hz10: return 8400;
case PepperlFreq.Hz11: return 7200;
case PepperlFreq.Hz13: return 6300;
case PepperlFreq.Hz15: return 5600;
case PepperlFreq.Hz16: return 5040;
case PepperlFreq.Hz20: return 4200;
case PepperlFreq.Hz23: return 3600;
case PepperlFreq.Hz26: return 3150;
case PepperlFreq.Hz30: return 2800;
case PepperlFreq.Hz33: return 2520;
case PepperlFreq.Hz35: return 2400;
case PepperlFreq.Hz40: return 2100;
case PepperlFreq.Hz46: return 1800;
case PepperlFreq.Hz50: return 1680;
default: return 0;
}
}
public static int Frequency(this PepperlFreq freq)
{
switch (freq)
{
case PepperlFreq.Hz10: return 10;
case PepperlFreq.Hz11: return 11;
case PepperlFreq.Hz13: return 13;
case PepperlFreq.Hz15: return 15;
case PepperlFreq.Hz16: return 16;
case PepperlFreq.Hz20: return 20;
case PepperlFreq.Hz23: return 23;
case PepperlFreq.Hz26: return 26;
case PepperlFreq.Hz30: return 30;
case PepperlFreq.Hz33: return 33;
case PepperlFreq.Hz35: return 35;
case PepperlFreq.Hz40: return 40;
case PepperlFreq.Hz46: return 46;
case PepperlFreq.Hz50: return 50;
default: return 0;
}
}
}
}
<file_sep>/GoBot/Composants/RichTextBoxPlus.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace Composants
{
public partial class RichTextBoxPlus : RichTextBox
{
public RichTextBoxPlus()
{
InitializeComponent();
}
public RichTextBoxPlus(IContainer container)
{
container.Add(this);
InitializeComponent();
}
/// <summary>
/// Ajoute une ligne de teste dans le couleur spécifiée. L'heure peut etre auomatiquement ajoutée en début de ligne.
/// </summary>
/// <param name="text">Texte à ajouter</param>
/// <param name="color">Couleur du texte à ajouter</param>
/// <param name="withDate">Si vrain la date est ajoutée au début de la ligne</param>
public void AddLine(String text, Color color, bool withDate = true)
{
text = withDate ? DateTime.Now.ToLongTimeString() + " > " + text + Environment.NewLine : text + Environment.NewLine;
SuspendLayout();
SelectionStart = TextLength;
SelectedText = text;
SelectionStart = TextLength - text.Length + 1;
SelectionLength = text.Length;
SelectionColor = color;
ResumeLayout();
Select(TextLength, 0);
SelectionStart = TextLength;
ScrollToCaret();
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesCrossingPoints.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes
{
internal static class ShapesCrossingPoints
{
public static List<RealPoint> CircleAndCircle(Circle circle1, Circle circle2)
{
List<RealPoint> output = new List<RealPoint>();
bool aligned = Math.Abs(circle2.Center.Y - circle1.Center.Y) < RealPoint.PRECISION;
if (aligned)// Cercles non alignés horizontalement (on pivote pour les calculs, sinon division par 0)
circle2 = circle2.Rotation(90, circle1.Center);
RealPoint oc1 = new RealPoint(circle2.Center), oc2 = new RealPoint(circle1.Center);
double b = circle2.Radius, c = circle1.Radius;
double a = (-(Math.Pow(oc1.X, 2)) - (Math.Pow(oc1.Y, 2)) + Math.Pow(oc2.X, 2) + Math.Pow(oc2.Y, 2) + Math.Pow(b, 2) - Math.Pow(c, 2)) / (2 * (oc2.Y - oc1.Y));
double d = ((oc2.X - oc1.X) / (oc2.Y - oc1.Y));
double A = Math.Pow(d, 2) + 1;
double B = -2 * oc1.X + 2 * oc1.Y * d - 2 * a * d;
double C = Math.Pow(oc1.X, 2) + Math.Pow(oc1.Y, 2) - 2 * oc1.Y * a + Math.Pow(a, 2) - Math.Pow(b, 2);
double delta = Math.Pow(B, 2) - 4 * A * C;
if (delta >= 0)
{
double x1 = (-B + Math.Sqrt(delta)) / (2 * A);
double y1 = a - x1 * d;
output.Add(new RealPoint(x1, y1));
if (delta > 0)
{
double x2 = (-B - Math.Sqrt(delta)) / (2 * A);
double y2 = a - x2 * d;
output.Add(new RealPoint(x2, y2));
}
}
if (aligned)
output = output.ConvertAll(p => p.Rotation(-90, circle1.Center));
return output;
}
public static List<RealPoint> CircleAndSegment(Circle circle, Segment segment)
{
List<RealPoint> intersectsPoints = new List<RealPoint>();
double dx = segment.EndPoint.X - segment.StartPoint.X;
double dy = segment.EndPoint.Y - segment.StartPoint.Y;
double Ox = segment.StartPoint.X - circle.Center.X;
double Oy = segment.StartPoint.Y - circle.Center.Y;
double A = dx * dx + dy * dy;
double B = 2 * (dx * Ox + dy * Oy);
double C = Ox * Ox + Oy * Oy - circle.Radius * circle.Radius;
double delta = B * B - 4 * A * C;
if (delta < 0 + double.Epsilon && delta > 0 - double.Epsilon)
{
double t = -B / (2 * A);
if (t >= 0 && t <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t * dx, segment.StartPoint.Y + t * dy));
}
if (delta > 0)
{
double t1 = (double)((-B - Math.Sqrt(delta)) / (2 * A));
double t2 = (double)((-B + Math.Sqrt(delta)) / (2 * A));
if (t1 >= 0 && t1 <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t1 * dx, segment.StartPoint.Y + t1 * dy));
if (t2 >= 0 && t2 <= 1)
intersectsPoints.Add(new RealPoint(segment.StartPoint.X + t2 * dx, segment.StartPoint.Y + t2 * dy));
}
return intersectsPoints;
}
}
}
<file_sep>/GoBot/GoBot/Communications/LiaisonDataCheck.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Communications
{
class LiaisonDataCheck
{
private Connexion Connexion { get; set; }
private Carte Carte { get; set; }
private bool Bloquant { get; set; }
public byte IDTestEmissionActuel { get; set; }
private byte IDTestReceptionActuel { get; set; }
public int NombreMessagesTotal { get; private set; }
public int NombreMessagesCorrects { get; private set; }
public int NombreMessagesPerdusEmission { get; private set; }
public int NombreMessagesCorrompusEmission { get; private set; }
public int NombreMessagesPerdusReception { get; private set; }
public int NombreMessagesCorrompusReception { get; private set; }
public Dictionary<int, List<ReponseLiaison>> Reponses { get; set; }
public enum ReponseLiaison
{
OK,
PerduEmission,
PerduReception,
CorrompuEmission,
CorrompuReception,
}
public LiaisonDataCheck(Connexion connexion, Carte carte, bool bloquant)
{
Reponses = new Dictionary<int, List<ReponseLiaison>>();
for (int i = 0; i < 255; i++ )
Reponses.Add(i, new List<ReponseLiaison>());
Connexion = connexion;
Carte = carte;
Bloquant = bloquant;
NombreMessagesTotal = 0;
NombreMessagesCorrects = 0;
NombreMessagesPerdusEmission = 0;
NombreMessagesCorrompusEmission = 0;
NombreMessagesPerdusReception = 0;
NombreMessagesCorrompusReception = 0;
IDTestEmissionActuel = 255;
IDTestReceptionActuel = 0;
}
public void EnvoiTest()
{
NombreMessagesTotal++;
IDTestEmissionActuel++;
Trame t = TrameFactory.TestEmission(Carte, IDTestEmissionActuel);
Connexion.SendMessage(t);
}
public void MessageRecu(Trame trame)
{
if ((FonctionBalise)trame[1] == FonctionBalise.TestEmissionCorrompu)
{
Reponses[trame[2]].Add(ReponseLiaison.CorrompuEmission);
NombreMessagesCorrompusEmission++;
if (trame[2] != IDTestReceptionActuel)
{
if (trame[2] < IDTestReceptionActuel)
{
NombreMessagesPerdusReception += 255 - IDTestReceptionActuel;
NombreMessagesPerdusReception += trame[2];
for (int i = IDTestReceptionActuel + 1; i < 256; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
for (int i = 0; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
else
{
NombreMessagesPerdusReception += trame[2] - IDTestReceptionActuel;
for (int i = IDTestReceptionActuel; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
}
IDTestReceptionActuel = (byte)(trame[2] + 1);
}
if ((FonctionBalise)trame[1] == FonctionBalise.TestEmissionReussi)
{
if (trame[2] != IDTestReceptionActuel)
{
if (trame[2] < IDTestReceptionActuel)
{
NombreMessagesPerdusReception += 255 - IDTestReceptionActuel;
NombreMessagesPerdusReception += trame[2];
for (int i = IDTestReceptionActuel + 1; i < 256; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
for (int i = 0; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
else
{
NombreMessagesPerdusReception += trame[2] - IDTestReceptionActuel;
for (int i = IDTestReceptionActuel; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
}
bool verif = true;
if (trame.Length == 19)
{
for (int i = 0; i < 16; i++)
if (trame[i + 3] != i)
verif = false;
if (verif)
{
NombreMessagesCorrects++;
Reponses[trame[2]].Add(ReponseLiaison.OK);
}
else
{
NombreMessagesCorrompusReception++;
Reponses[trame[2]].Add(ReponseLiaison.CorrompuReception);
}
}
IDTestReceptionActuel = (byte)(trame[2] + 1);
}
if ((FonctionBalise)trame[1] == FonctionBalise.TestEmissionPerdu)
{
byte idAttendu = trame[2];
byte idRecu = trame[3];
if (idRecu > idAttendu)
NombreMessagesPerdusEmission += idRecu - idAttendu;
else
{
NombreMessagesPerdusEmission += 255 - idAttendu;
NombreMessagesPerdusEmission += idRecu;
}
if (trame[2] != IDTestReceptionActuel)
{
if (trame[2] < IDTestReceptionActuel)
{
NombreMessagesPerdusReception += 255 - IDTestReceptionActuel;
NombreMessagesPerdusReception += trame[2];
for (int i = IDTestReceptionActuel + 1; i < 256; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
for (int i = 0; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
else
{
NombreMessagesPerdusReception += trame[2] - IDTestReceptionActuel;
for (int i = IDTestReceptionActuel; i < trame[2]; i++)
Reponses[i].Add(ReponseLiaison.PerduReception);
}
}
IDTestReceptionActuel = (byte)(idRecu + 1);
}
}
public void CalculerResultats()
{
foreach(KeyValuePair<int, List<ReponseLiaison>> pair in Reponses)
{
if (Reponses[pair.Key].Count == 0)
Reponses[pair.Key].Add(LiaisonDataCheck.ReponseLiaison.PerduEmission);
}
for (int i = 0; i < 255; i++)
{
int nbOk = 0;
foreach (LiaisonDataCheck.ReponseLiaison rep in Reponses[i])
{
if (rep == LiaisonDataCheck.ReponseLiaison.OK)
nbOk++;
if (rep != LiaisonDataCheck.ReponseLiaison.OK)
Console.WriteLine(i + " " + rep.ToString());
}
if (nbOk > 1)
Console.WriteLine(i + " " + nbOk + " OK");
}
}
}
}
<file_sep>/GoBot/GoBot/GameElements/ColorDropOff.cs
using Geometry;
using Geometry.Shapes;
using GoBot.BoardContext;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace GoBot.GameElements
{
public class ColorDropOff : GameElementZone
{
private List<Color> _loadOnRed; // 0 = Contre la bordure ...1...2...3 = vers la table
private List<Color> _loadOnGreen;
private Buoy _buoyOutside1, _buoyOutside2;
private Buoy _buoyInside1, _buoyInside2;
private Color _pendingLeft, _pendingRight;
private RealPoint _pendingLeftPos, _pendingRightPos;
public ColorDropOff(RealPoint position, Color color, Buoy buoyOutside1, Buoy buoyOutside2, Buoy buoyInside1, Buoy buoyInside2) : base(position, color, 150)
{
_loadOnRed = Enumerable.Repeat(Color.Transparent, 5).ToList();
_loadOnGreen = Enumerable.Repeat(Color.Transparent, 5).ToList();
_buoyOutside1 = buoyOutside1;
_buoyOutside2 = buoyOutside2;
_buoyInside1 = buoyInside1;
_buoyInside2 = buoyInside2;
_pendingLeft = Color.Transparent;
_pendingRight = Color.Transparent;
}
public int LoadsOnRed => _loadOnRed.Count(c => c != Color.Transparent);
public int LoadsOnGreen => _loadOnGreen.Count(c => c != Color.Transparent);
public void SetPendingLeft(Color c, RealPoint point)
{
_pendingLeft = c;
_pendingLeftPos = point;
}
public void SetPendingRight(Color c, RealPoint point)
{
_pendingRight = c;
_pendingRightPos = point;
}
public void RemovePending()
{
_pendingLeft = Color.Transparent;
_pendingRight = Color.Transparent;
}
public override void Paint(Graphics g, WorldScale scale)
{
base.Paint(g, scale);
double x = _position.X - 110;
double y = 2000 - 10 - 85/2;
double dy = -85;
if (_loadOnGreen != null)
for (int j = 0; j < _loadOnGreen.Count; j++)
if (_loadOnGreen[j] != Color.Transparent)
new Circle(new RealPoint(x, y + dy * j), 36).Paint(g, Color.Black, 1, _loadOnGreen[j], scale);
x = _position.X + 110;
if (_loadOnRed != null)
for (int j = 0; j < _loadOnRed.Count; j++)
if (_loadOnRed[j] != Color.Transparent)
new Circle(new RealPoint(x, y + dy * j), 36).Paint(g, Color.Black, 1, _loadOnRed[j], scale);
if (_pendingLeft != Color.Transparent)
new Circle(_pendingLeftPos, 36).Paint(g, Color.Black, 1, _pendingLeft, scale);
if (_pendingRight != Color.Transparent)
new Circle(_pendingRightPos, 36).Paint(g, Color.Black, 1, _pendingRight, scale);
}
public void SetBuoyOnRed(Color c, int level)
{
if (level < _loadOnRed.Count)
_loadOnRed[level] = c;
}
public void SetBuoyOnGreen(Color c, int level)
{
if (level < _loadOnGreen.Count)
_loadOnGreen[level] = c;
}
public int GetAvailableLevel()
{
return Math.Max(_loadOnRed.FindIndex(c => c == Color.Transparent), _loadOnGreen.FindIndex(c => c == Color.Transparent));
}
public bool HasInsideBuoys => _buoyInside1.IsAvailable || _buoyInside2.IsAvailable;
public bool HasOutsideBuoys => _buoyOutside1.IsAvailable || _buoyOutside2.IsAvailable;
public void TakeInsideBuoys()
{
_buoyInside1.IsAvailable = false;
_buoyInside2.IsAvailable = false;
}
public void TakeOutsideBuoys()
{
_buoyOutside1.IsAvailable = false;
_buoyOutside2.IsAvailable = false;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelDisplacement.cs
using System;
using System.Windows.Forms;
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
namespace GoBot.IHM
{
public partial class PanelDisplacement : UserControl
{
private ToolTip tooltip;
public Robot Robot { get; set; }
public PanelDisplacement()
{
InitializeComponent();
tooltip = new ToolTip();
tooltip.InitialDelay = 1500;
tooltip.SetToolTip(btnForward, "Avancer");
tooltip.SetToolTip(btnBackward, "Reculer");
tooltip.SetToolTip(btnPivotRight, "Pivoter vers la droite");
tooltip.SetToolTip(btnPivotLeft, "Pivoter vers la gauche");
tooltip.SetToolTip(btnTurnBackwardRight, "Virage vers l'arrière droite");
tooltip.SetToolTip(btnTurnForwardRight, "Virage vers l'avant droite");
tooltip.SetToolTip(btnTurnBackwardLeft, "Virage vers l'arrière gauche");
tooltip.SetToolTip(btnTurnForwardLeft, "Virage vers l'avant droite");
tooltip.SetToolTip(btnStop, "Stop");
}
public virtual void Init()
{
// Charger la config
if (Robot == Robots.MainRobot)
{
trkLineSpeed.SetValue(Config.CurrentConfig.ConfigRapide.LineSpeed, false);
trkLineAccel.SetValue(Config.CurrentConfig.ConfigRapide.LineAcceleration, false);
trkLineDecel.SetValue(Config.CurrentConfig.ConfigRapide.LineDeceleration, false);
trkPivotSpeed.SetValue(Config.CurrentConfig.ConfigRapide.PivotSpeed, false);
trkPivotAccel.SetValue(Config.CurrentConfig.ConfigRapide.PivotAcceleration, false);
numCoeffP.Value = Config.CurrentConfig.GRCoeffP;
numCoeffI.Value = Config.CurrentConfig.GRCoeffI;
numCoeffD.Value = Config.CurrentConfig.GRCoeffD;
Robot.SendPID(Config.CurrentConfig.GRCoeffP, Config.CurrentConfig.GRCoeffI, Config.CurrentConfig.GRCoeffD);
}
}
#region Boutons pilotage
protected virtual void btnForward_Click(object sender, EventArgs e)
{
int distance;
if (!(Int32.TryParse(txtDistance.Text, out distance) && distance != 0))
txtDistance.ErrorMode = true;
else
Robot.MoveForward(distance, false);
}
protected virtual void btnBackward_Click(object sender, EventArgs e)
{
int distance;
if (!(Int32.TryParse(txtDistance.Text, out distance) && distance != 0))
txtDistance.ErrorMode = true;
else
Robot.MoveBackward(distance, false);
}
protected virtual void btnPivotLeft_Click(object sender, EventArgs e)
{
int angle;
if (!(Int32.TryParse(txtAngle.Text, out angle) && angle != 0))
txtAngle.ErrorMode = true;
else
Robot.PivotLeft(angle, false);
}
protected virtual void btnPivotRight_Click(object sender, EventArgs e)
{
int angle;
if (!(Int32.TryParse(txtAngle.Text, out angle) && angle != 0))
txtAngle.ErrorMode = true;
else
Robot.PivotRight(angle, false);
}
protected virtual void btnTurnForwardRight_Click(object sender, EventArgs e)
{
DoTurn(SensAR.Avant, SensGD.Droite);
}
protected virtual void btnTurnForwardLeft_Click(object sender, EventArgs e)
{
DoTurn(SensAR.Avant, SensGD.Gauche);
}
protected virtual void btnTurnBackwardLeft_Click(object sender, EventArgs e)
{
DoTurn(SensAR.Arriere, SensGD.Gauche);
}
protected virtual void btnTurnBackwardRight_Click(object sender, EventArgs e)
{
DoTurn(SensAR.Arriere, SensGD.Droite);
}
protected void DoTurn(SensAR sensAr, SensGD sensGd)
{
int distance;
int angle;
bool ok = true;
if (!Int32.TryParse(txtDistance.Text, out distance) || distance == 0)
{
txtDistance.ErrorMode = true;
ok = false;
}
if (!Int32.TryParse(txtAngle.Text, out angle) || angle == 0)
{
txtAngle.ErrorMode = true;
ok = false;
}
if (ok)
Robot.Turn(sensAr, sensGd, distance, angle, false);
}
protected virtual void btnStopSmooth_Click(object sender, EventArgs e)
{
if (freelyToolStripMenuItem.Checked)
Robot.Stop(StopMode.Freely);
else if (smoothToolStripMenuItem.Checked)
Robot.Stop(StopMode.Smooth);
else if (abruptToolStripMenuItem.Checked)
Robot.Stop(StopMode.Abrupt);
}
private void stopToolStripMenuItem_Click(object sender, EventArgs e)
{
freelyToolStripMenuItem.Checked = false;
smoothToolStripMenuItem.Checked = false;
abruptToolStripMenuItem.Checked = false;
((ToolStripMenuItem)sender).Checked = true;
btnStop.PerformClick();
}
#endregion
#region Vitesse ligne
protected virtual void trkLineSpeed_TickValueChanged(object sender, double value)
{
Robot.SpeedConfig.LineSpeed = (int)value;
}
private void trkLineSpeed_ValueChanged(object sender, double value)
{
numLineSpeed.Value = (int)value;
}
private void numLineSpeed_ValueChanged(object sender, EventArgs e)
{
if (numLineSpeed.Focused)
trkLineSpeed.SetValue((double)numLineSpeed.Value);
}
#endregion
#region Accélération ligne
protected virtual void trkLineAccel_TickValueChanged(object sender, double value)
{
Robot.SpeedConfig.LineAcceleration = (int)value;
}
private void trkLineAccel_ValueChanged(object sender, double value)
{
numLineAccel.Value = (int)value;
}
private void numLineAccel_ValueChanged(object sender, EventArgs e)
{
if (numLineAccel.Focused)
trkLineAccel.SetValue((double)numLineAccel.Value);
}
#endregion
#region Décélération ligne
private void trkLineDecel_TickValueChanged(object sender, double value)
{
Robot.SpeedConfig.LineDeceleration = (int)value;
}
private void trkLineDecel_ValueChanged(object sender, double value)
{
numLineDecel.Value = (int)value;
}
private void numLineDecel_ValueChanged(object sender, EventArgs e)
{
if (numLineDecel.Focused)
trkLineDecel.SetValue((double)numLineDecel.Value);
}
#endregion
#region Vitesse pivot
private void trkPivotSpeed_TickValueChanged(object sender, double value)
{
Robot.SpeedConfig.PivotSpeed = (int)value;
}
private void trkPivotSpeed_ValueChanged(object sender, double value)
{
numPivotSpeed.Value = (int)value;
}
private void numPivotSpeed_ValueChanged(object sender, EventArgs e)
{
if (numPivotSpeed.Focused)
trkPivotSpeed.SetValue((double)numPivotSpeed.Value);
}
#endregion
#region Acceleration pivot
private void trkPivotAccel_TickValueChanged(object sender, double value)
{
Robot.SpeedConfig.PivotAcceleration = (int)value;
Robot.SpeedConfig.PivotDeceleration = (int)value;
}
private void trkPivotAccel_ValueChanged(object sender, double value)
{
numPivotAccel.Value = (int)value;
}
private void numPivotAccel_ValueChanged(object sender, EventArgs e)
{
if (numPivotAccel.Focused)
trkPivotAccel.SetValue((double)numPivotAccel.Value);
}
#endregion
#region Pilotage manuel
protected virtual void pnlManual_KeyUp(object sender, KeyEventArgs e)
{
e.Handled = true;
if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
Robot.Stop();
}
protected virtual void pnlManual_KeyPressed(PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
// Reculer
Robot.MoveBackward(10000, false);
}
else if (e.KeyCode == Keys.Up)
{
// Avancer
Robot.MoveForward(10000, false);
}
else if (e.KeyCode == Keys.Left)
{
// Pivot gauche
Robot.PivotLeft(90, false);
}
else if (e.KeyCode == Keys.Right)
{
// Pivot droit
Robot.PivotRight(90, false);
}
}
#endregion
private void btnCalibration_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link =>
{
btnCalibration.InvokeAuto(() => btnCalibration.Enabled = false);
Robot.MoveForward(10);
Robot.SetSpeedSlow();
Robot.Recalibration(SensAR.Arriere, true, false);
Robot.SetSpeedFast();
btnCalibration.InvokeAuto(() => btnCalibration.Enabled = true);
}).StartThread();
}
private void btnCalibrationForward_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link =>
{
btnCalibration.InvokeAuto(() => btnCalibration.Enabled = false);
Robot.MoveBackward(10);
Robot.SetSpeedSlow();
Robot.Recalibration(SensAR.Avant, true, true);
Robot.SetSpeedFast();
btnCalibration.InvokeAuto(() => btnCalibration.Enabled = true);
}).StartThread();
}
private void btnGoTo_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link => ThreadGoTo(link)).StartThread();
}
private void ThreadGoTo(ThreadLink link)
{
link.RegisterName();
Robot.GoToPosition(new Position((double)numTeta.Value, new RealPoint((double)numX.Value, (double)numY.Value)));
}
private void btnLow_Click(object sender, EventArgs e)
{
Robot.SetSpeedSlow();
trkLineSpeed.SetValue(Robot.SpeedConfig.LineSpeed, false);
trkLineAccel.SetValue(Robot.SpeedConfig.LineAcceleration, false);
trkLineDecel.SetValue(Robot.SpeedConfig.LineDeceleration, false);
trkPivotSpeed.SetValue(Robot.SpeedConfig.LineSpeed, false);
trkPivotAccel.SetValue(Robot.SpeedConfig.LineSpeed, false);
}
private void btnFast_Click(object sender, EventArgs e)
{
Robot.SetSpeedFast();
trkLineSpeed.SetValue(Robot.SpeedConfig.LineSpeed, false);
trkLineAccel.SetValue(Robot.SpeedConfig.LineAcceleration, false);
trkLineDecel.SetValue(Robot.SpeedConfig.LineDeceleration, false);
trkPivotSpeed.SetValue(Robot.SpeedConfig.PivotSpeed, false);
trkPivotAccel.SetValue(Robot.SpeedConfig.PivotAcceleration, false);
}
private void numCoeffPID_ValueChanged(object sender, EventArgs e)
{
btnPIDXY.Enabled = true;
}
private void btnPIDPol_Click(object sender, EventArgs e)
{
Robots.MainRobot.SendPIDCap((int)numCoeffP.Value, (int)numCoeffI.Value, (int)numCoeffD.Value);
}
private void btnPIDVit_Click(object sender, EventArgs e)
{
Robots.MainRobot.SendPIDSpeed((int)numCoeffP.Value, (int)numCoeffI.Value, (int)numCoeffD.Value);
}
private void btnPIDXY_Click(object sender, EventArgs e)
{
Robot.SendPID((int)numCoeffP.Value, (int)numCoeffI.Value, (int)numCoeffD.Value);
if (Robot == Robots.MainRobot)
{
Config.CurrentConfig.GRCoeffP = (int)numCoeffP.Value;
Config.CurrentConfig.GRCoeffI = (int)numCoeffI.Value;
Config.CurrentConfig.GRCoeffD = (int)numCoeffD.Value;
Config.Save();
}
btnPIDXY.Enabled = false;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/RealPointWithCircle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class RealPointWithCircle
{
public static bool Contains(RealPoint containingPoint, Circle containedCircle)
{
return containedCircle.Center == containingPoint && containedCircle.Radius == 0;
}
public static bool Cross(RealPoint point, Circle circle)
{
return CircleWithRealPoint.Cross(circle, point);
}
public static double Distance(RealPoint point, Circle circle)
{
return CircleWithRealPoint.Distance(circle, point);
}
public static List<RealPoint> GetCrossingPoints(RealPoint point, Circle circle)
{
return CircleWithRealPoint.GetCrossingPoints(circle, point);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Forms/SplashScreen.cs
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace GoBot.IHM
{
/// <summary>
/// Fenêtre de lancement de l'application avec image et messages personnalisés.
/// </summary>
public static class SplashScreen
{
private static SplashForm _form;
private static Thread _formThread;
private static Bitmap _image;
private static Rectangle _messageRect;
/// <summary>
/// Affiche l'écran de lancement.
/// </summary>
/// <param name="image">Image de fond de l'écran de lancement.</param>
/// <param name="messageRect">Coordonnée du rectangle d'affichage de messages.</param>
/// <param name="speed">L'image apparait par fondu en gagnant une opacité équivalente au paramètre speed à chaque itération.</param>
public static void ShowSplash(Bitmap image, Rectangle messageRect, int speed = 7)
{
_image = image;
_messageRect = messageRect;
_formThread = new Thread(Open);
_formThread.SetApartmentState(ApartmentState.STA);
_formThread.Start(speed);
while (_form == null) ;
}
/// <summary>
/// Ferme l'écran de lancement.
/// </summary>
/// <param name="speed">L'image disparait par fondu en perdant une opacité équivalente au paramètre speed à chaque itération.</param>
public static void CloseSplash(int speed = 10)
{
if (speed == -1)
_form.InvokeAuto(() => _form.Close());
else
{
_form.Speed = -speed;
_form.StartTimer();
}
}
public static void SetImage(Image img)
{
_form.SetImage(img);
Thread.Sleep(500);
}
/// <summary>
/// Affiche le message donné dans la couleur choisie.
/// </summary>
/// <param name="text">Message à afficher.</param>
/// <param name="color">Couleur du message à afficher.</param>
public static void SetMessage(String text, Color color)
{
_form.SetText(text, color);
}
private static void Open(object speed)
{
_form = new SplashForm(_image);
_form.Speed = (int)speed;
_form.MessageRect = _messageRect;
_form.ShowDialog();
}
private class SplashForm : Form
{
private int _speed;
private int _oppacity;
private Image _currentBitmap;
private Image _originalBitmap;
private string _text;
private Color _textColor;
private Rectangle _messageRect;
private System.Timers.Timer _timerOpacity;
public int Speed
{
get
{
return _speed;
}
set
{
_speed = value;
}
}
public Rectangle MessageRect
{
get
{
return _messageRect;
}
set
{
_messageRect = value;
}
}
public SplashForm(Bitmap img)
{
InitializeComponent(img.Size);
//img = WriteVersion(img);
_oppacity = 0;
_originalBitmap = img;
_text = "";
_textColor = Color.Black;
_currentBitmap = new Bitmap(_originalBitmap);
_timerOpacity = new System.Timers.Timer(15);
_timerOpacity.Elapsed += _timerOpacity_Elapsed;
_timerOpacity.Interval = 15;
this.StartTimer();
}
public void SetImage(Image img)
{
_originalBitmap = new Bitmap(img);
Image lastImage;
lock (_form)
{
_currentBitmap.Dispose();
_currentBitmap = GenerateImage();
lastImage = _currentBitmap;
}
this.ShowBitmap(lastImage, (byte)_oppacity);
}
public void SetText(String text, Color color)
{
_text = text;
_textColor = color;
Image lastImage;
lock (_form)
{
_currentBitmap.Dispose();
_currentBitmap = GenerateImage();
lastImage = _currentBitmap;
}
this.ShowBitmap(lastImage, (byte)_oppacity);
}
public void StartTimer()
{
_timerOpacity.Start();
}
private Image GenerateImage()
{
Bitmap newBitmap = new Bitmap(_originalBitmap);
Graphics g = Graphics.FromImage(newBitmap);
StringFormat fmt = new StringFormat();
fmt.LineAlignment = StringAlignment.Center;
fmt.Alignment = StringAlignment.Center;
g.DrawString(_text, new Font("Ink free", 22, FontStyle.Bold), new SolidBrush(_textColor), _messageRect, fmt);
g.Dispose();
return newBitmap;
}
private void InitializeComponent(Size sz)
{
this.SuspendLayout();
this.Size = sz;
this.Cursor = Cursors.AppStarting;
this.FormBorderStyle = FormBorderStyle.None;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
}
private void _timerOpacity_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Image lastImg;
_oppacity += _speed;
if (_oppacity < 0)
{
_timerOpacity.Stop();
_oppacity = 0;
this.InvokeAuto(() => this.Close());
}
else if (_oppacity > 255)
{
_timerOpacity.Stop();
_oppacity = 255;
lock (_form)
lastImg = _currentBitmap;
this.ShowBitmap(lastImg, (byte)(_oppacity));
}
else
{
lock (_form)
lastImg = _currentBitmap;
this.ShowBitmap(lastImg, (byte)(_oppacity));
}
}
private Bitmap WriteVersion(Bitmap img)
{
Graphics g = Graphics.FromImage(img);
g.DrawString(Application.ProductVersion.Substring(0, Application.ProductVersion.LastIndexOf('.')), new Font("Calibri", 16, FontStyle.Bold), new SolidBrush(Color.FromArgb(67, 78, 84)), new PointF(82, 212));
return img;
}
private void ShowBitmap(Image bitmap, byte opacity)
{
Bitmap copyBmp;
// The idea of this is very simple,
// 1. Create a compatible DC with screen;
// 2. Select the bitmap with 32bpp with alpha-channel in the compatible DC;
// 3. Call the UpdateLayeredWindow.
try
{
lock (_form)
{
// On copie l'image parce qu'avec l'invocation on sait pas trop quand ça va être executé et l'image aura peut être été détruite.
copyBmp = new Bitmap(bitmap);
}
IntPtr screenDc = Win32.GetDC(IntPtr.Zero);
IntPtr memDc = Win32.CreateCompatibleDC(screenDc);
IntPtr hBitmap = IntPtr.Zero;
IntPtr oldBitmap = IntPtr.Zero;
try
{
hBitmap = copyBmp.GetHbitmap(Color.FromArgb(0)); // grab a GDI handle from this GDI+ bitmap
oldBitmap = Win32.SelectObject(memDc, hBitmap);
Win32.Size size = new Win32.Size(copyBmp.Width, copyBmp.Height);
Win32.Point pointSource = new Win32.Point(0, 0);
Win32.Point topPos = new Win32.Point(Left, Top);
Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION();
blend.BlendOp = Win32.AC_SRC_OVER;
blend.BlendFlags = 0;
blend.SourceConstantAlpha = opacity;
blend.AlphaFormat = Win32.AC_SRC_ALPHA;
this.InvokeAuto(() => Win32.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, Win32.ULW_ALPHA));
}
finally
{
Win32.ReleaseDC(IntPtr.Zero, screenDc);
if (hBitmap != IntPtr.Zero)
{
Win32.SelectObject(memDc, oldBitmap);
Win32.DeleteObject(hBitmap);
}
Win32.DeleteDC(memDc);
copyBmp.Dispose();
}
}
catch { }
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x00080000; // This form has to have the WS_EX_LAYERED extended style
cp.ExStyle |= 0x00000008; // WS_EX_TOPMOST
return cp;
}
}
private class Win32
{
public enum Bool
{
False = 0,
True
};
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public Int32 x;
public Int32 y;
public Point(Int32 x, Int32 y) { this.x = x; this.y = y; }
}
[StructLayout(LayoutKind.Sequential)]
public struct Size
{
public Int32 cx;
public Int32 cy;
public Size(Int32 cx, Int32 cy) { this.cx = cx; this.cy = cy; }
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct ARGB
{
public byte Blue;
public byte Green;
public byte Red;
public byte Alpha;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
public const Int32 ULW_COLORKEY = 0x00000001;
public const Int32 ULW_ALPHA = 0x00000002;
public const Int32 ULW_OPAQUE = 0x00000004;
public const byte AC_SRC_OVER = 0x00;
public const byte AC_SRC_ALPHA = 0x01;
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pprSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);
[DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll", ExactSpelling = true)]
public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll", ExactSpelling = true)]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern Bool DeleteObject(IntPtr hObject);
}
}
}
}
<file_sep>/GoBot/Extensions/StringExtensions.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Extensions
{
internal static class StringExtensions
{
public static String FirstCamelWord(this String txt)
{
string word = string.Empty;
if (!string.IsNullOrEmpty(txt))
{
foreach (char ch in txt)
{
if (char.IsLower(ch))
word += ch.ToString();
else
break;
}
}
return word;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageStorage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PageStorage : UserControl
{
public PageStorage()
{
InitializeComponent();
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/Graph.cs
using System;
using System.Collections;
using System.Collections.Generic;
using Geometry.Shapes;
using System.Linq;
namespace AStarFolder
{
public class Graph
{
private double _resolution, _distanceMax;
private List<Arc> _arcs, _tmpArcs;
private List<Node> _nodes, _tmpNodes;
public Graph(double resolution, double distanceMaxRaccordable)
{
_resolution = resolution;
_distanceMax = distanceMaxRaccordable;
_tmpArcs = new List<Arc>();
_tmpNodes = new List<Node>();
_arcs = new List<Arc>();
_nodes = new List<Node>();
}
double Resolution { get { return _resolution; } }
double DistanceMaxRaccordable { get { return _distanceMax; } }
public IList<Node> Nodes { get { return _nodes; } }
public IList<Arc> Arcs { get { return _arcs; } }
public void Clear()
{
_nodes.Clear();
_arcs.Clear();
}
/// <summary>
/// Ajoute un noeud au graph en reliant tous les points à une distance maximale et en prenant en compte les obstacles à éviter
/// Si permanent == false, le point sera supprimé au prochain appel de @CleanNodesArcsAdd
/// </summary>
/// <param name="node">Noeud à ajouter</param>
/// <param name="obstacles">Obstacles à éviter</param>
/// <param name="safeDistance">Distance (mm) de sécurité auour des obstacles</param>
/// <param name="permnant">True si le point est ajouté de façon permanente et donc ne sera pas supprimé au prochain appel de @CleanNodesArcsAdd</param>
/// <returns>Nombre de points reliés au point ajouté</returns>
public int AddNode(Node node, IEnumerable<IShape> obstacles, double safeDistance, bool isPermanent = false)
{
// Si un noeud est deja présent à cet endroit on ne l'ajoute pas
if (_nodes.Contains(node))
return 0;
// Teste si le noeud est franchissable avec la liste des obstacles
if (obstacles.Any(o => o.Distance(node.Position) < safeDistance))
return 0;
_nodes.Add(node);
if (!isPermanent) _tmpNodes.Add(node);
int connections = 0;
// Liaisons avec les autres noeuds du graph
foreach (Node no in _nodes.Where(iNode => iNode != node
&& node.Position.Distance(iNode.Position) < _distanceMax
&& !obstacles.Any(iObstacle => iObstacle.Distance(new Segment(iNode.Position, node.Position)) < safeDistance)))
{
AddLiaison(node, no, isPermanent);
connections++;
}
return connections;
}
/// <summary>
/// Retourne vrai si le noeud peut se lier avec au moins un autre noeud du graph
/// </summary>
/// <param name="node"></param>
/// <param name="obstacles"></param>
/// <param name="distanceSecurite"></param>
/// <param name="distanceMax"></param>
/// <returns></returns>
public bool Raccordable(Node node, IEnumerable<IShape> obstacles, double distanceSecurite)
{
return _nodes.Any(iNode => iNode != node
&& node.Position.Distance(iNode.Position) < _distanceMax
&& !obstacles.Any(iObstacle => iObstacle.Distance(new Segment(iNode.Position, node.Position)) < distanceSecurite));
}
/// <summary>
/// Nettoie les arcs et noeuds ajoutés temporairement
/// </summary>
public void CleanNodesArcsAdd()
{
foreach (Arc a in _tmpArcs)
RemoveArc(a);
_tmpArcs.Clear();
foreach (Node n in _tmpNodes)
RemoveNode(n);
_tmpNodes.Clear();
}
public Arc AddArc(Node startNode, Node endNode, bool isPermanent)
{
Arc arc = new Arc(startNode, endNode);
_arcs.Add(arc);
if (!isPermanent) _tmpArcs.Add(arc);
return arc;
}
public void AddLiaison(Node node1, Node node2, bool isPermanent)
{
AddArc(node1, node2, isPermanent);
AddArc(node2, node1, isPermanent);
}
public void RemoveNode(Node node)
{
RemoveNodeAt(_nodes.IndexOf(node));
}
public void RemoveNodeAt(int index)
{
Node node = _nodes[index];
foreach (Arc intput in node.IncomingArcs)
{
intput.StartNode.OutgoingArcs.Remove(intput);
_arcs.Remove(intput);
}
foreach (Arc output in node.OutgoingArcs)
{
output.EndNode.IncomingArcs.Remove(output);
_arcs.Remove(output);
}
_nodes.RemoveAt(index);
}
public void RemoveArc(Arc arc)
{
RemoveArcAt(_arcs.IndexOf(arc));
}
public void RemoveArcAt(int index)
{
Arc ArcToRemove = (Arc)_arcs[index];
_arcs.RemoveAt(index);
ArcToRemove.StartNode.OutgoingArcs.Remove(ArcToRemove);
ArcToRemove.EndNode.IncomingArcs.Remove(ArcToRemove);
}
public Node ClosestNode(RealPoint p, out double distance)
{
Node closest = null;
distance = double.MaxValue;
foreach (Node node in _nodes.Where(o => o.Passable))
{
double currentDistance = node.Position.Distance(p);
if (distance > currentDistance)
{
distance = currentDistance;
closest = node;
}
}
return closest;
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using GoBot.Movements;
namespace GoBot.Strategies
{
class StrategyTest : Strategy
{
public override bool AvoidElements => false;
protected override void SequenceBegin()
{
List<Movement> mouvements = new List<Movement>();
// Charger ICI les mouvements à tester
}
protected override void SequenceCore()
{
foreach (Movement move in Movements)
{
for (int i = 0; i < move.Positions.Count; i++)
{
Robots.MainRobot.SetAsservOffset(move.Positions[i]);
Thread.Sleep(500);
move.Execute();
}
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/WorldPanel.cs
using Geometry;
using Geometry.Shapes;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class WorldPanel : PictureBox
{
private RealPoint _pointClicked, _centerAtStart;
private WorldScale _scaleAtStart;
public WorldDimensions Dimensions { get; protected set; }
public delegate void WorldChangeDelegate();
public event WorldChangeDelegate WorldChange;
public delegate void StartMoveDelegate();
public event StartMoveDelegate StartMove;
public delegate void StopMoveDelegate();
public event StopMoveDelegate StopMove;
public WorldPanel()
{
InitializeComponent();
Dimensions = new WorldDimensions();
Dimensions.WorldChange += Dimensions_WorldChange;
_pointClicked = null;
}
public bool Moving
{
get
{
return _pointClicked != null;
}
}
public RealPoint ClickedPoint
{
get
{
return _pointClicked;
}
}
protected void OnWorldChange()
{
WorldChange?.Invoke();
}
protected void OnStartMove()
{
StartMove?.Invoke();
}
protected void OnStopMove()
{
StopMove?.Invoke();
}
public WorldPanel(IContainer container)
{
container.Add(this);
InitializeComponent();
Dimensions = new WorldDimensions();
Dimensions.WorldChange += Dimensions_WorldChange;
_pointClicked = null;
}
private void Dimensions_WorldChange()
{
OnWorldChange();
}
private void WorldPanel_MouseDown(object sender, MouseEventArgs e)
{
_pointClicked = Dimensions.WorldScale.ScreenToRealPosition(e.Location);
_centerAtStart = Dimensions.WorldRect.Center();
_scaleAtStart = new WorldScale(Dimensions.WorldScale);
OnStartMove();
}
private void WorldPanel_MouseMove(object sender, MouseEventArgs e)
{
if (_pointClicked != null)
{
RealPoint newMousePosition = _scaleAtStart.ScreenToRealPosition(e.Location);
RealPoint delta = _pointClicked - newMousePosition;
Dimensions.SetWorldCenter(_centerAtStart + delta);
}
}
private void WorldPanel_MouseUp(object sender, MouseEventArgs e)
{
_pointClicked = null;
OnStopMove();
}
private void WorldPanel_SizeChanged(object sender, System.EventArgs e)
{
Dimensions.SetScreenSize(this.Size);
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaModel.cs
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PagePandaModel : UserControl
{
public PagePandaModel()
{
InitializeComponent();
}
}
}
<file_sep>/GoBot/Composants/BinaryGraph.cs
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class BinaryGraph : UserControl
{
public BinaryGraph()
{
InitializeComponent();
}
/// <summary>
/// Ajoute un point au graph
/// </summary>
/// <param name="value">Valeur binaire à ajouter</param>
public void AddPoint(bool value)
{
if (value)
led.Color = Color.LimeGreen;
else
led.Color = Color.Red;
graph.AddPoint("Bin", value ? 1 : 0, Color.DodgerBlue);
graph.DrawCurves();
}
}
}
<file_sep>/GoBot/Geometry/ListRealPoints.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Geometry.Shapes
{
public static class ListRealPointsExtensions
{
/// <summary>
/// Retourne le barycentre des points
/// </summary>
/// <param name="pts">Liste des points</param>
/// <returns>Barycentre des points</returns>
public static RealPoint GetBarycenter(this IEnumerable<RealPoint> pts)
{
return new RealPoint(pts.Average(p => p.X), pts.Average(p => p.Y));
}
/// <summary>
/// Retourne une droite approximant la liste de points par la méthode des moindres carrés
/// </summary>
/// <param name="pts">Liste de points à approximer</param>
/// <returns>Droite estimée</returns>
public static Line FitLine(this IEnumerable<RealPoint> pts)
{
return new Line(pts);
}
/// <summary>
/// Retourne un segment approximant la liste de points par la méthode des moindres carrés
/// </summary>
/// <param name="pts">Liste de points à approximer</param>
/// <returns>Segment estimée</returns>
public static Segment FitSegment(this IEnumerable<RealPoint> pts)
{
Segment res = null;
if (pts.Count() >= 2)
{
Line line = new Line(pts);
List<RealPoint> projections = pts.Select(o => line.GetProjection(o)).ToList();
res = new Segment(projections[0], projections[1]);
for (int i = 2; i < projections.Count; i++)
{
res = res.Join(projections[i]);
}
}
return res;
}
/// <summary>
/// Retourne le plus petit cercle contenant tous les points et dont le centre est le barycentre des points
/// </summary>
/// <param name="pts">Liste des points à contenir</param>
/// <returns>Cercle obtenu</returns>
public static Circle GetContainingCircle(this IEnumerable<RealPoint> pts)
{
RealPoint center = pts.GetBarycenter();
double ray = pts.Max(p => p.Distance(center));
return new Circle(center, ray);
}
/// <summary>
/// Retourne la distance entre les deux points les plus éloignés de la liste
/// </summary>
/// <param name="pts">Liste de points</param>
/// <returns>Distance maximale</returns>
public static double MaxDistance(this IEnumerable<RealPoint> pts)
{
return pts.Max(p1 => pts.Max(p2 => p1.Distance(p2)));
}
/// <summary>
/// Retourne la distance entre les deux points les plus proches de la liste
/// </summary>
/// <param name="pts">Liste de points</param>
/// <returns>Distance minimale</returns>
public static double MinDistance(this IEnumerable<RealPoint> pts)
{
return pts.Min(p1 => pts.Min(p2 => p1.Distance(p2)));
}
/// <summary>
/// Regroupe les points en différents groupes suivant leur proximité et une distance maximale de regroupement
/// </summary>
/// <param name="pts">Liste de points à regrouper</param>
/// <param name="maxDistance">Distance maximale pour accrocher un point à un groupe. Représente donc également la distance minimale entre deux groupes.</param>
/// <returns>Liste des listes de points pour chaque regroupement</returns>
public static List<List<RealPoint>> GroupByDistance(this IEnumerable<RealPoint> pts, double maxDistance)
{
List<RealPoint> pool = new List<RealPoint>(pts);
List<List<RealPoint>> fullGroups = new List<List<RealPoint>>();
List<List<RealPoint>> groups = new List<List<RealPoint>>();
while (pool.Count > 0)
{
List<RealPoint> group = new List<RealPoint>();
groups.Add(group);
group.Add(pool[0]);
pool.RemoveAt(0);
for (int i = 0; i < group.Count; i++)
{
group.AddRange(pool.Where(p => p.Distance(group[i]) < maxDistance).ToList());
pool.RemoveAll(p => p.Distance(group[i]) < maxDistance);
}
}
return groups;
}
/// <summary>
/// Décalle tous les points dans une certaine direction
/// </summary>
/// <param name="pts">Points à décaller</param>
/// <param name="deltaX">Delta sur l'axe des abscisses</param>
/// <param name="deltaY">Delta sur l'axe des ordonnées</param>
public static void Shift(this List<RealPoint> pts, double deltaX, double deltaY)
{
pts.ForEach(p => p.Set(p.X + deltaX, p.Y + deltaY));
}
/// <summary>
/// Retourne les points qui sont proches d'une forme
/// </summary>
/// <param name="pts">Liste de points</param>
/// <param name="shape">Forme dont les points doivent être proche</param>
/// <param name="maxDistance">Distance maximale à la forme pour être sélectionné</param>
/// <returns></returns>
public static IEnumerable<RealPoint> GetPointsNearFrom(this IEnumerable<RealPoint> pts, IShape shape, double maxDistance)
{
return pts.Where(p => p.Distance(shape) <= maxDistance);
}
/// <summary>
/// Retourne les points contenus dans une forme
/// </summary>
/// <param name="pts">Liste de points</param>
/// <param name="shape">Forme qui doit contenir les points</param>
/// <returns>Points contenus par la forme</returns>
public static IEnumerable<RealPoint> GetPointsInside(this List<RealPoint> pts, IShape shape)
{
return pts.Where(p => shape.Contains(p));
}
/// <summary>
/// Retourne le cercle correspondant le mieux aux points données.
/// </summary>
/// <param name="pts">Points dont on cherche un cercle approchant.</param>
/// <returns>Cercle calculé</returns>
public static Circle FitCircle(this List<RealPoint> pts)
{
double[,] m1 = new double[pts.Count, 3];
double[] m2 = new double[pts.Count];
for (int n = 0; n < pts.Count; n++)
{
m1[n, 0] = -2f * pts[n].X;
m1[n, 1] = -2f * pts[n].Y;
m1[n, 2] = 1;
m2[n] = -(Math.Pow(pts[n].X, 2) + Math.Pow(pts[n].Y, 2));
}
double[,] m3 = Matrix.Transpose(m1);
double[,] m4 = Matrix.Inverse3x3(Matrix.Multiply(m3, m1));
double[] m5 = Matrix.Multiply(m3, m2);
double[] m6 = Matrix.Multiply(m4, m5);
RealPoint center = new RealPoint(m6[0], m6[1]);
double radius = Math.Sqrt(Math.Pow(center.X, 2) + Math.Pow(center.Y, 2) - m6[2]);
return new Circle(center, radius);
}
/// <summary>
/// Retourne un score de correspondance des points à un cercle. (Meilleur score = Meilleure correspondance avec le cercle)
/// </summary>
/// <param name="pts">Points</param>
/// <param name="circle">Cercle avec lequel calculer la correspondance</param>
/// <returns>Score de correspondance</returns>
public static double FitCircleScore(this List<RealPoint> pts, Circle circle)
{
return 1 - pts.Average(o => Math.Abs(o.Distance(circle.Center) - circle.Radius)) / circle.Radius * pts.Select(o => Math.Atan2(circle.Center.Y - o.Y, circle.Center.X - o.X)).ToList().StandardDeviation();
}
/// <summary>
/// Calcule le facteur de corrélation de la régression linaire des points en une droite.
/// </summary>
/// <param name="pts">Points</param>
/// <returns>Facteur de corrélation (-1 à 1)</returns>
public static double FitLineCorrelation(this List<RealPoint> pts)
{
double varX = pts.Average(o => o.X * o.X) - Math.Pow(pts.Average(o => o.X), 2);
double varY = pts.Average(o => o.Y * o.Y) - Math.Pow(pts.Average(o => o.Y), 2);
double covar = pts.Average(o => o.X * o.Y) - pts.Average(o => o.X) * pts.Average(o => o.Y);
return covar / (Math.Sqrt(varX) * Math.Sqrt(varY));
}
}
}<file_sep>/GoBot/GoBot/Movements/MovementBuoy.cs
using Geometry;
using GoBot.Actionneurs;
using GoBot.GameElements;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.Movements
{
class MovementBuoy : Movement
{
private Buoy _buoy;
private Elevator _elevator;
public MovementBuoy(Buoy buoy)
{
_buoy = buoy;
_elevator = Actionneur.FindElevator(_buoy.Color);
double delta = _elevator == Actionneur.ElevatorLeft ? 30 : -30;
//for (int i = 0; i < 360; i += 60)
//{
// Positions.Add(new Geometry.Position(i + delta + 180, new Geometry.Shapes.RealPoint(_buoy.Position.X + 200* new AnglePosition(delta + i).Cos, _buoy.Position.Y + 200 * new AnglePosition(delta + i).Sin)));
//}
for (int i = 0; i < 360; i += 60)
{
Positions.Add(new Geometry.Position(i + 180 + delta, new Geometry.Shapes.RealPoint(_buoy.Position.X + 250 * new AnglePosition(i).Cos, _buoy.Position.Y + 250 * new AnglePosition(i).Sin)));
}
//AnglePosition a = 0;
//Positions.Add(new Geometry.Position(a + 180 + delta, new Geometry.Shapes.RealPoint(_buoy.Position.X + 250 * new AnglePosition(a).Cos, _buoy.Position.Y + 250 * new AnglePosition(a).Sin)));
//a = 180;
//Positions.Add(new Geometry.Position(a + 180 + delta, new Geometry.Shapes.RealPoint(_buoy.Position.X + 250 * new AnglePosition(a).Cos, _buoy.Position.Y + 250 * new AnglePosition(a).Sin)));
}
public override bool CanExecute => _buoy.IsAvailable && _elevator.CountTotal < Elevator.MaxLoad - 1;
public override int Score => 0;
public override double Value => 0.5;
public override GameElement Element => _buoy;
public override Robot Robot => Robots.MainRobot;
public override Color Color => Color.White;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
_elevator.DoGrabOpen();
Robot.SetSpeedSlow();
Robot.MoveForward(150);
Robot.SetSpeedFast();
_elevator.DoSequencePickupColorThread(_buoy.Color);
_buoy.IsAvailable = false;
return true;
}
protected override void MovementEnd()
{
}
}
}
<file_sep>/GoBot/Geometry/ListDouble.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Geometry
{
public static class ListDoubleExtensions
{
/// <summary>
/// Retourne l'écart-type d'une liste de valeurs décimales
/// </summary>
/// <param name="values">Valeurs décimales</param>
/// <returns>Ecart-type</returns>
public static double StandardDeviation(this IEnumerable<double> values)
{
if (values.Count() > 0)
{
double avg = values.Average();
double diffs = 0;
foreach (double val in values)
diffs += (val - avg) * (val - avg);
diffs /= values.Count();
diffs = Math.Sqrt(diffs);
return diffs;
}
else
return 0;
}
}
}
<file_sep>/GoBot/GoBot/FenGoBot.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IhmRobot
{
public partial class FenGoBot : Form
{
public FenGoBot()
{
InitializeComponent();
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void Depl_Enter(object sender, EventArgs e)
{
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClose2_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClose3_Click(object sender, EventArgs e)
{
this.Close();
}
#region Texte par défaut TextBox
private void txtDistanceGR_Enter(object sender, EventArgs e)
{
if (txtDistanceGR.Text == "Distance")
{
txtDistanceGR.ForeColor = Color.Black;
txtDistanceGR.Text = "";
}
}
private void txtDistanceGR_Leave(object sender, EventArgs e)
{
if (txtDistanceGR.Text == "")
{
txtDistanceGR.ForeColor = Color.LightGray;
txtDistanceGR.Text = "Distance";
}
}
private void txtAngleGR_Enter(object sender, EventArgs e)
{
if (txtAngleGR.Text == "Angle")
{
txtAngleGR.ForeColor = Color.Black;
txtAngleGR.Text = "";
}
}
private void txtAngleGR_Leave(object sender, EventArgs e)
{
if (txtAngleGR.Text == "")
{
txtAngleGR.ForeColor = Color.LightGray;
txtAngleGR.Text = "Angle";
}
}
#endregion
private void btnAvanceGR_Click(object sender, EventArgs e)
{
int resultat;
if (Int32.TryParse(txtDistanceGR.Text, out resultat) && resultat != 0)
// Robot.avance(resultat);
resultat = resultat;
else
txtDistanceGR.BackColor = Color.Red;
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyMatch.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using GoBot.Movements;
using GoBot.BoardContext;
using Geometry;
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.GameElements;
using GoBot.Threading;
namespace GoBot.Strategies
{
class StrategyMatch : Strategy
{
private List<Movement> fixedMovements;
public override bool AvoidElements => true;
protected override void SequenceBegin()
{
// TODOEACHYEAR Actions fixes au lancement du match
Robot robot = Robots.MainRobot;
fixedMovements = new List<Movement>();
// Ajouter les points fixes au score (non forfait, elements posés etc)
int initScore = 0;
initScore += 2; // Phare posé
initScore += 15; // 2 manches à air
GameBoard.Score = initScore;
// Sortir ICI de la zonde de départ
robot.UpdateGraph(GameBoard.ObstaclesAll);
// codé en bleu avec miroir
Elevator left = GameBoard.MyColor == GameBoard.ColorLeftBlue ? (Elevator)Actionneur.ElevatorLeft : Actionneur.ElevatorRight;
Elevator right = GameBoard.MyColor == GameBoard.ColorLeftBlue ? (Elevator)Actionneur.ElevatorRight : Actionneur.ElevatorLeft;
ThreadManager.CreateThread(link =>
{
left.DoGrabOpen();
Thread.Sleep(750);
left.DoGrabClose();
}).StartThread();
robot.MoveForward((int)(850 - 120 - Robots.MainRobot.LenghtBack + 50)); // Pour s'aligner sur le centre de l'écueil
left.DoGrabOpen();
robot.MoveBackward(50);
right.DoGrabOpen();
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
GameBoard.Elements.FindBuoy(new RealPoint(450, 510)).IsAvailable = false;
else
GameBoard.Elements.FindBuoy(new RealPoint(3000 - 450, 510)).IsAvailable = false;
robot.GoToAngle(-90);
robot.SetSpeedSlow();
robot.MoveForward(50);
ThreadLink grabLink = ThreadManager.CreateThread(l => right.DoSequencePickupColor(GameBoard.MyColor == GameBoard.ColorLeftBlue ? Buoy.Green : Buoy.Red));
grabLink.StartThread();
Thread.Sleep(1000);
Actionneur.ElevatorLeft.DoGrabOpen();
Actionneur.ElevatorRight.DoGrabOpen();
robot.MoveForward(450);
grabLink.WaitEnd();
//robot.MoveForward((int)(850 - 120 - Robots.MainRobot.LenghtBack)); // Pour s'aligner sur le centre de l'écueil
//robot.GoToAngle(-90);
//robot.SetSpeedSlow();
//Actionneur.ElevatorLeft.DoGrabOpen();
//Actionneur.ElevatorRight.DoGrabOpen();
//robot.MoveForward(500);
Threading.ThreadManager.CreateThread(link => { Actionneur.ElevatorLeft.DoSequencePickupColor(Buoy.Red); }).StartThread();
Threading.ThreadManager.CreateThread(link => { Actionneur.ElevatorRight.DoSequencePickupColor(Buoy.Green); }).StartThread();
List<Buoy> taken = GameBoard.Elements.Buoys.Where(b => b.Position.X < robot.Position.Coordinates.X + 200 && b.Position.X > robot.Position.Coordinates.X - 200 && b.Position.Y < 1000 && b.Position.Y > 0).ToList();
taken.ForEach(b => b.IsAvailable = false);
Thread.Sleep(500);
robot.MoveBackward(35);
robot.SetSpeedFast();
robot.Pivot(180);
// Ajouter ICI l'ordre de la strat fixe avant détection d'adversaire
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
{
fixedMovements.Add(new MovementGroundedZone(GameBoard.Elements.GroundedZones[2]));
fixedMovements.Add(new MovementBuoy(GameBoard.Elements.FindBuoy(new RealPoint(300, 400))));
fixedMovements.Add(new MovementLightHouse(GameBoard.Elements.LightHouses[0]));
fixedMovements.Add(new MovementGreenDropoff(GameBoard.Elements.RandomDropoffs[0]));
fixedMovements.Add(new MovementGroundedZone(GameBoard.Elements.GroundedZones[0]));
fixedMovements.Add(new MovementRedDropoff(GameBoard.Elements.RandomDropoffs[0]));
}
else
{
fixedMovements.Add(new MovementGroundedZone(GameBoard.Elements.GroundedZones[1]));
fixedMovements.Add(new MovementBuoy(GameBoard.Elements.FindBuoy(new RealPoint(2700, 400))));
fixedMovements.Add(new MovementLightHouse(GameBoard.Elements.LightHouses[1]));
fixedMovements.Add(new MovementGreenDropoff(GameBoard.Elements.RandomDropoffs[1]));
fixedMovements.Add(new MovementGroundedZone(GameBoard.Elements.GroundedZones[3]));
fixedMovements.Add(new MovementRedDropoff(GameBoard.Elements.RandomDropoffs[1]));
}
}
protected override void SequenceCore()
{
Movement bestMovement;
int iMovement = 0;
bool ok = true;
// Execution de la strat fixe tant que rien n'échoue
while (ok && iMovement < fixedMovements.Count)
{
int score = fixedMovements[iMovement].Score;
ok = fixedMovements[iMovement].Execute();
if (ok) GameBoard.Score += score;
iMovement++;
}
// Passage en mode recherche de la meilleure action
while (IsRunning)
{
List<Movement> sorted = Movements.Where(m => m.IsCorrectColor() && m.CanExecute).OrderBy(m => m.GlobalCost).ToList();
if (sorted.Count > 0)
{
bestMovement = sorted[0];
if (bestMovement.GlobalCost != double.MaxValue && bestMovement.Value != 0)
{
int score = bestMovement.Score;
if (bestMovement.Execute())
GameBoard.Score += score;
else
bestMovement.Deactivate(new TimeSpan(0, 0, 1));
}
else
{
Robots.MainRobot.Historique.Log("Aucune action à effectuer");
Thread.Sleep(500);
}
}
else
{
Robots.MainRobot.Historique.Log("Aucune action à effectuer");
Thread.Sleep(500);
}
}
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/AStar.cs
// Copyright 2003 <NAME> - <<EMAIL>>
//
// This source file(s) may be redistributed by any means PROVIDING they
// are not sold for profit without the authors expressed written consent,
// and providing that this notice and the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AStarFolder
{
/// <summary>
/// A heuristic is a function that associates a value with a node to gauge it considering the node to reach.
/// </summary>
public delegate double Heuristic(Node NodeToEvaluate, Node TargetNode);
/// <summary>
/// Class to search the best path between two nodes on a graph.
/// </summary>
public class AStar
{
Graph _graph;
Tracks _open;
Dictionary<Node, Track> _closedTracks;
Dictionary<Node, Track> _openTracks;
Track _LeafToGoBackUp;
int _iterations = -1;
/// <summary>
/// Heuristic based on the euclidian distance : Sqrt(Dx²+Dy²)
/// </summary>
public static Heuristic EuclidianHeuristic
{ get { return new Heuristic(Node.EuclidianDistance); } }
/// <summary>
/// Gets/Sets the heuristic that AStar will use.
/// It must be homogeneous to arc's cost.
/// </summary>
public Heuristic ChoosenHeuristic
{
get { return Track.ChoosenHeuristic; }
set { Track.ChoosenHeuristic = value; }
}
/// <summary>
/// This value must belong to [0; 1] and it determines the influence of the heuristic on the algorithm.
/// If this influence value is set to 0, then the search will behave in accordance with the Dijkstra algorithm.
/// If this value is set to 1, then the cost to come to the current node will not be used whereas only the heuristic will be taken into account.
/// </summary>
/// <exception cref="ArgumentException">Value must belong to [0;1].</exception>
public double DijkstraHeuristicBalance
{
get { return Track.DijkstraHeuristicBalance; }
set
{
if (value < 0 || value > 1) throw new ArgumentException("DijkstraHeuristicBalance value must belong to [0;1].");
Track.DijkstraHeuristicBalance = value;
}
}
/// <summary>
/// AStar Constructor.
/// </summary>
/// <param name="graph">The graph on which AStar will perform the search.</param>
public AStar(Graph graph)
{
_graph = graph;
_open = new Tracks();
_openTracks = new Dictionary<Node, Track>();
_closedTracks = new Dictionary<Node, Track>();
ChoosenHeuristic = EuclidianHeuristic;
DijkstraHeuristicBalance = 0.5;
}
/// <summary>
/// Searches for the best path to reach the specified EndNode from the specified StartNode.
/// </summary>
/// <exception cref="ArgumentNullException">StartNode and EndNode cannot be null.</exception>
/// <param name="startNode">The node from which the path must start.</param>
/// <param name="endNode">The node to which the path must end.</param>
/// <returns>'true' if succeeded / 'false' if failed.</returns>
public bool SearchPath(Node startNode, Node endNode)
{
//lock (_graph)
//{
Initialize(startNode, endNode);
while (NextStep()) { }
return PathFound;
//}
}
/// <summary>
/// Use for a 'step by step' search only. This method is alternate to SearchPath.
/// Initializes AStar before performing search steps manually with NextStep.
/// </summary>
/// <exception cref="ArgumentNullException">StartNode and EndNode cannot be null.</exception>
/// <param name="StartNode">The node from which the path must start.</param>
/// <param name="EndNode">The node to which the path must end.</param>
protected void Initialize(Node StartNode, Node EndNode)
{
if (StartNode == null || EndNode == null) throw new ArgumentNullException();
_closedTracks.Clear();
_open.Clear();
_openTracks.Clear();
Track.Target = EndNode;
Track newTrack = new Track(StartNode);
_open.Add(newTrack);
_openTracks.Add(StartNode, newTrack);
_iterations = 0;
_LeafToGoBackUp = null;
}
/// <summary>
/// Use for a 'step by step' search only. This method is alternate to SearchPath.
/// The algorithm must have been initialize before.
/// </summary>
/// <exception cref="InvalidOperationException">You must initialize AStar before using NextStep().</exception>
/// <returns>'true' unless the search ended.</returns>
protected bool NextStep()
{
if (_open.Count == 0) return false;
_iterations++;
// Console.WriteLine("_iterations : " + _iterations.ToString());
Track bestTrack = _open[0];
if (GoBot.Config.CurrentConfig.AfficheDetailTraj > 0)
{
GoBot.Dessinateur.CurrentTrack = bestTrack;
System.Threading.Thread.Sleep(GoBot.Config.CurrentConfig.AfficheDetailTraj);
}
_open.RemoveAt(0);
_openTracks.Remove(bestTrack.EndNode);
if (bestTrack.Succeed)
{
_LeafToGoBackUp = bestTrack;
_open.Clear();
_openTracks.Clear();
}
else
{
Propagate(bestTrack);
}
return (_open.Count > 0);
}
private void Propagate(Track TrackToPropagate)
{
_closedTracks[TrackToPropagate.EndNode] = TrackToPropagate;
foreach (Arc arc in TrackToPropagate.EndNode.OutgoingArcs)
{
if (arc.Passable && arc.EndNode.Passable)
{
Track successor = new Track(TrackToPropagate, arc);
Track trackInClose, trackInOpen;
_closedTracks.TryGetValue(successor.EndNode, out trackInClose);
_openTracks.TryGetValue(successor.EndNode, out trackInOpen);
if (trackInClose != null && successor.Cost >= trackInClose.Cost)
continue;
if (trackInOpen != null && successor.Cost >= trackInOpen.Cost)
continue;
if (trackInClose != null)
{
_closedTracks.Remove(successor.EndNode);
}
if (trackInOpen != null)
{
_open.Remove(trackInOpen);
}
_open.Add(successor);
_openTracks[successor.EndNode] = successor;
}
}
}
/// <summary>
/// To know if a path has been found.
/// </summary>
public bool PathFound { get { return _LeafToGoBackUp != null; } }
/// <summary>
/// Use for a 'step by step' search only.
/// Gets the number of the current step.
/// -1 if the search has not been initialized.
/// 0 if it has not been started.
/// </summary>
public int StepCounter { get { return _iterations; } }
/// <summary>
/// Gets the array of nodes representing the found path.
/// </summary>
/// <exception cref="InvalidOperationException">You cannot get a result unless the search has ended.</exception>
public Node[] PathByNodes
{
get
{
if (!PathFound) return null;
return GoBackUpNodes(_LeafToGoBackUp);
}
}
private Node[] GoBackUpNodes(Track T)
{
int Nb = T.NbArcsVisited;
Node[] Path = new Node[Nb + 1];
for (int i = Nb; i >= 0; i--, T = T.Queue)
Path[i] = T.EndNode;
return Path;
}
}
}
<file_sep>/GoBot/Composants/ColorDisplay.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Composants
{
public partial class ColorDisplay : UserControl
{
public ColorDisplay()
{
InitializeComponent();
}
/// <summary>
/// Détermine la couleur actuellement affichée
/// </summary>
/// <param name="color">Couleur affichée</param>
public void SetColor(Color c)
{
this.InvokeAuto(() =>
{
ColorPlus color = c;
lblR.Text = color.Red.ToString();
lblG.Text = color.Green.ToString();
lblB.Text = color.Blue.ToString();
lblH.Text = ((int)(color.Hue)).ToString();
lblS.Text = ((int)(color.Saturation * 255)).ToString();
lblL.Text = ((int)(color.Lightness * 255)).ToString();
picColor.Image = MakeColorZone(picColor.Size, color);
picR.Image = MakeColorBar(picR.Size, Color.Red, color.Red);
picG.Image = MakeColorBar(picG.Size, Color.FromArgb(44, 208, 0), color.Green);
picB.Image = MakeColorBar(picB.Size, Color.FromArgb(10, 104, 199), color.Blue);
picH.Image = MakeColorBarRainbow(picR.Size, color.Hue);
picS.Image = MakeColorBar2(picG.Size, ColorPlus.FromHsl(color.Hue, 0, 0.5), ColorPlus.FromHsl(color.Hue, 1, 0.5), (int)(color.Saturation * 255));
picL.Image = MakeColorBar2(picB.Size, ColorPlus.FromHsl(color.Hue, 1, 0), ColorPlus.FromHsl(color.Hue, 1, 1), (int)(color.Lightness * 255));
});
}
private Image MakeColorZone(Size sz, Color color)
{
Bitmap bmp = new Bitmap(sz.Width, sz.Height);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
SolidBrush brush = new SolidBrush(color);
int margin = 2;
g.FillEllipse(brush, new Rectangle(margin, margin, sz.Width - margin * 2, sz.Height - margin * 2));
g.DrawEllipse(Pens.Black, new Rectangle(margin, margin, sz.Width - margin * 2, sz.Height - margin * 2));
brush.Dispose();
return bmp;
}
private Image MakeColorBar(Size sz, Color color, int value)
{
Bitmap bmp = new Bitmap(sz.Width, sz.Height);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
SolidBrush brush = new SolidBrush(color);
int margin = 2;
int height = (int)((sz.Height - margin * 2) * value / 255.0);
Rectangle rect = new Rectangle(margin, sz.Height - margin - height, sz.Width - margin * 2, height);
GraphicsPath path = CreateMixRect(rect, new List<int> { Math.Min(5, height), Math.Min(5, height), 0, 0 });
g.FillPath(brush, path);
g.DrawPath(Pens.Black, path);
brush.Dispose();
return bmp;
}
private Image MakeColorBar2(Size sz, ColorPlus colorBottom, ColorPlus colorTop, float value)
{
Bitmap bmp = new Bitmap(sz.Width, sz.Height);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
LinearGradientBrush brush = new LinearGradientBrush(new Point(0, bmp.Height), new Point(0, 0), colorBottom, colorTop);
int margin = 2;
int height = (int)(sz.Height - margin * 2);
Rectangle rect = new Rectangle(margin, sz.Height - margin - height, sz.Width - margin * 2, height);
GraphicsPath path = CreateMixRect(rect, new List<int> { Math.Min(2, height), Math.Min(2, height), Math.Min(2, height), Math.Min(2, height) });
g.FillPath(brush, path);
g.DrawPath(Pens.Black, path);
height = (int)((sz.Height - margin * 2 - 2) * (1 - value / 255.0)) + 2;
g.DrawLine(Pens.Black, 0, height - 1, bmp.Width, height - 1);
g.DrawLine(Pens.White, 0, height, bmp.Width, height);
g.DrawLine(Pens.Black, 0, height + 1, bmp.Width, height + 1);
brush.Dispose();
return bmp;
}
private Image MakeColorBarRainbow(Size sz, double hue)
{
Bitmap bmp = new Bitmap(sz.Width, sz.Height);
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
int margin = 2;
int totalHeight = (int)(sz.Height - margin * 2);
Rectangle rect = new Rectangle(margin, sz.Height - margin - totalHeight, sz.Width - margin * 2, totalHeight);
GraphicsPath path = CreateMixRect(rect, new List<int> { Math.Min(2, totalHeight), Math.Min(2, totalHeight), Math.Min(2, totalHeight), Math.Min(2, totalHeight) });
int height = (int)((sz.Height - margin * 2 - 2) * (1 - hue / 360)) + 2;
LinearGradientBrush brush = new LinearGradientBrush(new Point(0, height + totalHeight/2), new Point(0, height + totalHeight + totalHeight / 2), Color.White, Color.Black);
ColorBlend colors = new ColorBlend(7);
colors.Colors = new Color[] { Color.Red, Color.Yellow, Color.Lime, Color.Cyan, Color.Blue, Color.Magenta, Color.Red };
colors.Positions = new float[] { 0 / 6f, 1 / 6f, 2 / 6f, 3 / 6f, 4 / 6f, 5 / 6f, 6 / 6f };
brush.InterpolationColors = colors;
g.FillPath(brush, path);
g.DrawPath(Pens.Black, path);
height = (int)(sz.Height /2);
g.DrawLine(Pens.Black, 0, height - 1, bmp.Width, height - 1);
g.DrawLine(Pens.White, 0, height, bmp.Width, height);
g.DrawLine(Pens.Black, 0, height + 1, bmp.Width, height + 1);
brush.Dispose();
return bmp;
}
private GraphicsPath CreateMixRect(Rectangle rct, List<int> rays)
{
GraphicsPath pth = new GraphicsPath();
int dd = 1;
if (rays[0] > 0)
pth.AddArc(rct.X, rct.Y, rays[0] * 2, rays[0] * 2, 180, 90);
pth.AddLine(rct.X + rays[0], rct.Y, rct.Right - dd - rays[1], rct.Y);
if ((rays[1] > 0))
pth.AddArc(rct.Right - dd - 2 * rays[1], rct.Y, rays[1] * 2, rays[1] * 2, 270, 90);
pth.AddLine(rct.Right - dd, rct.Y + rays[1], rct.Right - dd, rct.Bottom - dd - rays[2]);
if ((rays[2] > 0))
pth.AddArc(rct.Right - dd - 2 * rays[2], rct.Bottom - dd - 2 * rays[2], rays[2] * 2, rays[2] * 2, 0, 90);
pth.AddLine(rct.Right - dd - rays[2], rct.Bottom - dd, rct.X + rays[3], rct.Bottom - dd);
if ((rays[3] > 0))
pth.AddArc(rct.X, rct.Bottom - dd - 2 * rays[3], rays[3] * 2, rays[3] * 2, 90, 90);
pth.AddLine(rct.X, rct.Bottom - dd - rays[3], rct.X, rct.Y + rays[0]);
pth.CloseFigure();
return pth;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PagePanda.cs
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using GoBot.Communications;
using GoBot.Devices;
using GoBot.IHM.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PagePanda : UserControl
{
private ThreadLink _linkBattery;
public PagePanda()
{
InitializeComponent();
}
private void PagePanda_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
Connections.AllConnections.ForEach(c => c.ConnectionChecker.ConnectionStatusChange += ConnectionChecker_ConnectionStatusChange);
AllDevices.LidarAvoid.ConnectionChecker.ConnectionStatusChange += LidarAvoid_ConnectionStatusChange;
SetPicImage(picLidar, Devices.AllDevices.LidarAvoid.ConnectionChecker.Connected);
SetPicImage(picIO, Connections.ConnectionIO.ConnectionChecker.Connected);
SetPicImage(picMove, Connections.ConnectionMove.ConnectionChecker.Connected);
SetPicImage(picCAN, Connections.ConnectionCanBridge.ConnectionChecker.Connected);
SetPicImage(picServo1, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo1].ConnectionChecker.Connected);
SetPicImage(picServo2, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo2].ConnectionChecker.Connected);
SetPicImage(picServo3, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo3].ConnectionChecker.Connected);
SetPicImage(picServo4, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo4].ConnectionChecker.Connected);
SetPicImage(picServo5, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo5].ConnectionChecker.Connected);
SetPicImage(picServo6, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo6].ConnectionChecker.Connected);
_linkBattery = ThreadManager.CreateThread(link => UpdateBatteryIcon());
_linkBattery.StartInfiniteLoop(1000);
pagePandaMatch.CalibrationDone += PagePandaMatch_CalibrationDone;
}
}
private void PagePandaMatch_CalibrationDone()
{
tabControlPanda.InvokeAuto(() => ChangePageDelay());
}
private void ChangePageDelay(int delayMs = 500)
{
Thread.Sleep(500); tabControlPanda.SelectedIndex += 1;
}
private void UpdateBatteryIcon()
{
_linkBattery?.RegisterName();
picBattery.InvokeAuto(() =>
{
if (!Robots.Simulation && !Connections.ConnectionCanAlim.ConnectionChecker.Connected)
{
picBattery.Image = Properties.Resources.BatteryUnknow96;
lblBattery.Text = ("--,--") + "V";
}
else
{
double voltage = Robots.MainRobot.BatterieVoltage;
if (voltage > Config.CurrentConfig.BatterieRobotVert)
picBattery.Image = Properties.Resources.BatteryFull96;
else if (voltage > Config.CurrentConfig.BatterieRobotOrange)
picBattery.Image = Properties.Resources.BatteryMid96;
else if (voltage > Config.CurrentConfig.BatterieRobotRouge)
picBattery.Image = Properties.Resources.BatteryLow96;
else if (voltage > Config.CurrentConfig.BatterieRobotCritique)
picBattery.Image = Properties.Resources.BatteryCritical96;
else
picBattery.Image = Properties.Resources.BatteryUnknow96;
lblBattery.Text = voltage.ToString("00.00") + "V";
}
});
}
private void LidarAvoid_ConnectionStatusChange(Connection sender, bool connected)
{
SetPicImage(picLidar, connected);
}
private void ConnectionChecker_ConnectionStatusChange(Connection sender, bool connected)
{
if (sender == Connections.ConnectionIO)
SetPicImage(picIO, connected);
else if (sender == Connections.ConnectionMove)
SetPicImage(picMove, connected);
else if (sender == Connections.ConnectionCanBridge)
SetPicImage(picCAN, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo1])
SetPicImage(picServo1, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo2])
SetPicImage(picServo2, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo3])
SetPicImage(picServo3, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo4])
SetPicImage(picServo4, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo5])
SetPicImage(picServo5, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo6])
SetPicImage(picServo6, connected);
}
private static void SetPicImage(PictureBox pic, bool ok)
{
pic.Image = ok ? Properties.Resources.ValidOk48 : Properties.Resources.ValidNok48;
}
private void btnClose_Click(object sender, EventArgs e)
{
FormConfirm form = new FormConfirm();
if (form.ShowDialog() == DialogResult.Yes)
this.ParentForm.Close();
form.Dispose();
}
private void btnNextPage_Click(object sender, EventArgs e)
{
tabControlPanda.SelectedIndex = (tabControlPanda.SelectedIndex + 1) % tabControlPanda.TabCount;
}
#region Buttons style
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.Location = new Point(btnClose.Location.X + 2, btnClose.Location.Y + 2);
}
private void btnClose_MouseUp(object sender, MouseEventArgs e)
{
btnClose.Location = new Point(btnClose.Location.X - 2, btnClose.Location.Y - 2);
}
private void btnNextPage_MouseDown(object sender, MouseEventArgs e)
{
btnNextPage.Location = new Point(btnNextPage.Location.X + 2, btnNextPage.Location.Y + 2);
}
private void btnNextPage_MouseUp(object sender, MouseEventArgs e)
{
btnNextPage.Location = new Point(btnNextPage.Location.X - 2, btnNextPage.Location.Y - 2);
}
#endregion
private void tabControlPanda_SelectedIndexChanged(object sender, EventArgs e)
{
pagePandaLidar.LidarEnable(tabControlPanda.SelectedTab == tabPandaLidar);
}
}
}
<file_sep>/GoBot/GoBot/Actions/ActionMoteur.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionMoteur : IAction
{
private int vitesse;
MotorID moteur;
private Robot robot;
public ActionMoteur(Robot r, int vi, MotorID mo)
{
robot = r;
vitesse = vi;
moteur = mo;
}
public override String ToString()
{
return robot + " tourne " + NameFinder.GetName(moteur) + " à " + NameFinder.GetName(vitesse, moteur);
}
void IAction.Executer()
{
robot.SetMotorAtPosition(moteur, vitesse);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Motor16;
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageCheckSpeed.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PageCheckSpeed : UserControl
{
public PageCheckSpeed()
{
InitializeComponent();
}
private void btnTest_Click(object sender, EventArgs e)
{
Threading.ThreadManager.CreateThread(link =>
{
List<int>[] vals = Robots.MainRobot.DiagnosticLine((int)numDistance.Value, SensAR.Arriere);
SetPoints(vals[0], vals[1]);
}).StartThread();
}
private void SetPoints(List<int> left, List<int> right)
{
List<double> posLeft = Smooth(TargetCount(left.ConvertAll(v => (double)v), gphPos.Width), 30);
List<double> posRight = Smooth(TargetCount(right.ConvertAll(v => (double)v), gphPos.Width), 30);
List<double> speedLeft = Derivation(posLeft, 30);
List<double> speedRight = Derivation(posRight, 30);
List<double> accelLeft = Derivation(speedLeft, 30);
List<double> accelRight = Derivation(speedRight, 30);
gphPos.DeleteCurve("Gauche pos.");
gphPos.DeleteCurve("Droite pos.");
gphPos.DeleteCurve("Gauche Vit.");
gphPos.DeleteCurve("Droite Vit.");
gphPos.DeleteCurve("Gauche Accel.");
gphPos.DeleteCurve("Droite Accel.");
for (int i = 0; i < posLeft.Count; i++)
{
gphPos.AddPoint("Gauche pos.", posLeft[i], Color.Lime, false);
gphPos.AddPoint("Droite pos.", posRight[i], Color.OrangeRed, false);
gphPos.AddPoint("Gauche Vit.", speedLeft[i], Color.Green, false);
gphPos.AddPoint("Droite Vit.", speedRight[i], Color.Red, false);
gphPos.AddPoint("Gauche Accel.", accelLeft[i], Color.DarkGreen, false);
gphPos.AddPoint("Droite Accel.", accelRight[i], Color.DarkRed, false);
}
gphPos.DrawCurves();
}
private List<double> Derivation(List<double> values, int interval = 1)
{
List<double> output = new List<double>();
for (int i = 0; i < values.Count; i++)
{
output.Add(values[Math.Min(i + interval, values.Count - 1)] - values[i]);
}
return output;
}
private List<double> TargetCount(List<double> values, int count)
{
List<double> output;
if (values.Count > count)
{
output = new List<double>();
int avg = (int)Math.Ceiling((double)values.Count / count);
for (int i = 0; i < values.Count - avg; i++)
{
output.Add(values.GetRange(i, avg).Average());
}
}
else
{
output = new List<double>(values);
while (values.Count < count / 2)
{
output = new List<double>();
for (int i = 0; i < values.Count - 1; i++)
{
output.Add(values[i]);
output.Add((values[i] + values[i + 1]) / 2);
}
values = output;
}
}
return output;
}
private List<double> Smooth(List<double> values, int count)
{
List<double> output = new List<double>();
for (int i = 0; i < values.Count - count; i++)
output.Add(values.GetRange(i, count).Average());
return output;
}
}
}
<file_sep>/GoBot/GoBot/Strategies/Strategy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using GoBot.Movements;
using AStarFolder;
using GoBot.Threading;
using System.Diagnostics;
using GoBot.BoardContext;
using GoBot.Devices;
using GoBot.Actionneurs;
namespace GoBot.Strategies
{
public abstract class Strategy
{
private System.Timers.Timer endMatchTimer;
private ThreadLink _linkMatch;
public abstract bool AvoidElements { get; }
/// <summary>
/// Obtient ou définit la durée d'un match
/// </summary>
public TimeSpan MatchDuration { get; set; }
/// <summary>
/// Retourne vrai si le match est en cours d'execution
/// </summary>
public bool IsRunning
{
get
{
return _linkMatch != null && _linkMatch.Running;
}
}
/// <summary>
/// Retourne l'heure de début du match
/// </summary>
public DateTime StartingDateTime { get; protected set; }
/// <summary>
/// Retourne le temps écoulé depuis le début du match
/// </summary>
public TimeSpan TimeSinceBegin
{
get
{
return DateTime.Now - StartingDateTime;
}
}
/// <summary>
/// Retourne le temps restant avant la fin du match
/// </summary>
public TimeSpan TimeBeforeEnd
{
get
{
return (StartingDateTime + MatchDuration) - DateTime.Now;
}
}
/// <summary>
/// Contient la liste de tous les mouvements du match
/// </summary>
public List<Movement> Movements { get; protected set; }
/// <summary>
/// Constructeur
/// </summary>
public Strategy()
{
if (Debugger.IsAttached)
{
MatchDuration = new TimeSpan(0, 0, 100);
}
else
{
MatchDuration = new TimeSpan(0, 0, 100);
}
Movements = new List<Movement>();
// TODOEACHYEAR Charger ICI dans Movements les mouvements possibles
for (int i = 0; i < GameBoard.Elements.GroundedZones.Count; i++)
Movements.Add(new MovementGroundedZone(GameBoard.Elements.GroundedZones[i]));
for (int i = 0; i < GameBoard.Elements.RandomDropoffs.Count; i++)
{
Movements.Add(new MovementRandomDropoff(GameBoard.Elements.RandomDropoffs[i]));
Movements.Add(new MovementGreenDropoff(GameBoard.Elements.RandomDropoffs[i]));
Movements.Add(new MovementRedDropoff(GameBoard.Elements.RandomDropoffs[i]));
}
for (int i = 0; i < GameBoard.Elements.ColorDropoffs.Count; i++)
Movements.Add(new MovementColorDropoff(GameBoard.Elements.ColorDropoffs[i]));
for (int i = 0; i < GameBoard.Elements.LightHouses.Count; i++)
Movements.Add(new MovementLightHouse(GameBoard.Elements.LightHouses[i]));
//Movements.Add(new MovementBuoy(GameBoard.Elements.FindBuoy(new Geometry.Shapes.RealPoint(300, 400))));
//Movements.Add(new MovementBuoy(GameBoard.Elements.FindBuoy(new Geometry.Shapes.RealPoint(2700, 400))));
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
for (int i = 0; i < GameBoard.Elements.BuoysForLeft.Count; i++)
Movements.Add(new MovementBuoy(GameBoard.Elements.BuoysForLeft[i]));
else
for (int i = 0; i < GameBoard.Elements.BuoysForRight.Count; i++)
Movements.Add(new MovementBuoy(GameBoard.Elements.BuoysForRight[i]));
for (int iMov = 0; iMov < Movements.Count; iMov++)
{
for (int iPos = 0; iPos < Movements[iMov].Positions.Count; iPos++)
{
if (!Movements[iMov].Robot.Graph.Raccordable(new Node(Movements[iMov].Positions[iPos].Coordinates),
GameBoard.ObstaclesAll,
Movements[iMov].Robot.Radius))
{
Movements[iMov].Positions.RemoveAt(iPos);
iPos--;
}
}
}
Movements.Add(new MovementRandomPickup(GameBoard.Elements.RandomPickup));
}
/// <summary>
/// Execute le match
/// </summary>
public void ExecuteMatch()
{
Robots.MainRobot.Historique.Log("DEBUT DU MATCH", TypeLog.Strat);
StartingDateTime = DateTime.Now;
GameBoard.StartMatch();
endMatchTimer = new System.Timers.Timer();
endMatchTimer.Elapsed += new ElapsedEventHandler(endMatchTimer_Elapsed);
endMatchTimer.Interval = MatchDuration.TotalMilliseconds;
endMatchTimer.Start();
_linkMatch = ThreadManager.CreateThread(link => Execute());
_linkMatch.StartThread();
}
/// <summary>
/// Interrompt le match
/// </summary>
public void Stop()
{
_linkMatch.Kill();
SequenceEnd();
}
private void endMatchTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Robots.MainRobot.Historique.Log("FIN DU MATCH", TypeLog.Strat);
endMatchTimer.Stop();
_linkMatch.Kill();
SequenceEnd();
}
private void Execute()
{
_linkMatch.RegisterName();
SequenceBegin();
SequenceCore();
}
/// <summary>
/// Contient l'execution des actions au début du match
/// </summary>
protected abstract void SequenceBegin();
/// <summary>
/// Contient l'execution des actions du match
/// </summary>
protected abstract void SequenceCore();
/// <summary>
/// Contient l'execution des actions à la fin du match
/// </summary>
protected virtual void SequenceEnd()
{
// TODOEACHYEAR Couper ICI tous les actionneurs à la fin du match et lancer la Funny Action / afficher le score
Robots.MainRobot.Stop(StopMode.Freely);
Actionneur.ElevatorLeft.DoElevatorFree();
Actionneur.ElevatorRight.DoElevatorFree();
MovementFlags moveFlags = new MovementFlags();
if (moveFlags.ExecuteHere())
GameBoard.Score += moveFlags.Score;
System.Threading.Thread.Sleep(1000);
AllDevices.CanServos.DisableAll();
// On renvoie le score au cas où histoire d'assurer le truc...
if (!Config.CurrentConfig.IsMiniRobot)
Robots.MainRobot.ShowMessage("Estimation :", GameBoard.Score.ToString() + " points");
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/LineWithRealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class LineWithRealPoint
{
public static bool Contains(Line containingLine, RealPoint containedPoint)
{
bool output;
if (containingLine.IsHorizontal)
output = Math.Abs(containedPoint.Y - containingLine.B) <= RealPoint.PRECISION;
else if (containingLine.IsVertical)
output = Math.Abs(containedPoint.X - -containingLine.B) <= RealPoint.PRECISION;
else
{
// Vérifie si le point est sur la droite en vérifiant sa coordonnée Y pour sa coordonnée X par rapport à l'équation de la droite
double expectedY = containingLine.A * containedPoint.X + containingLine.B;
output = Math.Abs(expectedY - containedPoint.Y) <= RealPoint.PRECISION;
}
return output;
}
public static bool Cross(Line line, RealPoint point)
{
// Pour qu'une droite croise un point c'est qu'elle contient le point...
return Contains(line, point);
}
public static double Distance(Line line, RealPoint point)
{
// Pour calculer la distance, on calcule la droite perpendiculaire passant par ce point
// Puis on calcule l'intersection de la droite et de sa perpendiculaire
// On obtient la projection orthogonale du point, qui est le point de la droite le plus proche du point donné
// On retourne la distance entre ces deux points
return point.Distance(line.GetProjection(point));
}
public static List<RealPoint> GetCrossingPoints(Line line, RealPoint point)
{
// Si la droite contient le point, son seul croisement c'est le point lui même...
List<RealPoint> output = new List<RealPoint>();
if (line.Contains(point))
output.Add(new RealPoint(point));
return output;
}
}
}
<file_sep>/GoBot/GeometryTester/TestRectangles.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Geometry.Shapes;
namespace GeometryTester
{
[TestClass]
public class TestRectangle
{
//[TestMethod] // Test bidon histoire de charger les librairies et vérifier temps execution des tests suivants
//public void DummyTest()
//{
// Polygon r0 = new PolygonRectangle(new RealPoint(0, 0), 0, 0);
// Assert.AreEqual(r0, r0.Rotation(90));
//}
// Tests d'égalité entre plusieurs rectangles
[TestMethod]
public void TestRectangleEqual()
{
Polygon r0 = new PolygonRectangle(new RealPoint(0, 0), 0, 0);
Assert.AreEqual(r0, r0);
Assert.AreEqual(r0, r0.Rotation(90));
Assert.AreEqual(r0, r0.Rotation(-180));
Assert.AreEqual(r0, r0.Rotation(-90));
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 100, 100);
Polygon r2 = new PolygonRectangle(new RealPoint(0, 0), 100, 100);
Assert.AreEqual(r1, r1);
Assert.AreEqual(r1, r2);
Assert.AreEqual(r1, r2.Rotation(90));
Assert.AreEqual(r1, r2.Rotation(180));
Assert.AreEqual(r1, r2.Rotation(-90));
r1 = new PolygonRectangle(new RealPoint(10, 10), 100, 100);
r2 = new PolygonRectangle(new RealPoint(10, 10), 100, 100);
Assert.AreEqual(r1, r1);
Assert.AreEqual(r1, r2);
Assert.AreEqual(r1, r2.Rotation(90));
Assert.AreEqual(r1, r2.Rotation(180));
Assert.AreEqual(r1, r2.Rotation(-90));
r1 = new PolygonRectangle(new RealPoint(-10, -10), -100, -100);
r2 = new PolygonRectangle(new RealPoint(-10, -10), -100, -100);
Assert.AreEqual(r1, r1);
Assert.AreEqual(r1, r2);
Assert.AreEqual(r1, r2.Rotation(90));
Assert.AreEqual(r1, r2.Rotation(180));
Assert.AreEqual(r1, r2.Rotation(-90));
}
// Tests de distance entre rectangles et segments
[TestMethod]
public void TestRectangleSegmentDistance()
{
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 10, 10);
// Test avec segments confondus
Segment s11 = new Segment( new RealPoint(0, 0), new RealPoint(0, 10) );
Segment s12 = new Segment(new RealPoint(0, 10), new RealPoint(10, 10));
Segment s13 = new Segment(new RealPoint(10, 10), new RealPoint(10, 0));
Segment s14 = new Segment(new RealPoint(10, 0), new RealPoint(0, 0));
Assert.AreEqual(0, r1.Distance(s11));
Assert.AreEqual(0, r1.Distance(s12));
Assert.AreEqual(0, r1.Distance(s13));
Assert.AreEqual(0, r1.Distance(s14));
// Test avec segments décales
Segment s21 = new Segment(new RealPoint(20, 0), new RealPoint(20, 10));
Segment s22 = new Segment(new RealPoint(-10, 0), new RealPoint(-10, 10));
Segment s23 = new Segment(new RealPoint(0, -10), new RealPoint(10, -10));
Segment s24 = new Segment(new RealPoint(0, 20), new RealPoint(10, 20));
Assert.AreEqual(10, r1.Distance(s21));
Assert.AreEqual(10, r1.Distance(s22));
Assert.AreEqual(10, r1.Distance(s23));
Assert.AreEqual(10, r1.Distance(s24));
}
// Tests de distance entre plusieurs rectangles
[TestMethod]
public void TestRectanglesDistance()
{
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 10, 10);
// Polygones décalés vérticalements OU horizontalement + coincidence segment
Polygon r11 = new PolygonRectangle(new RealPoint(10, 0), 10, 10);
Polygon r12 = new PolygonRectangle(new RealPoint(-10, 0), 10, 10);
Polygon r13 = new PolygonRectangle(new RealPoint(0, 10), 10, 10);
Polygon r14 = new PolygonRectangle(new RealPoint(0, -10), 10, 10);
Assert.AreEqual(0, r1.Distance(r11));
Assert.AreEqual(0, r1.Distance(r12));
Assert.AreEqual(0, r1.Distance(r13));
Assert.AreEqual(0, r1.Distance(r14));
// Polygones décalés vérticalements ou horizontalement + coincidence coin
Polygon r21 = new PolygonRectangle(new RealPoint(10, 0), 10, 10);
Polygon r22 = new PolygonRectangle(new RealPoint(-10, 0), 10, 10);
Polygon r23 = new PolygonRectangle(new RealPoint(0, 10), 10, 10);
Polygon r24 = new PolygonRectangle(new RealPoint(0, -10), 10, 10);
Assert.AreEqual(0, r1.Distance(r21));
Assert.AreEqual(0, r1.Distance(r22));
Assert.AreEqual(0, r1.Distance(r23));
Assert.AreEqual(0, r1.Distance(r24));
// Polygones décalés vérticalements ET horizontalement
Polygon r31 = new PolygonRectangle(new RealPoint(20, 20), 10, 10);
Polygon r32 = new PolygonRectangle(new RealPoint(-20, -20), 10, 10);
Polygon r33 = new PolygonRectangle(new RealPoint(-20, -20), 10, 10);
Assert.AreEqual( Math.Sqrt(10*10+10*10), r1.Distance(r31));
Assert.AreEqual( Math.Sqrt(10*10+10*10), r1.Distance(r32));
}
// Tests de distance entre plusieurs rectangles qui se croisent
[TestMethod]
public void TestCrossRectanglesDistance()
{
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 10, 10);
Polygon r11 = new PolygonRectangle(new RealPoint(5, 5), 10, 10); // Rectangles qui se croisent sur 2 points
Assert.AreEqual(0, r1.Distance(r11));
Polygon r12 = new PolygonRectangle(new RealPoint(2, 2), 6, 6); // Rectangles imbriqués
Assert.AreEqual(0, r1.Distance(r12)); // Test imbrication rectangle A dans B
Assert.AreEqual(0, r12.Distance(r1)); // Test imbrication rectangle B dans A
}
// Tests de distance entre rectangle et Cercle
[TestMethod]
public void TestRectangleAndCircleDistance()
{
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 10, 10);
Circle c11 = new Circle(new RealPoint(0, 0), 10);
Assert.AreEqual(0, r1.Distance(c11));
Assert.AreEqual(0, c11.Distance(r1));
}
// Tests de distance entre rectangle et Cercle imbriqués
[TestMethod]
public void TestCrossRectangleAndCircleDistance()
{
Polygon r1 = new PolygonRectangle(new RealPoint(0, 0), 10, 10);
Circle c11 = new Circle( new RealPoint(5, 5), 2 );
Assert.AreEqual(0, r1.Distance(c11));
Assert.AreEqual(0, c11.Distance(r1));
}
}
}
<file_sep>/GoBot/GoBot/Actions/Asservissement/ActionVitessePivot.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionVitessePivot : IAction
{
private int _speed;
private Robot _robot;
public ActionVitessePivot(Robot r, int speed)
{
_robot = r;
_speed = speed;
}
public override String ToString()
{
return _robot.Name + " vitesse pivot à " + _speed;
}
void IAction.Executer()
{
_robot.SpeedConfig.PivotSpeed = _speed;
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Speed16;
}
}
}
}
<file_sep>/GoBot/GoBot/Communications/Frame.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace GoBot.Communications
{
[Serializable]
public class Frame
{
/// <summary>
/// Liste des octets de la trame
/// </summary>
private List<Byte> Bytes { get; set; }
/// <summary>
/// Liste des séparateurs entre les différents octets dans une chaine à convertir en trame
/// </summary>
private static char[] _separators = { '.', ' ', ':', ';', '-', '_', ',', '/', '\\' };
/// <summary>
/// Construit une trame à partir d'un tableau d'octets
/// </summary>
/// <param name="message">Octets à convertir</param>
public Frame(IEnumerable<Byte> message)
{
Bytes = new List<Byte>();
foreach (Byte b in message)
Bytes.Add((Byte)b);
}
/// <summary>
/// Construit une trame à partir d'une chaine de caractères (Format "01 23 45 67 89 AB CD EF")
/// </summary>
/// <param name="message">Message à convertir</param>
public Frame(String message)
{
Bytes = new List<Byte>();
String[] splits = message.Split(_separators,StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < splits.Length; i++)
{
try
{
Bytes.Add(byte.Parse(splits[i], System.Globalization.NumberStyles.HexNumber));
}
catch (Exception)
{
Bytes.Add(0);
}
}
}
/// <summary>
/// Retourne l'octet à l'index i
/// </summary>
/// <param name="i">Index de l'octet à retourner</param>
/// <returns>Octet à l'index i</returns>
public Byte this[int i]
{
get
{
return At(i);
}
}
/// <summary>
/// Retourne l'octet à l'index i
/// </summary>
/// <param name="i">Index de l'octet à retourner</param>
/// <returns>Octet à l'index i</returns>
public Byte At(int i)
{
int num = Bytes.ElementAt(i);
if(num >= 0 && num <= 255)
return (Byte)num;
return 0;
}
override public String ToString()
{
String output = "";
foreach (byte b in Bytes)
{
String val = String.Format("{0:x}", b);
if (val.Length == 1)
val = "0" + val;
output = output + val + " ";
}
output = output.TrimEnd().ToUpper();
return output;
}
/// <summary>
/// Convertit la trame en tableau d'octets
/// </summary>
/// <returns>Tableau d'octets correspondant à la trame</returns>
public byte[] ToBytes()
{
byte[] retour = new byte[Bytes.Count];
for(int i = 0; i < Bytes.Count; i++)
{
retour[i] = Bytes[i];
}
return retour;
}
/// <summary>
/// Longueur de la trame
/// </summary>
public int Length
{
get
{
return Bytes.Count;
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/Line.cs
using Geometry.Shapes.ShapesInteractions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
namespace Geometry.Shapes
{
/// <summary>
/// Droite avec une équation de la forme cy = ax + b
/// Pour une droite standard, c = 1
/// Pour une droite verticale, c = 0 et a = 1
/// </summary>
public class Line : IShape, IShapeModifiable<Line>
{
#region Attributs
protected double _a, _b, _c;
#endregion
#region Constructeurs
/// <summary>
/// Constructeur par défaut y = 0
/// </summary>
public Line()
{
_a = 0;
_b = 0;
_c = 1;
}
/// <summary>
/// Constructeur type cy = ax + b
/// </summary>
/// <param name="a">A</param>
/// <param name="b">B</param>
/// <param name="c">C</param>
public Line(double a, double b, double c = 1)
{
this._a = a;
this._b = b;
this._c = c;
}
/// <summary>
/// Construit la droite passant par deux points
/// </summary>
/// <param name="p1">Premier point</param>
/// <param name="p2">Deuxième point</param>
public Line(RealPoint p1, RealPoint p2)
{
SetLine(p1, p2);
}
/// <summary>
/// Construit la Droite à partir d'une autre Droite
/// </summary>
/// <param name="line">Droite à copier</param>
public Line(Line line)
{
_a = line.A;
_b = line.B;
_c = line.C;
}
/// <summary>
/// Contruit la Droite à partir d'une liste de points en interpolation.
/// Régression linéaire par la méthode des moindres carrés.
/// </summary>
/// <param name="points">Liste des points qui génèrent la droite</param>
public Line(IEnumerable<RealPoint> points)
{
double xAvg, yAvg, sum1, sum2;
sum1 = 0;
sum2 = 0;
xAvg = points.Average(p => p.X);
yAvg = points.Average(p => p.Y);
foreach (RealPoint p in points)
{
sum1 += (p.X - xAvg) * (p.Y - yAvg);
sum2 += (p.X - xAvg) * (p.X - xAvg);
}
if (sum2 == 0)
{
// Droite verticale
_a = 0;
_b = -points.ElementAt(0).X;
_c = 0;
}
else
{
_a = sum1 / sum2;
_b = yAvg - _a * xAvg;
_c = 1;
}
}
/// <summary>
/// Calcule l'équation de la droite passant par deux points
/// </summary>
/// <param name="p1">Premier point</param>
/// <param name="p2">Deuxième point</param>
protected void SetLine(RealPoint p1, RealPoint p2)
{
if (p2.X - p1.X == 0)
{
_a = 1;
_b = -p1.X;
_c = 0;
}
else
{
_a = (p2.Y - p1.Y) / (p2.X - p1.X);
_b = -(_a * p1.X - p1.Y);
_c = 1;
}
}
#endregion
#region Propriétés
/// <summary>
/// Accesseur sur le paramètre A de la droite sous la forme cy = ax + b
/// </summary>
public double A
{
get
{
return _a;
}
}
/// <summary>
/// Accesseur sur le paramètre B de la droite sous la forme cy = ax + b
/// </summary>
public double B
{
get
{
return _b;
}
}
/// <summary>
/// Accesseur sur le paramètre C de la droite sous la forme cy = ax + b
/// </summary>
public double C
{
get
{
return _c;
}
}
/// <summary>
/// Retourne vrai si la droite est parrallèle à l'axe des abscisses.
/// Dans ce cas l'équation donne Y = B
/// </summary>
public bool IsHorizontal
{
get
{
return _a == 0;
}
}
/// <summary>
/// Retourne vrai si la droite est parallèle à l'axe des ordonnées.
/// Dans ce cas l'équation donne X = -B
/// </summary>
public bool IsVertical
{
get
{
return _c == 0;
}
}
/// <summary>
/// Obtient la surface de la droite
/// </summary>
public virtual double Surface
{
get
{
return 0;
}
}
/// <summary>
/// Obtient le barycentre de la droite
/// </summary>
public virtual RealPoint Barycenter
{
get
{
return null; // Ca n'existe pas le barycentre d'une droite
}
}
#endregion
#region Opérateurs & Surcharges
public static bool operator ==(Line a, Line b)
{
if ((object)a == null || (object)b == null)
return (object)a == null && (object)b == null;
else
return Math.Abs(a.A - b.A) < RealPoint.PRECISION
&& Math.Abs(a.B - b.B) < RealPoint.PRECISION
&& Math.Abs(a.C - a.C) < RealPoint.PRECISION;
}
public static bool operator !=(Line a, Line b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
Line p = obj as Line;
if ((Object)p == null)
{
return false;
}
return (Line)obj == this;
}
public override int GetHashCode()
{
return (int)_a ^ (int)_b ^ (int)_c;
}
/// <summary>
/// Retourne une chaine contenant l'équation de la Droite
/// Droite verticale : x = valeur
/// Droite horizontale : y = valeur
/// Droite "normale" : y = valeur X + valeur
/// </summary>
/// <returns>Chaine représentant la Droite</returns>
public override string ToString()
{
String output;
String cString = C != 1 ? C.ToString("0.00") : "";
String aString = A != 1 ? A.ToString("0.00") : "";
if (this.IsVertical)
output = "X = " + ((-B).ToString("0.00"));
else if (this.IsHorizontal)
output = cString + "Y = " + B.ToString("0.00");
else if (B == 0)
output = cString + "Y = " + aString + "X";
else
output = cString + "Y = " + aString + "X " + (B > 0 ? "+ " : "- ") + Math.Abs(B).ToString("0.00");
return output;
}
#endregion
#region Distance
/// <summary>
/// Retourne la distance minimale entre la Droite et la forme donnée
/// </summary>
/// <param name="shape">IForme testée</param>
/// <returns>Distance minimale</returns>
public virtual double Distance(IShape shape)
{
double output = 0;
if (shape is RealPoint) output = LineWithRealPoint.Distance(this, shape as RealPoint);
else if (shape is Segment) output = LineWithSegment.Distance(this, shape as Segment);
else if (shape is Polygon) output = LineWithPolygon.Distance(this, shape as Polygon);
else if (shape is Circle) output = LineWithCircle.Distance(this, shape as Circle);
else if (shape is Line) output = LineWithLine.Distance(this, shape as Line);
return output;
}
#endregion
#region Contient
/// <summary>
/// Teste si la droite courante contient la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si la droite contient la forme donnée</returns>
public virtual bool Contains(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = LineWithRealPoint.Contains(this, shape as RealPoint);
else if (shape is Segment) output = LineWithSegment.Contains(this, shape as Segment);
else if (shape is Polygon) output = LineWithPolygon.Contains(this, shape as Polygon);
else if (shape is Circle) output = LineWithCircle.Contains(this, shape as Circle);
else if (shape is Line) output = LineWithLine.Contains(this, shape as Line);
return output;
}
#endregion
#region Croisement
/// <summary>
/// Retourne la liste des points de croisement avec la forme donnée
/// </summary>
/// <param name="shape">Forme à tester</param>
/// <returns>Liste des points de croisement</returns>
public virtual List<RealPoint> GetCrossingPoints(IShape shape)
{
List<RealPoint> output = new List<RealPoint>();
if (shape is RealPoint) output = LineWithRealPoint.GetCrossingPoints(this, shape as RealPoint);
else if (shape is Segment) output = LineWithSegment.GetCrossingPoints(this, shape as Segment);
else if (shape is Polygon) output = LineWithPolygon.GetCrossingPoints(this, shape as Polygon);
else if (shape is Circle) output = LineWithCircle.GetCrossingPoints(this, shape as Circle);
else if (shape is Line) output = LineWithLine.GetCrossingPoints(this, shape as Line);
return output;
}
/// <summary>
/// Teste si la droite courante croise la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si droite croise la forme testée</returns>
public virtual bool Cross(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = LineWithRealPoint.Cross(this, shape as RealPoint);
else if (shape is Segment) output = LineWithSegment.Cross(this, shape as Segment);
else if (shape is Polygon) output = LineWithPolygon.Cross(this, shape as Polygon);
else if (shape is Circle) output = LineWithCircle.Cross(this, shape as Circle);
else if (shape is Line) output = LineWithLine.Cross(this, shape as Line);
return output;
}
#endregion
#region Transformations
/// <summary>
/// Retourne une ligne qui est translatée des distances données
/// </summary>
/// <param name="dx">Distance en X</param>
/// <param name="dy">Distance en Y</param>
/// <returns>Ligne translatée des distances données</returns>
public Line Translation(double dx, double dy)
{
return new Line(_a, _b + dx + dy, _c);
}
/// <summary>
/// Retourne une ligne qui est tournée de l'angle donné
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation, si null (0, 0) est utilisé</param>
/// <returns>Droite tournée de l'angle donné</returns>
public Line Rotation(AngleDelta angle, RealPoint rotationCenter = null)
{
RealPoint p1, p2;
if (rotationCenter == null) rotationCenter = Barycenter;
if (_c == 1)
{
p1 = new RealPoint(0, _a * 0 + _b);
p2 = new RealPoint(1, _a * 1 + _b);
p1 = p1.Rotation(angle, rotationCenter);
p2 = p2.Rotation(angle, rotationCenter);
}
else
{
p1 = new RealPoint(_b, 0);
p2 = new RealPoint(_b, 1);
}
return new Line(p1, p2);
}
#endregion
/// <summary>
/// Retourne l'équation de la droite perpendiculaire à celle-ci et passant par un point donné
/// </summary>
/// <param name="point">Point contenu par la perpendiculaire recherchée</param>
/// <returns>Equation de la droite perpendiculaire à celle-ci et passant par le point donné</returns>
public Line GetPerpendicular(RealPoint point)
{
// Si je suis une droite verticale, je retourne l'horizontale qui passe par le point
if (C == 0)
return new Line(0, point.Y);
// Si je suis une droite horizontale, je retourne la verticale qui passe par le point
else if (A == 0)
return new Line(1, -point.X, 0);
// Si je suis une droite banale, je calcule
else
{
double newA = -1 / _a;
double newB = -newA * point.X + point.Y;
return new Line(newA, newB);
}
}
/// <summary>
/// Retourne la projection hortogonale du point sur la droite.
/// </summary>
/// <param name="point">Point à projet sur la droite</param>
/// <returns>Projection du point sur la droite</returns>
public RealPoint GetProjection(RealPoint point)
{
return GetCrossingPoints(GetPerpendicular(point))[0]; ;
}
public bool IsParallel(Line other)
{
// Les deux horizontales, les deux verticales, ou la même pente
return this.IsHorizontal && other.IsHorizontal ||
this.IsVertical && other.IsVertical ||
(!this.IsHorizontal && !this.IsVertical && !other.IsHorizontal && !other.IsVertical && this.A == other.A);
}
#region Peinture
/// <summary>
/// Dessine la ligne sur un Graphic
/// </summary>
/// <param name="g">Graphic sur lequel dessiner</param>
/// <param name="outline">Pen utilisé pour dessiner le contour de la ligne</param>
/// <param name="fill">Brush utilisé pour remplissage de la ligne</param>
/// <param name="scale">Echelle de conversion</param>
public virtual void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale)
{
// Un peu douteux mais bon
RealPoint p1, p2;
if (this.IsVertical)
{
p1 = GetCrossingPoints(new Line(new RealPoint(-100000, -100000), new RealPoint(+100000, -100000))).FirstOrDefault();
p2 = GetCrossingPoints(new Line(new RealPoint(-100000, +100000), new RealPoint(+100000, +100000))).FirstOrDefault();
}
else
{
p1 = GetCrossingPoints(new Line(new RealPoint(-100000, -100000), new RealPoint(-100000, +100000))).FirstOrDefault();
p2 = GetCrossingPoints(new Line(new RealPoint(+100000, -100000), new RealPoint(+100000, +100000))).FirstOrDefault();
}
if (p1 != null && p2 != null)
new Segment(p1, p2).Paint(g, outline, fill, scale);
}
#endregion
}
}
<file_sep>/GoBot/GoBot/Movements/Movement.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using Geometry;
using Geometry.Shapes;
using GoBot.GameElements;
using GoBot.PathFinding;
using GoBot.BoardContext;
namespace GoBot.Movements
{
public abstract class Movement
{
protected DateTime dateMinimum { get; set; }
protected DateTime startTime { get; set; }
protected int minimumOpponentDistance { get; set; }
/// <summary>
/// Facteur pour la normalisation du cout de l'action affiché à 1 pour la moins chère de toutes
/// </summary>
public double DisplayCostFactor { get; set; }
/// <summary>
/// Obtient si le mouvement est réalisable (par exemple stock pas plein)
/// </summary>
public abstract bool CanExecute { get; }
/// <summary>
/// Obtient le score rapporté par l'execution de l'action
/// </summary>
public abstract int Score { get; }
/// <summary>
/// Obtient la valeur de l'action, c'est à dire l'interet qu'il existe à la réaliser
/// </summary>
public abstract double Value { get; }
/// <summary>
/// Obtient la liste des positions à laquelle le mouvement est réalisable
/// </summary>
public List<Position> Positions { get; protected set; }
/// <summary>
/// Obtient l'élément en relation avec le mouvement (optionnel)
/// </summary>
public abstract GameElement Element { get; }
/// <summary>
/// Obtient le robot qui doit executer ce mouvement
/// </summary>
public abstract Robot Robot { get; }
/// <summary>
/// Obtient la couleur d'appartenance de l'action (ou blanc)
/// </summary>
public abstract Color Color { get; }
public Movement()
{
Positions = new List<Position>();
DisplayCostFactor = 1;
dateMinimum = DateTime.Now;
minimumOpponentDistance = 400;
}
/// <summary>
/// Execute le mouvement en enchainant l'action de début de mouvement, le pathfinding vers la position d'approche puis le mouvement lui même
/// </summary>
/// <returns>Retourne vrai si le mouvement a pu s'executer intégralement sans problème</returns>
public bool Execute()
{
Robots.MainRobot.Historique.Log("Début " + this.ToString());
startTime = DateTime.Now;
Position position = BestPosition;
Trajectory traj = null;
bool ok = true;
if (position != null)
{
bool alreadyOnPosition = (position.Coordinates.Distance(Robot.Position.Coordinates) < 10 && (position.Angle - Robot.Position.Angle) < 2);
if (!alreadyOnPosition)
traj = PathFinder.ChercheTrajectoire(Robot.Graph, GameBoard.ObstaclesAll, GameBoard.ObstaclesOpponents, new Position(Robot.Position), position, Robot.Radius, Robot.Width / 2);
if (alreadyOnPosition || traj != null)
{
MovementBegin();
if (alreadyOnPosition)
ok = true;
else
{
ok = Robot.RunTrajectory(traj);
}
if (ok)
{
ok = MovementCore();
if (ok)
Robots.MainRobot.Historique.Log("Fin réussie " + this.ToString() + " en " + (DateTime.Now - startTime).TotalSeconds.ToString("#.#") + "s");
else
Robots.MainRobot.Historique.Log("Fin ratée " + this.ToString() + " en " + (DateTime.Now - startTime).TotalSeconds.ToString("#.#") + "s");
}
else
{
Robots.MainRobot.Historique.Log("Annulation " + this.ToString() + ", trajectoire échouée");
ok = false;
}
MovementEnd();
}
else
{
Robots.MainRobot.Historique.Log("Annulation " + this.ToString() + ", trajectoire introuvable");
ok = false;
}
}
else
{
Robots.MainRobot.Historique.Log("Annulation " + this.ToString() + ", aucune position trouvée");
ok = false;
}
Robots.MainRobot.UpdateGraph(GameBoard.ObstaclesAll);
return ok;
}
public bool ExecuteHere()
{
bool ok;
MovementBegin();
ok = MovementCore();
MovementEnd();
return ok;
}
/// <summary>
/// Représente les actions à effectuer avant de se rendre à la position d'approche du mouvement
/// </summary>
protected abstract void MovementBegin();
/// <summary>
/// Représente les actions à effectuer une fois arrivé à la position d'approche du mouvement
/// </summary>
protected abstract bool MovementCore();
/// <summary>
/// Représente les actions à effectuer à la fin du mouvement, qu'il soit réussi ou non
/// </summary>
protected abstract void MovementEnd();
/// <summary>
/// Retourne vrai si la couleur de l'action correspond à la couleur du robot qui peut la réaliser
/// </summary>
/// <returns></returns>
public bool IsCorrectColor()
{
return (Color == null) || (Color == GameBoard.MyColor) || (Color == Color.White);
}
/// <summary>
/// Obtient la meilleure position d'approche pour aborder le mouvement.
/// Cette position est la plus proche de nous tout en étant à laa distance minimale réglementaire de tout adversaire
/// </summary>
public Position BestPosition
{
get
{
if (Positions.Count < 1)
return null;
if (Positions.Count == 1)
return Positions[0];
double closestDist = double.MaxValue;
Position closestPoint = Positions[0];
List<Circle> opponents = new List<IShape>(GameBoard.ObstaclesOpponents).OfType<Circle>().ToList();
foreach (Position position in Positions)
{
double distancePosition = Robot.Position.Coordinates.Distance(position.Coordinates);
double distanceAdv = double.MaxValue;
if (opponents.Count > 0)
{
distanceAdv = opponents.Min(op => position.Coordinates.Distance(op.Center));
if (distanceAdv < minimumOpponentDistance)
distancePosition = double.PositiveInfinity;
else
distancePosition -= Math.Sqrt(distanceAdv);
}
if (distancePosition < closestDist)
{
closestDist = distancePosition;
closestPoint = position;
}
}
return closestPoint;
}
}
/// <summary>
/// Coût global de l'action prenant en compte la valeur de l'action mais également le temps de trajectoire pour s'y rendre ou la proximité des adversaires
/// </summary>
public double GlobalCost
{
get
{
if (!IsAvailable || !CanExecute)
return double.MaxValue;
if (Value <= 0 && Positions.Count < 1)
return double.MaxValue;
Position position = BestPosition;
if (position == null)
return double.MaxValue;
double distance = Math.Max(50, Robot.Position.Coordinates.Distance(position.Coordinates)); // En dessous de 5cm de distance, tout se vaut
double cout = (Math.Sqrt(distance)) / Value;
bool adversairePlusProche = false;
List<IShape> opponents = new List<IShape>(GameBoard.ObstaclesOpponents);
foreach (Circle c in opponents)
{
double distanceAdv = position.Coordinates.Distance(c.Center);
if (distanceAdv < minimumOpponentDistance)
cout = double.PositiveInfinity;
else
cout /= ((distanceAdv / 10) * (distanceAdv / 10));
if (distanceAdv < distance)
adversairePlusProche = true;
}
if (adversairePlusProche)
cout *= 2;
return cout;
}
}
/// <summary>
/// Peint le mouvement en indiquant les différentes positions d'approche, la meilleure, et l'élément concerné
/// </summary>
/// <param name="g">Graphique sur lequel peindre</param>
/// <param name="scale">Echelle de conversion</param>
public void Paint(Graphics g, WorldScale scale)
{
Font font = new Font("Calibri", 8);
Pen penRedDot = new Pen(Color.Red);
penRedDot.DashStyle = DashStyle.Dot;
Pen penBlackDot = new Pen(Color.Black);
penBlackDot.DashStyle = DashStyle.Dot;
Pen penTransparent = new Pen(Color.FromArgb(40, Color.Black));
Brush brushTransparent = new SolidBrush(Color.FromArgb(40, Color.Black));
Point point;
if (Element != null)
{
Point pointElement = scale.RealToScreenPosition(Element.Position);
if (GlobalCost != double.MaxValue && !double.IsInfinity(GlobalCost))
{
Point pointProche = scale.RealToScreenPosition(BestPosition.Coordinates);
foreach (Position p in Positions)
{
point = scale.RealToScreenPosition(p.Coordinates);
if (point != pointProche)
{
g.FillEllipse(Brushes.Red, point.X - 2, point.Y - 2, 4, 4);
g.DrawLine(penRedDot, point, pointElement);
}
}
g.FillEllipse(Brushes.White, pointProche.X - 2, pointProche.Y - 2, 4, 4);
g.DrawLine(Pens.White, pointProche, pointElement);
g.DrawString((GlobalCost / DisplayCostFactor).ToString("0.00"), font, Brushes.White, pointProche);
}
else
{
if (!IsCorrectColor())
{
foreach (Position p in Positions)
{
point = scale.RealToScreenPosition(p.Coordinates);
g.FillEllipse(brushTransparent, point.X - 2, point.Y - 2, 4, 4);
g.DrawLine(penTransparent, point, pointElement);
}
}
else
{
foreach (Position p in Positions)
{
point = scale.RealToScreenPosition(p.Coordinates);
g.FillEllipse(Brushes.Black, point.X - 2, point.Y - 2, 4, 4);
g.DrawLine(penBlackDot, point, pointElement);
}
}
}
}
brushTransparent.Dispose();
penTransparent.Dispose();
penBlackDot.Dispose();
penRedDot.Dispose();
font.Dispose();
}
/// <summary>
/// Désactive le mouvement pendant une durée determinée.
/// Le mouvement aura une valeur nulle jusqu'à sa réactivation.
/// </summary>
/// <param name="duration">Durée de désactivation du mouvement</param>
public void Deactivate(TimeSpan duration)
{
dateMinimum = DateTime.Now + duration;
}
/// <summary>
/// Réactive le mouvement avant la fin de l'attente de la durée de désactivation
/// </summary>
public void Reactivate()
{
dateMinimum = DateTime.Now;
}
/// <summary>
/// Retourne vrai si l'action n'est pas désactivée
/// </summary>
public Boolean IsAvailable
{
get
{
// Si il faut attendre avant de faire cette action
return DateTime.Now >= dateMinimum;
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelServoCan.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using GoBot.Threading;
using GoBot.Devices.CAN;
using GoBot.Devices;
using System.Linq;
using System.Reflection;
using GoBot.Actionneurs;
namespace GoBot.IHM
{
public partial class PanelServoCan : UserControl
{
private ThreadLink _linkPolling, _linkDrawing;
private CanServo _servo;
private PositionableServo _currentPositionable;
public Dictionary<String, PropertyInfo> _positionsProp;
public PanelServoCan()
{
InitializeComponent();
numID.Maximum = Enum.GetValues(typeof(ServomoteurID)).Cast<int>().Max();
}
public void SetServo(ServomoteurID servo)
{
if (_servo is null || _servo.ID != servo)
{
numID.Value = (int)(servo);
_servo = AllDevices.CanServos[(ServomoteurID)numID.Value];
picConnection.Visible = false;
lblName.Text = "";
ReadValues();
_currentPositionable = FindPositionnableFromServo(servo);
SetPositions(_currentPositionable);
}
}
private PositionableServo FindPositionnableFromServo(ServomoteurID servo)
{
PropertyInfo[] properties = Config.CurrentConfig.GetType().GetProperties();
List<PositionableServo> positionnables = properties.Where(o => typeof(PositionableServo).IsAssignableFrom(o.PropertyType)).Select(o => o.GetValue(Config.CurrentConfig, null)).Cast<PositionableServo>().ToList();
return positionnables.Where(o => o.ID == servo).FirstOrDefault();
}
private void SetPositions(Positionable pos)
{
cboPositions.Items.Clear();
btnSavePosition.Enabled = false;
if (pos != null)
{
PropertyInfo[] properties = pos.GetType().GetProperties();
List<String> noms = new List<string>();
_positionsProp = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo property in properties)
{
if (property.Name != "ID")
{
noms.Add(Config.PropertyNameToScreen(property) + " : " + property.GetValue(pos, null));
_positionsProp.Add(noms[noms.Count - 1], property);
}
}
cboPositions.Enabled = true;
cboPositions.Items.AddRange(noms.ToArray());
}
else
{
cboPositions.Enabled = false;
}
}
private void DrawTimeArrow()
{
Bitmap bmp = new Bitmap(picArrow.Width, picArrow.Height);
Graphics g = Graphics.FromImage(bmp);
Pen p = new Pen(Color.DimGray, 1);
g.SmoothingMode = SmoothingMode.AntiAlias;
p.StartCap = LineCap.Custom;
p.EndCap = LineCap.Custom;
p.CustomStartCap = p.CustomEndCap = new AdjustableArrowCap(3, 3);
g.DrawLine(p, new Point(0, picArrow.Height / 2), new Point(picArrow.Width, picArrow.Height / 2));
p.Dispose();
picArrow.Image = bmp;
lblTrajectoryTime.Visible = true;
}
private void trackBarPosition_TickValueChanged(object sender, double value)
{
numPosition.Value = (int)value;
}
private void boxTorque_ValueChanged(object sender, bool value)
{
if (value)
{
_linkPolling = ThreadManager.CreateThread(link => GetServoInfos());
_linkPolling.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 20));
_linkDrawing = ThreadManager.CreateThread(link => DrawTorqueCurve());
_linkDrawing.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 100));
}
else
{
_linkPolling.Cancel();
_linkDrawing.Cancel();
_linkPolling.WaitEnd();
_linkDrawing.WaitEnd();
_linkPolling = null;
_linkDrawing = null;
}
}
private void GetServoInfos()
{
_linkPolling.RegisterName(" : " + _servo.ID.ToString());
gphMonitoringTorque.AddPoint("Couple", _servo.ReadTorqueCurrent(), Color.Firebrick, true);
gphMonitoringTorque.AddPoint("Alerte", _servo.LastTorqueMax, Color.Red, false);
gphMonitoringPos.AddPoint("Position", _servo.ReadPosition(), Color.RoyalBlue);
}
private void DrawTorqueCurve()
{
_linkDrawing.RegisterName(" : " + _servo.ID.ToString());
this.InvokeAuto(() =>
{
gphMonitoringPos.DrawCurves();
gphMonitoringTorque.DrawCurves();
});
}
private void btnGo_Click(object sender, EventArgs e)
{
_servo.SetTrajectory((int)numPosition.Value, (int)numSpeedMax.Value, (int)numAccel.Value);
}
private void numPosition_ValueChanged(object sender, EventArgs e)
{
_servo.SetPosition((int)numPosition.Value);
}
private void numPositionMin_ValueChanged(object sender, EventArgs e)
{
int val = (int)numPositionMin.Value;
if (_servo.LastPositionMin != val)
{
_servo.SetPositionMin(val);
gphMonitoringPos.MinLimit = val;
}
trkPosition.Min = val;
}
private void numPositionMax_ValueChanged(object sender, EventArgs e)
{
int val = (int)numPositionMax.Value;
if (_servo.LastPositionMax != val)
{
_servo.SetPositionMax(val);
gphMonitoringPos.MaxLimit = val;
}
trkPosition.Max = val;
}
private void numAccel_ValueChanged(object sender, EventArgs e)
{
if (_servo.LastAcceleration != (int)numAccel.Value)
_servo.SetAcceleration((int)numAccel.Value);
}
private void numSpeedMax_ValueChanged(object sender, EventArgs e)
{
if (_servo.LastSpeedMax != (int)numSpeedMax.Value)
_servo.SetSpeedMax((int)numSpeedMax.Value);
}
private void numTorqueMax_ValueChanged(object sender, EventArgs e)
{
if (_servo.LastTorqueMax != (int)numTorqueMax.Value)
{
_servo.SetTorqueMax((int)numTorqueMax.Value);
gphMonitoringTorque.MaxLimit = _servo.LastTorqueMax * 1.5;
}
}
private void trkTrajectoryTarget_ValueChanged(object sender, double value)
{
lblTrajectoryTarget.Text = trkTrajectoryTarget.Value.ToString();
DrawTrajectoryGraphs();
}
private void trkTrajectorySpeed_ValueChanged(object sender, double value)
{
lblTrajectorySpeed.Text = trkTrajectorySpeed.Value.ToString();
DrawTrajectoryGraphs();
}
private void trkTrajectoryAccel_ValueChanged(object sender, double value)
{
lblTrajectoryAccel.Text = trkTrajectoryAccel.Value.ToString();
DrawTrajectoryGraphs();
}
private void numID_ValueChanged(object sender, EventArgs e)
{
SetServo((ServomoteurID)numID.Value);
}
private void DrawTrajectoryGraphs()
{
SpeedConfig config = new SpeedConfig((int)trkTrajectorySpeed.Value, (int)trkTrajectoryAccel.Value, (int)trkTrajectoryAccel.Value, 0, 0, 0);
SpeedSample sample = new SpeedSampler(config).SampleLine(_servo.LastPosition, (int)trkTrajectoryTarget.Value, gphTrajectoryPosition.Width);
gphTrajectorySpeed.DeleteCurve("Vitesse");
gphTrajectoryPosition.DeleteCurve("Position");
if (sample.Valid)
{
sample.Speeds.ForEach(s => gphTrajectorySpeed.AddPoint("Vitesse", s, Color.Purple));
gphTrajectorySpeed.DrawCurves();
sample.Positions.ForEach(s => gphTrajectoryPosition.AddPoint("Position", s, Color.ForestGreen));
gphTrajectoryPosition.DrawCurves();
lblTrajectoryTime.Text = sample.Duration.TotalSeconds.ToString("0.0") + "s";
}
if (picArrow.Image == null) DrawTimeArrow();
}
private void btnStop_Click(object sender, EventArgs e)
{
_servo.DisableOutput();
}
private void btnAutoMax_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Lancer une recherche automatique de maximum ?", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
btnAutoMax.Enabled = false;
ThreadManager.CreateThread(link =>
{
link.Name = "Recherche servo max";
_servo.SearchMax();
this.InvokeAuto(() => ReadValues());
btnAutoMin.InvokeAuto(() => btnAutoMax.Enabled = true);
}).StartThread();
}
}
private void btnAutoMin_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Lancer une recherche automatique de minimum ?", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
btnAutoMin.Enabled = false;
ThreadManager.CreateThread(link =>
{
link.Name = "Recherche servo min";
_servo.SearchMin();
this.InvokeAuto(() => ReadValues());
btnAutoMin.InvokeAuto(() => btnAutoMin.Enabled = true);
}).StartThread();
}
}
private void PanelServoCan_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
gphMonitoringTorque.ScaleMode = Composants.GraphPanel.ScaleType.FixedIfEnough;
gphMonitoringPos.ScaleMode = Composants.GraphPanel.ScaleType.FixedIfEnough;
}
}
private void btnSauvegarderPosition_Click(object sender, EventArgs e)
{
int index = cboPositions.SelectedIndex;
_positionsProp[(String)cboPositions.SelectedItem].SetValue(_currentPositionable, _servo.ReadPosition(), null);
SetPositions(_currentPositionable);
cboPositions.SelectedIndex = index;
Config.Save();
}
private void cboPositions_SelectedIndexChanged(object sender, EventArgs e)
{
btnSavePosition.Enabled = true;
}
private void ReadValues()
{
try
{
numPositionMin.Value = _servo.ReadPositionMin();
numPositionMax.Value = _servo.ReadPositionMax();
numPosition.Value = _servo.ReadPosition();
numAccel.Value = _servo.ReadAcceleration();
numSpeedMax.Value = _servo.ReadSpeedMax();
numTorqueMax.Value = _servo.ReadTorqueMax();
trkPosition.Min = _servo.LastPositionMin;
trkPosition.Max = _servo.LastPositionMax;
trkPosition.SetValue(_servo.LastPosition, false);
//trkTrajectoryTarget.Min = _servo.LastPositionMin;
//trkTrajectoryTarget.Max = _servo.LastPositionMax;
//trkTrajectoryTarget.SetValue(_servo.LastPosition);
//trkTrajectorySpeed.SetValue(_servo.LastSpeedMax);
//trkTrajectoryAccel.SetValue(_servo.LastAcceleration);
gphMonitoringTorque.MinLimit = 0;
gphMonitoringTorque.MaxLimit = _servo.LastTorqueMax * 1.5;
gphMonitoringPos.MinLimit = _servo.LastPositionMin;
gphMonitoringPos.MaxLimit = _servo.LastPositionMax;
picConnection.Visible = true;
picConnection.Image = GoBot.Properties.Resources.ConnectionOk;
lblName.Text = NameFinder.GetName(_servo.ID);
grpControl.Enabled = true;
grpMonitoring.Enabled = true;
grpTrajectory.Enabled = true;
grpSettings.Enabled = true;
grpPositions.Enabled = true;
}
catch
{
picConnection.Visible = true;
picConnection.Image = GoBot.Properties.Resources.ConnectionNok;
lblName.Text = "Pas de connexion";
grpControl.Enabled = false;
grpMonitoring.Enabled = false;
grpTrajectory.Enabled = false;
grpSettings.Enabled = false;
grpPositions.Enabled = false;
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/Circle.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using Geometry.Shapes.ShapesInteractions;
namespace Geometry.Shapes
{
public class Circle : IShape, IShapeModifiable<Circle>
{
#region Attributs
private RealPoint _center;
private double _radius;
#endregion
#region Constructeurs
/// <summary>
/// Construit un cercle depuis son centre et son rayon
/// </summary>
/// <param name="center">Point central du cercle</param>
/// <param name="radius">Rayon du cercle</param>
public Circle(RealPoint center, double radius)
{
if (radius < 0) throw new ArgumentException("Radius must be >= 0");
_center = center;
_radius = radius;
}
/// <summary>
/// Construit un cercle depuis un autre cercle
/// </summary>
/// <param name="circle">cercle à copier</param>
public Circle(Circle circle)
{
_center = circle._center;
_radius = circle._radius;
}
#endregion
#region Propriétés
/// <summary>
/// Obtient le centre du cercle
/// </summary>
public RealPoint Center { get { return _center; } }
/// <summary>
/// Obtient le rayon du cercle
/// </summary>
public double Radius { get { return _radius; } }
/// <summary>
/// Obtient la surface du cercle
/// </summary>
public double Surface { get { return _radius * _radius * Math.PI; } }
/// <summary>
/// Obtient le barycentre du cercle
/// </summary>
public RealPoint Barycenter { get { return _center; } }
#endregion
#region Opérateurs & Surcharges
public static bool operator ==(Circle a, Circle b)
{
if ((object)a == null || (object)b == null)
return (object)a == null && (object)b == null;
else
return Math.Abs(a.Radius - b.Radius) < RealPoint.PRECISION
&& a.Center == b.Center;
}
public static bool operator !=(Circle a, Circle b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
Circle p = obj as Circle;
if ((Object)p == null)
{
return false;
}
return (Circle)obj == this;
}
public override int GetHashCode()
{
return (int)(_center.GetHashCode()) ^ (int)_radius;
}
public override string ToString()
{
return "C = " + _center.ToString() + "; R = " + _radius.ToString("0.00");
}
#endregion
#region Distance
/// <summary>
/// Retourne la distance minimale entre le cercle courant et la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Distance minimale</returns>
public double Distance(IShape shape)
{
double output = 0;
if (shape is RealPoint) output = CircleWithRealPoint.Distance(this, shape as RealPoint);
else if (shape is Segment) output = CircleWithSegment.Distance(this, shape as Segment);
else if (shape is Polygon) output = CircleWithPolygon.Distance(this, shape as Polygon);
else if (shape is Circle) output = CircleWithCircle.Distance(this, shape as Circle);
else if (shape is Line) output = CircleWithLine.Distance(this, shape as Line);
return output;
}
#endregion
#region Contient
/// <summary>
/// Teste si le cercle courant contient la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si le cercle contient la forme testée</returns>
public bool Contains(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = CircleWithRealPoint.Contains(this, shape as RealPoint);
else if (shape is Segment) output = CircleWithSegment.Contains(this, shape as Segment);
else if (shape is Polygon) output = CircleWithPolygon.Contains(this, shape as Polygon);
else if (shape is Circle) output = CircleWithCircle.Contains(this, shape as Circle);
else if (shape is Line) output = CircleWithLine.Contains(this, shape as Line);
return output;
}
#endregion
#region Croise
/// <summary>
/// Retourne la liste des points de croisement avec la forme donnée
/// </summary>
/// <param name="shape">Forme à tester</param>
/// <returns>Liste des points de croisement</returns>
public List<RealPoint> GetCrossingPoints(IShape shape)
{
List<RealPoint> output = new List<RealPoint>();
if (shape is RealPoint) output = CircleWithRealPoint.GetCrossingPoints(this, shape as RealPoint);
else if (shape is Segment) output = CircleWithSegment.GetCrossingPoints(this, shape as Segment);
else if (shape is Polygon) output = CircleWithPolygon.GetCrossingPoints(this, shape as Polygon);
else if (shape is Circle) output = CircleWithCircle.GetCrossingPoints(this, shape as Circle);
else if (shape is Line) output = CircleWithLine.GetCrossingPoints(this, shape as Line);
return output;
}
/// <summary>
/// Teste si le cercle courant croise la forme donnée
/// </summary>
/// <param name="shape">Forme testéé</param>
/// <returns>Vrai si le cercle courant croise la forme donnée</returns>
public bool Cross(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = CircleWithRealPoint.Cross(this, shape as RealPoint);
else if (shape is Segment) output = CircleWithSegment.Cross(this, shape as Segment);
else if (shape is Polygon) output = CircleWithPolygon.Cross(this, shape as Polygon);
else if (shape is Circle) output = CircleWithCircle.Cross(this, shape as Circle);
else if (shape is Line) output = CircleWithLine.Cross(this, shape as Line);
return output;
}
#endregion
#region Transformations
/// <summary>
/// Retourne un cercle qui est translaté des distances données
/// </summary>
/// <param name="dx">Distance en X</param>
/// <param name="dy">Distance en Y</param>
/// <returns>Cercle translaté des distances données</returns>
public Circle Translation(double dx, double dy)
{
return new Circle(_center.Translation(dx, dy), _radius);
}
/// <summary>
/// Retourne un cercle qui est tourné de l'angle donné
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation, si null le barycentre est utilisé</param>
/// <returns>Cercle tourné de l'angle donné</returns>
public Circle Rotation(AngleDelta angle, RealPoint rotationCenter = null)
{
if (rotationCenter == null) rotationCenter = Barycenter;
return new Circle(_center.Rotation(angle, rotationCenter), _radius);
}
#endregion
#region Peinture
/// <summary>
/// Dessine le cercle sur un Graphic
/// </summary>
/// <param name="g">Graphic sur lequel dessiner</param>
/// <param name="outline">Pen utilisé pour dessiner le contour du cercle</param>
/// <param name="fill">Brush utilisé pour remplissage du cercle</param>
/// <param name="scale">Echelle de conversion</param>
public void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale)
{
Point screenPosition = scale.RealToScreenPosition(Center);
int screenRadius = scale.RealToScreenDistance(Radius);
if (fill != null)
g.FillEllipse(fill, new Rectangle(screenPosition.X - screenRadius, screenPosition.Y - screenRadius, screenRadius * 2, screenRadius * 2));
if (outline != null)
g.DrawEllipse(outline, new Rectangle(screenPosition.X - screenRadius, screenPosition.Y - screenRadius, screenRadius * 2, screenRadius * 2));
}
#endregion
}
}
<file_sep>/GoBot/GoBot/GameElements/GroundedZone.cs
using Geometry.Shapes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.GameElements
{
public class GroundedZone : GameElementZone
{
private List<Buoy> _buoys;
public GroundedZone(RealPoint position, Color color, List<Buoy> buoys) : base(position, color, 150)
{
_buoys = buoys;
}
public List<Buoy> Buoys => _buoys;
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/SegmentWithLine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class SegmentWithLine
{
public static bool Contains(Segment containingSegment, Line containedLine)
{
// Un segment fini ne peut pas contenir une droite infinie.
return false;
}
public static bool Cross(Segment segment, Line line)
{
return LineWithSegment.Cross(line, segment);
}
public static double Distance(Segment segment, Line line)
{
return LineWithSegment.Distance(line, segment);
}
public static List<RealPoint> GetCrossingPoints(Segment segment, Line line)
{
return LineWithSegment.GetCrossingPoints(line, segment);
}
}
}
<file_sep>/GoBot/GoBot/Communications/UDP/UdpFrameFactory.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Devices;
using System.Collections.Generic;
using System.Drawing;
using System;
namespace GoBot.Communications.UDP
{
static class UdpFrameFactory
{
static public UdpFrameFunction ExtractFunction(Frame frame)
{
return (UdpFrameFunction)frame[1];
}
static public Board ExtractBoard(Frame frame)
{
return (Board)frame[0];
}
static public Board ExtractSender(Frame frame, bool isInput)
{
return isInput ? (Board)frame[0] : Board.PC;
}
static public Board ExtractReceiver(Frame frame, bool isInput)
{
return isInput ? Board.PC : (Board)frame[0];
}
private static byte ByteDivide(int valeur, bool poidsFort)
{
byte b;
if (poidsFort)
b = (byte)(valeur >> 8);
else
b = (byte)(valeur & 0x00FF);
return b;
}
static public Frame Debug(Board board, int numDebug)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
switch(board)
{
case Board.RecIO:
tab[1] = (byte)UdpFrameFunction.Debug;
break;
case Board.RecMove:
tab[1] = (byte)UdpFrameFunction.Debug;
break;
}
tab[2] = (byte)numDebug;
return new Frame(tab);
}
static public Frame DemandeTensionBatterie(Board board)
{
byte[] tab = new byte[2];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandeTension;
return new Frame(tab);
}
static public Frame DemandeCapteurCouleur(Board board, SensorColorID capteur)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandeCapteurCouleur;
tab[2] = (byte)capteur;
return new Frame(tab);
}
static public Frame DemandeMesureLidar(LidarID lidar)
{
byte[] tab = new byte[3];
tab[0] = (byte)Board.RecMove;
tab[1] = (byte)UdpFrameFunction.DemandeLidar;
tab[2] = (byte)lidar;
return new Frame(tab);
}
static public Frame ActionneurOnOff(Board board, ActuatorOnOffID actionneur, bool onOff)
{
byte[] tab = new byte[4];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.PilotageOnOff;
tab[2] = (byte)actionneur;
tab[3] = (byte)(onOff ? 1 : 0);
return new Frame(tab);
}
static public Frame DemandeCapteurOnOff(Board board, SensorOnOffID capteur)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandeCapteurOnOff;
tab[2] = (byte)capteur;
return new Frame(tab);
}
static public Frame MoteurPosition(Board board, MotorID moteur, int position)
{
byte[] tab = new byte[5];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurPosition;
tab[2] = (byte)moteur;
tab[3] = (byte)ByteDivide(position, true);
tab[4] = (byte)ByteDivide(position, false);
return new Frame(tab);
}
static public Frame MoteurStop(Board board, MotorID moteur, StopMode mode)
{
byte[] tab = new byte[4];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurStop;
tab[2] = (byte)moteur;
tab[3] = (byte)mode;
return new Frame(tab);
}
static public Frame MoteurVitesse(Board board, MotorID moteur, SensGD sens, int vitesse)
{
byte[] tab = new byte[6];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurVitesse;
tab[2] = (byte)moteur;
tab[3] = (byte)sens;
tab[4] = (byte)ByteDivide(vitesse, true);
tab[5] = (byte)ByteDivide(vitesse, false);
return new Frame(tab);
}
static public Frame MoteurAcceleration(Board board, MotorID moteur, int acceleration)
{
byte[] tab = new byte[5];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurAccel;
tab[2] = (byte)moteur;
tab[3] = (byte)ByteDivide(acceleration, true);
tab[4] = (byte)ByteDivide(acceleration, false);
return new Frame(tab);
}
static public Frame MoteurResetPosition(Board board, MotorID moteur)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurResetPosition;
tab[2] = (byte)moteur;
return new Frame(tab);
}
static public Frame MoteurOrigin(Board board, MotorID moteur)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.MoteurOrigin;
tab[2] = (byte)moteur;
return new Frame(tab);
}
static public Frame Deplacer(SensAR sens, int distance, Robot robot)
{
byte[] tab = new byte[5];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.Deplace;
tab[2] = (byte)sens;
tab[3] = ByteDivide(distance, true);
tab[4] = ByteDivide(distance, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame OffsetPos(Position pos, Robot robot)
{
byte[] tab = new byte[8];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserEnvoiPositionAbsolue;
tab[2] = ByteDivide((int)pos.Coordinates.X, true);
tab[3] = ByteDivide((int)pos.Coordinates.X, false);
tab[4] = ByteDivide((int)pos.Coordinates.Y, true);
tab[5] = ByteDivide((int)pos.Coordinates.Y, false);
tab[6] = ByteDivide((int)(pos.Angle.InPositiveDegrees * 100), true);
tab[7] = ByteDivide((int)(pos.Angle.InPositiveDegrees * 100), false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame Pivot(SensGD sens, AngleDelta angle, Robot robot)
{
byte[] tab = new byte[7];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.Pivot;
tab[2] = (byte)sens;
tab[3] = ByteDivide((int)(angle * 100.0), true);
tab[4] = ByteDivide((int)(angle * 100.0), false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame Stop(StopMode mode, Robot robot)
{
byte[] tab = new byte[3];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.Stop;
tab[2] = (byte)mode;
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandePositionContinue(int intervalle, Robot robot)
{
byte[] tab = new byte[3];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserIntervalleRetourPosition;
tab[2] = (byte)(intervalle / 10.0);
Frame retour = new Frame(tab);
return retour;
}
static public Frame CoeffAsserv(int p, int i, int d, Robot robot)
{
byte[] tab = new byte[8];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserPID;
tab[2] = (byte)ByteDivide(p, true);
tab[3] = (byte)ByteDivide(p, false);
tab[4] = (byte)ByteDivide(i, true);
tab[5] = (byte)ByteDivide(i, false);
tab[6] = (byte)ByteDivide(d, true);
tab[7] = (byte)ByteDivide(d, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame CoeffAsservCap(int p, int i, int d, Robot robot)
{
byte[] tab = new byte[8];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserPIDCap;
tab[2] = (byte)ByteDivide(p / 100, true);
tab[3] = (byte)ByteDivide(p / 100, false);
tab[4] = (byte)ByteDivide(i, true);
tab[5] = (byte)ByteDivide(i, false);
tab[6] = (byte)ByteDivide(d / 100, true);
tab[7] = (byte)ByteDivide(d / 100, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame CoeffAsservVitesse(int p, int i, int d, Robot robot)
{
byte[] tab = new byte[8];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserPID;
tab[2] = (byte)ByteDivide(p, true);
tab[3] = (byte)ByteDivide(p, false);
tab[4] = (byte)ByteDivide(i, true);
tab[5] = (byte)ByteDivide(i, false);
tab[6] = (byte)ByteDivide(d, true);
tab[7] = (byte)ByteDivide(d, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame Virage(SensAR sensAr, SensGD sensGd, int rayon, AngleDelta angle, Robot robot)
{
byte[] tab = new byte[8];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.Virage;
tab[2] = (byte)sensAr;
tab[3] = (byte)sensGd;
tab[4] = (byte)ByteDivide(rayon, true);
tab[5] = (byte)ByteDivide(rayon, false);
tab[6] = (byte)ByteDivide((int)(angle * 100), true);
tab[7] = (byte)ByteDivide((int)(angle * 100), false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame TrajectoirePolaire(SensAR sensAr, List<RealPoint> points, Robot robot)
{
byte[] tab = new byte[5 + points.Count * 2 * 2];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.TrajectoirePolaire;
tab[2] = (byte)sensAr;
tab[3] = (byte)ByteDivide(points.Count, true);
tab[4] = (byte)ByteDivide(points.Count, false);
for (int i = 0; i < points.Count; i++)
{
tab[5 + i * 4 + 0] = ByteDivide((int)(points[i].X * 10), true);
tab[5 + i * 4 + 1] = ByteDivide((int)(points[i].X * 10), false);
tab[5 + i * 4 + 2] = ByteDivide((int)(points[i].Y * 10), true);
tab[5 + i * 4 + 3] = ByteDivide((int)(points[i].Y * 10), false);
}
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandePosition(Robot robot)
{
byte[] tab = new byte[2];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserDemandePositionXYTeta;
Frame retour = new Frame(tab);
return retour;
}
static public Frame VitesseLigne(int vitesse, Robot robot)
{
byte[] tab = new byte[4];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserVitesseDeplacement;
tab[2] = (byte)ByteDivide(vitesse, true);
tab[3] = (byte)ByteDivide(vitesse, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame AccelLigne(int accelDebut, int accelFin, Robot robot)
{
byte[] tab = new byte[6];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserAccelerationDeplacement;
tab[2] = (byte)ByteDivide(accelDebut, true);
tab[3] = (byte)ByteDivide(accelDebut, false);
tab[4] = (byte)ByteDivide(accelFin, true);
tab[5] = (byte)ByteDivide(accelFin, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame VitessePivot(int vitesse, Robot robot)
{
byte[] tab = new byte[4];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserVitessePivot;
tab[2] = (byte)ByteDivide(vitesse, true);
tab[3] = (byte)ByteDivide(vitesse, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame AccelPivot(int accel, Robot robot)
{
byte[] tab = new byte[4];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserAccelerationPivot;
tab[2] = (byte)ByteDivide(accel, true);
tab[3] = (byte)ByteDivide(accel, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame Recallage(SensAR sens, Robot robot)
{
byte[] tab = new byte[3];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.Recallage;
tab[2] = (byte)sens;
Frame retour = new Frame(tab);
return retour;
}
static public Frame TestConnexion(Board board)
{
byte[] tab = new byte[2];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.TestConnexion;
return new Frame(tab);
}
static public Frame EnvoiConsigneBrute(int consigne, SensAR sens, Robot robot)
{
byte[] tab = new byte[5];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserEnvoiConsigneBrutePosition;
tab[2] = (byte)sens;
tab[3] = (byte)ByteDivide(consigne, true);
tab[4] = (byte)ByteDivide(consigne, false);
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandePositionsCodeurs(Robot robot)
{
byte[] tab = new byte[2];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.AsserDemandePositionCodeurs;
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandeValeursAnalogiques(Board board)
{
byte[] tab = new byte[2];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandeValeursAnalogiques;
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandeValeursNumeriques(Board board)
{
byte[] tab = new byte[2];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandeValeursNumeriques;
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandeCpuPwm(Robot robot)
{
byte[] tab = new byte[2];
tab[0] = (byte)robot.AsservBoard;
tab[1] = (byte)UdpFrameFunction.DemandeChargeCPU_PWM;
Frame retour = new Frame(tab);
return retour;
}
static public Frame EnvoyerUart1(Board board, Frame trame)
{
byte[] tab = new byte[3 + trame.Length];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.EnvoiUart1;
tab[2] = (byte)trame.Length;
for (int i = 0; i < trame.Length; i++)
tab[3 + i] = trame[i];
Frame retour = new Frame(tab);
return retour;
}
static public Frame EnvoyerCAN(Board board, Frame trame)
{
byte[] tab = new byte[3 + trame.Length];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.EnvoiCAN;
tab[2] = (byte)trame.Length;
for (int i = 0; i < trame.Length; i++)
tab[3 + i] = trame[i];
Frame retour = new Frame(tab);
return retour;
}
static public Frame EnvoyerUart2(Board board, Frame trame)
{
byte[] tab = new byte[3 + trame.Length];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.EnvoiUart2;
tab[2] = (byte)trame.Length;
for (int i = 0; i < trame.Length; i++)
tab[3 + i] = trame[i];
Frame retour = new Frame(tab);
return retour;
}
static public Frame CodeurPosition(Board board, CodeurID codeur)
{
byte[] tab = new byte[3];
tab[0] = (byte)board;
tab[1] = (byte)UdpFrameFunction.DemandePositionCodeur;
tab[2] = (byte)codeur;
Frame retour = new Frame(tab);
return retour;
}
static public Frame DemandeCouleurEquipe()
{
byte[] tab = new byte[2];
tab[0] = (byte)Board.RecMove;
tab[1] = (byte)UdpFrameFunction.DemandeCouleurEquipe;
return new Frame(tab);
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/LineWithCircle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
public static class LineWithCircle
{
public static bool Contains(Line containingLine, Circle containedCircle)
{
// Une droite contient un cercle si son rayon est nul et qu'il est sur la droite
return containedCircle.Radius == 0 && containingLine.Contains(containedCircle.Center);
}
public static bool Cross(Line line, Circle circle)
{
return CircleWithLine.Cross(circle, line);
}
public static double Distance(Line line, Circle circle)
{
return CircleWithLine.Distance(circle, line);
}
public static List<RealPoint> GetCrossingPoints(Line line, Circle circle)
{
return CircleWithLine.GetCrossingPoints(circle, line);
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/PolygonWithRealPoint.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class PolygonWithRealPoint
{
public static bool Contains(Polygon containingPolygon, RealPoint containedPoint)
{
if(containingPolygon is PolygonRectangle)
{
// Plus rapide que la méthode des polygones
return containedPoint.X >= containingPolygon.Points[0].X && containedPoint.X <= containingPolygon.Points[2].X && containedPoint.Y >= containingPolygon.Points[0].Y && containedPoint.Y <= containingPolygon.Points[2].Y;
}
// Pour savoir si le Polygone contient un point on trace un segment entre ce point et un point très éloigné
// On compte combien de cotés du polygone croisent cette droite
// Si ce nombre est impaire alors le point est contenu dans le polygone
int crossCount = 0;
Segment testSeg = new Segment(containedPoint, new RealPoint(containingPolygon.Sides.Min(o => o.StartPoint.X) - 10000, containedPoint.Y));
foreach (Segment s in containingPolygon.Sides)
{
if (s.Contains(containedPoint))
return true;
if (s.Cross(testSeg))
{
List<RealPoint> cross = testSeg.GetCrossingPoints(s);
if (cross.Count > 0 && cross[0] != s.EndPoint) // Pour ne pas compter 2 fois un croisement sur un sommet, il sera déjà compté sur le Begin d'un autre
crossCount++;
}
}
crossCount -= containingPolygon.Sides.Count(o => Math.Abs(o.StartPoint.Y - containedPoint.Y) < RealPoint.PRECISION);
return (crossCount % 2 == 1);
}
public static bool Cross(Polygon polygon, RealPoint point)
{
return RealPointWithPolygon.Cross(point, polygon);
}
public static double Distance(Polygon polygon, RealPoint point)
{
return RealPointWithPolygon.Distance(point, polygon);
}
public static List<RealPoint> GetCrossingPoints(Polygon polygon, RealPoint point)
{
return RealPointWithPolygon.GetCrossingPoints(point, polygon);
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Actionneur.cs
using GoBot.BoardContext;
using GoBot.Devices;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace GoBot.Actionneurs
{
static class Actionneur
{
private static FingerLeft _fingerLeft;
private static FingerRight _fingerRight;
private static ElevatorRight _elevatorRight;
private static ElevatorLeft _elevatorLeft;
private static Lifter _lifter;
private static LiftLeft _liftLeft;
private static LiftRight _liftRight;
private static LiftBack _liftBack;
private static Arms _arms;
private static Flags _flags;
public static void Init()
{
_flags = new Flags();
_fingerLeft = new FingerLeft();
_fingerRight = new FingerRight();
_elevatorRight = new ElevatorRight();
_elevatorLeft = new ElevatorLeft();
_lifter = new Lifter();
_liftLeft = new LiftLeft();
_liftRight = new LiftRight();
_liftBack = new LiftBack();
_arms = new Arms();
//_elevatorLeft.FillWith(Buoy.Red);
//_elevatorRight.FillWith(Buoy.Green);
//_lifter.Load = new List<Color>(){ Buoy.Red, Buoy.Green, Buoy.Red, Buoy.Green, Buoy.Red};
}
public static FingerLeft FingerLeft { get => _fingerLeft; }
public static FingerRight FingerRight { get => _fingerRight; }
public static ElevatorRight ElevatorRight { get => _elevatorRight; }
public static ElevatorLeft ElevatorLeft { get => _elevatorLeft; }
public static Lifter Lifter { get => _lifter; }
public static LiftLeft LiftLeft { get => _liftLeft; }
public static LiftRight LiftRight { get => _liftRight; }
public static LiftBack LiftBack { get => _liftBack; }
public static Arms Arms { get => _arms; }
public static Flags Flags { get => _flags; }
public static Elevator FindElevator(Color color)
{
if (color == Buoy.Red)
return _elevatorLeft;
else
return _elevatorRight;
}
}
}
<file_sep>/GoBot/GoBot/SpeedConfig.cs
using Geometry;
using GoBot.PathFinding;
using System;
using System.IO;
namespace GoBot
{
[Serializable]
public class SpeedConfig
{
#region Core
private int _lineAcceleration;
private int _lineDeceleration;
private int _lineSpeed;
private int _pivotAcceleration;
private int _pivotDeceleration;
private int _pivotSpeed;
#endregion
#region Constructors
public SpeedConfig(int lineSpeed, int lineAccel, int lineDecel, int pivotSpeed, int pivotAccel, int pivotDecel)
{
SetParams(lineSpeed, lineAccel, lineDecel, pivotSpeed, pivotAccel, pivotDecel);
}
public SpeedConfig()
{
SetParams(500, 500, 500, 500, 500, 500);
}
#endregion
#region Properties
public int LineAcceleration
{
get { return _lineAcceleration; }
set
{
if (_lineAcceleration != value)
{
_lineAcceleration = value;
OnParamChange(true, false, false, false, false, false);
}
}
}
public int LineDeceleration
{
get { return _lineDeceleration; }
set
{
if (_lineDeceleration != value)
{
_lineDeceleration = value;
OnParamChange(false, true, false, false, false, false);
}
}
}
public int LineSpeed
{
get { return _lineSpeed; }
set
{
if (_lineSpeed != value)
{
_lineSpeed = value;
OnParamChange(false, false, true, false, false, false);
}
}
}
public int PivotAcceleration
{
get { return _pivotAcceleration; }
set
{
if (_pivotAcceleration != value)
{
_pivotAcceleration = value;
OnParamChange(false, false, false, true, false, false);
}
}
}
public int PivotDeceleration
{
get { return _pivotDeceleration; }
set
{
if (_pivotDeceleration != value)
{
_pivotDeceleration = value;
OnParamChange(false, false, false, false, true, false);
}
}
}
public int PivotSpeed
{
get { return _pivotSpeed; }
set
{
if (_pivotSpeed != value)
{
_pivotSpeed = value;
OnParamChange(false, false, false, false, false, true);
}
}
}
#endregion
#region Events
public delegate void ParamChangeDelegate(bool lineAccelChange, bool lineDecelChange, bool lineSpeedChange, bool pivotAccelChange, bool pivotDecelChange, bool pivotSpeedChange);
public event ParamChangeDelegate ParamChange;
protected void OnParamChange(bool lineAccelChange, bool lineDecelChange, bool lineSpeedChange, bool pivotAccelChange, bool pivotDecelChange, bool pivotSpeedChange)
{
ParamChange?.Invoke(lineAccelChange, lineDecelChange, lineSpeedChange, pivotAccelChange, pivotDecelChange, pivotSpeedChange);
}
#endregion
#region Public
public TimeSpan LineDuration(int distance)
{
TimeSpan accel, maxSpeed, braking;
return DistanceDuration((int)distance, LineAcceleration, LineSpeed, LineDeceleration, out accel, out maxSpeed, out braking);
}
public TimeSpan LineDuration(int distance, out TimeSpan accelDuration, out TimeSpan maxSpeedDuration, out TimeSpan brakingDuration)
{
return DistanceDuration((int)distance, LineAcceleration, LineSpeed, LineDeceleration, out accelDuration, out maxSpeedDuration, out brakingDuration);
}
public TimeSpan PivotDuration(AngleDelta angle, double axialDistance)
{
double dist = (Math.PI * axialDistance) / 360 * Math.Abs(angle.InDegrees);
TimeSpan accel, maxSpeed, braking;
return DistanceDuration((int)dist, PivotAcceleration, PivotSpeed, PivotDeceleration, out accel, out maxSpeed, out braking);
}
public TimeSpan PivotDuration(AngleDelta angle, double axialDistance, out TimeSpan accelDuration, out TimeSpan maxSpeedDuration, out TimeSpan brakingDuration)
{
double dist = (Math.PI * axialDistance) / 360 * Math.Abs(angle.InDegrees);
return DistanceDuration((int)dist, PivotAcceleration, PivotSpeed, PivotDeceleration, out accelDuration, out maxSpeedDuration, out brakingDuration);
}
public void SetParams(int lineSpeed, int lineAccel, int lineDecel, int pivotSpeed, int pivotAccel, int pivotDecel)
{
_lineSpeed = lineSpeed;
_lineAcceleration = lineAccel;
_lineDeceleration = lineDecel;
_pivotSpeed = pivotSpeed;
_pivotAcceleration = pivotAccel;
_pivotDeceleration = pivotDecel;
OnParamChange(true, true, true, true, true, true);
}
public void SetParams(SpeedConfig config)
{
_lineSpeed = config.LineSpeed;
_lineAcceleration = config.LineAcceleration;
_lineDeceleration = config.LineDeceleration;
_pivotSpeed = config.PivotSpeed;
_pivotAcceleration = config.PivotAcceleration;
_pivotDeceleration = config.PivotDeceleration;
OnParamChange(true, true, true, true, true, true);
}
#endregion
#region Private
private TimeSpan DistanceDuration(int distance, int acceleration, int maxSpeed, int deceleration, out TimeSpan accelDuration, out TimeSpan maxSpeedDuration, out TimeSpan brakingDuration)
{
if (distance == 0 || acceleration == 0 || deceleration == 0 || maxSpeed == 0)
{
accelDuration = new TimeSpan();
maxSpeedDuration = new TimeSpan();
brakingDuration = new TimeSpan();
return new TimeSpan();
}
else
{
double durationAccel, durationMaxSpeed, durationBraking;
double distanceAccel, distanceMaxSpeed, distanceBraking;
distanceAccel = (maxSpeed * maxSpeed) / (double)(2 * acceleration);
distanceBraking = (maxSpeed * maxSpeed) / (double)(2 * deceleration);
if (distanceAccel + distanceBraking < distance)
{
distanceMaxSpeed = distance - distanceAccel - distanceBraking;
durationAccel = maxSpeed / (double)acceleration;
durationBraking = maxSpeed / (double)deceleration;
durationMaxSpeed = distanceMaxSpeed / (double)maxSpeed;
}
else
{
distanceMaxSpeed = 0;
durationMaxSpeed = 0;
double rapport = deceleration / (double)acceleration;
distanceBraking = (int)(distance / (rapport + 1));
distanceAccel = distance - distanceBraking;
durationAccel = Math.Sqrt((2 * distanceAccel) / (double)acceleration);
durationBraking = Math.Sqrt((2 * distanceBraking) / (double)(deceleration));
}
accelDuration = new TimeSpan(0, 0, 0, 0, (int) (1000 * durationAccel));
maxSpeedDuration = new TimeSpan(0, 0, 0, 0, (int)(1000 * durationMaxSpeed));
brakingDuration = new TimeSpan(0, 0, 0, 0, (int)(1000 * durationBraking));
}
return accelDuration + maxSpeedDuration + brakingDuration;
}
#endregion
}
}
<file_sep>/GoBot/Composants/ByteBinaryGraph.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Composants
{
public partial class ByteBinaryGraph : UserControl
{
private List<Label> Labels { get; set; }
private List<BinaryGraph> Graphs { get; set; }
public ByteBinaryGraph()
{
InitializeComponent();
Labels = new List<Label>() { label1, label2, label3, label4, label5, label6, label7, label8 };
Graphs = new List<BinaryGraph>() { binaryGraph1, binaryGraph2, binaryGraph3, binaryGraph4, binaryGraph5, binaryGraph6, binaryGraph7, binaryGraph8 };
}
/// <summary>
/// Permet de définir la liste des nom des graphes
/// </summary>
/// <param name="names">Noms des graphes</param>
public void SetNames(List<String> names)
{
for (int i = 0; i < names.Count && i < Labels.Count; i++)
{
Labels[i].Text = names[i];
}
}
/// <summary>
/// Permet d'ajouter une valeur aux 8 graphes sous forme d'un octet fonctionnant comme un masque
/// </summary>
/// <param name="value">Masque des valeurs à ajouter aux graphes</param>
public void SetValue(Byte value)
{
for(int i = 0; i < 8; i++)
{
if (Labels[i].Text != "-")
Graphs[i].AddPoint((value & 0x1) > 0);
value = (Byte)(value >> 1);
}
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Lifts.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace GoBot.Actionneurs
{
public abstract class Lift
{
protected SmallElevator _elevator;
protected ActuatorOnOffID _makeVacuum, _openVacuum;
protected SensorOnOffID _pressure;
public void DoAirLock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, true);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, false);
}
public void DoAirUnlock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, false);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, true);
}
public bool HasSomething()
{
return Robots.MainRobot.ReadSensorOnOff(_pressure);
}
public void DoPositionBottom()
{
_elevator.SendPosition(_elevator.PositionBottom);
}
public void DoPositionMiddle()
{
_elevator.SendPosition(_elevator.PositionMiddle);
}
public void DoPositionTop()
{
_elevator.SendPosition(_elevator.PositionTop);
}
public void DoPositionGrab()
{
_elevator.SendPosition(_elevator.PositionGrab);
}
public void DoTest()
{
for (int i = 0; i < 3; i++)
{
DoPositionBottom();
Thread.Sleep(500);
DoAirLock();
Thread.Sleep(500);
if (HasSomething())
{
DoPositionTop();
}
else
{
DoPositionMiddle();
}
Thread.Sleep(1000);
DoAirUnlock();
}
}
}
public class LiftLeft : Lift
{
public LiftLeft()
{
_elevator = Config.CurrentConfig.SmallElevatorLeft;
_makeVacuum = ActuatorOnOffID.MakeVacuumLeft;
_openVacuum = ActuatorOnOffID.OpenVacuumLeft;
_pressure = SensorOnOffID.PressureSensorLeft;
}
}
public class LiftRight : Lift
{
public LiftRight()
{
_elevator = Config.CurrentConfig.SmallElevatorRight;
_makeVacuum = ActuatorOnOffID.MakeVacuumRight;
_openVacuum = ActuatorOnOffID.OpenVacuumRight;
_pressure = SensorOnOffID.PressureSensorRight;
}
}
public class LiftBack : Lift
{
protected Selector _selector;
protected Retractor _retractor;
public LiftBack()
{
_elevator = Config.CurrentConfig.SmallElevatorBack;
_makeVacuum = ActuatorOnOffID.MakeVacuumBack;
_openVacuum = ActuatorOnOffID.OpenVacuumBack;
_pressure = SensorOnOffID.PressureSensorBack;
_selector = Config.CurrentConfig.Selector;
}
public void DoPositionSelectorRight()
{
_selector.SendPosition(_selector.PositionRight);
}
public void DoPositionSelectorMiddle()
{
_selector.SendPosition(_selector.PositionMiddle);
}
public void DoPositionSelectorLeft()
{
_selector.SendPosition(_selector.PositionLeft);
}
public void DoEngage()
{
_retractor.SendPosition(_retractor.PositionEngage);
}
public void DoDisengage()
{
_retractor.SendPosition(_retractor.PositionDisengage);
}
public void DoTestBack()
{
DoEngage();
Thread.Sleep(500);
DoDisengage();
Thread.Sleep(500);
DoPositionSelectorRight();
Thread.Sleep(500);
DoPositionSelectorMiddle();
Thread.Sleep(500);
DoPositionSelectorLeft();
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/Tracks.cs
using System;
using System.Collections;
using System.Collections.Generic;
namespace AStarFolder
{
public class Tracks : IEnumerable<Track>
{
private List<Track> _list;
private IComparer<Track> _comparer;
public Tracks()
{
_comparer = new ComparisonCost();
_list = new List<Track>();
}
public Track this[int Index]
{
get
{
return _list[Index];
}
}
public int Add(Track newTrack)
{
int index = -1;
int Index = FindBestPlaceFor(newTrack);
int NewIndex = Index >= 0 ? Index : -Index - 1;
if (NewIndex >= Count) _list.Add(newTrack);
else _list.Insert(NewIndex, newTrack);
index = NewIndex;
return index;
}
protected int FindBestPlaceFor(Track t)
{
int place = _list.BinarySearch(t, _comparer);
while (place > 0 && _list[place - 1].Equals(t)) place--; // We want to point at the FIRST occurence
return place;
}
public void Clear()
{
_list.Clear();
}
public void Remove(Track t)
{
_list.Remove(t);
}
public void RemoveAt(int Index) { _list.RemoveAt(Index); }
public int Count { get { return _list.Count; } }
public override string ToString()
{
return "Count = " + _list.Count;
}
public override bool Equals(object o)
{
Tracks other = (Tracks)o;
if (other.Count != Count)
return false;
for (int i = 0; i < Count; i++)
if (!other[i].Equals(this[i]))
return false;
return true;
}
public override int GetHashCode()
{
return _list.GetHashCode();
}
public IEnumerator<Track> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
private class ComparisonCost : IComparer<Track>
{
public int Compare(Track O1, Track O2)
{
IComparable C = O1 as IComparable;
return O1.Evaluation.CompareTo(O2.Evaluation);
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelSensorsColor.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM
{
public partial class PanelSensorsColor : UserControl
{
ThreadLink _linkColorLeft, _linkColorRight;
public PanelSensorsColor()
{
InitializeComponent();
}
private void PanelSensorsColor_Load(object sender, EventArgs e)
{
picColorLeft.SetColor(Color.DarkRed);
picColorRight.SetColor(Color.DarkRed);
}
private void btnColorLeft_ValueChanged(object sender, bool value)
{
if (value)
{
Robots.MainRobot.SetActuatorOnOffValue(ActuatorOnOffID.PowerSensorColorBuoyLeft, true);
Robots.MainRobot.SensorColorChanged += GrosRobot_SensorColorChanged;
ThreadManager.CreateThread(link => PollingColorLeft(link)).StartInfiniteLoop(50);
}
else
{
Robots.MainRobot.SetActuatorOnOffValue(ActuatorOnOffID.PowerSensorColorBuoyLeft, false);
_linkColorLeft.Cancel();
_linkColorLeft.WaitEnd();
_linkColorLeft = null;
}
}
private void btnColorRight_ValueChanged(object sender, bool value)
{
if (value)
{
Robots.MainRobot.SetActuatorOnOffValue(ActuatorOnOffID.PowerSensorColorBuoyRight, true);
Robots.MainRobot.SensorColorChanged += GrosRobot_SensorColorChanged;
ThreadManager.CreateThread(link => PollingColorRight(link)).StartInfiniteLoop(50);
}
else
{
Robots.MainRobot.SetActuatorOnOffValue(ActuatorOnOffID.PowerSensorColorBuoyRight, false);
_linkColorRight.Cancel();
_linkColorRight.WaitEnd();
_linkColorRight = null;
}
}
void PollingColorLeft(ThreadLink link)
{
_linkColorLeft = link;
_linkColorLeft.RegisterName();
Robots.MainRobot.ReadSensorColor(SensorColorID.BuoyLeft, false);
}
void PollingColorRight(ThreadLink link)
{
_linkColorRight = link;
_linkColorRight.RegisterName();
Robots.MainRobot.ReadSensorColor(SensorColorID.BuoyRight, false);
}
void GrosRobot_SensorColorChanged(SensorColorID sensor, Color color)
{
this.InvokeAuto(() =>
{
switch (sensor)
{
case SensorColorID.BuoyRight:
picColorRight.SetColor(color);
break;
case SensorColorID.BuoyLeft:
picColorLeft.SetColor(color);
break;
}
});
}
}
}
<file_sep>/GoBot/Geometry/Shapes/Polygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using Geometry.Shapes.ShapesInteractions;
namespace Geometry.Shapes
{
public class Polygon : IShape, IShapeModifiable<Polygon>
{
#region Attributs
/// <summary>
/// Liste des côtés du Polygone sous forme de segments
/// La figure est forcément fermée et le dernier point est donc forcément relié au premier
/// </summary>
protected List<Segment> _sides;
protected VolatileResult<RealPoint> _barycenter;
protected VolatileResult<double> _surface;
#endregion
#region Constructeurs
/// <summary>
/// Contruit un polygone selon une liste de cotés
/// Les côtés doivent être donnés dans l'ordre
/// Si 2 côtés ne se touchent pas ils sont automatiquement reliés par un Segment intermédiaire
/// Si 2 côtés se croisent une exception ArgumentException est levée
/// Si le polygone n'est pas fermé le premier et le dernier point sont reliés
/// </summary>
/// <param name="sides">Liste des cotés</param>
public Polygon(IEnumerable<Segment> sides) : this(sides, true)
{
// Construit le polygon en forcant la vérification des croisements
}
protected Polygon(IEnumerable<Segment> sides, bool checkCrossing) : this()
{
BuildPolygon(sides, checkCrossing);
}
/// <summary>
/// Constructeur par défaut utile uniquement pour les héritiés
/// </summary>
protected Polygon()
{
_barycenter = new VolatileResult<RealPoint>(ComputeBarycenter);
_surface = new VolatileResult<double>(ComputeSurface);
_sides = new List<Segment>();
}
/// <summary>
/// Construit un Polygone depuis un autre Polygone
/// </summary>
public Polygon(Polygon polygon) : this()
{
polygon.Sides.ForEach(s => _sides.Add(new Segment(s)));
}
/// <summary>
/// Construit un polygone selon une liste de points
/// Si le polygone n'est pas fermé le premier et le dernier point sont reliés
/// </summary>
/// <param name="points">Liste des points du polygone dans l'ordre où ils sont reliés</param>
public Polygon(IEnumerable<RealPoint> points) : this(points, true)
{
// Construit le polygon en forcant la vérification des croisements
}
/// <summary>
/// Construit un polygone selon une liste de points
/// Si le polygone n'est pas fermé le premier et le dernier point sont reliés
/// </summary>
/// <param name="points">Liste des points du polygone dans l'ordre où ils sont reliés</param>
/// <param name="checkCrossing">Vrai pour vérifier le croisement entre les côtés</param>
protected Polygon(IEnumerable<RealPoint> points, bool checkCrossing) : this()
{
List<Segment> segs = new List<Segment>();
if (points.Count() == 0)
return;
for (int i = 1; i < points.Count(); i++)
segs.Add(new Segment(points.ElementAt(i - 1), points.ElementAt(i)));
segs.Add(new Segment(points.ElementAt(points.Count() - 1), points.ElementAt(0)));
BuildPolygon(segs, checkCrossing);
}
/// <summary>
/// Construit le polygone à partir d'une liste de segment définissant son contour
/// </summary>
/// <param name="segs">Segments du contour</param>
/// <param name="crossChecking">Vrai pour vérifier les croisements des côtés</param>
protected void BuildPolygon(IEnumerable<Segment> segs, bool crossChecking)
{
if (segs.Count() == 0)
return;
_sides.Clear();
for (int i = 0; i < segs.Count() - 1; i++)
{
Segment seg1 = segs.ElementAt(i);
Segment seg2 = segs.ElementAt(i + 1);
_sides.Add(seg1);
if (seg1.EndPoint != seg2.StartPoint)
_sides.Add(new Segment(seg1.EndPoint, seg2.StartPoint));
}
_sides.Add(segs.ElementAt(segs.Count() - 1));
if (crossChecking)
{
for (int i = 0; i < _sides.Count; i++)
for (int j = i + 1; j < _sides.Count; j++)
{
List<RealPoint> cross = _sides[i].GetCrossingPoints(_sides[j]);
if (cross.Count > 0 && cross[0] != _sides[i].StartPoint && cross[0] != _sides[i].EndPoint)
throw new ArgumentException("Impossible to create a polygon with crossing sides.");
}
}
}
#endregion
#region Propriétés
/// <summary>
/// Obtient la liste des cotés du polygone
/// </summary>
public List<Segment> Sides
{
get
{
return _sides;
}
}
/// <summary>
/// Obtient la liste des sommets du polygone
/// </summary>
public List<RealPoint> Points
{
get
{
return _sides.Select(s => new RealPoint(s.StartPoint)).ToList();
}
}
/// <summary>
/// Obtient la surface du polygone
/// </summary>
public double Surface
{
get
{
return _surface.Value;
}
}
protected virtual double ComputeSurface()
{
double surface = 0;
foreach (PolygonTriangle t in this.ToTriangles())
surface += t.Surface;
return surface;
}
/// <summary>
/// Obtient le barycentre du polygone
/// </summary>
public RealPoint Barycenter
{
get
{
return _barycenter.Value;
}
}
protected virtual RealPoint ComputeBarycenter()
{
double surface = Surface;
RealPoint output = null;
if (this.Surface == 0)
{
output = new RealPoint(_sides[0].StartPoint);
}
else
{
output = new RealPoint();
foreach (PolygonTriangle t in this.ToTriangles())
{
RealPoint barycentreTriangle = t.Barycenter;
double otherSurface = t.Surface;
if (t.Surface > 0)
{
output.X += barycentreTriangle.X * otherSurface / surface;
output.Y += barycentreTriangle.Y * otherSurface / surface;
}
}
}
return output;
}
#endregion
#region Opérateurs & Surcharges
public static bool operator ==(Polygon a, Polygon b)
{
bool ok;
if ((object)a == null || (object)b == null)
ok = (object)a == null && (object)b == null;
else if (a.Sides.Count == b.Sides.Count)
{
ok = a.Points.TrueForAll(p => b.Points.Contains(p));
}
else
ok = false;
return ok;
}
public static bool operator !=(Polygon a, Polygon b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
Polygon p = obj as Polygon;
if ((Object)p == null)
{
return false;
}
return (Polygon)obj == this;
}
public override int GetHashCode()
{
if (_sides.Count == 0)
return 0;
int hash = _sides[0].GetHashCode();
for (int i = 1; i < _sides.Count; i++)
hash ^= _sides[i].GetHashCode();
return hash;
}
public override string ToString()
{
if (_sides.Count == 0)
return "-";
String chaine = _sides[0].ToString() + Environment.NewLine;
for (int i = 1; i < _sides.Count; i++)
chaine += _sides[i].ToString() + Environment.NewLine;
return chaine;
}
#endregion
#region Distance
/// <summary>
/// Retourne la distance minimum entre le polygone courant et la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Distance minimum entre le polygone et la forme donnée</returns>
public double Distance(IShape shape)
{
double output = 0;
if (shape is RealPoint) output = PolygonWithRealPoint.Distance(this, shape as RealPoint);
else if (shape is Segment) output = PolygonWithSegment.Distance(this, shape as Segment);
else if (shape is Polygon) output = PolygonWithPolygon.Distance(this, shape as Polygon);
else if (shape is Circle) output = PolygonWithCircle.Distance(this, shape as Circle);
else if (shape is Line) output = PolygonWithLine.Distance(this, shape as Line);
return output;
}
#endregion
#region Contient
/// <summary>
/// Teste si le polygone courant contient la forme donnée
/// </summary>
/// <param name="shape">Forme testé</param>
/// <returns>Vrai si le polygone contient la forme testée</returns>
public bool Contains(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = PolygonWithRealPoint.Contains(this, shape as RealPoint);
else if (shape is Segment) output = PolygonWithSegment.Contains(this, shape as Segment);
else if (shape is Polygon) output = PolygonWithPolygon.Contains(this, shape as Polygon);
else if (shape is Circle) output = PolygonWithCircle.Contains(this, shape as Circle);
else if (shape is Line) output = PolygonWithLine.Contains(this, shape as Line);
return output;
}
#endregion
#region Croisements
/// <summary>
/// Retourne la liste des points de croisement avec la forme donnée
/// </summary>
/// <param name="forme">Forme à tester</param>
/// <returns>Liste des points de croisement</returns>
public List<RealPoint> GetCrossingPoints(IShape shape)
{
List<RealPoint> output = new List<RealPoint>();
if (shape is RealPoint) output = PolygonWithRealPoint.GetCrossingPoints(this, shape as RealPoint);
else if (shape is Segment) output = PolygonWithSegment.GetCrossingPoints(this, shape as Segment);
else if (shape is Polygon) output = PolygonWithPolygon.GetCrossingPoints(this, shape as Polygon);
else if (shape is Circle) output = PolygonWithCircle.GetCrossingPoints(this, shape as Circle);
else if (shape is Line) output = PolygonWithLine.GetCrossingPoints(this, shape as Line);
return output;
}
/// <summary>
/// Teste si le polygone courant croise la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si le polygone croise la forme donnée</returns>
public bool Cross(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = PolygonWithRealPoint.Cross(this, shape as RealPoint);
else if (shape is Segment) output = PolygonWithSegment.Cross(this, shape as Segment);
else if (shape is Polygon) output = PolygonWithPolygon.Cross(this, shape as Polygon);
else if (shape is Circle) output = PolygonWithCircle.Cross(this, shape as Circle);
else if (shape is Line) output = PolygonWithLine.Cross(this, shape as Line);
return output;
}
#endregion
#region Intersection
/// <summary>
/// Sépare un polygone en coupant les segments qui croisent un autre polygone
/// </summary>
/// <param name="origin">Le polygone a découper</param>
/// <param name="cutter">Le polygone qui découpe</param>
/// <returns>Le polygone d'origine dont les cotés sont coupés</returns>
private List<Segment> Cut(Polygon origin, Polygon cutter)
{
List<Segment> segs = new List<Segment>();
foreach (Segment seg in origin.Sides)
{
List<RealPoint> points = cutter.GetCrossingPoints(seg).OrderBy(p => p.Distance(seg.StartPoint)).ToList();
if (points.Count != 0)
{
points.Insert(0, seg.StartPoint);
points.Add(seg.EndPoint);
// Découpage du coté selon les points de croisement
for (int i = 0; i < points.Count - 1; i++)
{
if (points[i] != points[i + 1])
segs.Add(new Segment(points[i], points[i + 1]));
}
}
else
{
// Si aucun croisement, ajout du coté tel quel
segs.Add(new Segment(seg.StartPoint, seg.EndPoint));
}
}
return segs;
}
/// <summary>
/// Retourne les polygones représentant l'intersection entre le polygone courant et le polygone donné
/// </summary>
/// <param name="other">Polygone avec lequel calculer l'intersection</param>
/// <returns>Liste des polygones d'intersection</returns>
public List<Polygon> Intersection(Polygon other)
{
List<Segment> segsMe = Cut(this, other);
List<Segment> segsOther = Cut(other, this);
// On supprime les segments qui ne sont pas dans les 2 polygones
for (int i = segsMe.Count - 1; i >= 0; i--)
{
if (!other.Contains(segsMe[i]))
segsMe.RemoveAt(i);
}
for (int i = segsOther.Count - 1; i >= 0; i--)
{
if (!this.Contains(segsOther[i]))
segsOther.RemoveAt(i);
}
List<Segment> segs = new List<Segment>();
segs.AddRange(segsMe);
segs.AddRange(segsOther);
return BuildPolygons(segs);
}
/// <summary>
/// Crée une liste de polygone à partir d'une liste de segment.
/// On cherche à rejoindre les début et fin de segment pour former les polygones.
/// </summary>
/// <param name="inputSegs">Segments à partir desquels contruire les polygones</param>
/// <returns>Liste de polygones construits</returns>
private List<Polygon> BuildPolygons(List<Segment> inputSegs)
{
List<Segment> currentSegs = new List<Segment>();
List<Polygon> polygons = new List<Polygon>();
while (inputSegs.Count != 0)
{
currentSegs.Add(inputSegs[0]);
inputSegs.RemoveAt(0);
bool polygonOpen = true;
while (polygonOpen)
{
for (int i = inputSegs.Count - 1; i >= 0; i--)
{
Segment seg = inputSegs[i];
inputSegs.RemoveAt(i);
if (currentSegs[currentSegs.Count - 1].EndPoint == seg.StartPoint)
{
// Le segment est la suite du polygone ...
if (currentSegs[0].StartPoint == seg.EndPoint)
{
// ... et le ferme : on a terminé un polygone
currentSegs.Add(seg);
polygons.Add(new Polygon(currentSegs, false));
currentSegs.Clear();
polygonOpen = false;
break;
}
else
{
// ... on l'ajoute
currentSegs.Add(seg);
}
}
else if (currentSegs[currentSegs.Count - 1].EndPoint == seg.EndPoint)
{
// Le segment à l'envers est la suite du polygone ...
if (currentSegs[0].StartPoint == seg.StartPoint)
{
// ... et le ferme : on le retourne et on a terminé un polygone
currentSegs.Add(new Segment(seg.EndPoint, seg.StartPoint));
polygons.Add(new Polygon(currentSegs, false));
currentSegs.Clear();
polygonOpen = false;
break;
}
else
{
// ... on le retourne et on l'ajoute
currentSegs.Add(new Segment(seg.EndPoint, seg.StartPoint));
}
}
}
}
}
return polygons;
}
/// <summary>
/// Calcule la liste des polygones résultant de l'intersection de tous les polygones donnés
/// </summary>
/// <param name="polygons">Polygones à intersecter</param>
/// <returns>Intersections des polygones</returns>
public static List<Polygon> Intersections(List<Polygon> polygons)
{
List<Polygon> currentIntersects = new List<Polygon>();
List<Polygon> intersects = new List<Polygon>();
if (polygons.Count >= 2)
{
intersects = polygons[0].Intersection(polygons[1]);
for (int i = 2; i < polygons.Count; i++)
{
currentIntersects.Clear();
foreach (Polygon p in intersects)
currentIntersects.AddRange(p.Intersection(polygons[i]));
intersects.Clear();
intersects.AddRange(currentIntersects);
}
}
return intersects;
}
#endregion
#region Transformations
/// <summary>
/// Retourne un polygone qui est translaté des distances données
/// </summary>
/// <param name="dx">Distance en X</param>
/// <param name="dy">Distance en Y</param>
/// <returns>Polygone translaté des distances données</returns>
public Polygon Translation(double dx, double dy)
{
Polygon output = new Polygon(Points.Select(p => p.Translation(dx, dy)), false);
if (_barycenter.Computed)
output._barycenter.Value = _barycenter.Value.Translation(dx, dy);
return output;
}
/// <summary>
/// Retourne un polygone qui est tourné de l'angle donné
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation, si null le barycentre est utilisé</param>
/// <returns>Polygone tourné de l'angle donné</returns>
public Polygon Rotation(AngleDelta angle, RealPoint rotationCenter = null)
{
if (rotationCenter == null)
rotationCenter = Barycenter;
Polygon output = new Polygon(Points.ConvertAll(p => p.Rotation(angle, rotationCenter)), false);
if (_barycenter.Computed && _barycenter.Value == rotationCenter)
output._barycenter.Value = new RealPoint(_barycenter.Value);
return output;
}
/// <summary>
/// Transforme le polygone en liste de triangle qui représentent la même surface.
/// </summary>
/// <returns>Liste de triangles équivalente au polygone</returns>
public List<PolygonTriangle> ToTriangles()
{
List<PolygonTriangle> triangles = new List<PolygonTriangle>();
List<RealPoint> points = new List<RealPoint>(Points);
RealPoint p1, p2, p3;
do
{
p1 = points[0];
p2 = points[1];
p3 = points[2];
PolygonTriangle triangle = new PolygonTriangle(p1, p2, p3);
if (this.Contains(triangle.Barycenter))
{
triangles.Add(triangle);
points.Add(p1);
points.RemoveAt(1);
points.RemoveAt(0);
}
else
{
points.Add(p1);
points.RemoveAt(0);
}
} while (points.Count >= 3);
return triangles;
}
#endregion
#region Peinture
/// <summary>
/// Dessine le polygone sur un Graphic
/// </summary>
/// <param name="g">Graphic sur lequel dessiner</param>
/// <param name="outlineColor">Couleur du contour du polygone</param>
/// <param name="outlineWidth">Epaisseur du contour</param>
/// <param name="fillColor">Couleur de remplissage du polygone</param>
/// <param name="scale">Echelle de conversion</param>
public void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale)
{
if (Sides.Count == 0)
return;
Point[] listePoints = new Point[Sides.Count + 1];
listePoints[0] = scale.RealToScreenPosition(Sides[0].StartPoint);
for (int i = 0; i < Sides.Count; i++)
{
Segment s = Sides[i];
listePoints[i] = scale.RealToScreenPosition(s.EndPoint);
}
listePoints[listePoints.Length - 1] = listePoints[0];
if (fill != null)
g.FillPolygon(fill, listePoints, System.Drawing.Drawing2D.FillMode.Winding);
if (outline != null)
g.DrawPolygon(outline, listePoints);
}
#endregion
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageNumeric.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PanelBoardNumeric : UserControl
{
private ThreadLink _link;
private Board _board;
public PanelBoardNumeric()
{
InitializeComponent();
byteBinaryGraphA1.SetNames(new List<String>() { "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7" });
byteBinaryGraphA2.SetNames(new List<String>() { "A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15" });
byteBinaryGraphB1.SetNames(new List<String>() { "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7" });
byteBinaryGraphB2.SetNames(new List<String>() { "B8", "B9", "B10", "B11", "B12", "B13", "B14", "B15" });
byteBinaryGraphC1.SetNames(new List<String>() { "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7" });
byteBinaryGraphC2.SetNames(new List<String>() { "C8", "C9", "C10", "C11", "C12", "C13", "C14", "C15" });
}
private void AskValues()
{
Robots.MainRobot.ReadNumericPins(_board, true);
lock (Robots.MainRobot.NumericPinsValue)
{
if (switchButtonPortA.Value)
{
byteBinaryGraphA1.SetValue(Robots.MainRobot.NumericPinsValue[_board][1]);
byteBinaryGraphA2.SetValue(Robots.MainRobot.NumericPinsValue[_board][0]);
}
if (switchButtonPortB.Value)
{
byteBinaryGraphB1.SetValue(Robots.MainRobot.NumericPinsValue[_board][3]);
byteBinaryGraphB2.SetValue(Robots.MainRobot.NumericPinsValue[_board][2]);
}
if (switchButtonPortC.Value)
{
byteBinaryGraphC1.SetValue(Robots.MainRobot.NumericPinsValue[_board][5]);
byteBinaryGraphC2.SetValue(Robots.MainRobot.NumericPinsValue[_board][4]);
}
}
}
public void SetBoard(Board board)
{
_board = board;
if (board == Board.RecIO)
{
byteBinaryGraphA1.SetNames(new List<String>() { "Moteur 4 I", "Moteur 2 I", "OSC", "A3 (Free)", "Ethernet reset", "-", "-", "Capt. couleur S3" });
byteBinaryGraphA2.SetNames(new List<String>() { "Capt. couleur led", "Ethernet CS", "Capt. couleur S2", "-", "-", "-", "-", "-" });
byteBinaryGraphB1.SetNames(new List<String>() { "Moteur 1 I", "Moteur 3 I", "Tension bat.", "Vacuostat 2", "Capt. couleur Out", "PGD - JTAG", "PGJ - JTAG", "Ethernet INT" });
byteBinaryGraphB2.SetNames(new List<String>() { "Codeur 1B", "Codeur 1A", "Moteur 2 H", "Moteur 2 L", "Moteur 3 H", "Moteur 3 L", "Moteur 4 H", "Moteur 4 L" });
byteBinaryGraphC1.SetNames(new List<String>() { "Vacuostat 1", "-", "-", "Ethernet SCK", "Ethernet MOSI", "Ethernet MISO", "Moteur 1 H", "Moteur 1 L" });
byteBinaryGraphC2.SetNames(new List<String>() { "Codeur 2 A", "Codeur 2 B", "-", "-", "-", "-", "-", "-" });
}
else if (board == Board.RecMove)
{
byteBinaryGraphA1.SetNames(new List<String>() { "Moteur 4 I", "Moteur 2 I", "OSC", "Shunt (OSC2)", "Ethernet reset", "-", "-", "Capt. couleur S3" });
byteBinaryGraphA2.SetNames(new List<String>() { "Capt. couleur led", "Ethernet CS", "Capt. couleur S2", "-", "-", "-", "-", "-" });
byteBinaryGraphB1.SetNames(new List<String>() { "Moteur 1 I", "Moteur 3 I", "Jack", "Lidar TX", "Capt. couleur Out", "PGD - JTAG", "PGJ - JTAG", "Ethernet INT" });
byteBinaryGraphB2.SetNames(new List<String>() { "Codeur 1B", "Codeur 1A", "Moteur 2 H", "Moteur 2 L", "Moteur 3 H", "Moteur 3 L", "Moteur 4 H", "Moteur 4 L" });
byteBinaryGraphC1.SetNames(new List<String>() { "Lidar RX", "Vacuostat 1", "Vacuostat 2", "Ethernet SCK", "Ethernet MOSI", "Ethernet MISO", "Moteur 1 H", "Moteur 1 L" });
byteBinaryGraphC2.SetNames(new List<String>() { "Codeur 2 A", "Codeur 2 B", "-", "-", "-", "-", "-", "-" });
}
}
private void switchButtonPort_ValueChanged(object sender, bool value)
{
if ((switchButtonPortA.Value || switchButtonPortB.Value || switchButtonPortC.Value) && _link == null)
{
_link = ThreadManager.CreateThread(link => AskValues());
_link.Name = "Ports numériques " + _board.ToString();
_link.StartInfiniteLoop(50);
}
if (!switchButtonPortA.Value & !switchButtonPortB.Value & !switchButtonPortC.Value & _link != null)
{
_link.Cancel();
_link.WaitEnd();
_link = null;
}
}
}
}
<file_sep>/GoBot/GoBot/Communications/Connections.cs
using GoBot.Communications.CAN;
using GoBot.Communications.UDP;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
namespace GoBot.Communications
{
static class Connections
{
private static ThreadLink _linkTestConnections;
private static Dictionary<CanBoard, CanSubConnection> _connectionsCan;
public static UDPConnection ConnectionMove { get; private set; }
public static UDPConnection ConnectionIO { get; private set; }
public static UDPConnection ConnectionCanBridge { get; private set; }
public static CanSubConnection ConnectionCanAlim { get; private set; }
public static Dictionary<CanBoard, CanSubConnection> ConnectionsCan { get { return _connectionsCan; } }
public static CanConnection ConnectionCan { get; set; }
/// <summary>
/// Liste de toutes les connexions suivies par Connections
/// </summary>
public static List<Connection> AllConnections { get; set; }
/// <summary>
/// Association de la connexion avec la carte UDP
/// </summary>
public static Dictionary<Board, Connection> UDPBoardConnection { get; private set; }
/// <summary>
/// Activation ou désactivation de la connexion
/// </summary>
public static Dictionary<Board, bool> EnableConnection { get; private set; }
/// <summary>
/// Intervalle entre les vérifications de connexion
/// </summary>
private static int IntervalLoopTests = 1000;
/// <summary>
/// Initialise toutes les connexions
/// </summary>
public static void Init()
{
_connectionsCan = new Dictionary<CanBoard, CanSubConnection>();
EnableConnection = new Dictionary<Board, bool>();
UDPBoardConnection = new Dictionary<Board, Connection>();
AllConnections = new List<Connection>();
ConnectionIO = AddUDPConnection(Board.RecIO, IPAddress.Parse("10.1.0.14"), 12324, 12314);
ConnectionIO.Name = Board.RecIO.ToString();
ConnectionMove = AddUDPConnection(Board.RecMove, IPAddress.Parse("10.1.0.11"), 12321, 12311);
ConnectionMove.Name = Board.RecMove.ToString();
ConnectionCanBridge = AddUDPConnection(Board.RecCan, IPAddress.Parse("10.1.0.15"), 12325, 12315);
ConnectionCanBridge.Name = Board.RecCan.ToString();
ConnectionCan = new CanConnection(Board.RecCan);
_connectionsCan.Add(CanBoard.CanServo1, new CanSubConnection(ConnectionCan, CanBoard.CanServo1));
_connectionsCan.Add(CanBoard.CanServo2, new CanSubConnection(ConnectionCan, CanBoard.CanServo2));
_connectionsCan.Add(CanBoard.CanServo3, new CanSubConnection(ConnectionCan, CanBoard.CanServo3));
_connectionsCan.Add(CanBoard.CanServo4, new CanSubConnection(ConnectionCan, CanBoard.CanServo4));
_connectionsCan.Add(CanBoard.CanServo5, new CanSubConnection(ConnectionCan, CanBoard.CanServo5));
_connectionsCan.Add(CanBoard.CanServo6, new CanSubConnection(ConnectionCan, CanBoard.CanServo6));
ConnectionCanAlim = new CanSubConnection(ConnectionCan, CanBoard.CanAlim);
_connectionsCan.Add(CanBoard.CanAlim, ConnectionCanAlim);
_connectionsCan.Values.ToList().ForEach(o => AllConnections.Add(o));
// En remplacement des tests de connexion des ConnexionCheck, pour les syncroniser
_linkTestConnections = ThreadManager.CreateThread(link => TestConnections());
_linkTestConnections.Name = "Tests de connexion";
_linkTestConnections.StartInfiniteLoop();
}
public static void StartConnections()
{
ConnectionIO.StartReception();
ConnectionMove.StartReception();
ConnectionCan.StartReception();
}
/// <summary>
/// Ajoute une connexion UDP aux connexions suivies
/// </summary>
/// <param name="board">Carte associée à la connexion</param>
/// <param name="ip">Adresse IP de la connexion</param>
/// <param name="inPort">Port d'entrée pour le PC</param>
/// <param name="outPort">Port de sortie pour le PC</param>
/// <returns>La connexion créée</returns>
private static UDPConnection AddUDPConnection(Board board, IPAddress ip, int inPort, int outPort)
{
UDPConnection output = new UDPConnection();
output.Connect(ip, inPort, outPort);
UDPBoardConnection.Add(board, output);
EnableConnection.Add(board, true);
AllConnections.Add(output);
output.ConnectionChecker.SendConnectionTest += ConnexionCheck_SendConnectionTestUDP;
return output;
}
/// <summary>
/// Envoie un teste de connexion UDP à une connexion UDP
/// </summary>
/// <param name="sender">Connexion à laquelle envoyer le test</param>
private static void ConnexionCheck_SendConnectionTestUDP(Connection sender)
{
sender.SendMessage(UdpFrameFactory.TestConnexion(GetUDPBoardByConnection(sender)));
}
/// <summary>
/// Boucle de tests de connexions pour maintenir les vérification à intervalle régulier
/// </summary>
private static void TestConnections()
{
int interval = IntervalLoopTests / AllConnections.Count();
foreach (Connection conn in AllConnections.OrderBy(c => Connections.GetUDPBoardByConnection(c).ToString()))
{
if (!_linkTestConnections.Cancelled)
{
conn.ConnectionChecker.CheckConnection();
Thread.Sleep(interval);
}
}
}
/// <summary>
/// Retourne la carte concernée par une connexion
/// </summary>
/// <param name="conn">Connexion dont on veut la carte</param>
/// <returns>La carte concernée par la connexion donnée</returns>
public static Board GetUDPBoardByConnection(Connection conn)
{
Board output = Board.RecMove;
foreach (Board c in Enum.GetValues(typeof(Board)))
{
if (UDPBoardConnection.ContainsKey(c) && UDPBoardConnection[c] == conn)
output = c;
}
return output;
}
/// <summary>
/// Retourne la carte concernée par une connexion
/// </summary>
/// <param name="conn">Connexion dont on veut la carte</param>
/// <returns>La carte concernée par la connexion donnée</returns>
public static CanBoard GetCANBoardByConnection(Connection conn)
{
CanBoard output = CanBoard.CanServo1;
foreach (CanBoard c in Enum.GetValues(typeof(CanBoard)))
{
if (_connectionsCan.ContainsKey(c) && _connectionsCan[c] == conn)
output = c;
}
return output;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/SegmentWithSegment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class SegmentWithSegment
{
public static bool Contains(Segment containingSegment, Segment containedSegment)
{
// Il suffit de vérifier que le segment contient les deux extrémités
return SegmentWithRealPoint.Contains(containingSegment, containedSegment.StartPoint) && SegmentWithRealPoint.Contains(containingSegment, containedSegment.EndPoint);
}
public static bool Cross(Segment segment1, Segment segment2)
{
return GetCrossingPoints(segment1, segment2).Count > 0;
}
public static double Distance(Segment segment1, Segment segment2)
{
// Si les segments se croisent la distance est de 0
if (Cross(segment1, segment2))
return 0;
// Sinon c'est la distance minimale entre (chaque extremité d'un segment) et (l'autre segment)
double minDistance = double.MaxValue;
// Le minimal est peut être entre les extremités
minDistance = Math.Min(minDistance, segment1.StartPoint.Distance(segment2.StartPoint));
minDistance = Math.Min(minDistance, segment1.StartPoint.Distance(segment2.EndPoint));
minDistance = Math.Min(minDistance, segment1.EndPoint.Distance(segment2.StartPoint));
minDistance = Math.Min(minDistance, segment1.EndPoint.Distance(segment2.EndPoint));
// Le minimal est peut etre entre une extremité et son projeté hortogonal sur l'autre segment
Line perpendicular = segment1.GetPerpendicular(segment2.StartPoint);
List<RealPoint> cross = segment1.GetCrossingPoints(perpendicular);
if (cross.Count > 0) minDistance = Math.Min(minDistance, cross[0].Distance(segment2.StartPoint));
perpendicular = segment1.GetPerpendicular(segment2.EndPoint);
cross = segment1.GetCrossingPoints(perpendicular);
if (cross.Count > 0) minDistance = Math.Min(minDistance, cross[0].Distance(segment2.EndPoint));
perpendicular = segment2.GetPerpendicular(segment1.StartPoint);
cross = segment2.GetCrossingPoints(perpendicular);
if (cross.Count > 0) minDistance = Math.Min(minDistance, cross[0].Distance(segment1.StartPoint));
perpendicular = segment2.GetPerpendicular(segment1.EndPoint);
cross = segment2.GetCrossingPoints(perpendicular);
if (cross.Count > 0) minDistance = Math.Min(minDistance, cross[0].Distance(segment1.EndPoint));
return minDistance;
}
public static List<RealPoint> GetCrossingPoints(Segment segment1, Segment segment2)
{
List<RealPoint> output = new List<RealPoint>();
double x1, x2, x3, x4, y1, y2, y3, y4;
x1 = segment1.StartPoint.X;
x2 = segment1.EndPoint.X;
x3 = segment2.StartPoint.X;
x4 = segment2.EndPoint.X;
y1 = segment1.StartPoint.Y;
y2 = segment1.EndPoint.Y;
y3 = segment2.StartPoint.Y;
y4 = segment2.EndPoint.Y;
double den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
if (den != 0)
{
double t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den;
double u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den;
if (t > 0 && t < 1 && u > 0 && u < 1)
{
output.Add(new RealPoint(x1 + t * (x2 - x1), y1 + t * (y2 - y1)));
}
}
return output;
}
}
}
<file_sep>/GoBot/GoBot/Actions/Asservissement/ActionAccelerationLigne.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionAccelerationLigne : IAction
{
private int _accel;
private int _decel;
private Robot _robot;
public ActionAccelerationLigne(Robot r, int accel, int decel)
{
_robot = r;
_accel = accel;
_decel = decel;
}
public override String ToString()
{
return _robot.Name + " accélération ligne à " + _accel + " / " + _decel;
}
void IAction.Executer()
{
_robot.SpeedConfig.LineAcceleration = _accel;
_robot.SpeedConfig.LineDeceleration = _decel;
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Speed16;
}
}
}
}
<file_sep>/GoBot/GoBot/Dessinateur.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Threading;
using Geometry.Shapes;
using AStarFolder;
using Geometry;
using GoBot.Beacons;
using GoBot.GameElements;
using GoBot.PathFinding;
using System.Drawing.Drawing2D;
using System.Diagnostics;
using GoBot.Threading;
using GoBot.Devices;
using GoBot.BoardContext;
using GoBot.Actionneurs;
namespace GoBot
{
static class Dessinateur
{
private static ThreadLink _linkDisplay;
#region Conversion coordonnées réelles / écran
/// <summary>
/// Nombre de pixels par mm du terrain
/// </summary>
private const double RAPPORT_SCREEN_REAL = (3000.0 / 805);
/// <summary>
/// Position en pixel sur l'image de l'abscisse 0 de la table
/// </summary>
private const int OFFSET_IMAGE_X = 35;
/// <summary>
/// Position en pixel sur l'image de l'ordonnée 0 de la table
/// </summary>
private const int OFFSET_IMAGE_Y = 35;
#endregion
//Déclaration du délégué pour l’évènement détection de positions
public delegate void TableDessineeDelegate(Image img);
//Déclaration de l’évènement utilisant le délégué
public static event TableDessineeDelegate TableDessinee;
private static RealPoint positionCurseur;
public static RealPoint PositionCurseurTable { get; set; }
public static RealPoint positionDepart;
public static List<Point> trajectoirePolaireScreen;
private static List<Point> pointsPolaireScreen;
public static bool MouseClicked { get; set; }
public static bool AfficheGraphArretes { get; set; } = false;
public static bool AfficheGraph { get; set; } = false;
public static bool AfficheObstacles { get; set; } = false;
public static bool AfficheTable { get; set; } = true;
public static bool AfficheTableRelief { get; set; } = false;
public static bool AfficheHistoriqueCoordonnees { get; set; } = false;
public static bool AfficheCoutsMouvements { get; set; } = false;
public static bool AfficheElementsJeu { get; set; } = true;
public static MouseMode modeCourant;
private static Pen penRougePointille = new Pen(Color.Red),
penNoirPointille = new Pen(Color.Black),
penBleuClairPointille = new Pen(Color.LightBlue),
penBlancTransparent = new Pen(Color.FromArgb(40, Color.Black)),
penBlancFleche = new Pen(Color.White, 3),
penCouleurGauche = new Pen(GameBoard.ColorLeftBlue),
penCouleurGaucheFleche = new Pen(GameBoard.ColorLeftBlue, 3),
penCouleurGaucheEpais = new Pen(Color.FromArgb(35, GameBoard.ColorLeftBlue), 3),
penCouleurDroite = new Pen(GameBoard.ColorRightYellow),
penCouleurDroiteFleche = new Pen(GameBoard.ColorRightYellow, 3),
penCouleurDroiteEpais = new Pen(Color.FromArgb(35, GameBoard.ColorRightYellow), 3),
penRougeEpais = new Pen(Color.Red, 3),
penBleuEpais = new Pen(GameBoard.ColorRightYellow, 3),
penVertEpais = new Pen(Color.Green, 3);
private static SolidBrush brushNoir = new SolidBrush(Color.Black),
brushNoirTresTransparent = new SolidBrush(Color.FromArgb(35, Color.Black)),
brushCouleurGauche = new SolidBrush(GameBoard.ColorLeftBlue),
brushCouleurGaucheTransparent = new SolidBrush(Color.FromArgb(110, GameBoard.ColorLeftBlue)),
brushCouleurGaucheTresTransparent = new SolidBrush(Color.FromArgb(35, GameBoard.ColorLeftBlue)),
brushCouleurDroite = new SolidBrush(GameBoard.ColorRightYellow),
brushCouleurDroiteTransparent = new SolidBrush(Color.FromArgb(110, GameBoard.ColorRightYellow)),
brushCouleurDroiteTresTransparent = new SolidBrush(Color.FromArgb(35, GameBoard.ColorRightYellow));
public static WorldScale Scale { get; } = new WorldScale(RAPPORT_SCREEN_REAL, OFFSET_IMAGE_X, OFFSET_IMAGE_Y);
public static RealPoint PositionCurseur
{
get
{
return positionCurseur;
}
set
{
positionCurseur = value;
PositionCurseurTable = Scale.ScreenToRealPosition(value);
}
}
public static List<RealPoint> TrajectoirePolaire
{
set
{
trajectoirePolaireScreen = new List<Point>();
for (int i = 0; i < value.Count; i++)
trajectoirePolaireScreen.Add(Scale.RealToScreenPosition(value[i]));
}
}
public static List<RealPoint> PointsPolaire
{
set
{
pointsPolaireScreen = new List<Point>();
for (int i = 0; i < value.Count; i++)
pointsPolaireScreen.Add(Scale.RealToScreenPosition(value[i]));
}
}
public static void Init()
{
penRougePointille.DashStyle = DashStyle.Dot;
penBleuClairPointille.DashStyle = DashStyle.Dot;
penNoirPointille.DashStyle = DashStyle.Dot;
penCouleurGaucheFleche.StartCap = LineCap.Round;
penCouleurGaucheFleche.EndCap = LineCap.ArrowAnchor;
penBlancFleche.StartCap = LineCap.Round;
penBlancFleche.EndCap = LineCap.ArrowAnchor;
}
public static void Start()
{
PositionCurseur = new RealPoint();
_linkDisplay = ThreadManager.CreateThread(link => DisplayLoop());
_linkDisplay.Name = "Affichage de la table";
_linkDisplay.StartThread();
}
public static void Stop()
{
_linkDisplay?.Cancel();
_linkDisplay?.WaitEnd();
_linkDisplay = null;
}
public enum MouseMode
{
None,
PositionCentre,
PositionFace,
TeleportCentre,
TeleportFace,
TrajectoirePolaire
}
public static void DisplayLoop()
{
Stopwatch sw = Stopwatch.StartNew();
while (!_linkDisplay.Cancelled)
{
_linkDisplay.LoopsCount++;
// Limitation à 20FPS
long sleep = 50 - sw.ElapsedMilliseconds - 1;
if (sleep > 0)
Thread.Sleep((int)sleep);
sw.Restart();
try
{
Bitmap bmp;
if (AfficheTable)
bmp = new Bitmap(Properties.Resources.TablePlan);
else
bmp = new Bitmap(Properties.Resources.TablePlan.Width, Properties.Resources.TablePlan.Height);
{
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.SetClip(Scale.RealToScreenRect(new RectangleF(0, 0, 3000, 2000)));
g.DrawEllipse(Pens.DimGray, Scale.RealToScreenRect(new RectangleF(1000, -500, 1000, 1000)));
g.ResetClip();
if (AfficheGraph || AfficheGraphArretes)
DessineGraph(Robots.MainRobot, g, AfficheGraph, AfficheGraphArretes);
if (AfficheHistoriqueCoordonnees && Robots.MainRobot.PositionsHistorical != null)
DessineHistoriqueTrajectoire(Robots.MainRobot, g);
if (AfficheObstacles)
DessineObstacles(g, Robots.MainRobot);
if (true)
DrawOpponents(g, GameBoard.ObstaclesOpponents);
if (AfficheElementsJeu)
DessineElementsJeu(g, GameBoard.Elements);
if (Robots.MainRobot != null)
DessineRobot(Robots.MainRobot, g);
DessinePathFinding(g);
DessinePositionEnnemis(g);
DessineDetections(g);
Robots.MainRobot.PositionTarget?.Paint(g, Color.Red, 5, Color.Red, Scale);
if (AfficheCoutsMouvements)
{
if (GameBoard.Strategy != null && GameBoard.Strategy.Movements != null)
{
GameBoard.Strategy.Movements.ForEach(mouv => mouv.DisplayCostFactor = GameBoard.Strategy.Movements.Min(m => m.GlobalCost));
GameBoard.Strategy.Movements.ForEach(mouv => mouv.Paint(g, Scale));
}
}
if ((modeCourant == MouseMode.PositionCentre || modeCourant == MouseMode.TeleportCentre) && positionDepart != null)
{
Point positionFin = positionCurseur;
Bitmap bmpGrosRobot = new Bitmap(Scale.RealToScreenDistance(Robots.MainRobot.Diameter * 3), Scale.RealToScreenDistance(Robots.MainRobot.Diameter * 3));
Graphics gGros = Graphics.FromImage(bmpGrosRobot);
gGros.Clear(Color.Transparent);
Direction traj = Maths.GetDirection(positionDepart, PositionCurseurTable);
Rectangle r = new Rectangle(bmpGrosRobot.Width / 2 - Scale.RealToScreenDistance(Robots.MainRobot.Width / 2),
bmpGrosRobot.Height / 2 - Scale.RealToScreenDistance(Robots.MainRobot.LenghtFront),
Scale.RealToScreenDistance(Robots.MainRobot.Width),
Scale.RealToScreenDistance(Robots.MainRobot.LenghtTotal));
gGros.FillRectangle(brushNoirTresTransparent, r);
gGros.DrawRectangle(GameBoard.MyColor == GameBoard.ColorLeftBlue ? penCouleurGauche : penCouleurDroite, r);
gGros.DrawLine(GameBoard.MyColor == GameBoard.ColorLeftBlue ? penCouleurGauche : penCouleurDroite, bmpGrosRobot.Width / 2, bmpGrosRobot.Height / 2, bmpGrosRobot.Width / 2, bmpGrosRobot.Height / 2 - Scale.RealToScreenDistance(Robots.MainRobot.LenghtFront));
Point pointOrigine = Scale.RealToScreenPosition(positionDepart);
g.DrawImage(RotateImage(bmpGrosRobot, 360 - traj.angle.InDegrees + 90), pointOrigine.X - bmpGrosRobot.Width / 2, pointOrigine.Y - bmpGrosRobot.Height / 2);
g.DrawLine(penBlancFleche, (Point)Scale.RealToScreenPosition(positionDepart), positionFin);
}
else if ((modeCourant == MouseMode.PositionFace || modeCourant == MouseMode.TeleportFace) && positionDepart != null)
{
Point positionFin = positionCurseur;
Bitmap bmpGrosRobot = new Bitmap(Scale.RealToScreenDistance(Robots.MainRobot.Diameter * 3), Scale.RealToScreenDistance(Robots.MainRobot.Diameter * 3));
Graphics gGros = Graphics.FromImage(bmpGrosRobot);
gGros.Clear(Color.Transparent);
Direction traj = Maths.GetDirection(positionDepart, PositionCurseurTable);
Point pointOrigine = Scale.RealToScreenPosition(positionDepart);
Position departRecule = new Position(-traj.angle, pointOrigine);
departRecule.Move(Scale.RealToScreenDistance(-Robots.MainRobot.LenghtFront));
Rectangle r = new Rectangle(bmpGrosRobot.Width / 2 - Scale.RealToScreenDistance(Robots.MainRobot.Width / 2),
bmpGrosRobot.Height / 2 - Scale.RealToScreenDistance(Robots.MainRobot.LenghtFront),
Scale.RealToScreenDistance(Robots.MainRobot.Width),
Scale.RealToScreenDistance(Robots.MainRobot.LenghtTotal));
gGros.FillRectangle(brushNoirTresTransparent, r);
gGros.DrawRectangle(GameBoard.MyColor == GameBoard.ColorLeftBlue ? penCouleurGauche : penCouleurDroite, r);
gGros.DrawLine(GameBoard.MyColor == GameBoard.ColorLeftBlue ? penCouleurGauche : penCouleurDroite, bmpGrosRobot.Width / 2, bmpGrosRobot.Height / 2, bmpGrosRobot.Width / 2, bmpGrosRobot.Height / 2 - Scale.RealToScreenDistance(Robots.MainRobot.LenghtFront));
g.DrawImage(RotateImage(bmpGrosRobot, 360 - traj.angle.InDegrees + 90), (int)(departRecule.Coordinates.X) - bmpGrosRobot.Width / 2, (int)(departRecule.Coordinates.Y) - bmpGrosRobot.Height / 2);
g.DrawLine(penBlancFleche, (Point)Scale.RealToScreenPosition(positionDepart), positionFin);
}
if (Robots.MainRobot.TrajectoryRunning != null)
{
Trajectory traj = new Trajectory();
traj.AddPoint(Robots.MainRobot.Position.Coordinates);
for (int iPoint = 1; iPoint < Robots.MainRobot.TrajectoryRunning.Points.Count; iPoint++)
traj.AddPoint(Robots.MainRobot.TrajectoryRunning.Points[iPoint]);
traj.Paint(g, Scale);
}
// Trajectoire polaire
//if (modeCourant == Mode.TrajectoirePolaire)
{
if (trajectoirePolaireScreen != null)
foreach (Point p in trajectoirePolaireScreen)
g.FillEllipse(Brushes.Red, p.X - 1, p.Y - 1, 2, 2);
if (pointsPolaireScreen != null)
foreach (Point p in pointsPolaireScreen)
{
g.FillEllipse(Brushes.White, p.X - 3, p.Y - 3, 6, 6);
g.DrawEllipse(Pens.Black, p.X - 3, p.Y - 3, 6, 6);
}
}
TableDessinee?.Invoke(bmp);
}
}
catch (Exception ex)
{
Console.WriteLine("Erreur pendant le dessin de la table " + ex.Message);
}
}
}
private static void DessineElementsJeu(Graphics g, IEnumerable<GameElement> elements)
{
foreach (GameElement element in elements)
element.Paint(g, Scale);
}
private static void DessinePositionEnnemis(Graphics g)
{
for (int i = 0; i < SuiviBalise.PositionsEnnemies.Count; i++)
{
RealPoint p = SuiviBalise.PositionsEnnemies[i];
Point positionEcran = Scale.RealToScreenPosition(p);
if (p == null)
continue;
int vitesse = (int)Math.Sqrt(SuiviBalise.VecteursPositionsEnnemies[i].X * SuiviBalise.VecteursPositionsEnnemies[i].X + SuiviBalise.VecteursPositionsEnnemies[i].Y * SuiviBalise.VecteursPositionsEnnemies[i].Y);
//if (vitesse < 50)
// g.DrawImage(Properties.Resources.Stop, positionEcran.X - Properties.Resources.Stop.Width / 2, positionEcran.Y - Properties.Resources.Stop.Height / 2, Properties.Resources.Stop.Width, Properties.Resources.Stop.Height);
g.FillEllipse(GameBoard.MyColor == GameBoard.ColorRightYellow ? brushCouleurGaucheTransparent : brushCouleurDroiteTransparent, positionEcran.X - Scale.RealToScreenDistance(GameBoard.OpponentRadius), positionEcran.Y - Scale.RealToScreenDistance(GameBoard.OpponentRadius), Scale.RealToScreenDistance(GameBoard.OpponentRadius * 2), Scale.RealToScreenDistance(GameBoard.OpponentRadius * 2));
g.DrawEllipse(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurGauche : penCouleurDroite, positionEcran.X - Scale.RealToScreenDistance(GameBoard.OpponentRadius), positionEcran.Y - Scale.RealToScreenDistance(GameBoard.OpponentRadius), Scale.RealToScreenDistance(GameBoard.OpponentRadius * 2), Scale.RealToScreenDistance(GameBoard.OpponentRadius * 2));
g.DrawLine(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurGaucheEpais : penCouleurDroiteEpais, new Point(positionEcran.X - 7, positionEcran.Y - 7), new Point(positionEcran.X + 7, positionEcran.Y + 7));
g.DrawLine(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurGaucheEpais : penCouleurDroiteEpais, new Point(positionEcran.X - 7, positionEcran.Y + 7), new Point(positionEcran.X + 7, positionEcran.Y - 7));
g.DrawLine(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurGaucheFleche : penCouleurDroiteFleche, positionEcran.X, positionEcran.Y, positionEcran.X + Scale.RealToScreenDistance(SuiviBalise.VecteursPositionsEnnemies[i].X / 3), positionEcran.Y + Scale.RealToScreenDistance(SuiviBalise.VecteursPositionsEnnemies[i].Y / 3));
g.DrawString(i + " - " + vitesse.ToString() + "mm/s", new Font("Calibri", 9, FontStyle.Bold), Brushes.White, positionEcran.X, positionEcran.Y);
}
}
private static void DessineDetections(Graphics g)
{
List<IShape> detections = GameBoard.Detections;
if (detections != null)
{
foreach (IShape d in detections)
{
d?.Paint(g, Color.DodgerBlue, 1, Color.LightSkyBlue, Scale);
}
}
}
private static void DessineRobot(Robot robot, Graphics g)
{
List<Color> load;
Point positionRobot = Scale.RealToScreenPosition(robot.Position.Coordinates);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.TranslateTransform(positionRobot.X, positionRobot.Y);
g.RotateTransform((float)(robot.Position.Angle.InDegrees));
g.TranslateTransform(-positionRobot.X, -positionRobot.Y);
Rectangle robotRect = new Rectangle(positionRobot.X - Scale.RealToScreenDistance(robot.LenghtBack), positionRobot.Y - Scale.RealToScreenDistance(robot.Width / 2), Scale.RealToScreenDistance(robot.LenghtBack + robot.LenghtFront), Scale.RealToScreenDistance(robot.Width));
if (Actionneur.Lifter.Loaded)
{
load = Actionneur.Lifter.Load;
int offset = Actionneur.Lifter.Opened ? -55 : 0;
for (int j = 0; j < load.Count; j++)
PaintRobotBuoy(g, robot, new RealPoint(offset - 160, (j - 2) * 75), load[j]);
}
Rectangle grabberRect = robotRect;
grabberRect.Height = (int)((double)robotRect.Height / Properties.Resources.Robot.Height * Properties.Resources.GrabberLeft.Height);
grabberRect.Y -= (grabberRect.Height - robotRect.Height) / 2;
if (Actionneur.ElevatorLeft.GrabberOpened)
g.DrawImage(Properties.Resources.GrabberLeft, grabberRect);
if (Actionneur.ElevatorRight.GrabberOpened)
g.DrawImage(Properties.Resources.GrabberRight, grabberRect);
if (Config.CurrentConfig.IsMiniRobot)
g.DrawImage(Properties.Resources.RobotMiniClose, robotRect);
else
g.DrawImage(Properties.Resources.Robot, robotRect);
//g.FillRectangle(Brushes.White, robotRect);
//using (SolidBrush brush = new SolidBrush(Color.FromArgb(50, GameBoard.MyColor)))
// g.FillRectangle(brush, robotRect);
//g.DrawRectangle(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurDroite : penCouleurGauche, robotRect);
//g.DrawLine(GameBoard.MyColor == GameBoard.ColorRightYellow ? penCouleurDroite : penCouleurGauche, robotRect.Center(), new Point(robotRect.Right, (int)robotRect.Center().Y));
// TODOEACHYEAR Dessiner ici les actionneurs pour qu'ils prennent l'inclinaison du robot
load = Actionneur.ElevatorLeft.LoadFirst;
for (int i = load.Count - 1; i >= 0; i--)
PaintRobotBuoy(g, robot, new RealPoint(+30 + i * 22, -110), load[i]);
load = Actionneur.ElevatorLeft.LoadSecond;
for (int i = load.Count - 1; i >= 0; i--)
PaintRobotBuoy(g, robot, new RealPoint(-85 + i * 22, -110), load[i]);
load = Actionneur.ElevatorRight.LoadFirst;
for (int i = load.Count - 1; i >= 0; i--)
PaintRobotBuoy(g, robot, new RealPoint(+30 + i * 22, 110), load[i]);
load = Actionneur.ElevatorRight.LoadSecond;
for (int i = load.Count - 1; i >= 0; i--)
PaintRobotBuoy(g, robot, new RealPoint(-85 + i * 22, 110), load[i]);
PaintRobotBuoy(g, robot, new RealPoint(-86.5, -193.5), Actionneur.FingerLeft.Load);
PaintRobotBuoy(g, robot, new RealPoint(-86.5, 193.5), Actionneur.FingerRight.Load);
if (Actionneur.Flags.LeftOpened)
{
RectangleF flagRect = new RectangleF((float)robot.Position.Coordinates.X - 20, (float)robot.Position.Coordinates.Y - 140, 53, 70);
Bitmap img = new Bitmap(Properties.Resources.FlagT2);
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
g.DrawImage(img, Scale.RealToScreenRect(flagRect));
img.Dispose();
}
if (Actionneur.Flags.RightOpened)
{
RectangleF flagRect = new RectangleF((float)robot.Position.Coordinates.X - 20, (float)robot.Position.Coordinates.Y + 140 - 70, 53, 70);
g.DrawImage(Properties.Resources.FlagO2, Scale.RealToScreenRect(flagRect));
Bitmap img = new Bitmap(Properties.Resources.FlagO2);
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
g.DrawImage(img, Scale.RealToScreenRect(flagRect));
img.Dispose();
}
if (Actionneur.Lifter.Opened)
{
Rectangle lifterRect = robotRect;
lifterRect.Width = (int)((double)robotRect.Width / Properties.Resources.Robot.Width * Properties.Resources.Lifter.Width);
lifterRect.X -= (lifterRect.Width - robotRect.Width) / 2;
g.DrawImage(Properties.Resources.Lifter, lifterRect);
}
g.ResetTransform();
}
private static void PaintRobotBuoy(Graphics g, Robot robot, RealPoint center, Color c)
{
if (c != Color.Transparent) new Circle(new RealPoint(robot.Position.Coordinates.X + center.X, robot.Position.Coordinates.Y + center.Y), 36).Paint(g, Color.Black, 1, c, Scale);
}
private static void DessineObstacles(Graphics g, Robot robot)
{
g.SetClip(Scale.RealToScreenRect(new RectangleF(-GameBoard.BorderSize, -GameBoard.BorderSize, GameBoard.Width + GameBoard.BorderSize * 2, GameBoard.Height + GameBoard.BorderSize * 2)));
foreach (IShape forme in GameBoard.ObstaclesAll)
forme.Paint(g, Color.Red, 5, Color.Transparent, Scale);
new Circle(robot.Position.Coordinates, robot.Radius).Paint(g, Color.LimeGreen, 2, Color.Transparent, Scale);
DessineZoneMorte(g);
g.ResetClip();
}
private static void DrawOpponents(Graphics g, IEnumerable<IShape> opponents)
{
foreach (IShape shape in opponents)
{
if (shape is Circle)
{
Circle pos = (Circle)shape;
Rectangle r = Scale.RealToScreenRect(new RectangleF((float)(pos.Center.X - pos.Radius), (float)(pos.Center.Y - pos.Radius), (float)pos.Radius*2, (float)pos.Radius*2));
g.DrawImage(Properties.Resources.Skull, r);
}
}
}
private static void DessineZoneMorte(Graphics g)
{
int farAway = 10000;
if (AllDevices.LidarAvoid != null && AllDevices.LidarAvoid.DeadAngle > 0)
{
AnglePosition debutAngleMort = AllDevices.LidarAvoid.Position.Angle + 180 + new AngleDelta(AllDevices.LidarAvoid.DeadAngle / 2);
AnglePosition finAngleMort = AllDevices.LidarAvoid.Position.Angle + 180 + new AngleDelta(-AllDevices.LidarAvoid.DeadAngle / 2);
List<Point> points = new List<Point>();
points.Add(Scale.RealToScreenPosition(AllDevices.LidarAvoid.Position.Coordinates));
points.Add(Scale.RealToScreenPosition(new Point((int)(AllDevices.LidarAvoid.Position.Coordinates.X + debutAngleMort.Cos * farAway), (int)(AllDevices.LidarAvoid.Position.Coordinates.Y + debutAngleMort.Sin * farAway))));
points.Add(Scale.RealToScreenPosition(new Point((int)(AllDevices.LidarAvoid.Position.Coordinates.X + finAngleMort.Cos * farAway), (int)(AllDevices.LidarAvoid.Position.Coordinates.Y + finAngleMort.Sin * farAway))));
g.IntersectClip(new Rectangle(Scale.RealToScreenPosition(new Point(0, 0)), new Size(Scale.RealToScreenDistance(GameBoard.Width), Scale.RealToScreenDistance(GameBoard.Height))));
g.DrawLine(Pens.Black, points[0], points[1]);
g.DrawLine(Pens.Black, points[0], points[2]);
Brush brush = new SolidBrush(Color.FromArgb(80, Color.Black));
g.FillPolygon(brush, points.ToArray());
brush.Dispose();
g.ResetClip();
}
}
private static void DessinePlateau(Graphics g)
{
g.DrawImage(Properties.Resources.TablePlan, 0, 0, Properties.Resources.TablePlan.Width, Properties.Resources.TablePlan.Height);
}
private static void DessineHistoriqueTrajectoire(Robot robot, Graphics g)
{
lock (Robots.MainRobot.PositionsHistorical)
{
for (int i = 1; i < Robots.MainRobot.PositionsHistorical.Count; i++)
{
int couleur = (int)(i * 1200 / robot.PositionsHistorical.Count * 255 / 1200);
Color pointColor = Color.FromArgb(couleur, couleur, couleur);
RealPoint point = robot.PositionsHistorical[i].Coordinates;
RealPoint pointPrec = robot.PositionsHistorical[i - 1].Coordinates;
new Segment(point, pointPrec).Paint(g, pointColor, 1, Color.Transparent, Scale);
point.Paint(g, Color.Black, 3, pointColor, Scale);
}
}
}
private static void DessineGraph(Robot robot, Graphics g, bool graph, bool arretes)
{
// Dessin du graph
//robot.SemGraph.WaitOne();
lock (robot.Graph)
{
// Dessin des arcs
if (arretes)
foreach (Arc a in robot.Graph.Arcs)
{
if (a.Passable)
new Segment(a.StartNode.Position, a.EndNode.Position).Paint(g, Color.RoyalBlue, 1, Color.Transparent, Scale);
}
if (graph)
//Dessin des noeuds
foreach (Node n in robot.Graph.Nodes)
{
n.Position.Paint(g, n.Passable ? Color.Black : Color.RoyalBlue, 3, n.Passable ? Color.RoyalBlue : Color.Transparent, Scale);
}
}
//robot.SemGraph.Release();
}
public static Track CurrentTrack;
private static void DessinePathFinding(Graphics g)
{
if (GoBot.Config.CurrentConfig.AfficheDetailTraj > 0)
{
if (CurrentTrack != null)
{
Track track = CurrentTrack;
Node n1, n2;
n1 = track.EndNode;
while (track.Queue != null)
{
track = track.Queue;
n2 = track.EndNode;
new Segment(n1.Position, n2.Position).Paint(g, Color.White, 4, Color.Yellow, Scale);
if (PathFinder.CheminEnCoursNoeuds != null && PathFinder.CheminEnCoursNoeuds.Contains(n2))
break;
// g.DrawLine(Pens.Red, Scale.RealToScreenPosition(n1.Position), Scale.RealToScreenPosition(n2.Position));
n1 = n2;
}
}
if (PathFinder.CheminTest != null)
{
PathFinder.CheminTest.Paint(g, Color.White, 4, Color.DodgerBlue, Scale);
}
//List<RealPoint> points = null;
//if (PathFinder.PointsTrouves != null)
// points = new List<RealPoint>(PathFinder.PointsTrouves);
//if (points != null && points.Count > 1)
//{
// for (int i = 1; i < points.Count; i++)
// {
// g.DrawLine(penVertEpais, Scale.RealToScreenPosition(points[i - 1]), Scale.RealToScreenPosition(points[i - 1]));
// }
//}
//Arc cheminTest = PathFinder.CheminTest;
//if (cheminTest != null)
// g.DrawLine(penRougeEpais, Scale.RealToScreenPosition(new RealPoint(cheminTest.StartNode.Position.X, cheminTest.StartNode.Position.Y)), Scale.RealToScreenPosition(new RealPoint(cheminTest.EndNode.Position.X, cheminTest.EndNode.Position.Y)));
//if (robot.ObstacleTeste != null)
// DessinerForme(g, Color.Green, 10, robot.ObstacleTeste);
IShape obstacleProbleme = PathFinder.ObstacleProbleme;
if (obstacleProbleme != null)
obstacleProbleme.Paint(g, Color.Red, 10, Color.Transparent, Scale);
if (PathFinder.CheminEnCoursNoeudsSimplifyed != null && PathFinder.CheminEnCoursNoeudsSimplifyed.Count > 0)
{
Node n1, n2;
n1 = PathFinder.CheminEnCoursNoeudsSimplifyed[0];
int i = 1;
while (i < PathFinder.CheminEnCoursNoeudsSimplifyed?.Count)
{
n2 = PathFinder.CheminEnCoursNoeudsSimplifyed[i];
new Segment(n1.Position, n2.Position).Paint(g, Color.White, 4, Color.Orange, Scale);
i++;
n1 = n2;
}
}
if (PathFinder.CheminEnCoursNoeuds != null && PathFinder.CheminEnCoursNoeuds.Count > 0)
{
Node n1, n2;
n1 = PathFinder.CheminEnCoursNoeuds[0];
int i = 1;
while (i < PathFinder.CheminEnCoursNoeuds.Count)
{
n2 = PathFinder.CheminEnCoursNoeuds[i];
new Segment(n1.Position, n2.Position).Paint(g, Color.White, 4, Color.Green, Scale);
i++;
n1 = n2;
}
}
}
}
private static Bitmap RotateImage(Bitmap b, AnglePosition angle)
{
//create a new empty bitmap to hold rotated image
Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
try
{
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(returnBitmap);
//move rotation point to center of image
g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
//rotate
g.RotateTransform((float)angle);
//move image back
g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
//draw passed in image onto graphics object
g.DrawImage(b, 0, 0, b.Width, b.Height);
}
catch (Exception)
{
returnBitmap.Dispose();
return null;
}
return returnBitmap;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageDiagnosticMove.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PageDiagnosticMove : UserControl
{
private ThreadLink _linkPolling;
private ThreadLink _linkDrawing;
double _cpuAverage;
public PageDiagnosticMove()
{
InitializeComponent();
}
private void btnLaunch_Click(object sender, EventArgs e)
{
if (_linkPolling == null)
{
btnLaunch.Text = "Stopper";
btnLaunch.Image = Properties.Resources.Pause16;
_linkPolling = ThreadManager.CreateThread(link => Measure());
_linkPolling.StartInfiniteLoop(new TimeSpan(0));
_linkDrawing = ThreadManager.CreateThread(link => DrawMeasures());
_linkDrawing.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 50));
}
else
{
btnLaunch.Text = "Lancer";
btnLaunch.Image = Properties.Resources.Play16;
_linkPolling.Cancel();
_linkDrawing.Cancel();
_linkPolling.WaitEnd();
_linkDrawing.WaitEnd();
_linkPolling = null;
_linkDrawing = null;
}
}
private void DrawMeasures()
{
this.InvokeAuto(() =>
{
lblCpuLoad.Text = (_cpuAverage * 100).ToString("00") + "%";
gphCpu.DrawCurves();
gphPwmRight.DrawCurves();
gphPwmLeft.DrawCurves();
Image img = new Bitmap(Properties.Resources.Vumetre);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(new SolidBrush(Color.FromArgb(250, 250, 250)), 0, 0, 12, img.Height - (int)(_cpuAverage * img.Height));
picVumetre.Image = img;
});
}
private void Measure()
{
List<double>[] values = Robots.MainRobot.DiagnosticCpuPwm(30);
_cpuAverage = values[0].Average();
int min = Math.Min(values[0].Count, values[1].Count);
min = Math.Min(min, values[2].Count);
for (int i = 0; i < min; i++)
{
gphCpu.AddPoint("Charge CPU", values[0][i], Color.Green, true);
gphPwmLeft.AddPoint("PWM Gauche", values[1][i], Color.Blue, true);
gphPwmRight.AddPoint("PWM Droite", values[2][i], Color.Red, true);
}
}
private void PanelDiagnosticMove_Load(object sender, EventArgs e)
{
if(!Execution.DesignMode)
{
gphCpu.MaxLimit = 1;
gphCpu.MinLimit = 0;
gphCpu.ScaleMode = Composants.GraphPanel.ScaleType.Fixed;
gphCpu.NamesVisible = true;
gphCpu.BorderVisible = true;
gphCpu.BorderColor = Color.FromArgb(100, 100, 100);
gphCpu.BackColor = Color.FromArgb(250, 250, 250);
gphCpu.NamesAlignment = ContentAlignment.BottomLeft;
gphPwmLeft.MaxLimit = 4000;
gphPwmLeft.MinLimit = -4000;
gphPwmLeft.ScaleMode = Composants.GraphPanel.ScaleType.Fixed;
gphPwmLeft.NamesVisible = true;
gphPwmLeft.BorderVisible = true;
gphPwmLeft.BorderColor = Color.FromArgb(100, 100, 100);
gphPwmLeft.BackColor = Color.FromArgb(250, 250, 250);
gphPwmLeft.NamesAlignment = ContentAlignment.TopLeft;
gphPwmRight.MaxLimit = 4000;
gphPwmRight.MinLimit = -4000;
gphPwmRight.ScaleMode = Composants.GraphPanel.ScaleType.Fixed;
gphPwmRight.NamesVisible = true;
gphPwmRight.BorderVisible = true;
gphPwmRight.BorderColor = Color.FromArgb(100, 100, 100);
gphPwmRight.BackColor = Color.FromArgb(250, 250, 250);
gphPwmRight.NamesAlignment = ContentAlignment.BottomLeft;
}
}
}
}
<file_sep>/GoBot/GoBot/Config.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using Microsoft.Win32;
using GoBot.Actionneurs;
using System.Reflection;
using GoBot.Communications.UDP;
using GoBot.Communications.CAN;
namespace GoBot
{
[Serializable]
public partial class Config
{
private static Config config = null;
public static List<Positionable> Positionnables { get; set; }
public static void ChargerPositionnables()
{
Positionnables = new List<Positionable>();
PropertyInfo[] proprietes = typeof(Config).GetProperties();
foreach (PropertyInfo p in proprietes)
{
if (p.PropertyType.IsSubclassOf(typeof(Positionable)))
{
if (p.GetValue(Config.CurrentConfig, null) == null)
p.SetValue(Config.CurrentConfig, Activator.CreateInstance(p.PropertyType), null);
Positionnables.Add((Positionable)(p.GetValue(Config.CurrentConfig, null)));
}
}
}
public static string PropertyNameToScreen(PropertyInfo property)
{
String typeName = property.Name;
String nom = "";
foreach (char c in typeName)
{
char ch = c;
if (c <= 'Z' && c>= 'A')
nom += " " + (char)(c + 32);
else
nom += c;
}
nom = typeName.Substring(0, 1) + nom.Substring(2);
return nom;
}
public Config()
{
ConfigLent = new SpeedConfig();
ConfigRapide = new SpeedConfig();
}
public bool IsMiniRobot { get; set; }
public int AfficheDetailTraj { get; set; }
// Batteries
public double BatterieRobotVert { get; set; } // 23
public double BatterieRobotOrange { get; set; } // 22
public double BatterieRobotRouge { get; set; } // 21
public double BatterieRobotCritique { get; set; } // 3
// Zone camera
public int CameraXMin { get; set; }
public int CameraXMax { get; set; }
public int CameraYMin { get; set; }
public int CameraYMax { get; set; }
// Déplacement gros robot
public SpeedConfig ConfigRapide { get; set; }
public SpeedConfig ConfigLent { get; set; }
public int GRCoeffP { get; set; } = 60;
public int GRCoeffI { get; set; } = 0;
public int GRCoeffD { get; set; } = 400;
// Offset balises
public double OffsetBaliseCapteur1 { get; set; }
public double OffsetBaliseCapteur2 { get; set; }
// Parametres logs UDP
public SerializableDictionary<UdpFrameFunction, bool> LogsFonctionsIO { get; set; }
public SerializableDictionary<UdpFrameFunction, bool> LogsFonctionsMove { get; set; }
public SerializableDictionary<UdpFrameFunction, bool> LogsFonctionsGB { get; set; }
public SerializableDictionary<UdpFrameFunction, bool> LogsFonctionsCan { get; set; }
public SerializableDictionary<Board, bool> LogsExpediteurs { get; set; }
public SerializableDictionary<Board, bool> LogsDestinataires { get; set; }
// Parametres logs CAN
public SerializableDictionary<CanFrameFunction, bool> LogsCanFunctions { get; set; }
public SerializableDictionary<CanBoard, bool> LogsCanSenders { get; set; }
public SerializableDictionary<CanBoard, bool> LogsCanReceivers { get; set; }
public double GetOffsetBalise(int iCapteur)
{
if (iCapteur == 1)
{
return OffsetBaliseCapteur1;
}
else if (iCapteur == 2)
{
return OffsetBaliseCapteur2;
}
return 0;
}
public void SetOffsetBalise(int iCapteur, double offset)
{
if (iCapteur == 1)
{
OffsetBaliseCapteur1 = offset;
}
else if (iCapteur == 2)
{
OffsetBaliseCapteur2 = offset;
}
}
public static Config CurrentConfig
{
get
{
if (config == null)
config = new Config();
return config;
}
set
{
config = value;
}
}
public static void Load()
{
try
{
XmlSerializer mySerializer = new XmlSerializer(typeof(Config));
using (FileStream myFileStream = new FileStream(PathData + "/config.xml", FileMode.Open))
CurrentConfig = (Config)mySerializer.Deserialize(myFileStream);
CurrentConfig.AfficheDetailTraj = 0;
}
catch (Exception)
{
MessageBox.Show("Aucune configuration chargée.");
}
ChargerPositionnables();
}
public static void Save()
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer mySerializer = new XmlSerializer(typeof(Config));
using (StreamWriter myWriter = new StreamWriter(PathData + "/config.xml"))
mySerializer.Serialize(myWriter, CurrentConfig, ns);
File.Copy(PathData + "/config.xml", PathData + "/Configs/config" + Execution.LaunchStartString + ".xml", true);
}
public static String PathData
{
get
{
return (String)Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("GoBot").GetValue("Path");
}
}
}
}
<file_sep>/GoBot/GoBot/Threading/ThreadLink.cs
using System;
using System.Diagnostics;
using System.Threading;
namespace GoBot.Threading
{
/// <summary>
/// Lien vers un thread d'execution supervisé. Permet de suivre l'état de son execution et de demander son extinction.
/// </summary>
public class ThreadLink
{
#region Delegates
public delegate void CallBack(ThreadLink link);
#endregion
#region Fields
private static int _idCounter = 0;
private int _id;
private String _name;
private DateTime _startDate;
private DateTime _endDate;
private bool _started;
private bool _cancelled;
private bool _ended;
private bool _loopPaused;
private int _loopsCount;
private int _loopsTarget;
private Thread _innerThread;
private CallBack _innerCallback;
private Semaphore _loopLock;
#endregion
#region Properties
/// <summary>
/// Numéro d'identification.
/// </summary>
public int Id
{
get
{
return _id;
}
private set
{
_id = value;
}
}
/// <summary>
/// Nom de la fonction executée ou appelante.
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
/// <summary>
/// Retourne vrai si le trhead a été lancé.
/// </summary>
public bool Started
{
get
{
return _started;
}
private set
{
_started = value;
}
}
/// <summary>
/// Retourne la date de lancement du thread.
/// </summary>
public DateTime StartDate
{
get
{
return _startDate;
}
private set
{
_startDate = value;
}
}
/// <summary>
/// Retourne vrai si le thread a terminé son execution.
/// </summary>
public bool Ended
{
get
{
return _ended;
}
private set
{
_ended = value;
}
}
/// <summary>
/// Retourne la date de fin d'execution.
/// </summary>
public DateTime EndDate
{
get
{
return _endDate;
}
private set
{
_endDate = value;
}
}
/// <summary>
/// Retourne la durée d'execution jusqu'à la date actuelle, ou la date de fin si le thread est déjà terminé.
/// </summary>
public TimeSpan Duration
{
get
{
TimeSpan output;
if (!Started)
output = new TimeSpan();
else if (!Ended)
output = DateTime.Now - StartDate;
else
output = EndDate - StartDate;
return output;
}
}
/// <summary>
/// Retourne vrai si le thread est lancé et non terminé.
/// </summary>
public bool Running
{
get
{
return Started && !Cancelled && !Ended;
}
}
/// <summary>
/// Retourne vrai si l'annulation du thread a été demandée.
/// </summary>
public bool Cancelled
{
get
{
return _cancelled;
}
private set
{
_cancelled = value;
}
}
/// <summary>
/// Retourne vrai si la boucle d'execution est en pause.
/// </summary>
public bool LoopPaused
{
get
{
return _loopPaused;
}
private set
{
_loopPaused = value;
}
}
/// <summary>
/// Obtient ou définit le nombre d'execution de la boucle de thread qui ont déjà été effectuées.
/// </summary>
public int LoopsCount
{
get
{
return _loopsCount;
}
set
{
_loopsCount = value;
}
}
/// <summary>
/// Obtient le nombre d'executions attendues de la boucle (0 si pas de limite)
/// </summary>
public int LoopsTarget
{
get
{
return _loopsTarget;
}
private set
{
_loopsTarget = value;
}
}
#endregion
#region Constructors
public ThreadLink(CallBack call)
{
_innerCallback = call;
_id = _idCounter++;
_name = "Started by " + GetCaller(2);
_cancelled = false;
_started = false;
_ended = false;
_loopLock = null;
_loopPaused = false;
_loopsCount = 0;
_loopsTarget = 0;
_loopLock = null;
}
#endregion
#region Public methods
/// <summary>
/// Lance le thread sur une execution unique.
/// </summary>
public void StartThread()
{
_innerThread = new Thread(f => ThreadCall(_innerCallback));
_innerThread.IsBackground = true;
_innerThread.Start();
}
/// <summary>
/// Execute un thread après l'attente spécifiée.
/// </summary>
/// <param name="delay">Délai avant l'execution.</param>
public void StartDelayedThread(TimeSpan delay)
{
_innerThread = new Thread(f => ThreadCallDelayed(delay, _innerCallback));
_innerThread.IsBackground = true;
_innerThread.Start();
}
/// <summary>
/// Execute un thread après l'attente spécifiée.
/// </summary>
/// <param name="delay">Délai avant l'execution.</param>
public void StartDelayedThread(int delayMs)
{
_innerThread = new Thread(f => ThreadCallDelayed(new TimeSpan(0, 0, 0, 0, delayMs), _innerCallback));
_innerThread.IsBackground = true;
_innerThread.Start();
}
/// <summary>
/// Lance le thread sur une execution à intervalle régulier pour un certain nombre de fois.
/// </summary>
/// <param name="interval">Intervalle entre les executions. (De la fin d'une execution au début de la suivante)</param>
/// <param name="executions">Nombre total d'executions attendues.</param>
public void StartLoop(TimeSpan interval, int executions)
{
_loopsTarget = executions;
_innerThread = new Thread(f => ThreadLoop(interval, executions));
_innerThread.IsBackground = true;
_innerThread.Start();
}
/// <summary>
/// Lance le thread sur une execution à intervalle régulier pour un certain nombre de fois.
/// </summary>
/// <param name="interval">Intervalle entre les executions. (De la fin d'une execution au début de la suivante)</param>
/// <param name="executions">Nombre total d'executions attendues.</param>
public void StartLoop(int intervalMs, int executions)
{
this.StartLoop(new TimeSpan(0, 0, 0, 0, intervalMs), executions);
}
/// <summary>
/// Lance le thread sur une execution à intervalle régulier pour un nombre illimité de fois.
/// </summary>
/// <param name="interval">Intervalle entre les executions. (De la fin d'une execution au début de la suivante)</param>
public void StartInfiniteLoop(TimeSpan interval)
{
_innerThread = new Thread(f => ThreadInfiniteLoop(interval));
_innerThread.IsBackground = true;
_innerThread.Start();
}
/// <summary>
/// Lance le thread sur une execution à intervalle régulier pour un nombre illimité de fois.
/// </summary>
/// <param name="interval">Intervalle entre les executions. (De la fin d'une execution au début de la suivante)</param>
public void StartInfiniteLoop(int intervalMs = 0)
{
this.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, intervalMs));
}
/// <summary>
/// Demande l'annulation de l'execution du thread. La fonction appellée doit tester la propriété Cancelled pour interrompre volontairement son execution.
/// </summary>
public void Cancel()
{
_cancelled = true;
}
/// <summary>
/// Enregistre la classe et le nom de la fonction appellante comme nom du thread.
/// </summary>
public void RegisterName(String complement = "")
{
_name = GetCaller() + complement;
}
/// <summary>
/// Met en pause la boucle d'execution du thread à la fin de l'itératino actuelle.
/// </summary>
public void PauseLoop()
{
_loopPaused = true;
_loopLock = new Semaphore(0, int.MaxValue);
}
/// <summary>
/// Reprends l'execution de la boucle après sa mise en pause.
/// </summary>
public void ResumeLoop()
{
_loopPaused = false;
_loopLock?.Release();
}
/// <summary>
/// Attend la fin de l'execution du thread sans bloquer le thread principal.
/// </summary>
/// <param name="timeout">Nombre de millisecondes avant l'abandon de l'attente de fin.</param>
/// <returns>Retourne vrai si le thread s'est terminé avant le timeout.</returns>
public bool WaitEnd(int timeout = 2000)
{
Stopwatch sw = Stopwatch.StartNew();
// Si jamais la boucle était en pause il faut la libérer pour qu'elle puisse se terminer.
_loopLock?.Release();
// Pompage des messages windows parce que si on attend sur le thread principal une invocation du thread principal c'est un deadlock...
while (_innerThread != null && sw.ElapsedMilliseconds < timeout && !_innerThread.Join(10))
System.Windows.Forms.Application.DoEvents();
sw.Stop();
return sw.ElapsedMilliseconds < timeout;
}
/// <summary>
/// Tente de tuer le thread immédiatement sans précautions. Les appels à Kill doivent être évités au maximum et l'utilisation de Cancel avec gestion de l'annulation doit être privilégiée.
/// </summary>
public void Kill()
{
this.Cancel();
_innerThread.Abort();
}
#endregion
#region Private methods
private void ThreadCall(CallBack call)
{
_startDate = DateTime.Now;
_started = true;
call.Invoke(this);
_ended = true;
_endDate = DateTime.Now;
}
private void ThreadCallDelayed(TimeSpan delay, CallBack call)
{
_startDate = DateTime.Now;
_started = true;
Thread.Sleep(delay);
call.Invoke(this);
_ended = true;
_endDate = DateTime.Now;
}
private void ThreadLoop(TimeSpan interval, int executions)
{
Thread.Sleep(0); // Permet d'executer la fin d'appel de lancement avant de commencer
_startDate = DateTime.Now;
_started = true;
while (!_cancelled && _loopsCount < executions)
{
_loopLock?.WaitOne();
_loopLock = null;
_loopsCount++;
_innerCallback.Invoke(this);
Thread.Sleep(interval);
}
_ended = true;
_endDate = DateTime.Now;
}
private void ThreadInfiniteLoop(TimeSpan interval)
{
Thread.Sleep(0); // Permet d'executer la fin d'appel de lancement avant de commencer
_startDate = DateTime.Now;
_started = true;
while (!this.Cancelled)
{
_loopLock?.WaitOne();
_loopLock = null;
_loopsCount++;
_innerCallback.Invoke(this);
if(interval.TotalMilliseconds > 15)
Thread.Sleep(interval);
else
{
Stopwatch chrono = Stopwatch.StartNew();
while (chrono.Elapsed < interval) ;
}
}
_ended = true;
_endDate = DateTime.Now;
}
private static String GetCaller(int floors = 1)
{
StackFrame stack = new StackTrace().GetFrame(1 + floors);
return stack.GetMethod().DeclaringType.Name + "." + stack.GetMethod().Name;
}
#endregion
#region Type modifications
public override string ToString()
{
String output = "Thread " + _id.ToString() + " \"" + _name + "\"";
if (Started)
{
output += ", started at " + _startDate.ToLongTimeString();
if (_cancelled)
output += ", cancelled";
else if (_ended)
output += ", ended at " + _endDate.ToLongTimeString();
if (_loopsCount > 0)
output += ", " + _loopsCount.ToString() + " loops";
output += " (" + Duration.ToString(@"hh\:mm\:ss") + ")";
}
else
output += ", not started.";
return output;
}
#endregion
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionPivot.cs
using Geometry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionPivot : ITimeableAction
{
private AngleDelta angle;
private Robot robot;
private SensGD sens;
public ActionPivot(Robot r, AngleDelta a, SensGD s)
{
robot = r;
angle = a;
sens = s;
}
System.Drawing.Image IAction.Image
{
get
{
if (sens == SensGD.Droite)
return GoBot.Properties.Resources.TurnRigth16;
else
return GoBot.Properties.Resources.TurnLeft16;
}
}
public override String ToString()
{
return robot.Name + " pivote de " + angle + " " + sens.ToString().ToLower();
}
void IAction.Executer()
{
if(sens == SensGD.Droite)
robot.PivotRight(angle);
else
robot.PivotLeft(angle);
}
public TimeSpan Duration
{
get
{
return robot.SpeedConfig.PivotDuration(angle, robot.WheelSpacing);
}
}
}
}
<file_sep>/GoBot/GoBot/Logs/Logs.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace GoBot.Logs
{
public static class Logs
{
public static ILog LogDebug { get; private set; }
public static ILog LogConsole { get; private set; }
public static void Init()
{
LogDebug = new LogFile(Config.PathData + "/LogsTraces/LogDebug" + Execution.LaunchStartString + ".txt");
LogConsole = new LogConsole();
try
{
if (!Directory.Exists(Config.PathData + "/Logs/"))
Directory.CreateDirectory(Config.PathData + "/Logs/");
if (!Directory.Exists(Config.PathData + "/Configs/"))
Directory.CreateDirectory(Config.PathData + "/Configs/");
if (!Directory.Exists(Config.PathData + "/LogsTraces/"))
Directory.CreateDirectory(Config.PathData + "/LogsTraces/");
Directory.CreateDirectory(Config.PathData + "/Logs/" + Execution.LaunchStartString);
}
catch (Exception)
{
MessageBox.Show("Problème lors de la création des dossiers de log.\nVérifiez si le dossier n'est pas protégé en écriture.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
<file_sep>/GoBot/GoBot/Beacons/SuiviBalise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Geometry.Shapes;
namespace GoBot.Beacons
{
/// <summary>
/// Association d'une position dans un plan à une date d'acquisition
/// </summary>
class PositionTemporelle
{
/// <summary>
/// Date d'acquisition de la position
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Position mesurée
/// </summary>
public RealPoint Position { get; set; }
/// <summary>
/// Constructeur
/// </summary>
/// <param name="date">Date d'acquisition de la position</param>
/// <param name="position">Position mesurée</param>
public PositionTemporelle(DateTime date, RealPoint position)
{
Date = date;
Position = position;
}
}
/// <summary>
/// Petmet d'effectuer un tracking sur les différentes positions ennemies calculées par les balises.
/// </summary>
public static class SuiviBalise
{
// Nombre de balises à suivre
public static int NombreMaxBalises { get; set; }
public static List<RealPoint> PositionsEnnemies { get; set; }
public static List<RealPoint> VecteursPositionsEnnemies { get; set; }
private static List<List<PositionTemporelle>> PositionsTemporelles { get; set; }
private static List<DateTime> DatePositionsBalises { get; set; }
private const double deplacementMaxSeconde = 4000;
public static void Init()
{
NombreMaxBalises = 2;
PositionsEnnemies = new List<RealPoint>();
PositionsTemporelles = new List<List<PositionTemporelle>>();
VecteursPositionsEnnemies = new List<RealPoint>();
}
public static void MajPositions(List<RealPoint> detections, bool force = false)
{
//if (detections.Count < NombreMaxBalises && (detections.Count == 0 || detections.Count < PositionsEnnemies.Count))
// return;
//if (force && detections.Count <= NombreMaxBalises)
{
VecteursPositionsEnnemies.Clear();
PositionsEnnemies.Clear();
PositionsEnnemies.AddRange(detections);
DatePositionsBalises = new List<DateTime>();
PositionsTemporelles.Clear();
for (int i = 0; i < PositionsEnnemies.Count; i++)
{
DatePositionsBalises.Add(DateTime.Now);
PositionsTemporelles.Add(new List<PositionTemporelle>());
PositionsTemporelles[i].Add(new PositionTemporelle(DateTime.Now, PositionsEnnemies[i]));
VecteursPositionsEnnemies.Add(new RealPoint());
}
}
/*else
{
for (int i = 0; i < PositionsEnnemies.Count; i++)
{
int plusProche = 0;
for(int j = 1; j < detections.Count; j++)
{
if (PositionsEnnemies[i].Distance(detections[j]) < PositionsEnnemies[i].Distance(detections[plusProche]))
{
plusProche = i;
}
}
if (PositionsEnnemies[i].Distance(detections[plusProche]) < deplacementMaxSeconde / 1000.0 * (DateTime.Now - DatePositionsBalises[i]).TotalMilliseconds)
{
PositionsEnnemies[i] = detections[plusProche];
DatePositionsBalises[i] = DateTime.Now;
PositionsTemporelles[i].Add(new PositionTemporelle(DateTime.Now, detections[plusProche]));
if (PositionsTemporelles[i].Count > 7)
PositionsTemporelles[i].RemoveAt(0);
}
}
}
CalculVecteurs();*/
if (PositionEnnemisActualisee != null)
PositionEnnemisActualisee();
}
private static void CalculVecteurs()
{
for(int i = 0; i < PositionsEnnemies.Count; i++)
{
List<RealPoint> deplacements = new List<RealPoint>();
for (int j = 1; j < PositionsTemporelles[i].Count; j++)
{
double dx = PositionsTemporelles[i][j].Position.X - PositionsTemporelles[i][j - 1].Position.X;
double dy = PositionsTemporelles[i][j].Position.Y - PositionsTemporelles[i][j - 1].Position.Y;
TimeSpan t = PositionsTemporelles[i][j].Date - PositionsTemporelles[i][j - 1].Date;
if(t.TotalMilliseconds > 0)
deplacements.Add(new RealPoint(dx * 1000.0 / t.TotalMilliseconds, dy * 1000.0 / t.TotalMilliseconds));
}
double x = 0, y = 0;
foreach (RealPoint p in deplacements)
{
x += p.X;
y += p.Y;
}
if (deplacements.Count > 0)
{
x /= deplacements.Count;
y /= deplacements.Count;
}
VecteursPositionsEnnemies[i] = new RealPoint(x, y);
}
}
//Déclaration du délégué pour l’évènement de position des ennemis
public delegate void PositionEnnemisDelegate();
//Déclaration de l’évènement utilisant le délégué
public static event PositionEnnemisDelegate PositionEnnemisActualisee;
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/Pepperl.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using GoBot.BoardContext;
using System.Threading;
namespace GoBot.Devices
{
class Pepperl : Lidar
{
IPAddress _ip;
PepperlManager _manager;
PepperlFreq _freq;
PepperlFilter _filter;
int _filterWidth;
ThreadLink _feedLink;
List<RealPoint> _lastMeasure;
Mutex _lockMeasure;
public Pepperl(IPAddress ip)
{
_ip = ip;
_manager = new PepperlManager(ip, 32123);
_manager.NewMeasure += _manager_NewMeasure;
_freq = PepperlFreq.Hz35;
_filter = PepperlFilter.None;
_filterWidth = 2;
_checker.SendConnectionTest += _checker_SendConnectionTest;
}
private void _checker_SendConnectionTest(Communications.Connection sender)
{
if (!_checker.Connected && _started)
{
// On est censés être connectés mais en fait non, donc on essaie de relancer
lock (this)
{
// TODO : ou pas... ça déconne on dirait
//StopLoop();
//StartLoop();
}
}
}
public override AngleDelta DeadAngle => 0;
public override bool Activated => _feedLink != null && _feedLink.Running;
public int PointsPerScan { get { return _freq.SamplesPerScan() / (_filter == PepperlFilter.None ? 1 : _filterWidth); } }
public AngleDelta Resolution { get { return new AngleDelta(new AngleDelta(360).InRadians / PointsPerScan, AngleType.Radian); } }
public PepperlFreq Frequency { get { return _freq; } }
public PepperlFilter Filter { get { return _filter; } }
public int FilterWidth { get { return _filterWidth; } }
public double PointsDistanceAt(double distance)
{
return distance * Resolution.InRadians;
}
private void _manager_NewMeasure(List<PepperlManager.PepperlPoint> measure, Geometry.AnglePosition startAngle, Geometry.AngleDelta resolution)
{
List<RealPoint> points = ValuesToPositions(measure.Select(p => p.distance).ToList(), startAngle, resolution, false, 0, 5000, _position);
_lastMeasure = new List<RealPoint>(points);
_lockMeasure?.ReleaseMutex();
OnNewMeasure(points);
}
public void ShowMessage(String txt1, String txt2)
{
_manager.ShowMessage(txt1, txt2);
}
public void SetFrequency(PepperlFreq freq)
{
_freq = freq;
_manager.SetFrequency(freq);
}
public void SetFilter(PepperlFilter filter, int size)
{
_filter = filter;
_filterWidth = size;
_manager.SetFilter(_filter, _filterWidth);
}
protected override bool StartLoop()
{
bool ok;
if (_manager.CreateChannelUDP())
{
_feedLink = ThreadManager.CreateThread(link => FeedWatchDog());
_feedLink.Name = "R2000 Watchdog";
_feedLink.StartInfiniteLoop(1000);
ok = true;
}
else
{
ok = false;
}
return ok;
}
protected override void StopLoop()
{
if (_feedLink != null)
{
_manager.CloseChannelUDP();
_feedLink.Cancel();
_feedLink.WaitEnd();
_feedLink = null;
}
}
public void Reboot()
{
_manager.Reboot();
}
public AngleDelta ScanRange { get { return 360; } }
private List<RealPoint> ValuesToPositions(List<uint> measures, AnglePosition startAngle, AngleDelta resolution, bool limitOnTable, int minDistance, int maxDistance, Position refPosition)
{
List<RealPoint> positions = new List<RealPoint>();
for (int i = 0; i < measures.Count; i++)
{
AnglePosition angle = resolution * i;
if (measures[i] > minDistance && (measures[i] < maxDistance || maxDistance == -1))
{
AnglePosition anglePoint = new AnglePosition(angle.InPositiveRadians - refPosition.Angle.InPositiveRadians - ScanRange.InRadians / 2 - Math.PI / 2, AngleType.Radian);
RealPoint pos = new RealPoint(refPosition.Coordinates.X - anglePoint.Sin * measures[i], refPosition.Coordinates.Y - anglePoint.Cos * measures[i]);
int marge = 20; // Marge en mm de distance de detection à l'exterieur de la table (pour ne pas jeter les mesures de la bordure qui ne collent pas parfaitement)
if (!limitOnTable || (pos.X > -marge && pos.X < GameBoard.Width + marge && pos.Y > -marge && pos.Y < GameBoard.Height + marge))
positions.Add(pos);
}
}
return positions;
}
private void FeedWatchDog()
{
_manager.FeedWatchDog();
}
public override List<RealPoint> GetPoints()
{
_lockMeasure = new Mutex();
_lockMeasure.WaitOne();
_lockMeasure.Dispose();
_lockMeasure = null;
return new List<RealPoint>(_lastMeasure);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageGestionLogs.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.IO;
using System.Windows.Forms;
using GoBot.Communications;
namespace GoBot.IHM.Pages
{
public partial class PageGestionLog : UserControl
{
private enum Columns : int
{
Date,
Taille,
TramesMove,
TramesIO,
TramesGB,
Events
}
public PageGestionLog()
{
InitializeComponent();
dataSet = new DataSet();
dataSet.Tables.Add();
dataSet.Tables[0].Columns.Add("Date", typeof(DateTime));
dataSet.Tables[0].Columns.Add("Taille", typeof(TailleDossier));
dataSet.Tables[0].Columns.Add("Trames Move", typeof(int));
dataSet.Tables[0].Columns.Add("Trames IO", typeof(int));
dataSet.Tables[0].Columns.Add("Trames GoBot", typeof(int));
dataSet.Tables[0].Columns.Add("Events", typeof(int));
dataSetArchivage = new DataSet();
dataSetArchivage.Tables.Add();
dataSetArchivage.Tables[0].Columns.Add("Nom", typeof(String));
dataSetArchivage.Tables[0].Columns.Add("Date", typeof(DateTime));
dataSetArchivage.Tables[0].Columns.Add("Taille", typeof(TailleDossier));
dataSetArchivage.Tables[0].Columns.Add("Trames Move", typeof(int));
dataSetArchivage.Tables[0].Columns.Add("Trames IO", typeof(int));
dataSetArchivage.Tables[0].Columns.Add("Trames GoBot", typeof(int));
dataSetArchivage.Tables[0].Columns.Add("Events", typeof(int));
}
DataSet dataSet = null;
DataSet dataSetArchivage = null;
public static long FolderSize(string path)
{
long size = 0;
DirectoryInfo directoryInfo = new DirectoryInfo(path);
IEnumerable<FileInfo> files = directoryInfo.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
size += file.Length;
}
return size;
}
private BackgroundWorker worker = new BackgroundWorker();
private void PanelGestionLog_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.RunWorkerAsync();
//dataGridViewHistoLog.DataSource = dataSet.Tables[0];
//dataGridViewArchives.DataSource = dataSetArchivage.Tables[0];
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblDatePlusVieux.Text = plusVieux.ToString();
lblNombreLogs.Text = nbLogs.ToString();
TailleDossier tailleDossier = new TailleDossier(FolderSize(Config.PathData + "/Logs/"));
lblTailleTotale.Text = tailleDossier.ToString();
dataGridViewHistoLog.DataSource = dataSet.Tables[0];
dataGridViewArchives.DataSource = dataSetArchivage.Tables[0];
progressBar.Visible = false;
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private DateTime plusVieux = DateTime.Now;
private int nbLogs;
void worker_DoWork(object sender, DoWorkEventArgs e)
{
plusVieux = DateTime.Now;
int currentLog = 0;
List<String> dossiers = (List<String>)Directory.EnumerateDirectories(Config.PathData + @"\Logs\").ToList<String>();
nbLogs = dossiers.Count;
dossiers.Sort(OrdreAlphabetiqueInverse);
foreach (String dossier in dossiers)
{
if (dossier.Contains(Execution.LaunchStartString))
continue;
if (Execution.Shutdown)
return;
currentLog++;
String dossier1 = Path.GetFileName(dossier);
DateTime date;
int nbElements = 0;
try
{
String[] tab = dossier1.Split(new char[5] { '.', ' ', 'h', 'm', 's' });
date = new DateTime(Convert.ToInt16(tab[0]), Convert.ToInt16(tab[1]), Convert.ToInt16(tab[2]), Convert.ToInt16(tab[3]), Convert.ToInt16(tab[4]), Convert.ToInt16(tab[5]));
if (date < plusVieux)
plusVieux = date;
long taille = FolderSize(dossier);
Object[] datas = new Object[Enum.GetValues(typeof(Columns)).Length];
datas[(int)Columns.Date] = date;
datas[(int)Columns.Taille] = new TailleDossier(taille);
//TODO2018 ca marche plus ça avec les nouveaux fichiers
foreach (String fichier in Directory.EnumerateFiles(dossier))
{
if (Path.GetFileName(fichier) == "ActionsGros.elog")
{
EventsReplay r = new EventsReplay();
if (r.Charger(fichier))
{
datas[(int)Columns.Events] = r.Events.Count;
nbElements += r.Events.Count;
}
else
datas[(int)Columns.Events] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionGB.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
{
datas[(int)Columns.TramesGB] = r.Frames.Count;
nbElements += r.Frames.Count;
}
else
datas[(int)Columns.TramesGB] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionMove.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
{
datas[(int)Columns.TramesMove] = r.Frames.Count;
nbElements += r.Frames.Count;
}
else
datas[(int)Columns.TramesMove] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionIO.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
{
datas[(int)Columns.TramesIO] = r.Frames.Count;
nbElements += r.Frames.Count;
}
else
datas[(int)Columns.TramesIO] = -1;
}
}
// S'il y a moins de 10 éléments dans ce log, on le supprime
if (nbElements < 10)
Directory.Delete(dossier, true);
else
dataSet.Tables[0].Rows.Add(datas);
}
catch (Exception)
{
}
worker.ReportProgress((int)(currentLog * 100 / nbLogs));
}
if (Directory.Exists(Config.PathData + "/Archives/"))
{
foreach (String dossier in Directory.EnumerateDirectories(Config.PathData + "/Archives/"))
{
if (Execution.Shutdown)
return;
currentLog++;
String dossier1 = Path.GetFileName(dossier);
DateTime date;
try
{
String[] tab = dossier1.Split(new char[5] { '.', ' ', 'h', 'm', 's' });
date = new DateTime(Convert.ToInt16(tab[0]), Convert.ToInt16(tab[1]), Convert.ToInt16(tab[2]), Convert.ToInt16(tab[3]), Convert.ToInt16(tab[4]), Convert.ToInt16(tab[5]));
if (date < plusVieux)
plusVieux = date;
long taille = FolderSize(dossier);
Object[] datas = new Object[Enum.GetValues(typeof(Columns)).Length+1];
datas[(int)Columns.Date + 1] = date;
datas[(int)Columns.Taille + 1] = new TailleDossier(taille);
foreach (String fichier in Directory.EnumerateFiles(dossier))
{
if (Path.GetFileName(fichier) == "ActionsGros.elog")
{
EventsReplay r = new EventsReplay();
if (r.Charger(fichier))
datas[(int)Columns.Events + 1] = r.Events.Count;
else
datas[(int)Columns.Events + 1] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionGB.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
datas[(int)Columns.TramesGB + 1] = r.Frames.Count;
else
datas[(int)Columns.TramesGB + 1] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionMove.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
datas[(int)Columns.TramesMove + 1] = r.Frames.Count;
else
datas[(int)Columns.TramesMove + 1] = -1;
}
else if (Path.GetFileName(fichier) == "ConnexionIO.tlog")
{
FramesLog r = new FramesLog();
r.Import(fichier);
if (r.Import(fichier))
datas[(int)Columns.TramesIO + 1] = r.Frames.Count;
else
datas[(int)Columns.TramesIO + 1] = -1;
}
else if (Path.GetFileName(fichier) == "Archivage")
{
StreamReader reader = new StreamReader(fichier);
datas[0] = reader.ReadLine();
reader.Close();
}
}
dataSetArchivage.Tables[0].Rows.Add(datas);
}
catch (Exception)
{
}
}
}
}
private int OrdreAlphabetiqueInverse(String a, String b)
{
return a.CompareTo(b) * -1;
}
private void btnOuvrirDossier_Click(object sender, EventArgs e)
{
if (dataGridViewHistoLog.SelectedRows.Count > 0)
{
DateTime ligne = (DateTime)dataGridViewHistoLog.SelectedRows[0].Cells["Date"].Value;
String dossier = Config.PathData + "\\Logs\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s";
System.Diagnostics.Process.Start("explorer.exe", dossier);
}
}
private void btnSupprimer_Click(object sender, EventArgs e)
{
if (dataGridViewHistoLog.SelectedRows.Count > 0)
{
String listeDossiers = "";
for (int i = 0; i < dataGridViewHistoLog.SelectedRows.Count && i <= 20; i++)
{
DateTime ligne = (DateTime)dataGridViewHistoLog.SelectedRows[i].Cells["Date"].Value;
listeDossiers += Config.PathData + "\\Logs\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s" + Environment.NewLine;
if (i == 20)
listeDossiers += "... Et " + (dataGridViewHistoLog.SelectedRows.Count - i) + " autres dossiers ...";
}
if (MessageBox.Show("Êtes vous sûr de vouloir supprimer le(s) dossier(s) de log suivant(s) ?" + Environment.NewLine + Environment.NewLine + listeDossiers + " ?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
for (int i = dataGridViewHistoLog.SelectedRows.Count - 1; i >= 0; i--)
{
DateTime ligne = (DateTime)dataGridViewHistoLog.SelectedRows[i].Cells["Date"].Value;
String dossier = Config.PathData + "\\Logs\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s" + Environment.NewLine;
Directory.Delete(dossier, true);
dataGridViewHistoLog.Rows.RemoveAt(dataGridViewHistoLog.SelectedRows[i].Index);
}
}
}
}
private void dataGridViewHistoLog_SelectionChanged(object sender, EventArgs e)
{
if (dataGridViewHistoLog.SelectedRows.Count > 0)
{
dataGridViewFichiersLog.Rows.Clear();
DateTime ligne = (DateTime)dataGridViewHistoLog.SelectedRows[0].Cells["Date"].Value;
String dossier = Config.PathData + "\\Logs\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s";
lblFichiers.Text = "Fichiers du " + ligne.ToString();
if (Directory.Exists(dossier))
{
foreach (String fichier in Directory.EnumerateFiles(dossier))
{
String extension = Path.GetExtension(fichier);
if (extension == FramesLog.FileExtension || extension == ".elog")
{
dataGridViewFichiersLog.Rows.Add(Path.GetFileName(fichier), fichier);
}
}
}
}
}
private void dataGridViewFichiersLog_DoubleClick(object sender, EventArgs e)
{
if (dataGridViewFichiersLog.SelectedRows.Count > 0)
{
String fichier = (String)(dataGridViewFichiersLog.Rows[dataGridViewFichiersLog.SelectedRows[0].Index].Cells["Chemin"].Value);
FenGoBot.Instance.ChargerReplay(fichier);
}
}
private void btnArchivage_Click(object sender, EventArgs e)
{
if (dataGridViewHistoLog.SelectedRows.Count > 0)
{
DateTime ligne = (DateTime)dataGridViewHistoLog.SelectedRows[0].Cells["Date"].Value;
String dossier = Config.PathData + "\\Logs\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s";
String nomCourt = Path.GetFileName(dossier);
FenNomArchivage fen = new FenNomArchivage();
fen.Nom = ligne.ToString();
fen.ShowDialog();
if (!fen.OK)
return;
Directory.Move(dossier, Config.PathData + "\\Archives\\" + nomCourt);
StreamWriter writer = new StreamWriter(Config.PathData + "\\Archives\\" + nomCourt + "\\Archivage");
writer.Write(fen.Nom);
writer.Close();
Object[] datas = new Object[Enum.GetValues(typeof(Columns)).Length + 1];
datas[0] = fen.Nom;
for (int i = 0; i < Enum.GetValues(typeof(Columns)).Length; i++)
datas[i + 1] = dataGridViewHistoLog.SelectedRows[0].Cells[i].Value;
dataGridViewHistoLog.Rows.RemoveAt(dataGridViewHistoLog.SelectedRows[0].Index);
dataSetArchivage.Tables[0].Rows.Add(datas);
}
}
private void dataGridViewArchives_SelectionChanged(object sender, EventArgs e)
{
if (dataGridViewArchives.SelectedRows.Count > 0)
{
dataGridViewFichiersLog.Rows.Clear();
DateTime ligne = (DateTime)dataGridViewArchives.SelectedRows[0].Cells["Date"].Value;
String dossier = Config.PathData + "\\Archives\\" + ligne.Year.ToString("0000") + "." + ligne.Month.ToString("00") + "." + ligne.Day.ToString("00") + " " + ligne.Hour.ToString("00") + "h" + ligne.Minute.ToString("00") + "m" + ligne.Second.ToString("00") + "s";
lblFichiers.Text = "Fichiers du " + ligne.ToString();
if (Directory.Exists(dossier))
{
foreach (String fichier in Directory.EnumerateFiles(dossier))
{
String extension = Path.GetExtension(fichier);
if (extension == FramesLog.FileExtension || extension == ".elog")
{
dataGridViewFichiersLog.Rows.Add(Path.GetFileName(fichier), fichier);
}
}
}
}
}
}
class TailleDossier : IComparable
{
String taille;
long tailleOctets;
public TailleDossier(long t)
{
tailleOctets = t;
long tailleModif = tailleOctets;
String extension = " o";
if (tailleModif > 1024)
{
tailleModif /= 1024;
extension = " ko";
}
if (tailleModif > 1024)
{
tailleModif /= 1024;
extension = " mo";
}
taille = tailleModif + extension;
}
public override string ToString()
{
return taille;
}
public int CompareTo(object obj)
{
TailleDossier autre = (TailleDossier)obj;
if (autre.tailleOctets > tailleOctets)
return 1;
if (autre.tailleOctets == tailleOctets)
return 0;
return -1;
}
}
}
<file_sep>/GoBot/Composants/TrackBarPlus.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
namespace Composants
{
public partial class TrackBarPlus : UserControl
{
private bool _isReversed;
private bool _isVertical;
private double _value, _maxValue, _minValue;
private int _decimalPlaces;
private bool _isMoving;
private int _cursorSize;
private double _lastTickedValue = -1;
public delegate void ValueChangedDelegate(object sender, double value);
public event ValueChangedDelegate TickValueChanged;
public event ValueChangedDelegate ValueChanged;
public TrackBarPlus()
{
InitializeComponent();
DecimalPlaces = 0;
_isVertical = false;
_isReversed = false;
IntervalTimer = 1;
TimerTickValue = new Timer();
TimerTickValue.Tick += new EventHandler(TimerTickValue_Tick);
_minValue = 0;
_maxValue = 100;
_isMoving = false;
_decimalPlaces = 0;
_cursorSize = Height - 1;
}
private Timer TimerTickValue { get; set; }
public double Value => _value;
public uint IntervalTimer { get; set; }
public int DecimalPlaces { get; set; }
public double Min
{
get { return _minValue; }
set
{
_minValue = value;
SetValue(_value);
}
}
public double Max
{
get { return _maxValue; }
set
{
_maxValue = value;
SetValue(_value);
}
}
public bool Vertical
{
get
{
return _isVertical;
}
set
{
int oldWidth = Width;
int oldHeight = Height;
if (value)
{
MaximumSize = new Size(15, 3000);
MinimumSize = new Size(15, 30);
Height = Math.Max(oldWidth, oldHeight);
Width = Math.Min(oldWidth, oldHeight);
}
else
{
MaximumSize = new Size(3000, 15);
MinimumSize = new Size(30, 15);
Width = Math.Max(oldWidth, oldHeight);
Height = Math.Min(oldWidth, oldHeight);
}
_isVertical = value;
_cursorSize = _isVertical ? Width - 1 : Height - 1;
Invalidate();
}
}
public bool Reverse
{
get
{
return _isReversed;
}
set
{
_isReversed = value;
Invalidate();
}
}
public void SetValue(double val, bool tickEvent = true)
{
val = Math.Max(Min, Math.Min(Max, val));
if (_value != val)
{
_value = Math.Round(val, DecimalPlaces);
if (tickEvent)
TickValueChanged?.Invoke(this, _value);
ValueChanged?.Invoke(this, _value);
}
Invalidate();
}
#region Events
protected override void OnPreviewKeyDown(PreviewKeyDownEventArgs e)
{
int direction = Reverse ? -1 : 1;
if (e.KeyCode == Keys.Down)
{
SetValue(Reverse ? Max : Min);
e.IsInputKey = true;
}
else if (e.KeyCode == Keys.Up)
{
SetValue(Reverse ? Min : Max);
e.IsInputKey = true;
}
else if (e.KeyCode == Keys.Left)
{
SetValue(_value - Math.Ceiling((Max - Min) * 0.05) * direction);
e.IsInputKey = true;
}
else if (e.KeyCode == Keys.Right)
{
SetValue(_value + Math.Ceiling((Max - Min) * 0.05) * direction);
e.IsInputKey = true;
}
else if (e.KeyCode == Keys.Add)
{
SetValue(_value + direction);
e.IsInputKey = true;
}
else if (e.KeyCode == Keys.Subtract)
{
SetValue(_value - direction);
e.IsInputKey = true;
}
base.OnPreviewKeyDown(e);
}
void img_MouseMove(object sender, MouseEventArgs e)
{
OnMouseMove(e);
}
void img_MouseUp(object sender, MouseEventArgs e)
{
OnMouseUp(e);
}
void img_MouseDown(object sender, MouseEventArgs e)
{
OnMouseDown(e);
}
protected override void OnEnter(EventArgs e)
{
Invalidate();
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
Invalidate();
base.OnLeave(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
Focus();
if (e.Button == MouseButtons.Left)
{
StartMoving();
SetCursorPosition(this.PointToClient(Cursor.Position));
}
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
EndMoving();
base.OnMouseDown(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_isMoving) SetCursorPosition(this.PointToClient(Cursor.Position));
base.OnMouseMove(e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
Focus();
SetValue(_value + Math.Sign(e.Delta) * (_maxValue - _minValue) / 100, true);
}
private void TrackBarPlus_Leave(object sender, EventArgs e)
{
Invalidate();
}
private void TrackBarPlus_Enter(object sender, EventArgs e)
{
Invalidate();
}
private void TrackBarPlus_SizeChanged(object sender, EventArgs e)
{
_cursorSize = _isVertical ? Width - 1 : Height - 1;
}
#endregion
private void StartMoving()
{
_isMoving = true;
// Le premier tick se fait en 1 milliseconde, les autres suivant l'intervalle
TimerTickValue.Interval = 1;
TimerTickValue.Start();
}
private void EndMoving()
{
_isMoving = false;
}
void TimerTickValue_Tick(object sender, EventArgs e)
{
// les ticks suivants se font avec l'intervalle voulu
TimerTickValue.Interval = (int)IntervalTimer;
if (_lastTickedValue != _value)
{
_lastTickedValue = _value;
TickValueChanged?.Invoke(this, _value);
}
if (!_isMoving)
TimerTickValue.Stop();
}
private void TrackBarPlus_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
PaintBack(e.Graphics);
PaintCursor(e.Graphics);
}
private void PaintBack(Graphics g)
{
GraphicsPath path = new GraphicsPath();
int x, y, w, h;
Brush b;
if (_isVertical)
{
h = Height - 1;
w = (int)(Width / 2.5);
x = Width / 2 - w / 2;
y = 0;
path.AddLine(x + w - 1, y + w / 2 + 1, x + w - 1, y + h - w / 2 - 1);
path.AddArc(new Rectangle(x + 1, y + h - w - 1, w - 2, w - 2), 0, 180);
path.AddLine(x + 1, y + w - 1, x + 1, y + w / 2 + 1);
path.AddArc(new Rectangle(x + 1, y + 1, w - 2, w - 2), 180, 180);
if (_isReversed)
b = new LinearGradientBrush(new Rectangle(x, y, w, h), Color.Gainsboro, Color.White, LinearGradientMode.Vertical);
else
b = new LinearGradientBrush(new Rectangle(x, y, w, h), Color.White, Color.Gainsboro, LinearGradientMode.Vertical);
}
else
{
h = (int)(Height / 2.5);
w = Width - 1;
x = 0;
y = Height / 2 - h / 2;
path.AddLine(x + h / 2 + 1, y + 1, x + w - h / 2 - 1, y + 1);
path.AddArc(new Rectangle(x + w - h - 1, y + 1, h - 2, h - 2), -90, 180);
path.AddLine(x + w - h / 2 - 1, y + h - 1, x + h / 2 + 1, y + h - 1);
path.AddArc(new Rectangle(x + 1, y + 1, h - 2, h - 2), 90, 180);
if (_isReversed)
b = new LinearGradientBrush(new Rectangle(x, y, w, h), Color.White, Color.Gainsboro, LinearGradientMode.Horizontal);
else
b = new LinearGradientBrush(new Rectangle(x, y, w, h), Color.Gainsboro, Color.White, LinearGradientMode.Horizontal);
}
g.FillPath(b, path);
b.Dispose();
g.DrawPath(Pens.LightGray, path);
path.Dispose();
}
private void PaintCursor(Graphics g)
{
Rectangle rBall;
if (_isVertical)
{
int y;
if (_isReversed)
y = (int)(((_value - _minValue) * (Height - 1 - _cursorSize)) / (_maxValue - _minValue));
else
y = Height - _cursorSize - 1 - (int)(((_value - _minValue) * (Height - 1 - _cursorSize)) / (_maxValue - _minValue));
if (_minValue == _maxValue)
y = 0;
rBall = new Rectangle(0, y, _cursorSize, _cursorSize);
}
else
{
int x;
if (_isReversed)
x = Width - _cursorSize - 1 - (int)(((_value - _minValue) * (Width - 1 - _cursorSize)) / (_maxValue - _minValue));
else
x = (int)(((_value - _minValue) * (Width - 1 - _cursorSize)) / (_maxValue - _minValue));
if (_minValue == _maxValue)
x = 0;
rBall = new Rectangle(x, 0, _cursorSize, _cursorSize);
}
Brush bBall = new LinearGradientBrush(rBall, Color.WhiteSmoke, Color.LightGray, 100);
g.FillEllipse(bBall, rBall);
bBall.Dispose();
g.DrawEllipse(Focused ? Pens.DodgerBlue : Pens.Gray, rBall);
}
private void SetCursorPosition(Point pos)
{
double val;
if (!Vertical)
{
if (pos.X <= _cursorSize / 2)
val = (_isReversed) ? _maxValue : _minValue;
else if (pos.X >= this.Width - _cursorSize / 2 - 1)
val = (_isReversed) ? _minValue : _maxValue;
else
{
val = _minValue + (_maxValue - _minValue) * (pos.X - _cursorSize / 2) / (float)(Width - 1 - _cursorSize);
if (_isReversed)
val = _maxValue - val + _minValue;
}
}
else
{
if (pos.Y <= _cursorSize / 2)
val = (!_isReversed) ? _maxValue : _minValue;
else if (pos.Y >= this.Height - _cursorSize / 2 - 1)
val = (!_isReversed) ? _minValue : _maxValue;
else
{
val = _minValue + (_maxValue - _minValue) * (pos.Y - _cursorSize / 2) / (float)(Height - 1 - _cursorSize);
if (!_isReversed)
val = _maxValue - val + _minValue;
}
}
SetValue(val, false);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelConnections.cs
using Composants;
using GoBot.Communications;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class PanelConnexions : UserControl
{
private Timer _timerBatteries;
public PanelConnexions()
{
InitializeComponent();
}
void timerBatteries_Tick(object sender, EventArgs e)
{
if (Robots.Simulation)
{
batteryPack.Enabled = false;
}
else
{
if (Connections.ConnectionIO.ConnectionChecker.Connected)
{
batteryPack.Enabled = true;
batteryPack.CurrentVoltage = Robots.MainRobot.BatterieVoltage;
lblVoltage.Text = Robots.MainRobot.BatterieVoltage.ToString("0.00") + "V";
}
else
{
batteryPack.Enabled = false;
lblVoltage.Text = "-";
}
}
}
private void PanelConnexions_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
ConnectionStatus statusAvoid = new ConnectionStatus();
statusAvoid.Connection = Devices.AllDevices.LidarAvoid?.ConnectionChecker;
statusAvoid.ConnectionName = "Avoid";
_ledsPanel.Controls.Add(statusAvoid);
foreach (Connection conn in Connections.AllConnections)
{
ConnectionStatus status = new ConnectionStatus();
status.Connection = conn.ConnectionChecker;
status.ConnectionName = conn.Name;
_ledsPanel.Controls.Add(status);
}
batteryPack.VoltageHigh = Config.CurrentConfig.BatterieRobotVert;
batteryPack.VoltageAverage = Config.CurrentConfig.BatterieRobotOrange;
batteryPack.VoltageLow = Config.CurrentConfig.BatterieRobotRouge;
batteryPack.VoltageVeryLow = Config.CurrentConfig.BatterieRobotCritique;
_timerBatteries = new System.Windows.Forms.Timer();
_timerBatteries.Interval = 1000;
_timerBatteries.Tick += new EventHandler(timerBatteries_Tick);
_timerBatteries.Start();
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/SegmentWithPolygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class SegmentWithPolygon
{
public static bool Contains(Segment containingSegment, Polygon containedPolygon)
{
// Contenir un polygone dans un segment revient à contenir tous les points du polygone
return containedPolygon.Points.TrueForAll(p => SegmentWithRealPoint.Contains(containingSegment, p));
}
public static bool Cross(Segment segment, Polygon polygon)
{
return polygon.Sides.Exists(s => SegmentWithSegment.Cross(s, segment));
}
public static double Distance(Segment segment, Polygon polygon)
{
return polygon.Sides.Min(s => SegmentWithSegment.Distance(s, segment));
}
public static List<RealPoint> GetCrossingPoints(Segment segment, Polygon polygon)
{
return polygon.Sides.SelectMany(s => SegmentWithSegment.GetCrossingPoints(s, segment)).ToList();
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaTable.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using GoBot.BoardContext;
using GoBot.Communications;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PagePandaTable : UserControl
{
public PagePandaTable()
{
InitializeComponent();
}
private void PagePandaTable_Load(object sender, System.EventArgs e)
{
if (!Execution.DesignMode)
{
btnTrap.Focus();
Dessinateur.TableDessinee += Dessinateur_TableDessinee;
}
}
private void Dessinateur_TableDessinee(Image img)
{
picTable.BackgroundImage = img;
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/PolygonWithCircle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class PolygonWithCircle
{
public static bool Contains(Polygon containingPolygon, Circle containedCircle)
{
// Pour contenir un cercle, un polygone ne doit pas être contenu par le cercle, ne pas le croiser et contenir son centre
return !CircleWithPolygon.Contains(containedCircle, containingPolygon) && !PolygonWithCircle.Cross(containingPolygon, containedCircle) && PolygonWithRealPoint.Contains(containingPolygon, containedCircle.Center);
}
public static bool Cross(Polygon polygon, Circle circle)
{
return CircleWithPolygon.Cross(circle, polygon);
}
public static double Distance(Polygon polygon, Circle circle)
{
return CircleWithPolygon.Distance(circle, polygon);
}
public static List<RealPoint> GetCrossingPoints(Polygon polygon, Circle circle)
{
return CircleWithPolygon.GetCrossingPoints(circle, polygon);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/ConnectionStatus.cs
using GoBot.Communications;
using GoBot.Communications.UDP;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class ConnectionStatus : UserControl
{
private ConnectionChecker _connection;
private Timer _timer;
public ConnectionStatus()
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 500;
_timer.Tick += _timer_Tick;
_timer.Start();
}
private void _timer_Tick(object sender, EventArgs e)
{
if (_connection != null)
this.InvokeAuto(() => _conIndicator.BlinkColor(GetColor(_connection.Connected, _connection.Connected)));
}
public ConnectionChecker Connection
{
get
{
return _connection;
}
set
{
if (_connection != null)
_connection.ConnectionStatusChange -= ConnexionCheck_ConnectionStatusChange;
_connection = value;
if (_connection != null)
{
_conIndicator.Color = GetColor(_connection.Connected, _connection.Connected);
_connection.ConnectionStatusChange += ConnexionCheck_ConnectionStatusChange;
}
}
}
public String ConnectionName
{
set { _lblName.Text = value; }
}
public Color TextColor
{
set { _lblName.ForeColor = value; }
}
private void ConnexionCheck_ConnectionStatusChange(Connection sender, bool connected)
{
this.InvokeAuto(() => _conIndicator.BlinkColor(GetColor(_connection.Connected, connected)));
}
private ColorPlus GetColor(bool inOK, bool outOk)
{
ColorPlus output;
if (inOK && outOk)
output = Color.LimeGreen;
else if (!inOK && !outOk)
output = Color.Red;
else
output = Color.Orange;
return output;
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaMatch.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using GoBot.BoardContext;
using GoBot.Communications;
using GoBot.Threading;
namespace GoBot.IHM.Pages
{
public partial class PagePandaMatch : UserControl
{
public delegate void DoneDelegate();
public event DoneDelegate CalibrationDone;
public PagePandaMatch()
{
InitializeComponent();
GameBoard.MyColorChange += GameBoard_MyColorChange;
btnColorLeft.BackColor = GameBoard.ColorLeftBlue;
btnColorRight.BackColor = GameBoard.ColorRightYellow;
}
private void PageMatch_Load(object sender, System.EventArgs e)
{
if (!Execution.DesignMode)
{
btnTrap.Focus();
Dessinateur.TableDessinee += Dessinateur_TableDessinee;
Robots.MainRobot.SensorOnOffChanged += MainRobot_SensorOnOffChanged;
Connections.AllConnections.ForEach(c => c.ConnectionChecker.ConnectionStatusChange += ConnectionChecker_ConnectionStatusChange);
Devices.AllDevices.LidarAvoid.ConnectionChecker.ConnectionStatusChange += LidarAvoid_ConnectionStatusChange;
Devices.AllDevices.LidarGround.ConnectionChecker.ConnectionStatusChange += LidarGround_ConnectionStatusChange;
SetPicImage(picLidar, Devices.AllDevices.LidarAvoid.ConnectionChecker.Connected);
//SetPicImage(picLidar2, Devices.AllDevices.LidarGround.ConnectionChecker.Connected);
SetPicImage(picIO, Connections.ConnectionIO.ConnectionChecker.Connected);
SetPicImage(picMove, Connections.ConnectionMove.ConnectionChecker.Connected);
SetPicImage(picCAN, Connections.ConnectionCanBridge.ConnectionChecker.Connected);
SetPicImage(picServo1, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo1].ConnectionChecker.Connected);
SetPicImage(picServo2, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo2].ConnectionChecker.Connected);
SetPicImage(picServo3, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo3].ConnectionChecker.Connected);
SetPicImage(picServo4, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo4].ConnectionChecker.Connected);
SetPicImage(picServo5, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo5].ConnectionChecker.Connected);
SetPicImage(picServo6, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo6].ConnectionChecker.Connected);
//SetPicImage(picAlim, Connections.ConnectionsCan[Communications.CAN.CanBoard.CanAlim].ConnectionChecker.Connected);
bool jack = Robots.MainRobot.ReadStartTrigger();
SetPicImage(picStartTrigger, jack);
btnCalib.Enabled = jack;
}
}
private void LidarAvoid_ConnectionStatusChange(Connection sender, bool connected)
{
SetPicImage(picLidar, connected);
}
private void LidarGround_ConnectionStatusChange(Connection sender, bool connected)
{
//SetPicImage(picLidar2, connected);
}
private void ConnectionChecker_ConnectionStatusChange(Connection sender, bool connected)
{
if (sender == Connections.ConnectionIO)
SetPicImage(picIO, connected);
else if (sender == Connections.ConnectionMove)
SetPicImage(picMove, connected);
else if (sender == Connections.ConnectionCanBridge)
SetPicImage(picCAN, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo1])
SetPicImage(picServo1, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo2])
SetPicImage(picServo2, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo3])
SetPicImage(picServo3, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo4])
SetPicImage(picServo4, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo5])
SetPicImage(picServo5, connected);
else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanServo6])
SetPicImage(picServo6, connected);
//else if (sender == Connections.ConnectionsCan[Communications.CAN.CanBoard.CanAlim])
// SetPicImage(picAlim, connected);
}
private void MainRobot_SensorOnOffChanged(SensorOnOffID capteur, bool etat)
{
if (capteur == SensorOnOffID.StartTrigger)
{
SetPicImage(picStartTrigger, etat);
btnCalib.InvokeAuto(() => btnCalib.Enabled = true);
}
}
private static void SetPicImage(PictureBox pic, bool ok)
{
if (pic.Width > 50)
pic.Image = ok ? Properties.Resources.ValidOk96 : Properties.Resources.ValidNok96;
else
pic.Image = ok ? Properties.Resources.ValidOk48 : Properties.Resources.ValidNok48;
}
private void GameBoard_MyColorChange(object sender, EventArgs e)
{
Rectangle r = new Rectangle(8, 8, 78, 78);
Bitmap img = new Bitmap(picColor.Width, picColor.Height);
Graphics g = Graphics.FromImage(img);
Brush brush = new LinearGradientBrush(r, ColorPlus.GetIntense(GameBoard.MyColor), ColorPlus.GetPastel(GameBoard.MyColor), 24);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillEllipse(brush, r);
g.DrawImage(Properties.Resources.Circle96, 0, 0, 96, 96);
brush.Dispose();
g.Dispose();
picColor.Image = img;
}
private void Dessinateur_TableDessinee(Image img)
{
picTable.BackgroundImage = img;
}
private void btnCalib_Click(object sender, System.EventArgs e)
{
ThreadManager.CreateThread(link =>
{
link.Name = "Calibration";
Recalibration.Calibration();
picCalibration.InvokeAuto(() => picCalibration.Image = Properties.Resources.ValidOk96);
CalibrationDone?.Invoke();
}).StartThread();
btnTrap.Focus();
}
private void btnColorLeft_Click(object sender, EventArgs e)
{
GameBoard.MyColor = GameBoard.ColorLeftBlue;
btnTrap.Focus();
}
private void btnColorRight_Click(object sender, EventArgs e)
{
GameBoard.MyColor = GameBoard.ColorRightYellow;
btnTrap.Focus();
}
private void btnInit_Click(object sender, EventArgs e)
{
btnTrap.Focus();
Robots.MainRobot.ActuatorsStore();
SetPicImage(picInit, true);
btnInit.Enabled = false;
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Fingers.cs
using GoBot.GameElements;
using GoBot.Threading;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
namespace GoBot.Actionneurs
{
class FingerLeft : Finger
{
public FingerLeft()
{
_makeVacuum = ActuatorOnOffID.MakeVacuumLeftBack;
_openVacuum = ActuatorOnOffID.OpenVacuumLeftBack;
_pressure = SensorOnOffID.PressureSensorLeftBack;
_finger = Config.CurrentConfig.ServoFingerLeft;
}
}
class FingerRight : Finger
{
public FingerRight()
{
_makeVacuum = ActuatorOnOffID.MakeVacuumRightBack;
_openVacuum = ActuatorOnOffID.OpenVacuumRightBack;
_pressure = SensorOnOffID.PressureSensorRightBack;
_finger = Config.CurrentConfig.ServoFingerRight;
}
}
abstract class Finger
{
protected ActuatorOnOffID _makeVacuum, _openVacuum;
protected SensorOnOffID _pressure;
protected ServoFinger _finger;
protected Color _load;
public bool Loaded => _load != Color.Transparent;
public Color Load => _load;
public Finger()
{
_load = Color.Transparent;
}
public void DoDemoGrab(ThreadLink link = null)
{
Stopwatch swMain = Stopwatch.StartNew();
bool ok;
DoAirLock();
while (!link.Cancelled && swMain.Elapsed.TotalMinutes < 1)
{
ok = false;
Thread.Sleep(1000);
if (!HasSomething())
{
DoPositionGrab();
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 1000 && !ok)
{
Thread.Sleep(50);
ok = HasSomething();
}
if (ok)
DoPositionKeep();
else
DoPositionHide();
}
}
DoPositionHide();
DoAirUnlock();
}
public bool DoGrabGreen()
{
bool ok = false;
DoAirLock();
DoPositionGrab();
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 750 && !ok)
{
Thread.Sleep(50);
ok = HasSomething();
}
if (ok)
{
_load = Buoy.Green;
DoPositionKeep();
}
else
{
DoAirUnlock();
DoPositionHide();
}
return ok;
}
public bool DoGrabColor(Color c)
{
bool ok = false;
DoAirLock();
DoPositionGrab();
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < 750 && !ok)
{
Thread.Sleep(50);
ok = HasSomething();
}
if (ok)
{
_load = c;
DoPositionKeep();
}
else
{
DoAirUnlock();
DoPositionHide();
}
return ok;
}
public void DoRelease()
{
DoAirUnlock();
DoPositionHide();
_load = Color.Transparent;
}
public void DoAirLock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, true);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, false);
}
public void DoAirUnlock()
{
Robots.MainRobot.SetActuatorOnOffValue(_makeVacuum, false);
Robots.MainRobot.SetActuatorOnOffValue(_openVacuum, true);
}
public void DoPositionHide()
{
_finger.SendPosition(_finger.PositionHide);
}
public void DoPositionKeep()
{
_finger.SendPosition(_finger.PositionKeep);
}
public void DoPositionGrab()
{
_finger.SendPosition(_finger.PositionGrab);
}
public bool HasSomething()
{
return Robots.MainRobot.ReadSensorOnOff(_pressure);
}
}
}<file_sep>/GoBot/Composants/Battery.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace Composants
{
public partial class Battery : PictureBox
{
private System.Windows.Forms.Timer timerBlink;
private double currentVoltage;
private State currentState;
public enum State
{
High,
MidHigh,
Average,
Low,
VeryLow,
Absent
}
/// <summary>
/// Définit la tension au dessus de laquelle la tension est considérée comme élevée
/// </summary>
public double VoltageHigh { get; set; }
/// <summary>
/// Définit la tension au dessus de laquelle la tension est considérée comme moyenne
/// </summary>
public double VoltageAverage { get; set; }
/// <summary>
/// Définit la tension au dessus de laquelle la tension est considérée comme basse
/// </summary>
public double VoltageLow { get; set; }
/// <summary>
/// Définit la tension au dessus de laquelle la tension est considérée comme critique
/// </summary>
public double VoltageVeryLow { get; set; }
public Battery()
{
InitializeComponent();
timerBlink = new System.Windows.Forms.Timer();
timerBlink.Interval = 300;
timerBlink.Tick += new EventHandler(timer_Tick);
CurrentVoltage = -1;
CurrentState = State.Absent;
VoltageLow = 0;
VoltageAverage = 0;
VoltageHigh = 0;
toolTip.SetToolTip(this, "0V");
}
/// <summary>
/// Permet d'obtenir ou de définir le visuel actuel de la batterie
/// </summary>
public State CurrentState
{
get { return currentState; }
set
{
Image img;
currentState = value;
if (Enabled)
{
switch (currentState)
{
case State.High:
img = Properties.Resources.BatHigh;
ChangeImage(Properties.Resources.BatHigh, false);
break;
case State.MidHigh:
ChangeImage(Properties.Resources.BatMidHigh, false);
break;
case State.Average:
ChangeImage(Properties.Resources.BatMid, false);
break;
case State.Low:
img = Properties.Resources.BatLow;
ChangeImage(Properties.Resources.BatLow, true);
break;
case State.VeryLow:
img = Properties.Resources.BatCrit;
ChangeImage(Properties.Resources.BatCrit, true);
break;
case State.Absent:
ChangeImage(Properties.Resources.BatNo);
break;
}
}
else
ChangeImage(Properties.Resources.BatNo, false);
}
}
/// <summary>
/// Permet de définir ou d'obtenir la tension qui détermine le visuel
/// </summary>
public double CurrentVoltage
{
get { return currentVoltage; }
set
{
toolTip.SetToolTip(this, currentVoltage + "V");
currentVoltage = value;
if (value > VoltageHigh)
CurrentState = State.High;
else if (value > VoltageAverage)
CurrentState = State.Average;
else if (value > VoltageLow)
CurrentState = State.Low;
else if (value >= VoltageVeryLow)
CurrentState = State.VeryLow;
}
}
private void ChangeImage(Image img, bool blink = false)
{
timerBlink.Stop();
Visible = true;
Image = img;
if (blink)
timerBlink.Start();
}
void timer_Tick(object sender, EventArgs e)
{
if (Visible)
Visible = false;
else
{
Visible = true;
timerBlink.Stop();
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelSensorsOnOff.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GoBot.IHM
{
public partial class PanelSensorsOnOff : UserControl
{
public PanelSensorsOnOff()
{
InitializeComponent();
}
private void PanelSensorsOnOff_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
int y = 20;
foreach (SensorOnOffID sensor in Enum.GetValues(typeof(SensorOnOffID)))
{
PanelSensorOnOff panel = new PanelSensorOnOff();
panel.SetBounds(5, y, grpSensors.Width - 10, panel.Height);
panel.SetSensor(sensor);
y += panel.Height;
grpSensors.Controls.Add(panel);
}
grpSensors.Height = y + 5;
this.Height = grpSensors.Bottom + 3;
}
}
}
}
<file_sep>/GoBot/GoBot/Enums.cs
namespace GoBot
{
public enum SensAR
{
Avant = 0,
Arriere = 1
}
public enum SensGD
{
Gauche = 2,
Droite = 3
}
public enum StopMode
{
Freely = 0x00,
Smooth = 0x01,
Abrupt = 0x02
}
public enum ServomoteurID
{
Unused00 = 0,
LockerRight = 1,
LockerLeft = 2,
Unused03 = 3,
PushArmRight = 4,
FlagRight = 5,
Unused06 = 6,
Unused07 = 7,
Clamp1 = 8,
Clamp2 = 9,
Tilter = 10,
Lifter = 11,
Unused12 = 12,
Unused13 = 13,
FlagLeft = 14,
PushArmLeft = 15,
Clamp3 = 16,
Unused17 = 17,
Clamp4 = 18,
Clamp5 = 19,
GrabberLeft = 20,
FingerRight = 21,
FingerLeft = 22,
GrabberRight = 23,
// Petit robot (astuce no >= 100 = modulo)
ElevatorRight = 100,
Unued101 = 101,
ArmLeft = 102,
ElevatorLeft = 103,
ElevatorBack = 104,
Retractor = 105,
ArmRight = 106,
Selector = 107
}
public enum MotorID
{
ElevatorLeft = 0x00,
ElevatorRight = 0x01,
AvailableOnRecIO2 = 0x02,
AvailableOnRecIO3 = 0x03,
AvailableOnRecMove11 = 0x11,
AvailableOnRecMove12 = 0x12
}
public enum ActuatorOnOffID
{
PowerSensorColorBuoyRight = 0x00,
PowerSensorColorBuoyLeft = 0x01,
MakeVacuumRightFront = 0x11,
MakeVacuumLeftFront = 0x12,
MakeVacuumRightBack = 0x13,
MakeVacuumLeftBack = 0x14,
OpenVacuumRightFront = 0x21,
OpenVacuumLeftFront = 0x20,
OpenVacuumRightBack = 0x22,
OpenVacuumLeftBack = 0x23,
// Petit robot
MakeVacuumLeft = 0x24,
MakeVacuumRight = 0x25,
MakeVacuumBack = 0x26,
OpenVacuumLeft = 0x27,
OpenVacuumRight = 0x28,
OpenVacuumBack = 0x29
}
public enum SensorOnOffID
{
StartTrigger = 0x10,
PressureSensorRightFront = 0x11,
PressureSensorLeftFront = 0x12,
PressureSensorRightBack = 0x13,
PressureSensorLeftBack = 0x14,
PresenceBuoyRight = 0x20,
// Petit robot
PressureSensorLeft = 0x21,
PressureSensorRight = 0x22,
PressureSensorBack = 0x23
}
public enum SensorColorID
{
BuoyRight = 0,
BuoyLeft = 1
}
public enum CodeurID
{
Manuel = 1
}
public enum BaliseID
{
Principale = 0
}
public enum LidarID
{
Ground = 0,
Avoid = 1
}
public enum Board
{
PC = 0xA1,
RecMove = 0xC1,
RecIO = 0xC4,
RecCan = 0xC5
}
public enum ServoBaudrate
{
b1000000 = 1,
b500000 = 3,
b400000 = 4,
b250000 = 7,
b200000 = 9,
b115200 = 16,
b57600 = 34,
b19200 = 103,
b9600 = 207
}
public static class EnumExtensions
{
public static int Factor(this SensAR sens)
{
return sens == SensAR.Avant ? 1 : -1;
}
public static int Factor(this SensGD sens)
{
return sens == SensGD.Droite ? 1 : -1;
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelAnalogique.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
using GoBot.Communications;
using GoBot.Threading;
namespace GoBot.IHM
{
public partial class PanelAnalogique : UserControl
{
private ThreadLink _linkPolling, _linkDraw;
public PanelAnalogique()
{
InitializeComponent();
}
public Board Carte { get; set; }
private void PanelAnalogique_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
ctrlGraphique.BorderVisible = true;
ctrlGraphique.BorderColor = Color.LightGray;
}
}
void AskValues()
{
Robots.MainRobot.ReadAnalogicPins(Carte, true);
if (Robots.MainRobot.AnalogicPinsValue[Carte] != null)
{
this.InvokeAuto(() =>
{
List<double> values = Robots.MainRobot.AnalogicPinsValue[Carte];
lblAN1.Text = values[0].ToString("0.0000") + " V";
lblAN2.Text = values[1].ToString("0.0000") + " V";
lblAN3.Text = values[2].ToString("0.0000") + " V";
lblAN4.Text = values[3].ToString("0.0000") + " V";
lblAN5.Text = values[4].ToString("0.0000") + " V";
lblAN6.Text = values[5].ToString("0.0000") + " V";
lblAN7.Text = values[6].ToString("0.0000") + " V";
lblAN8.Text = values[7].ToString("0.0000") + " V";
lblAN9.Text = values[8].ToString("0.0000") + " V";
ctrlGraphique.AddPoint("AN1", values[0], ColorPlus.FromHsl(360 / 9 * 0, 1, 0.4));
ctrlGraphique.AddPoint("AN2", values[1], ColorPlus.FromHsl(360 / 9 * 1, 1, 0.4));
ctrlGraphique.AddPoint("AN3", values[2], ColorPlus.FromHsl(360 / 9 * 2, 1, 0.4));
ctrlGraphique.AddPoint("AN4", values[3], ColorPlus.FromHsl(360 / 9 * 3, 1, 0.4));
ctrlGraphique.AddPoint("AN5", values[4], ColorPlus.FromHsl(360 / 9 * 4, 1, 0.4));
ctrlGraphique.AddPoint("AN6", values[5], ColorPlus.FromHsl(360 / 9 * 5, 1, 0.4));
ctrlGraphique.AddPoint("AN7", values[6], ColorPlus.FromHsl(360 / 9 * 6, 1, 0.4));
ctrlGraphique.AddPoint("AN8", values[7], ColorPlus.FromHsl(360 / 9 * 7, 1, 0.4));
ctrlGraphique.AddPoint("AN9", values[8], ColorPlus.FromHsl(360 / 9 * 8, 1, 0.4));
});
}
}
private void switchBouton_ValueChanged(object sender, bool value)
{
if(value)
{
_linkPolling = ThreadManager.CreateThread(link => AskValues());
_linkPolling.Name = "Ports analogiques " + Carte.ToString();
_linkPolling.StartInfiniteLoop(50);
_linkDraw = ThreadManager.CreateThread(link => ctrlGraphique.DrawCurves());
_linkDraw.Name = "Graph ports analogiques " + Carte.ToString();
_linkDraw.StartInfiniteLoop(100);
}
else
{
_linkPolling.Cancel();
_linkPolling.WaitEnd();
_linkPolling = null;
_linkDraw.Cancel();
_linkDraw.WaitEnd();
_linkDraw = null;
}
}
private void boxAN1_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN1", boxIOAN1.Checked);
}
private void boxAN2_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN2", boxIOAN2.Checked);
}
private void boxAN3_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN3", boxIOAN3.Checked);
}
private void boxAN4_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN4", boxIOAN4.Checked);
}
private void boxAN5_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN5", boxIOAN5.Checked);
}
private void boxAN6_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN6", boxIOAN6.Checked);
}
private void boxAN7_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN7", boxIOAN7.Checked);
}
private void boxAN8_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN8", boxIOAN8.Checked);
}
private void boxAN9_CheckedChanged(object sender, EventArgs e)
{
ctrlGraphique.ShowCurve("AN9", boxIOAN9.Checked);
}
}
}
<file_sep>/GoBot/GoBot/IHM/Elements/PanelBoardCanServos.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GoBot.Threading;
using System.Threading;
using GoBot.Devices.CAN;
using GoBot.Devices;
using GoBot.Communications.CAN;
namespace GoBot.IHM
{
public partial class PanelBoardCanServos : UserControl
{
private CanBoard _boardID;
private CanServo _servo1, _servo2, _servo3, _servo4;
public PanelBoardCanServos()
{
InitializeComponent();
}
public void SetBoardID(CanBoard board)
{
_boardID = board;
if (_servo1 != null)
{
_servo1.TorqueAlert -= PanelBoardCanServos_TorqueAlert1;
_servo2.TorqueAlert -= PanelBoardCanServos_TorqueAlert2;
_servo3.TorqueAlert -= PanelBoardCanServos_TorqueAlert3;
_servo4.TorqueAlert -= PanelBoardCanServos_TorqueAlert4;
}
_servo1 = AllDevices.CanServos[(ServomoteurID)(((int)_boardID - 1) * 4 + 0)];
_servo2 = AllDevices.CanServos[(ServomoteurID)(((int)_boardID - 1) * 4 + 1)];
_servo3 = AllDevices.CanServos[(ServomoteurID)(((int)_boardID - 1) * 4 + 2)];
_servo4 = AllDevices.CanServos[(ServomoteurID)(((int)_boardID - 1) * 4 + 3)];
lblTitle.Text = _boardID.ToString();
lblServo1.Text = Parse(_servo1.ID);
lblServo2.Text = Parse(_servo2.ID);
lblServo3.Text = Parse(_servo3.ID);
lblServo4.Text = Parse(_servo4.ID);
if (!Execution.DesignMode)
{
_servo1.TorqueAlert += PanelBoardCanServos_TorqueAlert1;
_servo2.TorqueAlert += PanelBoardCanServos_TorqueAlert2;
_servo3.TorqueAlert += PanelBoardCanServos_TorqueAlert3;
_servo4.TorqueAlert += PanelBoardCanServos_TorqueAlert4;
}
}
private void PanelBoardCanServos_TorqueAlert1()
{
ThreadManager.CreateThread(link =>
{
lblServo1.InvokeAuto(() => lblServo1.ForeColor = Color.Red);
Thread.Sleep(2000);
lblServo1.InvokeAuto(() => lblServo1.ForeColor = Color.Black);
}).StartThread();
}
private void PanelBoardCanServos_TorqueAlert2()
{
ThreadManager.CreateThread(link =>
{
lblServo2.InvokeAuto(() => lblServo2.ForeColor = Color.Red);
Thread.Sleep(2000);
lblServo2.InvokeAuto(() => lblServo2.ForeColor = Color.Black);
}).StartThread();
}
private void PanelBoardCanServos_TorqueAlert3()
{
ThreadManager.CreateThread(link =>
{
lblServo3.InvokeAuto(() => lblServo3.ForeColor = Color.Red);
Thread.Sleep(2000);
lblServo3.InvokeAuto(() => lblServo3.ForeColor = Color.Black);
}).StartThread();
}
private void PanelBoardCanServos_TorqueAlert4()
{
ThreadManager.CreateThread(link =>
{
lblServo4.InvokeAuto(() => lblServo4.ForeColor = Color.Red);
Thread.Sleep(2000);
lblServo4.InvokeAuto(() => lblServo4.ForeColor = Color.Black);
}).StartThread();
}
private String Parse(ServomoteurID servo)
{
return servo.ToString().Replace("Unused", "");
}
public delegate void ServoClickDelegate(ServomoteurID servoNo);
public event ServoClickDelegate ServoClick;
private void lblServo1_Click(object sender, EventArgs e)
{
ServoClick?.Invoke((ServomoteurID)(((int)_boardID - 1) * 4 + 0));
}
private void lblServo2_Click(object sender, EventArgs e)
{
ServoClick?.Invoke((ServomoteurID)(((int)_boardID - 1) * 4 + 1));
}
private void lblServo3_Click(object sender, EventArgs e)
{
ServoClick?.Invoke((ServomoteurID)(((int)_boardID - 1) * 4 + 2));
}
private void lblServo4_Click(object sender, EventArgs e)
{
ServoClick?.Invoke((ServomoteurID)(((int)_boardID - 1) * 4 + 3));
}
}
}
<file_sep>/GoBot/GoBot/Actions/ITimeableAction.cs
using System;
namespace GoBot.Actions
{
public interface ITimeableAction : IAction
{
TimeSpan Duration { get; }
}
}
<file_sep>/GoBot/Composants/ColorPickup.cs
using System.Drawing;
using System.Windows.Forms;
namespace Composants
{
public partial class ColorPickup : PictureBox
{
public delegate void ColorDelegate(Color color);
/// <summary>
/// Se produit lorsque la souris passe sur une nouvelle couleur
/// </summary>
public event ColorDelegate ColorHover;
/// <summary>
/// Se produit lorsque la souris clique sur une couleur
/// </summary>
public event ColorDelegate ColorClick;
public ColorPickup()
{
InitializeComponent();
this.Image = Properties.Resources.Rainbow2D;
this.Width = this.Image.Width;
this.Height = this.Image.Height;
this.MouseMove += ColorPickup_MouseMove;
this.MouseClick += ColorPickup_MouseClick;
}
void ColorPickup_MouseClick(object sender, MouseEventArgs e)
{
ColorClick?.Invoke(GetColor(new Point(e.X, e.Y)));
}
void ColorPickup_MouseMove(object sender, MouseEventArgs e)
{
ColorHover?.Invoke(GetColor(new Point(e.X, e.Y)));
}
private Color GetColor(Point pos)
{
return Properties.Resources.Rainbow2D.GetPixel(pos.X, pos.Y);
}
}
}
<file_sep>/GoBot/GoBot/MinimumDelay.cs
using System.Diagnostics;
using System.Threading;
namespace GoBot
{
class MinimumDelay
{
private Stopwatch _lastCommandTime;
private int _delay;
public MinimumDelay(int delayMs)
{
_delay = delayMs;
}
public void Wait()
{
if (_lastCommandTime != null)
{
while (_lastCommandTime.ElapsedMilliseconds < _delay)
Thread.Sleep(1);
}
_lastCommandTime = Stopwatch.StartNew();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Forms/DebugLidar.cs
using GoBot.Devices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GoBot.IHM.Forms
{
public partial class DebugLidar : Form
{
public DebugLidar()
{
InitializeComponent();
}
private void btnAsk_Click(object sender, EventArgs e)
{
Stopwatch sw = Stopwatch.StartNew();
txtMessage.Text = ((HokuyoRec)AllDevices.LidarGround).ReadMessage();
lblTime.Text = sw.ElapsedMilliseconds.ToString() + "ms";
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageServomotors.cs
using System;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PageServomotors : UserControl
{
public PageServomotors()
{
InitializeComponent();
}
private void panelCan_ServoClick(ServomoteurID servoNo)
{
panelServoCan.SetServo(servoNo);
}
private void PageServomotors_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
panelBoardCanServos1.SetBoardID(Communications.CAN.CanBoard.CanServo1);
panelBoardCanServos2.SetBoardID(Communications.CAN.CanBoard.CanServo2);
panelBoardCanServos3.SetBoardID(Communications.CAN.CanBoard.CanServo3);
panelBoardCanServos4.SetBoardID(Communications.CAN.CanBoard.CanServo4);
panelBoardCanServos5.SetBoardID(Communications.CAN.CanBoard.CanServo5);
panelBoardCanServos6.SetBoardID(Communications.CAN.CanBoard.CanServo6);
}
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementRandomPickup.cs
using Geometry;
using Geometry.Shapes;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.Movements
{
class MovementRandomPickup : Movement
{
private bool _hasBuoys = true;
private GameElementZone _zone;
public MovementRandomPickup(GameElementZone zone)
{
_zone = zone;
Positions.Add(new Position(-45, new RealPoint(1050, 400)));
Positions.Add(new Position(-45 + 180, new RealPoint(1950, 400)));
}
public override bool CanExecute => _hasBuoys;
public override int Score => 0;
public override double Value => _hasBuoys ? 1 : 0;
public override GameElement Element => _zone;
public override Robot Robot => Robots.MainRobot;
public override Color Color => Color.White;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
bool found = true;
while (found && Actionneurs.Actionneur.ElevatorLeft.CanStoreMore)
found = Actionneurs.Actionneur.ElevatorLeft.DoSearchBuoy(Buoy.Green, new Circle(_zone.Position, _zone.HoverRadius));
while (found && Actionneurs.Actionneur.ElevatorRight.CanStoreMore)
found = Actionneurs.Actionneur.ElevatorRight.DoSearchBuoy(Buoy.Red, new Circle(_zone.Position, _zone.HoverRadius));
_hasBuoys = false;
return found;
}
protected override void MovementEnd()
{
Actionneurs.Actionneur.ElevatorLeft.DoStoreActuators();
Actionneurs.Actionneur.ElevatorRight.DoStoreActuators();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageTable.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
using GoBot.BoardContext;
using GoBot.GameElements;
using GoBot.Strategies;
using GoBot.Movements;
namespace GoBot.IHM.Pages
{
public partial class PageTable : UserControl
{
private static ThreadLink _linkDisplay;
public static GameBoard Plateau { get; set; }
public PageTable()
{
InitializeComponent();
Plateau = new GameBoard();
GameBoard.ScoreChange += new GameBoard.ScoreChangeDelegate(Plateau_ScoreChange);
GameBoard.MyColorChange += GameBoard_MyColorChange;
Dessinateur.TableDessinee += Dessinateur_TableDessinee;
btnColorLeft.BackColor = GameBoard.ColorLeftBlue;
btnColorRight.BackColor = GameBoard.ColorRightYellow;
checkedListBox.SetItemChecked(0, true);
checkedListBox.SetItemChecked(1, true);
checkedListBox.SetItemChecked(5, true);
toolTip.SetToolTip(btnTeleportRPFace, "Téléportation de face");
toolTip.SetToolTip(btnTeleportRPCentre, "Téléportation de centre");
toolTip.SetToolTip(btnPathRPFace, "Path finding de face");
toolTip.SetToolTip(btnPathRPCentre, "Path finding du centre");
}
private void GameBoard_MyColorChange(object sender, EventArgs e)
{
picColor.BackColor = GameBoard.MyColor;
}
void Dessinateur_TableDessinee(Image img)
{
this.InvokeAuto(() => pictureBoxTable.Image = img);
}
void Plateau_ScoreChange(int score)
{
this.InvokeAuto(() => lblScore.Text = score.ToString());
}
void DisplayInfos()
{
this.InvokeAuto(() =>
{
Position pos = Robots.MainRobot.Position;
lblPosX.Text = pos.Coordinates.X.ToString("0.00");
lblPosY.Text = pos.Coordinates.Y.ToString("0.00");
lblPosTheta.Text = pos.Angle.InDegrees.ToString("0.00") + "°";
});
if (GameBoard.Strategy != null)
{
TimeSpan tempsRestant = GameBoard.Strategy.TimeBeforeEnd;
if (tempsRestant.TotalMilliseconds <= 0)
tempsRestant = new TimeSpan(0);
Color couleur;
if (tempsRestant.TotalSeconds > GameBoard.Strategy.MatchDuration.TotalSeconds / 2)
couleur = Color.FromArgb((int)((GameBoard.Strategy.MatchDuration.TotalSeconds - tempsRestant.TotalSeconds) * (150.0 / (GameBoard.Strategy.MatchDuration.TotalSeconds / 2.0))), 150, 0);
else
couleur = Color.FromArgb(150, 150 - (int)((GameBoard.Strategy.MatchDuration.TotalSeconds / 2.0 - tempsRestant.TotalSeconds) * (150.0 / (GameBoard.Strategy.MatchDuration.TotalSeconds / 2.0))), 0);
this.InvokeAuto(() =>
{
lblSecondes.Text = tempsRestant.TotalSeconds.ToString("0");
lblSecondes.ForeColor = couleur;
});
}
}
private void btnAffichage_Click(object sender, EventArgs e)
{
if (btnAffichage.Text == "Lancer l'affichage")
{
_linkDisplay = ThreadManager.CreateThread(link => DisplayInfos());
_linkDisplay.Name = "Affichage des données";
_linkDisplay.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 100));
Dessinateur.Start();
btnAffichage.Text = "Stopper l'affichage";
btnAffichage.Image = GoBot.Properties.Resources.Pause16;
}
else
{
_linkDisplay?.Cancel();
_linkDisplay?.WaitEnd();
_linkDisplay = null;
Dessinateur.Stop();
btnAffichage.Text = "Lancer l'affichage";
btnAffichage.Image = GoBot.Properties.Resources.Play16;
}
}
DateTime dateCapture = DateTime.Now;
Semaphore semMove = new Semaphore(1, 1);
Random rand = new Random();
private void pictureBoxTable_MouseMove(object sender, MouseEventArgs e)
{
semMove.WaitOne();
Dessinateur.PositionCurseur = pictureBoxTable.PointToClient(MousePosition);
if (pSelected != -1)
{
pointsPolaires[pSelected] = Dessinateur.Scale.ScreenToRealPosition(e.Location);
trajectoirePolaire = BezierCurve.GetPoints(pointsPolaires, (int)(numNbPoints.Value));//((int)pointsPolaires[0].Distance(pointsPolaires[pointsPolaires.Count - 1])) / 50);
Dessinateur.TrajectoirePolaire = trajectoirePolaire;
Dessinateur.PointsPolaire = pointsPolaires;
}
if (boxSourisObstacle.Checked)
{
if ((DateTime.Now - dateCapture).TotalMilliseconds > 50)
{
dateCapture = DateTime.Now;
Point p = Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition));
List<RealPoint> positions = new List<RealPoint>();
positions.Add(Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition)));
GameBoard.SetOpponents(positions);
//SuiviBalise.MajPositions(positions, Plateau.Enchainement == null || Plateau.Enchainement.DebutMatch == null);
}
}
else
{
RealPoint posOnTable = Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition));
lblX.Text = posOnTable.X.ToString("0");
lblY.Text = posOnTable.Y.ToString("0");
bool hoverElement = false;
foreach (GameElement element in GameBoard.Elements)
{
if (posOnTable.Distance(element.Position) < element.HoverRadius)
{
element.IsHover = true;
hoverElement = true;
}
else
element.IsHover = false;
}
if (hoverElement)
this.Cursor = Cursors.Hand;
else
this.Cursor = Cursors.Arrow;
//System.Threading.Tasks.Task.Factory.StartNew(() => ChercheTraj(new Position(Robots.GrosRobot.Position)));
}
semMove.Release();
}
public void ThreadAction()
{
if (!move.Execute())
{
#if DEBUG
MessageBox.Show("Echec");
#endif
}
move = null;
}
Movement move;
private void btnReset_Click(object sender, EventArgs e)
{
// Todo
GameBoard.Score = 0;
}
private void CheckElementClick()
{
foreach (GameElement element in GameBoard.Elements)
if (element.IsHover)
ThreadManager.CreateThread(link =>
{
link.Name = "Action " + element.ToString();
element.ClickAction();
}).StartThread();
}
//MouseEventArgs ev;
private void btnGo_Click(object sender, EventArgs e)
{
if (Config.CurrentConfig.IsMiniRobot)
GameBoard.Strategy = new StrategyMini();
else
GameBoard.Strategy = new StrategyMatch();
GameBoard.Strategy.ExecuteMatch();
}
private void PanelTable_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
}
}
public void StartDisplay()
{
btnAffichage_Click(null, null);
}
private int pSelected = -1;
private void pictureBoxTable_MouseDown(object sender, MouseEventArgs e)
{
Dessinateur.positionDepart = Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition));
Dessinateur.MouseClicked = true;
if (Dessinateur.modeCourant == Dessinateur.MouseMode.TrajectoirePolaire)
{
moveMouse = false;
Point pClic = e.Location;
for (int i = 0; i < pointsPolaires.Count; i++)
{
Point pPolaire = Dessinateur.Scale.RealToScreenPosition(pointsPolaires[i]);
if (new RealPoint(pClic).Distance(new RealPoint(pPolaire)) <= 3)
{
moveMouse = true;
pSelected = i;
}
}
}
}
List<RealPoint> trajectoirePolaire;
List<RealPoint> pointsPolaires;
private void pictureBoxTable_MouseUp(object sender, MouseEventArgs e)
{
if (pSelected != -1)
pSelected = -1;
if (Dessinateur.modeCourant == Dessinateur.MouseMode.PositionCentre || Dessinateur.modeCourant == Dessinateur.MouseMode.TeleportCentre)
{
Direction traj = Maths.GetDirection(Dessinateur.positionDepart, Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition)));
positionArrivee = new Position(new AnglePosition(-traj.angle), Dessinateur.positionDepart);
if (Dessinateur.modeCourant == Dessinateur.MouseMode.PositionCentre)
ThreadManager.CreateThread(link => ThreadTrajectory(link)).StartThread();
else
Robots.MainRobot.SetAsservOffset(positionArrivee);
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
else if (Dessinateur.modeCourant == Dessinateur.MouseMode.PositionFace || Dessinateur.modeCourant == Dessinateur.MouseMode.TeleportFace)
{
Point positionFin = pictureBoxTable.PointToClient(MousePosition);
Direction traj = Maths.GetDirection(Dessinateur.positionDepart, Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition)));
Point pointOrigine = Dessinateur.positionDepart;
Position departRecule = new Position(new AnglePosition(-traj.angle), pointOrigine);
departRecule.Move(-Robots.MainRobot.LenghtFront);
departRecule = new Position(new AnglePosition(-traj.angle), new RealPoint(departRecule.Coordinates.X, departRecule.Coordinates.Y));
positionArrivee = departRecule;
if (Dessinateur.modeCourant == Dessinateur.MouseMode.PositionFace)
ThreadManager.CreateThread(link => ThreadTrajectory(link)).StartThread();
else
Robots.MainRobot.SetAsservOffset(positionArrivee);
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
Dessinateur.MouseClicked = false;
}
private void btnAleatoire_Click(object sender, EventArgs e)
{
GameBoard.Strategy = new StrategyRandomMoves();
GameBoard.Strategy.ExecuteMatch();
}
Position positionArrivee;
private void ThreadTrajectory(ThreadLink link)
{
link.RegisterName();
this.InvokeAuto(() => btnPathRPCentre.Enabled = false);
Robots.MainRobot.GoToPosition(new Position(positionArrivee.Angle.InDegrees, positionArrivee.Coordinates));
this.InvokeAuto(() => btnPathRPCentre.Enabled = true);
}
#region GroupBox Déplacements
private void btnPathRPCentre_Click(object sender, EventArgs e)
{
Dessinateur.positionDepart = null;
if (Dessinateur.modeCourant != Dessinateur.MouseMode.PositionCentre)
Dessinateur.modeCourant = Dessinateur.MouseMode.PositionCentre;
else
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
private void btnPathRPFace_Click(object sender, EventArgs e)
{
Dessinateur.positionDepart = null;
if (Dessinateur.modeCourant != Dessinateur.MouseMode.PositionFace)
Dessinateur.modeCourant = Dessinateur.MouseMode.PositionFace;
else
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
private void btnTeleportRPCentre_Click(object sender, EventArgs e)
{
Dessinateur.positionDepart = null;
if (Dessinateur.modeCourant != Dessinateur.MouseMode.TeleportCentre)
Dessinateur.modeCourant = Dessinateur.MouseMode.TeleportCentre;
else
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
private void btnTeleportRPFace_Click(object sender, EventArgs e)
{
Dessinateur.positionDepart = null;
if (Dessinateur.modeCourant != Dessinateur.MouseMode.TeleportFace)
Dessinateur.modeCourant = Dessinateur.MouseMode.TeleportFace;
else
Dessinateur.modeCourant = Dessinateur.MouseMode.None;
}
#endregion
private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
String ligne = (String)checkedListBox.Items[e.Index];
if (ligne == "Plateau")
Dessinateur.AfficheTable = e.NewValue == CheckState.Checked;
if (ligne == "Plateau perspective")
Dessinateur.AfficheTableRelief = e.NewValue == CheckState.Checked;
if (ligne == "Obstacles")
Dessinateur.AfficheObstacles = e.NewValue == CheckState.Checked;
if (ligne == "Elements de jeu")
Dessinateur.AfficheElementsJeu = e.NewValue == CheckState.Checked;
if (ligne == "Graph (noeuds)")
Dessinateur.AfficheGraph = e.NewValue == CheckState.Checked;
if (ligne == "Graph (arcs)")
Dessinateur.AfficheGraphArretes = e.NewValue == CheckState.Checked;
if (ligne == "Coûts mouvements")
Dessinateur.AfficheCoutsMouvements = e.NewValue == CheckState.Checked;
if (ligne == "Calcul path finding")
Config.CurrentConfig.AfficheDetailTraj = e.NewValue == CheckState.Checked ? 30 : 0;
if (ligne == "Historique trajectoire")
Dessinateur.AfficheHistoriqueCoordonnees = e.NewValue == CheckState.Checked;
}
private void btnZoneDepart_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link => GoToDepart(link)).StartThread();
}
public void GoToDepart(ThreadLink link)
{
link.RegisterName();
Robots.MainRobot.GoToPosition(Recalibration.StartPosition);
}
private void btnStratNul_Click(object sender, EventArgs e)
{
GameBoard.Strategy = new StrategyEmpty();
GameBoard.Strategy.ExecuteMatch();
}
private void btnStratTest_Click(object sender, EventArgs e)
{
GameBoard.Strategy = new StrategyRoundTrip();
GameBoard.Strategy.ExecuteMatch();
}
private void btnTestAsser_Click(object sender, EventArgs e)
{
ThreadLink th = ThreadManager.CreateThread(link => TestAsser(link));
th.StartThread();
}
private void TestAsser(ThreadLink link)
{
link.RegisterName();
Robots.MainRobot.MoveForward(2000);
Robots.MainRobot.PivotRight(270);
Robots.MainRobot.MoveForward(200);
Robots.MainRobot.PivotRight(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.PivotRight(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.PivotRight(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.MoveBackward(1000);
Robots.MainRobot.PivotLeft(90);
Robots.MainRobot.MoveBackward(500);
Robots.MainRobot.PivotLeft(10);
Robots.MainRobot.MoveForward(1000);
Robots.MainRobot.PivotLeft(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.PivotLeft(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.PivotLeft(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.PivotLeft(10);
Robots.MainRobot.MoveForward(100);
Robots.MainRobot.GoToPosition(Recalibration.StartPosition);
Robots.MainRobot.MoveBackward(300);
}
private void btnTrajCreer_Click(object sender, EventArgs e)
{
Dessinateur.modeCourant = Dessinateur.MouseMode.TrajectoirePolaire;
pSelected = -1;
pointsPolaires = new List<RealPoint>();
}
private void btnTrajLancer_Click(object sender, EventArgs e)
{
Robots.MainRobot.PolarTrajectory(SensAR.Avant, trajectoirePolaire, false);
}
bool moveMouse = false;
private void pictureBoxTable_Click(object sender, EventArgs e)
{
if (boxSourisObstacle.Checked)
boxSourisObstacle.Checked = false;
else if (!moveMouse && Dessinateur.modeCourant == Dessinateur.MouseMode.TrajectoirePolaire)
{
RealPoint point = Dessinateur.Scale.ScreenToRealPosition(pictureBoxTable.PointToClient(MousePosition));
//if (pointsPolaires.Count >= 2 && pointsPolaires.Count < 4)
// pointsPolaires.Insert(pointsPolaires.Count - 1, point);
//else if (pointsPolaires.Count < 4)
pointsPolaires.Add(point);
if (pointsPolaires.Count > 1)
{
trajectoirePolaire = BezierCurve.GetPoints(pointsPolaires, (int)(numNbPoints.Value));//((int)pointsPolaires[0].Distance(pointsPolaires[pointsPolaires.Count - 1])) / 50);
Dessinateur.TrajectoirePolaire = trajectoirePolaire;
Dessinateur.PointsPolaire = pointsPolaires;
}
}
else
{
CheckElementClick();
}
}
private void ThreadMouvement(Object o)
{
Movement m = (Movement)o;
m.Execute();
}
private void ThreadEnchainement(Object o)
{
Strategy m = (Strategy)o;
GameBoard.Strategy = m;
GameBoard.Strategy.ExecuteMatch();
}
private void btnTestScore_Click(object sender, EventArgs e)
{
GameBoard.Score++;
}
private void btnRestartRecal_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link =>
{
link.Name = "GoToCalibration";
if (Recalibration.GoToCalibration()) Recalibration.Calibration();
}).StartThread();
}
private void btnColorLeft_Click(object sender, EventArgs e)
{
GameBoard.MyColor = GameBoard.ColorLeftBlue;
}
private void btnColorRight_Click(object sender, EventArgs e)
{
GameBoard.MyColor = GameBoard.ColorRightYellow;
}
private void btnCalib_Click(object sender, EventArgs e)
{
ThreadManager.CreateThread(link =>
{
link.Name = "Calibration";
Recalibration.Calibration();
}).StartThread();
}
}
}
<file_sep>/GoBot/GoBot/Movements/MovementGreenDropoff.cs
using Geometry.Shapes;
using GoBot.Actionneurs;
using GoBot.BoardContext;
using GoBot.GameElements;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.Movements
{
class MovementGreenDropoff : Movement
{
private RandomDropOff _randomDropOff;
public MovementGreenDropoff(RandomDropOff dropoff)
{
_randomDropOff = dropoff;
Positions.Add(new Geometry.Position(90, new RealPoint(_randomDropOff.Position.X + (_randomDropOff.Position.X < 1500 ? 50 : -50), 730)));
}
public override bool CanExecute => !_randomDropOff.HasLoadOnTop && Actionneur.Lifter.Loaded;
public override int Score
{
get
{
if (!_randomDropOff.HasLoadOnBottom)
return 8;
else
return 22 - 8;
}
}
public override double Value => 2;
public override GameElement Element => _randomDropOff;
public override Robot Robot => Robots.MainRobot;
public override Color Color => _randomDropOff.Owner;
protected override void MovementBegin()
{
}
protected override bool MovementCore()
{
Actionneur.Lifter.DoSequenceDropOff();
_randomDropOff.SetLoadTop(Actionneur.Lifter.Load);
Actionneur.Lifter.Load = null;
GameBoard.AddObstacle(new Segment(new RealPoint(_randomDropOff.Position.X - 200, 525), new RealPoint(_randomDropOff.Position.X + 200, 525)));
return true;
}
protected override void MovementEnd()
{
}
}
}
<file_sep>/GoBot/GoBot/PathFinding/PathFinder.cs
using AStarFolder;
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using GoBot.BoardContext;
namespace GoBot.PathFinding
{
static class PathFinder
{
private static ThreadLink _linkResetRadius;
public static List<Node> CheminEnCoursNoeuds { get; private set; }
public static List<Node> CheminEnCoursNoeudsSimplifyed { get; private set; }
public static List<Arc> CheminEnCoursArcs { get; private set; }
public static Segment CheminTest { get; private set; }
public static IShape ObstacleTeste { get; private set; }
public static IShape ObstacleProbleme { get; private set; }
public static List<RealPoint> PointsTrouves { get; private set; }
private static Trajectory DirectTrajectory(IEnumerable<IShape> obstacles, Position startPos, Position endPos, double securityRadius)
{
Segment directLine = new Segment(new RealPoint(startPos.Coordinates), new RealPoint(endPos.Coordinates));
Trajectory output = null;
if (obstacles.All(o => o.Distance(directLine) > securityRadius))
{
output = new Trajectory();
output.StartAngle = startPos.Angle;
output.AddPoint(startPos.Coordinates);
output.AddPoint(endPos.Coordinates);
output.EndAngle = endPos.Angle;
}
return output;
}
public static Trajectory ChercheTrajectoire(Graph graph, IEnumerable<IShape> obstacles, IEnumerable<IShape> opponents, Position startPos, Position endPos, double rayonSecurite, double distanceSecuriteCote)
{
Stopwatch sw = Stopwatch.StartNew();
bool pathFound = false;
Trajectory output = DirectTrajectory(obstacles.Concat(opponents), startPos, endPos, rayonSecurite);
if (output != null)
pathFound = true;
else
{
_linkResetRadius = null;
double distance;
bool raccordable = false;
output = new Trajectory();
output.StartAngle = startPos.Angle;
output.EndAngle = endPos.Angle;
PointsTrouves = new List<RealPoint>();
PointsTrouves.Add(new RealPoint(startPos.Coordinates));
output.AddPoint(new RealPoint(startPos.Coordinates));
lock (graph)
{
Console.WriteLine("Cherche trajectoire début");
int nbPointsDepart = 0;
int nbPointsArrivee = 0;
Node debutNode = null, finNode = null;
Node nodeProche = graph.ClosestNode(startPos.Coordinates, out distance);
if (distance != 0)
{
debutNode = new Node(startPos.Coordinates);
nbPointsDepart = graph.AddNode(debutNode, obstacles, rayonSecurite);
}
else
{
debutNode = nodeProche;
nbPointsDepart = debutNode.OutgoingArcs.Count;
}
//TODO2018 phase d'approche finale pourrie, l'angle final peut se faire à la fin au lieu de à la fin du path finding avant l'approche finale
if (nbPointsDepart == 0)
{
// On ne peut pas partir de là où on est
Position positionTestee = new Position(startPos);
bool franchissable = true;
// Boucle jusqu'à trouver un point qui se connecte au graph jusqu'à 1m devant
int i;
for (i = 0; i < 100 && !raccordable; i += 1)
{
positionTestee.Move(10);
debutNode = new Node(positionTestee.Coordinates);
raccordable = graph.Raccordable(debutNode, obstacles, rayonSecurite);
}
// Le point à i*10 mm devant nous est reliable au graph, on cherche à l'atteindre
if (raccordable)
{
Segment segmentTest = new Segment(new RealPoint(positionTestee.Coordinates), new RealPoint(startPos.Coordinates));
// Test des obstacles
foreach (IShape obstacle in obstacles)
{
if (obstacle.Distance(segmentTest) < distanceSecuriteCote)
{
franchissable = false;
// Si l'obstacle génant est un adversaire, on diminue petit à petit son rayon pour pouvoir s'échapper au bout d'un moment
if (opponents.Contains(obstacle) && GameBoard.OpponentRadius > 50)
{
Robots.MainRobot.Historique.Log("Adversaire au contact, impossible de s'enfuir, réduction du périmètre adverse", TypeLog.PathFinding);
GameBoard.OpponentRadius -= 10;
_linkResetRadius?.Cancel();
}
}
}
// Si le semgent entre notre position et le graph relié au graph est parcourable on y va !
if (franchissable)
{
PointsTrouves.Add(new RealPoint(positionTestee.Coordinates));
output.AddPoint(new RealPoint(positionTestee.Coordinates));
debutNode = new Node(positionTestee.Coordinates);
nbPointsDepart = graph.AddNode(debutNode, obstacles, rayonSecurite);
}
}
else
franchissable = false;
// Si toujours pas, on teste en marche arrière
if (!franchissable)
{
franchissable = true;
raccordable = false;
nbPointsDepart = 0;
positionTestee = new Position(startPos);
for (i = 0; i > -100 && !raccordable; i--)
{
positionTestee.Move(-10);
debutNode = new Node(positionTestee.Coordinates);
raccordable = graph.Raccordable(debutNode, obstacles, rayonSecurite);
}
// Le point à i*10 mm derrière nous est reliable au graph, on cherche à l'atteindre
if (raccordable)
{
Segment segmentTest = new Segment(new RealPoint(positionTestee.Coordinates), new RealPoint(startPos.Coordinates));
// Test des obstacles
foreach (IShape obstacle in obstacles)
{
if (obstacle.Distance(segmentTest) < distanceSecuriteCote)
{
franchissable = false;
// Si l'obstacle génant est un adversaire, on diminue petit à petit son rayon pour pouvoir s'échapper au bout d'un moment
if (opponents.Contains(obstacle) && GameBoard.OpponentRadius > 50)
{
Robots.MainRobot.Historique.Log("Adversaire au contact, impossible de s'enfuir, réduction du périmètre adverse", TypeLog.PathFinding);
GameBoard.OpponentRadius -= 10;
_linkResetRadius?.Cancel();
}
}
}
// Si le semgent entre notre position et le graph relié au graph est parcourable on y va !
if (franchissable)
{
PointsTrouves.Add(new RealPoint(positionTestee.Coordinates));
output.AddPoint(new RealPoint(positionTestee.Coordinates));
debutNode = new Node(positionTestee.Coordinates);
nbPointsDepart = graph.AddNode(debutNode, obstacles, rayonSecurite);
}
}
}
}
if (nbPointsDepart > 0)
{
finNode = graph.ClosestNode(endPos.Coordinates, out distance);
if (distance != 0)
{
finNode = new Node(endPos.Coordinates);
nbPointsArrivee = graph.AddNode(finNode, obstacles, rayonSecurite);
}
else
{
nbPointsArrivee = 1;
}
if (nbPointsArrivee == 0)
{
Console.WriteLine("Blocage arrivée");
// On ne peut pas arriver là où on souhaite aller
// On teste si on peut faire une approche en ligne
// teta ne doit pas être nul sinon c'est qu'on ne maitrise pas l'angle d'arrivée et on ne connait pas l'angle d'approche
Position positionTestee = new Position(endPos);
bool franchissable = true;
raccordable = false;
// Boucle jusqu'à trouver un point qui se connecte au graph jusqu'à 1m devant
int i;
for (i = 0; i < 100 && !raccordable; i++)
{
positionTestee.Move(10);
raccordable = graph.Raccordable(new Node(positionTestee.Coordinates), obstacles, rayonSecurite);
}
// Le point à i*10 mm devant nous est reliable au graph, on cherche à l'atteindre
if (raccordable)
{
Segment segmentTest = new Segment(new RealPoint(positionTestee.Coordinates), new RealPoint(endPos.Coordinates));
// Test des obstacles
foreach (IShape obstacle in obstacles)
{
if (obstacle.Distance(segmentTest) < distanceSecuriteCote)
franchissable = false;
}
}
else
franchissable = false;
// Si toujours pas, on teste en marche arrière
if (!franchissable)
{
positionTestee = new Position(endPos);
nbPointsArrivee = 0;
for (i = 0; i > -100 && !raccordable; i--)
{
positionTestee.Move(-10);
raccordable = graph.Raccordable(new Node(positionTestee.Coordinates), obstacles, rayonSecurite);
}
if (raccordable)
{
franchissable = true;
Segment segmentTest = new Segment(new RealPoint(positionTestee.Coordinates), new RealPoint(endPos.Coordinates));
// Test des obstacles
foreach (IShape obstacle in obstacles)
{
if (obstacle.Distance(segmentTest) < distanceSecuriteCote)
franchissable = false;
}
}
}
// Si le semgent entre notre position et le node relié au graph est parcourable on y va !
if (franchissable)
{
finNode = new Node(positionTestee.Coordinates);
nbPointsArrivee = graph.AddNode(finNode, obstacles, rayonSecurite);
}
}
}
if (nbPointsDepart > 0 && nbPointsArrivee > 0)
{
// Teste s'il est possible d'aller directement à la fin sans passer par le graph
bool toutDroit = true;
Segment segment = new Segment(debutNode.Position, finNode.Position);
foreach (IShape forme in obstacles)
{
if (segment.Distance(forme) < rayonSecurite)
{
toutDroit = false;
break;
}
}
if (toutDroit)
{
Robots.MainRobot.Historique.Log("Chemin trouvé : ligne droite", TypeLog.PathFinding);
pathFound = true;
PointsTrouves.Add(finNode.Position);
output.AddPoint(finNode.Position);
if (endPos.Coordinates.Distance(finNode.Position) > 1)
{
PointsTrouves.Add(new RealPoint(endPos.Coordinates));
output.AddPoint(new RealPoint(endPos.Coordinates));
}
}
// Sinon on passe par le graph
else
{
AStar aStar = new AStar(graph);
aStar.DijkstraHeuristicBalance = 0;
//Console.WriteLine("Avant pathFinding : " + (DateTime.Now - debut).TotalMilliseconds + "ms");
if (aStar.SearchPath(debutNode, finNode))
{
//Console.WriteLine("PathFinding trouvé : " + (DateTime.Now - debut).TotalMilliseconds + "ms");
List<Node> nodes = aStar.PathByNodes.ToList<Node>();
Robots.MainRobot.Historique.Log("Chemin trouvé : " + (nodes.Count - 2) + " noeud(s) intermédiaire(s)", TypeLog.PathFinding);
CheminEnCoursNoeuds = new List<Node>();
CheminEnCoursArcs = new List<Arc>();
//Console.WriteLine("Début simplification : " + (DateTime.Now - debut).TotalMilliseconds + "ms");
// Simplification du chemin
// On part du début et on essaie d'aller au point du plus éloigné au moins éloigné en testant si le passage est possible
// Si c'est possible on zappe tous les points entre les deux
for (int iNodeDepart = 0; iNodeDepart < nodes.Count - 1; iNodeDepart++)
{
if (iNodeDepart != 0)
{
PointsTrouves.Add(nodes[iNodeDepart].Position);
output.AddPoint(nodes[iNodeDepart].Position);
}
CheminEnCoursNoeuds.Add(nodes[iNodeDepart]);
bool raccourciPossible = true;
for (int iNodeArrivee = nodes.Count - 1; iNodeArrivee > iNodeDepart; iNodeArrivee--)
{
raccourciPossible = true;
Segment racourci = new Segment(nodes[iNodeDepart].Position, nodes[iNodeArrivee].Position);
//Arc arcRacourci = new Arc(nodes[iNodeDepart], nodes[iNodeArrivee]);
CheminTest = racourci;
//arcRacourci.Passable = false;
for (int i = obstacles.Count() - 1; i >= 4; i--) // > 4 pour ne pas tester les bordures
{
IShape forme = obstacles.ElementAt(i);
ObstacleTeste = forme;
ObstacleProbleme = null;
if (racourci.Distance(forme) < rayonSecurite)
{
ObstacleProbleme = forme;
raccourciPossible = false;
break;
}
//else if(Config.CurrentConfig.AfficheDetailTraj > 0)
// Thread.Sleep(Config.CurrentConfig.AfficheDetailTraj);
}
if (Config.CurrentConfig.AfficheDetailTraj > 0)
Thread.Sleep(Config.CurrentConfig.AfficheDetailTraj);
ObstacleTeste = null;
if (raccourciPossible)
{
//CheminEnCoursArcs.Add(arcRacourci);
iNodeDepart = iNodeArrivee - 1;
break;
}
}
CheminTest = null;
if (!raccourciPossible)
{
//Arc arc = new Arc(nodes[iNodeDepart], nodes[iNodeDepart + 1]);
//CheminEnCoursArcs.Add(arc);
}
}
CheminEnCoursNoeuds.Add(nodes[nodes.Count - 1]);
PointsTrouves.Add(nodes[nodes.Count - 1].Position);
output.AddPoint(nodes[nodes.Count - 1].Position);
Robots.MainRobot.Historique.Log("Chemin optimisé : " + (CheminEnCoursNoeuds.Count - 2) + " noeud(s) intermédiaire(s)", TypeLog.PathFinding);
pathFound = true;
if (endPos.Coordinates.Distance(finNode.Position) > 1)
{
PointsTrouves.Add(new RealPoint(endPos.Coordinates));
output.AddPoint(new RealPoint(endPos.Coordinates));
}
}
else
{
CheminEnCoursNoeuds = null;
CheminEnCoursArcs = null;
pathFound = false;
}
}
}
graph.CleanNodesArcsAdd();
}
}
Dessinateur.CurrentTrack = null;
//CheminEnCoursNoeuds = null;
Console.WriteLine("Cherche trajectoire fin : " + sw.ElapsedMilliseconds + "ms");
PointsTrouves = null;
ObstacleProbleme = null;
ObstacleTeste = null;
//Console.WriteLine("PathFinding en " + (DateTime.Now - debut).TotalMilliseconds + " ms");
if (!pathFound)
{
Robots.MainRobot.Historique.Log("Chemin non trouvé", TypeLog.PathFinding);
return null;
}
else
{
if (GameBoard.OpponentRadius < GameBoard.OpponentRadiusInitial)
{
_linkResetRadius = ThreadManager.CreateThread(link => ResetOpponentRadiusLoop());
_linkResetRadius.StartThread();
}
if (output.Lines.Count > 1)
{
output = ReduceLines(output, obstacles.Concat(opponents), rayonSecurite);
}
return output;
}
}
private static void ResetOpponentRadiusLoop()
{
_linkResetRadius.RegisterName();
Thread.Sleep(1000);
while (_linkResetRadius != null && !_linkResetRadius.Cancelled && GameBoard.OpponentRadius < GameBoard.OpponentRadiusInitial)
{
GameBoard.OpponentRadius++;
Thread.Sleep(50);
}
}
private static Trajectory ReduceLines(Trajectory traj, IEnumerable<IShape> obstacles, double securityRadius)
{
Trajectory output = traj;
TimeSpan currentDuration = output.GetDuration(Robots.MainRobot);
Console.WriteLine("Avant : " + currentDuration.ToString());
int iSeg = 1;
while (iSeg < output.Lines.Count - 1)
{
Trajectory tested = new Trajectory(output);
tested.RemoveLine(iSeg);
iSeg++;
CheminEnCoursNoeudsSimplifyed = tested.Points.Select(o => new Node(o)).ToList();
ObstacleProbleme = obstacles.FirstOrDefault(o => tested.Lines.Any(s => s.Distance(o) < securityRadius));
Thread.Sleep(Config.CurrentConfig.AfficheDetailTraj * 15);
if (ObstacleProbleme == null)
{
TimeSpan testedDuration = tested.GetDuration(Robots.MainRobot);
if (testedDuration < currentDuration)
{
output = tested;
if (Config.CurrentConfig.AfficheDetailTraj > 0)
{
CheminEnCoursNoeuds = CheminEnCoursNoeudsSimplifyed;
CheminEnCoursNoeudsSimplifyed = null;
Thread.Sleep(Config.CurrentConfig.AfficheDetailTraj * 15);
}
currentDuration = testedDuration;
iSeg--;
}
}
}
CheminEnCoursNoeuds = null;
CheminEnCoursNoeudsSimplifyed = null;
Console.WriteLine("Après : " + currentDuration.ToString());
return output;
}
}
}
<file_sep>/GoBot/GoBot/Devices/Hokuyo/Hokuyo.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using GoBot.BoardContext;
namespace GoBot.Devices
{
public class Hokuyo : Lidar
{
#region Attributs
private LidarID _id;
private SerialPort _port;
protected String _frameMeasure;
protected String _frameDetails;
protected String _frameSpecif;
protected String _frameHighSentitivity, _frameLowSentitivity;
protected String _romVendor, _romProduct, _romFirmware, _romProtocol, _romSerialNumber, _romModel;
protected int _romMinDistance, _romMaxDistance, _romDivisions, _romFirstMeasure, _romLastMeasure, _romTotalMeasures, _romMotorSpeed;
protected int _usefullMeasures;
protected AngleDelta _scanRange, _resolution;
protected int _distanceMinLimit, _distanceMaxLimit;
protected int _keepFrom, _keepTo;
protected bool _invertRotation;
private Semaphore _lock;
private ThreadLink _linkMeasures;
private List<RealPoint> _lastMeasure;
protected bool _connected;
#endregion
#region Propriétés
public LidarID ID { get { return _id; } }
public String Model { get { return _romModel; } }
public AngleDelta ScanRange { get { return _scanRange; } }
public override AngleDelta DeadAngle { get { return new AngleDelta(360 - _scanRange); } }
public override bool Activated => _linkMeasures != null && _linkMeasures.Running;
public int PointsCount { get { return _romTotalMeasures; } }
public List<RealPoint> LastMeasure { get { return _lastMeasure; } }
public int DistanceMaxLimit { get { return _distanceMaxLimit; } set { _distanceMaxLimit = value; } }
public int KeepFrom
{
get { return _keepFrom; }
set
{
_lock.WaitOne();
_keepFrom = value;
_frameMeasure = "MS" + _keepFrom.ToString("0000") + _keepTo.ToString("0000") + "00001\n";
_lock.Release();
}
}
public int KeepTo
{
get { return _keepTo; }
set
{
_lock.WaitOne();
_keepTo = value;
_frameMeasure = "MS" + _keepFrom.ToString("0000") + _keepTo.ToString("0000") + "00001\n";
_lock.Release();
}
}
#endregion
#region Constructeurs
public Hokuyo(LidarID id)
{
_id = id;
_lock = new Semaphore(1, 1);
_distanceMaxLimit = 3999; // En dessous de 4000 parce que le protocole choisi seuille le maximum à 4000 niveau matos
_position = new Position();
_lastMeasure = null;
_frameDetails = "VV\n";
_frameSpecif = "PP\n";
_frameLowSentitivity = "HS0\n";
_frameHighSentitivity = "HS1\n";
_invertRotation = false;
}
public Hokuyo(LidarID id, String portCom) : this(id)
{
_port = new SerialPort(portCom, 115200);
_port.Open();
IdentifyModel();
}
#endregion
#region Fonctionnement externe
protected override bool StartLoop()
{
_linkMeasures = ThreadManager.CreateThread(link => DoMeasure());
_linkMeasures.Name = "Mesure Hokuyo " + _id.ToString();
_linkMeasures.StartInfiniteLoop(new TimeSpan(0, 0, 0, 0, 100));
return true;
}
protected override void StopLoop()
{
_linkMeasures.Cancel();
}
public override List<RealPoint> GetPoints()
{
return GetPoints(true);
}
public List<RealPoint> GetRawPoints()
{
return GetPoints(false);
}
#endregion
#region Fonctionnement interne
private List<RealPoint> GetPoints(bool useReference)
{
List<RealPoint> points = new List<RealPoint>();
_lock.WaitOne();
String reponse = GetMeasure();
try
{
if (reponse != "")
{
List<int> mesures = DecodeMessage(reponse);
points = ValuesToPositions(mesures, false, _distanceMinLimit, _distanceMaxLimit, (useReference ? _position : new Position())) ;
}
}
catch (Exception) { }
_lock.Release();
return points;
}
private void IdentifyModel()
{
SendMessage(_frameDetails);
String response = GetResponse();
List<String> details = response.Split(new char[] { '\n', ':', ';' }).ToList();
_romVendor = details[3];
_romProduct = details[6];
_romFirmware = details[9];
_romProtocol = details[12];
_romSerialNumber = details[15];
SendMessage(_frameSpecif);
response = GetResponse();
details = response.Split(new char[] { '\n', ':', ';' }).ToList();
_romModel = details[3];
_romMinDistance = int.Parse(details[6]);
_romMaxDistance = int.Parse(details[9]);
_romDivisions = int.Parse(details[12]);
_romFirstMeasure = int.Parse(details[15]);
_romLastMeasure = int.Parse(details[18]);
_romTotalMeasures = int.Parse(details[21]) * 2 + 1;
_romMotorSpeed = int.Parse(details[24]);
_usefullMeasures = _romTotalMeasures - (_romTotalMeasures - (_romLastMeasure + 1)) - _romFirstMeasure;
_resolution = 360.0 / _romDivisions;
_scanRange = _resolution * _usefullMeasures;
_keepFrom = _romFirstMeasure;
_keepTo = _romFirstMeasure + _usefullMeasures - 1;
_frameMeasure = "MS" + _keepFrom.ToString("0000") + _keepTo.ToString("0000") + "00001\n";
}
private String GetMeasure(int timeout = 500)
{
SendMessage(_frameMeasure);
return GetResponse(timeout);
}
protected virtual void SendMessage(String msg)
{
_port.Write(msg);
}
protected virtual String GetResponse(int timeout = 500)
{
Stopwatch chrono = Stopwatch.StartNew();
String reponse = "";
do
{
reponse += _port.ReadExisting();
} while (!reponse.Contains("\n\n") && chrono.ElapsedMilliseconds < timeout);
chrono.Stop();
if (chrono.ElapsedMilliseconds >= timeout)
return "";
else
return reponse;
}
private void DoMeasure()
{
try
{
_lastMeasure = GetPoints();
if (!_linkMeasures.Cancelled) OnNewMeasure(_lastMeasure);
}
catch(Exception ex)
{
Debug.Print("ERREUR LIDAR : " + ex.Message);
}
}
private List<RealPoint> ValuesToPositions(List<int> measures, bool limitOnTable, int minDistance, int maxDistance, Position refPosition)
{
List<RealPoint> positions = new List<RealPoint>();
for (int i = 0; i < measures.Count; i++)
{
AnglePosition angle = _resolution * (i + _keepFrom);
if (measures[i] > minDistance && (measures[i] < maxDistance || maxDistance == -1))
{
AnglePosition anglePoint = new AnglePosition(angle.InPositiveRadians - refPosition.Angle.InPositiveRadians - ScanRange.InRadians / 2 - Math.PI / 2, AngleType.Radian);
RealPoint pos = new RealPoint(refPosition.Coordinates.X - anglePoint.Sin * measures[i], refPosition.Coordinates.Y - anglePoint.Cos * measures[i]);
int marge = 20; // Marge en mm de distance de detection à l'exterieur de la table (pour ne pas jeter les mesures de la bordure qui ne collent pas parfaitement)
if (!limitOnTable || (pos.X > -marge && pos.X < GameBoard.Width + marge && pos.Y > -marge && pos.Y < GameBoard.Height + marge))
positions.Add(pos);
}
}
return positions;
}
private List<int> DecodeMessage(String message)
{
List<int> values = new List<int>();
String[] tab = message.Split(new char[] { '\n' });
Boolean started = false;
for (int i = 0; i < tab.Length - 2; i++)
{
if (tab[i].Length > 64) started = true;
if (started)
{
for (int j = 0; j < tab[i].Length - 1; j += 2)
{
int val = DecodeValue(tab[i].Substring(j, 2));
values.Add(val);
}
}
}
if (values.Count >= _romTotalMeasures)
values = values.GetRange(_keepFrom, _keepTo - _keepFrom);
if (_invertRotation)
values.Reverse();
return values;
}
private int DecodeValue(String data)
{
int value = 0;
for (int i = 0; i < data.Length; ++i)
{
value <<= 6;
value &= ~0x3f;
value |= data[i] - 0x30;
}
return value;
}
#endregion
}
}
<file_sep>/GoBot/GoBot/Devices/CAN/CanServo.cs
using GoBot.Communications;
using GoBot.Communications.CAN;
using GoBot.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace GoBot.Devices.CAN
{
/// <summary>
/// Représente un servomoteur piloté par liaison CAN
/// </summary>
public class CanServo
{
private ServomoteurID _id;
private int _position;
private int _positionMin, _positionMax;
private int _acceleration;
private int _speedMax;
private int _torqueCurrent, _torqueMax;
private bool _enableAutoCut;
private Semaphore _lockResponse;
private iCanSpeakable _communication;
private ThreadLink _nextDisable;
public delegate void TorqueAlertDelegate();
public event TorqueAlertDelegate TorqueAlert;
public CanServo(ServomoteurID id, iCanSpeakable communication)
{
_id = (ServomoteurID)((int)id % 100);
_communication = communication;
_lockResponse = new Semaphore(0, int.MaxValue);
_enableAutoCut = false;
_nextDisable = null;
}
public ServomoteurID ID { get => _id; }
public int LastPosition { get => _position; }
public int LastPositionMin { get => _positionMin; }
public int LastPositionMax { get => _positionMax; }
public int LastSpeedMax { get => _speedMax; }
public int LastTorqueCurrent { get => _torqueCurrent; }
public int LastTorqueMax { get => _torqueMax; }
public int LastAcceleration { get => _acceleration; }
public bool AutoCut { get => _enableAutoCut; set => _enableAutoCut = value; }
public int ReadPosition()
{
_communication.SendFrame(CanFrameFactory.BuildGetPosition(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _position : -1;
}
public int ReadPositionMax()
{
_communication.SendFrame(CanFrameFactory.BuildGetPositionMax(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _positionMax : -1;
}
public int ReadPositionMin()
{
_communication.SendFrame(CanFrameFactory.BuildGetPositionMin(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _positionMin : -1;
}
public int ReadSpeedMax()
{
_communication.SendFrame(CanFrameFactory.BuildGetSpeedMax(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _speedMax : -1;
}
public int ReadAcceleration()
{
_communication.SendFrame(CanFrameFactory.BuildGetAcceleration(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _acceleration : -1;
}
public int ReadTorqueCurrent()
{
_communication.SendFrame(CanFrameFactory.BuildGetTorqueCurrent(_id));
bool ok = _lockResponse.WaitOne(200);
Debug.Print(_torqueCurrent.ToString());
return ok ? _torqueCurrent : -1;
}
public int ReadTorqueMax()
{
_communication.SendFrame(CanFrameFactory.BuildGetTorqueMax(_id));
bool ok = _lockResponse.WaitOne(200);
return ok ? _torqueMax : -1;
}
public void SearchMax()
{
int initial = ReadPosition() / 100 * 100;
int max = initial;
int tempo = 500;
int targetTorque = ReadTorqueMax();
SetPositionMax(60000);
while (ReadTorqueCurrent() < targetTorque)
{
max += 500;
SetPosition(max);
Thread.Sleep(tempo);
}
max -= 500;
SetPosition(max);
Thread.Sleep(tempo);
while (ReadTorqueCurrent() < targetTorque)
{
max += 100;
SetPosition(max);
Thread.Sleep(tempo);
}
max -= 100;
SetPositionMax(max);
}
public void SearchMin()
{
int initial = ReadPosition() / 100 * 100; ;
int min = initial;
int tempo = 500;
int targetTorque = ReadTorqueMax();
SetPositionMin(0);
while (ReadTorqueCurrent() < targetTorque)
{
min -= 500;
SetPosition(min);
Thread.Sleep(tempo);
}
min += 500;
SetPosition(min);
Thread.Sleep(tempo);
while (ReadTorqueCurrent() < targetTorque)
{
min -= 100;
SetPosition(min);
Thread.Sleep(tempo);
}
min += 100;
SetPositionMin(min);
SetPosition(initial);
}
public void SetAcceleration(int acceleration)
{
_communication.SendFrame(CanFrameFactory.BuildSetAcceleration(_id, acceleration));
_acceleration = acceleration;
}
public void SetPosition(int position)
{
CancelDisable();
_communication.SendFrame(CanFrameFactory.BuildSetPosition(_id, position));
}
public void SetPositionMax(int positionMax)
{
_communication.SendFrame(CanFrameFactory.BuildSetPositionMax(_id, positionMax));
_positionMax = positionMax;
}
public void SetPositionMin(int positionMin)
{
_communication.SendFrame(CanFrameFactory.BuildSetPositionMin(_id, positionMin));
_positionMin = positionMin;
}
public void SetSpeedMax(int speedMax)
{
_communication.SendFrame(CanFrameFactory.BuildSetSpeedMax(_id, speedMax));
_speedMax = speedMax;
}
public void SetTorqueMax(int torqueMax)
{
_communication.SendFrame(CanFrameFactory.BuildSetTorqueMax(_id, torqueMax));
_torqueMax = torqueMax;
}
public void SetTrajectory(int position, int speed, int accel)
{
_communication.SendFrame(CanFrameFactory.BuildSetTrajectory(_id, position, speed, accel));
}
public void DisableOutput(int delayMs = 0)
{
if (delayMs > 0)
{
CancelDisable();
ThreadManager.CreateThread(link =>
{
_nextDisable = link;
if (!link.Cancelled)
_communication.SendFrame(CanFrameFactory.BuildDisableOutput(_id));
}).StartDelayedThread(delayMs);
}
else
{
_communication.SendFrame(CanFrameFactory.BuildDisableOutput(_id));
}
}
public void FrameReceived(Frame frame)
{
CanFrameFunction function = CanFrameFactory.ExtractFunction(frame);
try
{
switch (function)
{
case CanFrameFunction.PositionResponse:
_position = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.PositionMaxResponse:
_positionMax = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.PositionMinResponse:
_positionMin = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.SpeedMaxResponse:
_speedMax = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.TorqueCurrentResponse:
_torqueCurrent = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.TorqueMaxResponse:
_torqueMax = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.AccelerationResponse:
_acceleration = CanFrameFactory.ExtractValue(frame);
_lockResponse.Release();
break;
case CanFrameFunction.TorqueAlert:
//AllDevices.RecGoBot.Buzz(".-.");
AllDevices.Buzzer.Buzz(2000, 250);
if (_enableAutoCut)
_communication.SendFrame(CanFrameFactory.BuildDisableOutput(_id));
TorqueAlert?.Invoke();
break;
}
}
catch (Exception e)
{
Console.WriteLine(DateTime.Now.ToLongTimeString() + ":" + DateTime.Now.Millisecond.ToString("000") + " : Erreur servo CAN : " + e.Message);
}
}
private void CancelDisable()
{
if (_nextDisable != null)
{
_nextDisable.Cancel();
_nextDisable = null;
}
}
}
}
<file_sep>/GoBot/GoBot/Actionneurs/Positionables.cs
using System;
using System.Collections.Generic;
using System.Reflection;
namespace GoBot.Actionneurs
{
public abstract class Positionable
{
private int? _lastPosition;
public List<String> GetPositionsName()
{
PropertyInfo[] properties = this.GetType().GetProperties();
List<String> propertiesName = new List<string>();
foreach (PropertyInfo p in properties)
{
if (p.Name.StartsWith("Position"))
propertiesName.Add(p.Name);
}
return propertiesName;
}
public Dictionary<String, int> GetPositions()
{
PropertyInfo[] properties = this.GetType().GetProperties();
Dictionary<String, int> positions = new Dictionary<String, int>();
foreach (PropertyInfo p in properties)
{
if (p.Name.StartsWith("Position"))
positions.Add(p.Name, (int)p.GetValue(this, null));
}
return positions;
}
public int GetLastPosition()
{
return _lastPosition.HasValue ? _lastPosition.Value : (Minimum + Maximum) / 2;
}
public void SendPosition(int position)
{
_lastPosition = position;
SendPositionSpecific(position);
}
protected abstract void SendPositionSpecific(int position);
public override string ToString()
{
String typeName = this.GetType().Name;
String name = "";
foreach (char c in typeName)
{
char ch = c;
if (c <= 'Z' && c >= 'A')
name += " " + (char)(c + 32);
else
name += c;
}
name = typeName.Substring(0, 1) + name.Substring(2);
return name;
}
public int Minimum { get; set; }
public int Maximum { get; set; }
}
public abstract class PositionableServo : Positionable
{
public abstract ServomoteurID ID { get; }
protected override void SendPositionSpecific(int position)
{
Devices.AllDevices.CanServos[ID].SetPosition(position);
}
public void DisableTorque()
{
Devices.AllDevices.CanServos[ID].DisableOutput();
}
}
public abstract class PositionableMotorPosition : Positionable
{
public abstract MotorID ID { get; }
protected override void SendPositionSpecific(int position)
{
Robots.MainRobot.SetMotorAtPosition(ID, position, true);
}
public void Stop(StopMode mode)
{
Robots.MainRobot.SetMotorStop(ID, mode);
}
public void OriginInit()
{
Stop(StopMode.Abrupt);
Robots.MainRobot.SetMotorAtOrigin(ID, true);
Robots.MainRobot.SetMotorReset(ID);
Stop(StopMode.Abrupt);
Robots.MainRobot.SetMotorAtPosition(ID, 30);
}
}
public abstract class PositionableMotorSpeed : Positionable
{
public abstract MotorID ID { get; }
protected override void SendPositionSpecific(int position)
{
Robots.MainRobot.SetMotorSpeed(ID, position > 0 ? SensGD.Gauche : SensGD.Droite, Math.Abs(position));
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageLidar.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Geometry.Shapes;
using GoBot.Devices;
using GoBot.BoardContext;
namespace GoBot.IHM.Pages
{
public partial class PageLidar : UserControl
{
private Lidar _selectedLidar;
private List<RealPoint> _lastMeasure;
public PageLidar()
{
InitializeComponent();
_lastMeasure = null;
_selectedLidar = null;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
if (!picWorld.RectangleToScreen(picWorld.ClientRectangle).Contains(MousePosition))
{
base.OnMouseWheel(e);
}
else
{
if (e.Delta > 0)
trackZoom.SetValue(trackZoom.Value * 0.90, true);
else
trackZoom.SetValue(trackZoom.Value * 1.1, true);
}
}
private void switchEnable_ValueChanged(object sender, bool value)
{
if (_selectedLidar != null)
{
_selectedLidar.FrequencyChange -= lidar_FrequencyChange;
_selectedLidar.NewMeasure -= lidar_NewMeasure;
_selectedLidar.StartLoopMeasure();
}
if (value)
{
if ((String)cboLidar.Text == "Ground")
_selectedLidar = AllDevices.LidarGround;
else if ((String)cboLidar.Text == "Avoid")
_selectedLidar = AllDevices.LidarAvoid;
else
_selectedLidar = null;
if (_selectedLidar != null)
{
_selectedLidar.FrequencyChange += lidar_FrequencyChange;
_selectedLidar.NewMeasure += lidar_NewMeasure;
_selectedLidar.StartLoopMeasure();
}
}
}
private void lidar_NewMeasure(List<RealPoint> measure)
{
_lastMeasure = measure;
picWorld.Invalidate();
}
private void PanelLidar_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
trackZoom.SetValue(1);
cboLidar.Items.Add("Ground");
cboLidar.Items.Add("Avoid");
}
}
private void lidar_FrequencyChange(double value)
{
lblMeasuresPerSecond.InvokeAuto(() => lblMeasuresPerSecond.Text = value.ToString("0.00") + " mesures/s");
}
private void trackZoom_ValueChanged(object sender, double value)
{
picWorld.Dimensions.SetZoomFactor(value);
}
private void picWorld_WorldChange()
{
picWorld.Invalidate();
}
private void picWorld_Paint(object sender, PaintEventArgs e)
{
List<RealPoint> points = _lastMeasure;
Graphics g = e.Graphics;
if (picWorld.Width > 0 && picWorld.Height > 0)
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.DrawRectangle(Pens.Gray, 0, 0, picWorld.Width - 1, picWorld.Height - 1);
if (boxScale.Checked)
{
for (int i = 100; i < 5000; i += 100)
{
new Circle(new RealPoint(), i).Paint(g, Color.Gray, picWorld.Dimensions.WorldScale.Factor < 1 ? 2 : 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
if (picWorld.Dimensions.WorldScale.Factor < 1)
{
for (int i = 10; i < 5000; i += 10)
{
if (i % 100 != 0)
{
new Circle(new RealPoint(), i).Paint(g, Color.LightGray, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
}
}
if (points?.Count > 0)
{
if (rdoOutline.Checked)
{
points.Add(new RealPoint());
Polygon poly = new Polygon(points);
points.RemoveAt(points.Count - 1);
poly.Paint(g, Color.Red, 1, Color.LightGray, picWorld.Dimensions.WorldScale);
}
else if (rdoShadows.Checked)
{
points.Add(new RealPoint());
Polygon poly = new Polygon(points);
points.RemoveAt(points.Count - 1);
g.FillRectangle(Brushes.LightGray, 0, 0, picWorld.Width, picWorld.Height);
poly.Paint(g, Color.Red, 1, Color.White, picWorld.Dimensions.WorldScale);
}
else if (rdoObjects.Checked)
{
foreach (RealPoint p in points)
{
p.Paint(g, Color.Black, 3, Color.Red, picWorld.Dimensions.WorldScale);
}
}
else
{
foreach (RealPoint p in points)
{
Segment s = new Segment(new RealPoint(), p);
s.Paint(g, Color.Red, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
if (boxGroup.Checked)
{
points = points.Where(o => GameBoard.IsInside(o)).ToList();
List<List<RealPoint>> groups = points.GroupByDistance(50);
List<Color> colors = new List<Color>() { Color.Blue, Color.Green, Color.Red, Color.Brown };
List<IShape> shapes = new List<IShape>();
for (int i = 0; i < groups.Count; i++)
{
if (groups[i].Count > 5 && i < colors.Count)
{
Circle circle = groups[i].FitCircle();
//Line line = groups[i].FitLine();
//Segment line = groups[i].FitSegment();
shapes.Add(circle);
circle.Paint(g, colors[i], 1, Color.Transparent, picWorld.Dimensions.WorldScale);
g.DrawString((circle.Radius * 2).ToString("0") + "mm / " + (groups[i].FitCircleScore(circle) * 100).ToString("0") + "% / " + (groups[i].FitLineCorrelation()).ToString("0.00") + "%", new Font("Calibri", 9), new SolidBrush(colors[i]), picWorld.Dimensions.WorldScale.RealToScreenPosition(circle.Center.Translation(circle.Radius, 0)));
//line.Paint(g, colors[i], 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
//Plateau.Detections = shapes;
}
else
{
//Plateau.Detections = new List<IShape>(points);
}
new Circle(_selectedLidar.Position.Coordinates, 20).Paint(g, Color.Black, 1, Color.White, picWorld.Dimensions.WorldScale);
}
}
}
private void picWorld_MouseMove(object sender, MouseEventArgs e)
{
lblMousePosition.Text = picWorld.Dimensions.WorldScale.ScreenToRealPosition(e.Location).ToString();
}
}
}
<file_sep>/GoBot/GoBot/GameElements/RandomDropOff.cs
using Geometry;
using Geometry.Shapes;
using GoBot.BoardContext;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace GoBot.GameElements
{
public class RandomDropOff : GameElementZone
{
private List<List<Color>> _loads;
private List<Color> _loadOnTop;
private List<Color> _loadOnBottom;
public RandomDropOff(RealPoint position, Color color) : base(position, color, 200)
{
_loads = new List<List<Color>>();
_loadOnTop = null;
_loadOnBottom = null;
}
public int LoadsCount => _loads.Count;
public bool HasLoadOnTop => _loadOnTop != null;
public bool HasLoadOnBottom => _loadOnBottom != null;
public override void Paint(Graphics g, WorldScale scale)
{
base.Paint(g, scale);
double x = (Owner == GameBoard.ColorLeftBlue ? 55 : 3000 - 55);
double dx = (Owner == GameBoard.ColorLeftBlue ? 85 : -85);
for (int i = 0; i < _loads.Count; i++)
for (int j = 0; j < _loads[i].Count; j++)
new Circle(new RealPoint(x + dx * i, _position.Y - (j - 2) * 75), 36).Paint(g, Color.Black, 1, _loads[i][j], scale);
x = _position.X + (Owner == GameBoard.ColorLeftBlue ? -130 : 130);
dx = (Owner == GameBoard.ColorLeftBlue ? 85 : -85);
if (_loadOnTop != null)
for (int j = 0; j < _loadOnTop.Count; j++)
new Circle(new RealPoint(x + dx * j, _position.Y - 280), 36).Paint(g, Color.Black, 1, _loadOnTop[j], scale);
if (_loadOnBottom != null)
for (int j = 0; j < _loadOnBottom.Count; j++)
new Circle(new RealPoint(x + dx * j, _position.Y + 280), 36).Paint(g, Color.Black, 1, _loadOnBottom[j], scale);
}
public void AddLoad(List<Color> load)
{
if (load != null)
{
load = new List<Color>(load);
if (Owner == GameBoard.ColorLeftBlue)
load.Reverse();
_loads.Add(load);
}
}
public void SetLoadTop(List<Color> load)
{
_loadOnTop = new List<Color>(load);
}
public void SetLoadBottom(List<Color> load)
{
_loadOnBottom = new List<Color>(load);
_loadOnBottom.Reverse();
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaLidar.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Geometry.Shapes;
using GoBot.Devices;
using GoBot.BoardContext;
using System.Drawing.Drawing2D;
namespace GoBot.IHM.Pages
{
public partial class PagePandaLidar : UserControl
{
private Lidar _selectedLidar;
private List<RealPoint> _measureObjects, _measureBoard;
private Bitmap _background;
private RectangleF _backgroundRect;
private bool _enableBoard;
private bool _showLines, _showPoints;
private bool _enableGroup;
private bool _running;
public PagePandaLidar()
{
InitializeComponent();
_measureObjects = null;
_selectedLidar = null;
picWorld.Dimensions.SetZoomFactor(5);
_enableGroup = false;
_enableBoard = true;
_showPoints = true;
_showLines = false;
_running = false;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
if (!picWorld.RectangleToScreen(picWorld.ClientRectangle).Contains(MousePosition))
{
base.OnMouseWheel(e);
}
else
{
if (e.Delta > 0)
picWorld.Dimensions.SetZoomFactor(picWorld.Dimensions.WorldScale.Factor * 0.8);
else
picWorld.Dimensions.SetZoomFactor(picWorld.Dimensions.WorldScale.Factor * 1.25);
}
}
private void lidar_NewMeasure(List<RealPoint> measure)
{
List<IShape> obstacles = GameBoard.ObstaclesBoardConstruction.ToList();
List<RealPoint> tmpObjects, tmpBoard;
if (!_enableBoard)
{
tmpObjects = measure.Where(o => GameBoard.IsInside(o, 50)).ToList();
tmpObjects = tmpObjects.Where(p => !obstacles.Exists(o => o.Distance(p) < 30)).ToList();
tmpBoard = measure.Where(p => !tmpObjects.Contains(p)).ToList();
_measureObjects = tmpObjects.Select(p => new RealPoint(p.X - _selectedLidar.Position.Coordinates.X, p.Y - _selectedLidar.Position.Coordinates.Y)).ToList();
_measureBoard = tmpBoard.Select(p => new RealPoint(p.X - _selectedLidar.Position.Coordinates.X, p.Y - _selectedLidar.Position.Coordinates.Y)).ToList();
}
else
{
_measureObjects = measure.Select(p => new RealPoint(p.X - _selectedLidar.Position.Coordinates.X, p.Y - _selectedLidar.Position.Coordinates.Y)).ToList();
_measureBoard = null;
}
picWorld.Invalidate();
}
private void PanelLidar_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
btnTrap.Focus();
_running = false;
_selectedLidar = null;
}
}
private void picWorld_WorldChange()
{
picWorld.Invalidate();
}
private Bitmap GenerateBackground()
{
Bitmap b = new Bitmap(picWorld.Width, picWorld.Height);
Graphics g = Graphics.FromImage(b);
if (picWorld.Width > 0 && picWorld.Height > 0)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
PolygonRectangle bounds = new PolygonRectangle(picWorld.Dimensions.WorldRect);
for (int i = 100; i < 5000; i += 100)
{
Circle c = new Circle(new RealPoint(), i);
if (c.Cross(bounds) || bounds.Contains(c))
{
c.Paint(g, i % 1000 == 0 ? Color.LightGray : Color.DimGray, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
if (picWorld.Dimensions.WorldScale.Factor < 1 && !picWorld.Moving)
{
for (int i = 10; i < 5000; i += 10)
{
if (i % 100 != 0)
{
Circle c = new Circle(new RealPoint(), i);
if (c.Cross(bounds) || bounds.Contains(c))
{
c.Paint(g, Color.FromArgb(60, 60, 60), 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
}
}
}
g.Dispose();
return b;
}
private void picWorld_Paint(object sender, PaintEventArgs e)
{
if (_background == null || _backgroundRect != picWorld.Dimensions.WorldRect)
{
_background = GenerateBackground();
_backgroundRect = picWorld.Dimensions.WorldRect;
}
Bitmap background = _background;
List<RealPoint> pointsObjects = _measureObjects;
List<RealPoint> pointsBoard = _measureBoard;
Graphics g = e.Graphics;
if (picWorld.Width > 0 && picWorld.Height > 0)
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawImage(background, 0, 0);
if (picWorld.Moving)
{
int diam = 100;
Point p = picWorld.Dimensions.WorldScale.RealToScreenPosition(picWorld.ClickedPoint);
//g.FillEllipse(Brushes.White, p.X - diam / 2, p.Y - diam / 2, diam, diam);
GraphicsPath path = new GraphicsPath();
path.AddEllipse(p.X - diam / 2, p.Y - diam / 2, diam, diam);
PathGradientBrush b = new PathGradientBrush(path);
b.CenterPoint = p;
b.CenterColor = Color.White;
b.SurroundColors = new[] { Color.Transparent };
b.FocusScales = new PointF(0, 0);
g.FillEllipse(b, p.X - diam / 2, p.Y - diam / 2, diam, diam);
b.Dispose();
path.Dispose();
}
if (pointsBoard?.Count > 0)
{
if (_showPoints)
{
foreach (RealPoint p in pointsBoard)
{
p.Paint(g, Color.DarkRed, 3, Color.Red, picWorld.Dimensions.WorldScale);
}
}
if (_showLines)
{
foreach (RealPoint p in pointsBoard)
{
Segment s = new Segment(new RealPoint(), p);
s.Paint(g, Color.Red, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
}
if (pointsObjects?.Count > 0)
{
if (_showPoints)
{
foreach (RealPoint p in pointsObjects)
{
p.Paint(g, Color.DarkGreen, 3, Color.Lime, picWorld.Dimensions.WorldScale);
}
}
if (_showLines)
{
foreach (RealPoint p in pointsObjects)
{
Segment s = new Segment(new RealPoint(), p);
s.Paint(g, Color.Lime, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
if (_enableGroup)
{
//points = points.Where(o => GameBoard.IsInside(o)).ToList();
List<List<RealPoint>> groups = pointsObjects.GroupByDistance(80);
//for (int i = 0; i < groups.Count; i++)
//{
// Circle circle = groups[i].FitCircle();
// if (circle.Radius < 100 && groups[i].Count > 4)
// {
// circle.Paint(g, Color.White, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
// }
//}
for (int i = 0; i < groups.Count; i++)
{
if (groups[i].Count > 4)
{
RealPoint center = groups[i].GetBarycenter();
double var = Math.Sqrt(groups[i].Average(p => p.Distance(center) * p.Distance(center))) * 2;
new Circle(center, var).Paint(g, var > 35 ? Color.Lime : Color.Red, 1, Color.Transparent, picWorld.Dimensions.WorldScale);
}
}
//Plateau.Detections = shapes;
}
else
{
//Plateau.Detections = new List<IShape>(points);
}
}
}
}
public void LidarEnable(bool lidarEnable)
{
if (_selectedLidar != null && !lidarEnable && _running)
{
_selectedLidar.NewMeasure -= lidar_NewMeasure;
_running = false;
}
if (lidarEnable && !_running)
{
if (_selectedLidar != null)
{
_selectedLidar.NewMeasure += lidar_NewMeasure;
if (!_selectedLidar.Activated)
_selectedLidar.StartLoopMeasure();
_running = true;
}
}
}
private void picWorld_StopMove()
{
_background = GenerateBackground();
picWorld.Invalidate();
}
private void picWorld_StartMove()
{
picWorld.Invalidate();
}
private void btnZoomPlus_Click(object sender, EventArgs e)
{
picWorld.Dimensions.SetZoomFactor(picWorld.Dimensions.WorldScale.Factor * 0.8);
btnTrap.Focus();
}
private void btnZoomMinus_Click(object sender, EventArgs e)
{
picWorld.Dimensions.SetZoomFactor(picWorld.Dimensions.WorldScale.Factor * 1.25);
btnTrap.Focus();
}
private void btnZoomReset_Click(object sender, EventArgs e)
{
picWorld.Dimensions.SetZoomFactor(5);
picWorld.Dimensions.SetWorldCenter(new RealPoint(0, 0));
btnTrap.Focus();
}
private void SetLidar(Lidar lidar)
{
if (_selectedLidar != lidar)
{
if (_selectedLidar != null)
{
_selectedLidar.NewMeasure -= lidar_NewMeasure;
if (_selectedLidar == AllDevices.LidarGround)
_selectedLidar.StopLoopMeasure();
}
_selectedLidar = lidar;
if (_selectedLidar != null)
{
_selectedLidar.NewMeasure += lidar_NewMeasure;
if (_selectedLidar == AllDevices.LidarGround)
_selectedLidar.StartLoopMeasure();
}
_measureObjects = null;
_measureBoard = null;
picWorld.Invalidate();
}
}
private void btnGroup_Click(object sender, EventArgs e)
{
_enableGroup = !_enableGroup;
btnGroup.Image = _enableGroup ? Properties.Resources.LidarGroup : Properties.Resources.LidarGroupDisable;
}
private void btnLidarAvoid_Click(object sender, EventArgs e)
{
SetLidar(AllDevices.LidarAvoid);
}
private void btnLidarGround_Click(object sender, EventArgs e)
{
SetLidar(AllDevices.LidarGround);
}
private void btnEnableBoard_Click(object sender, EventArgs e)
{
_enableBoard = !_enableBoard;
btnEnableBoard.Image = _enableBoard ? Properties.Resources.LidarBoardOn : Properties.Resources.LidarBoardOff;
btnTrap.Focus();
}
private void btnPoints_Click(object sender, EventArgs e)
{
_showPoints = !_showPoints;
_showLines = !_showLines;
btnPoints.Image = _showPoints ? Properties.Resources.LidarPoints : Properties.Resources.LidarLines;
btnTrap.Focus();
}
}
}
<file_sep>/GoBot/GoBot/IHM/PagesPanda/PagePandaMove.cs
using System;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PagePandaMove : UserControl
{
bool _asserEna = true; // TODO faut garder la vraie valeur dans le robot...
public PagePandaMove()
{
InitializeComponent();
}
private void PagePandaMove_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
btnTrap.Focus();
}
}
private void btnRight_Click(object sender, EventArgs e)
{
Robots.MainRobot.PivotRight(90);
btnTrap.Focus();
}
private void btnUp_Click(object sender, EventArgs e)
{
Robots.MainRobot.MoveForward(100);
btnTrap.Focus();
}
private void btnDown_Click(object sender, EventArgs e)
{
Robots.MainRobot.MoveBackward(100);
btnTrap.Focus();
}
private void btnLeft_Click(object sender, EventArgs e)
{
Robots.MainRobot.PivotLeft(90);
btnTrap.Focus();
}
private void btnAsserv_Click(object sender, EventArgs e)
{
_asserEna = !_asserEna;
if (_asserEna)
{
Robots.MainRobot.Stop(StopMode.Abrupt);
btnAsserv.Image = Properties.Resources.GearsOn124;
}
else
{
Robots.MainRobot.Stop(StopMode.Freely);
btnAsserv.Image = Properties.Resources.GearsOff124;
}
btnTrap.Focus();
}
private void btnCalibration_Click(object sender, EventArgs e)
{
Robots.MainRobot.SetSpeedVerySlow();
Robots.MainRobot.Recalibration(SensAR.Arriere, true);
Robots.MainRobot.SetSpeedFast();
btnTrap.Focus();
}
private void btnFast_Click(object sender, EventArgs e)
{
Robots.MainRobot.SetSpeedFast();
}
private void btnSlow_Click(object sender, EventArgs e)
{
Robots.MainRobot.SetSpeedVerySlow();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PanelStorage.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using GoBot.Threading;
using GoBot.Actionneurs;
namespace GoBot.IHM.Panels
{
public partial class PanelStorage : UserControl
{
int _lateralPosition = 0;
int _verticalPosition = 0;
bool _isOnLeft = false;
ThreadLink _linkAnimation;
Color _red, _green;
List<Color> _leftStorage, _rightStorage;
Color _onGround;
public PanelStorage()
{
InitializeComponent();
_red = Color.FromArgb(150, 0, 0);
_green = Color.FromArgb(0, 150, 0);
_onGround = Color.Transparent;
_rightStorage = new List<Color>
{
Color.Transparent,
Color.Transparent,
Color.Transparent
};
_leftStorage = new List<Color>
{
Color.Transparent,
Color.Transparent,
Color.Transparent
};
Bitmap img;
img = new Bitmap(btnSpawnGreen.Width, btnSpawnGreen.Height);
Graphics g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.Transparent);
PaintBuoy(g, new PointF(img.Width / 2, 6), _green, 0.45f);
g.Dispose();
btnSpawnGreen.Image = img;
img = new Bitmap(btnSpawnRed.Width, btnSpawnRed.Height);
g = Graphics.FromImage(img);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.Clear(Color.Transparent);
PaintBuoy(g, new PointF(img.Width / 2, 6), _red, 0.45f);
g.Dispose();
btnSpawnRed.Image = img;
}
private void picStorage_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle r = new Rectangle(50 + _lateralPosition, 143, 260, 300);
Brush bsh = new LinearGradientBrush(r, Color.White, Color.WhiteSmoke, 30);
e.Graphics.FillRectangle(bsh, r);
e.Graphics.DrawRectangle(Pens.LightGray, r);
PaintBuoy(e.Graphics, new PointF(250, 450 - _verticalPosition), _onGround, 1.2f);
PaintBuoy(e.Graphics, new PointF(110 + _lateralPosition, 290), _leftStorage[2], 1.2f);
PaintLocker(e.Graphics, new PointF(110 + _lateralPosition, 290), true);
PaintBuoy(e.Graphics, new PointF(110 + _lateralPosition, 220), _leftStorage[1], 1.2f);
PaintLocker(e.Graphics, new PointF(110 + _lateralPosition, 220), true);
PaintBuoy(e.Graphics, new PointF(110 + _lateralPosition, 150), _leftStorage[0], 1.2f);
PaintLocker(e.Graphics, new PointF(110 + _lateralPosition, 150), true);
PaintBuoy(e.Graphics, new PointF(250 + _lateralPosition, 290), _rightStorage[2], 1.2f);
PaintLocker(e.Graphics, new PointF(250 + _lateralPosition, 290), false);
PaintBuoy(e.Graphics, new PointF(250 + _lateralPosition, 220), _rightStorage[1], 1.2f);
PaintLocker(e.Graphics, new PointF(250 + _lateralPosition, 220), false);
PaintBuoy(e.Graphics, new PointF(250 + _lateralPosition, 150), _rightStorage[0], 1.2f);
PaintLocker(e.Graphics, new PointF(250 + _lateralPosition, 150), false);
}
private void PaintBuoy(Graphics g, PointF center, ColorPlus color, float scale)
{
if (color.Alpha != 0)
{
List<PointF> pts = BuoyPoints(center, scale);
Brush bsh = new LinearGradientBrush(new PointF(pts.Min(o => o.X), pts.Min(o => o.Y)), new PointF(pts.Max(o => o.X), pts.Min(o => o.Y)), ColorPlus.FromAhsl(color.Alpha, color.Hue, color.Saturation, Math.Min(color.Lightness * 2, 1)), color);
g.FillPolygon(bsh, pts.ToArray());
bsh.Dispose();
g.DrawPolygon(Pens.Black, pts.ToArray());
}
}
private void PaintLocker(Graphics g, PointF center, bool onLeft)
{
List<PointF> pts = LockerPoints(center, onLeft);
//g.DrawLines(Pens.Black, pts.ToArray());
g.FillPolygon(Brushes.WhiteSmoke, pts.ToArray());
g.DrawPolygon(Pens.Black, pts.ToArray());
}
private List<PointF> BuoyPoints(PointF topCenter, float scale)
{
float topWidth, bottomWidth, height;
topWidth = 54;
bottomWidth = 72;
height = 115;
List<PointF> pts = new List<PointF>();
pts.Add(new PointF(topCenter.X - topWidth / 2, topCenter.Y + 0));
pts.Add(new PointF(topCenter.X + topWidth / 2, topCenter.Y + 0));
pts.Add(new PointF(topCenter.X + bottomWidth / 2, topCenter.Y + height));
pts.Add(new PointF(topCenter.X - bottomWidth / 2, topCenter.Y + height));
return pts.Select(o => new PointF((o.X - topCenter.X) * scale + topCenter.X, (o.Y - topCenter.Y) * scale + topCenter.Y)).ToList();
}
private List<PointF> LockerPoints(PointF topCenter, bool onLeft)
{
float scale, bottomWidth, height;
scale = 1.2f;
bottomWidth = 72;
height = 115;
PointF p;
int factor;
if (onLeft)
{
p = new PointF(topCenter.X - bottomWidth / 2 + 2, topCenter.Y + height + 1);
factor = 1;
}
else
{
p = new PointF(topCenter.X + bottomWidth / 2 - 2, topCenter.Y + height + 1);
factor = -1;
}
List<PointF> pts = new List<PointF>();
pts.Add(p);
pts.Add(new PointF(p.X - 4 * factor, p.Y + 8));
pts.Add(new PointF(p.X - 11 * factor, p.Y + 8));
pts.Add(new PointF(p.X - 12 * factor, p.Y + 7));
pts.Add(new PointF(p.X - 12 * factor, p.Y - 10));
pts.Add(new PointF(p.X - 8 * factor, p.Y - 10));
pts.Add(new PointF(p.X - 6 * factor, p.Y));
return pts.Select(o => new PointF((o.X - topCenter.X) * scale + topCenter.X, (o.Y - topCenter.Y) * scale + topCenter.Y)).ToList();
}
private void btnLateral_Click(object sender, EventArgs e)
{
_isOnLeft = !_isOnLeft;
if (_linkAnimation != null)
{
_linkAnimation.Cancel();
_linkAnimation.WaitEnd();
}
if (!_isOnLeft)
{
Actionneur.ElevatorRight.DoPushInside();
btnLateral.Image = Properties.Resources.BigArrow;
}
else
{
Actionneur.ElevatorRight.DoPushOutside();
Bitmap bmp = new Bitmap(Properties.Resources.BigArrow);
bmp.RotateFlip(RotateFlipType.RotateNoneFlipX);
btnLateral.Image = bmp;
}
_linkAnimation = ThreadManager.CreateThread(link => ThreadLateral(!_isOnLeft ? -4 : 4));
_linkAnimation.StartInfiniteLoop(15);
picStorage.Focus();
}
private void ThreadLateral(int offset)
{
_lateralPosition += offset;
picStorage.Invalidate();
if (_lateralPosition >= 140)
{
_lateralPosition = 140;
_linkAnimation.Cancel();
}
else if (_lateralPosition <= 0)
{
_lateralPosition = 0;
_linkAnimation.Cancel();
}
}
private void ThreadVertical(int offset)
{
int index = 0;
int maxVertical = 0;
_verticalPosition += offset;
picStorage.Invalidate();
if (_isOnLeft)
{
if (_leftStorage[0] == Color.Transparent)
{
maxVertical = 450 - 150;
index = 0;
}
else if (_leftStorage[1] == Color.Transparent)
{
maxVertical = 450 - 220;
index = 1;
}
else if (_leftStorage[2] == Color.Transparent)
{
maxVertical = 450 - 290;
index = 2;
}
}
else
{
if (_rightStorage[0] == Color.Transparent)
{
maxVertical = 450 - 150;
index = 0;
}
else if (_rightStorage[1] == Color.Transparent)
{
maxVertical = 450 - 220;
index = 1;
}
else if (_rightStorage[2] == Color.Transparent)
{
maxVertical = 450 - 290;
index = 2;
}
}
if (_verticalPosition >= maxVertical)
{
if (_isOnLeft)
_leftStorage[index] = _onGround;
else
_rightStorage[index] = _onGround;
_verticalPosition = 0;
_linkAnimation.Cancel();
_onGround = Color.Transparent;
this.InvokeAuto(() =>
{
btnSpawnGreen.Visible = true;
btnSpawnRed.Visible = true;
});
}
else if (_verticalPosition <= 0)
{
_verticalPosition = 0;
_linkAnimation.Cancel();
}
}
private void btnSpawnGreen_Click(object sender, EventArgs e)
{
_onGround = _green;
picStorage.Invalidate();
picStorage.Focus();
btnSpawnGreen.Visible = false;
btnSpawnRed.Visible = false;
}
private void btnSpawnRed_Click(object sender, EventArgs e)
{
_onGround = _red;
picStorage.Invalidate();
picStorage.Focus();
btnSpawnGreen.Visible = false;
btnSpawnRed.Visible = false;
}
private void btnUp_Click(object sender, EventArgs e)
{
if (_linkAnimation != null)
{
_linkAnimation.Cancel();
_linkAnimation.WaitEnd();
}
_linkAnimation = ThreadManager.CreateThread(link => ThreadVertical(4));
_linkAnimation.StartInfiniteLoop(10);
picStorage.Focus();
}
private void btnDown_Click(object sender, EventArgs e)
{
if (_linkAnimation != null)
{
_linkAnimation.Cancel();
_linkAnimation.WaitEnd();
}
List<Color> colors = _isOnLeft ? _leftStorage : _rightStorage;
int index = 0;
if (colors[2] != Color.Transparent)
{
_verticalPosition = 450 - 290;
index = 2;
}
else if (colors[1] != Color.Transparent)
{
_verticalPosition = 450 - 220;
index = 1;
}
else if (colors[0] != Color.Transparent)
{
_verticalPosition = 450 - 150;
index = 0;
}
btnSpawnGreen.Visible = false;
btnSpawnRed.Visible = false;
_onGround = colors[index];
colors[index] = Color.Transparent;
_linkAnimation = ThreadManager.CreateThread(link => ThreadVertical(-4));
_linkAnimation.StartInfiniteLoop(10);
picStorage.Focus();
}
}
}
<file_sep>/GoBot/GoBot/Devices/Hokuyo/HokuyoRec.cs
using Geometry;
using Geometry.Shapes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Devices
{
class HokuyoRec : Hokuyo
{
private double _deltaX, _deltaY;
public HokuyoRec(LidarID id) : base(id)
{
//_model = "UBG-04LX-F01";
//_pointsCount = 725;
_scanRange = 240;
//_pointsOffset = 44;
_distanceMinLimit = 50;
_distanceMaxLimit = 600;
_keepFrom = 175;
_keepTo = 575;
_invertRotation = false;
_resolution = 240 / 725.0;
_deltaX = 112;
_deltaY = 0;
}
protected override void SendMessage(string msg)
{
// non...
}
protected override String GetResponse(int timeout = 5000)
{
Position robotPos;
String mesure = Robots.MainRobot.ReadLidarMeasure(ID, timeout, out robotPos);
if (robotPos != null)
_position = new Position(robotPos.Angle, new RealPoint(robotPos.Coordinates.X + _deltaX, robotPos.Coordinates.Y + _deltaY).Rotation(new AngleDelta(robotPos.Angle), robotPos.Coordinates));
return mesure;
}
public string ReadMessage()
{
return GetResponse();
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageLogCan.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using GoBot.Communications;
using GoBot.Communications.CAN;
namespace GoBot.IHM.Pages
{
public partial class PageLogCan : UserControl
{
private FramesLog _log;
private Dictionary<CanBoard, Color> _boardColor;
private DateTime _startTime;
private DateTime _previousTime, _previousDisplayTime;
private System.Windows.Forms.Timer _displayTimer;
private int _counter = 0;
private Thread _thReplay;
private List<CheckedListBox> _boxLists;
bool _loading;
public PageLogCan()
{
InitializeComponent();
_loading = true;
dgvLog.Columns.Add("ID", "ID");
dgvLog.Columns[0].Width = 40;
dgvLog.Columns.Add("Heure", "Heure");
dgvLog.Columns[1].Width = 80;
dgvLog.Columns.Add("Expediteur", "Expediteur");
dgvLog.Columns[2].Width = 70;
dgvLog.Columns.Add("Destinataire", "Destinataire");
dgvLog.Columns[3].Width = 70;
dgvLog.Columns.Add("Message", "Message");
dgvLog.Columns[4].Width = 300;
dgvLog.Columns.Add("Trame", "Trame");
dgvLog.Columns[5].Width = dgvLog.Width - 18 - dgvLog.Columns[0].Width - dgvLog.Columns[1].Width - dgvLog.Columns[2].Width - dgvLog.Columns[3].Width - dgvLog.Columns[4].Width;
_boardColor = new Dictionary<CanBoard, Color>();
_boardColor.Add(CanBoard.PC, Color.FromArgb(180, 245, 245));
_boardColor.Add(CanBoard.CanServo1, Color.FromArgb(70, 255, 220));
_boardColor.Add(CanBoard.CanServo2, Color.FromArgb(100, 255, 220));
_boardColor.Add(CanBoard.CanServo3, Color.FromArgb(130, 255, 220));
_boardColor.Add(CanBoard.CanServo4, Color.FromArgb(160, 255, 220));
_boardColor.Add(CanBoard.CanServo5, Color.FromArgb(190, 255, 220));
_boardColor.Add(CanBoard.CanServo6, Color.FromArgb(220, 255, 220));
_boardColor.Add(CanBoard.CanAlim, Color.FromArgb(250, 255, 220));
_boxLists = new List<CheckedListBox>();
_boxLists.Add(lstSender);
_boxLists.Add(lstReceiver);
_boxLists.Add(lstFunctions);
if (Config.CurrentConfig.LogsCanFunctions == null)
Config.CurrentConfig.LogsCanFunctions = new SerializableDictionary<CanFrameFunction, bool>();
if (Config.CurrentConfig.LogsCanSenders == null)
Config.CurrentConfig.LogsCanSenders = new SerializableDictionary<CanBoard, bool>();
if (Config.CurrentConfig.LogsCanReceivers== null)
Config.CurrentConfig.LogsCanReceivers = new SerializableDictionary<CanBoard, bool>();
// L'ajout de champs déclenche le SetCheck event qui ajoute les éléments automatiquement dans le dictionnaire
foreach (CanFrameFunction func in Enum.GetValues(typeof(CanFrameFunction)))
{
if (!Config.CurrentConfig.LogsCanFunctions.ContainsKey(func))
Config.CurrentConfig.LogsCanFunctions.Add(func, true);
lstFunctions.Items.Add(func.ToString(), Config.CurrentConfig.LogsCanFunctions[func]);
}
foreach (CanBoard board in Enum.GetValues(typeof(CanBoard)))
{
if (!Config.CurrentConfig.LogsCanSenders.ContainsKey(board))
Config.CurrentConfig.LogsCanSenders.Add(board, true);
lstSender.Items.Add(board.ToString(), Config.CurrentConfig.LogsCanSenders[board]);
if (!Config.CurrentConfig.LogsCanReceivers.ContainsKey(board))
Config.CurrentConfig.LogsCanReceivers.Add(board, true);
lstReceiver.Items.Add(board.ToString(), Config.CurrentConfig.LogsCanReceivers[board]);
}
_loading = false;
_log = new FramesLog();
}
#region Publiques
public void Clear()
{
_log = new FramesLog();
}
public void DisplayFrame(TimedFrame tFrame)
{
String time = "";
try
{
if (rdoTimeAbsolute.Checked)
time = tFrame.Date.ToString("hh:mm:ss:fff");
if (rdoTimeFromStart.Checked)
time = (tFrame.Date - _startTime).ToString(@"hh\:mm\:ss\:fff");
if (rdoTimeFromPrev.Checked)
time = ((int)(tFrame.Date - _previousTime).TotalMilliseconds).ToString() + " ms";
if (rdoTimeFromPrevDisplay.Checked)
time = ((int)(tFrame.Date - _previousDisplayTime).TotalMilliseconds).ToString() + " ms";
CanBoard board = CanFrameFactory.ExtractBoard(tFrame.Frame);
CanBoard sender = CanFrameFactory.ExtractSender(tFrame.Frame, tFrame.IsInputFrame);
CanBoard receiver = CanFrameFactory.ExtractReceiver(tFrame.Frame, tFrame.IsInputFrame);
if (board == CanBoard.PC) throw new Exception();
bool receiverVisible = Config.CurrentConfig.LogsCanReceivers[receiver];
bool senderVisible = Config.CurrentConfig.LogsCanSenders[sender];
bool functionVisible = Config.CurrentConfig.LogsCanFunctions[CanFrameFactory.ExtractFunction(tFrame.Frame)];
if (senderVisible && receiverVisible && functionVisible)
{
dgvLog.Rows.Add(_counter, time, sender.ToString(), receiver.ToString(), CanFrameDecoder.Decode(tFrame.Frame), tFrame.Frame.ToString());
_previousDisplayTime = tFrame.Date;
if (rdoColorByBoard.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[board];
else if (rdoColorByReceiver.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[receiver];
else if (rdoColorBySender.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[sender];
}
}
catch (Exception e)
{
dgvLog.Rows.Add(_counter, time, "?", "?", "Inconnu !", tFrame.Frame.ToString());
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = Color.Red;
}
_counter++;
_previousTime = tFrame.Date;
}
public void DisplayLog()
{
try
{
dgvLog.Rows.Clear();
if (_log.Frames.Count > 0)
{
_startTime = _log.Frames[0].Date;
_previousTime = _log.Frames[0].Date;
_previousDisplayTime = _log.Frames[0].Date;
_counter = 0;
for (int iFrame = 0; iFrame < _log.Frames.Count; iFrame++)
DisplayFrame(_log.Frames[iFrame]);
}
}
catch (Exception)
{
MessageBox.Show("Impossible de décoder toutes les trames contenues dans ce fichier.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void LoadLog()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Fichiers replay trames (*" + FramesLog.FileExtension + ")| *" + FramesLog.FileExtension + "";
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
foreach (String fichier in open.FileNames)
{
LoadLog(fichier);
}
_log.Sort();
DisplayLog();
}
}
public void LoadLog(String file)
{
FramesLog log = new FramesLog();
log.Import(file);
foreach (TimedFrame t in log.Frames)
_log.Frames.Add(t);
}
#endregion
#region Privées
private void EnableAllCheckBoxes(bool enable)
{
for (int iList = 0; iList < _boxLists.Count; iList++)
for (int iItem = 0; iItem < _boxLists[iList].Items.Count; iItem++)
_boxLists[iList].SetItemChecked(iItem, enable);
}
private TimedFrame GetFrameFromLine(DataGridViewRow line)
{
return _log.Frames[Convert.ToInt32(dgvLog["ID", line.Index].Value)];
}
private void ShowFramesReceiver(CanBoard board, bool show)
{
lstReceiver.Items.Remove(board.ToString());
lstReceiver.Items.Add(board.ToString(), show);
Config.CurrentConfig.LogsCanReceivers[board] = show;
}
private void ShowFramesSender(CanBoard board, bool show)
{
lstSender.Items.Remove(board.ToString());
lstSender.Items.Add(board.ToString(), show);
Config.CurrentConfig.LogsCanSenders[board] = show;
}
private void ShowFrameFunction(CanFrameFunction func, bool show)
{
lstFunctions.Items.Remove(func.ToString());
lstFunctions.Items.Add(func.ToString(), show);
Config.CurrentConfig.LogsCanFunctions[func] = show;
}
private FramesLog CreateLogFromSelection()
{
FramesLog logSelection = new FramesLog();
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame trameReplay = GetFrameFromLine(line);
logSelection.AddFrame(trameReplay.Frame, trameReplay.IsInputFrame, trameReplay.Date);
}
return logSelection;
}
private void ReplayLog(FramesLog log)
{
_thReplay = new Thread(_log.ReplayInputFrames);
_thReplay.Start();
}
#endregion
#region Events
private void btnReplayAll_Click(object sender, EventArgs e)
{
ReplayLog(_log);
}
private void btnReplaySelected_Click(object sender, EventArgs e)
{
ReplayLog(CreateLogFromSelection());
}
private void lstSender_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
String boardStr = (String)lstSender.Items[e.Index];
CanBoard board = (CanBoard)Enum.Parse(typeof(CanBoard), boardStr);
Config.CurrentConfig.LogsCanReceivers[board] = (e.NewValue == CheckState.Checked);
}
}
private void lstReceiver_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
String boardStr = (String)lstReceiver.Items[e.Index];
CanBoard board = (CanBoard)Enum.Parse(typeof(CanBoard), boardStr);
Config.CurrentConfig.LogsCanReceivers[board] = (e.NewValue == CheckState.Checked);
}
}
private void lstFunctions_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
String funcStr = (String)lstFunctions.Items[e.Index];
CanFrameFunction func = (CanFrameFunction)Enum.Parse(typeof(CanFrameFunction), funcStr);
Config.CurrentConfig.LogsCanFunctions[func] = (e.NewValue == CheckState.Checked);
}
}
private void mnuHideSameSenderFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFramesSender(CanFrameFactory.ExtractSender(tFrame.Frame, tFrame.IsInputFrame), false);
}
DisplayLog();
}
}
private void mnuHideSameReceiverFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFramesReceiver(CanFrameFactory.ExtractReceiver(tFrame.Frame, tFrame.IsInputFrame), false);
}
DisplayLog();
}
}
private void mnuHideSameBoardFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
CanBoard board = CanFrameFactory.ExtractBoard(GetFrameFromLine(line).Frame);
ShowFramesReceiver(board, false);
ShowFramesSender(board, false);
}
DisplayLog();
}
}
private void mnuHideAllFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.Rows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFrameFunction(CanFrameFactory.ExtractFunction(tFrame.Frame), false);
}
DisplayLog();
}
}
private void mnuFrameCopy_Click(object sender, EventArgs e)
{
if (dgvLog.Rows.Count > 0)
Clipboard.SetText(GetFrameFromLine(dgvLog.SelectedRows[0]).Frame.ToString());
}
private void btnAllCheck_Click(object sender, EventArgs e)
{
EnableAllCheckBoxes(true);
}
private void btnAllUncheck_Click(object sender, EventArgs e)
{
EnableAllCheckBoxes(false);
}
private void btnRefresh_Click(object sender, EventArgs e)
{
DisplayLog();
}
private void dgvLog_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex > 0 && e.ColumnIndex > 0)
dgvLog.CurrentCell = dgvLog.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
private void mnuHideSameTypeFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFrameFunction(CanFrameFactory.ExtractFunction(tFrame.Frame), false);
}
DisplayLog();
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
if (_displayTimer == null || !_displayTimer.Enabled)
{
_log = new FramesLog();
_displayTimer = new System.Windows.Forms.Timer();
_displayTimer.Interval = 1000;
_displayTimer.Tick += displayTimer_Tick;
_displayTimer.Start();
Connections.ConnectionCan.FrameReceived += new CanConnection.NewFrameDelegate((frame) => _log.AddFrame(frame, true));
Connections.ConnectionCan.FrameSend += new CanConnection.NewFrameDelegate((frame) => _log.AddFrame(frame, false));
btnReplayAll.Enabled = false;
btnReplaySelected.Enabled = false;
btnLoad.Enabled = false;
btnDisplay.Text = "Arrêter la surveillance";
btnDisplay.Image = Properties.Resources.GlassPause48;
}
else
{
_displayTimer.Stop();
Connections.ConnectionCan.FrameReceived -= new CanConnection.NewFrameDelegate((frame) => _log.AddFrame(frame, true));
Connections.ConnectionCan.FrameSend -= new CanConnection.NewFrameDelegate((frame) => _log.AddFrame(frame, false));
btnReplayAll.Enabled = true;
btnReplaySelected.Enabled = true;
btnLoad.Enabled = true;
btnDisplay.Text = "Lancer la surveillance";
btnDisplay.Image = Properties.Resources.GlassStart48;
}
}
void displayTimer_Tick(object sender, EventArgs e)
{
int nbTrames = _log.Frames.Count;
for (int i = _counter; i < nbTrames; i++)
DisplayFrame(_log.Frames[i]);
if (boxScroll.Checked && dgvLog.Rows.Count > 10)
dgvLog.FirstDisplayedScrollingRowIndex = dgvLog.RowCount - 1;
}
private void btnLoad_Click(object sender, EventArgs e)
{
LoadLog();
}
#endregion
}
}
<file_sep>/GoBot/Geometry/Maths.cs
using System;
using Geometry.Shapes;
namespace Geometry
{
public struct Direction
{
public AngleDelta angle;
public double distance;
}
public class Maths
{
/// <summary>
/// Retourne la direction (angle et distance) à suivre pour arriver à un point donné en partant d'une corrdonnée précise (et par défaut, angle de 0°)
/// </summary>
/// <param name="startPoint">Coordonnées de départ</param>
/// <param name="endPoint">Coordonnées d'arrivée</param>
/// <returns>Direction à suivre</returns>
public static Direction GetDirection(RealPoint startPoint, RealPoint endPoint)
{
Position startPosition = new Position(0, startPoint);
return GetDirection(startPosition, endPoint);
}
/// <summary>
/// Retourne la direction (angle et distance) à suivre pour arriver à un point donné en partant d'une position précise (coordonnées et angle)
/// </summary>
/// <param name="startPosition">Position de départ</param>
/// <param name="endPoint">Coordonnées d'arrivée</param>
/// <returns>Direction à suivre</returns>
public static Direction GetDirection(Position startPosition, RealPoint endPoint)
{
Direction result = new Direction();
result.distance = startPosition.Coordinates.Distance(endPoint);
double angleCalc = 0;
// Deux points sur le même axe vertical : 90° ou -90° selon le point le plus haut
if (endPoint.X == startPosition.Coordinates.X)
{
angleCalc = Math.PI / 2;
if (endPoint.Y > startPosition.Coordinates.Y)
angleCalc = -angleCalc;
}
// Deux points sur le même axe horizontal : 0° ou 180° selon le point le plus à gauche
else if (endPoint.Y == startPosition.Coordinates.Y)
{
angleCalc = Math.PI;
if (endPoint.X > startPosition.Coordinates.X)
angleCalc = 0;
}
// Cas général : Calcul de l'angle
else
{
angleCalc = Math.Acos((endPoint.X - startPosition.Coordinates.X) / result.distance);
if (endPoint.Y > startPosition.Coordinates.Y)
angleCalc = -angleCalc;
}
// Prendre en compte l'angle initial
AngleDelta angle = new AngleDelta(angleCalc, AngleType.Radian);
angle = angle + startPosition.Angle;
result.angle = angle.Modulo();
return result;
}
/// <summary>
/// Retourne les coordonnées d'une coordonnée initiale modifiée par une prise de direction
/// </summary>
/// <param name="startPoint">Coordonnée de départ</param>
/// <param name="direction">Direction suivie</param>
/// <returns>Coordonnées du point</returns>
public static RealPoint GetDestination(RealPoint startPoint, Direction direction)
{
double x = startPoint.X + direction.angle.Cos * direction.distance;
double y = startPoint.Y - direction.angle.Sin * direction.distance;
return new RealPoint(new RealPoint(x, y));
}
/// <summary>
/// Retourne les coordonnées d'une position initiale modifiée par une prise de direction
/// </summary>
/// <param name="startPosition">Position de départ</param>
/// <param name="direction">Direction suivie</param>
/// <returns>Coordonnées du point</returns>
public static Position GetDestination(Position startPosition, Direction direction)
{
AnglePosition endAngle = startPosition.Angle + direction.angle;
double x = startPosition.Coordinates.X + endAngle.Cos * direction.distance;
double y = startPosition.Coordinates.Y - endAngle.Sin * direction.distance;
return new Position(endAngle, new RealPoint(x, y));
}
/// <summary>
/// Retourne la longueur de l'hypothenuse d'un triangle rectangle à partir des longueur des 2 autres côtés.
/// </summary>
/// <param name="side1">Longueur du 1er côté</param>
/// <param name="side2">Longueur du 2ème côté</param>
/// <returns>Longueur de l'hypothenuse</returns>
public static double Hypothenuse(double side1, double side2)
{
return Math.Sqrt(side1 * side1 + side2 * side2);
}
public static double Scale(double value, double oldMax, double newMax)
{
return value / oldMax * newMax;
}
public static double Scale(double value, double oldMin, double oldMax, double newMin, double newMax)
{
return (value - oldMin) / (oldMax - oldMin) * (newMax - newMin) + newMin;
}
}
}
<file_sep>/GoBot/Geometry/Util.cs
using System;
namespace Geometry
{
public static class Util
{
public static dynamic ToRealType(Object o)
{
Type type = o.GetType();
dynamic pp = Convert.ChangeType(o, type);
return pp;
}
}
}
<file_sep>/GoBot/GoBot/Historique.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoBot.Actions;
using System.Threading;
using System.Xml.Serialization;
using System.IO;
namespace GoBot
{
[Serializable]
public enum TypeLog
{
Action,
Strat,
PathFinding
}
[Serializable]
public class HistoLigne : IComparable
{
private static int idActuel = 0;
public int ID { get; set; }
public String Message { get; set; }
public DateTime Heure { get; set; }
public TypeLog Type {get;set;}
public IDRobot Robot { get; set; }
public HistoLigne(IDRobot robot, DateTime heure, String message, TypeLog type = TypeLog.Strat)
{
ID = idActuel++;
Robot = robot;
Message = message;
Heure = heure;
Type = type;
}
public HistoLigne()
{
}
public int CompareTo(object obj)
{
if (ID == ((HistoLigne)obj).ID)
return Heure.CompareTo(((HistoLigne)obj).Heure);
else
return ID.CompareTo(((HistoLigne)obj).ID);
}
}
public class Historique
{
int NBACTIONSMAX = 10;
public IDRobot Robot { get; private set; }
private List<IAction> actions;
public List<IAction> Actions
{
get
{
return actions;
}
}
public delegate void DelegateAction(IAction action);
public event DelegateAction NouvelleAction;
public delegate void DelegateLog(HistoLigne ligne);
public event DelegateLog NouveauLog;
public Historique(IDRobot robot)
{
Robot = robot;
actions = new List<IAction>();
HistoriqueLignes = new List<HistoLigne>();
}
public void AjouterAction(IAction action)
{
/*Actions.Add(action);
Log(action.ToString(), TypeLog.Action);
while (Actions.Count > NBACTIONSMAX)
Actions.RemoveAt(0);
if (NouvelleAction != null)
NouvelleAction(action);*/
}
public void Log(String message, TypeLog type = TypeLog.Strat)
{
HistoLigne ligne = new HistoLigne(Robot, DateTime.Now, message, type);
HistoriqueLignes.Add(ligne);
if (NouveauLog != null)
NouveauLog(ligne);
}
public List<HistoLigne> HistoriqueLignes { get; set; }
/// <summary>
/// Charge une sauvegarde d'historique
/// </summary>
/// <param name="nomFichier">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde a été correctement chargée</returns>
public bool Charger(String nomFichier)
{
try
{
XmlSerializer mySerializer = new XmlSerializer(typeof(List<HistoLigne>));
using (FileStream myFileStream = new FileStream(nomFichier, FileMode.Open))
HistoriqueLignes = (List<HistoLigne>)mySerializer.Deserialize(myFileStream);
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Sauvegarde l'ensemble de l'historique dans un fichier
/// </summary>
/// <param name="nomFichier">Chemin du fichier</param>
/// <returns>Vrai si la sauvegarde s'est correctement déroulée</returns>
public bool Sauvegarder(String nomFichier)
{
try
{
XmlSerializer mySerializer = new XmlSerializer(typeof(List<HistoLigne>));
using (StreamWriter myWriter = new StreamWriter(nomFichier))
mySerializer.Serialize(myWriter, HistoriqueLignes);
return true;
}
catch (Exception)
{
return false;
}
}
}
}
<file_sep>/GoBot/GoBot/SpeedSampler.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot
{
class SpeedSample
{
private List<double> _pos, _speed;
private List<TimeSpan> _times;
public SpeedSample(List<TimeSpan> times, List<double> positions, List<double> speeds)
{
_times = times;
_pos = positions;
_speed = speeds;
}
public List<double> Positions { get { return _pos; } }
public List<double> Speeds { get { return _speed; } }
public List<TimeSpan> Times { get { return _times; } }
public TimeSpan Duration { get { return _times[_times.Count - 1] - _times[0]; } }
public bool Valid { get { return _pos.Count > 0; } }
}
class SpeedSampler
{
private SpeedConfig _config;
public SpeedSampler(SpeedConfig config)
{
_config = config;
}
public SpeedSample SampleLine(int startPos, int endPos, int samplesCnt)
{
TimeSpan accelDuration, maxSpeedDuration, brakingDuration, totalDuration;
totalDuration = _config.LineDuration(Math.Abs(endPos - startPos), out accelDuration, out maxSpeedDuration, out brakingDuration);
TimeSpan division = new TimeSpan(totalDuration.Ticks / samplesCnt);
List<double> speeds = new List<double>();
List<double> positions = new List<double>();
List<TimeSpan> times = new List<TimeSpan>();
double currentSpeed = 0, currentPosition = startPos;
int direction = ((endPos - startPos) > 0 ? 1 : -1);
double accelPerDiv = (_config.LineAcceleration * division.TotalSeconds) * direction;
TimeSpan currentTime = new TimeSpan();
while (speeds.Count < samplesCnt)
{
speeds.Add(currentSpeed);
positions.Add(currentPosition);
times.Add(currentTime);
currentTime += division;
if (currentTime < accelDuration)
currentSpeed += accelPerDiv;
else if (currentTime > accelDuration + maxSpeedDuration)
currentSpeed -= accelPerDiv;
else
currentSpeed = _config.LineSpeed * direction;
if(direction < 0)
currentSpeed = Math.Min(0, Math.Max(currentSpeed, _config.LineSpeed *direction));
else
currentSpeed = Math.Max(0, Math.Min(currentSpeed, _config.LineSpeed * direction));
currentPosition += currentSpeed;
}
return new SpeedSample(times, positions, speeds);
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyEmpty.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Strategies
{
class StrategyEmpty : Strategy
{
public override bool AvoidElements => false;
protected override void SequenceBegin()
{
}
protected override void SequenceCore()
{
}
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/PepperlManager.cs
using Geometry;
using GoBot.Communications;
using GoBot.Communications.UDP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace GoBot.Devices
{
public class PepperlManager
{
public struct PepperlPoint
{
public uint distance;
public ushort amplitude;
public override string ToString()
{
return distance.ToString() + "mm - " + Math.Round(amplitude / 40.95f, 0).ToString() + "%";
}
}
private IPAddress _ip;
private int _port;
private String _handle;
private TimeSpan _timeout;
private PepperlComm _comm;
private UDPConnection _udp;
List<PepperlPoint> _currentMeasure;
int _currentScan;
public delegate void NewMeasureHandler(List<PepperlPoint> measure, AnglePosition startAngle, AngleDelta resolution);
public event NewMeasureHandler NewMeasure;
public PepperlManager(IPAddress ip, int port)
{
_ip = ip;
_port = port;
_currentScan = -1;
_timeout = new TimeSpan(0, 0, 10);
_comm = new PepperlComm(_ip);
}
protected void OnNewMeasure(List<PepperlPoint> measure, AnglePosition startAngle, AngleDelta resolution)
{
NewMeasure?.Invoke(_currentMeasure, startAngle, resolution);
_currentMeasure = null;
}
public void Reboot()
{
_comm.SendCommand(PepperlCmd.Reboot);
}
public bool CreateChannelUDP()
{
bool ok = false;
try
{
Dictionary<String, String> rep = _comm.SendCommand(PepperlCmd.CreateChannelUDP,
PepperlConst.ParamUdpAddress, FindMyIP().ToString(),
PepperlConst.ParamUdpPort, _port.ToString(),
PepperlConst.ParamUdpWatchdog, PepperlConst.ValueUdpWatchdogOn,
PepperlConst.ParamUdpWatchdogTimeout, _timeout.TotalMilliseconds.ToString(),
PepperlConst.ParamUdpPacketType, PepperlConst.ValueUdpPacketTypeDistanceAmplitudeCompact);
if (rep != null)
{
_handle = rep[PepperlConst.ParamUdpHandle];
if (_handle != "")
{
_udp = new UDPConnection();
_udp.Connect(_ip, _port, _port + 1);
_udp.StartReception();
_udp.FrameReceived += _udp_FrameReceived;
_comm.SendCommand(PepperlCmd.ScanStart,
PepperlConst.ParamUdpHandle, _handle);
ok = true;
}
}
}
catch (Exception)
{
ok = false;
if (_udp != null && _udp.Connected)
{
_udp.Close();
_udp = null;
}
}
return ok;
}
public void CloseChannelUDP()
{
_comm.SendCommand(PepperlCmd.ScanStop,
PepperlConst.ParamUdpHandle, _handle);
_udp?.Close();
_udp = null;
_handle = null;
}
private void _udp_FrameReceived(Frame frame)
{
int addr = 0;
ushort magic = (ushort)Read(frame, ref addr, 2);
ushort packetType = (ushort)Read(frame, ref addr, 2);
uint packetSize = (uint)Read(frame, ref addr, 4);
ushort headerSize = (ushort)Read(frame, ref addr, 2);
ushort scanNumber = (ushort)Read(frame, ref addr, 2);
ushort packetNumber = (ushort)Read(frame, ref addr, 2);
long timestampRaw = (long)Read(frame, ref addr, 8);
long timestampSync = (long)Read(frame, ref addr, 8);
uint statusFlag = (uint)Read(frame, ref addr, 4);
uint scanFrequency = (uint)Read(frame, ref addr, 4);
ushort numPointsScan = (ushort)Read(frame, ref addr, 2);
ushort numPointsPacket = (ushort)Read(frame, ref addr, 2);
ushort firstIndex = (ushort)Read(frame, ref addr, 2);
int firstAngle = ReadInt(frame, ref addr);
int angularIncrement = ReadInt(frame, ref addr);
uint iqInput = (uint)Read(frame, ref addr, 4);
uint iqOverload = (uint)Read(frame, ref addr, 4);
long iqTimestampRaw = (long)Read(frame, ref addr, 8);
long iqTimestampSync = (long)Read(frame, ref addr, 8);
if (firstIndex == 0)
{
_currentMeasure = new List<PepperlPoint>();
_currentScan = scanNumber;
}
if (_currentMeasure != null && _currentScan == scanNumber)
{
String type = ((char)packetType).ToString();
if (type == PepperlConst.ValueUdpPacketTypeDistance)
{
for (int iPt = 0; iPt < numPointsPacket; iPt++)
_currentMeasure.Add(ReadMeasureA(frame, ref addr));
}
else if (type == PepperlConst.ValueUdpPacketTypeDistanceAmplitude)
{
for (int iPt = 0; iPt < numPointsPacket; iPt++)
_currentMeasure.Add(ReadMeasureB(frame, ref addr));
}
else if (type == PepperlConst.ValueUdpPacketTypeDistanceAmplitudeCompact)
{
for (int iPt = 0; iPt < numPointsPacket; iPt++)
_currentMeasure.Add(ReadMeasureC(frame, ref addr));
}
if (_currentMeasure.Count == numPointsScan)
{
OnNewMeasure(_currentMeasure, firstAngle / 10000f, angularIncrement / 10000f);
_currentMeasure = null;
}
}
// TODO vérification CRC32C ?
}
public void FeedWatchDog()
{
_comm.SendCommand(PepperlCmd.FeedWatchdog,
PepperlConst.ParamFeedWatchdogHandle, _handle);
}
public void ShowMessage(String txt1, String txt2)
{
_comm.SetParameters(PepperlConst.ParamHmiMode, PepperlConst.ValueHmiModeSoftText,
PepperlConst.ParamHmiSoftText1, txt1,
PepperlConst.ParamHmiSoftText2, txt2);
}
public void SetFrequency(PepperlFreq freq)
{
_comm.SetParameters(PepperlConst.ParamScanFrequency, freq.Frequency().ToString(),
PepperlConst.ParamSamplesPerScan, freq.SamplesPerScan().ToString());
}
public void SetFilter(PepperlFilter filter, int size)
{
_comm.SetParameters(PepperlConst.ParamFilterType, filter.GetText(),
PepperlConst.ParamFilterWidth, size.ToString());
}
private IPAddress FindMyIP()
{
return Dns.GetHostAddresses(Dns.GetHostName()).ToList().First(ip => ip.ToString().StartsWith("10.1.0."));
}
private long Read(Frame frame, ref int index, int lenght)
{
long val = 0;
for (int i = index + lenght - 1; i >= index; i--)
{
val = val << 8;
val += frame[i];
}
index += lenght;
return val;
}
private int ReadInt(Frame frame, ref int index)
{
int val = frame[index] | frame[index + 1] << 8 | frame[index + 2] << 16 | frame[index + 3] << 24;
index += 4;
return val;
}
private PepperlPoint ReadMeasureA(Frame f, ref int i)
{
PepperlPoint p;
p.distance = (uint)Read(f, ref i, 4);
p.amplitude = 0xFFF;
if (p.distance == 0xFFFFFFFF) p.distance = 0;
return p;
}
private PepperlPoint ReadMeasureB(Frame f, ref int i)
{
PepperlPoint p;
p.distance = (uint)Read(f, ref i, 4);
p.amplitude = (ushort)Read(f, ref i, 2);
if (p.distance == 0xFFFFF) p.distance = 0;
return p;
}
private PepperlPoint ReadMeasureC(Frame f, ref int i)
{
long val = Read(f, ref i, 4);
PepperlPoint p;
p.distance = (uint)(val & 0xFFFFF);
p.amplitude = (ushort)(val >> 20);
if (p.distance == 0xFFFFF) p.distance = 0;
return p;
}
}
}
<file_sep>/GoBot/Geometry/WorldRect.cs
using System.Drawing;
using Geometry.Shapes;
namespace Geometry
{
public class WorldDimensions
{
private Size _screenSize;
public WorldScale WorldScale { get; protected set; }
public RectangleF WorldRect { get; protected set; }
public delegate void WorldChangeDelegate();
public event WorldChangeDelegate WorldChange;
public WorldDimensions()
{
WorldScale = new WorldScale(5, 0, 0);
WorldRect = new RectangleF();
}
public void SetScreenSize(Size size)
{
WorldRect = WorldRect.ExpandWidth(WorldScale.ScreenToRealDistance(size.Width));
WorldRect = WorldRect.ExpandHeight(WorldScale.ScreenToRealDistance(size.Height));
_screenSize = size;
WorldChange?.Invoke();
}
public void SetZoomFactor(double mmPerPixel)
{
RealPoint center = WorldRect.Center();
WorldRect = WorldRect.ExpandWidth(WorldRect.Width * (mmPerPixel / WorldScale.Factor));
WorldRect = WorldRect.ExpandHeight(WorldRect.Height * (mmPerPixel / WorldScale.Factor));
WorldScale = new WorldScale(mmPerPixel, (int)(-WorldRect.X / mmPerPixel), (int)(-WorldRect.Y / mmPerPixel));
WorldChange?.Invoke();
}
public void SetWorldCenter(RealPoint center)
{
WorldRect = WorldRect.SetCenter(center);
WorldScale = new WorldScale(WorldScale.Factor, -WorldScale.RealToScreenDistance(WorldRect.X), -WorldScale.RealToScreenDistance(WorldRect.Y));
WorldChange?.Invoke();
}
}
}
<file_sep>/GoBot/GoBot/Actions/ActionServo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionServo : IAction
{
private int position;
ServomoteurID pince;
private Robot robot;
public ActionServo(Robot r, int po, ServomoteurID pi)
{
robot = r;
position = po;
pince = pi;
}
public override String ToString()
{
return robot + " bouge " + NameFinder.GetName(pince) + " à " + NameFinder.GetName(position, pince);
}
void IAction.Executer()
{
Devices.AllDevices.CanServos[pince].SetPosition(position);
}
public System.Drawing.Image Image
{
get
{
return GoBot.Properties.Resources.Motor16;
}
}
}
}
<file_sep>/GoBot/GoBot/GameElements/GameElement.cs
using Geometry;
using Geometry.Shapes;
using GoBot.Movements;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using GoBot.BoardContext;
namespace GoBot.GameElements
{
public abstract class GameElement
{
protected RealPoint _position;
protected bool _isAvailable;
protected bool _isHover;
protected int _hoverRadius;
protected Color _owner;
/// <summary>
/// Obtient ou définit si l'élement de jeu est parti et donc n'est plus disponible
/// </summary>
public bool IsAvailable
{
get { return _isAvailable; }
set { _isAvailable = value; }
}
/// <summary>
/// Obtient ou définir la couleur de l'action (joueur propriétaire ou blanc)
/// </summary>
public Color Owner
{
get { return _owner; }
set { _owner = value; }
}
/// <summary>
/// Position du centre de l'action
/// </summary>
public RealPoint Position
{
get { return _position; }
set { _position = value; }
}
/// <summary>
/// Obtient ou définit si l'action est actuellement survolée par la souris
/// </summary>
public bool IsHover
{
get { return _isHover; }
set { _isHover = value; }
}
/// <summary>
/// Obtient ou définit le rayon du srvol de la souris
/// </summary>
public int HoverRadius
{
get { return _hoverRadius; }
set { _hoverRadius = value; }
}
/// <summary>
/// Constructeur
/// </summary>
/// <param name="position">Position de l'élément</param>
/// <param name="owner">Couleur d'appartenance de l'élément</param>
/// <param name="hoverRadius">Rayon de survol de l'élément</param>
public GameElement(RealPoint position, Color owner, int hoverRadius)
{
this._hoverRadius = hoverRadius;
this._position = position;
this._owner = owner;
this._isAvailable = true;
}
/// <summary>
/// Peint l'élément sur le Graphic donné à l'échelle donnée
/// </summary>
/// <param name="g">Graphic sur lequel peindre</param>
/// <param name="scale">Echelle de peinture</param>
public abstract void Paint(Graphics g, WorldScale scale);
/// <summary>
/// Action à executer au clic de la souris
/// </summary>
/// <returns>Vrai si l'éction a été correctement executée</returns>
public virtual bool ClickAction()
{
IEnumerable<Movement> movements = GameBoard.Strategy.Movements.Where(m => m.Element == this);
if(movements.Count() > 0)
{
Movement move = movements.OrderBy(m => m.GlobalCost).First();
return move.Execute();
}
return false;
}
}
}
<file_sep>/GoBot/GoBot/TicksPerSecond.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace GoBot
{
class TicksPerSecond
{
private int _counter;
private List<int> _measures;
private Timer _timer;
private double _lastValue;
public int MeasuresCount { get; set; }
public delegate void ValueChangeDelegate(double value);
public event ValueChangeDelegate ValueChange;
public TicksPerSecond()
{
_measures = new List<int>();
_counter = 0;
MeasuresCount = 10;
_lastValue = -1;
}
public void Start()
{
if(_timer == null)
{
_counter = 0;
_timer = new Timer(1000);
_timer.Elapsed += _timer_Elapsed;
_timer.Start();
}
}
public void Stop()
{
if(_timer != null)
{
_timer.Stop();
_timer = null;
_measures.Clear();
_lastValue = 0;
ValueChange?.Invoke(_lastValue);
}
}
public void AddTick()
{
_counter++;
}
private void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_measures.Add(_counter);
_counter = 0;
if (_measures.Count > MeasuresCount)
_measures.RemoveRange(0, _measures.Count - MeasuresCount);
double newValue = _measures.Average();
if (newValue != _lastValue)
{
_lastValue = newValue;
ValueChange?.Invoke(_lastValue);
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageLogUdp.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using GoBot.Communications;
using GoBot.Communications.UDP;
namespace GoBot.IHM.Pages
{
public partial class PageLogUdp : UserControl
{
private FramesLog _log;
private Dictionary<Board, Color> _boardColor;
private DateTime _startTime;
private DateTime _previousTime, _previousDisplayTime;
private System.Windows.Forms.Timer _displayTimer;
private int _counter = 0;
private Thread _thReplay;
private List<CheckedListBox> _boxLists;
private Dictionary<CheckedListBox, Dictionary<UdpFrameFunction, bool>> _configFunctions;
private Dictionary<Board, CheckedListBox> _lstFunctions;
bool _loading;
public PageLogUdp()
{
InitializeComponent();
_loading = true;
dgvLog.Columns.Add("ID", "ID");
dgvLog.Columns[0].Width = 40;
dgvLog.Columns.Add("Heure", "Heure");
dgvLog.Columns[1].Width = 80;
dgvLog.Columns.Add("Expediteur", "Expediteur");
dgvLog.Columns[2].Width = 70;
dgvLog.Columns.Add("Destinataire", "Destinataire");
dgvLog.Columns[3].Width = 70;
dgvLog.Columns.Add("Message", "Message");
dgvLog.Columns[4].Width = 300;
dgvLog.Columns.Add("Trame", "Trame");
dgvLog.Columns[5].Width = dgvLog.Width - 18 - dgvLog.Columns[0].Width - dgvLog.Columns[1].Width - dgvLog.Columns[2].Width - dgvLog.Columns[3].Width - dgvLog.Columns[4].Width;
_boardColor = new Dictionary<Board, Color>();
_boardColor.Add(Board.PC, Color.FromArgb(180, 245, 245));
_boardColor.Add(Board.RecMove, Color.FromArgb(143, 255, 143));
_boardColor.Add(Board.RecIO, Color.FromArgb(210, 254, 211));
_boardColor.Add(Board.RecCan, Color.FromArgb(254, 244, 188));
_boxLists = new List<CheckedListBox>();
_boxLists.Add(lstSender);
_boxLists.Add(lstReceiver);
_boxLists.Add(lstRecIOFunctions);
_boxLists.Add(lstRecMoveFunctions);
_boxLists.Add(lstRecGoBotFunctions);
_boxLists.Add(lstRecCanFunctions);
if (Config.CurrentConfig.LogsFonctionsMove == null)
Config.CurrentConfig.LogsFonctionsMove = new SerializableDictionary<UdpFrameFunction, bool>();
if (Config.CurrentConfig.LogsFonctionsIO == null)
Config.CurrentConfig.LogsFonctionsIO = new SerializableDictionary<UdpFrameFunction, bool>();
if (Config.CurrentConfig.LogsFonctionsGB == null)
Config.CurrentConfig.LogsFonctionsGB = new SerializableDictionary<UdpFrameFunction, bool>();
if (Config.CurrentConfig.LogsFonctionsCan == null)
Config.CurrentConfig.LogsFonctionsCan = new SerializableDictionary<UdpFrameFunction, bool>();
if (Config.CurrentConfig.LogsExpediteurs == null)
Config.CurrentConfig.LogsExpediteurs = new SerializableDictionary<Board, bool>();
if (Config.CurrentConfig.LogsDestinataires == null)
Config.CurrentConfig.LogsDestinataires = new SerializableDictionary<Board, bool>();
_configFunctions = new Dictionary<CheckedListBox, Dictionary<UdpFrameFunction, bool>>();
_configFunctions.Add(lstRecIOFunctions, Config.CurrentConfig.LogsFonctionsIO);
_configFunctions.Add(lstRecMoveFunctions, Config.CurrentConfig.LogsFonctionsMove);
_configFunctions.Add(lstRecGoBotFunctions, Config.CurrentConfig.LogsFonctionsGB);
_configFunctions.Add(lstRecCanFunctions, Config.CurrentConfig.LogsFonctionsCan);
_lstFunctions = new Dictionary<Board, CheckedListBox>();
_lstFunctions.Add(Board.RecIO, lstRecIOFunctions);
_lstFunctions.Add(Board.RecMove, lstRecMoveFunctions);
_lstFunctions.Add(Board.RecCan, lstRecCanFunctions);
foreach (CheckedListBox lst in _configFunctions.Keys)
{
// L'ajout de champs déclenche le SetCheck event qui ajoute les éléments automatiquement dans le dictionnaire
foreach (UdpFrameFunction func in Enum.GetValues(typeof(UdpFrameFunction)))
{
if (!_configFunctions[lst].ContainsKey(func))
_configFunctions[lst].Add(func, true);
lst.Items.Add(func.ToString(), _configFunctions[lst][func]);
}
}
foreach (Board board in Enum.GetValues(typeof(Board)))
{
if (!Config.CurrentConfig.LogsExpediteurs.ContainsKey(board))
Config.CurrentConfig.LogsExpediteurs.Add(board, true);
lstSender.Items.Add(board.ToString(), Config.CurrentConfig.LogsExpediteurs[board]);
if (!Config.CurrentConfig.LogsDestinataires.ContainsKey(board))
Config.CurrentConfig.LogsDestinataires.Add(board, true);
lstReceiver.Items.Add(board.ToString(), Config.CurrentConfig.LogsDestinataires[board]);
}
_loading = false;
_log = new FramesLog();
}
#region Publiques
public void Clear()
{
_log = new FramesLog();
}
public void DisplayFrame(TimedFrame tFrame)
{
String time = "";
try
{
if (rdoTimeAbsolute.Checked)
time = tFrame.Date.ToString("hh:mm:ss:fff");
if (rdoTimeFromStart.Checked)
time = (tFrame.Date - _startTime).ToString(@"hh\:mm\:ss\:fff");
if (rdoTimeFromPrev.Checked)
time = ((int)(tFrame.Date - _previousTime).TotalMilliseconds).ToString() + " ms";
if (rdoTimeFromPrevDisplay.Checked)
time = ((int)(tFrame.Date - _previousDisplayTime).TotalMilliseconds).ToString() + " ms";
Board board = UdpFrameFactory.ExtractBoard(tFrame.Frame);
Board sender = UdpFrameFactory.ExtractSender(tFrame.Frame, tFrame.IsInputFrame);
Board receiver = UdpFrameFactory.ExtractReceiver(tFrame.Frame, tFrame.IsInputFrame);
UdpFrameFunction func = UdpFrameFactory.ExtractFunction(tFrame.Frame);
if (board == Board.PC) throw new Exception();
bool receiverVisible = Config.CurrentConfig.LogsDestinataires[receiver];
bool senderVisible = Config.CurrentConfig.LogsExpediteurs[sender];
bool functionVisible = (_configFunctions[_lstFunctions[board]][func]);
if (senderVisible && receiverVisible && functionVisible)
{
dgvLog.Rows.Add(_counter, time, sender.ToString(), receiver.ToString(), UdpFrameDecoder.Decode(tFrame.Frame), tFrame.Frame.ToString());
_previousDisplayTime = tFrame.Date;
if (rdoColorByBoard.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[board];
else if (rdoColorByReceiver.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[receiver];
else if (rdoColorBySender.Checked)
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = _boardColor[sender];
}
}
catch (Exception)
{
dgvLog.Rows.Add(_counter, time, "?", "?", "Inconnu !", tFrame.Frame.ToString());
dgvLog.Rows[dgvLog.Rows.Count - 1].DefaultCellStyle.BackColor = Color.Red;
}
_counter++;
_previousTime = tFrame.Date;
}
public void DisplayLog()
{
try
{
dgvLog.Rows.Clear();
if (_log.Frames.Count > 0)
{
_startTime = _log.Frames[0].Date;
_previousTime = _log.Frames[0].Date;
_previousDisplayTime = _log.Frames[0].Date;
_counter = 0;
for (int iFrame = 0; iFrame < _log.Frames.Count; iFrame++)
DisplayFrame(_log.Frames[iFrame]);
}
}
catch (Exception)
{
MessageBox.Show("Impossible de décoder toutes les trames contenues dans ce fichier.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void LoadLog()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Fichiers replay trames (*" + FramesLog.FileExtension + ")| *" + FramesLog.FileExtension + "";
open.Multiselect = true;
if (open.ShowDialog() == DialogResult.OK)
{
foreach (String fichier in open.FileNames)
{
LoadLog(fichier);
}
_log.Sort();
DisplayLog();
}
}
public void LoadLog(String file)
{
FramesLog log = new FramesLog();
log.Import(file);
foreach (TimedFrame t in log.Frames)
_log.Frames.Add(t);
}
#endregion
#region Privées
private void EnableAllCheckBoxes(bool enable)
{
for (int iList = 0; iList < _boxLists.Count; iList++)
for (int iItem = 0; iItem < _boxLists[iList].Items.Count; iItem++)
_boxLists[iList].SetItemChecked(iItem, enable);
}
private TimedFrame GetFrameFromLine(DataGridViewRow line)
{
return _log.Frames[Convert.ToInt32(dgvLog["ID", line.Index].Value)];
}
private void ShowFramesReceiver(Board board, bool show)
{
lstReceiver.Items.Remove(board.ToString());
lstReceiver.Items.Add(board.ToString(), show);
Config.CurrentConfig.LogsDestinataires[board] = show;
}
private void ShowFramesSender(Board board, bool show)
{
lstSender.Items.Remove(board.ToString());
lstSender.Items.Add(board.ToString(), show);
Config.CurrentConfig.LogsExpediteurs[board] = show;
}
private void ShowFrameFunction(Board board, UdpFrameFunction func, bool show)
{
_lstFunctions[board].Items.Remove(func.ToString());
_lstFunctions[board].Items.Add(func.ToString(), show);
_configFunctions[_lstFunctions[board]][func] = show;
}
private FramesLog CreateLogFromSelection()
{
FramesLog logSelection = new FramesLog();
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame trameReplay = GetFrameFromLine(line);
logSelection.AddFrame(trameReplay.Frame, trameReplay.IsInputFrame, trameReplay.Date);
}
return logSelection;
}
private void ReplayLog(FramesLog log)
{
_thReplay = new Thread(_log.ReplayInputFrames);
_thReplay.Start();
}
#endregion
#region Events
private void btnReplayAll_Click(object sender, EventArgs e)
{
ReplayLog(_log);
}
private void btnReplaySelected_Click(object sender, EventArgs e)
{
ReplayLog(CreateLogFromSelection());
}
private void lstSender_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
String boardStr = (String)lstSender.Items[e.Index];
Board board = (Board)Enum.Parse(typeof(Board), boardStr);
Config.CurrentConfig.LogsExpediteurs[board] = (e.NewValue == CheckState.Checked);
}
}
private void lstReceiver_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
String boardStr = (String)lstReceiver.Items[e.Index];
Board board = (Board)Enum.Parse(typeof(Board), boardStr);
Config.CurrentConfig.LogsDestinataires[board] = (e.NewValue == CheckState.Checked);
}
}
private void lstFunctions_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (!Execution.DesignMode && !_loading)
{
CheckedListBox lst = (CheckedListBox)sender;
String funcStr = (String)lst.Items[e.Index];
UdpFrameFunction func = (UdpFrameFunction)Enum.Parse(typeof(UdpFrameFunction), funcStr);
_configFunctions[lst][func] = (e.NewValue == CheckState.Checked);
}
}
private void mnuHideSameSenderFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFramesSender(UdpFrameFactory.ExtractSender(tFrame.Frame, tFrame.IsInputFrame), false);
}
DisplayLog();
}
}
private void mnuHideSameReceiverFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFramesReceiver(UdpFrameFactory.ExtractReceiver(tFrame.Frame, tFrame.IsInputFrame), false);
}
DisplayLog();
}
}
private void mnuHideSameBoardFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
Board board = UdpFrameFactory.ExtractBoard(GetFrameFromLine(line).Frame);
ShowFramesReceiver(board, false);
ShowFramesSender(board, false);
}
DisplayLog();
}
}
private void mnuHideAllFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.Rows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFrameFunction(UdpFrameFactory.ExtractBoard(tFrame.Frame), UdpFrameFactory.ExtractFunction(tFrame.Frame), false);
}
DisplayLog();
}
}
private void mnuFrameCopy_Click(object sender, EventArgs e)
{
if (dgvLog.Rows.Count > 0)
Clipboard.SetText(GetFrameFromLine(dgvLog.SelectedRows[0]).Frame.ToString());
}
private void btnAllCheck_Click(object sender, EventArgs e)
{
EnableAllCheckBoxes(true);
}
private void btnAllUncheck_Click(object sender, EventArgs e)
{
EnableAllCheckBoxes(false);
}
private void btnRefresh_Click(object sender, EventArgs e)
{
DisplayLog();
}
private void dgvLog_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right && e.RowIndex > 0 && e.ColumnIndex > 0)
dgvLog.CurrentCell = dgvLog.Rows[e.RowIndex].Cells[e.ColumnIndex];
}
private void mnuHideSameTypeFrames_Click(object sender, EventArgs e)
{
if (dgvLog.SelectedRows.Count >= 1)
{
foreach (DataGridViewRow line in dgvLog.SelectedRows)
{
TimedFrame tFrame = GetFrameFromLine(line);
ShowFrameFunction(UdpFrameFactory.ExtractBoard(tFrame.Frame), UdpFrameFactory.ExtractFunction(tFrame.Frame), false);
}
DisplayLog();
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
if (_displayTimer == null || !_displayTimer.Enabled)
{
_log = new FramesLog();
_displayTimer = new System.Windows.Forms.Timer();
_displayTimer.Interval = 1000;
_displayTimer.Tick += displayTimer_Tick;
_displayTimer.Start();
Connections.AllConnections.ForEach(conn =>
{
if (conn.GetType() == typeof(UDPConnection))
{
conn.FrameReceived += new Connection.NewFrameDelegate((frame) => _log.AddFrame(frame, true));
conn.FrameSend += new Connection.NewFrameDelegate((frame) => _log.AddFrame(frame, false));
}
});
btnReplayAll.Enabled = false;
btnReplaySelected.Enabled = false;
btnLoad.Enabled = false;
btnDisplay.Text = "Arrêter la surveillance";
btnDisplay.Image = Properties.Resources.GlassPause48;
}
else
{
_displayTimer.Stop();
Connections.AllConnections.ForEach(conn =>
{
if (conn.GetType() == typeof(UDPConnection))
{
conn.FrameReceived -= new Connection.NewFrameDelegate((frame) => _log.AddFrame(frame, true));
conn.FrameSend -= new Connection.NewFrameDelegate((frame) => _log.AddFrame(frame, false));
}
});
btnReplayAll.Enabled = true;
btnReplaySelected.Enabled = true;
btnLoad.Enabled = true;
btnDisplay.Text = "Lancer la surveillance";
btnDisplay.Image = Properties.Resources.GlassStart48;
}
}
void displayTimer_Tick(object sender, EventArgs e)
{
int nbTrames = _log.Frames.Count;
for (int i = _counter; i < nbTrames; i++)
DisplayFrame(_log.Frames[i]);
if (boxScroll.Checked && dgvLog.Rows.Count > 10)
dgvLog.FirstDisplayedScrollingRowIndex = dgvLog.RowCount - 1;
}
private void btnLoad_Click(object sender, EventArgs e)
{
LoadLog();
}
#endregion
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/PepperlConst.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Devices
{
public class PepperlConst
{
public const String CmdReboot = "reboot_device";
public const String CmfFactoryReset = "factory_reset";
public const String CmdHandleUdp = "request_handle_udp";
public const String CmdHandleTcp = "request_handle_tcp";
public const String CmdProtocolInfo = "get_protocol_info";
public const String CmdFeedWatchdog = "feed_watchdog";
public const String CmdListParameters = "list_parameters";
public const String CmdGetParameter = "get_parameter";
public const String CmdSetParameter = "set_parameter";
public const String CmdResetParameter = "reset_parameter";
public const String CmdReleaseHandle = "release_handle";
public const String CmdStartScan = "start_scanoutput";
public const String CmdStopScan = "stop_scanoutput";
public const String CmdGetScanConfig = "get_scanoutput_config";
public const String CmdSetScanConfig = "set_scanoutput_config";
public const String ParamVendor = "vendor";
public const String ParamProduct = "product";
public const String ParamPart = "part";
public const String ParamSerial = "serial";
public const String ParamRevisionFw = "revision_fw";
public const String ParamRevisionHw = "revision_hw";
public const String ParamMaxConnections = "max_connections";
public const String ParamFeatureFlags = "feature_flags";
public const String ParamRadialRangeMin = "radial_range_min";
public const String ParamRadialRangeMax = "radial_range_max";
public const String ParamRadialResolution = "radial_resolution";
public const String ParamAngularFov = "angular_fov";
public const String ParamAngularResolution = "angular_resolution";
public const String ParamScanFrequencyMin = "scan_frequency_min";
public const String ParamScanFrequencyMax = "scan_frequency_max";
public const String ParamSamplingRateMin = "sampling_rate_min";
public const String ParamSamplingRateMax = "sampling_rate_max";
public const String ParamSamplesPerScan = "samples_per_scan";
public const String ParamScanFrequencyMeasured = "scan_frequency_measured";
public const String ParamStatusFlags = "status_flags";
public const String ParamLoadIndication = "load_indication";
public const String ParamDeviceFamily = "device_family";
public const String ParamMacAddress = "mac_address";
public const String ParamIpModeCurrent = "ip_mode_current";
public const String ParamIpAddressCurrent = "ip_address_current";
public const String ParamSubnetMaskCurrent = "subnet_mask_current";
public const String ParamGatewayCurrent = "gateway_current";
public const String ParamSystemTimeRaw = "system_time_raw";
public const String ParamUserTag = "user_tag";
public const String ParamUserNotes = "user_notes";
public const String ParamEmitterType = "emitter_type";
public const String ParamUptime = "up_time";
public const String ParamPowerCycles = "power_cycles";
public const String ParamOperationTime = "operation_time";
public const String ParamOperationTimeScaled = "operation_time_scaled";
public const String ParamTemperatureCurrent = "temperature_current";
public const String ParamTemperatureMin = "temperature_min";
public const String ParamTemperatureMax = "temperature_max";
public const String ParamHmiHardBitmap = "hmi_static_logo";
public const String ParamHmiSoftBitmap = "hmi_application_bitmap";
public const String ParamHmiHardText1 = "hmi_static_text_1";
public const String ParamHmiHardText2 = "hmi_static_text_2";
public const String ParamHmiSoftText1 = "hmi_application_text_1";
public const String ParamHmiSoftText2 = "hmi_application_text_2";
public const String ParamFilterWidth = "filter_width";
public const String ParamFilterMaximumMargin = "filter_maximum_margin";
public const String ParamUdpAddress = "address";
public const String ParamUdpPort = "port";
public const String ParamUdpWatchdogTimeout = "watchdogtimeout";
public const String ParamUdpPacketCrc = "packet_crc";
public const String ParamUdpStartAngle = "start_angle";
public const String ParamUdpPointsCount = "max_num_points_scan";
public const String ParamUdpSkipScans = "skip_scans";
public const String ParamUdpHandle = "handle";
public const String ParamTcpAddress = "address";
public const String ParamTcpPort = "port";
public const String ParamTcpPacketCrc = "packet_crc";
public const String ParamTcpStartAngle = "start_angle";
public const String ParamTcpPointsCount = "max_num_points_scan";
public const String ParamTcpSkipScans = "skip_scans";
public const String ParamTcpHandle = "handle";
public const String ParamProtocolName = "protocol_name";
public const String ParamProtocolVersionMajor = "version_major";
public const String ParamProtocolVersionMinor = "version_minor";
public const String ParamProtocolCommands = "commands";
public const String ParamErrorCode = "error_code";
public const String ParamErrorText = "error_text";
public const String ParamContaminationDetectionWarnings = "lcm_sector_warn_flags";
public const String ParamContaminationDetectionErrors = "lcm_sector_error_flags";
public const String ParamContaminationDetectionPeriod = "lcm_detection_period";
public const String ParamFeedWatchdogHandle = "handle";
public const String ParamUdpWatchdog = "watchdog";
public const String ValueUdpWatchdogOn = "on";
public const String ValueUdpWatchdogOff = "off";
public const String ParamTcpWatchdog = "watchdog";
public const String ValueTcpWatchdogOn = "on";
public const String ValueTcpWatchdogOff = "off";
public const String ParamIpMode = "ip_mode";
public const String ValueIpModeStatic = "static";
public const String ValueIpModeAuto = "autoip";
public const String ValueIpModeDhcp = "dhcp";
public const String ParamIpAddress = "ip_address";
public const String ParamSubnetMask = "subnet_mask";
public const String ParamGateway = "gateway";
public const String ParamScanFrequency = "scan_frequency";
public const String ParamScanDirection = "scan_direction";
public const String ValueScanDirectionClockwise = "cw";
public const String ValueScanDirectionCounterClockwise = "ccw";
public const String ParamHmiMode = "hmi_display_mode";
public const String ValueHmiModeOff = "off";
public const String ValueHmiModeHardLogo = "static_logo";
public const String ValueHmiModeHardText = "static_text";
public const String ValueHmiModeBargraphDistance = "bargraph_distance";
public const String ValueHmiModeBargraphEcho = "bargraph_echo";
public const String ValueHmiModeBargraphReflector = "bargraph_reflector";
public const String ValueHmiModeSoftBitmap = "application_bitmap";
public const String ValueHmiModeSoftText = "application_text";
public const String ParamHmiLanguage = "hmi_language";
public const String ValueHmiLanguageEnglish = "engligh";
public const String ValueHmiLanguageGerman = "german";
public const String ParamHmiButtonLock = "hmi_button_lock";
public const String ValueHmiButtonLockOn = "on";
public const String ValueHmiButtonLockOff = "off";
public const String ParamHmiParameterLock = "hmi_parameter_lock";
public const String ValueHmiParameterLockOn = "on";
public const String ValueHmiParameterLockOff = "off";
public const String ParamLocatorIndication = "locator_indication";
public const String ValueLocatorIndicationLockOn = "on";
public const String ValueLocatorIndicationOff = "off";
public const String ParamOperatingMode = "operating_mode";
public const String ValueOperatingModeMeasure = "measure";
public const String ValueOperatingModeOff = "emitter_off";
public const String ParamFilterType = "filter_type";
public const String ValueFilterTypeNone = "none";
public const String ValueFilterTypeAverage = "average";
public const String ValueFilterTypeMedian = "median";
public const String ValueFilterTypeMaximum = "maximum";
public const String ValueFilterTypeRemission = "remission";
public const String ParamFilterErrorHandling = "filter_error_handling";
public const String ValueFilterErrorHandlingStrict = "strict";
public const String ValueFilterErrorHandlingTolerant = "tolerant";
public const String ParamFilterRemissionThreshold = "filter_remission_threshold";
public const String ValueFilterRemissionThresholdDiffuseLow = "diffuse_low";
public const String ValueFilterRemissionThresholdDiffuseHigh = "diffuse_high";
public const String ValueFilterRemissionThresholdReflectorMin = "reflector_min";
public const String ValueFilterRemissionThresholdReflectorLow = "reflector_low";
public const String ValueFilterRemissionThresholdReflectorStd = "reflector_std";
public const String ValueFilterRemissionThresholdReflectorHigh = "reflector_high";
public const String ValueFilterRemissionThresholdReflectorMax = "reflector_max";
public const String ParamUdpPacketType = "packet_type";
public const String ValueUdpPacketTypeDistance = "A";
public const String ValueUdpPacketTypeDistanceAmplitude = "B";
public const String ValueUdpPacketTypeDistanceAmplitudeCompact = "C";
public const String ParamTcpWatchdogTimeout = "watchdogtimeout";
public const String ParamTcpPacketType = "packet_type";
public const String ValueTcpPacketTypeDistance = "A";
public const String ValueTcpPacketTypeDistanceAmplitude = "B";
public const String ValueTcpPacketTypeDistanceAmplitudeCompact = "C";
public const String ParamContaminationDetectionSensivity = "lcm_detection_sensitivity";
public const String ValueContaminationDetectionSensivityDisabled = "disabled";
public const String ValueContaminationDetectionSensivityLow = "low";
public const String ValueContaminationDetectionSensivityMedium = "medium";
public const String ValueContaminationDetectionSensivityHigh = "high";
public const String ParamContaminationDetectionSectorEnable = "lcm_sector_enable";
public const String ValueContaminationDetectionSectorEnableOn = "on";
public const String ValueContaminationDetectionSectorEnableOff = "off";
public const int FlagStatusInitialization = 1 << 00;
public const int FlagStatusscanOutputMuted = 1 << 02;
public const int FlagStatusUnstableRotation = 1 << 03;
public const int FlagStatusDeviceWarning = 1 << 08;
public const int FlagStatusLensContaminationWarning = 1 << 09;
public const int FlagStatusLowTemperatureWarning = 1 << 10;
public const int FlagStatusHighTemperatureWarning = 1 << 11;
public const int FlagStatusDeviceOverloadWarning = 1 << 12;
public const int FlagStatusDeviceError = 1 << 16;
public const int FlagStatusLensContaminationError = 1 << 17;
public const int FlagStatusLowTemperatureError = 1 << 18;
public const int FlagStatusHighTemperatureError = 1 << 19;
public const int FlagStatusDeviceOverloadError = 1 << 20;
public const int FlagStatusDeviceDefect = 1 << 30;
public const int ErrorSuccess = 0;
public const int ErrorUnknownArgument = 100;
public const int ErrorUnknownParameter = 110;
public const int ErrorInvalidHandle = 120;
public const int ErrorArgumentMissing = 130;
public const int ErrorInvalidValue = 200;
public const int ErrorOutOfRangeValue = 210;
public const int ErrorReadOnly = 220;
public const int ErrorMemory = 230;
public const int ErrorAlreadyInUse = 240;
public const int ErrorInternal = 333;
}
}
<file_sep>/GoBot/GoBot/Actions/Deplacement/ActionRecule.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Actions
{
class ActionRecule : ITimeableAction
{
private int distance;
private Robot robot;
public ActionRecule(Robot r, int dist)
{
robot = r;
distance = dist;
}
System.Drawing.Image IAction.Image
{
get { return GoBot.Properties.Resources.DownGreen16; }
}
public override String ToString()
{
return robot.Name + " recule de " + distance + "mm";
}
void IAction.Executer()
{
robot.MoveBackward(distance);
}
public TimeSpan Duration
{
get
{
return robot.SpeedConfig.LineDuration(distance);
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Pages/PageRobot.cs
using System;
using System.Windows.Forms;
namespace GoBot.IHM.Pages
{
public partial class PageRobot : UserControl
{
public PageRobot()
{
InitializeComponent();
}
public void Init()
{
panelDisplacement.Robot = Robots.MainRobot;
panelDisplacement.Init();
}
private void btnClose_Click(object sender, EventArgs e)
{
Config.Save();
Control parent = Parent;
while (parent.Parent != null)
parent = parent.Parent;
if (parent != null)
parent.Dispose();
}
private void rdoMainRobot_CheckedChanged(object sender, EventArgs e)
{
if (Config.CurrentConfig.IsMiniRobot != !rdoMainRobot.Checked)
{
Config.CurrentConfig.IsMiniRobot = !rdoMainRobot.Checked;
Robots.Init();
}
}
private void PageRobot_Load(object sender, EventArgs e)
{
rdoMainRobot.Checked = !Config.CurrentConfig.IsMiniRobot;
rdoSecondaryRobot.Checked = Config.CurrentConfig.IsMiniRobot;
}
}
}
<file_sep>/GoBot/GoBot/IHM/PanelTestLiaisons.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GoBot.Communications;
using System.Threading;
namespace GoBot.IHM
{
public partial class PanelTestLiaisons : UserControl
{
List<LiaisonDataCheck> Liaisons { get; set; }
System.Windows.Forms.Timer Timer { get; set; }
System.Windows.Forms.Timer TimerIhm { get; set; }
public PanelTestLiaisons()
{
InitializeComponent();
Timer = null;
}
private void btnStart_Click(object sender, EventArgs e)
{
if (Timer == null)
{
Liaisons = new List<LiaisonDataCheck>();
Liaisons.Add(new LiaisonDataCheck(Connexions.ConnexionBun, Carte.RecBun, false));
Liaisons.Add(new LiaisonDataCheck(Connexions.ConnexionBeu, Carte.RecBeu, false));
Liaisons.Add(new LiaisonDataCheck(Connexions.ConnexionBoi, Carte.RecBoi, false));
Liaisons.Add(new LiaisonDataCheck(Connexions.ConnexionPi, Carte.RecPi, true));
Connexions.ConnexionMiwi.NouvelleTrameRecue += Liaisons[0].MessageRecu;
Connexions.ConnexionMiwi.NouvelleTrameRecue += Liaisons[1].MessageRecu;
Connexions.ConnexionMiwi.NouvelleTrameRecue += Liaisons[2].MessageRecu;
Connexions.ConnexionMiwi.NouvelleTrameRecue += Liaisons[3].MessageRecu;
Timer = new System.Windows.Forms.Timer();
Timer.Interval = (int)numIntervalle.Value;
Timer.Tick += new EventHandler(Timer_Tick);
TimerIhm = new System.Windows.Forms.Timer();
TimerIhm.Interval = 1000;
TimerIhm.Tick += new EventHandler(TimerIhm_Tick);
btnStart.Text = "Stop";
btnStart.Image = GoBot.Properties.Resources.Pause;
numIntervalle.Enabled = false;
Timer.Start();
TimerIhm.Start();
}
else
{
Timer.Stop();
Timer = null;
TimerIhm.Stop();
btnStart.Text = "Lancer";
numIntervalle.Enabled = true;
btnStart.Image = GoBot.Properties.Resources.Play;
}
}
void TimerIhm_Tick(object sender, EventArgs e)
{
this.Invoke(new EventHandler(delegate
{
lblB1Nombre.Text = Liaisons[0].NombreMessagesTotal.ToString();
if (Liaisons[0].NombreMessagesTotal > 0)
{
lblB1Corrects.Text = Liaisons[0].NombreMessagesCorrects + " - " + (Liaisons[0].NombreMessagesCorrects * 100.0 / (double)Liaisons[0].NombreMessagesTotal).ToString("#.##") + "%";
lblB1CorrompusEmission.Text = Liaisons[0].NombreMessagesCorrompusEmission + " - " + (Liaisons[0].NombreMessagesCorrompusEmission * 100.0 / (double)Liaisons[0].NombreMessagesTotal).ToString("#.##") + "%";
lblB1CorrompusReception.Text = Liaisons[0].NombreMessagesCorrompusReception + " - " + (Liaisons[0].NombreMessagesCorrompusReception * 100.0 / (double)Liaisons[0].NombreMessagesTotal).ToString("#.##") + "%";
lblB1PerdusEmission.Text = Liaisons[0].NombreMessagesPerdusEmission + " - " + (Liaisons[0].NombreMessagesPerdusEmission * 100.0 / (double)Liaisons[0].NombreMessagesTotal).ToString("#.##") + "%";
lblB1PerdusReception.Text = Liaisons[0].NombreMessagesPerdusReception + " - " + (Liaisons[0].NombreMessagesPerdusReception * 100.0 / (double)Liaisons[0].NombreMessagesTotal).ToString("#.##") + "%";
}
lblB2Nombre.Text = Liaisons[1].NombreMessagesTotal.ToString();
if (Liaisons[1].NombreMessagesTotal > 0)
{
lblB2Corrects.Text = Liaisons[1].NombreMessagesCorrects + " - " + (Liaisons[1].NombreMessagesCorrects * 100.0 / (double)Liaisons[1].NombreMessagesTotal).ToString("#.##") + "%";
lblB2CorrompusEmission.Text = Liaisons[1].NombreMessagesCorrompusEmission + " - " + (Liaisons[1].NombreMessagesCorrompusEmission * 100.0 / (double)Liaisons[1].NombreMessagesTotal).ToString("#.##") + "%";
lblB2CorrompusReception.Text = Liaisons[1].NombreMessagesCorrompusReception + " - " + (Liaisons[1].NombreMessagesCorrompusReception * 100.0 / (double)Liaisons[1].NombreMessagesTotal).ToString("#.##") + "%";
lblB2PerdusEmission.Text = Liaisons[1].NombreMessagesPerdusEmission + " - " + (Liaisons[1].NombreMessagesPerdusEmission * 100.0 / (double)Liaisons[1].NombreMessagesTotal).ToString("#.##") + "%";
lblB2PerdusReception.Text = Liaisons[1].NombreMessagesPerdusReception + " - " + (Liaisons[1].NombreMessagesPerdusReception * 100.0 / (double)Liaisons[1].NombreMessagesTotal).ToString("#.##") + "%";
}
lblB3Nombre.Text = Liaisons[2].NombreMessagesTotal.ToString();
if (Liaisons[2].NombreMessagesTotal > 0)
{
lblB3Corrects.Text = Liaisons[2].NombreMessagesCorrects + " - " + (Liaisons[2].NombreMessagesCorrects * 100.0 / (double)Liaisons[2].NombreMessagesTotal).ToString("#.##") + "%";
lblB3CorrompusEmission.Text = Liaisons[2].NombreMessagesCorrompusEmission + " - " + (Liaisons[2].NombreMessagesCorrompusEmission * 100.0 / (double)Liaisons[2].NombreMessagesTotal).ToString("#.##") + "%";
lblB3CorrompusReception.Text = Liaisons[2].NombreMessagesCorrompusReception + " - " + (Liaisons[2].NombreMessagesCorrompusReception * 100.0 / (double)Liaisons[2].NombreMessagesTotal).ToString("#.##") + "%";
lblB3PerdusEmission.Text = Liaisons[2].NombreMessagesPerdusEmission + " - " + (Liaisons[2].NombreMessagesPerdusEmission * 100.0 / (double)Liaisons[2].NombreMessagesTotal).ToString("#.##") + "%";
lblB3PerdusReception.Text = Liaisons[2].NombreMessagesPerdusReception + " - " + (Liaisons[2].NombreMessagesPerdusReception * 100.0 / (double)Liaisons[2].NombreMessagesTotal).ToString("#.##") + "%";
}
lblPRNombre.Text = Liaisons[3].NombreMessagesTotal.ToString();
if (Liaisons[3].NombreMessagesTotal > 0)
{
lblPRCorrects.Text = Liaisons[3].NombreMessagesCorrects + " - " + (Liaisons[3].NombreMessagesCorrects * 100.0 / (double)Liaisons[3].NombreMessagesTotal).ToString("#.##") + "%";
lblPRCorrompusEmission.Text = Liaisons[3].NombreMessagesCorrompusEmission + " - " + (Liaisons[3].NombreMessagesCorrompusEmission * 100.0 / (double)Liaisons[3].NombreMessagesTotal).ToString("#.##") + "%";
lblPRCorrompusReception.Text = Liaisons[3].NombreMessagesCorrompusReception + " - " + (Liaisons[3].NombreMessagesCorrompusReception * 100.0 / (double)Liaisons[3].NombreMessagesTotal).ToString("#.##") + "%";
lblPRPerdusEmission.Text = Liaisons[3].NombreMessagesPerdusEmission + " - " + (Liaisons[3].NombreMessagesPerdusEmission * 100.0 / (double)Liaisons[3].NombreMessagesTotal).ToString("#.##") + "%";
lblPRPerdusReception.Text = Liaisons[3].NombreMessagesPerdusReception + " - " + (Liaisons[3].NombreMessagesPerdusReception * 100.0 / (double)Liaisons[3].NombreMessagesTotal).ToString("#.##") + "%";
}
}));
}
void Timer_Tick(object sender, EventArgs e)
{
//for (int i = 0; i < Liaisons.Count; i++)
// Liaisons[i].EnvoiTest();
Liaisons[0].EnvoiTest();
if (Liaisons[0].IDTestEmissionActuel == 255)
{
btnStart_Click(null, null);
Thread.Sleep(1000);
}
}
}
}
<file_sep>/GoBot/Geometry/AngleDelta.cs
using System;
namespace Geometry
{
public struct AngleDelta
{
#region Constantes
public const double PRECISION = 0.01;
#endregion
#region Attributs
private double _angle;
#endregion
#region Constructeurs
/// <summary>
/// Construit un angle avec la valeur passée en paramètre
/// </summary>
/// <param name="angle">Angle de départ</param>
public AngleDelta(double angle, AngleType type = AngleType.Degre)
{
if (type == AngleType.Degre)
_angle = angle;
else
_angle = (180 * angle / Math.PI);
}
#endregion
/// <summary>
/// Minimize l'angle en considérant que la valeur doit se situer entre -180° et +180°.
/// Exemple : 370° est minimisé à 10°.
/// </summary>
public AngleDelta Modulo()
{
while (_angle > 180)
_angle -= 360;
while (_angle < -180)
_angle += 360;
return this;
}
#region Trigonométrie
public double Cos
{
get
{
return Math.Cos(InRadians);
}
}
public double Sin
{
get
{
return Math.Sin(InRadians);
}
}
public double Tan
{
get
{
return Math.Tan(InRadians);
}
}
#endregion
#region Proprietes
/// <summary>
/// Retourne l'angle en radians
/// </summary>
public double InRadians
{
get
{
return (double)(_angle / 180 * Math.PI);
}
}
/// <summary>
/// Retourne l'angle en degrés
/// </summary>
public double InDegrees
{
get
{
return _angle;
}
}
#endregion
#region Operateurs
public static AngleDelta operator +(AngleDelta a1, AngleDelta a2)
{
return new AngleDelta(a1.InDegrees + a2.InDegrees, AngleType.Degre);
}
public static AngleDelta operator -(AngleDelta a1, AngleDelta a2)
{
return new AngleDelta(a1.InDegrees - a2.InDegrees, AngleType.Degre);
}
public static bool operator ==(AngleDelta a1, AngleDelta a2)
{
return Math.Abs((a1 - a2).InDegrees) <= PRECISION;
}
public static bool operator !=(AngleDelta a1, AngleDelta a2)
{
return !(a1 == a2);
}
public static implicit operator AngleDelta(double angle)
{
return new AngleDelta(angle);
}
public static implicit operator double(AngleDelta angle)
{
return angle.InDegrees;
}
#endregion
#region Overrides
public override bool Equals(object obj)
{
try
{
return Math.Abs(((AngleDelta)obj)._angle - _angle) < PRECISION;
}
catch
{
return false;
}
}
public override int GetHashCode()
{
return (int)(_angle * (1 / PRECISION));
}
public override string ToString()
{
return _angle.ToString("0.00") + "°";
}
#endregion
}
}<file_sep>/GoBot/Geometry/Shapes/Segment.cs
using Geometry.Shapes.ShapesInteractions;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Geometry.Shapes
{
// Un segment est une Droite avec deux extrémités
public class Segment : Line, IShapeModifiable<Segment>
{
#region Attributs
protected RealPoint _startPoint, _endPoint;
#endregion
#region Constructeurs
public Segment(RealPoint start, RealPoint end)
{
_startPoint = new RealPoint(start);
_endPoint = new RealPoint(end);
SetLine(StartPoint, EndPoint);
}
public Segment(Segment segment)
{
_startPoint = new RealPoint(segment.StartPoint);
_endPoint = new RealPoint(segment.EndPoint);
_a = segment.A;
_b = segment.B;
_c = segment.C;
SetLine(StartPoint, EndPoint);
}
#endregion
#region Propriétés
/// <summary>
/// Obtient la 1ère extremité du segment
/// </summary>
public RealPoint StartPoint
{
get
{
return _startPoint;
}
set
{
_startPoint = value;
SetLine(StartPoint, EndPoint);
}
}
/// <summary>
/// Obtient la 2ème extremité du segment
/// </summary>
public RealPoint EndPoint
{
get
{
return _endPoint;
}
set
{
_endPoint = value;
SetLine(StartPoint, EndPoint);
}
}
/// <summary>
/// Obtient la longueur du segment
/// </summary>
public Double Length
{
get
{
return StartPoint.Distance(EndPoint);
}
}
/// <summary>
/// Obtient la droite sur laquelle le segment se trouve
/// </summary>
public Line Line
{
get
{
return new Line(this);
}
}
/// <summary>
/// Obtient la surface du segment
/// </summary>
public override double Surface
{
get
{
return 0;
}
}
/// <summary>
/// Obtient le barycentre du segment
/// </summary>
public override RealPoint Barycenter
{
get
{
return new RealPoint((_startPoint.X + _endPoint.X) / 2, (_startPoint.Y + _endPoint.Y) / 2);
}
}
#endregion
#region Opérateurs & Surcharges
public static bool operator ==(Segment a, Segment b)
{
if ((object)a == null || (object)b == null)
return (object)a == null && (object)b == null;
else
return a.A == b.A
&& a.B == b.B
&& a.C == a.C
&& a.StartPoint == b.StartPoint
&& a.EndPoint == b.StartPoint;
}
public static bool operator !=(Segment a, Segment b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
Segment p = obj as Segment;
if ((Object)p == null)
{
return false;
}
return (Segment)obj == this;
}
public override int GetHashCode()
{
return (int)StartPoint.X ^ (int)StartPoint.Y ^ (int)EndPoint.X ^ (int)EndPoint.Y;
}
public override string ToString()
{
return StartPoint + " -> " + EndPoint;
}
#endregion
#region Croisements
/// <summary>
/// Retourne la liste des points de croisement avec la forme donnée
/// </summary>
/// <param name="shape">Forme à tester</param>
/// <returns>Liste des points de croisement</returns>
public override List<RealPoint> GetCrossingPoints(IShape shape)
{
List<RealPoint> output = new List<RealPoint>();
if (shape is RealPoint) output = SegmentWithRealPoint.GetCrossingPoints(this, shape as RealPoint);
else if (shape is Segment) output = SegmentWithSegment.GetCrossingPoints(this, shape as Segment);
else if (shape is Polygon) output = SegmentWithPolygon.GetCrossingPoints(this, shape as Polygon);
else if (shape is Circle) output = SegmentWithCircle.GetCrossingPoints(this, shape as Circle);
else if (shape is Line) output = SegmentWithLine.GetCrossingPoints(this, shape as Line);
return output;
}
private List<RealPoint> GetCrossingPointsWithPolygon(Polygon polygon)
{
return polygon.GetCrossingPoints(this); // Le polygone sait faire
}
/// <summary>
/// Teste si le segment courant croise la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si le segment croise la forme donnée</returns>
public override bool Cross(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = SegmentWithRealPoint.Cross(this, shape as RealPoint);
else if (shape is Segment) output = SegmentWithSegment.Cross(this, shape as Segment);
else if (shape is Polygon) output = SegmentWithPolygon.Cross(this, shape as Polygon);
else if (shape is Circle) output = SegmentWithCircle.Cross(this, shape as Circle);
else if (shape is Line) output = SegmentWithLine.Cross(this, shape as Line);
return output;
}
/// <summary>
/// Teste si le segment courant croise la droite donnée
/// </summary>
/// <param name="line">Droite testée</param>
/// <returns>Vrai si la segment contient la droite donnée</returns>
protected bool Cross(Line line)
{
return GetCrossingPoints(line).Count > 0;
}
/// <summary>
/// Teste si le segment courant croise le polygone donné
/// </summary>
/// <param name="polygon">Polygone testé</param>
/// <returns>Vrai si le segment croise le polygone donné</returns>
protected bool Cross(Polygon polygon)
{
return polygon.Cross(this);
}
#endregion
#region Contient
/// <summary>
/// Teste si le segment courant contient la forme donnée
/// </summary>
/// <param name="shape">Forme testée</param>
/// <returns>Vrai si le segment contient la forme donnée</returns>
public override bool Contains(IShape shape)
{
bool output = false;
if (shape is RealPoint) output = SegmentWithRealPoint.Contains(this, shape as RealPoint);
else if (shape is Segment) output = SegmentWithSegment.Contains(this, shape as Segment);
else if (shape is Polygon) output = SegmentWithPolygon.Contains(this, shape as Polygon);
else if (shape is Circle) output = SegmentWithCircle.Contains(this, shape as Circle);
else if (shape is Line) output = SegmentWithLine.Contains(this, shape as Line);
return output;
}
#endregion
#region Distance
public override double Distance(IShape shape)
{
double output = 0;
if (shape is RealPoint) output = SegmentWithRealPoint.Distance(this, shape as RealPoint);
else if (shape is Segment) output = SegmentWithSegment.Distance(this, shape as Segment);
else if (shape is Polygon) output = SegmentWithPolygon.Distance(this, shape as Polygon);
else if (shape is Circle) output = SegmentWithCircle.Distance(this, shape as Circle);
else if (shape is Line) output = SegmentWithLine.Distance(this, shape as Line);
return output;
}
/// <summary>
/// Retourne la distance minimale entre le segment courant et la droite donnée
/// </summary>
/// <param name="forme">Droite testée</param>
/// <returns>Distance minimale</returns>
public double Distance(Line line)
{
// Si la droite et le segment se croisent la distance est de 0
if (Cross(line))
return 0;
// Sinon c'est la distance minimale entre chaque extremité du segment et la droite
double minDistance = double.MaxValue;
minDistance = Math.Min(minDistance, line.Distance(StartPoint));
minDistance = Math.Min(minDistance, line.Distance(EndPoint));
return minDistance;
}
#endregion
#region Transformations
/// <summary>
/// Retourne un segment qui est translaté des distances données
/// </summary>
/// <param name="dx">Distance en X</param>
/// <param name="dy">Distance en Y</param>
/// <returns>Segment translaté des distances données</returns>
public new Segment Translation(double dx, double dy)
{
return new Segment(_startPoint.Translation(dx, dy), _endPoint.Translation(dx, dy));
}
/// <summary>
/// Retourne un segment qui est tournée de l'angle donné
/// </summary>
/// <param name="angle">Angle de rotation</param>
/// <param name="rotationCenter">Centre de rotation, si null (0, 0) est utilisé</param>
/// <returns>Segment tourné de l'angle donné</returns>
public new Segment Rotation(AngleDelta angle, RealPoint rotationCenter = null)
{
if (rotationCenter == null) rotationCenter = Barycenter;
return new Segment(_startPoint.Rotation(angle, rotationCenter), _endPoint.Rotation(angle, rotationCenter));
}
/// <summary>
/// Retourne un segment qui prolonge l'actuel en ajoutant un point.
/// Le résultat est valide uniquement si le point ajouté se trouve sur la droite formée par le segment.
/// </summary>
/// <param name="pt">Point à ajouter au segment</param>
/// <returns>Segment prolongé jusqu'au point donné</returns>
public Segment Join(RealPoint pt)
{
Segment s1 = new Segment(_startPoint, pt);
Segment s2 = new Segment(_endPoint, pt);
Segment res;
if (this.Contains(pt))
res = new Segment(this);
else if (s1.Contains(_endPoint))
res = s1;
else if (s2.Contains(_startPoint))
res = s2;
else
res = null;
return res;
}
#endregion
#region Peinture
/// <summary>
/// Peint le segment sur le Graphic donné
/// </summary>
/// <param name="g">Graphique sur lequel peindre</param>
/// <param name="outlineColor">Couleur du contour</param>
/// <param name="outlineWidth">Epaisseur du segment</param>
/// <param name="fillColor">Couleur de remplissage</param>
/// <param name="scale">Echelle de conversion</param>
public override void Paint(Graphics g, Pen outline, Brush fill, WorldScale scale)
{
Point startPoint = scale.RealToScreenPosition(StartPoint);
Point endPoint = scale.RealToScreenPosition(EndPoint);
if (outline != null)
g.DrawLine(outline, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y);
}
#endregion
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/LineWithSegment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class LineWithSegment
{
public static bool Contains(Line containingLine, Segment containedSegment)
{
// Contenir un segment revient à contenir la droite sur laquelle se trouve le segment
return LineWithLine.Contains(containingLine, containedSegment);
}
public static bool Cross(Line line, Segment segment)
{
// Pas trouvé plus simple
return GetCrossingPoints(line, segment).Count > 0;
}
public static double Distance(Line line, Segment segment)
{
double output;
if (Cross(line, segment))
{
// Si la droite et le segment se croisent la distance est de 0
output = 0;
}
else
{
// Sinon c'est la distance minimale entre chaque extremité du segment et la droite puisque c'est forcément un de ces deux points le plus proche
output = Math.Min(line.Distance(segment.StartPoint), line.Distance(segment.EndPoint));
}
return output;
}
public static List<RealPoint> GetCrossingPoints(Line line, Segment segment)
{
// Vérifie de la même manière qu'une droite mais vérifie ensuite que le point obtenu (s'il existe) appartient bien au segment
List<RealPoint> output = LineWithLine.GetCrossingPoints(line, segment);
if (output.Count > 0 && !segment.Contains(output[0]))
output.Clear();
return output;
}
}
}
<file_sep>/GoBot/GoBot/TestCode.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GoBot.Actions;
using System.Windows.Forms;
using GoBot.Communications;
using GoBot.Communications.UDP;
using System.Diagnostics;
namespace GoBot
{
public static class TestCode
{
public static void TestEnums()
{
StringBuilder errors = new StringBuilder();
errors.AppendLine("Les valeurs d'énumerations suivantes n'ont pas de traduction littérale dans le nommeur :");
bool error = false;
List<Type> typesEnum = new List<Type>();
typesEnum.Add(typeof(SensorOnOffID));
typesEnum.Add(typeof(ActuatorOnOffID));
typesEnum.Add(typeof(ServomoteurID));
typesEnum.Add(typeof(MotorID));
typesEnum.Add(typeof(CodeurID));
typesEnum.Add(typeof(SensorColorID));
typesEnum.Add(typeof(BaliseID));
typesEnum.Add(typeof(LidarID));
typesEnum.Add(typeof(UdpFrameFunction));
foreach (Type type in typesEnum)
{
foreach (var value in Enum.GetValues(type))
{
String result = NameFinder.GetNameUnknow((Convert.ChangeType(value, type)));
if (result == (Convert.ChangeType(value, type).ToString()) || result == "" || result == "Inconnu")
{
errors.Append("\t");
errors.Append(type.ToString());
errors.Append(".");
errors.AppendLine(Convert.ChangeType(value, type).ToString());
error = true;
}
}
}
if (error && Debugger.IsAttached)
{
Console.WriteLine(errors.ToString());
//MessageBox.Show(errors.ToString(), "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/PolygonWithSegment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class PolygonWithSegment
{
public static bool Contains(Polygon containingPolygon, Segment containedSegement)
{
// Il suffit de contenir les deux extrémités du segment et de ne jamais croiser le segment
// À part si le croisement se fait sur une extremité
bool result;
if (Cross(containingPolygon, containedSegement))
{
// Si ça se croise : ça peut encore être les extremités qui touchent
List<RealPoint> crossPoints = GetCrossingPoints(containingPolygon, containedSegement);
if (crossPoints.Count > 2)
{
// Plus de 2 croisements : le segment n'est pas contenu
result = false;
}
else
{
// Maximum 2 croisements (= les 2 extremités) : le segment est contenu si les 2 extremités et le milieu sont contenus
if (PolygonWithRealPoint.Contains(containingPolygon, containedSegement.StartPoint) && PolygonWithRealPoint.Contains(containingPolygon, containedSegement.EndPoint) && PolygonWithRealPoint.Contains(containingPolygon, containedSegement.Barycenter))
result = true;
else
result = false;
}
}
else
{
// Pas de croisement, il suffit de contenir un point du segment
result = PolygonWithRealPoint.Contains(containingPolygon, containedSegement.StartPoint);
}
return result;
}
public static bool Cross(Polygon polygon, Segment segment)
{
return SegmentWithPolygon.Cross(segment, polygon);
}
public static double Distance(Polygon polygon, Segment segment)
{
return SegmentWithPolygon.Distance(segment, polygon);
}
public static List<RealPoint> GetCrossingPoints(Polygon polygon, Segment segment)
{
return SegmentWithPolygon.GetCrossingPoints(segment, polygon);
}
}
}
<file_sep>/GoBot/GeometryTester/TestPolygonWithPolygon.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeometryTester
{
[TestClass]
public class TestPolygonWithPolygon
{
#region Contains
#endregion
}
}
<file_sep>/GoBot/Geometry/RectangleExtensions.cs
using System.Drawing;
internal static class RectangleExtensions
{
#region RectangleF
/// <summary>
/// Retourne le point central du rectangle
/// </summary>
/// <param name="rect">Rectangle dont on cherche le centre</param>
/// <returns>Point central du rectangle<returns>
public static PointF Center(this RectangleF rect)
{
return new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
}
/// <summary>
/// Augmente la largeur du rectangle tout en conservant son centre au même endroit
/// </summary>
/// <param name="rect">Rectangle à modifier</param>
/// <param name="newWidth">Nouvelle largeur</param>
public static RectangleF ExpandWidth(this RectangleF rect, double newWidth)
{
rect.X -= (float)(newWidth - rect.Width) / 2;
rect.Width = (float)newWidth;
return rect;
}
/// <summary>
/// Augmente la hauteur du rectangle tout en conservant son centre au même endroit
/// </summary>
/// <param name="rect">Rectangle à modifier</param>
/// <param name="newHeight">Nouvelle hauteur</param>
public static RectangleF ExpandHeight(this RectangleF rect, double newHeight)
{
rect.Y -= (float)(newHeight - rect.Height) / 2;
rect.Height = (float)newHeight;
return rect;
}
/// <summary>
/// Déplace le rectangle sur les axes X et Y suivant les deltas donnés
/// </summary>
/// <param name="rect">Ractangle à déplacer</param>
/// <param name="deltaX">Déplacement sur l'axe des abscisses</param>
/// <param name="deltaY">Déplacement sur l'axe des ordonnées</param>
public static RectangleF Shift(this RectangleF rect, double deltaX, double deltaY)
{
rect.X += (float)deltaX;
rect.Y += (float)deltaY;
return rect;
}
/// <summary>
/// Déplace le rectangle en modifiant son centre et en conservant sa taille
/// </summary>
/// <param name="rect">Rectangle à modifier</param>
/// <param name="center">Nouveau centre</param>
public static RectangleF SetCenter(this RectangleF rect, PointF center)
{
rect.X = center.X - rect.Width / 2;
rect.Y = center.Y - rect.Height / 2;
return rect;
}
#endregion
#region Rectangle
public static PointF Center(this Rectangle rect)
{
return new PointF(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
}
#endregion
}
<file_sep>/GoBot/GoBot/PathFinding/Trajectory.cs
using GoBot.Actions;
using Geometry;
using Geometry.Shapes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
namespace GoBot.PathFinding
{
public class Trajectory
{
List<RealPoint> _points;
List<Segment> _lines;
AnglePosition _startAngle, _endAngle;
/// <summary>
/// Liste des points de passage de la trajectoire
/// </summary>
public ReadOnlyCollection<RealPoint> Points { get { return _points.AsReadOnly(); } }
/// <summary>
/// Liste des segments de la trajectoire
/// </summary>
public ReadOnlyCollection<Segment> Lines { get { return _lines.AsReadOnly(); } }
public AnglePosition StartAngle { get { return _startAngle; } set { _startAngle = value; } }
public AnglePosition EndAngle { get { return _endAngle; } set { _endAngle = value; } }
public Trajectory()
{
_points = new List<RealPoint>();
_lines = new List<Segment>();
}
public Trajectory(Trajectory other)
{
_points = new List<RealPoint>(other.Points);
_lines = new List<Segment>(other.Lines);
_startAngle = other.StartAngle;
_endAngle = other.EndAngle;
}
/// <summary>
/// Ajoute un point de passage à la trajectoire
/// </summary>
/// <param name="point">Point à ajouter à la trajectoire</param>
public void AddPoint(RealPoint point)
{
_points.Add(point);
if (_points.Count > 1)
_lines.Add(new Segment(Points[Points.Count - 2], Points[Points.Count - 1]));
}
/// <summary>
/// Convertit la trajectoire en suite d'actions de déplacement à effectuer pour suivre la trajectoire
/// </summary>
/// <returns>Liste des déplacements correspondant</returns>
public List<ITimeableAction> ConvertToActions(Robot robot)
{
List<ITimeableAction> actions = new List<ITimeableAction>();
AnglePosition angle = _startAngle;
for (int i = 0; i < Points.Count - 1; i++)
{
RealPoint c1 = new RealPoint(Points[i].X, Points[i].Y);
RealPoint c2 = new RealPoint(Points[i + 1].X, Points[i + 1].Y);
Position p = new Position(angle, c1);
Direction traj = Maths.GetDirection(p, c2);
// Désactivation 2019 de la possibilité de faire des marches arrière pour conserver le LDIAR d'évitement dans le sens de déplacement du robot
bool canReverse = false;
// Teste si il est plus rapide (moins d'angle à tourner) de se déplacer en marche arrière avant la fin
bool inverse = false;
if (canReverse)
{
if (i < _points.Count - 2)
{
inverse = Math.Abs(traj.angle) > 90;
}
else
{
// On cherche à minimiser le tout dernier angle quand on fait l'avant dernier
AnglePosition finalAngle = angle - traj.angle;
inverse = Math.Abs(finalAngle - _endAngle) > 90;
}
if (inverse)
traj.angle = new AngleDelta(traj.angle - 180);
}
traj.angle.Modulo();
if (traj.angle < 0)
{
actions.Add(new ActionPivot(robot, -traj.angle, SensGD.Droite));
angle -= traj.angle;
}
else if (traj.angle > 0)
{
actions.Add(new ActionPivot(robot, traj.angle, SensGD.Gauche));
angle -= traj.angle;
}
if (inverse)
actions.Add(new ActionRecule(robot, (int)(traj.distance)));
else
actions.Add(new ActionAvance(robot, (int)(traj.distance)));
}
AngleDelta diff = angle - _endAngle;
if (Math.Abs(diff) > 0.2) // Angle minimal en dessous duquel on considère qu'il n'y a pas besoin d'effectuer le pivot
{
if (diff < 0)
actions.Add(new ActionPivot(robot, -diff, SensGD.Droite));
else
actions.Add(new ActionPivot(robot, diff, SensGD.Gauche));
}
return actions;
}
public TimeSpan GetDuration(Robot robot)
{
return new TimeSpan(ConvertToActions(robot).Sum(o => o.Duration.Ticks));
}
public void Paint(Graphics g, WorldScale scale)
{
Point previousPoint = Points[0];
using (Pen redPen = new Pen(Color.Red, 2), whitePen = new Pen(Color.White, 4))
{
for (int i = 0; i < Points.Count; i++)
{
Point pointNode = scale.RealToScreenPosition(Points[i]);
if (i >= 1)
{
g.DrawLine(whitePen, pointNode, previousPoint);
g.DrawLine(redPen, pointNode, previousPoint);
}
previousPoint = pointNode;
}
for (int i = 0; i < Points.Count; i++)
{
Point point = scale.RealToScreenPosition(Points[i]);
g.FillEllipse(Brushes.Red, new Rectangle(point.X - 4, point.Y - 4, 8, 8));
g.DrawEllipse(Pens.White, new Rectangle(point.X - 4, point.Y - 4, 8, 8));
}
}
}
public void RemovePoint(int index)
{
if (index == 0)
{
_points.RemoveAt(0);
_lines.RemoveAt(0);
}
else if (index == _points.Count - 1)
{
_points.RemoveAt(_points.Count - 1);
_points.RemoveAt(_lines.Count - 1);
}
else
{
Segment newSeg = new Segment(_points[index - 1], _points[index + 1]);
_points.RemoveAt(index);
_lines.RemoveAt(index - 1);
_lines.RemoveAt(index - 1);
_lines.Insert(index, newSeg);
}
}
public bool RemoveLine(int index)
{
bool ok = true;
if (index == 0)
{
_points.RemoveAt(0);
_lines.RemoveAt(0);
}
else if (index == _lines.Count - 1)
{
_points.RemoveAt(_points.Count - 1);
_points.RemoveAt(_lines.Count - 1);
}
else
{
Segment s1 = _lines[index - 1];
Segment s2 = _lines[index + 1];
if (s1.Line.Cross(s2.Line))
{
RealPoint cross = s1.Line.GetCrossingPoints(s2.Line)[0];
Segment newSeg1 = new Segment(s1.EndPoint, cross);
Segment newSeg2 = new Segment(cross, s2.StartPoint);
_lines[index - 1] = newSeg1;
_lines[index + 1] = newSeg2;
_lines.RemoveAt(index);
_points.RemoveRange(index, 2);
_points.Insert(index, cross);
}
else
{
ok = false;
}
}
return ok;
}
}
}
<file_sep>/GoBot/GoBot/Program.cs
using System;
using System.Linq;
using System.Windows.Forms;
using GoBot.Communications;
using GoBot.IHM;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Diagnostics;
using GoBot.Devices;
using GoBot.Actionneurs;
using GoBot.Threading;
using GoBot.Beacons;
using GoBot.BoardContext;
namespace GoBot
{
static class Program
{
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Execution.DesignMode = false;
Execution.LaunchStart = DateTime.Now;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SplashScreen.ShowSplash(Properties.Resources.Splash1, new Rectangle(495, 115, 275, 80));
CheckAlreadyLaunched();
DebugChecks();
Update();
CheckIP();
SplashScreen.SetMessage("Initialisation\nConnexions...", Color.Black);
SplashScreen.SetImage(Properties.Resources.Splash1);
ThreadManager.Init();
Connections.Init();
SplashScreen.SetMessage("Initialisation\nConfig...", Color.Black);
SplashScreen.SetImage(Properties.Resources.Splash2);
Config.Load();
SplashScreen.SetMessage("Initialisation\nDevices...", Color.Black);
SplashScreen.SetImage(Properties.Resources.Splash3);
AllDevices.Init();
Actionneur.Init();
SuiviBalise.Init();
SplashScreen.SetMessage("Initialisation\nRobot...", Color.Black);
Robots.Init();
Recalibration.Init();
SplashScreen.SetMessage("Initialisation\nPlateau...", Color.Black);
Dessinateur.Init();
GameBoard.Init();
SplashScreen.SetMessage("Initialisation\nLogs...", Color.Black);
SplashScreen.SetImage(Properties.Resources.Splash4);
Logs.Logs.Init();
SplashScreen.SetMessage("Initialisation\nInterface...", Color.Black);
SplashScreen.SetImage(Properties.Resources.Splash5);
Application.Run(new FenGoBot(args));
}
static void DebugChecks()
{
if (Debugger.IsAttached)
{
TestCode.TestEnums();
}
}
static void CheckIP()
{
if(!Dns.GetHostAddresses(Dns.GetHostName()).ToList().Exists(ip => ip.ToString().StartsWith("10.1.0.")))
{
SplashScreen.SetMessage("Attention !\nIP non configurée...", Color.Red);
Thread.Sleep(1000);
}
}
static void CheckAlreadyLaunched()
{
int tryCount = 0;
int tryMax = 5;
bool ok = false;
String messageWait = "Execution de GoBot\nen attente";
Process[] proc;
do
{
proc = Process.GetProcessesByName("GoBot");
ok = (proc.Length <= 1);
if(!ok)
{
messageWait += ".";
SplashScreen.SetMessage(messageWait, Color.Orange);
Thread.Sleep(1000);
}
tryCount++;
} while (!ok && tryCount < tryMax);
if (!ok)
{
SplashScreen.SetMessage("GoBot est déjà lancé...", Color.Red);
Thread.Sleep(1000);
Environment.Exit(0);
}
}
static void Update()
{
// Pas d'update automatique si on est dans l'IDE ou si le fichier NoUpdate existe à coté de l'exe
if (!Debugger.IsAttached)
{
String noUpdateFile = Application.StartupPath + "\\NoUpdate";
if (!File.Exists(noUpdateFile))
{
SplashScreen.SetMessage("GoBot recherche\ndes mises à jour...", Color.Black);
String versionCourante = Application.ProductVersion.Substring(0, Application.ProductVersion.LastIndexOf('.'));
String derniereVersion;
try
{
HttpWebRequest r = (HttpWebRequest)WebRequest.Create("http://www.omybot.com/GoBot/version.txt");
HttpWebResponse rep = (HttpWebResponse)r.GetResponse();
StreamReader sr = new StreamReader(rep.GetResponseStream());
derniereVersion = sr.ReadLine();
sr.Close();
}
catch (Exception)
{
derniereVersion = versionCourante;
SplashScreen.SetMessage("Impossible de mettre\nà jour...", Color.Red);
Thread.Sleep(1000);
}
if (versionCourante != derniereVersion)
{
SplashScreen.SetMessage("Une nouvelle version\n est disponible.", Color.Green);
Thread.Sleep(1000);
SplashScreen.SetMessage("Téléchargement de la\n dernière version...", Color.FromArgb(50, 50, 50));
WebClient wc = new WebClient();
String setup = System.IO.Path.GetTempPath() + "SetupGoBot.exe";
try
{
wc.DownloadFile("http://www.omybot.com/GoBot/SetupGoBot.exe", System.IO.Path.GetTempPath() + "SetupGoBot.exe");
SplashScreen.SetMessage("GoBot va se relancer...", Color.FromArgb(50, 50, 50));
Thread.Sleep(1000);
System.Diagnostics.ProcessStartInfo myInfo = new System.Diagnostics.ProcessStartInfo();
myInfo.FileName = setup;
myInfo.Arguments = "/SP- /VERYSILENT";
System.Diagnostics.Process.Start(myInfo);
Application.Exit();
}
catch (Exception)
{
SplashScreen.SetMessage("Erreur !" + Environment.NewLine + " Mise à jour échouée", Color.Red);
Thread.Sleep(2000);
}
}
}
}
}
}
}
<file_sep>/GoBot/Geometry/Shapes/ShapesInteractions/SegmentWithCircle.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Geometry.Shapes.ShapesInteractions
{
internal static class SegmentWithCircle
{
public static bool Contains(Segment containingSegment, Circle containedCircle)
{
// Contenir un cercle revient à avoir un cercle de rayon 0 dont le centre se trouve sur le segment
return SegmentWithRealPoint.Contains(containingSegment, containedCircle.Center) && containedCircle.Radius == 0;
}
public static bool Cross(Segment segment, Circle circle)
{
return CircleWithSegment.Cross(circle, segment);
}
public static double Distance(Segment segment, Circle circle)
{
return CircleWithSegment.Distance(circle, segment);
}
public static List<RealPoint> GetCrossingPoints(Segment segment, Circle circle)
{
return CircleWithSegment.GetCrossingPoints(circle, segment);
}
}
}
<file_sep>/GoBot/GoBot/Execution.cs
using System;
namespace GoBot
{
public class Execution
{
/// <summary>
/// Permet de savoir si l'application est mode Design (concepteur graphique) ou en cours d'execution
/// Le DesignMode de base :
/// - Ne fonctionne pas dans les contructeurs
/// - Ne fonctionne pas pour les contrôles imbriqués
/// </summary>
public static bool DesignMode { get; set; } = true;
/// <summary>
/// Obtient ou défini si l'application est en train de se couper
/// </summary>
public static bool Shutdown { get; set; } = false;
/// <summary>
/// Date de lancement de l'application
/// </summary>
public static DateTime LaunchStart { get; set; }
/// <summary>
/// Date de lancement de l'application sous format texte triable alphabétiquement
/// </summary>
public static String LaunchStartString { get { return Execution.LaunchStart.ToString("yyyy.MM.dd HH\\hmm\\mss\\s"); } }
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/PepperlComm.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace GoBot.Devices
{
class PepperlComm
{
IPAddress _ip;
public PepperlComm(IPAddress ip)
{
_ip = ip;
}
public Dictionary<String, String> SetParameter(String parameter, String value)
{
return SendCommand(PepperlConst.CmdSetParameter, parameter, value);
}
public Dictionary<String, String> SetParameters(IEnumerable<String> parameters, IEnumerable<String> values)
{
return SendCommand(PepperlConst.CmdSetParameter, parameters, values);
}
public Dictionary<String, String> SetParameters(params String[] paramVals)
{
return SendCommand(PepperlConst.CmdSetParameter, paramVals);
}
public Dictionary<String, String> SendCommand(String command)
{
return JsonDumbParser.Parse(SendMessage(command));
}
public Dictionary<String, String> SendCommand(PepperlCmd command)
{
return JsonDumbParser.Parse(SendMessage(command.GetText()));
}
public Dictionary<String, String> SendCommand(PepperlCmd command, IEnumerable<String> parameters, IEnumerable<String> values)
{
return SendCommand(command.GetText(), parameters, values);
}
public Dictionary<String, String> SendCommand(String command, IEnumerable<String> parameters, IEnumerable<String> values)
{
if (parameters.Count() != values.Count())
return new Dictionary<String, String>();
StringBuilder message = new StringBuilder(command + "?");
for (int i = 0; i < parameters.Count(); i++)
message = message.Append(parameters.ElementAt(i) + "=" + values.ElementAt(i) + "&");
message.Remove(message.Length - 1, 1); // Le dernier & inutile
String response = SendMessage(message.ToString());
//Console.WriteLine(response);
return JsonDumbParser.Parse(response);
}
public Dictionary<String, String> SendCommand(PepperlCmd command, params String[] paramVals)
{
return SendCommand(command.GetText(), paramVals);
}
public Dictionary<String, String> SendCommand(String command, params String[] paramVals)
{
if (paramVals.Length % 2 != 0)
return new Dictionary<String, String>();
List<String> parameters = new List<String>();
List<String> values = new List<String>();
for (int i = 0; i < paramVals.Length; i += 2)
{
parameters.Add(paramVals[i]);
values.Add(paramVals[i + 1]);
}
return SendCommand(command, parameters, values);
}
private String SendMessage(String message)
{
String rep = "";
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://" + _ip.ToString() + "/cmd/" + message);
request.Timeout = 500;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
rep = reader.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("ERROR Lidar Pepperl envoi " + message + " - " + e.Message);
rep = "";
}
return rep;
}
}
}
<file_sep>/GoBot/GoBot/Strategies/StrategyMinimumScore.cs
using System.Collections.Generic;
using Geometry;
using Geometry.Shapes;
using GoBot.Movements;
using GoBot.BoardContext;
namespace GoBot.Strategies
{
/// <summary>
/// Stratégie qui consiste à marquer juste quelques points (pour homologuation de capacité à marquer des points par exemple)
/// </summary>
class StrategyMinimumScore : Strategy
{
private bool _avoidElements = true;
public override bool AvoidElements => _avoidElements;
List<Movement> mouvements = new List<Movement>();
protected override void SequenceBegin()
{
// Sortir ICI de la zonde de départ
Robots.MainRobot.UpdateGraph(GameBoard.ObstaclesAll);
//Robots.MainRobot.MoveForward(500);
if (GameBoard.MyColor == GameBoard.ColorLeftBlue)
{
//*mouvements.Add(new MoveAccelerator(Plateau.Elements.AcceleratorYellow));
}
else
{
//*mouvements.Add(new MoveAccelerator(Plateau.Elements.AcceleratorViolet));
}
}
protected override void SequenceCore()
{
// TODOYEACHYEAR Ajouter ICI l'ordre de la strat fixe avant détection d'adversaire
_avoidElements = true;
foreach (Movement move in mouvements)
{
bool ok = false;
while (!ok)
{
ok = move.Execute();
}
}
while (IsRunning)
{
while (!Robots.MainRobot.GoToPosition(new Position(0, new RealPoint(700, 1250)))) ;
while (!Robots.MainRobot.GoToPosition(new Position(180, new RealPoint(3000 - 700, 1250)))) ;
}
}
}
}
<file_sep>/GoBot/GoBot/IHM/Panels/PotarControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GoBot.Actionneurs;
using System.Threading;
using GoBot.Threading;
using System.Reflection;
using GoBot.Devices;
namespace GoBot.IHM
{
public partial class PotarControl : UserControl
{
private ThreadLink _linkPolling;
private Positionable _currentPositionnable;
private int _currentPosition;
public Dictionary<String, PropertyInfo> _positionsProp;
public PotarControl()
{
InitializeComponent();
_linkPolling = null;
}
private void PotarControl_Load(object sender, EventArgs e)
{
if (!Execution.DesignMode)
{
cboPositionnable.Items.AddRange(Config.Positionnables.ToArray());
}
}
private void cboPositionnable_SelectedIndexChanged(object sender, EventArgs e)
{
lock (this)
{
_currentPositionnable = (Positionable)cboPositionnable.SelectedItem;
SetPositions(_currentPositionnable);
}
}
private void switchBouton_ValueChanged(object sender, bool value)
{
if (value)
{
trackBar.Min = _currentPositionnable.Minimum;
trackBar.Max = _currentPositionnable.Maximum;
_linkPolling = ThreadManager.CreateThread(link => PollingLoop());
_linkPolling.StartThread();
}
else
{
_linkPolling.Cancel();
}
}
private void PollingLoop()
{
double posValue;
double ticksCurrent, ticksMin, ticksRange;
int pointsParTour = 4096;
double toursRange = 5;
_linkPolling.RegisterName();
ticksCurrent = 0;//TODO2020 AllDevices.RecGoBot.GetCodeurPosition();
ticksMin = ticksCurrent;
ticksRange = pointsParTour * toursRange;
posValue = _currentPositionnable.Minimum;
while (!_linkPolling.Cancelled)
{
lock (this)
{
_linkPolling.LoopsCount++;
toursRange = trackBarSpeed.Value;
ticksRange = pointsParTour * toursRange;
Thread.Sleep(50);
ticksCurrent = 0;//TODO2020 AllDevices.RecGoBot.GetCodeurPosition();
if (ticksCurrent > ticksMin + ticksRange)
ticksMin = ticksCurrent - ticksRange;
else if (ticksCurrent < ticksMin)
ticksMin = ticksCurrent;
posValue = (ticksCurrent - ticksMin) / ticksRange * (_currentPositionnable.Maximum - _currentPositionnable.Minimum) + _currentPositionnable.Minimum;
posValue = Math.Min(posValue, _currentPositionnable.Maximum);
posValue = Math.Max(posValue, _currentPositionnable.Minimum);
}
SetPosition((int)posValue);
}
_linkPolling = null;
}
private void SetPosition(int position)
{
if (position != _currentPosition)
{
_currentPosition = position;
_currentPositionnable.SendPosition((int)_currentPosition);
this.InvokeAuto(() =>
{
trackBar.SetValue(_currentPosition);
lblValue.Text = _currentPosition.ToString();
});
}
}
private void trackBarSpeed_ValueChanged(object sender, double value)
{
lblSpeed.Text = "Rapport " + value.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
String[] tab = ((String)(cboPositions.SelectedItem)).Split(new char[] { ':' });
String position = tab[0].Trim().ToLower();
int valeur = Convert.ToInt32(tab[1].Trim());
int index = cboPositions.SelectedIndex;
_positionsProp[(String)cboPositions.SelectedItem].SetValue((Positionable)cboPositionnable.SelectedItem, _currentPosition, null);
trackBar.Min = _currentPositionnable.Minimum;
trackBar.Max = _currentPositionnable.Maximum;
SetPositions(_currentPositionnable);
cboPositions.SelectedIndex = index;
Config.Save();
}
private void SetPositions(Positionable pos)
{
PropertyInfo[] properties = _currentPositionnable.GetType().GetProperties();
List<String> noms = new List<string>();
_positionsProp = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo property in properties)
{
if (property.Name != "ID")
{
noms.Add(Config.PropertyNameToScreen(property) + " : " + property.GetValue(_currentPositionnable, null));
_positionsProp.Add(noms[noms.Count - 1], property);
}
}
cboPositions.Items.Clear();
cboPositions.Items.AddRange(noms.ToArray());
btnSave.Enabled = false;
}
private void cboPositions_SelectedIndexChanged(object sender, EventArgs e)
{
btnSave.Enabled = true;
_currentPosition = (int)_positionsProp[(String)cboPositions.SelectedItem].GetValue(cboPositionnable.SelectedItem, null);
}
}
}
<file_sep>/GoBot/GoBot/Devices/Pepperl/JsonDumbParser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GoBot.Devices
{
public class JsonDumbParser
{
public static Dictionary<String, String> Parse(String json)
{
Dictionary<String, String> values = new Dictionary<string, string>();
if (json == "") return null;
json = json.Replace("{", "").Replace("}", "").Replace(",\r\n", ":").Replace("\r\n", "");
List<String> splits = json.Split(new String[] { ":" }, StringSplitOptions.None).ToList();
for (int i = 0; i < splits.Count; i += 2)
{
values.Add(splits[i].Replace("\"", ""), splits[i + 1].Replace("\"", ""));
}
return values;
}
}
}
| f129f0d9cad25d310cc71686514ea119bddfb798 | [
"C#",
"Text"
] | 241 | C# | Omybot/GoBot | 3892bc3d5087e5f4663ea787db1f4d4fd6742721 | 5ed460599622b40c7d3abf984cdd7056d97b5b17 | |
refs/heads/master | <file_sep>#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
class _ManyButtonsCreater:
def __init__(self, master):
self.__master = master
def addButton(self, **kw):
return tk.Button(self.__master, **kw)
class _ButtonCanBeSelected(_ManyButtonsCreater):
def deselectAll():
pass
def _selectButton(btn):
btn['state'] = 'disable'
def _deselectButton(btn):
btn['state'] = 'active'
class OnlyOneButtonCanBeSelected(_ButtonCanBeSelected):
def __init__(self, master):
super().__init__(master)
self.__selected = None
def __buttonClicked(self, btn):
if self.__selected != None:
_deselectButton(self.__selected)
self.__selected = btn
_selectButton(btn)
def __clickCommand(self, btn, cmd):
self.__buttonClicked(btn)
if cmd is not None:
cmd()
def addButton(self, **kw):
if 'command' in kw:
cmd = kw.pop('command')
else:
cmd = None
btn = super().addButton(**kw)
btn['command'] = lambda: self.__clickCommand(btn, cmd)
return btn
def deselectAll(self):
if self.__selected is not None:
_deselectButton(self.__selected)
self.__selected = None
class OnlyTowButtonCanBeSelected(_ButtonCanBeSelected):
def __init__(self, master: tk.Widget):
super().__init__(master)
self.__selected = []
def __buttonClicked(self, btn):
self.__selected.append(btn)
_selectButton(btn)
def __clickCommand(self, btn, cmd):
if len(self.__selected) < 2:
self.__buttonClicked(btn)
if cmd is not None:
cmd()
def addButton(self, **kw):
if 'command' in kw:
cmd = kw.pop('command')
else:
cmd = None
btn = super().addButton(**kw)
btn['command'] = lambda: self.__clickCommand(btn, cmd)
return btn
def deselectAll(self):
while self.__selected:
_deselectButton(self.__selected.pop())
@property
def count(self):
return len(self.__selected)
<file_sep>#!/usr/bin/env python3
import tkinter as tk
import tkinter.ttk as ttk
PAD = 3
class ManyBuutonsPacker:
def __init__(self, width):
self.__width = width
self.__counter = 0
def pack(self, w: tk.Widget):
rtn = w.grid(padx=PAD, pady=PAD, row=int(self.__counter/self.__width), column=self.__counter%self.__width)
self.__counter += 1
return rtn
class ScrollableFrame(ttk.Frame):
def __init__(self, container, bar_x = True, bar_y = True):
super().__init__(container)
self.canvas = tk.Canvas(self, width=1280, height=720)
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(
scrollregion=self.canvas.bbox("all")
)
)
self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
if bar_y:
self.scrollbar_y = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.scrollbar_y.pack(side=tk.RIGHT, fill="y")
self.canvas.configure(yscrollcommand=self.scrollbar_y.set)
if bar_x:
self.scrollbar_x = ttk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
self.scrollbar_x.pack(side=tk.BOTTOM, fill="x")
self.canvas.configure(xscrollcommand=self.scrollbar_x.set)
self.canvas.pack(side=tk.LEFT, fill="both", expand=True)
class FrameMaker:
def __init__(self, master):
u = tk.Frame(master)
u.pack(padx=PAD, pady=PAD, side=tk.TOP)
d = ScrollableFrame(master)
d.pack(padx=PAD, pady=PAD, side=tk.TOP)
ul = tk.Frame(u)
ul.pack(padx=PAD, pady=PAD, side=tk.LEFT)
ur = tk.Frame(u)
ur.pack(padx=PAD, pady=PAD, side=tk.LEFT)
self.__upperleft = ul
self.__upperright = ur
self.__down = d.scrollable_frame
@property
def upperleft(self):
return self.__upperleft
@property
def upperright(self):
return self.__upperright
@property
def down(self):
return self.__down
def destroy_child(frame: tk.Frame):
children = frame.winfo_children()
for child in children:
child.destroy()
<file_sep>#!/usr/bin/env python3
import tkinter as tk
import functools as ft
from . import _utils as utils
class _ManyCheckbuttonCreater:
def __init__(self, master):
self.__master = master
def addCheckbutton(self, **kw):
return tk.Checkbutton(self.__master, **kw)
def cleanFrame(self):
utils.destroy_child(self.__master)
class _CheckbuttonCanBeSelected(_ManyCheckbuttonCreater):
pass
def _selectCheckbutton(cb: tk.Checkbutton):
cb.select()
def _deselectCheckbutton(cb: tk.Checkbutton):
cb.deselect()
class OnlyOneCheckbuttonCanBeSelected(_CheckbuttonCanBeSelected):
def __init__(self, master):
super().__init__(master)
self.__selected = None
def __checkbuttonSelected(self, cb):
if self.__selected != None:
_deselectCheckbutton(self.__selected)
self.__selected = cb
def __selectCommand(self, cb, cmd):
self.__checkbuttonSelected(cb)
if cmd is not None:
cmd()
def addCheckbutton(self, **kw):
if 'command' in kw:
cmd = kw.pop('command')
else:
cmd = None
cb = super().addCheckbutton(**kw)
# cb['command'] = lambda: self.__selectCommand(cb, cmd)
cb['command'] = ft.partial(self.__selectCommand, cb, cmd)
return cb
def cleanFrame(self):
self.__selected = None
super().cleanFrame()
class OnlyTowCheckbuttonCanBeSelected(_CheckbuttonCanBeSelected):
def __init__(self, master: tk.Widget):
super().__init__(master)
self.__selected = list()
def __checkbuttonSelected(self, cb):
self.__selected.append(cb)
def __checkbuttonDeselected(self, cb):
_deselectCheckbutton(cb)
self.__selected.remove(cb)
def __selectCommand(self, cb, cmd):
if len(self.__selected) < 2:
self.__checkbuttonSelected(cb)
if cmd is not None:
cmd()
else:
_deselectCheckbutton(cb)
def __deselectCommand(self, cb, cmd):
self.__checkbuttonDeselected(cb)
if cmd is not None:
cmd()
def __command(self, cb, cmd):
if cb in self.__selected:
self.__deselectCommand(cb, cmd)
else:
self.__selectCommand(cb, cmd)
def addCheckbutton(self, **kw):
if 'command' in kw:
cmd = kw.pop('command')
else:
cmd = None
cb = super().addCheckbutton(**kw)
# cb['command'] = lambda: self.__command(cb, cmd)
cb['command'] = ft.partial(self.__command, cb, cmd)
return cb
def cleanFrame(self):
self.__selected.clear()
super().cleanFrame()
@property
def count(self):
return len(self.__selected)
@property
def selected(self):
return tuple([i['text'] for i in self.__selected])
<file_sep>#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
from ._utils import *
from ._ButtonCanBeSelected import *
import ui._CheckboxCanBeSelected as ccbs
<file_sep>#!/usr/bin/env python3
from .main import *
import sqlite3
from os.path import expanduser
class MyScene(list):
def __init__(self, obs: ObsControl, scene_name: str, scene_id: str, *items):
super().__init__(*items)
self.__obs = obs
self.__name = scene_name
self.__id = scene_id
@property
def name(self):
return self.__name
@property
def id(self):
return self.__id
class MyItem:
def __init__(self, obs: ObsControl, scene_id: str, item_name: str, item_id: str, source_id: str,
position_x: int, position_y: int, size_width: int, size_height: int):
self.__obs = obs
self.__scene_id = scene_id
self.__name = item_name
self.__item_id = item_id
self.__source_id = source_id
self.__position_x = position_x
self.__position_y = position_y
self.__size_width = size_width
self.__size_height = size_height
@property
def scene_id(self):
return self.__scene_id
@property
def name(self):
return self.__name
@property
def item_id(self):
return self.__item_id
@property
def source_id(self):
return self.__source_id
def align(self):
self.__obs.set_sceneitem_size(self.scene_id, self.item_id, self.__size_width, self.__size_height)
self.__obs.set_sceneitem_position(self.scene_id, self.item_id, self.__position_x, self.__position_y)
def read_db(db_file: str = expanduser('~/myobs.sqlite3')):
ret = dict()
obs = ObsControl()
conn = sqlite3.connect(db_file)
cur = conn.cursor()
cur.execute('select name, id from scene')
for row in cur:
scene_name, scene_id = row
ret[scene_name] = MyScene(obs, scene_name, scene_id)
cur.execute('select scene.name, scene_id, item_name, item_id, source_id, position_x, position_y, size_width, size_height from item innner join scene on scene_id = scene.id')
for row in cur:
scene_name = row[0]
newitem = MyItem(obs, *row[1:])
ret[scene_name].append(newitem)
conn.close()
return ret
<file_sep>#!/usr/bin/env python3
from .main import *
from .read_from_sqlite3 import *
<file_sep>#!/usr/bin/env python3
import subprocess
class SLManager:
def __init__(self):
self.__slset = {}
def start(self, desc, url):
proc = subprocess.Popen(['streamlink', url, '720p,720p60,480p,best' , '--player-external-http', '--player-external-http-port', str(desc), '--twitch-disable-ads'])
self.stop(desc)
self.__slset[desc] = proc
def stop(self, desc):
if desc in self.__slset:
proc = self.__slset.pop(desc)
proc.kill()
if __name__ == '__main__':
slm = SLManager()
slm.start(49152, 'https://www.youtube.com/watch?v=IBflp1YeR3k')
input()
slm.stop(49152)
<file_sep>#!/usr/bin/env python3
from .main import *
# __all__ = []
<file_sep>#!/usr/bin/env python3
import obscontrol
import streamlinkwrapper
slm = streamlinkwrapper.SLManager()
class _FewStreamManager:
def __init__(self, basedesc, quantity):
self.__basedesc = basedesc
self.__quantity = quantity
self.__count = 0
def setURL(self, *urls):
for url in urls:
if url is not None:
slm.start(self.__basedesc+self.__count, url)
self.__count += 1
def reset(self):
while self.__count > 0:
self.__count -= 1
slm.stop(self.__basedesc+self.__count)
print('Stopped {0}'.format(self.__basedesc+self.__count))
class _ManySteamManager:
def __init__(self, basedesc, quantity1, quantity2):
self.__waiting = list()
for i in range(quantity1):
self.__waiting.append(_FewStreamManager(basedesc+(i*quantity2), quantity2))
self.__used = dict()
def setURL(self, key, *urls):
if key not in self.__used:
self.__used[key] = self.__waiting.pop()
self.__used[key].reset()
self.__used[key].setURL(*urls)
def reset(self):
for k in reversed(list(self.__used)):
self.__used[k].reset()
self.__waiting.append(self.__used.pop(k))
<file_sep>#!/usr/bin/env python3
import ParticipantManager
import ui
import delivery
import obscontrol
import copy
import utils
import functools as ft
import copy as cp
def trainsition(scene: list):
for item in scene:
item.align()
def onlyOne(teams, u, desc, text, scene):
d = delivery._FewStreamManager(desc, 1)
tab = u.addTab(text)
fr = ui.FrameDesignerD(tab, d.reset, ft.partial(trainsition, scene))
for i in teams:
for j in teams[i]:
url = teams[i][j].videoURL
cmd = d.reset if url is None else utils.fpf(d.reset, ft.partial(d.setURL, cp.copy(url)))
fr.add(text = '{0} - {1}'.format(i, j), command = cmd)
return tab
def OnevOne(teams, u, desc, text, scene):
d = delivery._FewStreamManager(desc, 2)
tab = u.addTab(text)
fr = ui.FrameDesignerB(tab, d.reset, ft.partial(trainsition, scene))
for i in teams:
for j in teams[i]:
url = teams[i][j].videoURL
if url is not None:
cmd = ft.partial(d.setURL, cp.copy(url))
fr.add(text = '{0} - {1}'.format(i, j), command = cmd)
return tab
def OneTeam(teams, u, desc, text, scene):
d = delivery._FewStreamManager(desc, 3)
tab = u.addTab(text)
fr = ui.FrameDesignerB(tab, d.reset, ft.partial(trainsition, scene))
for i in teams:
urls = [teams[i][j].videoURL for j in teams[i] if teams[i][j] is not None]
cmd = utils.fpf(d.reset, ft.partial(d.setURL, *cp.copy(urls)))
fr.add(text = i, command=cmd)
return tab
def TowvTow(teams, u, desc, text, scene):
d = delivery._ManySteamManager(desc, 2, 2)
tab = u.addTab(text)
fr = ui.FrameDesignerA(tab, d.reset, ft.partial(trainsition, scene))
for i in teams:
mem = teams[i].keys()
def cmd(team, *selmem):
print(selmem)
d.setURL(id(team), *[team[j].videoURL for j in selmem])
fr.add(text=i, command=ft.partial(cmd, cp.copy(teams[i])), member=mem)
return tab
def OptionTab(u: ui.UI, text: str, listreload):
tab = u.addTab(text)
fr = ui.FrameDesignerC(tab)
fr.add(text='リスト再読込', command = listreload)
return tab
def imptabCreate(teams: ParticipantManager.Participant, u: ui.tk.Widget):
imptab = list()
db = obscontrol.read_db()
imptab.append(onlyOne(teams, u, 49513, '一人視点 A', db['1a']))
imptab.append(onlyOne(teams, u, 49514, '一人視点 B', db['1b']))
imptab.append(OnevOne(teams, u, 49515, '1vs1 A', db['2a']))
imptab.append(OnevOne(teams, u, 49517, '1vs1 B', db['2b']))
imptab.append(OnevOne(teams, u, 49519, '収容所 A', db['ga']))
imptab.append(OnevOne(teams, u, 49521, '収容所 B', db['gb']))
imptab.append(OneTeam(teams, u, 49523, '1チーム視点 A', db['3a']))
imptab.append(OneTeam(teams, u, 49526, '1チーム視点 B', db['3b']))
TowvTow(teams, u, 49529, '2vs2 A', db['4a'])
TowvTow(teams, u, 49533, '2vs2 B', db['4b'])
return imptab
def main():
teams = ParticipantManager.readFile()
u = ui.UI()
imptab = imptabCreate(teams, u)
def listreload():
teams = ParticipantManager.readFile()
u.destroy()
main()
OptionTab(u, 'オプション', listreload)
u.mainloop()
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env python3
import pyslobs as slobs
import asyncio
async def set_sceneitem_size(conn, scene_id, item_id, width, height):
ss = slobs.ScenesService(conn)
scene = await ss.get_scene(scene_id)
item = await scene.get_item(item_id)
source = await item.get_source()
if source.width != 0 and source.height !=0:
x_scale = float(width) / float(source.width)
y_scale = float(height) / float(source.height)
await item.set_scale(slobs.IVec2(x_scale, y_scale))
await conn.close()
async def set_sceneitem_position(conn, scene_id, item_id, x_pos, y_pos):
ss = slobs.ScenesService(conn)
scene = await ss.get_scene(scene_id)
item = await scene.get_item(item_id)
old_transform = item.transform
new_transform = slobs.ITransform(
crop=old_transform.crop,
scale=old_transform.scale,
position=slobs.IVec2(
x=x_pos,
y=y_pos,
),
rotation=old_transform.rotation,
)
await item.set_transform(new_transform)
await conn.close()
async def stadio_mode(conn: slobs.SlobsConnection):
ts = slobs.TransitionsService(conn)
await ts.enable_studio_mode()
await conn.close()
async def transiton(conn: slobs.SlobsConnection):
ts = slobs.TransitionsService(conn)
await ts.execute_studio_mode_transition()
await conn.close()
async def make_active(conn: slobs.SlobsConnection, scene_id: str):
ss = slobs.ScenesService(conn)
await ss.make_scene_active(scene_id)
await conn.close()
async def get_settings(conn: slobs.SlobsConnection, source_id: str):
ss = slobs.SourcesService(conn)
source = await ss.get_source(source_id)
settings = await source.get_settings()
print(settings)
await conn.close()
async def change_source_file(conn: slobs.SlobsConnection, source_id: str, filename: str):
ss = slobs.SourcesService(conn)
source = await ss.get_source(source_id)
await source.update_settings({'file': filename})
await conn.close()
async def change_source_input(conn: slobs.SlobsConnection, source_id: str, inputname: str):
ss = slobs.SourcesService(conn)
source = await ss.get_source(source_id)
await source.update_settings({'input': inputname})
await conn.close()
async def print_settings(conn: slobs.SlobsConnection, source_id: str):
ss = slobs.SourcesService(conn)
source = await ss.get_source(source_id)
settings = await source.get_settings()
print(settings)
await conn.close()
class ObsControl:
def set_sceneitem_size(self, scene_id, item_id, width, height):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(),
set_sceneitem_size(conn, scene_id, item_id, width, height))
asyncio.run(main())
def set_sceneitem_position(self, scene_id, item_id, x_pos, y_pos):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(),
set_sceneitem_position(conn, scene_id, item_id, x_pos, y_pos))
asyncio.run(main())
def stadio_mode(self):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), stadio_mode(conn))
asyncio.run(main())
def transition(self):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), transiton(conn))
asyncio.run(main())
def make_active(self, scene_id: str):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), make_active(conn, scene_id))
asyncio.run(main())
def change_source_file(self, source_id: str, filename: str):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), change_source_file(conn, source_id, filename))
asyncio.run(main())
def change_source_input(self, source_id: str, inputname: str):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), change_source_input(conn, source_id, inputname))
asyncio.run(main())
def print_settings(self, source_id: str):
conn = slobs.SlobsConnection(slobs.config_from_ini())
async def main():
await asyncio.gather(conn.background_processing(), print_settings(conn, source_id))
asyncio.run(main())
<file_sep>#!/usr/bin/env python3
import tkinter as tk
import functools as ft
from . import _utils as utils
from . import _ButtonCanBeSelected as bcbs
from . import _CheckbuttonCanBeSelected as ccbs
class CheckbuttonFromButtons:
def __init__(self, btnframe, cbframe1, cbframe2):
self.__bcbs = bcbs.OnlyTowButtonCanBeSelected(btnframe)
self.__ccbs1 = ccbs.OnlyTowCheckbuttonCanBeSelected(cbframe1)
self.__ccbs2 = ccbs.OnlyTowCheckbuttonCanBeSelected(cbframe2)
def __buttonCommand(self, cmd, mem):
kw = dict()
if self.__bcbs.count == 1:
kw['command'] = lambda: cmd(*self.__ccbs1.selected)
targetframe = self.__ccbs1
else:
kw['command'] = lambda: cmd(*self.__ccbs2.selected)
targetframe = self.__ccbs2
for i in mem:
kw['text'] = i
bln = tk.BooleanVar()
bln.set(False)
kw['variable'] = bln
targetframe.addCheckbutton(**kw).pack()
def addButton(self, **kw):
cmd = kw.pop('command') if 'command' in kw else None
mem = kw.pop('member') if 'member' in kw else tuple()
kw['command'] = ft.partial(self.__buttonCommand, cmd, mem)
return self.__bcbs.addButton(**kw)
def reset(self):
self.__ccbs1.cleanFrame()
self.__ccbs2.cleanFrame()
self.__bcbs.deselectAll()
<file_sep>#!/usr/bin/env python3
import csv
import os.path
class Player:
def __init__(self, videourl = ''):
self.__videourl = videourl
@property
def videoURL(self):
return self.__videourl
@videoURL.setter
def videoURL(self, videourl):
self.__videourl = videourl
class Team(dict[str,Player]):
pass
class Participant(dict[str,Team]):
pass
def readFile(filepath = os.path.expanduser('~/ParticipantList.txt')):
ret = Participant()
with open(filepath, 'r',encoding="utf-8_sig") as fd:
reader = csv.DictReader(fd, skipinitialspace = True)
for part in reader:
ret.setdefault(part['TeamName'], Team())
ret[part['TeamName']][part['PlayerName']] = Player(videourl = part['VideoURL'])
return ret
<file_sep>#!/usr/bin/env python3
import tkinter as tk
import functools as ft
from ._utils import *
from ._ButtonCanBeSelected import *
from . import _CheckbuttonFromButtons as cbfb
RESETBUTTONTEXT = 'リセット'
TRANSITIONBUTTONTEXT = 'トランジション'
class FrameDesignerA:
'''
ボタンを押すと左上にチェックボタンが現れます。ボタンは2個まで押せます。
'''
def __init__(self, master, resetfunc, transfunc):
self.__packer = ManyBuutonsPacker(12)
frames = FrameMaker(master)
cbframe1 = tk.Frame(frames.upperleft)
cbframe1.pack(side=tk.LEFT)
cbframe2 = tk.Frame(frames.upperleft)
cbframe2.pack(side=tk.LEFT)
self.__cbfb = cbfb.CheckbuttonFromButtons(frames.down, cbframe1, cbframe2)
def reset():
resetfunc()
self.__cbfb.reset()
resetbutton = tk.Button(frames.upperright, text=RESETBUTTONTEXT, command=reset, height=3)
resetbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
transbutton = tk.Button(frames.upperright, text=TRANSITIONBUTTONTEXT, command=transfunc, height=3)
transbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
def add(self, **kw):
kw.setdefault('width', 12)
btn = self.__cbfb.addButton(**kw)
self.__packer.pack(btn)
class FrameDesignerB:
'''
ボタンを2個まで押せます。
'''
def __init__(self, master, resetfunc, transfunc):
self.__packer = ManyBuutonsPacker(6)
self.__resetfunc = resetfunc
self.__transfnuc = transfunc
frames = FrameMaker(master)
resetbutton = tk.Button(frames.upperright, text=RESETBUTTONTEXT, command=self.reset, height=3)
resetbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
transbutton = tk.Button(frames.upperright, text=TRANSITIONBUTTONTEXT, command=transfunc, height=3)
transbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
self.__mbc = OnlyTowButtonCanBeSelected(frames.down)
def __buttonCommand(self, cmd):
if cmd is not None:
cmd()
def add(self, **kw):
kw.setdefault('width', 27)
btn = self.__mbc.addButton(**kw)
self.__packer.pack(btn)
def reset(self):
self.__resetfunc()
self.__mbc.deselectAll()
class FrameDesignerC:
def __init__(self, master):
self.__master = master
def add(self, **kw):
btn = tk.Button(self.__master, **kw)
btn.pack()
class FrameDesignerD:
'''
ボタンは1個しか押せません。
'''
def __init__(self, master, resetfunc, transfunc):
self.__packer = ManyBuutonsPacker(6)
self.__resetfunc = resetfunc
self.__transfnuc = transfunc
frames = FrameMaker(master)
resetbutton = tk.Button(frames.upperright, text=RESETBUTTONTEXT, command=self.reset, height=3)
resetbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
transbutton = tk.Button(frames.upperright, text=TRANSITIONBUTTONTEXT, command=transfunc, height=3)
transbutton.pack(padx=PAD, pady=PAD, side=tk.LEFT)
self.__mbc = OnlyOneButtonCanBeSelected(frames.down)
def __buttonCommand(self, cmd):
if cmd is not None:
cmd()
def add(self, **kw):
kw.setdefault('width', 27)
btn = self.__mbc.addButton(**kw)
self.__packer.pack(btn)
def reset(self):
self.__resetfunc()
self.__mbc.deselectAll()
class UI(tk.Tk):
'''
タブ付きウィンドウを作る
'''
def __init__(self):
super().__init__()
self.__notebook = ttk.Notebook(self)
self.__notebook.pack()
self.__cmdlist = {}
def tab_changed(_):
if len(self.__cmdlist) != 0:
cmd = self.__cmdlist[self.__notebook.select()]
if cmd is not None:
cmd()
self.bind('<<NotebookTabChanged>>', tab_changed)
self.__openingtab = None
def addTab(self, text = '', openfunc = None, closefunc = None):
frame = tk.Frame(self.__notebook)
self.__notebook.add(frame, text = text)
self.__cmdlist[self.__notebook.tabs()[self.__notebook.index('end')-1]] = openfunc
return frame
<file_sep>#!/usr/bin/env python3
class _fpf:
def __init__(self, f1, f2):
self.__f1 = f1
self.__f2 = f2
def __func(self):
self.__f1()
self.__f2()
def func(self):
return lambda: self.__func()
def fpf(f1, f2):
'''
関数同士をつなぎ合わせるだけ
'''
return _fpf(f1,f2).func()
| 09c8cf95489e714ecede6b6053b113a380963b50 | [
"Python"
] | 15 | Python | UnkoMamire/hgh | 471bd8b6161c16ee4f6f156c9dd13e0d82f86b60 | 4ff3a108fed21ea0c888c9c0d491c8dad47d68e7 | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using DAL;
namespace DAO
{
public class Category
{
public CatDal mainCatDal = new CatDal();
private int typeId;
private String mainCat;
private int mainCatID;
private String category;
private int catID;
private int uGrouoId;
public int UGrouoId
{
get { return uGrouoId; }
set { uGrouoId = value; }
}
private int subCatID;
public int SubCatID
{
get { return subCatID; }
set { subCatID = value; }
}
private String subCat;
public String SubCat
{
get { return subCat; }
set { subCat = value; }
}
public int CatID
{
get { return catID; }
set { catID = value; }
}
public String Category1
{
get { return category; }
set { category = value; }
}
public int MainCatID
{
get { return mainCatID; }
set { mainCatID = value; }
}
public String MainCat
{
get { return mainCat; }
set { mainCat = value; }
}
private String desc;
public String Desc
{
get { return desc; }
set { desc = value; }
}
private int status;
public int Status
{
get { return status; }
set { status = value; }
}
public int TypeId
{
get { return typeId; }
set { typeId = value; }
}
//Method for manage main categories
public Boolean InsertMainCategory(Category obj)
{
if (mainCatDal.insertMainCat(obj.typeId, obj.MainCat, obj.desc, obj.status))
return true;
else
return false;
}
//Method for manage main categories
public DataTable GetAllMainCategory()
{
DataTable Dt = mainCatDal.GetAllMainCategory();
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
//Method for manage main categories by category
public DataTable GetAllMainCategoryByName(String category)
{
DataTable Dt = mainCatDal.GetAllMainCategoryByName(category);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public DataTable GetMainCat(Category obj)
{
DataTable Dt = mainCatDal.GetMainCategory(obj.typeId);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
public DataTable GetCategoryByMaincat(Category obj)
{
DataTable Dt = mainCatDal.GetCategory(obj.mainCatID);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
public DataTable GetSubCategoryByCat(Category obj)
{
DataTable Dt = mainCatDal.GetSubCategoryByCategory(obj.catID);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
public DataTable GetAllData()
{
DataTable Dt = mainCatDal.GetAllDataForCategory();
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public DataTable GetAllDataWithSubCat(Category obj)
{
DataTable Dt = mainCatDal.GetAllDataForSubCategory(obj.catID);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public Boolean InsertCategory(Category obj)
{
if (mainCatDal.inserCat( obj.mainCatID,obj.category, obj.desc, obj.status))
return true;
else
return false;
}
//Method for manage main categories by category
public DataTable GetCategoryByName(String category)
{
DataTable Dt = mainCatDal.GetCategoryByName(category);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public DataTable GetSubCategoryByName(String subCategory)
{
DataTable Dt = mainCatDal.GetSubCategoryByName(subCategory);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
//Method for manage sub categories
public Boolean InsertSubCategory(Category obj)
{
if (mainCatDal.inserSubCat(obj.catID,obj.subCat , obj.desc, obj.status,obj.uGrouoId,"Admin"))
return true;
else
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace DAL
{
public class TaskDal : DataAccess
{
public DataTable GetAllDataForUser(String user)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT Sender, Message, ReceivedDate FROM FB_MessageReceived";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using DAL;
namespace DAO
{
public class Intraction
{
IntractionDal objItraction = new IntractionDal();
private int type;
public int Type
{
get { return type; }
set { type = value; }
}
private int intractionID;
public int IntractionID
{
get { return intractionID; }
set { intractionID = value; }
}
private int mainCat;
public int MainCat
{
get { return mainCat; }
set { mainCat = value; }
}
private int category;
public int Category
{
get { return category; }
set { category = value; }
}
private int subCat;
public int SubCat
{
get { return subCat; }
set { subCat = value; }
}
private String agentRemarks;
public String AgentRemarks
{
get { return agentRemarks; }
set { agentRemarks = value; }
}
private String status;
public String Status
{
get { return status; }
set { status = value; }
}
private String modifiedUser;
public String ModifiedUser
{
get { return modifiedUser; }
set { modifiedUser = value; }
}
private int assignGrp;
public int AssignGrp
{
get { return assignGrp; }
set { assignGrp = value; }
}
private int reassign;
public int Reassign
{
get { return reassign; }
set { reassign = value; }
}
public Boolean UpdateIntraction(Intraction obj)
{
if (objItraction.UpdateIntraction(obj.intractionID, obj.type, obj.mainCat, obj.category, obj.subCat, obj.agentRemarks, obj.status, obj.modifiedUser, obj.assignGrp, obj.reassign))
return true;
else
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
namespace DAO
{
public class LoginUser
{
//Variables for login
private String userName;
private String password;
public LoginDal dal = new LoginDal();
public String UserName
{
get { return userName; }
set { userName = value; }
}
public String Password
{
get { return password; }
set { password = value; }
}
public DataTable getUser(LoginUser obj)
{
DataTable Dt = dal.getLogin(obj.userName ,obj.password);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using System.Data;
namespace DAO
{
public class UserInfo
{
public UserDal userDal = new UserDal();
private String distribution;
public String Distribution
{
get { return distribution; }
set { distribution = value; }
}
private String userGroupName;
public String UserGroupName
{
get { return userGroupName; }
set { userGroupName = value; }
}
private String userGrouDesc;
public String UserGrouDesc
{
get { return userGrouDesc; }
set { userGrouDesc = value; }
}
private int assignUsers;
public int AssignUsers
{
get { return assignUsers; }
set { assignUsers = value; }
}
private String uName;
public String UName
{
get { return uName; }
set { uName = value; }
}
private String password;
public String Password
{
get { return password; }
set { password = value; }
}
private String email;
public String Email
{
get { return email; }
set { email = value; }
}
private int status;
public int Status
{
get { return status; }
set { status = value; }
}
private String userMode;
public String UserMode
{
get { return userMode; }
set { userMode = value; }
}
public bool SaveUserDetails(UserInfo objuser)
{
if (userDal.InserUserDetails(objuser.uName,objuser.password,objuser.email,objuser.status,objuser.userMode))
return true;
else
return false;
}
public DataTable GetUserData(UserInfo objuser)
{
DataTable Dt = userDal.GetAllDataForUser(objuser.userMode);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public DataTable GetUserByName(String user)
{
DataTable Dt = userDal.GetUserByName(user);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public DataTable GetAllusers()
{
DataTable Dt = userDal.GetAllusers();
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public bool SaveUserGroupDetails(UserInfo objuser)
{
if (userDal.InserUserGroupDetails(objuser.userGroupName, objuser.userGrouDesc, objuser.status, objuser.distribution))
return true;
else
return false;
}
public DataTable GetAlluserGroups()
{
DataTable Dt = userDal.GetAllusersAndGroups();
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
public DataTable GetAlluserGroupsBySubCat(int subCat)
{
DataTable Dt = userDal.GetAllusersAndGroupsBySubCat(subCat);
if (Dt.Rows.Count > 0)
return Dt;
else
return Dt;
}
public DataTable GetUserGroupByName(String user)
{
DataTable Dt = userDal.GetDetailsByName(user);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
public bool SaveUserGroupWithUsers(UserInfo objuser)
{
if (userDal.InserUserGroupDetailsWithUsers(objuser.userGroupName,objuser.uName))
return true;
else
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace DAL
{
public class UserDal : DataAccess
{
public Boolean InserUserDetails(String uname, String password, String email, int status, String mode)
{
try
{
SqlParameter[] param = new SqlParameter[5];
param[0] = new SqlParameter("@UserName", uname);
param[1] = new SqlParameter("@Password", password);
param[2] = new SqlParameter("@EmailAdd", email);
param[3] = new SqlParameter("@Status", status);
param[4] = new SqlParameter("@UserMode", mode);
callSp("Sp_InsertUser", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllDataForUser(String userMode)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT * FROM CIA_User WHERE UserMode = '" + userMode + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetUserByName(String Uname)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT UserID, Username, Password, Email, IsActive, CreatedDate, Login, UserMode FROM CIA_User where Username= '" + Uname + "' ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllusers()
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT UserID, Username, Password, Email, IsActive, CreatedDate, Login, UserMode FROM CIA_User ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public Boolean InserUserGroupDetails(String uGroupname, String desc, int status, String distribution)
{
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@UserGroupName", uGroupname);
param[1] = new SqlParameter("@Desc", desc);
param[2] = new SqlParameter("@Status", status);
param[3] = new SqlParameter("@Distribution", distribution);
callSp("Sp_InsertUserGroups", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public Boolean InserUserGroupDetailsWithUsers(String uGroupname, String @User)
{
try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@Group", uGroupname);
param[1] = new SqlParameter("@User", @User);
callSp("Sp_InsertUserGroupsToUsers", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllusersAndGroups()
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT CIA_User.Username, CIA_UserGroups.GroupID, CIA_Group.GroupName, CIA_Group.Description, CIA_Group.IsActive FROM CIA_User INNER JOIN "+
" CIA_UserGroups ON CIA_User.UserID = CIA_UserGroups.UserID RIGHT OUTER JOIN "+
" CIA_Group ON CIA_UserGroups.GroupID = CIA_Group.GroupID" ;
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllusersAndGroupsBySubCat(int Subcat)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT CIA_SubCategory.SubCatID, CIA_Group.GroupName ,CIA_Group.GroupName,CIA_Group.GroupID FROM CIA_SubCategory INNER JOIN " +
" CIA_Group ON CIA_SubCategory.AssignedGroup = CIA_Group.GroupID where SubCatID ='" + Subcat + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetDetailsByName(String groupName)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT GroupID, GroupName, Description, RegionID, AccessID, IsActive, CreatedDate, Distribution, MaxInteraction, MinInteraction FROM CIA_Group where GroupName ='" + groupName + "' ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using System.Data;
namespace DAO
{
public class PendingOrder : DataAccess
{
//get pending order summary
public List<OrderSummary> GetAllPendingOrder()
{
List<OrderSummary> _lst = new List<OrderSummary>();
string sql = "select * from view_pendingOrder";
SqlDataReader dr = getDataReaderData(sql);
if (dr.HasRows)
{
while (dr.Read())
{
_lst.Add(new OrderSummary
{
customerName = dr["Sender"] != DBNull.Value ? Convert.ToString(dr["Sender"]) : "",
receivedDate = dr["ReceivedDate"] != DBNull.Value ? Convert.ToDateTime(dr["ReceivedDate"]) : DateTime.Now,
orderId = dr["ID"] != DBNull.Value ? Convert.ToString(dr["ID"]) : "",
});
}
}
return _lst;
}
//get current order summary details
public List<CurrentOrderDetails> GetCurrentPendingOrder(string orderId)
{
List<OrderDetails> _lstOrder = new List<OrderDetails>();
List<OrderSummary> _lstCustomer = new List<OrderSummary>();
List<CurrentOrderDetails> _lstCurrentOrder= new List<CurrentOrderDetails>();
string sql = "SELECT DISTINCT dbo.FB_MessageReceived.ID, dbo.FB_MessageReceived.Sender," +
"dbo.FB_MessageReceived.ReceivedDate, dbo.FB_Order_Details.ItemCode, dbo.FB_Order_Details.Qty," +
"dbo.FB_Order_Details.UnitPrice,dbo.FB_Order_Details.Value, dbo.CIA_ItemMaster.ItemName FROM " +
" dbo.FB_MessageReceived INNER JOIN dbo.FB_Order_Details ON " +
"dbo.FB_MessageReceived.ID = dbo.FB_Order_Details.O_id INNER JOIN " +
"dbo.CIA_ItemMaster ON dbo.FB_Order_Details.ItemCode = dbo.CIA_ItemMaster.ItemCode " +
"where FB_MessageReceived.ID ='" + Convert.ToInt16(orderId) + "'";
SqlDataReader dr = getDataReaderData(sql);
if (dr.HasRows)
{
int i = 0;
while (dr.Read())
{
if (i == 0)
{
_lstCustomer.Add(new OrderSummary
{
customerName = dr["Sender"] != DBNull.Value ? Convert.ToString(dr["Sender"]) : "",
receivedDate = dr["ReceivedDate"] != DBNull.Value ? Convert.ToDateTime(dr["ReceivedDate"]) : DateTime.Now,
orderId = dr["ID"] != DBNull.Value ? Convert.ToString(dr["ID"]) : "",
});
}
_lstOrder.Add(new OrderDetails
{
itemCode = dr["ItemCode"] != DBNull.Value ? Convert.ToString(dr["ItemCode"]) : "-",
itemName = dr["ItemName"] != DBNull.Value ? Convert.ToString(dr["ItemName"]) : "-",
qty = dr["Qty"] != DBNull.Value ? Convert.ToString(dr["Qty"]) : "0",
unitPrice = dr["UnitPrice"] != DBNull.Value ? Convert.ToDecimal(dr["UnitPrice"]) : 0,
value = dr["Value"] != DBNull.Value ? Convert.ToDecimal(dr["Value"]) : 0,
});
i++;
}
_lstCurrentOrder.Add(new CurrentOrderDetails
{
customer = _lstCustomer,
currentOrder = _lstOrder
});
}
return _lstCurrentOrder;
}
//update order status
public bool UpdateOrderStatus(string orderId,string status)
{
string sql = "update FB_MessageReceived SET FB_MessageReceived.Status='" + status + "' where FB_MessageReceived.ID='" + Convert.ToInt16(orderId) + "'";
int state = exeNonQury(sql);
return state == 1 ? true : false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace DAL
{
public class CatDal: DataAccess
{
DataTable dt;
public DataTable GetMainCategory(int id)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT TypeID,Type FROM CIA_Type where InteractionTypeID = '" + id + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetCategory(int id)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT CatID ,Category FROM CIA_Category where TypeID = '" + id + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetSubCategoryByCategory(int id)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT SubCatID, CatID, SubCategory, Description, IsActive, CreatedUser, CreatedDate, AssignedGroup FROM CIA_SubCategory where CatID = '" + id + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllMainCategory()
{
try
{
string sql = "";
DataSet dt;
sql = " SELECT CIA_InteractionType.InteractionType, CIA_Type.Type " +
"FROM CIA_Type INNER JOIN " +
"CIA_InteractionType ON CIA_Type.InteractionTypeID = CIA_InteractionType.InteractionTypeID";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllMainCategoryByName(String mainCat)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT * FROM CIA_Type WHERE Type ='" + mainCat + "' ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllDataForCategory()
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT CIA_InteractionType.InteractionType, CIA_Type.Type, CIA_Type.TypeID, CIA_Category.Category ,CIA_Category.Description" +
" FROM CIA_Type INNER JOIN "+
"CIA_InteractionType ON CIA_Type.InteractionTypeID = CIA_InteractionType.InteractionTypeID INNER JOIN "+
"CIA_Category ON CIA_Type.TypeID = CIA_Category.TypeID ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public Boolean insertMainCat(Int32 IntractionTypeID,String mainType,String desc ,int status)
{
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@IntractionTypeID", IntractionTypeID);
param[1] = new SqlParameter("@MainType", mainType);
param[2] = new SqlParameter("@Desc", desc);
param[3] = new SqlParameter("@Status", status);
callSp("Sp_InsertMainCategory",param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public Boolean inserCat(int maincatID ,String category, String desc, int status)
{
try
{
SqlParameter[] param = new SqlParameter[4];
param[0] = new SqlParameter("@MainTypeID", maincatID);
param[1] = new SqlParameter("@Catgegory", category);
param[2] = new SqlParameter("@Desc", desc);
param[3] = new SqlParameter("@Status", status);
callSp("Sp_InsertCategory", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetCategoryByName(String Cat)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT * FROM CIA_Category where Category ='" + Cat + "' ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetSubCategoryByName(String sCat)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT * FROM CIA_SubCategory where SubCategory ='" + sCat + "' ";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
public Boolean inserSubCat(int catID, String category, String desc, int status,int uGroup,String User)
{
try
{
SqlParameter[] param = new SqlParameter[6];
param[0] = new SqlParameter("@CatID", catID);
param[1] = new SqlParameter("@SubCat", category);
param[2] = new SqlParameter("@Description", desc);
param[3] = new SqlParameter("@CreatedUser", User);
param[4] = new SqlParameter("@Status", status);
param[5] = new SqlParameter("@AssignedGroup", uGroup);
callSp("Sp_InsertSubCategory", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable GetAllDataForSubCategory(int catId)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT CIA_InteractionType.InteractionType, CIA_Type.Type, CIA_Type.TypeID, CIA_Category.Category, CIA_Category.Description, CIA_SubCategory.SubCategory, " +
"CIA_SubCategory.Description AS Expr1 FROM CIA_Type INNER JOIN" +
" CIA_InteractionType ON CIA_Type.InteractionTypeID = CIA_InteractionType.InteractionTypeID INNER JOIN " +
" CIA_Category ON CIA_Type.TypeID = CIA_Category.TypeID INNER JOIN " +
"CIA_SubCategory ON CIA_Category.CatID = CIA_SubCategory.CatID where CIA_SubCategory.CatID ='" + catId + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>
var loginAuth = (function () {
var UserName ='admin'
var Password ='<PASSWORD>'
return {
login: function (uName, pwd) {
if (uName == UserName && Password == pwd) {
window.location.href = "pendingOrders.aspx";
return;
}
else {
//invlid login details
notie.alert(3, 'Invalid use name or password!', 3);
return;
}
}
}
})();
$('#loginBtn').on('click', function () {
var userName = $('#userName').val();
var passWord = $('#password').val();
if (!userName) {
notie.alert(3, 'Please enter user name', 3);
$('#userName').focus();
return;
}
if (!passWord) {
notie.alert(3, 'Please enter passsowrd', 3);
$('#password').focus();
return;
}
loginAuth.login(userName,passWord);
});
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAO
{
public class OrderDetails
{
public string qty { get; set; }
public decimal unitPrice { get; set; }
public decimal value { get; set; }
public float total { get; set; }
public string itemName { get; set; }
public string itemCode { get; set; }
}
public class OrderSummary
{
public string customerName { get; set; }
public string orderId { get; set; }
public DateTime receivedDate { get; set; }
}
public class CurrentOrderDetails
{
public List<OrderSummary> customer { get; set; }
public List<OrderDetails> currentOrder { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using DAL;
namespace DAO
{
public class Tasks
{
private String UserName;
TaskDal taskObj = new TaskDal();
public String UserName1
{
get { return UserName; }
set { UserName = value; }
}
public DataTable GetTasksUserWise(String userName)
{
DataTable Dt = taskObj.GetAllDataForUser(userName);
if (Dt.Rows.Count > 0)
return Dt;
else
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DAL;
using System.Data.SqlClient;
namespace DAO
{
public class CompleteOrder:DataAccess
{
public List<OrderSummary> GetAllCompletOrder()
{
List<OrderSummary> _lst = new List<OrderSummary>();
string sql = "select * from view_completOrder";
SqlDataReader dr = getDataReaderData(sql);
if (dr.HasRows)
{
while (dr.Read())
{
_lst.Add(new OrderSummary
{
customerName = dr["Sender"] != DBNull.Value ? Convert.ToString(dr["Sender"]) : "",
receivedDate = dr["ReceivedDate"] != DBNull.Value ? Convert.ToDateTime(dr["ReceivedDate"]) : DateTime.Now,
orderId = dr["ID"] != DBNull.Value ? Convert.ToString(dr["ID"]) : "",
});
}
}
return _lst;
}
}
}
<file_sep>
var getPendingOrder = function () {
$('#table_id').html("");
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: 'services/pendingOredrService.asmx/GetPendingOrder',
success: function (data) {
var order = JSON.parse(data.d);
for (var i = 0; i < order.length; i++) {
$('#table_id').append("<tr><td>" + order[i].orderId +
"</td><td>" + order[i].customerName +
"</td><td>" + order[i].receivedDate +
"</td></td><td><button type='button' data-toggle='modal' data-target='#myModal'" +
"onClick='vieweMoreDetails(" + order[i].orderId + ")' class='btn btn-info'>" +
" View Order</button></td></tr>");
}
},
error: function (repo) {
console.log("error"+ repo);
}
});
}
getPendingOrder();
var getProcessingOrder = function () {
$('#tablePro_id').html("");
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: 'services/pendingOredrService.asmx/GetProcessingOrder',
success: function (data) {
var order = JSON.parse(data.d);
for (var i = 0; i < order.length; i++) {
$('#tablePro_id').append("<tr><td>" + order[i].orderId +
"</td><td>" + order[i].customerName +
"</td><td>" + order[i].receivedDate +
"</td></td><td><button type='button' data-toggle='modal'" +
"onClick='updateOrder(" + order[i].orderId + ",3)' class='btn btn-warning'>" +
" Order Complete</button></td></tr>");
}
},
error: function (repo) {
console.log("error" + repo);
}
});
}
getProcessingOrder();
var getCompleteOrder = function () {
$('#tableComplete_id').html("");
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: 'services/pendingOredrService.asmx/GetCompeleteOrder',
success: function (data) {
var order = JSON.parse(data.d);
for (var i = 0; i < order.length; i++) {
$('#tableComplete_id').append("<tr><td>" + order[i].orderId +
"</td><td>" + order[i].customerName +
"</td><td>" + order[i].receivedDate +
"</td></td><td><button type='button' data-toggle='modal'" +
" class='btn btn-success disabled'>" +
" Complete</button></td></tr>");
}
},
error: function (repo) {
console.log("error" + repo);
}
});
}
getCompleteOrder();
var vieweMoreDetails = function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({ 'orderId': id}),
contentType: "application/json",
dataType: "json",
url: 'services/pendingOredrService.asmx/GetCurrentPendingOrder',
success: function (data) {
var currentOrder = JSON.parse(data.d);
$('#OrderView_id').html("");
$('#total').html("");
var total = parseInt("0");
if (currentOrder.length > 0) {
document.getElementById('orderId').innerHTML = currentOrder[0].customer[0].orderId;
document.getElementById('customerName').innerHTML = currentOrder[0].customer[0].customerName;
for (var i = 0; i < currentOrder[0].currentOrder.length; i++) {
total = total + parseInt(currentOrder[0].currentOrder[i].value)
$('#OrderView_id').append("<tr><td>" + currentOrder[0].currentOrder[i].itemName +
"</td><td>" + currentOrder[0].currentOrder[i].itemCode +
"</td><td>" + +currentOrder[0].currentOrder[i].qty +
"</td><td>" + +currentOrder[0].currentOrder[i].unitPrice +
"</td><td>" + +currentOrder[0].currentOrder[i].value +
"</tr>");
}
document.getElementById('total').innerHTML = total = null ? "Total Rs : 0" : "Total Rs : " + total;
}
},
error: function (repo) {
console.log("error" + repo);
}
});
}
var updateOrder = function (orderId, status) {
var orderId = orderId;
var status = status;
if (orderId == null || orderId == "") {
var orderId = document.getElementById('orderId').innerHTML;
var status = 2;
}
$.ajax({
type: "POST",
data: JSON.stringify({ 'orderId': orderId, 'status': status }),
contentType: "application/json",
dataType: "json",
url: 'services/pendingOredrService.asmx/UpdateOrderStatus',
success: function (data) {
if (data.d) {
getPendingOrder();
getProcessingOrder();
$('#myModal').modal('toggle');
}
},
error: function (repo) {
console.log("error" + repo);
}
});
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
namespace DAL
{
public class IntractionDal : DataAccess
{
public Boolean UpdateIntraction(Int32 intractionID, int type, int mainCat, int cat, int subCat, String agentRemarks, String status, String modifiedUser, int assignGrp, int reassign)
{
try
{
SqlParameter[] param = new SqlParameter[10];
param[0] = new SqlParameter("@IntractionID", intractionID);
param[1] = new SqlParameter("@MainCat", mainCat);
param[2] = new SqlParameter("@Cat", cat);
param[3] = new SqlParameter("@SubCat", subCat);
param[4] = new SqlParameter("@AgentRemarks", agentRemarks);
param[5] = new SqlParameter("@Status", status);
param[6] = new SqlParameter("@ModifiedUser", modifiedUser);
param[7] = new SqlParameter("@AssignedGroup", assignGrp);
param[8] = new SqlParameter("@Reassign", reassign);
param[9] = new SqlParameter("@Type", type);
callSp("Sp_UpdateIntraction", param);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using DAO;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace OnlineOrderSystem.services
{
/// <summary>
/// Summary description for pendingOredrService
/// </summary>
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
[System.Web.Script.Services.ScriptService]
public class pendingOredrService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPendingOrder()
{
List<OrderSummary> _lstPendingLst = new List<OrderSummary>();
PendingOrder _pendingOrder = new PendingOrder();
_lstPendingLst = _pendingOrder.GetAllPendingOrder();
var jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(_lstPendingLst);
return jsonss;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetProcessingOrder()
{
List<OrderSummary> _lstPendingLst = new List<OrderSummary>();
ProcessingOrder _processingOrder = new ProcessingOrder();
_lstPendingLst = _processingOrder.GetAllProcessingOrder();
var jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(_lstPendingLst);
return jsonss;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCompeleteOrder()
{
List<OrderSummary> _lstPendingLst = new List<OrderSummary>();
CompleteOrder _compeletgOrder = new CompleteOrder();
_lstPendingLst = _compeletgOrder.GetAllCompletOrder();
var jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(_lstPendingLst);
return jsonss;
}
//{ parameter orderId = 0}
//get current pending order
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCurrentPendingOrder(string orderId)
{
List<CurrentOrderDetails> _lstCurrentOrderLst = new List<CurrentOrderDetails>();
PendingOrder _pendingOrder = new PendingOrder();
_lstCurrentOrderLst = _pendingOrder.GetCurrentPendingOrder(orderId);
var jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(_lstCurrentOrderLst);
return jsonss;
}
//update status
//order procssing
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool UpdateOrderStatus(string orderId,string status)
{
PendingOrder _pendingOrder = new PendingOrder();
if (string.IsNullOrEmpty(orderId) || string.IsNullOrEmpty(status))
{
return false;
}
return _pendingOrder.UpdateOrderStatus(orderId, status);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace DAL
{
public class LoginDal : DataAccess
{
DataTable dt;
// This method to get the user details for the given login details
public DataTable getLogin(String uname ,String password)
{
try
{
string sql = "";
DataSet dt;
sql = "SELECT * FROM CIA_User where Username= '" + uname + "' and Password ='" + password + "'";
dt = getDataset(sql);
return dt.Tables[0];
}
catch (Exception ex)
{
throw ex;
}
}
}
}
| 4fb69aca410361a7f127ebe9fdddc3d2465c01d8 | [
"JavaScript",
"C#"
] | 16 | C# | ishan099/SOPS-UI | 3d8fc2ee81bf1d56757a7a62671cc4da9a1033db | bc21d473bdcf19a68e110e59d8589c14ca33257a | |
refs/heads/main | <file_sep><?php
Auth::routes();
// front content
Route::get('/', 'FrontController@index')->name('index');
Route::get('cart', 'FrontController@cart')->name('cart');
Route::get('/product/{id}', 'FrontController@view')->name('view');
Route::get('/catalog/{id?}', 'FrontController@catalog')->name('catalog');
Route::get('add-to-cart/{id}', 'FrontController@addToCart')->name('addToCart');
Route::get('search', 'FrontController@search')->name('search');
// for ajax
Route::patch('update-cart', 'FrontController@update');
Route::delete('remove-from-cart', 'FrontController@remove');
Route::get('/home', 'HomeController@index')->name('home');
// edit group
Route::group(['middleware' => ['auth']], function () {
Route::group(['prefix' => 'edit-product'], function () {
Route::get('/', 'Backend\ProductsController@index')->name('edit-product.index');
Route::post('/', 'Backend\ProductsController@store')->name('edit-product.store');
Route::get('/{id}', 'Backend\ProductsController@edit')->name('edit-product.edit');
Route::patch('/{id}', 'Backend\ProductsController@update')->name('edit-product.update');
Route::delete('/{id}', 'Backend\ProductsController@destroy')->name('edit-product.delete');
});
Route::group(['prefix' => 'edit-categories'], function () {
Route::get('/', 'Backend\CategoriesController@index')->name('edit-categories.index');
Route::post('/', 'Backend\CategoriesController@store')->name('edit-categories.store');
Route::get('/{id}', 'Backend\CategoriesController@edit')->name('edit-categories.edit');
Route::patch('/{id}', 'Backend\CategoriesController@update')->name('edit-categories.update');
Route::delete('/{id}', 'Backend\CategoriesController@destroy')->name('edit-categories.delete');
});
});
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = ['_token', 'id'];
static function TakeParent($id = 0)
{
$result = self::where('parentId', $id)->get();
return $result;
}
public function takeBreadcrumb()
{
$temp = ($this->parentId !== 0) ? $this->recursia($this->parentId) : [];
return $temp;
}
public function recursia($id, $array = [])
{
var_dump($id);
$temp = Category::where('id', $id)->first();
echo $temp->name;
if ($temp) {
array_unshift( $array,[
$temp->name,
$temp->id
]);
if ($temp->parentId !== 0) {
$array = $this->recursia($temp->parentId, $array);
}
return $array;
}
}
public function ProductCategory(){
return $this->hasMany($this, 'parentId');
}
public function rootCategories(){
return $this->where('parentId', 0)->with('ProductCategory')->get();
}
public function products()
{
return $this->hasMany(Product::class, 'category_id', 'id');
}
public function categories()
{
return $this->hasMany(Category::class, 'parentId', 'id');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use App\User;
use Illuminate\Support\Facades\DB;
class UsersTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->insert([
'name' => 'test',
'email' => '<EMAIL>',
'password' => bcrypt('<PASSWORD>'),
]);
$users = factory(User::class, 20)->create();
}
}
<file_sep><?php
namespace App\Http\Controllers\Backend;
use App\Http\Requests\StoreCategoryRequest;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CategoriesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$data = new Category();
$action = route('edit-categories.store');
return view('backend.categories.index')->with(compact('data', 'action'));
}
public function store(StoreCategoryRequest $request)
{
$data = new Category($request->toArray());
if (!$data) {
abort(404);
}
$data->save();
return back();
}
public function update(StoreCategoryRequest $request)
{
$data = Category::find($request->id);
if (!$data) {
abort(404);
}
$data->name = $request->name;
$data->parentId = $request->parentId;
$data->save();
return redirect(route('edit-categories.index'));
}
public function destroy(Request $request)
{
$data = Category::find($request->id);
if (!$data) {
abort(404);
}
$data->delete();
return back();
}
public function edit($id)
{
$data = Category::find($id);
$action = route('edit-categories.update', ['id' => $id]);
return view('backend.categories.index')->with(compact('data', 'action'));
}
}
<file_sep><?php
use App\Models\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'name' => $faker->name(10),
'description' => $faker->text(110),
'price' => rand(1, 10),
'category_id' => rand(1, 10),
];
});
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $guarded = ['_token', 'id'];
public static function search($search, $category)
{
$data = Product::where('name', 'LIKE', "%{$search}%")->where('category_id', 'LIKE', $category)->get();
return $data;
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
class FrontController extends Controller
{
public function index()
{
$products = Product::paginate(9);
return view('front/main', compact('products'));
}
public function view($id)
{
$product = Product::find($id);
if (!$product) {
abort(404);
}
return view('front/view', compact('product'));
}
public function cart()
{
return view('front/cart');
}
public function catalog(Request $request)
{
$result = null;
$name = '';
$products = [];
$breadcrumb = [];
if (isset($request->id)) {
$temp = Category::where('id', $request->id)->first();
$name = ' - ' . $temp->name;
// $result = $temp->categories();
// $products = $temp->products();
// Рилейшены чего-то не работали я сделал так не обессудьте
$result = Category::where('parentId', $temp->id)->get()->toArray();
$products = Product::where('category_id', $temp->id)->get()->toArray();
$breadcrumb = $temp->takeBreadcrumb();
} else {
$result = Category::TakeParent()->toArray();
}
$data = (object)[
'name' => $name,
'catalogs' => $result,
'products' => $products,
'breadcrumb' => $breadcrumb,
];
return view('front/categories', compact('data'));
}
public function addToCart($id)
{
$product = Product::find($id);
if (!$product) {
abort(404);
}
$cart = session()->get('cart');
// если корзина пуста, то это первый товар
if (!$cart) {
$cart = [
$id => [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
]
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// если корзина не пуста, проверяет , существует ли этот товар, затем увеличьте количество
if (isset($cart[$id])) {
$cart[$id]['quantity']++;
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
// если товара нет в корзине, добавьте в корзину с количеством = 1
$cart[$id] = [
"name" => $product->name,
"quantity" => 1,
"price" => $product->price,
];
session()->put('cart', $cart);
return redirect()->back()->with('success', 'Product added to cart successfully!');
}
public function update(Request $request)
{
if ($request->id and $request->quantity) {
$cart = session()->get('cart');
$cart[$request->id]["quantity"] = $request->quantity;
session()->put('cart', $cart);
session()->flash('success', 'Cart updated successfully');
}
}
public function remove(Request $request)
{
if ($request->id) {
$cart = session()->get('cart');
if (isset($cart[$request->id])) {
unset($cart[$request->id]);
session()->put('cart', $cart);
}
session()->flash('success', 'Product removed successfully');
}
}
public function search(Request $request)
{
$search = $request->input('search');
$category = $request->input('category_id');
$products = Product::search($search, $category);
// $products = $query->paginate(6)->withQueryString();
return view('front.search', compact('products', 'search'));
}
}
<file_sep><?php
namespace App\Http\Controllers\Backend;
use App\Http\Requests\StoreProfuctRequest;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProductsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$data = new Product;
$action = route('edit-product.store');
return view('backend.products.index')->with(compact('data', 'action'));
}
public function store(StoreProfuctRequest $request)
{
$data = new Product($request->toArray());
if (!$data) {
abort(404);
}
$data->save();
return back();
}
public function update(StoreProfuctRequest $request)
{
$data = Product::find($request->id);
if (!$data) {
abort(404);
}
$data->name = $request->name;
$data->description = $request->description;
$data->price = $request->price;
$data->category_id = $request->category_id;
$data->save();
return redirect(route('edit-product.index'));
}
public function destroy(Request $request)
{
$data = Product::find($request->id);
if (!$data) {
abort(404);
}
$data->delete();
return back();
}
public function edit($id)
{
$data = Product::find($id);
$action = route('edit-product.update', ['id' => $id]);
return view('backend.products.index')->with(compact('data', 'action'));
}
}
| 9812718db1c3914b77393105417d836ca02dd312 | [
"PHP"
] | 8 | PHP | georgij-terleckij/shop-test | 9200e4e9ab6db0ad7705ed6d9fd80ffa5e188ca4 | 9d90bbd5fabede0f3105699bdfe92be2e89ea7a9 | |
refs/heads/master | <repo_name>vrjolke/selenium-first-practice<file_sep>/src/test/com/codecool/bence/selenium/SeleniumTasksTest.java
package com.codecool.bence.selenium;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SeleniumTasksTest {
private static SeleniumTasks st;
@BeforeAll
static void setup(){
st = new SeleniumTasks();
}
@Test
void datePicker() {
assertEquals(1, st.datePicker(2019, "Jan", 14));
}
@Test
void testNavigateToSimpleForms() {
assertEquals("https://www.seleniumeasy.com/test/basic-first-form-demo.html", st.navigateToSimpleForms());
}
@Test
void testSingleFiendAndButton() {
assertEquals("Hello World", st.singleFiendAndButton("Hello World"));
}
@Test
void testTwoFieldsAndButton() {
assertEquals("15", st.twoFieldsAndButton("5", "10"));
}
@Test
void testTwoFieldsAndButtonWithLargeNumbers() {
assertEquals("10000000000000000000000", st.twoFieldsAndButton("5000000000000000000000", "5000000000000000000000"));
}
@Test
void testSingleCheckbox() {
assertEquals("Success - Check box is checked", st.singleCheckbox());
}
@Test
void testMultipleCheckboxCheckAll() {
assertEquals(true, st.multipleCheckboxCheckAll());
}
@Test
void testMultipleCheckboxUncheckAll() {
assertEquals(true, st.multipleCheckboxUncheckAll());
}
@Test
void testMultipleCheckboxUncheckOne() {
assertEquals("Check All", st.multipleCheckboxUncheckOne());
}
@Test
void testSelectList() {
assertEquals("Day selected :- Tuesday", st.selectList());
}
@Test
void testSelectListAlternative() {
assertEquals("Day selected :- Tuesday", st.selectListAlternative());
}
@Test
void testGroupRadioButtons() {
String[] expected = {"Sex : Male\n" +
"Age group: 0 - 5","Sex : Female\n" +
"Age group: 15 - 50"};
assertArrayEquals(expected, st.groupRadioButtons());
}
@Test
void sortAndSearchSum() {
assertEquals(1164, st.sortAndSearchSum());
}
}
<file_sep>/src/main/java/com/codecool/bence/selenium/SeleniumTasks.java
package com.codecool.bence.selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.Calendar;
import java.util.List;
public class SeleniumTasks {
public static String driverPath = "/usr/bin/chromedriver";
public static WebDriver driver;
public SeleniumTasks() {
this.driver = new ChromeDriver();
System.setProperty("webdriver.chrome.driver", driverPath);
}
public String navigateToSimpleForms() {
driver.navigate().to("https://www.seleniumeasy.com/test/");
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("treemenu")));
driver.findElement(By.cssSelector("#treemenu > li > ul > li:nth-child(1) > a")).click();
driver.findElement(By.linkText("Simple Form Demo")).click();
String url = driver.getCurrentUrl();
return url;
}
public String singleFiendAndButton(String inputMessage) {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-first-form-demo.html");
driver.findElement(By.id("user-message")).sendKeys(inputMessage);
driver.findElement(By.cssSelector("#get-input > button")).click();
String message = driver.findElement(By.id("display")).getText();
return message;
}
public String twoFieldsAndButton(String input1, String input2) {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-first-form-demo.html");
// WebDriverWait wait = new WebDriverWait(driver, 20);
// wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("sum1")));
driver.findElement(By.id("sum1")).sendKeys(input1);
driver.findElement(By.id("sum2")).sendKeys(input2);
driver.findElement(By.cssSelector("#gettotal > button")).click();
String sum = driver.findElement(By.id("displayvalue")).getText();
return sum;
}
public String singleCheckbox() {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
driver.findElement(By.id("isAgeSelected")).click();
String message = driver.findElement(By.id("txtAge")).getText();
return message;
}
public void navigateAndClickCheckboxDemoButton() {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-checkbox-demo.html");
driver.findElement(By.id("check1")).click();
}
public boolean multipleCheckboxCheckAll() {
navigateAndClickCheckboxDemoButton();
List<WebElement> checkboxes = driver.findElements(By.cssSelector("input.cb1-element"));
for (WebElement checkbox : checkboxes) {
if (!checkbox.isSelected()) {
return false;
}
}
return true;
}
public boolean multipleCheckboxUncheckAll() {
navigateAndClickCheckboxDemoButton();
driver.findElement(By.id("check1")).click();
List<WebElement> checkboxes = driver.findElements(By.cssSelector("input.cb1-element"));
for (WebElement checkbox : checkboxes) {
if (checkbox.isSelected()) {
return false;
}
}
return true;
}
public String multipleCheckboxUncheckOne() {
navigateAndClickCheckboxDemoButton();
driver.findElements(By.cssSelector("input.cb1-element")).get(0).click();
String buttonText = driver.findElement(By.id("check1")).getAttribute("value");
return buttonText;
}
public String selectList() {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");
Select dropdownDays = new Select(driver.findElement(By.id("select-demo")));
dropdownDays.selectByVisibleText("Tuesday");
// String selectedOption = dropdownDays.getFirstSelectedOption().getText();
String selectedOption = driver.findElement(By.cssSelector("div.panel-body > p.selected-value")).getText();
return selectedOption;
}
public String selectListAlternative() {
driver.navigate().to("https://www.seleniumeasy.com/test/basic-select-dropdown-demo.html");
driver.findElement(By.id("select-demo")).click();
driver.findElement(By.cssSelector("#select-demo > option:nth-child(4)")).click();
String selectedOption = driver.findElement(By.cssSelector("div.panel-body > p.selected-value")).getText();
return selectedOption;
}
public String[] groupRadioButtons(){
driver.navigate().to("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");
String[] results = new String[2];
driver.findElement(By.cssSelector(generateRadioButtonSelector(2,2))).click();
driver.findElement(By.cssSelector(generateRadioButtonSelector(3,2))).click();
driver.findElement(By.cssSelector("#easycont div.panel-body > button")).click();
String resultText = driver.findElement(By.cssSelector("#easycont div.panel-body > p.groupradiobutton")).getText();
results[0] = resultText;
driver.findElement(By.cssSelector(generateRadioButtonSelector(2,3))).click();
driver.findElement(By.cssSelector(generateRadioButtonSelector(3,4))).click();
driver.findElement(By.cssSelector("#easycont div.panel-body > button")).click();
resultText = driver.findElement(By.cssSelector("#easycont div.panel-body > p.groupradiobutton")).getText();
results[1] = resultText;
return results;
}
public String generateRadioButtonSelector(int row, int col){
return "#easycont div.panel-body > div:nth-child("+row+") > label:nth-child("+col+") > input[type=radio]";
}
public int datePicker(int year, String month, int day){
driver.navigate().to("https://www.seleniumeasy.com/test/bootstrap-date-picker-demo.html");
driver.findElement(By.cssSelector("#sandbox-container1 > div > span")).click();
navigateTo(year, month);
List<WebElement> daysElements = driver.findElements(By.cssSelector("div.datepicker-days > table > tbody > tr > td"));
for(WebElement dayElement : daysElements){
if (dayElement.getAttribute("class").equals("day")) {
//System.out.println("Index: "+daysElements.indexOf(dayElement) % 7 + " Day: "+dayElement.getText());
if (dayElement.getText().equals(Integer.toString(day))) {
return daysElements.indexOf(dayElement) % 7 + 1;
}
}
}
return -1;
}
public void navigateTo(int year, String month){
String selectorYearString = driver.findElement(By.cssSelector("body table > thead > tr:nth-child(2) > th.datepicker-switch")).getText();
int selectorYear = Integer.parseInt(selectorYearString.substring(selectorYearString.length()-4));
driver.findElement(By.cssSelector("div.datepicker-days th.datepicker-switch")).click();
while(selectorYear != year){
driver.findElement(By.cssSelector("div.datepicker-months > table > thead > tr:nth-child(2) > th.prev")).click();
selectorYearString = driver.findElement(By.cssSelector("body div.datepicker-months > table > thead > tr:nth-child(2) > th.datepicker-switch")).getText();
selectorYear = Integer.parseInt(selectorYearString.substring(selectorYearString.length()-4));
}
List<WebElement> monthElements = driver.findElements(By.cssSelector("div.datepicker-months > table > tbody > tr > td > span"));
for(WebElement monthElement : monthElements){
if (monthElement.getText().equals(month)) {
monthElement.click();
break;
}
}
}
public int sortAndSearchSum(){
driver.navigate().to("https://www.seleniumeasy.com/test/table-sort-search-demo.html");
Select dropdownDays = new Select(driver.findElement(By.cssSelector("#example_length > label > select")));
dropdownDays.selectByVisibleText("25");
int ageSum = 0;
List<WebElement> ageCells = driver.findElements(By.cssSelector("#example > tbody > tr > td:nth-child(4)"));
for(WebElement ageCell : ageCells){
ageSum += Integer.parseInt(ageCell.getText());
}
return ageSum;
}
}
| 67113391704aeff7c704ac8764ba928e1d689819 | [
"Java"
] | 2 | Java | vrjolke/selenium-first-practice | 30aa9d25ee642ec723201d1228add68920fb1e30 | 2f2ca062aa05517c05a61d50eec610d87d60109d | |
refs/heads/master | <file_sep>import {Graph} from '@src/app/models/graph';
import {Square} from '@src/app/models/square';
import {Player} from '@src/app/models/player';
import {Edge} from '@src/app/models/edge';
export interface Game {
id: string;
graph: Graph;
squares: Square[];
players: Player[];
currentPlayerIdx: number;
moves: Edge[] | undefined;
}
<file_sep>import {GameComponent} from '@src/app/components/game/game.component';
describe('GameComponent', () => {
// let component: GameComponent;
// let fixture: ComponentFixture<GameComponent>;
// const gameService = jasmine.createSpyObj('GameService', ['getGame', 'setGame']);
// const authService = jasmine.createSpyObj('AuthService', ['getCurrentUser', 'googleSignin', 'signOut']);
//
// beforeEach(async(() => {
// TestBed.configureTestingModule({
// declarations: [GameComponent],
// providers: [
// {provide: GameService, useValue: gameService},
// {provide: AuthService, useValue: authService},
// ],
// })
// .compileComponents();
// }));
//
// beforeEach(async () => {
// const graph = Graph.initialize(5, 5);
// player1 = Player.create(0, 'Alice', '<PASSWORD>', 0);
// player2 = Player.create(1, 'Bob', '#F08080', 0);
// gameService.getGame.and.returnValue(from(Promise.resolve(
// <Game>{
// id: '1234',
// graph: graph,
// squares: Square.fromGraph(graph),
// players: [
// player1,
// player2,
// ],
// currentPlayerIdx: 0,
// },
// )));
// authService.getCurrentUser.and.returnValue(from(Promise.resolve(
// <User>{
// uid: '1',
// email: '<EMAIL>',
// },
// )));
// fixture = TestBed.createComponent(GameComponent);
// component = fixture.componentInstance;
// await component.onlineGame$.toPromise();
// fixture.detectChanges();
// });
//
// it('should render ownerless edges grey', () => {
// const edge = fixture.debugElement.query(By.css('#edge-0-0-1-1'));
// expect(edge.attributes['stroke']).toEqual('#ccc');
// });
//
// it('should change the owner of an edge on click and move to the next player', () => {
// const currentPlayer = component.currentPlayer(component.game$.value);
// const edge = fixture.debugElement.query(By.css('#edge-0-0-1-1'));
// edge.triggerEventHandler('click', null);
// expect(component.game$.value.graph.edges.find(e => e.owner.id === currentPlayer.id))
// .toBeTruthy();
// expect(component.currentPlayer(component.game$.value) === currentPlayer).toEqual(false);
// });
//
// it('should render player edges with the respective color', () => {
// component.game$.value.graph.edges[0].owner = player1;
// fixture.detectChanges();
//
// const edge = fixture.debugElement.query(By.css('#edge-0-0-1-1'));
// expect(edge.attributes['stroke']).toEqual(player1.color);
// });
//
// it('should render ownerless squares with the respective color', () => {
// const edge = fixture.debugElement.query(By.css('#square-0-0'));
// expect(edge.attributes['fill']).toEqual('#ccc');
// });
//
// it('should render player squares with the respective color', () => {
// component.game$.value.squares[0].owner = player1;
// component.game$.next(component.game$.value);
// fixture.detectChanges();
// const square = fixture.debugElement.query(By.css('#square-0-0'));
// expect(square.attributes['fill']).toEqual(player1.color);
// });
//
// it('should render the score', () => {
// component.game$.value.players[0].score = 5;
// component.game$.value.players[1].score = 3;
// component.game$.next(component.game$.value);
// fixture.detectChanges();
// const score1 = fixture.debugElement.query(By.css('#score-0'));
// const score2 = fixture.debugElement.query(By.css('#score-1'));
// expect(score1.nativeElement.textContent.trim()).toEqual('Alice: 5');
// expect(score2.nativeElement.textContent.trim()).toEqual('Bob: 3');
// });
//
// it('should behave correctly after closing a section', () => {
// drawEdge(0, 0, 1, 0);
// drawEdge(1, 0, 1, 1);
// drawEdge(0, 1, 1, 1);
// drawEdge(0, 0, 0, 1);
// expect(component.game$.value.squares[0].owner.id).toEqual(player2.id);
// expect(component.game$.value.players[1].score).toEqual(1);
// });
//
// it('should not change the owner squares that already have an owner', () => {
// // TODO but needs multiplayer capabilities
// });
//
// function drawEdge(x1: number, y1: number, x2: number, y2: number) {
// component.drawEdge(
// component.game$.value.graph.edges.find(e =>
// e.source.x === x1 && e.source.y === y1 && e.target.x === x2 && e.target.y === y2,
// ),
// component.game$.value,
// );
// }
});
<file_sep>import {Component, OnDestroy, OnInit} from '@angular/core';
import {Graph} from '@src/app/models/graph';
import {Edge} from '@src/app/models/edge';
import {Square} from '@src/app/models/square';
import {Polygon} from '@src/app/models/polygon';
import {GameService} from '@src/app/services/game.service';
import {AuthService} from '@src/app/services/auth.service';
import {map, switchMap} from 'rxjs/operators';
import {Game} from '@src/app/models/game';
import {UserStateType} from '@src/app/models/user-state';
import {ActivatedRoute} from '@angular/router';
import {EdgeStyle} from '@src/app/models/edge-style';
@Component({
selector: 'pnp-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css'],
})
export class GameComponent implements OnInit, OnDestroy {
constructor(
public gameService: GameService,
public auth: AuthService,
private route: ActivatedRoute,
) {
}
game$ = this.route.paramMap.pipe(
switchMap(params => this.gameService.getGame(params.get('id'))),
);
svgScalingFactor = 25;
viewBox$ = this.game$.pipe(
map(game => ({
width: game.graph.xSize * this.svgScalingFactor,
height: game.graph.ySize * this.svgScalingFactor,
}),
),
);
defaultEdgeStroke = '#ccc';
defaultEdgeOpacity = 1;
edgeStrokes$ = this.game$.pipe(
map(game => game.graph.edges.map(() => (<EdgeStyle>{
stroke: this.defaultEdgeStroke,
opacity: this.defaultEdgeOpacity,
}))),
);
userState = UserStateType;
currentPlayer(game: Game) {
return game.players[game.currentPlayerIdx];
}
scalePosition(pos: number): number {
return pos * this.svgScalingFactor + (this.svgScalingFactor / 2);
}
drawEdge(edge: Edge, game: Game) {
if (!Edge.isOwned(edge)) {
const player = this.currentPlayer(game);
const path = Graph.findPath(game.graph, edge.source, edge.target);
if (path.length > 0) {
const polygon = Polygon.fromPath(path);
const wonSquares = game.squares.filter(square => polygon.contains(square) && !Square.isOwned(square));
wonSquares.forEach(square => square.owner = player);
player.score += wonSquares.length;
} else {
this.nextPlayer(game);
}
if (Array.isArray(game.moves)) {
game.moves.push(edge);
}
edge.owner = player;
this.gameService.setGame(game);
}
}
nextPlayer(game: Game) {
if (game.currentPlayerIdx === game.players.length - 1) {
game.currentPlayerIdx = 0;
} else {
game.currentPlayerIdx++;
}
}
wasRecentlyDrawn(edge: Edge, game: Game): boolean {
if (Array.isArray(game.moves) && game.moves.length > 0) {
const lastMove = game.moves[game.moves.length - 1];
return Edge.hasSameCoordinates(edge, lastMove);
} else {
return false;
}
}
ngOnInit() {
}
ngOnDestroy() {
}
}
<file_sep>import {Graph} from '@src/app/models/graph';
import {Square} from '@src/app/models/square';
import {Vertex} from '@src/app/models/vertex';
describe('Square', () => {
describe('fromGraph', () => {
it('should initialize from an empty graph', () => {
const graph = Graph.initialize(0, 0);
const squares = Square.fromGraph(graph);
expect(squares).toEqual([]);
});
it('should initialize from a single vertex graph', () => {
const graph = Graph.initialize(1, 1);
const squares = Square.fromGraph(graph);
expect(squares).toEqual([]);
});
it('should initialize from a single square graph', () => {
const graph = Graph.initialize(2, 2);
const squares = Square.fromGraph(graph);
expect(squares).toEqual([
Square.create(
Vertex.create(0, 0, 0),
Vertex.create(1, 1, 0),
Vertex.create(2, 0, 1),
Vertex.create(3, 1, 1),
null,
),
]);
});
it('should initialize from a complex graph', () => {
const graph = Graph.initialize(4, 3);
const squares = Square.fromGraph(graph);
expect(squares).toEqual(jasmine.arrayContaining([
Square.create(
Vertex.create(0, 0, 0),
Vertex.create(1, 1, 0),
Vertex.create(4, 0, 1),
Vertex.create(5, 1, 1),
null,
),
Square.create(
Vertex.create(1, 1, 0),
Vertex.create(2, 2, 0),
Vertex.create(5, 1, 1),
Vertex.create(6, 2, 1),
null,
),
Square.create(
Vertex.create(2, 2, 0),
Vertex.create(3, 3, 0),
Vertex.create(6, 2, 1),
Vertex.create(7, 3, 1),
null,
),
Square.create(
Vertex.create(4, 0, 1),
Vertex.create(5, 1, 1),
Vertex.create(8, 0, 2),
Vertex.create(9, 1, 2),
null,
),
Square.create(
Vertex.create(5, 1, 1),
Vertex.create(6, 2, 1),
Vertex.create(9, 1, 2),
Vertex.create(10, 2, 2),
null,
),
Square.create(
Vertex.create(6, 2, 1),
Vertex.create(7, 3, 1),
Vertex.create(10, 2, 2),
Vertex.create(11, 3, 2),
null,
),
]));
});
});
});
<file_sep>export interface Vertex {
id: number;
x: number;
y: number;
}
export const Vertex = {
create: (id: number, x: number, y: number) => <Vertex>{
id: id,
x: x,
y: y,
},
};
<file_sep>export interface Player {
id: number;
name: string;
color: string;
score: number;
}
export const Player = {
create: (id: number, name: string, color: string, score: number) => <Player>{
id: id,
name: name,
color: color,
score: score,
},
};
<file_sep>import {Player} from '@src/app/models/player';
import {Graph} from '@src/app/models/graph';
import {Vertex} from '@src/app/models/vertex';
export interface Square {
topLeft: Vertex;
topRight: Vertex;
bottomLeft: Vertex;
bottomRight: Vertex;
owner: Player | null;
}
export const Square = {
create: (topLeft: Vertex, topRight: Vertex, bottomLeft: Vertex, bottomRight: Vertex, owner: Player | null) => <Square>{
topLeft: topLeft,
topRight: topRight,
bottomLeft: bottomLeft,
bottomRight: bottomRight,
owner: owner,
},
fromGraph: (graph: Graph) => {
if (graph.xSize <= 1 || graph.ySize <= 1) {
return [];
}
const squares: Square[] = [];
for (let y = 0; y < graph.ySize - 1; y++) {
for (let x = 0; x < graph.xSize - 1; x++) {
const i = x + y * graph.xSize;
squares.push(<Square>{
topLeft: graph.vertices[i],
topRight: graph.vertices[i + 1],
bottomLeft: graph.vertices[i + graph.xSize],
bottomRight: graph.vertices[i + graph.xSize + 1],
owner: null,
});
}
}
return squares;
},
isOwned: (square: Square) => square.owner !== null,
};
<file_sep>import {User} from '@src/app/models/user';
export interface LoggedIn {
type: UserStateType.LOGGED_IN;
user: User;
}
export interface NotLoggedIn {
type: UserStateType.NOT_LOGGED_IN;
}
export interface Loading {
type: UserStateType.LOADING;
}
export type UserState = LoggedIn | NotLoggedIn | Loading;
export enum UserStateType {
LOGGED_IN = 'LoggedIn',
NOT_LOGGED_IN = 'NotLoggedIn',
LOADING = 'Loading',
}
export const UserState = {
loggedIn: (user: User) => <LoggedIn>{
type: UserStateType.LOGGED_IN,
user: user,
},
notLoggedIn: <NotLoggedIn>{type: UserStateType.NOT_LOGGED_IN},
loading: <Loading>{type: UserStateType.LOADING},
};
export function isLoggedIn(user: UserState): user is LoggedIn {
return user.type === UserStateType.LOGGED_IN;
}
<file_sep>import {Vertex} from '@src/app/models/vertex';
export class SearchVertex {
constructor(
public self: Vertex,
public neighbors: SearchVertex[],
public seen: boolean,
) {
}
public static fromVertex(vertex: Vertex): SearchVertex {
return new SearchVertex(
vertex,
[],
false,
);
}
}
<file_sep>import {Vertex} from '@src/app/models/vertex';
import {Edge} from '@src/app/models/edge';
import {Utils} from '@src/app/utils';
import {SearchVertex} from '@src/app/models/search-vertex';
export interface Graph {
vertices: Vertex[];
edges: Edge[];
xSize: number;
ySize: number;
}
export const Graph = {
initialize: (xSize: number, ySize: number) => {
const vertices = Array.from(Array(xSize * ySize).keys())
.map(i =>
Vertex.create(
i,
i % xSize,
Math.floor(i / xSize),
),
);
const edges = Utils.flatMap(
vertices,
(vertex: Vertex, i: number) => {
const e: Edge[] = [];
if (vertex.x < xSize - 1) {
e.push(Edge.initialize(vertex, vertices[i + 1]));
}
if (vertex.y < ySize - 1) {
e.push(Edge.initialize(vertex, vertices[i + xSize]));
}
return e;
},
);
return <Graph>{
vertices: vertices,
edges: edges,
xSize: xSize,
ySize: ySize,
};
},
findPath: (graph: Graph, start: Vertex, end: Vertex) => {
let found = false;
const pathStack: Vertex[] = [];
let finalPath: Vertex[] = [];
function search(v: SearchVertex) {
pathStack.push(v.self);
if (v.self.id === end.id) {
found = true;
finalPath = [...pathStack];
return;
} else {
v.seen = true;
for (let i = 0; i < v.neighbors.length; i++) {
const neighbor = v.neighbors[i];
if (!neighbor.seen && !found) {
search(neighbor);
}
}
}
pathStack.pop();
}
const searchGraph = graph.vertices.map(SearchVertex.fromVertex);
graph.edges.filter(Edge.isOwned)
.forEach(edge => {
searchGraph[edge.source.id].neighbors.push(searchGraph[edge.target.id]);
searchGraph[edge.target.id].neighbors.push(searchGraph[edge.source.id]);
});
search(searchGraph[start.id]);
return finalPath;
},
};
<file_sep>import {Vertex} from '@src/app/models/vertex';
import {Player} from '@src/app/models/player';
export interface Edge {
source: Vertex;
target: Vertex;
owner: Player | null;
}
export const Edge = {
initialize: (source: Vertex, target: Vertex) => <Edge>{
source: source,
target: target,
owner: null,
},
isOwned: (edge: Edge) => edge.owner !== null,
hasSameCoordinates: (edgeA: Edge, edgeB: Edge) =>
edgeA.source.id === edgeB.source.id && edgeA.target.id === edgeB.target.id,
}
;
<file_sep>import {Vertex} from '@src/app/models/vertex';
import {Polygon} from '@src/app/models/polygon';
import {Edge} from '@src/app/models/edge';
import {Square} from '@src/app/models/square';
describe('Polygon', () => {
describe('fromPath', () => {
it('should create a polygon', () => {
const path: Vertex[] = [
Vertex.create(0, 0, 0),
Vertex.create(1, 1, 0),
Vertex.create(2, 0, 1),
Vertex.create(3, 1, 1),
];
expect(Polygon.fromPath(path)).toEqual(
new Polygon([
Edge.initialize(path[0], path[1]),
Edge.initialize(path[1], path[2]),
Edge.initialize(path[2], path[3]),
Edge.initialize(path[3], path[0]),
]),
);
});
it('should throw an exception if created from a path with fewer than 4 vertices', () => {
const path: Vertex[] = [
Vertex.create(0, 0, 0),
Vertex.create(1, 1, 0),
Vertex.create(2, 0, 1),
];
expect(() => Polygon.fromPath(path)).toThrowError();
});
});
describe('contains', () => {
/*
A-----B
| |
| x~~+~~
| |
C-----D
*/
it('should return true if the square lies within a simple polygon', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 0, 1);
const D = Vertex.create(3, 1, 1);
const polygon = Polygon.fromPath([A, B, D, C]);
const square = Square.create(A, B, C, D, null);
expect(polygon.contains(square)).toEqual(true);
});
/*
A-----B-----C-----D
| |
| |
| |
L I-----H E
| | | |
| x~~+~~~~~+~~~~~+~~
| | | |
K-----J G-----F
*/
it('should return true if the square within a complex polygon such that the ray intersects more than once', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 2, 0);
const D = Vertex.create(3, 3, 0);
const E = Vertex.create(4, 3, 1);
const F = Vertex.create(5, 3, 2);
const G = Vertex.create(6, 2, 2);
const H = Vertex.create(7, 2, 1);
const I = Vertex.create(8, 1, 1);
const J = Vertex.create(9, 1, 2);
const K = Vertex.create(10, 0, 2);
const L = Vertex.create(11, 0, 1);
const polygon = Polygon.fromPath([A, B, C, D, E, F, G, H, I, J, K, L]);
const square = Square.create(L, I, K, J, null);
expect(polygon.contains(square)).toEqual(true);
});
/*
A B
x~~~~~~
C-----D
| |
| |
| |
E-----F
*/
it('should return false if the square lies above the polygon', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 0, 1);
const D = Vertex.create(3, 1, 1);
const E = Vertex.create(4, 0, 2);
const F = Vertex.create(5, 1, 2);
const polygon = Polygon.fromPath([C, D, F, E]);
const square = Square.create(A, B, C, D, null);
expect(polygon.contains(square)).toEqual(false);
});
/*
A-----B
| |
| |
| |
C-----D
x~~~~~~
E F
*/
it('should return false if the square lies below the polygon', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 0, 1);
const D = Vertex.create(3, 1, 1);
const E = Vertex.create(4, 0, 2);
const F = Vertex.create(5, 1, 2);
const polygon = Polygon.fromPath([A, B, C, D]);
const square = Square.create(C, D, E, F, null);
expect(polygon.contains(square)).toEqual(false);
});
/*
A B-----C
| |
x~~+~~~~~+~~~
| |
D E-----F
*/
it('should return false if the square lies left of the polygon', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 2, 0);
const D = Vertex.create(3, 0, 1);
const E = Vertex.create(4, 1, 1);
const F = Vertex.create(5, 2, 1);
const polygon = Polygon.fromPath([B, C, F, E]);
const square = Square.create(A, B, D, E, null);
expect(polygon.contains(square)).toEqual(false);
});
/*
A-----B C
| |
| | x~~~~~~
| |
D-----E F
*/
it('should return false if the square lies right of the polygon', () => {
const A = Vertex.create(0, 0, 0);
const B = Vertex.create(1, 1, 0);
const C = Vertex.create(2, 2, 0);
const D = Vertex.create(3, 0, 1);
const E = Vertex.create(4, 1, 1);
const F = Vertex.create(5, 2, 1);
const polygon = Polygon.fromPath([A, B, E, D]);
const square = Square.create(B, C, E, F, null);
expect(polygon.contains(square)).toEqual(false);
});
});
});
<file_sep>import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {AppRoutingModule} from '@src/app/app-routing.module';
import {AppComponent} from '@src/app/app.component';
import {HomeComponent} from '@src/app/components/home/home.component';
import {GameComponent} from '@src/app/components/game/game.component';
import {AngularFireModule} from '@angular/fire';
import {AngularFireAuthModule} from '@angular/fire/auth';
import {AngularFirestoreModule} from '@angular/fire/firestore';
import {NgxFpTsModule} from 'ngx-fp-ts';
import {
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatDividerModule,
MatMenuModule,
MatProgressSpinnerModule,
MatToolbarModule
} from '@angular/material';
import {FontAwesomeModule} from '@fortawesome/angular-fontawesome';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MenuBarComponent} from '@src/app/components/menu-bar/menu-bar.component';
import {AuthService} from '@src/app/services/auth.service';
import {GameService} from '@src/app/services/game.service';
const firebaseConfig = {
apiKey: '<KEY>',
authDomain: 'stift-und-papier.firebaseapp.com',
databaseURL: 'https://stift-und-papier.firebaseio.com',
projectId: 'stift-und-papier',
storageBucket: 'stift-und-papier.appspot.com',
messagingSenderId: '436152985520',
appId: '1:436152985520:web:29245f67f32864151c1875',
};
@NgModule({
declarations: [
AppComponent,
HomeComponent,
GameComponent,
MenuBarComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule,
AngularFirestoreModule,
NgxFpTsModule,
MatProgressSpinnerModule,
MatCardModule,
MatButtonToggleModule,
MatButtonModule,
MatToolbarModule,
MatDividerModule,
MatMenuModule,
BrowserAnimationsModule,
FontAwesomeModule,
],
providers: [
AuthService,
GameService,
],
bootstrap: [AppComponent],
})
export class AppModule {
}
<file_sep>export interface EdgeStyle {
stroke: string;
opacity: number;
}
<file_sep>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {AngularFireAuth} from '@angular/fire/auth';
import {auth} from 'firebase';
import {UserState} from '@src/app/models/user-state';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private currentUser = new BehaviorSubject<UserState>(UserState.loading);
currentUser$ = this.currentUser.asObservable();
constructor(
public fireAuth: AngularFireAuth,
) {
fireAuth.authState.subscribe(user => {
if (user) {
this.currentUser.next(UserState.loggedIn(user));
} else {
this.currentUser.next(UserState.notLoggedIn);
}
});
}
async googleSignin() {
const provider = new auth.GoogleAuthProvider();
await this.fireAuth.auth.signInWithPopup(provider);
}
async signOut() {
await this.fireAuth.auth.signOut();
}
}
<file_sep>import {Injectable} from '@angular/core';
import {AngularFirestore} from '@angular/fire/firestore';
import {from, Observable} from 'rxjs';
import {Game} from '@src/app/models/game';
import {switchMap} from 'rxjs/operators';
import {Graph} from '@src/app/models/graph';
import {Square} from '@src/app/models/square';
import {Player} from '@src/app/models/player';
@Injectable({
providedIn: 'root',
})
export class GameService {
constructor(
private firestore: AngularFirestore,
) {
}
private gamesCollection = this.firestore.collection('games');
getGame(userId: string): Observable<Game> {
const gameDoc = this.gamesCollection.doc<Game>(userId);
return gameDoc.get().pipe(
switchMap(g => {
if (!g.exists) {
return from(this.resetGame(userId));
} else {
return from(Promise.resolve());
}
}),
switchMap(() => gameDoc.valueChanges()),
);
}
resetGame(userId: string): Promise<void> {
return this.gamesCollection.doc<Game>(userId).set(this.initializeGame(userId));
}
setGame(game: Game): Promise<void> {
return this.gamesCollection.doc<Game>(game.id).set(game);
}
private initializeGame(id: string): Game {
const graph = Graph.initialize(5, 5);
return <Game>{
id: id,
graph: graph,
squares: Square.fromGraph(graph),
players: [
Player.create(0, 'Alice', 'royalblue', 0),
Player.create(1, 'Bob', '#F08080', 0),
],
currentPlayerIdx: 0,
moves: [],
};
}
}
<file_sep># 📝 Pen & Paper
<a target="_blank" href="https://angular.io/"><img rel="noopener noreferrer" src="https://img.shields.io/badge/made%20with-Angular-blue.svg" alt="made with Angular"></a> <a target="_blank" href="https://www.electronjs.org/"><img rel="noopener noreferrer" src="https://img.shields.io/badge/made%20with-Electron-blue.svg" alt="made with Angular"></a> <a rel="noopener noreferrer" target="_blank" href="https://www.nativescript.org/"><img src="https://img.shields.io/badge/made%20with-NativeScript-blue.svg" alt="made with NativeScript"></a>
<img src="https://img.shields.io/badge/runs%20on-macOS-green.svg" alt="runs on macOS"> <img src="https://img.shields.io/badge/runs%20on-Linux-green.svg" alt="runs on Linux"> <img src="https://img.shields.io/badge/runs%20on-Windows-green.svg" alt="runs on Windows"> <img src="https://img.shields.io/badge/runs%20on-iOS-green.svg" alt="runs on iOS"> <img src="https://img.shields.io/badge/runs%20on-Android-green.svg" alt="runs on Android">
## Description
Want to join for a game, fam? https://stift-und-papier.web.app/
## Development
### Requirements
Go through the [NativeScript full setup](https://docs.nativescript.org/angular/start/quick-setup#full-setup).
### Commands
- `npm run start` to start the web app
- `npm run desktop` to start the desktop app
- `npm run android` to start the Android app
- `npm run ios` to start the iOS app
### Code Sharing / Separation
By adding a `.tns` before the file extension, you can indicate that this file is NativeScript-specific, while the same file without the .tns extension is marked as web-specific. If we have just one file without the .tns extension, then this makes it a shared file.
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {faBars, faHome, faSync} from '@fortawesome/free-solid-svg-icons';
import {GameService} from '@src/app/services/game.service';
import {AuthService} from '@src/app/services/auth.service';
import {filter, map} from 'rxjs/operators';
import {isLoggedIn, UserStateType} from '@src/app/models/user-state';
@Component({
selector: 'pnp-menu-bar',
templateUrl: './menu-bar.component.html',
styleUrls: ['./menu-bar.component.css'],
})
export class MenuBarComponent implements OnInit {
@Input()
title: string;
faBars = faBars;
faHome = faHome;
faSync = faSync;
userState = UserStateType;
constructor(
private gameService: GameService,
public authService: AuthService,
) {
}
async resetGame(): Promise<void> {
return await this.authService.currentUser$.pipe(
filter(isLoggedIn),
map(loggedIn => this.gameService.resetGame(loggedIn.user.uid)),
).toPromise();
}
ngOnInit() {
}
}
<file_sep># Security Policy
## Reporting a Vulnerability
If you find a vulnerability, please create a GitHub issue.
<file_sep>export class Utils {
public static flatMap<I, O>(xs: I[], f: (I, number) => O[]): O[] {
return xs.map(f).reduce((x, y) => x.concat(y), []);
}
}
<file_sep>export interface ScoreBoard {
[playerId: number]: number;
}
<file_sep>import {Graph} from '@src/app/models/graph';
import {Vertex} from '@src/app/models/vertex';
import {Edge} from '@src/app/models/edge';
import {Player} from '@src/app/models/player';
describe('Graph', () => {
describe('Initialization', () => {
it('should initialize an empty graph', () => {
const graph = Graph.initialize(0, 0);
expect(graph.vertices).toEqual([]);
expect(graph.edges).toEqual([]);
});
it('should initialize a graph with a single node', () => {
const graph = Graph.initialize(1, 1);
expect(graph.vertices).toEqual([
Vertex.create(0, 0, 0),
]);
expect(graph.edges).toEqual([]);
});
it('should initialize a non-empty graph', () => {
const graph = Graph.initialize(4, 3);
expect(graph.vertices).toEqual([
Vertex.create(0, 0, 0),
Vertex.create(1, 1, 0),
Vertex.create(2, 2, 0),
Vertex.create(3, 3, 0),
Vertex.create(4, 0, 1),
Vertex.create(5, 1, 1),
Vertex.create(6, 2, 1),
Vertex.create(7, 3, 1),
Vertex.create(8, 0, 2),
Vertex.create(9, 1, 2),
Vertex.create(10, 2, 2),
Vertex.create(11, 3, 2),
]);
expect(graph.edges).toEqual(jasmine.arrayContaining([
Edge.initialize(graph.vertices[0], graph.vertices[1]),
Edge.initialize(graph.vertices[1], graph.vertices[2]),
Edge.initialize(graph.vertices[2], graph.vertices[3]),
Edge.initialize(graph.vertices[0], graph.vertices[4]),
Edge.initialize(graph.vertices[1], graph.vertices[5]),
Edge.initialize(graph.vertices[2], graph.vertices[6]),
Edge.initialize(graph.vertices[3], graph.vertices[7]),
Edge.initialize(graph.vertices[4], graph.vertices[5]),
Edge.initialize(graph.vertices[5], graph.vertices[6]),
Edge.initialize(graph.vertices[6], graph.vertices[7]),
Edge.initialize(graph.vertices[4], graph.vertices[8]),
Edge.initialize(graph.vertices[5], graph.vertices[9]),
Edge.initialize(graph.vertices[6], graph.vertices[10]),
Edge.initialize(graph.vertices[7], graph.vertices[11]),
Edge.initialize(graph.vertices[8], graph.vertices[9]),
Edge.initialize(graph.vertices[9], graph.vertices[10]),
Edge.initialize(graph.vertices[10], graph.vertices[11]),
]));
});
});
describe('findPath', () => {
const player = Player.create(0, 'currentPlayer', 'green', 0);
it('should not detect a path if there is none due to missing ownership in a trivial graph', () => {
const graph = Graph.initialize(1, 2);
expect(Graph.findPath(graph, graph.vertices[0], graph.vertices[1])).toEqual([]);
});
it('should detect an existing path in a trivial graph', () => {
const graph = Graph.initialize(1, 2);
graph.edges[0].owner = player;
expect(Graph.findPath(graph, graph.vertices[0], graph.vertices[1])).toEqual([graph.vertices[0], graph.vertices[1]]);
});
it('should not detect a path if there is none due to missing ownership in a complex graph', () => {
const graph = Graph.initialize(100, 100);
expect(Graph.findPath(graph, graph.vertices[0], graph.vertices[99])).toEqual([]);
});
it('should detect an existing path in a complex graph', () => {
const graph = Graph.initialize(100, 100);
const expectedPath: Vertex[] = [graph.vertices[0]];
for (let x = 0; x < graph.xSize - 1; x++) {
const edge = graph.edges.find(e => e.source.x === x && e.source.y === 0);
edge.owner = player;
expectedPath.push(edge.target);
}
for (let y = 0; y < graph.xSize - 1; y++) {
const edge = graph.edges.find(e => e.source.x === graph.xSize - 1 && e.source.y === y);
edge.owner = player;
expectedPath.push(edge.target);
}
expect(Graph.findPath(graph, graph.vertices[0], graph.vertices[graph.vertices.length - 1])).toEqual(expectedPath);
});
});
});
<file_sep>import {Component, OnInit} from '@angular/core';
import {AuthService} from '@src/app/services/auth.service';
import {GameService} from '@src/app/services/game.service';
import {faGoogle} from '@fortawesome/free-brands-svg-icons';
import {faSignOutAlt} from '@fortawesome/free-solid-svg-icons';
import {UserStateType} from '@src/app/models/user-state';
@Component({
selector: 'pnp-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
title = 'Pen & Paper';
googleIcon = faGoogle;
logoutIcon = faSignOutAlt;
constructor(
public auth: AuthService,
public game: GameService,
) {
}
userState = UserStateType;
ngOnInit() {
}
}
<file_sep>import {Edge} from '@src/app/models/edge';
import {Vertex} from '@src/app/models/vertex';
import {Square} from '@src/app/models/square';
export class Polygon {
constructor(public edges: Edge[]) {
}
public static fromPath(path: Vertex[]): Polygon {
if (path.length < 4) {
throw new Error('Polygon must have at least 4 edges');
}
const edges: Edge[] = [];
for (let i = 0; i < path.length - 1; i++) {
edges.push(Edge.initialize(path[i], path[i + 1]));
}
edges.push(Edge.initialize(path[path.length - 1], path[0]));
return new Polygon(edges);
}
/*
Checks whether the square is contained within the polygon. We use
a simplified version of the ray casting algorithm. To solve our
square-in-polygon problem, we cast a ray from the center of the square
to the right and count the number of intersections with the polygon.
If the number of intersections is odd, the square lies within the polygon.
See the test cases for examples.
*/
public contains(square: Square): boolean {
const isVertical = (e: Edge) =>
e.source.x === e.target.x;
const squareIsLeftFromEdge = (s: Square, e: Edge) =>
s.topRight.x <= e.source.x;
const hasSameY = (s: Square, e: Edge) =>
Math.min(e.source.y, e.target.y) === square.topRight.y &&
Math.max(e.source.y, e.target.y) === square.bottomRight.y;
const numIntersections = this.edges
.filter(edge => isVertical(edge) && squareIsLeftFromEdge(square, edge) && hasSameY(square, edge))
.length;
return numIntersections % 2 === 1;
}
}
| 6268fd0e25aa3391239cd0423368b001b186a5da | [
"Markdown",
"TypeScript"
] | 24 | TypeScript | FRosner/stift-und-papier | 46a5bd13618c4540296fc38b7bc2ec7c7e60b5eb | 0bf6a428a09a0945b1bfbd23452aceea52bdea4c | |
refs/heads/main | <repo_name>EstebanK23/IETI-Laboratorio-10<file_sep>/FrontEnd/src/components/TodoApp.js
import React, {Component} from 'react';
import './TodoApp.css';
import {TodoList} from "./TodoList";
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';
import moment from "moment";
import TextField from '@material-ui/core/TextField';
export class TodoApp extends Component {
constructor(props) {
super(props);
this.state = {items: [], text: '', priority: 0, dueDate: moment()};
this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
this.handleNameChange = this.handleNameChange.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handleStatusChange = this.handleStatusChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<div className="TodoApp">
<TodoList todoList={this.state.items}/>
<TextField
autoFocus
margin="dense"
id="name"
label="Description"
type="text"
fullWidth
onChange = {this.handleDescriptionChange}
value = {this.state.description}
/>
<TextField
autoFocus
margin="dense"
id="name"
label="Name"
type="text"
fullWidth
onChange = {this.handleNameChange}
value = {this.state.name}
/>
<TextField
autoFocus
margin="dense"
id="name"
label="Email"
type="email"
fullWidth
onChange = {this.handleEmailChange}
value = {this.state.email}
/>
<TextField
autoFocus
margin="dense"
id="name"
label="Status"
type="text"
fullWidth
onChange = {this.handleStatusChange}
value = {this.state.status}
/>
<DatePicker
id="due-date"
selected={this.state.dueDate}
placeholderText="Due date"
onChange={this.handleDateChange}>
</DatePicker>
<input type="file" id="file" onChange={this.handleInputChange}/>
<td>{this.props.fileUrl ? <img src={this.props.fileUrl} /> : <div/>}</td>
</div>
);
}
handleDescriptionChange(e) {
this.setState({
description: e.target.value
});
}
handleNameChange(e) {
this.setState({
name: e.target.value
});
}
handleEmailChange(e) {
this.setState({
email: e.target.value
});
}
handleStatusChange(e) {
this.setState({
status: e.target.value
});
}
handleDateChange(date) {
this.setState({
dueDate: date
});
}
handleSubmit(e) {
e.preventDefault();
if (!this.state.text.length || !this.state.priority.length || !this.state.dueDate)
return;
const newItem = {
description: this.state.text,
name: this.state.priority,
email: this.state.dueDate,
status: this.state.text,
dueDate: this.state.priority,
};
this.setState(prevState => ({
items: prevState.items.concat(newItem),
description: '',
name: '',
email: '',
status: '',
dueDate: ''
}));
}
handleInputChange(e) {
this.setState({
file: e.target.files[0]
});
}
let data = new FormData();
data.append('file', this.state.file);
this.axios.post('files', data)
.then(function (response) {
console.log("file uploaded!", data);
})
.catch(function (error) {
console.log("failed file upload", error);
});
loadDataFromServer() {
let that = this;
this.axios.get("todo").then(function (response) {
console.log("This is my todolist: ", response.data);
that.setState({items: response.data})
})
.catch(function (error) {
console.log(error);
});
}
}
export default TodoApp;<file_sep>/FrontEnd/src/App.js
import React, {Component} from 'react';
import './App.css';
import {Login} from './components/Login';
import DrawerLeft from './components/DrawerLeft';
import {BrowserRouter as Router, Link, Route} from 'react-router-dom'
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLogginIn: false
}
}
componentLogin() {
this.setState({
isLogginIn: localStorage.getItem("isLogginIn")
})
}
render() {
const LoginView = () => (
<Login/>
);
const DrawerView = () => (
<DrawerLeft/>
);
return (
<Router>
<div className="App">
<ul>
{!this.state.isLogginIn && (<li><Link to="/login">Login</Link></li>)}:{!this.state.isLogginIn && (<li><Link to="/drawer">Drawer</Link></li>)}
</ul>
<div>
{!this.state.isLogginIn && (<Route exact path="/login" component={LoginView} />)}:{!this.state.isLogginIn && (<Route exact path="/drawer" component={DrawerView} />)}
</div>
</div>
</Router>
);
}
}
export default App;
| 9602d294b22016b1728ca8133062946f873cd518 | [
"JavaScript"
] | 2 | JavaScript | EstebanK23/IETI-Laboratorio-10 | 997fe3bc529e5119654baeeeb344b06c608bc764 | c66e076b83251b614778319688f22a005fdbb3e7 | |
refs/heads/master | <file_sep>class User < ApplicationRecord
after_create :create_tenant
def create_tenant
Apartment::Tenant.create(domain)
end
end
| 0bd38b28be82a20b00aa9fa1f304fadbd9e15304 | [
"Ruby"
] | 1 | Ruby | almirpask/apartament_dynamic_domain | c4ba1b129743719736c0d040fc391e78f6471738 | 09eb8e81ca5eba504df63d5dc137f45d2e2014d8 | |
refs/heads/master | <repo_name>Garat72/upgraded-raspberry<file_sep>/README.md
# upgraded-raspberry
Instalace Raspberry Pi
<file_sep>/test.sh
#!/bin/bash
set -e
source $PWD/upgraded-raspberry/include_function.sh
function pokracovat() {
display_info_n " $1 [Y/n]:"
read prompt
case $prompt in
Y|y) test=y;;
N|n) test=n;;
*) display_error " Zadejte Y nebo n" && pokracovat ;;
esac
}
logo
cd $BACK && pwd
display_info "###########################################################################################"
display_error "$HOME"
display_error "$PWD"
source "${1:h}/z.sh" | 5852a6aa42b12c73b393ba4f55921ce1f190d587 | [
"Markdown",
"Shell"
] | 2 | Markdown | Garat72/upgraded-raspberry | db29e4e4c1d74671334d2f96fd2b8f3fc5818a00 | c25a8673648ee401393b63045ccfb1e9eac6fa8c | |
refs/heads/master | <repo_name>codetechsoftware/codetechsoftware.github.io<file_sep>/docs/Gemfile
source 'https://codetechsoftware.github.io'
gemspec
gem "github-pages", group: :jekyll_plugins
<file_sep>/README.md
# 💻 CodeTech 💾 Software 📲
# 🎶 Music 🎧 Player 💗 Pro For 📲 Android Devices 📱...
| f91a46c7295cee95f017bc5ee97559ef81cddf0d | [
"Markdown",
"Ruby"
] | 2 | Ruby | codetechsoftware/codetechsoftware.github.io | 60c4e4290f5f27ce4bc68e80ec2620f2d57785b1 | 1bae1acc3ae7b228298b54f6a8ae3a75e4c76cad | |
refs/heads/master | <repo_name>davidjkim87/ExData_Plotting1<file_sep>/plot2.R
## load data
fulldata <- read.csv("./household_power_consumption.txt", header=T, sep=';', na.strings="?",
nrows=2075259, check.names=F, stringsAsFactors=F, comment.char="", quote='\"')
## create temp date to format date which then will be used to create subset of data
fulldata$Date_temp <- as.Date(fulldata$Date, format="%d/%m/%Y")
## create subset of data (limit data to 2007-02-01 and 2007-02-02)
subsetdata <- subset(fulldata, subset=(Date_temp>= "2007-02-01" & Date_temp <= "2007-02-02"))
## create date time variable that will be used to plot data
subsetdata$datetime <- as.POSIXct(paste(subsetdata$Date, subsetdata$Time), format = "%d/%m/%Y %T")
## generate graph and save in png device
png(file = "plot2.png", bg = "white")
plot(subsetdata$Global_active_power~subsetdata$datetime, type="l",
ylab="Global Active Power (kilowatts)", xlab="")
dev.off()
<file_sep>/plot4.R
## load data
fulldata <- read.csv("./household_power_consumption.txt", header=T, sep=';', na.strings="?",
nrows=2075259, check.names=F, stringsAsFactors=F, comment.char="", quote='\"')
## create temp date to format date which then will be used to create subset of data
fulldata$Date_temp <- as.Date(fulldata$Date, format="%d/%m/%Y")
## create subset of data (limit data to 2007-02-01 and 2007-02-02)
subsetdata <- subset(fulldata, subset=(Date_temp>= "2007-02-01" & Date_temp <= "2007-02-02"))
## create date time variable that will be used to plot data
subsetdata$datetime <- as.POSIXct(paste(subsetdata$Date, subsetdata$Time), format = "%d/%m/%Y %T")
## generate graph and save in png device
png(file = "plot4.png", bg = "white")
par(mfrow=c(2,2), mar=c(4,4,2,1), oma=c(0,0,2,0))
with(subsetdata, {
plot(Global_active_power~datetime, type="l",
ylab="Global Active Power", xlab="")
plot(Voltage~datetime, type="l",
ylab="Voltage", xlab="datetime")
plot(Sub_metering_1~datetime, type="l",
ylab="Energy sub metering", xlab="")
lines(Sub_metering_2~datetime,col='Red')
lines(Sub_metering_3~datetime,col='Blue')
legend("topright",inset=c(0,0), col=c("black", "red", "blue"), lty=1, lwd=2, bty="n",
legend=c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"))
plot(Global_reactive_power~datetime, type="l",
ylab="Global Reactive Power",xlab="datetime")
})
dev.off()<file_sep>/plot1.R
## load data
fulldata <- read.csv("./household_power_consumption.txt", header=T, sep=';', na.strings="?",
nrows=2075259, check.names=F, stringsAsFactors=F, comment.char="", quote='\"')
## create temp date to format date which then will be used to create subset of data
fulldata$Date_temp <- as.Date(fulldata$Date, format="%d/%m/%Y")
## create subset of data (limit data to 2007-02-01 and 2007-02-02)
subsetdata <- subset(fulldata, subset=(Date_temp>= "2007-02-01" & Date_temp <= "2007-02-02"))
## generate graph and save in png device
png(file = "plot1.png", bg = "white")
hist(subsetdata$Global_active_power, col="Red", main="Global Active Power",
xlab="Global Active Power (kilowatts)", ylab="Frequency")
dev.off()
| 068c07563ba23bba4718e0b9255ae30c041f106c | [
"R"
] | 3 | R | davidjkim87/ExData_Plotting1 | 2b08e244b9dc34ffde6cb45cc6aa959963a10d13 | c4b01210e855cf6426d2678ee7b8f5f6dd608aee | |
refs/heads/master | <repo_name>abdussametkaci/HotelReservationProgram<file_sep>/HotelReservationProgram/src/HotelReservationProgram/Yönetici.java
package HotelReservationProgram;
public class Yönetici {
String ad, soyad, kullanıcıAdı, şifre;
public Yönetici(){
}
public Yönetici(String ad, String soyad, String kullanıcıAdı, String şifre){
this.ad = ad;
this.soyad = soyad;
this.kullanıcıAdı = kullanıcıAdı;
this.şifre = şifre;
}
}
<file_sep>/README.md
# HotelReservationProgram
Java Swing arayüzü ile yapılmış otel rezervasyon alma programı
<file_sep>/HotelReservationProgram/src/HotelReservationProgram/KullanıcıHesap.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 HotelReservationProgram;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
/**
*
* @author Abdussamet
*/
public class KullanıcıHesap extends javax.swing.JFrame {
/**
* Creates new form KullanıcıGiriş
*/
public KullanıcıHesap() {
initComponents();
jRadioButtonErkek.setSelected(true);
}
boolean desenKontrol(String desenMetni, String icindeDesenArananMetin) {
Pattern desen = Pattern.compile(desenMetni);
Matcher arama = desen.matcher(icindeDesenArananMetin);
return arama.find();
}
boolean tcNumarasınınAynısındanVarMı(){
boolean aynıMı = false;
for(Kullanıcı k : AnaSayfa.müşteriler){
if(k.tc.equals(jTextFieldTC.getText())){
aynıMı = true;
}
}
return aynıMı;
}
/**
* 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabelAd = new javax.swing.JLabel();
jTextFieldAd = new javax.swing.JTextField();
jLabelSoyad = new javax.swing.JLabel();
jTextFieldSoyad = new javax.swing.JTextField();
jLabelTel = new javax.swing.JLabel();
jTextFieldTel = new javax.swing.JTextField();
jLabelEmail = new javax.swing.JLabel();
jTextFieldEmail = new javax.swing.JTextField();
jLabelYaş = new javax.swing.JLabel();
jSliderYaş = new javax.swing.JSlider();
jTextFieldYaş = new javax.swing.JTextField();
jLabelCinsiyet = new javax.swing.JLabel();
jRadioButtonErkek = new javax.swing.JRadioButton();
jRadioButtonKadın = new javax.swing.JRadioButton();
jButtonKaydol = new javax.swing.JButton();
jLabelTC = new javax.swing.JLabel();
jTextFieldTC = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabelAd.setText("Ad:");
jLabelSoyad.setText("Soyad:");
jLabelTel.setText("Tel:");
jLabelEmail.setText("Email:");
jLabelYaş.setText("Yaş:");
jSliderYaş.setMinimum(1);
jSliderYaş.setValue(1);
jSliderYaş.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSliderYaşStateChanged(evt);
}
});
jLabelCinsiyet.setText("Cinsiyet:");
buttonGroup1.add(jRadioButtonErkek);
jRadioButtonErkek.setText("Erkek");
jRadioButtonErkek.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonErkekActionPerformed(evt);
}
});
buttonGroup1.add(jRadioButtonKadın);
jRadioButtonKadın.setText("Kadın");
jButtonKaydol.setText("Kaydol");
jButtonKaydol.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonKaydolActionPerformed(evt);
}
});
jLabelTC.setText("TC:");
jLabel1.setText("+90");
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)
.addComponent(jLabelAd, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelSoyad)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelTel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1))
.addComponent(jLabelEmail))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextFieldAd, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)
.addComponent(jTextFieldSoyad)
.addComponent(jTextFieldTel)
.addComponent(jTextFieldEmail))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButtonErkek)
.addGap(24, 24, 24)
.addComponent(jRadioButtonKadın))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelTC)
.addGap(39, 39, 39)
.addComponent(jTextFieldTC, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabelCinsiyet)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelYaş)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSliderYaş, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jTextFieldYaş, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonKaydol, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(77, 77, 77))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelAd)
.addComponent(jTextFieldAd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelYaş))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabelSoyad)
.addComponent(jTextFieldSoyad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextFieldYaş, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSliderYaş, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTC)
.addComponent(jTextFieldTC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelTel)
.addComponent(jTextFieldTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelEmail)
.addComponent(jTextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabelCinsiyet)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButtonKadın)
.addComponent(jRadioButtonErkek))
.addGap(30, 30, 30)
.addComponent(jButtonKaydol, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jRadioButtonErkekActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonErkekActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jRadioButtonErkekActionPerformed
private void jSliderYaşStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSliderYaşStateChanged
jTextFieldYaş.setText("" + jSliderYaş.getValue());
}//GEN-LAST:event_jSliderYaşStateChanged
private void jButtonKaydolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonKaydolActionPerformed
if (jTextFieldAd.getText().isEmpty() || desenKontrol("[^A-z\\s]", jTextFieldAd.getText())) {
JOptionPane.showMessageDialog(this, "Lütfen adınızı düzgün giriniz!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if (jTextFieldSoyad.getText().isEmpty() || desenKontrol("[^A-z\\s]", jTextFieldSoyad.getText())) {
JOptionPane.showMessageDialog(this, "Lütfen soyadınızı düzgün giriniz!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if (jTextFieldTel.getText().isEmpty() || jTextFieldTel.getText().length() != 10 || desenKontrol("[^0-9]", jTextFieldTel.getText())) {
JOptionPane.showMessageDialog(this, "Telefon numarası 10 basamaklı ve sadece rakamdan oluşmalıdır!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if (jTextFieldEmail.getText().isEmpty() || !desenKontrol("[A-Za-z0-9]+[@][A-Za-z0-9]+(.com)", jTextFieldEmail.getText())) {
JOptionPane.showMessageDialog(this, "Lütfen emaili düzgün bir şekilde giriniz!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if (jTextFieldYaş.getText().isEmpty() || Integer.parseInt(jTextFieldYaş.getText()) < 18) {
JOptionPane.showMessageDialog(this, "18 yaşından küçükler hesap oluşturamazlar!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if (jTextFieldTC.getText().isEmpty() || desenKontrol("[^0-9]", jTextFieldTC.getText()) || jTextFieldTC.getText().length() != 11) {
JOptionPane.showMessageDialog(this, "Lütfen tc no'da sadece rakam kullanınız!\nAyrıca 11 basamaklı olmalı!", "Uyarı!", JOptionPane.WARNING_MESSAGE);
return;
} else if(tcNumarasınınAynısındanVarMı()){
JOptionPane.showMessageDialog(this, "TC numaranız veri tabanındaki birisi ile uyuşuyor.\nLütfen doğru girdiğinizden emin olunuz!", "Hata!", JOptionPane.WARNING_MESSAGE);
return;
}
String cinsiyet = "";
if (jRadioButtonErkek.isSelected()) {
cinsiyet = "erkek";
} else if (jRadioButtonKadın.isSelected()) {
cinsiyet = "kadın";
}
String kullanıcıAdı = "" + jTextFieldAd.getText().charAt(0) + "" + jTextFieldSoyad.getText().charAt(0) + "123";
String şifre = "" + jTextFieldTC.getText().substring(0, 5);
String[] seçimler = {"Evet", "Hayır"};
int seçim = JOptionPane.showOptionDialog(rootPane, "Bu bilgilerinizle kaydolmak istediğinize emin misiniz?", "Uyarı!", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, seçimler, seçimler[0]);
if (seçim == 0) {
Kullanıcı k = new Kullanıcı(jTextFieldAd.getText(), jTextFieldSoyad.getText(), jTextFieldEmail.getText(), cinsiyet,
jTextFieldTel.getText(), jTextFieldTC.getText(), Integer.parseInt(jTextFieldYaş.getText()));
k.kullanıcıAdı = kullanıcıAdı;
k.şifre = şifre;
AnaSayfa.müşteriler.add(k);
String mesaj = "Kullanıcı adınız: " + kullanıcıAdı + "\n"
+ "Şifreniz: " + şifre;
JOptionPane.showMessageDialog(this, "İşlminiz başarıyla tanımlanmıştır!", "Tebrikler!", JOptionPane.INFORMATION_MESSAGE);
System.out.println("kullanıcılar: " + AnaSayfa.müşteriler);
System.out.println(k.ad + " " + k.soyad + " " + k.kullanıcıAdı + " " + k.şifre);
JOptionPane.showMessageDialog(rootPane, mesaj, "Bilgilendirme!", JOptionPane.INFORMATION_MESSAGE);
return;
} else if (seçim == 1) {
JOptionPane.showMessageDialog(this, "İşleiniz iptal edilmiştir!", "Uyarı", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_jButtonKaydolActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
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(KullanıcıHesap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(KullanıcıHesap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(KullanıcıHesap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(KullanıcıHesap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new KullanıcıHesap().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonKaydol;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabelAd;
private javax.swing.JLabel jLabelCinsiyet;
private javax.swing.JLabel jLabelEmail;
private javax.swing.JLabel jLabelSoyad;
private javax.swing.JLabel jLabelTC;
private javax.swing.JLabel jLabelTel;
private javax.swing.JLabel jLabelYaş;
private javax.swing.JRadioButton jRadioButtonErkek;
private javax.swing.JRadioButton jRadioButtonKadın;
private javax.swing.JSlider jSliderYaş;
private javax.swing.JTextField jTextFieldAd;
private javax.swing.JTextField jTextFieldEmail;
private javax.swing.JTextField jTextFieldSoyad;
private javax.swing.JTextField jTextFieldTC;
private javax.swing.JTextField jTextFieldTel;
private javax.swing.JTextField jTextFieldYaş;
// End of variables declaration//GEN-END:variables
}
| 6d4fbb0e3fbd237416a5048b858275cdf2f1ec80 | [
"Markdown",
"Java"
] | 3 | Java | abdussametkaci/HotelReservationProgram | 72847be7ba09c26e01fa94978d48adee1bf0d998 | a01d46b31b6cd04167a24e6ac2ca151e8b9249e4 | |
refs/heads/master | <repo_name>adham95/Classification_Assignment<file_sep>/test.py
# Support Vector Machine (SVM)
# Importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report,accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier,BaggingClassifier,GradientBoostingClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.neural_network import MLPClassifier
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.preprocessing import LabelEncoder,StandardScaler
from xgboost import XGBClassifier
from pandas.plotting import scatter_matrix
import seaborn as sns
from scipy.stats import mode
from matplotlib.colors import ListedColormap
# Importing the dataset
missing_values=['?']
potential = pd.read_csv("potential-clients.csv", index_col="ID",na_values = missing_values)
current = pd.read_csv("current-clients.csv", index_col="ID",na_values = missing_values)
# fill the missing values with the mod
potential['workclass'].fillna(mode(potential['workclass']).mode[0],inplace=True)
potential['native-country'].fillna(mode(potential['native-country']).mode[0],inplace=True)
potential['occupation'].fillna(mode(potential['occupation']).mode[0],inplace=True)
current['occupation'].fillna(mode(current['occupation']).mode[0],inplace=True)
current['workclass'].fillna(mode(current['workclass']).mode[0],inplace=True)
current['native-country'].fillna(mode(current['native-country']).mode[0],inplace=True)
print (current.isnull().sum())
# drop missing values
current.dropna(inplace=True)
potential.dropna(inplace=True)
labelencoder = LabelEncoder()
cols = ['workclass' , 'education' , 'marital-status' , 'occupation' , 'sex' , 'native-country' , 'race' , 'relationship','class']
for col_name in cols:
current[col_name] = labelencoder.fit_transform(current[col_name])
# potential[col_name] = labelencoder.fit_transform(potential[col_name])
print(current.head())
y = current.pop('class').values
X = current.values
# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.20, random_state = 50,shuffle=True)
# Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Fitting XGBClassifier to the Training set
classifier = XGBClassifier(n_estimators=60, n_jobs=-1, random_state=50)
classifier.fit(X_train, y_train)
accuracy=classifier.score(X_test,y_test)
print('accuracy: ',accuracy)
# Predicting the Test set results
y_pred = classifier.predict(X_test)
# Making the Confusion Matrix
cm = confusion_matrix(y_test, y_pred)
cr=classification_report(y_test, y_pred)
print(cm)
print(cr)
# Visualising the Training set results
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
Xpred = np.array([X1.ravel(), X2.ravel()] + [np.repeat(0, X1.ravel().size) for _ in range(11)]).T
pred = classifier.predict(Xpred).reshape(X1.shape) # is a matrix of 0's and 1's !
# plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
# alpha = 0.75, cmap = ListedColormap(('red', 'green')))
# plt.contourf(X1, X2, pred,
# alpha=0.75, cmap=ListedColormap(('red', 'green')), )
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('XGBClassifier (Training set)')
plt.xlabel('Features')
plt.ylabel('Estimated Salary')
plt.legend()
plt.savefig('Training set')
plt.show()
# Visualising the Test set results
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
# plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
# alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.contourf(X1, X2, pred, alpha=0.75, cmap=ListedColormap(('red', 'green')), )
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('yellow', 'black'))(i), label = j)
plt.title('XGBClassifier (Test set)')
plt.xlabel('Features')
plt.ylabel('Estimated Salary')
plt.legend()
plt.savefig('Test set')
plt.show()
<file_sep>/profit.py
import pandas as pd
import classifier
new_potential = pd.read_csv("newPotential.csv", index_col="ID")
high_income_count=0
accuracy=classifier.results.mean()
low_income_count=0
file = open("ids.txt","w")
# file.write('ID'+' '+'\n')
for i,c in new_potential.iterrows():
if c['class']=='>50K':
high_income=c['class']
file.write(str(i)+'\n')
high_income_count+=1
file.close()
print('high income',high_income_count)
package_sent=high_income_count*10
profit=(high_income_count*accuracy*0.1*980)
cost=(high_income_count*(1-accuracy)*0.05*310)
total_profit=(profit-cost-package_sent)
print('Q1:',profit-package_sent)
print(' profit :',profit)
print(' cost :',cost)
print('total profit :',total_profit)
<file_sep>/classifier.py
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import model_selection
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, classification_report,accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier,BaggingClassifier,GradientBoostingClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.neural_network import MLPClassifier
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.preprocessing import LabelEncoder,StandardScaler
from xgboost import XGBClassifier
from pandas.plotting import scatter_matrix
import seaborn as sns
from scipy.stats import mode
from matplotlib.colors import ListedColormap
from datetime import datetime
# Reading data
missing_values=['?']
potential = pd.read_csv("potential-clients.csv", index_col="ID",na_values = missing_values)
current = pd.read_csv("current-clients.csv", index_col="ID",na_values = missing_values)
# print(current.head(20))
# print(potential.groupby('occupation').size())
# fill the missing values with the mod
potential['workclass'].fillna(mode(potential['workclass']).mode[0],inplace=True)
potential['native-country'].fillna(mode(potential['native-country']).mode[0],inplace=True)
potential['occupation'].fillna(mode(potential['occupation']).mode[0],inplace=True)
current['occupation'].fillna(mode(current['occupation']).mode[0],inplace=True)
current['workclass'].fillna(mode(current['workclass']).mode[0],inplace=True)
current['native-country'].fillna(mode(current['native-country']).mode[0],inplace=True)
print (current.isnull().sum())
# drop missing values
# current.dropna(inplace=True)
# potential.dropna(inplace=True)
# Feature Engineering
labelencoder = LabelEncoder()
cols = ['workclass' , 'education' , 'marital-status' , 'occupation' , 'sex' , 'native-country','race' , 'relationship']
for col_name in cols:
current[col_name] = labelencoder.fit_transform(current[col_name])
potential[col_name] = labelencoder.fit_transform(potential[col_name])
print(current.describe())
print(potential.describe())
# prepare configuration for cross validation test harness
# prepare models
y = current.pop('class')
x = current
seed=50
scoring = 'accuracy'
# models = []
# models.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))
# models.append(('LDA', LinearDiscriminantAnalysis()))
# models.append(('KNN', KNeighborsClassifier(n_neighbors=8)))
# models.append(('CART', DecisionTreeClassifier(max_depth=5)))
# models.append(('NB', GaussianNB()))
# models.append(('XGB', XGBClassifier(n_estimators=100, random_state=seed)))
# models.append(('SVM', SVC()))
# models.append(('CNN', MLPClassifier(alpha=1, max_iter=1000)))
# models.append(('AdaBoost', AdaBoostClassifier(n_estimators=100)))
# models.append(('Bagging', BaggingClassifier(base_estimator=SVC(),n_estimators=10, random_state=0)))
# models.append(('RF', RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1)))
# # evaluate each model in turn
# results = []
# names = []
# for name, model in models:
# kfold = model_selection.KFold(n_splits=20,random_state=seed,shuffle=True)
# cv_results = model_selection.cross_val_score(model, x, y, cv=kfold, scoring=scoring)
# results.append(cv_results)
# names.append(name)
# msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
# print(msg)
# #
# # # boxplot algorithm comparison
# fig = plt.figure()
# fig.suptitle('Algorithm Comparison')
# ax = fig.add_subplot(111)
# plt.boxplot(results)
# ax.set_xticklabels(names)
# plt.savefig('Algorithm Comparison')
# plt.show()
def timer(start_time=None):
if not start_time:
start_time = datetime.now()
return start_time
elif start_time:
thour, temp_sec = divmod((datetime.now() - start_time).total_seconds(), 3600)
tmin, tsec = divmod(temp_sec, 60)
print('\n Time taken: %i hours %i minutes and %s seconds.' % (thour, tmin, round(tsec, 2)))
X_train, X_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.20,random_state=seed,shuffle=True)
#finding Best K
# k_range = range(1, 10)
# k_scores = []
# for k in k_range:
# knn = KNeighborsClassifier(n_neighbors=k)
# scores = model_selection.cross_val# fig = plt.figure()
# fig.suptitle('Algorithm Comparison')
# ax = fig.add_subplot(111)
# plt.boxplot(results)
# ax.set_xticklabels(names)
# plt.savefig('Algorithm Comparison')
# plt.show()_score(knn, x, y, cv=5, scoring='accuracy')
# k_scores.append(scores.mean())
# print(k_scores)
# max_k=max(k_range)
# print(max_k)
# plt.plot( k_range ,k_scores)
# plt.savefig('best K ')
# plt.show()
# params = {
# 'min_child_weight': [1, 5, 10],
# 'gamma': [0.5, 1, 1.5, 2, 5,8,10],
# 'subsample': [0.6, 0.8, 1.0],
# 'colsample_bytree': [0.6, 0.8, 1.0],
# 'max_depth': [3, 4, 5,7,10],
# "learning_rate": [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] ,
# }
# xgb = XGBClassifier( n_estimators=60, objective='binary:logistic',
# silent=True, nthread=1)
# folds = 20
# param_comb = 5
# kfold = model_selection.KFold(n_splits=20, random_state=seed,shuffle=True)
# results = model_selection.cross_val_score(xgb, x, y, cv=kfold,scoring=scoring,error_score='raise')
# # skf = model_selection.StratifiedKFold(n_splits=folds, shuffle = True, random_state = seed)
#
# random_search = model_selection.RandomizedSearchCV(xgb, param_distributions=params, n_iter=param_comb, scoring='roc_auc', n_jobs=4, cv=kfold, verbose=3, random_state=1001 )
#
#
# # Here we go
# start_time = timer(None) # timing starts from this point for "start_time" variable
# random_search.fit(x,y)
# timer(start_time) # timing ends here for "start_time" variable
#
# print('\n All results:')
# print(random_search.cv_results_)
# print('\n Best estimator:')
# print(random_search.best_estimator_)
# print('\n Best normalized gini score for %d-fold search with %d parameter combinations:' % (folds, param_comb))
# print(random_search.best_score_ * 2 - 1)
# print('\n Best hyperparameters:')
# print(random_search.best_params_)
# result = pd.DataFrame(random_search.cv_results_)
# result.to_csv('xgb-random-grid-search-results-01.csv', index=False)
clf = XGBClassifier(n_estimators=60, n_jobs=-1, random_state=seed)
kfold = model_selection.KFold(n_splits=20, random_state=seed,shuffle=True)
results = model_selection.cross_val_score(clf, x, y, cv=kfold,scoring=scoring,error_score='raise')
print('Accuracy Score:',results.mean())
clf.fit(X_train,y_train)
pred = clf.predict(potential)
potential['class']=list(pred)
print(pred)
# potential.to_csv('newPotential.csv')
| 36b898486b011ba768777cb007a4eaafa0020ec3 | [
"Python"
] | 3 | Python | adham95/Classification_Assignment | 98c8552e6c722456471cad97adf857466d60d471 | 50167791bbcd1ccce11140b3107249a0570f119b | |
refs/heads/master | <file_sep>package com.orderbook.core;
import java.util.Map;
public interface OrderBook {
void getOrderBook();
void getAllAsk();
void getAllBid();
Map.Entry<Double, Integer> getSellAtLevel(int level);
Map.Entry<Double, Integer> getBuyAtLevel(int level);
void addNewOrder(double price, int qty, boolean isBuy);
void getMatchedOrders();
void clearOrderBook();
}
| f3b1836cedf903e6e3917bab0dc34fbbc55b2ec8 | [
"Java"
] | 1 | Java | msasia17/simple-order-book | e4229f399d8b7cf2c792f57394fcc3bc5f6682f0 | 3918f5caa19103c5668ca15a757e7327f38e8951 | |
refs/heads/master | <file_sep>var usingexternal;(function(){var n=ko.observable("Sean")})(usingexternal||(usingexternal={}))<file_sep>module using_interface {
//var registerEmployee = function (employee: { name: string; age?: number }) {
// if (employee.age === undefined) {
// employee.age = 20;
// }
// console.log(employee);
//}
// be careful, using ; instead of ,
interface RegisterOptions {
employee: Employee;
registerDate: Date;
department: string;
}
interface Employee {
name: string;
age?: number;
}
interface RegisterFunction {
(employee: Employee): void;
}
var registerEmployee: RegisterFunction = (employee) => {
if (employee.age === undefined) {
employee.age = 20;
}
console.log(employee);
}
var initRegister = (options: RegisterOptions) => {
var message = 'hi ' + options.employee.name + ' welcome';
console.log(message);
}
var options: RegisterOptions = {
employee: {
name: 'sean',
age: 28
},
registerDate: new Date(2012, 03, 01),
department: 'CL'
};
initRegister(options);
}<file_sep>var app;
(function (app) {
(function (tools) {
(function (utils) {
var Logger = (function () {
function Logger() {
}
Logger.prototype.log = function (message) {
console.log(message);
};
return Logger;
})();
utils.Logger = Logger;
})(tools.utils || (tools.utils = {}));
var utils = tools.utils;
})(app.tools || (app.tools = {}));
var tools = app.tools;
})(app || (app = {}));
<file_sep>var using_objects;
(function (using_objects) {
var obj = { x: 10, y: 20 };
obj.x;
var person = {
name: 'sean',
lastName: 'xu',
getFullName: function () {
return this.name + this.lastName;
}
};
console.log(person.getFullName());
//notice { name: string; age?: number }, it's semi-colon instead of comma, this confused me a lot of time;
// infact { name: string; age?: number }, is the interface of employee, it's not object literal
var registerEmployee = function (employee) {
if (employee.age === undefined) {
employee.age = 20;
}
console.log(employee);
};
registerEmployee({ name: 'sean' });
})(using_objects || (using_objects = {}));
<file_sep>/// <reference path="typings/knockout.d.ts" />
var viewModal = ((function () {
var _name = ko.observable('sean');
_name.subscribe(function (newValue) {
alert(newValue);
});
return {
name: _name
};
})());
<file_sep>/// <reference path="separatingmodule.ts" />
module app {
import Log = app.tools.utils.Logger;
export class AppViewModal implements IAppViewModal {
_logger: Log;
constructor() {
this._logger = new Log();
}
save() {
this._logger.log('saved');
}
}
}
module common {
export interface IConfig {
siteUrl: string;
timeout: number;
logger: app.tools.utils.Logger;
};
export function config ():IConfig {
return {
siteUrl: 'App',
timeout: 10,
logger: new app.tools.utils.Logger()
}
};
}
module app {
export interface IAppViewModal { }
}
var config = common.config();
var modal = new app.AppViewModal();
var logger = new app.tools.utils.Logger(); // this way, the namespace is too long, we can shorten the namespace by import
<file_sep>module using_objects {
var obj = { x: 10, y: 20 };
obj.x;
var person = {
name: 'sean',
lastName: 'xu',
getFullName: function () {
return this.name + this.lastName;
}
};
console.log(person.getFullName());
//notice { name: string; age?: number }, it's semi-colon instead of comma, this confused me a lot of time;
// infact { name: string; age?: number }, is the interface of employee, it's not object literal
var registerEmployee = function (employee: { name: string; age?: number }) {
if (employee.age === undefined) {
employee.age = 20;
}
console.log(employee);
}
registerEmployee({ name: 'sean' });
}<file_sep>var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var class_extend_demo;
(function (class_extend_demo) {
;
var BaseViewModal = (function () {
function BaseViewModal(deal) {
this._deal = deal;
}
BaseViewModal.prototype.methodCanbeOverride = function () {
console.log(this._deal);
console.log('call methodCanbeOverride2 from base class');
};
BaseViewModal.prototype.save = function () {
if (this.onbeforeSave) {
this.onbeforeSave();
}
console.log(this._deal);
console.log('saved');
if (this.onafterSave) {
this.onafterSave();
}
};
BaseViewModal.prototype.propertyAccessor = function (propertyName) {
return this._deal[propertyName];
};
return BaseViewModal;
})();
class_extend_demo.BaseViewModal = BaseViewModal;
var DealingViewModal = (function (_super) {
__extends(DealingViewModal, _super);
function DealingViewModal(deal) {
_super.call(this, deal);
this.onbeforeSave = function () {
console.log('on before save');
};
this.onafterSave = function () {
console.log('on after save');
};
}
DealingViewModal.prototype.calculateContractMonth = function (month) {
(this._deal).contractMonth = month;
};
DealingViewModal.prototype.methodCanbeOverride = function () {
_super.prototype.methodCanbeOverride.call(this);
console.log('call from sub');
};
return DealingViewModal;
})(BaseViewModal);
class_extend_demo.DealingViewModal = DealingViewModal;
var futureDeal = {
dealNumber: 1,
instrument: 'future and eto',
exchange: 'chargo exchange',
matureDate: new Date(),
contractMonth: 12
};
var future = new DealingViewModal(futureDeal);
future.calculateContractMonth(5);
future.methodCanbeOverride();
var contracMonth = future.propertyAccessor('contractMonth');
console.log(contracMonth);
future.save();
})(class_extend_demo || (class_extend_demo = {}));
<file_sep>document.addEventListener('DOMContentLoaded', function (event) {
}, false);
var ViewModel = (function () {
function ViewModel(id, txtId) {
this.btnClick = document.getElementById(id);
this.txtInput = document.getElementById(txtId);
this.init();
}
ViewModel.prototype.init = function () {
this.btnClick.addEventListener('click', this.onbtnClicked, false);
};
//init() {
// this.btnClick.addEventListener('click', this.onbtnClicked.bind(this), false);
//}
//init() {
// this.btnClick.addEventListener('click', (event) => {
// this.txtInput.value = 'button clicked';
// }, false);
// this.btnClick.addEventListener('click', this.onbtnClicked, false);
//}
ViewModel.prototype.onbtnClicked = function (event) {
console.log(this);
this.txtInput.value = 'button clicked';
};
return ViewModel;
})();
<file_sep>module app.tools.utils {
export class Logger {
log(message: string): void {
console.log(message);
}
}
}<file_sep>module usingexternal {
declare var ko;
declare var $;
var name = ko.observable('Sean');
var $obj = $('hello');
}
<file_sep>/// <reference path="typings/knockout.d.ts" />
var viewModal = (function () {
var _name = ko.observable('sean');
_name.subscribe((newValue) => {
alert(newValue);
});
return {
name: _name
};
} ());<file_sep>
// we can also use complex type
class Exchange {
constructor(public exchangeName: string) {
}
}
class Deal {
private _instrument: string;
private _exchange: Exchange;
constructor(instrument: string, exchange: Exchange) {
this._exchange = exchange;
this._instrument = instrument;
}
getExchange(): Exchange {
return this._exchange;
}
get instrument(): string {
return this._instrument;
}
set instrument(value: string) {
this._instrument = value;
}
static newDeal(): Deal {
return new Deal('', new Exchange(''));
}
}
//type convert
var table: HTMLTableElement = document.createElement('table');
//or
var table = <HTMLTableElement> document.createElement('table');
table.createTBody();
<file_sep>var using_interface;
(function (using_interface) {
var registerEmployee = function (employee) {
if (employee.age === undefined) {
employee.age = 20;
}
console.log(employee);
};
var initRegister = function (options) {
var message = 'hi ' + options.employee.name + ' welcome';
console.log(message);
};
var options = {
employee: {
name: 'sean',
age: 28
},
registerDate: new Date(2012, 03, 01),
department: 'CL'
};
initRegister(options);
})(using_interface || (using_interface = {}));
<file_sep>class Car {
private _enginType: string;
constructor(enginType: string) {
this._enginType = enginType;
}
Start(): void {
alert(this._enginType + 'Start');
}
Stop(): void {
alert(this._enginType + 'Stop');
}
}<file_sep>TypeScriptFundamental
=====================
Demo Code for TypeScriptFundamental
<file_sep>document.addEventListener('DOMContentLoaded', (event) => {
}, false);
class ViewModel {
private btnClick: HTMLInputElement;
private txtInput: HTMLInputElement;
constructor(id: string, txtId:string) {
this.btnClick = <HTMLInputElement>document.getElementById(id);
this.txtInput = <HTMLInputElement>document.getElementById(txtId);
this.init();
}
init() {
this.btnClick.addEventListener('click', this.onbtnClicked, false);
}
//init() {
// this.btnClick.addEventListener('click', this.onbtnClicked.bind(this), false);
//}
//init() {
// this.btnClick.addEventListener('click', (event) => {
// this.txtInput.value = 'button clicked';
// }, false);
// this.btnClick.addEventListener('click', this.onbtnClicked, false);
//}
onbtnClicked(event: Event) {
console.log(this);
this.txtInput.value = 'button clicked';
}
}
<file_sep>var Exchange = (function () {
function Exchange(exchangeName) {
this.exchangeName = exchangeName;
}
return Exchange;
})();
var Deal = (function () {
function Deal(instrument, exchange) {
this._exchange = exchange;
this._instrument = instrument;
}
Deal.prototype.getExchange = function () {
return this._exchange;
};
Object.defineProperty(Deal.prototype, "instrument", {
get: function () {
return this._instrument;
},
set: function (value) {
this._instrument = value;
},
enumerable: true,
configurable: true
});
Deal.newDeal = function () {
return new Deal('', new Exchange(''));
};
return Deal;
})();
var table = document.createElement('table');
var table = document.createElement('table');
table.createTBody();
<file_sep>var num:number = 2;
//you can also,
var str = 'two'; //same as var str:string = 'two';
//if you want dynamic, which is not recommanded, you can use any type
var any1: any = 2;
any1 = 'two';
//function type
var func: (firstPara: string, secondPara: number) => string = (firstPara, secondPara) => {
return firstPara + secondPara;
};
var result = func('hello', 2);
var thefunction_that_take_func_as_paramater: (func: (firstPara: string, secondPara: number) => string) => void
= (func) => {
var
hello = 'hello',
world = 2;
console.log(func(hello,world));
}
thefunction_that_take_func_as_paramater((a, b) => {
return '';
});
var obj = undefined;
<file_sep>module class_extend_demo {
export interface Deal {
dealNumber: number
};
export interface FutureDeal extends Deal {
instrument: string;
exchange: string;
matureDate: Date;
contractMonth: number;
}
export class BaseViewModal {
_deal: Deal;
onbeforeSave: () => void;
onafterSave: () => void;
constructor(deal: Deal) {
this._deal = deal;
}
public methodCanbeOverride(): void {
console.log(this._deal);
console.log('call methodCanbeOverride2 from base class');
}
public
save(): void {
if (this.onbeforeSave) {
this.onbeforeSave();
}
console.log(this._deal);
console.log('saved');
if (this.onafterSave) {
this.onafterSave();
}
}
propertyAccessor(propertyName: string): any {
return this._deal[propertyName];
}
}
export class DealingViewModal extends BaseViewModal {
constructor(deal: Deal) {
super(deal);
}
public calculateContractMonth(month: number): void {
(<FutureDeal>this._deal).contractMonth = month;
}
onbeforeSave = () => {
console.log('on before save');
}
onafterSave = () => {
console.log('on after save');
}
public methodCanbeOverride(): void {
super.methodCanbeOverride();
console.log('call from sub');
}
}
var futureDeal: FutureDeal = {
dealNumber: 1,
instrument: 'future and eto',
exchange: 'chargo exchange',
matureDate: new Date(),
contractMonth: 12
};
var future = new DealingViewModal(futureDeal);
future.calculateContractMonth(5);
future.methodCanbeOverride();
var contracMonth = future.propertyAccessor('contractMonth');
console.log(contracMonth);
future.save();
}
<file_sep>var num = 2;
var str = 'two';
var any1 = 2;
any1 = 'two';
var func = function (firstPara, secondPara) {
return firstPara + secondPara;
};
var result = func('hello', 2);
var thefunction_that_take_func_as_paramater = function (func) {
var hello = 'hello', world = 2;
console.log(func(hello, world));
};
thefunction_that_take_func_as_paramater(function (a, b) {
return '';
});
var obj = undefined;
| e15a04b1f1112f9cd12f8c584f44f42596267780 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 21 | JavaScript | xujihui1985/TypeScriptFundamental | 7c9f70305dc0677a392768adb8179e0b90e06fb1 | f304d38e11a3bd85892866e1be568a1d18a04339 | |
refs/heads/master | <repo_name>jbavitan/ShareAThon<file_sep>/public/javascripts/Giving.js
var app = angular.module('myApp', []);
app.controller('givingController',function($scope, $http){
$scope.experties = ['law', 'sport', 'music' ,'programmer'];
$scope.infoToSend;
$scope.showMatch;
$scope.showNotMatch;
$scope.chooseExp = function(experty){
$http.get("/getSubCatagories/" + experty).success(function(catagoryList){
$scope.catagoryList = catagoryList;
});
}
$scope.chooseSub = function(subCatagory){
$scope.chosenSub = subCatagory;
}
$scope.confirm = function(){
$http.post("/sendInfo", $scope.infoToSend).success(function(confirmation){
$scope.showMatch = confirmation;
$scope.showNotMatch = !confirmation;
}).error(function(){
alert("Error with the server");
})
}
$scope.DisConfirm = function(){
alert("You have declined the confirmation... To confirm press yes");
}
})<file_sep>/app/controllers/CityController.java
package controllers;
import io.ebean.Ebean;
import models.City;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class CityController extends Controller {
public Result getCities() {
return ok(Json.toJson(Ebean.find(City.class).findList()));
}
}
<file_sep>/app/controllers/SubCategoryController.java
package controllers;
import io.ebean.Ebean;
import models.SubCategory;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class SubCategoryController extends Controller {
public Result getSubCategory() {
return ok(Json.toJson(Ebean.find(SubCategory.class).findList()));
}
}
<file_sep>/app/controllers/CategoryController.java
package controllers;
import io.ebean.Ebean;
import models.Category;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class CategoryController extends Controller {
public Result getCategories() {
return ok(Json.toJson(Ebean.find(Category.class).findList()));
}
}
<file_sep>/app/controllers/MeetingController.java
package controllers;
import java.util.Date;
import com.fasterxml.jackson.databind.JsonNode;
import io.ebean.Ebean;
import models.Meeting;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
public class MeetingController extends Controller {
public Result getMeetings() {
return ok(Json.toJson(Ebean.find(Meeting.class).findList()));
}
public Result UpdateMeeting() {
Ebean.update(createMeeting());
return ok();
}
public Result DeleteMeeting() {
Ebean.delete(createMeeting());
return ok();
}
private static Meeting createMeeting() {
JsonNode request = request().body().asJson();
return (new Meeting(request.findValue("id").asInt(),
request.findValue("requestUser").asInt(),
request.findValue("offerUser").asInt(),
new Date(request.findValue("Date").asLong()),
request.findValue("location").asInt()));
}
}
| f7674406f5c24cbd229b525b567cd5dd3c919031 | [
"JavaScript",
"Java"
] | 5 | JavaScript | jbavitan/ShareAThon | ec17d435eb2bb1a8cf4e6e1bf1aa4fe56f49f16c | c5238da0eb29c3fee44351c14e47584dbebec11e | |
refs/heads/master | <repo_name>talapaillp/dpd.sdk<file_sep>/src/lib/Agents.php
<?php
namespace Ipol\DPD;
use \Ipol\DPD\API\User as API;
use \Ipol\DPD\Config\ConfigInterface;
/**
* Класс содержит набор готовых методов реализующих выполнение периодических
* заданий
*/
class Agents
{
/**
* Обновляет статусы заказов
*
* Обновление статусов происходит в 2 этапа.
* На первом этапе обрабатываются заказы, которые создались в статусе "Ожидают проверки менеджером DPD"
* На втором этапе обрабатываются остальные заказы. Для получения изменений по статусам используется
* метод getStatesByClient
*
* @param \Ipol\DPD\Config\ConfigInterface $config
*
* @return void
*/
public static function checkOrderStatus(ConfigInterface $config)
{
self::checkPindingOrderStatus($config);
self::checkTrakingOrderStatus($config);
}
/**
* Проверяет статусы заказов ожидающих проверки
*
* @return void
*/
protected static function checkPindingOrderStatus(ConfigInterface $config)
{
$table = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('order');
$orders = $table->find([
'where' => 'ORDER_STATUS = :order_status',
'order' => 'ORDER_DATE_STATUS ASC, ORDER_DATE_CREATE ASC',
'limit' => '0,2',
'bind' => [
':order_status' => \Ipol\DPD\Order::STATUS_PENDING
]
])->fetchAll(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, $table->getModelClass(), $table);
foreach ($orders as $order) {
$order->dpd()->checkStatus();
}
}
/**
* Проверяет статусы заказов прошедшие проверку
*
* @return void
*/
protected static function checkTrakingOrderStatus(ConfigInterface $config)
{
if (!$config->get('STATUS_ORDER_CHECK')) {
return;
}
do {
$ret = API::getInstanceByConfig($config)->getService('tracking')->getStatesByClient();
if (!$ret) {
return;
}
$states = (array) $ret['STATES'];
$states = array_key_exists('DPD_ORDER_NR', $states) ? array($states) : $states;
// сортируем статусы по их времени наступления
uasort($states, function($a, $b) {
if ($a['CLIENT_ORDER_NR'] == $b['CLIENT_ORDER_NR']) {
$time1 = strtotime($a['TRANSITION_TIME']);
$time2 = strtotime($b['TRANSITION_TIME']);
return $time1 - $time2;
}
return $a['CLIENT_ORDER_NR'] - $b['CLIENT_ORDER_NR'];
});
foreach ($states as $state) {
$order = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('order')->getByOrderId($state['CLIENT_ORDER_NR']);
if (!$order) {
continue;
}
$status = $state['NEW_STATE'];
if ($order->isSelfDelivery()
&& $status == \Ipol\DPD\Order::STATUS_TRANSIT_TERMINAL
&& $order->receiverTerminalCode == $state['TERMINAL_CODE']
) {
$status = \Ipol\DPD\Order::STATUS_ARRIVE;
}
$order->setOrderStatus($status, $statusTime);
$order->orderNum = $state['DPD_ORDER_NR'] ?: $order->orderNum;
$order->save();
}
if ($ret['DOC_ID'] > 0) {
API::getInstanceByConfig($config)->getService('tracking')->confirm($ret['DOC_ID']);
}
} while($ret['RESULT_COMPLETE'] != 1);
}
/**
* Загружает в локальную БД данные о местоположениях и терминалах
*
* @param \Ipol\DPD\Config\ConfigInterface $config
*
* @return string
*/
public static function loadExternalData(ConfigInterface $config)
{
$api = API::getInstanceByConfig($config);
$locationTable = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('location');
$terminalTable = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('terminal');
$locationLoader = new \Ipol\DPD\DB\Location\Agent($api, $locationTable);
$terminalLoader = new \Ipol\DPD\DB\Terminal\Agent($api, $terminalTable);
$currStep = $config->get('LOAD_EXTERNAL_DATA_STEP');
$position = $config->get('LOAD_EXTERNAL_DATA_POSITION');
switch ($currStep) {
case 'LOAD_LOCATION_ALL':
$ret = $locationLoader->loadAll($position);
$currStep = 'LOAD_LOCATION_ALL';
$nextStep = 'LOAD_LOCATION_CASH_PAY';
if ($ret !== true) {
break;
}
case 'LOAD_LOCATION_CASH_PAY':
$ret = $locationLoader->loadCashPay($position);
$currStep = 'LOAD_LOCATION_CASH_PAY';
$nextStep = 'LOAD_TERMINAL_UNLIMITED';
if ($ret !== true) {
break;
}
case 'LOAD_TERMINAL_UNLIMITED':
$ret = $terminalLoader->loadUnlimited($position);
$currStep = 'LOAD_TERMINAL_UNLIMITED';
$nextStep = 'LOAD_TERMINAL_LIMITED';
if ($ret !== true) {
break;
}
case 'LOAD_TERMINAL_LIMITED':
$ret = $terminalLoader->loadLimited($position);
$currStep = 'LOAD_TERMINAL_LIMITED';
$nextStep = 'LOAD_FINISH';
if ($ret !== true) {
break;
}
default:
$ret = true;
$currStep = 'LOAD_FINISH';
$nextStep = 'LOAD_LOCATION_ALL';
break;
}
$nextStep = is_bool($ret) ? $nextStep : $currStep;
$position = is_bool($ret) ? '' : $ret;
$config->set('LOAD_EXTERNAL_DATA_STEP', $nextStep);
$config->set('LOAD_EXTERNAL_DATA_POSITION', $position);
}
}<file_sep>/src/lib/DB/Order/Model.php
<?php
namespace Ipol\DPD\DB\Order;
use \Ipol\DPD\Order as DpdOrder;
use \Ipol\DPD\DB\Model as BaseModel;
use \Ipol\DPD\Shipment;
/**
* Модель одной записи таблицы заказов
*/
class Model extends BaseModel
{
const SERVICE_VARIANT_D = 'Д';
const SERVICE_VARIANT_T = 'Т';
/**
* Отправление
* @var \Ipol\DPD\Shipment
*/
protected $shipment;
/**
* Возвращает список статусов и их описаний
*
* @return array
*/
public static function StatusList()
{
return array(
DpdOrder::STATUS_NEW => 'Новый заказ, еще не отправлялся в DPD',
DpdOrder::STATUS_OK => 'Успешно создан',
DpdOrder::STATUS_PENDING => 'Принят, но нуждается в ручной доработке сотрудником DPD',
DpdOrder::STATUS_ERROR => 'Не принят, ошибка',
DpdOrder::STATUS_CANCEL => 'Заказ отменен',
DpdOrder::STATUS_CANCEL_PREV => 'Заказ отменен ранее',
DpdOrder::STATUS_NOT_DONE => 'Заказ отменен в процессе доставки',
DpdOrder::STATUS_DEPARTURE => 'Посылка находится на терминале приема отправления',
DpdOrder::STATUS_TRANSIT => 'Посылка находится в пути (внутренняя перевозка DPD)',
DpdOrder::STATUS_TRANSIT_TERMINAL => 'Посылка находится на транзитном терминале',
DpdOrder::STATUS_ARRIVE => 'Посылка находится на терминале доставки',
DpdOrder::STATUS_COURIER => 'Посылка выведена на доставку',
DpdOrder::STATUS_DELIVERED => 'Посылка доставлена получателю',
DpdOrder::STATUS_LOST => 'Посылка утеряна',
DpdOrder::STATUS_PROBLEM => 'C посылкой возникла проблемная ситуация',
DpdOrder::STATUS_RETURNED => 'Посылка возвращена с курьерской доставки',
DpdOrder::STATUS_NEW_DPD => 'Оформлен новый заказ по инициативе DPD',
DpdOrder::STATUS_NEW_CLIENT => 'Оформлен новый заказ по инициативе клиента',
);
}
/**
* Возвращает отправку
*
* @param bool $forced true - создает новый инстанс на основе полей записи
*
* @return \Ipol\DPD\Shipment
*/
public function getShipment($forced = false)
{
if (is_null($this->shipment) || $forced) {
$this->shipment = new Shipment($this->getTable()->getConfig());
$this->shipment->setSender($this->senderLocation);
$this->shipment->setReceiver($this->receiverLocation);
$this->shipment->setPaymentMethod($this->personeTypeId, $this->paySystemId);
$this->shipment->setItems($this->orderItems, $this->sumNpp);
list($selfPickup, $selfDelivery) = array_values($this->getServiceVariant());
$this->shipment->setSelfPickup($selfPickup);
$this->shipment->setSelfDelivery($selfDelivery);
if ($this->isCreated()) {
$this->shipment->setWidth($this->dimensionWidth);
$this->shipment->setHeight($this->dimensionHeight);
$this->shipment->setLength($this->dimensionLength);
$this->shipment->setWeight($this->cargoWeight);
}
}
return $this->shipment;
}
/**
* Ассоциирует внешнюю отправку с записью
* Происходит заполнение полей записи на основе данных отправки
*
* @param \Ipol\DPD\Shipment $shipment
*
* @return self
*/
public function setShipment(Shipment $shipment)
{
$this->shipment = $shipment;
$this->senderLocation = $shipment->getSender()['ID'];
$this->receiverLocation = $shipment->getReceiver()['ID'];
$this->cargoWeight = $shipment->getWeight();
$this->cargoVolume = $shipment->getVolume();
$this->dimensionWidth = $shipment->getWidth();
$this->dimensionWidth = $shipment->getHeight();
$this->dimensionLength = $shipment->getLength();
$this->personeTypeId = $shipment->getPaymentMethod()['PERSONE_TYPE_ID'];
$this->paySystemId = $shipment->getPaymentMethod()['PAY_SYSTEM_ID'];
$this->orderItems = $shipment->getItems();
$this->price = $shipment->getPrice();
$this->serviceVariant = [
'SELF_PICKUP' => $shipment->getSelfPickup(),
'SELF_DELIVERY' => $shipment->getSelfDelivery(),
];
return $this;
}
/**
* Сеттер св-ва ORDER_ITEMS
*
* @param array $items
*/
public function setOrderItems($items)
{
$this->fields['ORDER_ITEMS'] = \serialize($items);
return $this;
}
/**
* Геттер св-ва ORDER_ITEMS
*
* @return array
*/
public function getOrderItems()
{
return \unserialize($this->fields['ORDER_ITEMS']);
}
/**
* Сеттер св-ва NPP
*
* @param float $npp
*
* @return self
*/
public function setNpp($npp)
{
$this->fields['NPP'] = $npp;
$this->fields['SUM_NPP'] = $npp == 'Y' ? $this->price : 0;
return $this;
}
/**
* Устанавливает вариант доставки
*
* @param string $variant
*
* @return self
*/
public function setServiceVariant($variant)
{
$D = self::SERVICE_VARIANT_D;
$T = self::SERVICE_VARIANT_T;
if (is_string($variant) && preg_match('~^('. $D .'|'. $T .'){2}$~sUi', $variant)) {
$this->fields['SERVICE_VARIANT'] = $variant;
} else if (is_array($variant)) {
$selfPickup = $variant['SELF_PICKUP'];
$selfDelivery = $variant['SELF_DELIVERY'];
$this->fields['SERVICE_VARIANT'] = ''
. ($selfPickup ? $T : $D)
. ($selfDelivery ? $T : $D)
;
}
return $this;
}
/**
* Возвращает вариант доставки
*
* @return array
*/
public function getServiceVariant()
{
$D = self::SERVICE_VARIANT_D;
$T = self::SERVICE_VARIANT_T;
return array(
'SELF_PICKUP' => mb_substr($this->fields['SERVICE_VARIANT'], 0, 1) == $T,
'SELF_DELIVERY' => mb_substr($this->fields['SERVICE_VARIANT'], 1, 1) == $T,
);
}
/**
* Возвращает флаг доставка от ТЕРМИНАЛА или ДВЕРИ
*
* @return bool
*/
public function isSelfPickup()
{
$serviceVariant = $this->getServiceVariant();
return $serviceVariant['SELF_PICKUP'];
}
/**
* Возвращает флаг доставка до ТЕРМИНАЛА или ДВЕРИ
*
* @return bool
*/
public function isSelfDelivery()
{
$serviceVariant = $this->getServiceVariant();
return $serviceVariant['SELF_DELIVERY'];
}
/**
* Возвращает текстовое описание статуса заказа
*
* @return string
*/
public function getOrderStatusText()
{
$statusList = static::StatusList();
$ret = $statusList[$this->orderStatus];
if ($this->orderStatus == DpdOrder::STATUS_ERROR) {
$ret .= ': '. $this->orderError;
}
return $ret;
}
/**
* Возвращает ифнормацию о тарифе
*
* @param bool $forced пересоздать ли экземпляр отгрузки
*
* @return array
*/
public function getTariffDelivery($forced = false)
{
return $this->getShipment($forced)->calculator()->calculateWithTariff($this->serviceCode, $this->currency);
}
/**
* Возвращает стоимость доставки в заказе
*
* @return float
*/
public function getActualPriceDelivery()
{
$tariff = $this->getTariffDelivery();
if ($tariff) {
return $tariff['COST'];
}
return false;
}
/**
* Сеттер для номера заказа, попутно устанавливаем номер отправления
*
* @param $orderNum
*
* @return self
*/
public function setOrderNum($orderNum)
{
$this->fields['ORDER_NUM'] = $orderNum;
$this->fields['ORDER_DATE_CREATE'] = $orderNum ? date('Y-m-d H:i:s') : null;
return $this;
}
/**
* Сеттер для статуса заказа
*
* @param $orderStatus
* @param $orderStatusDate
*
* @return self
*/
public function setOrderStatus($orderStatus, $orderStatusDate = false)
{
if (empty($orderStatus)) {
return;
}
if (!array_key_exists($orderStatus, self::StatusList())) {
return;
}
$this->fields['ORDER_STATUS'] = $orderStatus;
$this->fields['ORDER_DATE_STATUS'] = $orderStatusDate ?: date('Y-m-d H:i:s');
if ($orderStatus == DpdOrder::STATUS_CANCEL) {
$this->fields['ORDER_DATE_CANCEL'] = $orderStatusDate ?: date('Y-m-d H:i:s');
}
}
/**
* Возвращает флаг новый заказ
*
* @return bool
*/
public function isNew()
{
return $this->fields['ORDER_STATUS'] == DpdOrder::STATUS_NEW;
}
/**
* Проверяет отправлялся ли заказ в DPD
*
* @return bool
*/
public function isCreated()
{
return $this->fields['ORDER_STATUS'] != DpdOrder::STATUS_NEW
&& $this->fields['ORDER_STATUS'] != DpdOrder::STATUS_CANCEL;
}
/**
* Проверяет отправлялся ли заказ в DPD и был ли он там успешно создан
*
* @return bool
*/
public function isDpdCreated()
{
return $this->isCreated() && !empty($this->fields['ORDER_NUM']);
}
/**
* Возвращает инстанс для работы с внешним заказом
*
* @return \Ipol\DPD\Order;
*/
public function dpd()
{
return new DpdOrder($this);
}
}<file_sep>/src/lib/DB/Terminal/Model.php
<?php
namespace Ipol\DPD\DB\Terminal;
use \Ipol\DPD\DB\Model as BaseModel;
use Ipol\DPD\Shipment;
/**
* Модель одной записи таблицы терминалов
*/
class Model extends BaseModel
{
/**
* Проверяет может ли терминал принять посылку
*
* @param \Ipol\DPD\Shipment $shipment
* @param bool $checkLocation
*
* @return bool
*/
public function checkShipment(Shipment $shipment, $checkLocation = true)
{
if ($checkLocation
&& !$this->checkLocation($shipment->getReceiver())
) {
return false;
}
if ($shipment->isPaymentOnDelivery()
&& !$this->checkShipmentPayment($shipment)
) {
return false;
}
if (!$this->checkShipmentDimessions($shipment)) {
return false;
}
return true;
}
/**
* Сверяет местоположение терминала и переданного местоположения
*
* @param array $location
*
* @return bool
*/
public function checkLocation(array $location)
{
return $this->fields['LOCATION_ID'] == $location['CITY_ID'];
}
/**
* Проверяет возможность принять НПП на терминале
*
* @param \Ipol\DPD\Shipment $shipment
*
* @return bool
*/
public function checkShipmentPayment(Shipment $shipment)
{
if ($this->fields['NPP_AVAILABLE'] != 'Y') {
return false;
}
return $this->fields['NPP_AMOUNT'] >= $shipment->getPrice();
}
/**
* Проверяет габариты посылки на возможность ее принятия на терминале
*
* @param \Ipol\DPD\Shipment $shipment
*
* @return bool
*/
public function checkShipmentDimessions(Shipment $shipment)
{
if ($this->fields['IS_LIMITED'] != 'Y') {
return true;
}
return (
$this->fields['LIMIT_MAX_WEIGHT'] <= 0
|| $shipment->getWeight() <= $this->fields['LIMIT_MAX_WEIGHT']
)
&& (
$this->fields['LIMIT_MAX_VOLUME'] <= 0
|| $shipment->getVolume() <= $this->fields['LIMIT_MAX_VOLUME']
)
&& (
$this->fields['LIMIT_SUM_DIMENSION'] <= 0
|| array_sum([$shipment->getWidth(), $shipment->getHeight(), $shipment->getLength()]) <= $this->fields['LIMIT_SUM_DIMENSION']
)
;
}
}<file_sep>/examples/create.php
<?php<?php
require __DIR__ .'/../src/autoload.php';
$config = new \Ipol\DPD\Config\Config([
'KLIENT_NUMBER' => '',
'KLIENT_KEY' => '',
'KLIENT_CURRENCY' => 'RUB',
'IS_TEST' => true,
]);
$shipment = new \Ipol\DPD\Shipment($config);
$shipment->setSender('Россия', 'Москва', 'г. Москва');
$shipment->setReceiver('Россия', 'Тульская область', 'г. Тула');
$shipment->setSelfDelivery(true);
$shipment->setSelfPickup(true);
$shipment->setItems([
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 200,
'WIDTH' => 100,
'HEIGHT' => 50,
]
],
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 350,
'WIDTH' => 70,
'HEIGHT' => 200,
]
],
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 220,
'WIDTH' => 100,
'HEIGHT' => 70,
]
],
], 3000);
$order = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('order')->makeModel();
$order->setShipment($shipment);
$order->orderId = 1;
$order->currency = 'RUB';
$order->serviceCode = 'PCL';
$order->senderName = 'Наименование отправителя';
$order->senderFio = 'ФИО отправителя';
$order->senderPhone = 'Телефон отправителя';
$order->senderTerminalCode = '009M';
$order->receiverName = 'Наименование получателя';
$order->receiverFio = 'ФИО получателя';
$order->receiverPhone = 'Телефон получателя';
$order->receiverTerminalCode = '012K';
$order->pickupDate = '2017-12-02';
$order->pickupTimePeriod = '9-18';
$result = $order->dpd()->create();
print_r($result);<file_sep>/data/db/install/mysql/b_ipol_dpd_location.sql
create table IF NOT EXISTS b_ipol_dpd_location (
ID int not null auto_increment,
COUNTRY_CODE varchar(255) null,
COUNTRY_NAME varchar(255) null,
REGION_CODE varchar(255) null,
REGION_NAME varchar(255) null,
CITY_ID bigint UNSIGNED NOT NULL default '0',
CITY_CODE varchar(255) null,
CITY_NAME varchar(255) null,
CITY_ABBR varchar(255) null,
LOCATION_ID int not null default '0',
IS_CASH_PAY char(1) not null default 'N',
ORIG_NAME varchar(255) null,
ORIG_NAME_LOWER varchar(255) null,
primary key (ID)
);
CREATE INDEX IF NOT EXISTS b_ipol_dpd_location_crc ON b_ipol_dpd_location (CITY_NAME, REGION_NAME, COUNTRY_NAME);
CREATE INDEX IF NOT EXISTS b_ipol_dpd_location_search_text ON b_ipol_dpd_location (ORIG_NAME_LOWER);<file_sep>/examples/load_terminals.php
<?php
require __DIR__ .'/../src/autoload.php';
$config = new \Ipol\DPD\Config\Config([
'KLIENT_NUMBER' => '',
'KLIENT_KEY' => '',
'KLIENT_CURRENCY' => 'RUB',
]);
$table = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('terminal');
$api = \Ipol\DPD\API\User\User::getInstanceByConfig($config);
$loader = new \Ipol\DPD\DB\Terminal\Agent($api, $table);
$loader->loadUnlimited();
$loader->loadLimited();
<file_sep>/examples/calculate.php
<?php<?php
require __DIR__ .'/../src/autoload.php';
$config = new \Ipol\DPD\Config\Config([
'KLIENT_NUMBER' => '',
'KLIENT_KEY' => '',
'KLIENT_CURRENCY' => 'RUB',
]);
$shipment = new \Ipol\DPD\Shipment($config);
$shipment->setSender('Россия', 'Москва', 'г. Москва');
$shipment->setReceiver('Россия', 'Тульская область', 'г. Тула');
// $shipment->setSelfDelivery(false);
// $shipment->setSelfPickup(false);
$shipment->setItems([
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 200,
'WIDTH' => 100,
'HEIGHT' => 50,
]
],
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 350,
'WIDTH' => 70,
'HEIGHT' => 200,
]
],
[
'NAME' => '<NAME>',
'QUANTITY' => 1,
'PRICE' => 1000,
'VAT_RATE' => 18,
'WEIGHT' => 1000,
'DIMENSIONS' => [
'LENGTH' => 220,
'WIDTH' => 100,
'HEIGHT' => 70,
]
],
], 3000);
$tariff = $shipment->calculator()->calculate();<file_sep>/examples/cancel.php
<?php<?php
require __DIR__ .'/../src/autoload.php';
$config = new \Ipol\DPD\Config\Config([
'KLIENT_NUMBER' => '',
'KLIENT_KEY' => '',
'KLIENT_CURRENCY' => 'RUB',
'IS_TEST' => true,
]);
// получить созданный ранее заказ и отменить его
$orderId = 1; // внешний ID заказа
$order = \Ipol\DPD\DB\Connection::getInstance($config)->getTable('order')->getByOrderId($orderId);
$ret = $order->dpd()->cancel();
var_dump($ret); | 3a22617e0ed303ea7c5897ef95af362f9838e426 | [
"SQL",
"PHP"
] | 8 | PHP | talapaillp/dpd.sdk | a174aa681db5c7a185447d62c6a89cf85d778ebf | 74ac2fe18a717902d311b0d64df9bb1a35d0b752 | |
refs/heads/master | <file_sep>#ifndef DATE_H
#define DATE_H
class Date {
public:
int year;
int month;
int day;
Date();
Date(int, int, int);
bool isLeap();
static Date getCurrentDate();
};
std::ostream& operator<<(std::ostream&, const Date&);
std::istream& operator>>(std::istream&, Date&);
bool operator== (Date const&, Date const&);
bool operator!= (Date const&, Date const&);
bool operator> (Date const&, Date const&);
bool operator< (Date const&, Date const&);
bool operator>= (Date const&, Date const&);
bool operator<= (Date const&, Date const&);
#endif
<file_sep>#ifndef COMMANDS_H
#define COMMANDS_H
#include <string>
#include "User.hpp"
#include "DatabaseHelper.hpp"
class BaseCommand {
private:
std::string name;
public:
BaseCommand(std::string);
std::string getName() const;
virtual void execute() = 0;
};
class HelpCommand : public BaseCommand {
public:
HelpCommand();
void execute();
};
class ExitCommand : public BaseCommand {
public:
ExitCommand();
void execute();
};
class UserCommand : public BaseCommand {
protected:
User& user;
DatabaseHelper& dbh;
public:
UserCommand(std::string, User&, DatabaseHelper&);
User& getUser() const;
virtual void execute() = 0;
};
class RegisterCommand : public UserCommand {
public:
RegisterCommand(User&, DatabaseHelper&);
void execute();
};
class LoginCommand : public UserCommand {
public:
LoginCommand(User&, DatabaseHelper&);
void execute();
};
class TravelCommand : public UserCommand {
public:
TravelCommand(User&, DatabaseHelper&);
void execute();
};
class BrowseCommand : public UserCommand {
public:
BrowseCommand(User&, DatabaseHelper&);
void execute();
};
class FriendCommand : public UserCommand {
public:
FriendCommand(User&, DatabaseHelper&);
void execute();
};
class ListCommand : public UserCommand {
public:
ListCommand(User&, DatabaseHelper&);
void execute();
};
class ListGradesCommand : public UserCommand {
public:
ListGradesCommand(User&, DatabaseHelper&);
void execute();
};
#endif
<file_sep>#ifndef ITEM_H
#define ITEM_H
#include <string>
#include "Date.hpp"
enum Metric {kg, l};
class Item {
private:
std::string name;
Date expirationDate;
Date admissionDate;
std::string manufacturerName;
Metric metric;
int quantity;
std::string comment;
public:
Item();
Item(std::string, Date, Date, std::string, Metric, int, std::string);
Item(std::string, Date, Date, std::string, Metric, int);
Item(std::string, Date, std::string, Metric, int, std::string);
Item(std::string, Date, std::string, Metric, int);
std::string getName() const;
Date getExpirationDate() const;
Date getAdmissionDate() const;
std::string getManufacturerName() const;
Metric getMetric() const;
int getQuantity() const;
std::string getComment() const;
void setName(std::string);
void setExpirationDate(Date);
void setAdmissionDate(Date);
void setManufacturerName(std::string);
void setMetric(Metric);
void setQuantity(int);
void setComment(std::string);
void print();
int updateQuantity(int);
friend std::ostream& operator<<(std::ostream&, const Item&);
friend std::istream& operator>>(std::istream&, Item&);
};
std::ostream& operator<<(std::ostream&, const Metric&);
std::istream& operator>>(std::istream&, Metric&);
#endif
<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
#include "Commands.hpp"
#include "Date.hpp"
#include "Warehouse.hpp"
#include <ctime>
int main() {
Warehouse warehouse;
std::vector<BaseCommand*> commands;
commands.push_back(new HelpCommand());
commands.push_back(new ExitCommand());
commands.push_back(new OpenCommand(warehouse));
commands.push_back(new CloseCommand(warehouse));
commands.push_back(new SaveCommand(warehouse));
commands.push_back(new SaveAsCommand(warehouse));
commands.push_back(new PrintCommand(warehouse));
commands.push_back(new AddCommand(warehouse));
commands.push_back(new RemoveCommand(warehouse));
commands.push_back(new LogCommand(warehouse));
commands.push_back(new CleanCommand(warehouse));
std::string command;
while (true) {
try {
std::cout << "Enter command: ";
std::cin >> command;
std::vector<BaseCommand*>::iterator pos = std::find_if(commands.begin(), commands.end(),
[&command](const BaseCommand* x) { return x->getName() == command; });
if (pos != commands.end()) {
(*pos)->execute();
} else {
std::cout << "Invalid command" << std::endl;
}
} catch (const char* err) {
std::cout << err << std::endl;
}
}
return 0;
}
// test 2000-05-05 2000-05-05 test kg 10 ee<file_sep>#include <map>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include "Warehouse.hpp"
#include "Item.hpp"
#include "Date.hpp"
Warehouse::Warehouse() : spaces(100), spaceCapacity(10) {};
Warehouse::Warehouse(int spaces, int capacity) : spaces(spaces), spaceCapacity(spaceCapacity) {};
std::map<int, Item> Warehouse::getItems() const {
return this->items;
}
void Warehouse::setItems(std::map<int, Item> items) {
this->items = items;
}
void Warehouse::addItem(Item item) {
int freeSpace = 1;
for (auto& [space, it] : this->items) {
if (space == freeSpace) {
freeSpace++;
}
if (item.getName() == it.getName() && item.getExpirationDate() == it.getExpirationDate()) {
int capacityLeft = this->spaceCapacity - it.getQuantity();
if (capacityLeft >= item.getQuantity()) {
it.updateQuantity(item.getQuantity());
this->actions.push_back(WarehouseAction("add", item, Date::getCurrentDate(), space));
return;
} else {
it.updateQuantity(capacityLeft);
int intendedQuan = item.updateQuantity(-capacityLeft);
item.setQuantity(capacityLeft);
this->actions.push_back(WarehouseAction("add", item, Date::getCurrentDate(), space));
item.setQuantity(intendedQuan);
}
}
}
int wholeQuantity = item.getQuantity();
do {
int quantity = std::min(this->spaceCapacity, item.getQuantity());
item.setQuantity(quantity);
wholeQuantity -= quantity;
this->items.insert(std::pair<int, Item>(freeSpace, item));
this->actions.push_back(WarehouseAction("add", item, Date::getCurrentDate(), freeSpace));
} while (wholeQuantity > 0);
}
void Warehouse::removeItem(std::string name, int quantity) {
std::vector<std::pair<int, Item>> items;
for (auto it = this->items.begin(); it != this->items.end(); ++it) {
if (it->second.getName() == name) {
items.push_back((*it));
}
}
int leftInStock = 0;
for (auto& [space, item] : items) {
leftInStock += item.getQuantity();
}
if (leftInStock < quantity) {
std::string answer;
do {
std::cout << "There are " << leftInStock << " " << name << " left in stock. Remove all of them? (y/n)";
std::cin >> answer;
} while (answer != "y" && answer != "n");
if (answer == "n") return;
quantity = leftInStock;
}
sort(items.begin(), items.end(), [](const std::pair<int, Item>& a, const std::pair<int, Item>& b) -> bool {
return a.second.getExpirationDate() > b.second.getExpirationDate();
});
for (auto& [space, item] : items) {
int oldQuantity = item.getQuantity();
this->items[space].updateQuantity( - std::min(quantity, this->items[space].getQuantity()));
quantity -= (oldQuantity - this->items[space].getQuantity());
Item copy = item;
copy.setQuantity(oldQuantity - this->items[space].getQuantity());
this->actions.push_back(WarehouseAction("remove", copy, Date::getCurrentDate(), space));
if (this->items[space].getQuantity() == 0) {
this->items.erase(space);
}
if (quantity == 0) {
break;
}
}
}
void Warehouse::clean() {
Date currentDate = Date::getCurrentDate();
for (auto it = this->items.begin(); it != items.end(); it++) {
if (it->second.getExpirationDate() < currentDate) {
this->actions.push_back(WarehouseAction("remove", it->second, Date::getCurrentDate(), it->first));
it = this->items.erase(it);
}
}
}
void Warehouse::print() const {
for (auto const& [space, item] : this->items) {
int totalQuantity = 0;
for (auto const& [key, value] : this->items) {
if (value.getName() == item.getName()) {
totalQuantity += value.getQuantity();
}
}
std::cout << space << " -> ";
std::cout << item.getName() << " " << item.getManufacturerName() << " Quanitity: " << item.getQuantity() << " Total in warehouse: " << totalQuantity << item.getMetric();
std::cout << " Admissioned at: " << item.getAdmissionDate() << " Expires at: " << item.getExpirationDate() << ". Comment: " << item.getComment() << std::endl;
}
}
void Warehouse::toFile(std::ofstream& ofs) const {
ofs << this->spaces << " " << this->spaceCapacity << std::endl;
for (auto const& [space, item] : this->items) {
ofs << space << " " << item << std::endl;
}
ofs << "|\n";
for (auto const& action : this->actions) {
ofs << action;
}
}
void Warehouse::fromFile(std::ifstream& ifs) {
ifs >> this->spaces >> this->spaceCapacity;
std::string space;
Item item;
std::cout << "ee";
while (ifs >> space) {
std::cout << "Read: " << space;
std::cout << (space == "|") << std::endl;
if (space == "|") break;
ifs >> item;
this->items.insert(std::pair<int, Item>(std::stoi(space), item));
}
// get new line
char c;
ifs >> c;
WarehouseAction action;
std::string line;
while(getline(ifs, line)) {
std::istringstream stream;
stream.str(line);
stream >> action;
this->actions.push_back(action);
}
}
void Warehouse::log(Date start, Date end) const {
std::vector<WarehouseAction> filtered;
std::copy_if(this->actions.begin(), this->actions.end(), std::back_inserter(filtered), [&start, &end](WarehouseAction action) {
return (action.getDate() > start && action.getDate() < end);
});
std::sort(filtered.begin(), filtered.end(), [](const WarehouseAction& a, const WarehouseAction& b) -> bool {
return a.getDate() > b.getDate();
});
for (auto& a : filtered) {
std::cout << a;
}
}
WarehouseAction::WarehouseAction() : action("null"), item(), date(), space(0) {};
WarehouseAction::WarehouseAction(std::string action, Item item, Date date, int space) : action(action), item(item), date(date), space(space) {};
Date WarehouseAction::getDate() const {
return this->date;
}
void WarehouseAction::print() const {
std::cout << this->date << " Action: " << this->action << " Space: " << this->space << " Item: " << this->item << std::endl;
}
std::ostream& operator<<(std::ostream& os, const WarehouseAction& action) {
os << action.date << " " << action.action << " " << action.space << " " << action.item << std::endl;
return os;
}
std::istream& operator>>(std::istream& is, WarehouseAction& action) {
is >> action.date >> action.action >> action.space >> action.item;
return is;
}<file_sep>#include <iostream>
#include <fstream>
#include <string>
#include <set>
#include <map>
#include "Commands.hpp"
#include "User.hpp"
#include "Travel.hpp"
BaseCommand::BaseCommand(std::string name) : name(name) {};
UserCommand::UserCommand(std::string name, User& user, DatabaseHelper& dbh) : BaseCommand(name), user(user), dbh(dbh) {};
HelpCommand::HelpCommand() : BaseCommand("help") {};
ExitCommand::ExitCommand() : BaseCommand("exit") {};
RegisterCommand::RegisterCommand(User& user, DatabaseHelper& dbh) : UserCommand("register", user, dbh) {};
LoginCommand::LoginCommand(User& user, DatabaseHelper& dbh) : UserCommand("login", user, dbh) {};
TravelCommand::TravelCommand(User& user, DatabaseHelper& dbh) : UserCommand("travel", user, dbh) {};
FriendCommand::FriendCommand(User& user, DatabaseHelper& dbh) : UserCommand("friend", user, dbh) {};
BrowseCommand::BrowseCommand(User& user, DatabaseHelper& dbh) : UserCommand("browse", user, dbh) {};
ListCommand::ListCommand(User& user, DatabaseHelper& dbh) : UserCommand("list", user, dbh) {};
ListGradesCommand::ListGradesCommand(User& user, DatabaseHelper& dbh) : UserCommand("list_grades", user, dbh) {};
std::string BaseCommand::getName() const {
return this->name;
}
User& UserCommand::getUser() const {
return this->user;
}
void HelpCommand::execute() {
std::cout << "The following commands are supported:" << std::endl;
std::cout << "help prints this information" << std::endl;
std::cout << "exit exists the program" << std::endl;
std::cout << "register register new user" << std::endl;
std::cout << "login login to existing user" << std::endl;
std::cout << "travel record one of your travels." << std::endl;
std::cout << "browse list all of your friends' travels" << std::endl;
std::cout << "list list all destinations in the database" << std::endl;
std::cout << "list_grades list all destinations with grades from users and average grade" << std::endl;
}
void ExitCommand::execute() {
exit(0);
}
void RegisterCommand::execute() {
if ( ! this->user.getLoggedIn()) {
bool taken = false;
std::string username, password, email;
do {
std::cout << "Enter username: ";
std::cin >> username;
} while(this->dbh.userExists(username));
std::cout << "Enter password: ";
std::cin >> password;
std::cout << "Enter email: ";
std::cin >> email;
this->user = User(username, password, email);
this->dbh.recordUser(this->user);
std::cout << "Registered successfully!";
} else {
throw "Currently logged in";
}
}
void LoginCommand::execute() {
if ( ! this->user.getLoggedIn()) {
std::string username, password;
std::cout << "Enter username: ";
std::cin >> username;
std::cout << "Enter password: ";
std::cin >> password;
this->user = this->dbh.getUser(username);
if (this->user.checkCredentials(username, password)) {
this->user.setLoggedIn(true);
} else {
this->user = User();
throw "Invalid username or password";
}
std::cout << "Loged in!";
} else {
throw "Already logged in";
}
}
void TravelCommand::execute() {
if (this->user.getLoggedIn()) {
Travel travel;
std::cin >> travel;
this->dbh.recordTravel(this->user, travel);
} else {
throw "Not logged in";
}
}
void BrowseCommand::execute() {
for (auto& fr : this->user.getFriends()) {
std::vector<Travel> travels = this->dbh.getTravels(fr);
for (auto& travel : travels) {
std::cout << fr << " traveled to ";
travel.print();
}
}
}
void FriendCommand::execute() {
if (this->user.getLoggedIn()) {
std::string name;
std::cout << "Enter friend name";
std::cin >> name;
this->user.addFriend(name);
this->dbh.addFriend(this->user, name);
} else {
throw "Not logged in";
}
}
void ListCommand::execute() {
if (this->user.getLoggedIn()) {
std::vector<User> users = this->dbh.getUsers();
std::set<std::string> destinations;
for (auto& user : users) {
std::vector<Travel> travels = this->dbh.getTravels(user.getUsername());
for (auto& travel : travels) {
destinations.insert(travel.getDestination());
}
}
std::cout << "List of all destinations: " << std::endl;
for (auto& destination : destinations) {
std::cout << "- " << destination << std::endl;
}
} else {
throw "Not logged in";
}
}
void ListGradesCommand::execute() {
if (this->user.getLoggedIn()) {
std::vector<User> users = this->dbh.getUsers();
std::map<std::string, std::pair<int, float>> destinations;
for (auto& user : users) {
std::vector<Travel> travels = this->dbh.getTravels(user.getUsername());
for (auto& travel : travels) {
std::cout << user.getUsername() << " gave " << travel.getDestination() << " grade " << travel.getGrade() << std::endl;
if (destinations.find(travel.getDestination()) == destinations.end()) {
destinations.insert(
std::pair<std::string, std::pair<int, float>>(
travel.getDestination(), std::pair<int, float>(1, travel.getGrade())
)
);
} else {
destinations[travel.getDestination()].first++;
destinations[travel.getDestination()].second += travel.getGrade();
}
}
}
std::cout << "Average grades: " << std::endl;
for (auto& [destination, grades] : destinations) {
std::cout << "- " << destination << " AVG: " << (grades.second / grades.first) << std::endl;
}
} else {
throw "Not logged in";
}
}
<file_sep>#ifndef WAREHOUSE_H
#define WAREHOUSE_H
#include <map>
#include <vector>
#include "Item.hpp"
class WarehouseAction {
private:
/* A big improvement would be not storing the whole item but just some id
but it was too much work to redo. Besides the whole project would be better as an actual database in the first place */
std::string action;
Item item;
Date date;
int space;
public:
WarehouseAction();
WarehouseAction(std::string, Item, Date, int);
Date getDate() const;
void print() const;
friend std::ostream& operator<<(std::ostream&, const WarehouseAction&);
friend std::istream& operator>>(std::istream&, WarehouseAction&);
};
class Warehouse {
private:
int spaces;
int spaceCapacity;
/*
Could be the same with vector but the map helps a bit with keeping it sorted
and mainly it can later be upgrated easier to track products in a more complex way rather than just a number
*/
std::map<int, Item> items;
std::vector<WarehouseAction> actions;
public:
Warehouse(int, int);
Warehouse();
std::map<int, Item> getItems() const;
void setItems(std::map<int, Item>);
void addItem(Item);
void removeItem(std::string, int);
void clean();
void log(Date, Date) const;
void print() const;
void toFile(std::ofstream&) const;
void fromFile(std::ifstream&);
};
#endif
<file_sep>#ifndef USER_H
#define USER_H
#include <string>
#include <vector>
class User {
private:
/* Would be better to identify with id insead of the username
but it's not a real database */
std::string username;
std::string passwordHash;
std::string email;
bool loggedIn = false;
std::vector<std::string> friends;
public:
User();
User(std::string, std::string, std::string);
std::string getUsername() const;
std::string getPasswordHash() const;
std::string getEmail() const;
std::vector<std::string> getFriends() const;
bool getLoggedIn() const;
void setLoggedIn(bool);
void addFriend(std::string);
bool checkCredentials(std::string, std::string);
friend std::ostream& operator<<(std::ostream&, const User&);
friend std::istream& operator>>(std::istream&, User&);
};
#endif
<file_sep>#ifndef TRAVEL_H
#define TRAVEL_H
#include <string>
#include <vector>
#include "Date.hpp"
class Travel {
private:
std::string destination;
Date from, to;
float grade;
std::string comment;
std::vector<std::string> photos;
public:
Travel();
Travel(std::string, Date, Date, float, std::string, std::vector<std::string>);
std::string getDestination() const;
Date getStartDate() const;
Date getEndDate() const;
float getGrade() const;
std::string getComment() const;
std::vector<std::string> getPhotos() const;
void setDestination(std::string);
void setStartDate(Date);
void setEndDate(Date);
void setGrade(float);
void setComment(std::string);
void setPhotos(std::vector<std::string>);
void print() const;
void addPhoto(std::string);
friend std::ostream& operator<<(std::ostream&, const Travel&);
friend std::istream& operator>>(std::istream&, Travel&);
};
#endif
<file_sep>#ifndef DATABASE_HELPER_H
#define DATABASE_HELPER_H
#include <string>
#include <fstream>
#include "User.hpp"
#include "Travel.hpp"
class DatabaseHelper {
private:
std::fstream users;
protected:
static std::string dbName;
public:
DatabaseHelper();
bool userExists(std::string);
User getUser(std::string);
void recordUser(const User&);
void recordTravel(const User&, const Travel&);
std::vector<Travel> getTravels(std::string);
std::vector<User> getUsers();
void addFriend(const User&, std::string);
};
#endif<file_sep>#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include "Travel.hpp"
Travel::Travel() {}
Travel::Travel(std::string destination, Date from, Date to, float grade, std::string comment, std::vector<std::string> photos)
: destination(destination), from(from), to(to), grade(grade), comment(comment), photos(photos) {
if (from > to) {
throw "Inavlid dates. Start date should be smaller than end date";
}
for (auto& photo : photos) {
std::string::size_type i;
for (i = 0; i < photo.size(); i++) {
if (photo[i] == '.') {
break;
} else if ((photo[i] < 'a' || photo[i] > 'z') && (photo[i] < 'A' || photo[i] > 'Z') && (photo[i] != '_')) {
throw "Invalid photo name";
}
}
std::string extension = photo.substr(i + 1);
if (extension != "jpeg" && extension != "png") {
throw "Invalid photo name";
}
}
if (grade < 1 || grade > 5) {
throw "Invalid grade";
}
}
std::string Travel::getDestination() const {
return this->destination;
}
Date Travel::getStartDate() const {
return this->from;
}
Date Travel::getEndDate() const {
return this->to;
}
float Travel::getGrade() const {
return this->grade;
}
std::string Travel::getComment() const {
return this->comment;
}
std::vector<std::string> Travel::getPhotos() const {
return this->photos;
}
void Travel::setDestination(std::string destination) {
this->destination = destination;
}
void Travel::setStartDate(Date from) {
this->from = from;
}
void Travel::setEndDate(Date to) {
this->to = to;
}
void Travel::setGrade(float grade) {
this->grade = grade;
}
void Travel::setComment(std::string comment) {
this->comment = comment;
}
void Travel::setPhotos(std::vector<std::string> photos) {
this->photos = photos;
}
void Travel::addPhoto(std::string photo) {
this->photos.push_back(photo);
}
void Travel::print() const {
std::cout << this->destination << " from " << this->from << " to " << this->to << " Rated: "
<< this->grade << " \"" << this->comment << "\" Photos:";
for (auto& photo : photos) {
std::cout << " " << photo;
}
std::cout << std::endl;
}
std::ostream& operator<<(std::ostream& os, const Travel& travel) {
os << travel.destination << "|" << travel.from << "|" << travel.to
<< "|" << travel.grade << "|" << travel.comment << "|";
for (auto& photo : travel.photos) {
os << " " << photo;
}
os << "|";
return os;
}
std::istream& operator>>(std::istream& is, Travel& travel) {
std::string token;
std::istringstream stream;
std::getline(is, travel.destination, '|');
std::getline(is, token, '|');
stream.str(token);
stream >> travel.from;
stream.clear();
std::getline(is, token, '|');
stream.str(token);
stream >> travel.to;
stream.clear();
std::getline(is, token, '|');
stream.str(token);
stream >> travel.grade;
stream.clear();
std::getline(is, travel.comment, '|');
std::getline(is, token, '|');
stream.str(token);
std::string photo;
while(stream >> photo) {
travel.addPhoto(photo);
}
return is;
}
<file_sep>#ifndef COMMANDS_H
#define COMMANDS_H
#include <string>
#include "Warehouse.hpp"
class BaseCommand {
private:
std::string name;
public:
BaseCommand(std::string);
std::string getName() const;
virtual void execute() = 0;
};
class HelpCommand : public BaseCommand {
public:
HelpCommand();
void execute();
};
class ExitCommand : public BaseCommand {
public:
ExitCommand();
void execute();
};
class FileCommand : public BaseCommand {
private:
Warehouse& warehouse;
protected:
static std::string filename;
public:
FileCommand(std::string, Warehouse&);
Warehouse& getWarehouse() const;
virtual void execute() = 0;
};
class OpenCommand : public FileCommand {
public:
OpenCommand(Warehouse&);
void execute();
};
class CloseCommand : public FileCommand {
public:
CloseCommand(Warehouse&);
void execute();
};
class SaveCommand : public FileCommand {
public:
SaveCommand(Warehouse&);
void execute();
};
class SaveAsCommand : public FileCommand {
public:
SaveAsCommand(Warehouse&);
void execute();
};
class PrintCommand : public FileCommand {
public:
PrintCommand(Warehouse&);
void execute();
};
class AddCommand : public FileCommand {
public:
AddCommand(Warehouse&);
void execute();
};
class RemoveCommand : public FileCommand {
public:
RemoveCommand(Warehouse&);
void execute();
};
class LogCommand : public FileCommand {
public:
LogCommand(Warehouse&);
void execute();
};
class CleanCommand : public FileCommand {
public:
CleanCommand(Warehouse&);
void execute();
};
#endif
<file_sep>#include <iostream>
#include <sstream>
#include "Item.hpp"
Item::Item()
: name(""), expirationDate(), admissionDate(), manufacturerName(""), metric(kg), quantity(0), comment("") {};
Item::Item(std::string name, Date expirationDate, Date admissionDate, std::string manufacturerName, Metric metric, int quantity, std::string comment)
: name(name), expirationDate(expirationDate), admissionDate(admissionDate), manufacturerName(manufacturerName), metric(metric), quantity(quantity), comment(comment) {};
Item::Item(std::string name, Date expirationDate, Date admissionDate, std::string manufacturerName, Metric metric, int quantity)
: Item(name, expirationDate, admissionDate, manufacturerName, metric, quantity, "No comment") {};
Item::Item(std::string name, Date expirationDate, std::string manufacturerName, Metric metric, int quantity, std::string comment)
: Item(name, expirationDate, Date::getCurrentDate(), manufacturerName, metric, quantity, comment) {};
Item::Item(std::string name, Date expirationDate, std::string manufacturerName, Metric metric, int quantity)
: Item(name, expirationDate, Date::getCurrentDate(), manufacturerName, metric, quantity, "No comment") {};
std::string Item::getName() const {
return this->name;
}
Date Item::getExpirationDate() const {
return this->expirationDate;
}
Date Item::getAdmissionDate() const {
return this->admissionDate;
}
std::string Item::getManufacturerName() const {
return this->manufacturerName;
}
Metric Item::getMetric() const {
return this->metric;
}
int Item::getQuantity() const {
return this->quantity;
}
std::string Item::getComment() const {
return this->comment;
}
void Item::setName(std::string name) {
this->name = name;
}
void Item::setExpirationDate(Date expirationDate) {
this->expirationDate = expirationDate;
}
void Item::setAdmissionDate(Date admissionDate) {
this->admissionDate = admissionDate;
}
void Item::setManufacturerName(std::string manufacturerName) {
this->manufacturerName = manufacturerName;
}
void Item::setMetric(Metric metric) {
this->metric = metric;
}
void Item::setQuantity(int quantity) {
this->quantity = quantity;
}
void Item::setComment(std::string comment) {
this->comment = comment;
}
std::ostream& operator<<(std::ostream& os, const Item& item) {
os << item.name << " " << item.expirationDate << " " << item.admissionDate << " " << item.manufacturerName << " "
<< item.metric << " " << item.quantity << " " << item.comment;
return os;
}
std::istream& operator>>(std::istream& input, Item& item) {
input >> item.name >> item.expirationDate >> item.admissionDate >> item.manufacturerName
>> item.metric >> item.quantity >> item.comment;
return input;
}
std::istream& operator>>(std::istream& is, Metric& m) {
std::string tmp;
if (is >> tmp) {
if (tmp == "kg") {
m = kg;
} else if (tmp == "l") {
m = l;
} else {
throw "Invalid metric";
}
}
return is;
}
std::ostream& operator<<(std::ostream& os, const Metric& m) {
std::string tmp;
switch (m) {
case kg: tmp = "kg"; break;
case l: tmp = "l"; break;
default: tmp = "?";
}
return os << tmp;
}
void Item::print() {
std::cout << this->manufacturerName << " " << this->name << " " << this->quantity << this->metric;
std::cout << " Admissioned at: " << this->admissionDate << " Expires at: " << this->expirationDate << ". Comment: " << this->comment;
}
int Item::updateQuantity(int amount) {
this->quantity += amount;
return this->quantity;
}
<file_sep>#include <tuple>
#include <iostream>
#include <cassert>
#include <ctime>
#include "Date.hpp"
Date::Date() : year(1), month(1), day(1) {};
Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
if (year < 0) {
throw "Invalid date";
}
if (month < 0 || month > 12) {
throw "Invalid month";
}
int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (this->isLeap()) {
monthDays[1]++;
}
if (day < 0 || day > monthDays[month - 1]) {
throw "Invalid day";
}
}
bool Date::isLeap() {
return ((this->year % 4 == 0) && (this->year % 100 != 0)) || (this->year % 400 == 0);
}
Date Date::getCurrentDate() {
std::time_t t = std::time(0);
std::tm* now = std::localtime(&t);
return Date(now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
}
std::ostream& operator<<(std::ostream& os, const Date& date) {
os << date.year << '-' << date.month << '-' << date.day;
return os;
}
std::istream& operator>>(std::istream& input, Date& date) {
std::string token;
std::getline(input, token, '-');
date.year = std::stoi(token);
std::getline(input, token, '-');
date.month = std::stoi(token);
// std::getline(input, token, ' ');
// date.day = std::stoi(token);
input >> date.day;
return input;
}
bool operator== (Date const& lhs, Date const& rhs) {
return lhs.year == rhs.year
&& lhs.month == rhs.month
&& lhs.day == rhs.day;
}
bool operator!= (Date const& lhs, Date const& rhs) {
return ! (lhs == rhs);
}
bool operator> (Date const& lhs, Date const& rhs) {
return std::tie(lhs.year, lhs.month, lhs.day)
> std::tie(rhs.year, rhs.month, rhs.day);
}
bool operator< (Date const& lhs, Date const& rhs) {
return ( ! (lhs > rhs) ) && lhs != rhs;
}
bool operator>= (Date const& lhs, Date const& rhs) {
return lhs > rhs || lhs == rhs;
}
bool operator<= (Date const& lhs, Date const& rhs) {
return lhs < rhs || rhs == rhs;
}
<file_sep>#include <string>
#include <sstream>
#include <iostream>
#include "User.hpp"
#include "Travel.hpp"
User::User() :loggedIn(false) {}
User::User(std::string username, std::string passwordHash, std::string email)
: username(username), passwordHash(<PASSWORD>Hash), email(email) {}
std::string User::getUsername() const {
return this->username;
}
std::string User::getPasswordHash() const {
return this->passwordHash;
}
std::string User::getEmail() const {
return this->email;
}
bool User::getLoggedIn() const {
return this->loggedIn;
}
std::vector<std::string> User::getFriends() const {
return this->friends;
}
void User::setLoggedIn(bool loggedIn) {
this->loggedIn = loggedIn;
}
bool User::checkCredentials(std::string username, std::string passwordHash) {
return this->username == username && this->passwordHash == passwordHash;
}
void User::addFriend(std::string fr) {
this->friends.push_back(fr);
}
std::ostream& operator<<(std::ostream& os, const User& user) {
os << user.username << " " << user.passwordHash << " " << user.email;
for (auto& fr : user.friends) {
os << " " << fr;
}
return os;
}
std::istream& operator>>(std::istream& is, User& user) {
is >> user.username >> user.passwordHash >> user.email;
std::string friends, fr;
getline(is, friends);
std::istringstream stream;
stream.str(friends);
while (stream >> fr) {
user.addFriend(fr);
}
return is;
}<file_sep>#include <iostream>
#include <fstream>
#include <string>
#include "Commands.hpp"
#include "Warehouse.hpp"
std::string FileCommand::filename = "";
BaseCommand::BaseCommand(std::string name) : name(name) {};
FileCommand::FileCommand(std::string name, Warehouse& warehouse) : BaseCommand(name), warehouse(warehouse) {};
HelpCommand::HelpCommand() : BaseCommand("help") {};
ExitCommand::ExitCommand() : BaseCommand("exit") {};
OpenCommand::OpenCommand(Warehouse& warehouse) : FileCommand("open", warehouse) {};
CloseCommand::CloseCommand(Warehouse& warehouse) : FileCommand("close", warehouse) {};
SaveCommand::SaveCommand(Warehouse& warehouse) : FileCommand("save", warehouse) {};
SaveAsCommand::SaveAsCommand(Warehouse& warehouse) : FileCommand("saveas", warehouse) {};
PrintCommand::PrintCommand(Warehouse& warehouse) : FileCommand("print", warehouse) {};
AddCommand::AddCommand(Warehouse& warehouse) : FileCommand("add", warehouse) {};
RemoveCommand::RemoveCommand(Warehouse& warehouse) : FileCommand("remove", warehouse) {};
LogCommand::LogCommand(Warehouse& warehouse) : FileCommand("log", warehouse) {};
CleanCommand::CleanCommand(Warehouse& warehouse) : FileCommand("clean", warehouse) {};
std::string BaseCommand::getName() const {
return this->name;
}
Warehouse& FileCommand::getWarehouse() const {
return this->warehouse;
}
void HelpCommand::execute() {
std::cout << "The following commands are supported:" << std::endl;
std::cout << "open <file> opens <file>" << std::endl;
std::cout << "close closes currently opened file" << std::endl;
std::cout << "save saves the currently open file" << std::endl;
std::cout << "saveas <file> saves the currently open file in <file>" << std::endl;
std::cout << "help prints this information" << std::endl;
std::cout << "exit exists the program" << std::endl;
std::cout << "print prints warehouse information" << std::endl;
std::cout << "add <Item> adds item to warehouse. Checks for valid data" << std::endl;
std::cout << "remove removes item from warehouse by given anem and quantity" << std::endl;
std::cout << "log <from> <to> prints all operation between dates <from> and <to>" << std::endl;
std::cout << "clean removes all items whose expiration dates have passed" << std::endl;
}
void ExitCommand::execute() {
exit(0);
}
void OpenCommand::execute() {
if (FileCommand::filename == "") {
std::cin >> FileCommand::filename;
std::ifstream file(FileCommand::filename, std::ios::in);
this->getWarehouse().fromFile(file);
file.close();
} else {
throw "Currently there is an open file. Please close first";
}
}
void CloseCommand::execute() {
if (FileCommand::filename != "") {
std::ofstream file(FileCommand::filename, std::ios::out);
this->filename = "";
file.close();
} else {
throw "No file to close. Open first";
}
}
void SaveCommand::execute() {
if (FileCommand::filename != "") {
std::ofstream file(FileCommand::filename, std::ios::out);
this->getWarehouse().toFile(file);
file.close();
} else {
throw "No file opened. Open first";
}
}
void SaveAsCommand::execute() {
if (FileCommand::filename != "") {
std::string filename;
std::cout << "Enter filename: ";
std::cin >> filename;
std::ofstream file(filename, std::ios::out);
this->getWarehouse().toFile(file);
file.close();
} else {
throw "No file opened. Open first";
}
}
void PrintCommand::execute() {
this->getWarehouse().print();
}
void AddCommand::execute() {
if (FileCommand::filename != "") {
Item item;
std::cin >> item;
this->getWarehouse().addItem(item);
} else {
throw "No file opened. Open first";
}
}
void RemoveCommand::execute() {
if (FileCommand::filename != "") {
std::string name;
int quantity;
std::cout << "Enter name: ";
std::cin >> name;
std::cout << "Enter quantity: ";
std::cin >> quantity;
this->getWarehouse().removeItem(name, quantity);;
} else {
throw "No file opened. Open first";
}
}
void LogCommand::execute() {
if (FileCommand::filename != "") {
Date start, end;
std::cout << "Enter start date (YYYY-MM-DD): ";
std::cin >> start;
std::cout << "Enter end date (YYYY-MM-DD): ";
std::cin >> end;
this->getWarehouse().log(start, end);
} else {
throw "No file opened. Open first";
}
}
void CleanCommand::execute() {
this->getWarehouse().clean();
}
<file_sep>#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include "Date.hpp"
#include "Commands.hpp"
#include "User.hpp"
int main() {
User user;
DatabaseHelper dbh;
std::string command;
std::vector<BaseCommand*> commands;
commands.push_back(new HelpCommand());
commands.push_back(new ExitCommand());
commands.push_back(new RegisterCommand(user, dbh));
commands.push_back(new LoginCommand(user, dbh));
commands.push_back(new TravelCommand(user, dbh));
commands.push_back(new FriendCommand(user, dbh));
commands.push_back(new BrowseCommand(user, dbh));
commands.push_back(new ListCommand(user, dbh));
commands.push_back(new ListGradesCommand(user, dbh));
while (true) {
try {
std::cout << "Enter command: ";
std::cin >> command;
std::vector<BaseCommand*>::iterator pos = std::find_if(commands.begin(), commands.end(),
[&command](const BaseCommand* x) { return x->getName() == command; });
if (pos != commands.end()) {
(*pos)->execute();
} else {
std::cout << "Invalid command" << std::endl;
}
} catch (const char* err) {
std::cout << err << std::endl;
}
}
return 0;
}
//g++ main.cpp Commands.cpp Travel.cpp DatabaseHelper.cpp Date.cpp User.cpp
/*
Burgas, Bulgaria|2019-07-15|2019-07-29|5|A beautiful city on the Black Sea coast. I spent two unforgettable weeks there, meeting new people|burgas.jpeg locumfest.png sunrise_on_the_coast.jpeg|
*/
<file_sep>#include <fstream>
#include <sstream>
#include <iostream>
#include "DatabaseHelper.hpp"
#include "User.hpp"
std::string DatabaseHelper::dbName = "users.db";
DatabaseHelper::DatabaseHelper() {};
bool DatabaseHelper::userExists(std::string username) {
try {
this->getUser(username);
return true;
} catch (const char* err) {
return false;
}
}
User DatabaseHelper::getUser(std::string username) {
std::ifstream users(DatabaseHelper::dbName, std::ios::in);
User user;
std::string line;
while (getline(users, line)) {
std::istringstream stream;
stream.str(line);
stream >> user;
if (user.getUsername() == username) {
users.close();
return user;
}
}
users.close();
throw "User not found";
}
void DatabaseHelper::recordUser(const User& user) {
std::ofstream users(DatabaseHelper::dbName, std::ios::out|std::ios::app);
users << user << std::endl;
users.close();
}
void DatabaseHelper::recordTravel(const User& user, const Travel& travel) {
std::ofstream travels(user.getUsername() + ".db", std::ios::out|std::ios::app);
travels << travel << std::endl;
travels.close();
}
std::vector<Travel> DatabaseHelper::getTravels(std::string username) {
std::ifstream travelsFile(username + ".db", std::ios::in);
std::vector<Travel> travels;
std::string line;
Travel t;
while(std::getline(travelsFile, line)) {
std::istringstream stream;
stream.str(line);
stream >> t;
travels.push_back(t);
}
travelsFile.close();
return travels;
}
std::vector<User> DatabaseHelper::getUsers() {
std::ifstream usersFile(DatabaseHelper::dbName, std::ios::in);
std::vector<User> users;
std::string line;
User user;
while(std::getline(usersFile, line)) {
std::istringstream stream;
stream.str(line);
stream >> user;
users.push_back(user);
}
usersFile.close();
return users;
}
void DatabaseHelper::addFriend(const User& user, std::string fr) {
std::ifstream users(DatabaseHelper::dbName, std::ios::in);
std::vector<std::string> lines;
std::string line;
while(std::getline(users, line)) {
lines.push_back(line);
}
users.close();
std::ofstream updated(DatabaseHelper::dbName, std::ios::out);
for (auto& l : lines) {
std::string usr = l.substr(0, l.find(' '));
if (usr == user.getUsername()) {
l += (" " + fr);
}
updated << l << std::endl;
}
} | a3332df18fb0be30d1f31ac9f4aa22a18c7cb1e8 | [
"C++"
] | 18 | C++ | toniuyt123/oop_proekti | 4c073bfc32926113cfea60383bab8858e046d8f3 | 700fd7f094f3762b8feaf16829047500c2ef109d | |
refs/heads/master | <file_sep>import os, sys, time, torch, random, argparse
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
from copy import deepcopy
from pathlib import Path
lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve()
if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir))
from procedures import get_optim_scheduler
from config_utils import load_config
from datasets import get_datasets
from log_utils import Logger, AverageMeter, time_string, convert_secs2time
from functions import pure_evaluate, procedure
def get_op_list(n):
ops = []
while len(ops) < 6:
ops.insert(0, int(n % 10))
n /= 10
return ops
def getvalue(item, key):
return item[:-4].split('_')[item[:-4].split('_').index(key)+1]
def main(super_path, ckp_path, workers, datasets, xpaths, splits, use_less):
from config_utils import dict2config
from models import get_cell_based_tiny_net
logger = Logger(str(ckp_path), 0, False)
ckp = torch.load(super_path)
from collections import OrderedDict
state_dict = OrderedDict()
model_name = super_path.split('/')[2][:-8]
old_state_dict = ckp['shared_cnn'] if model_name == 'ENAS' else ckp['search_model']
for k, v in old_state_dict.items():
if 'module' in k:
name = k[7:] # remove `module.`
else:
name = k
state_dict[name] = v
model_config = dict2config({'name': model_name,
'C': 16,
'N': 5,
'max_nodes': 4,
'num_classes': 10,
'space': ['none', 'skip_connect', 'nor_conv_1x1', 'nor_conv_3x3', 'avg_pool_3x3'],
'affine': False,
'track_running_stats': True}, None)
supernet = get_cell_based_tiny_net(model_config)
# supernet.load_state_dict(ckp['search_model'])
supernet.load_state_dict(state_dict)
ckp_names = os.listdir(ckp_path)
from datetime import datetime
random.seed(datetime.now())
random.shuffle(ckp_names)
for ckp_name in ckp_names:
if not ckp_name.endswith('.tar'):
continue
if 'super' in ckp_name:
continue
if not os.path.exists(os.path.join(ckp_path, ckp_name)):
continue
arch = getvalue(ckp_name, 'arch')
op_list = get_op_list(int(arch))
net = supernet.extract_sub({
'1<-0': op_list[0],
'2<-0': op_list[1],
'2<-1': op_list[2],
'3<-0': op_list[3],
'3<-1': op_list[4],
'3<-2': op_list[5],
})
network = torch.nn.DataParallel(net).cuda()
valid_losses, valid_acc1s, valid_acc5s, valid_tms = evaluate_all_datasets(network, datasets, xpaths, splits, use_less, workers, logger)
try:
old_ckp = torch.load(os.path.join(ckp_path, ckp_name))
except:
print(ckp_name)
continue
for key in valid_losses:
old_ckp[key] = valid_losses[key]
for key in valid_acc1s:
old_ckp[key] = valid_acc1s[key]
for key in valid_acc5s:
old_ckp[key] = valid_acc5s[key]
for key in valid_tms:
old_ckp[key] = valid_tms[key]
old_ckp['super'] = network.module.state_dict()
cf10_super = valid_acc1s['cf10-otest-acc1']
new_ckp_name = ckp_name[:-4] + f'_cf10-super_f{cf10_super}' + '.tar'
torch.save(old_ckp, os.path.join(ckp_path, new_ckp_name))
os.remove(os.path.join(ckp_path, ckp_name))
def evaluate_all_datasets(network, datasets, xpaths, splits, use_less, workers, logger):
valid_losses, valid_acc1s, valid_acc5s, valid_tms = {}, {}, {}, {}
for dataset, xpath, split in zip(datasets, xpaths, splits):
# train valid data
train_data, valid_data, xshape, class_num = get_datasets(dataset, xpath, -1)
# load the configuration
if dataset == 'cifar10' or dataset == 'cifar100':
if use_less: config_path = 'configs/nas-benchmark/LESS.config'
else : config_path = 'configs/nas-benchmark/CIFAR.config'
split_info = load_config('configs/nas-benchmark/cifar-split.txt', None, None)
elif dataset.startswith('ImageNet16'):
if use_less: config_path = 'configs/nas-benchmark/LESS.config'
else : config_path = 'configs/nas-benchmark/ImageNet-16.config'
split_info = load_config('configs/nas-benchmark/{:}-split.txt'.format(dataset), None, None)
else:
raise ValueError('invalid dataset : {:}'.format(dataset))
config = load_config(config_path, \
{'class_num': class_num,
'xshape' : xshape}, \
logger)
# check whether use splited validation set
if bool(split):
assert dataset == 'cifar10'
ValLoaders = {'ori-test': torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, shuffle=False, num_workers=workers, pin_memory=True)}
assert len(train_data) == len(split_info.train) + len(split_info.valid), 'invalid length : {:} vs {:} + {:}'.format(len(train_data), len(split_info.train), len(split_info.valid))
train_data_v2 = deepcopy(train_data)
train_data_v2.transform = valid_data.transform
valid_data = train_data_v2
# data loader
train_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(split_info.train), num_workers=workers, pin_memory=True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(split_info.valid), num_workers=workers, pin_memory=True)
ValLoaders['x-valid'] = valid_loader
else:
# data loader
train_loader = torch.utils.data.DataLoader(train_data, batch_size=config.batch_size, shuffle=True, num_workers=workers, pin_memory=True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, shuffle=False, num_workers=workers, pin_memory=True)
if dataset == 'cifar10':
ValLoaders = {'ori-test': valid_loader}
elif dataset == 'cifar100':
cifar100_splits = load_config('configs/nas-benchmark/cifar100-test-split.txt', None, None)
ValLoaders = {'ori-test': valid_loader,
'x-valid' : torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(cifar100_splits.xvalid), num_workers=workers, pin_memory=True),
'x-test' : torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(cifar100_splits.xtest ), num_workers=workers, pin_memory=True)
}
elif dataset == 'ImageNet16-120':
imagenet16_splits = load_config('configs/nas-benchmark/imagenet-16-120-test-split.txt', None, None)
ValLoaders = {'ori-test': valid_loader,
'x-valid' : torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(imagenet16_splits.xvalid), num_workers=workers, pin_memory=True),
'x-test' : torch.utils.data.DataLoader(valid_data, batch_size=config.batch_size, sampler=torch.utils.data.sampler.SubsetRandomSampler(imagenet16_splits.xtest ), num_workers=workers, pin_memory=True)
}
else:
raise ValueError('invalid dataset : {:}'.format(dataset))
dataset_key = '{:}'.format(dataset)
if bool(split): dataset_key = dataset_key + '-valid'
logger.log('Evaluate ||||||| {:10s} ||||||| Train-Num={:}, Valid-Num={:}, Valid-Loader-Num={:}, batch size={:}'.format(dataset_key, len(train_data), len(valid_data), len(valid_loader), config.batch_size))
optimizer, scheduler, criterion = get_optim_scheduler(network.parameters(), config)
for epoch in range(config.epochs): # finetune 5 epochs
scheduler.update(epoch, 0.0)
procedure(train_loader, network, criterion, scheduler, optimizer, 'train')
short = {
'ImageNet16-120': 'img',
'cifar10': 'cf10',
'cifar100': 'cf100',
'ori-test': 'otest',
'x-valid': 'xval',
'x-test': 'xtest'
}
with torch.no_grad():
for key, xloder in ValLoaders.items():
valid_loss, valid_acc1, valid_acc5, valid_tm = pure_evaluate(xloder, network)
valid_losses[short[dataset]+'-'+short[key]+'-'+'loss'] = valid_loss
valid_acc1s[short[dataset]+'-'+short[key]+'-'+'acc1'] = valid_acc1
valid_acc5s[short[dataset]+'-'+short[key]+'-'+'acc5'] = valid_acc5
valid_tms[short[dataset]+'-'+short[key]+'-'+'tm'] = valid_tm
logger.log('Evaluate ---->>>> {:10s} top1: {:} top5: {:} loss: {:}'.format(key, valid_acc1, valid_acc5, valid_loss))
return valid_losses, valid_acc1s, valid_acc5s, valid_tms
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='NAS-Bench-201', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--arch_path', type=str, help='Path to load supernet')
parser.add_argument('--ckp_path', type=str, help='Folder to checkpoints.')
# use for train the model
parser.add_argument('--workers', type=int, default=8, help='number of data loading workers (default: 2)')
parser.add_argument('--datasets', type=str, nargs='+', help='The applied datasets.')
parser.add_argument('--xpaths', type=str, nargs='+', help='The root path for this dataset.')
parser.add_argument('--splits', type=int, nargs='+', help='The root path for this dataset.')
parser.add_argument('--use_less', type=int, default=1, choices=[0,1], help='Using the less-training-epoch config.')
parser.add_argument('--seed', type=int, default=0, help='Using the less-training-epoch config.')
args = parser.parse_args()
print(args.datasets)
main(args.arch_path, args.ckp_path, args.workers, args.datasets, args.xpaths, args.splits, args.use_less > 0)
<file_sep>#!/bin/bash
# bash ./scripts-search/train-models.sh 0/1 0 100 -1 '777 888 999'
echo script name: $0
if [ "$TORCH_HOME" = "" ]; then
echo "Must set TORCH_HOME envoriment variable for data dir saving"
exit 1
else
echo "TORCH_HOME : $TORCH_HOME"
fi
arch_path=$1
ckp_path=$2
OMP_NUM_THREADS=4 python ./exps/NAS-Bench-201/validate_super.py \
--arch_path ${arch_path} \
--ckp_path ${ckp_path} \
--datasets cifar10 \
--splits 1 0 0 0 \
--xpaths $TORCH_HOME/cifar.python \
--workers 8
| 28cdfbf8f849aa27a669ef7e74548366d3a7fba1 | [
"Python",
"Shell"
] | 2 | Python | liqi0126/AutoDL-Projects | 1d742f10da061fc6b1b8512737d9f723f4bf325e | be194b414751c3deade484a7e27edbc81c58bd25 | |
refs/heads/master | <file_sep>package com.sitevente.app.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sitevente.app.repositories.ShowsRepository;
import com.sitevente.app.store.Pages;
import com.sitevente.app.store.Shows;
@RestController
@RequestMapping("/pages")
@CrossOrigin(origins = "*")
public class PagesController {
@Autowired
private ShowsRepository pagesRepository;
public String testRequest(){
return "Page content";
}
@RequestMapping("/homepage")
public Pages getHomePageContent(){
List<Shows> featuredShows = pagesRepository.findByFeaturedTrue();
List<String> carousselImages = new ArrayList<>();
for(Shows show: featuredShows) {
carousselImages.add(show.getImageUrl());
}
Pages page = new Pages(carousselImages, featuredShows);
return page;
}
}
<file_sep>package com.sitevente.app.repositories;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.sitevente.app.store.Sessions;
public interface SessionsRepository extends MongoRepository<Sessions, String> {
public Sessions findBySessionId(String sessionId);
}
<file_sep>package com.sitevente.app.repositories;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.sitevente.app.store.Orders;
public interface OrdersRepository extends MongoRepository<Orders, String>{
public Orders findByConfirmationNumber(String confirmationNumber);
public Orders findBySessionId(String sessionId);
}
<file_sep>package config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
private final String GESTIONNAIRE_DE_SALLE = "gestionnairedesalle";
private final String USERS = "users";
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/pages/**");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("gestionnairedesalle").password("<PASSWORD>").roles(GESTIONNAIRE_DE_SALLE)
.and();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/gestionnaire/**").hasRole(GESTIONNAIRE_DE_SALLE)
.and()
.formLogin();
}
}
<file_sep>spring.data.mongodb.host=ds249818.mlab.com
spring.data.mongodb.port=49818
spring.data.mongodb.database=heroku_z6zwz4vq
spring.data.mongodb.username=labgtivente
spring.data.mongodb.password=<PASSWORD>
<file_sep>package com.sitevente.app.store;
import java.util.Date;
import org.springframework.data.annotation.Id;
public class Tickets {
@Id
private String id;
private double price;
private String artistName;
private String title;
private String salleId;
private Date timeAdded;
private String showDate;
private boolean reserved;
private String showId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSalleId() {
return salleId;
}
public void setSalleId(String salleId) {
this.salleId = salleId;
}
public Date getTimeAdded() {
return timeAdded;
}
public void setTimeAdded(Date timeAdded) {
this.timeAdded = timeAdded;
}
public String getShowDate() {
return showDate;
}
public void setShowDate(String showDate) {
this.showDate = showDate;
}
public boolean isReserved() {
return reserved;
}
public void setReserved(boolean reserved) {
this.reserved = reserved;
}
public String getShowId() {
return showId;
}
public void setShowId(String showId) {
this.showId = showId;
}
}
<file_sep><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.ventesbillets.app</groupId>
<artifactId>rest-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Site Ventes 1 api</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
</executions>
<configuration>
<release>1.8</release>
<verbose>true</verbose>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<version>2.0.3</version>
</plugin>
</plugins>
</build>
<properties>
<start-class>com.sitevente.app.VentesApiApp</start-class>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<start-class>org.springframework.boot.sample.tomcat.SampleTomcatApplication</start-class>
</properties>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
<file_sep>package com.sitevente.app.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.sitevente.app.repositories.ShowsRepository;
import com.sitevente.app.store.Shows;
import com.sitevente.app.store.ShowsTicketsInfo;
import com.sitevente.app.store.Tickets;
@RestController
@RequestMapping("/gestionnaire")
//Devra etre changer pour permettre seulement au gestionnaire de salle d'utiliser ce controlleur
@CrossOrigin(origins = "*")
public class GestionnaireDeSalleController {
@Autowired
private ShowsRepository showsRepository;
/**
* Trouver les informations concernant tous les billets
* @return
*/
@RequestMapping("/shows")
public List<ShowsTicketsInfo> getShowsTicketsInfo(){
List<ShowsTicketsInfo> showsInfoList = new ArrayList<>();
for(Shows show: showsRepository.findAll()){
ShowsTicketsInfo showTicketsInfo = new ShowsTicketsInfo();
showTicketsInfo.setArtistName(show.getArtistName());
showTicketsInfo.setShowId(show.getId());
showTicketsInfo.setShowTitle(show.getTitle());
showTicketsInfo.setTicketsAvailable(show.getQtyAvailable());
showTicketsInfo.setTicketsSold(show.getQtySold());
showsInfoList.add(showTicketsInfo);
}
return showsInfoList;
}
/**
* Trouver les informations concernant un seul billet
* @param id
* @return
*/
@RequestMapping(value="/shows/{id}")
public Shows getSingleShowTicketsInfo(@PathVariable String id){
Shows show = showsRepository.findById(id).get();
return show;
}
@RequestMapping(method=RequestMethod.POST, value="/shows")
public void addShow(@RequestBody List<Shows>showsList){
for(Shows show: showsList){
show.setQtyAvailable();
}
showsRepository.saveAll(showsList);
}
@RequestMapping(method=RequestMethod.DELETE, value="/shows/{id}")
public String deleteShow(@PathVariable String id){
if(showsRepository.findById(id).isPresent()){
showsRepository.deleteById(id);
return "Spectacle suprime";
}else{
return "Le spectacle n'a pas ete trouve";
}
}
@RequestMapping(method=RequestMethod.PATCH, value="/shows/{id}")
public String editShow(@PathVariable String id, @RequestBody Shows show){
if(showsRepository.findById(id).isPresent()){
showsRepository.save(show);
return "Le spectacle a ete mis a jour";
}else{
return "Le spectacle n'a pas pu etre trouve";
}
}
@RequestMapping(value = "/shows/{id}/_terminate", method = RequestMethod.POST)
public Shows terminateTicketSale(@PathVariable String id){
if(showsRepository.findById(id).isPresent()){
showsRepository.findById(id).get().setSaleDone(true);
return showsRepository.findById(id).get();
}else{
return null;
}
}
@RequestMapping(value = "/addTickets/{showId}", method = RequestMethod.PATCH)
public String addTickets(@PathVariable String id, @RequestBody List<Tickets> ticketsList){
if(showsRepository.findById(id).isPresent()){
Shows show = showsRepository.findById(id).get();
show.addTickets(ticketsList);
showsRepository.save(show);
return "Les billets ont ete ajoutes";
}
return "Le spectacle n'a pas ete trouver";
}
}
<file_sep>package com.sitevente.app.store;
public class PaymentForm {
private String firstName;
private String lastName;
private String email;
private String address;
private String address2;
private String country;
private String region;
private String postalCode;
//Ajouter Un Objet de paiement
private String sessionId;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
<file_sep># e18-vente1-backend | 8fc65f6767222f7fc1128a8864ad97a4208dd6fd | [
"Markdown",
"Java",
"Maven POM",
"INI"
] | 10 | Java | gti525/e18-vente1-backend | 9cdbb9848e03a98a0b99279ccdb3b3942da3d8c0 | 8d2e41c168613995cf84b403e17f4f0d4d2fe3a0 | |
refs/heads/master | <repo_name>RobertPecz/PatientRegistry<file_sep>/UserInput.py
import re
from datetime import *
class UserInput:
"""Patient registry input by the user"""
def __init__(self):
self.FirstName = None
self.LastName = None
self.Dob = None
self.Phone_number = None
self.AppointmentDate = None
self.AppointmentTime = None
self.MotherMaidenName = None
def safe_cast(self,val,to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
def adding_new_patient(self):
# Adding a new customer
# Adding the first name
print("Please provide the following data's: First name, Last name, Age, Phone number, Appointment date")
is_match = None
while is_match is None:
self.FirstName=input("First name:")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][a-z]{0,}|[ ][A-Z][.]|[.][ ][A-Z][a-z]{0,}|)|NOTVALID)$", self.FirstName)
if is_match is None:
print("Please provide the first name in correct format (eg.:'Smith' or 'Smith-Black' or 'Smith Black')")
# Adding the last name
is_match = None
while is_match is None:
self.LastName=input("Last Name:")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([.][ ][A-Z][a-z]{0,}[.][ ][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}[.][ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}[.]|[.][ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}|[-][A-Z][a-z]{0,})|[A-Z][a-z]{0,})$", self.LastName)
if is_match is None:
print("Please provide the first name in correct format (eg.:'John' or 'J.' or '<NAME>')")
# Adding the Date of birth
is_match = None
while is_match is None:
self.Dob = input("Date of Birth (correct format: 1900-01-01):")
is_match = re.fullmatch(r"^[1-2][0-9]{3}[-][0-1][0-9]{1}[-][0-9]{2}$", self.Dob)
try:
dob_date = datetime.strptime(self.Dob, '%Y-%m-%d')
except ValueError:
print("Please provide a valid date between 01-01 and 12-31.")
continue
if dob_date < datetime(year=1900, month=1, day=1) or dob_date >= datetime.now():
is_match = None
print("Please provide the date at least today")
if is_match is None:
print("Please provide a correct date format (1900-01-01).")
# Adding the mother maiden name
is_match = None
while is_match is None:
self.MotherMaidenName = input("Mother Maiden name (correct format: Sue Doe or Sue Doe-Black or Sue Doe Black or Sue D. Black.):")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][a-z]{0,}|[ ][A-Z][.][ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][.])|NOTVALID)$", self.MotherMaidenName)
if is_match is None:
print("Please provide the mother maiden name in a correct form eg.: <NAME> or <NAME>-Black or <NAME> or <NAME>")
# Adding the phone number
is_match = None
while is_match is None:
self.Phone_number = input("Phone number(correct format: +36-00-000-0000):")
is_match = re.fullmatch(r"^[+][3][6][-][0-9]{2}[-][0-9]{3}[-][0-9]{4}$", self.Phone_number)
if is_match is None:
print("Please provide a correct phone number format (+36-00-000-0000).")
# Adding the appointment date and time
is_match = None
while is_match is None:
self.AppointmentDate = input("Appointment Date (correct format: 1900-01-01):")
is_match = re.fullmatch(r"^[2][0-9]{3}[-][0-1][0-9]{1}[-][0-9]{2}$", self.AppointmentDate)
try:
self.AppointmentDate = datetime.strptime(self.AppointmentDate, '%Y-%m-%d')
except ValueError:
print("Please provide a valid date between 01-01 and 12-31.")
continue
if self.AppointmentDate < datetime.now() - timedelta(days=1):
is_match = None
print("Please provide the date at least today")
if is_match is None:
print("Please provide a correct date format (1900-01-01).")
self.AppointmentTime = input("Appointment time (correct format: 00:00):")
is_match = re.fullmatch(r"^[0-9]{2}[:][0-9]{2}$", self.AppointmentTime)
start_time = time(hour=8, minute=0)
end_time = time(hour=16, minute=0)
try:
self.AppointmentTime = datetime.strptime(self.AppointmentTime, '%H:%M').time()
self.AppointmentDate = datetime.combine(self.AppointmentDate, self.AppointmentTime)
except ValueError:
print("Please provide a valid time between 08:00 and 16:00")
is_match = None
continue
if self.AppointmentTime < start_time or self.AppointmentTime > end_time:
is_match = None
print("Please provide a valid time between 08:00 and 16:00")
if is_match is None:
print("Please provide a correct time format (08:00).")
def change_first_name(self):
# Changing the first name
print("Please provide first name.")
is_match = None
while is_match is None:
self.FirstName = input("First name:")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][a-z]{0,}|[ ][A-Z][.]|[.][ ][A-Z][a-z]{0,}|)|NOTVALID)$", self.FirstName)
if is_match is None:
print("Please provide the first name in correct format (eg.:'Smith' or 'Smith-Black' or 'Smith Black')")
return self.FirstName
def change_last_name(self):
# Changing the last name
print("Please provide last name.")
is_match = None
while is_match is None:
self.LastName = input("Last Name:")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([.][ ][A-Z][a-z]{0,}[.][ ][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}[.][ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}[.]|[.][ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[.][ ][A-Z][a-z]{0,}|[-][A-Z][a-z]{0,})|[A-Z][a-z]{0,})$", self.LastName)
if is_match is None:
print("Please provide the first name in correct format (eg.:'John' or 'J.' or '<NAME>')")
return self.LastName
def change_dob(self):
# Changing the Date of birth
print("Provide the date of birth.")
is_match = None
while is_match is None:
self.Dob = input("Date of Birth (correct format: 1900-01-01):")
is_match = re.fullmatch(r"^[1-2][0-9]{3}[-][0-1][0-9]{1}[-][0-9]{2}$", self.Dob)
try:
dob_date = datetime.strptime(self.Dob, '%Y-%m-%d')
except ValueError:
print("Please provide a valid date between 01-01 and 12-31.")
continue
if dob_date < datetime(year=1900,month=1,day=1) or dob_date >= datetime.now():
is_match = None
print("Please provide the date at least today")
if is_match is None:
print("Please provide a correct date format (1900-01-01).")
return self.Dob
def change_mother_maiden_name(self):
# Changing mother maiden name.
print("Provide mother maiden name.")
is_match = None
while is_match is None:
self.MotherMaidenName = input("Mother Maiden name (correct format: Sue Doe or Sue Doe-Black or Sue Doe Black or Sue D. Black.):")
is_match = re.fullmatch(r"^([A-Z][a-z]{0,})?(?(1)([ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[-][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][a-z]{0,}|[ ][A-Z][.][ ][A-Z][a-z]{0,}|[ ][A-Z][a-z]{0,}[ ][A-Z][.])|NOTVALID)$", self.MotherMaidenName)
if is_match is None:
print("Please provide the mother maiden name in a correct form eg.: <NAME> or <NAME>-Black or <NAME> or <NAME>")
return self.MotherMaidenName
def change_phonenumber(self):
# Changing phone number.
print("Provide phone number.")
is_match = None
while is_match is None:
self.Phone_number = input("Phone number(correct format: +36-00-000-0000):")
is_match = re.fullmatch(r"^[+][3][6][-][0-9]{2}[-][0-9]{3}[-][0-9]{4}$", self.Phone_number)
if is_match is None:
print("Please provide a correct phone number format (+36-00-000-0000).")
return self.Phone_number
def change_appointment_date(self):
# Change appointment date and time
is_match = None
while is_match is None:
self.AppointmentDate = input("Appointment Date (correct format: 1900-01-01):")
is_match = re.fullmatch(r"^[2][0-9]{3}[-][0-1][0-9]{1}[-][0-9]{2}$", self.AppointmentDate)
try:
self.AppointmentDate = datetime.strptime(self.AppointmentDate, '%Y-%m-%d')
except ValueError:
print("Please provide a valid date between 01-01 and 12-31.")
continue
if self.AppointmentDate < datetime.now() - timedelta(days=1):
is_match = None
print("Please provide the date at least today")
if is_match is None:
print("Please provide a correct date format (1900-01-01).")
self.AppointmentTime = input("Appointment time (correct format: 00:00):")
is_match = re.fullmatch(r"^[0-9]{2}[:][0-9]{2}$", self.AppointmentTime)
start_time = time(hour=8, minute=0)
end_time = time(hour=16, minute=0)
try:
self.AppointmentTime = datetime.strptime(self.AppointmentTime, '%H:%M').time()
self.AppointmentDate = datetime.combine(self.AppointmentDate, self.AppointmentTime)
except ValueError:
print("Please provide a valid time between 08:00 and 16:00")
is_match = None
continue
if self.AppointmentTime < start_time or self.AppointmentTime > end_time:
is_match = None
print("Please provide a valid time between 08:00 and 16:00")
if is_match is None:
print("Please provide a correct time format (08:00).")
return self.AppointmentDate
<file_sep>/PatientModify.py
from SearchCustomer import *
from UserInput import *
from DatabaseConnection import *
class PatientModding:
"""Modifying a Patient include add, modify appoint date, delete appointment"""
def __init__(self):
self.firstName = None
self.lastName = None
self.dateOfBirth = None
self.phoneNumber = None
self.motherMaidenName = None
self.appointmentDate = None
self.pastAppointments = None
self.pastIsAppear = None
# Adding data to the class
def upload_all_data(self,first_name, last_name, date_of_birth, mother_maiden_name, phone_number, appointment_date, past_is_appear):
self.firstName = first_name
self.lastName = last_name
self.dateOfBirth = date_of_birth
self.motherMaidenName = mother_maiden_name
self.phoneNumber = phone_number
self.appointmentDate = appointment_date
self.pastAppointments = appointment_date
self.pastIsAppear = past_is_appear
def adding_customer(self):
# Upload a customer to the tables
# Connect to the database
cnxn, cursor = ConnectingToDatabase.connect_database(self)
# Select the last PK ID from Patient table and +1 to it.
id_last_number_query_patient = "SELECT TOP 1 ID FROM Patient ORDER BY ID Desc;"
cursor.execute(id_last_number_query_patient)
row = cursor.fetchone()
id_number_patient = row[0]+1
# Select the last PK ID from PastAppointments table and +1 to is
id_last_number_query_patient = "SELECT TOP 1 ID FROM PastAppointments ORDER BY ID Desc;"
cursor.execute(id_last_number_query_patient)
row = cursor.fetchone()
id_number_pastappointments = row[0]+1
# Input the customer data and validate that the patient is not in the table
search_customer_duplicate_checker = SearchingCustomer()
is_customer_in_table = search_customer_duplicate_checker.search_customer_duplicate_checker()
# Adding user data to this class variables
self.upload_all_data(search_customer_duplicate_checker.firstName,
search_customer_duplicate_checker.lastName,
search_customer_duplicate_checker.dateOfBirth,
search_customer_duplicate_checker.motherMaidenName,
search_customer_duplicate_checker.phoneNumber,
search_customer_duplicate_checker.appointmentDate,
"No")
# If the customer not find in the table inserting to the patient table
if is_customer_in_table is None:
# Insert Patient data's into the Patient table
query_insert = "INSERT INTO Patient(ID, FirstName, LastName, DateOfBirth, MotherMaidenName, PhoneNumber, AppointmentDate) VALUES(?,?,?,?,?,?,?);"
cursor.execute(query_insert, id_number_patient, self.firstName, self.lastName, self.dateOfBirth, self.motherMaidenName, self.phoneNumber, self.appointmentDate)
cnxn.commit()
# Select PK ID Where the firstname and lastname which is passed as variable
id_current_query = "SELECT ID FROM Patient WHERE FirstName=? and LastName=?;"
cursor.execute(id_current_query, self.firstName, self.lastName)
row = cursor.fetchone()
id_current_query = row[0]
# Insert the past appointments to the PastAppointments table set the Isappear column default to No.
query_insert = "INSERT INTO PastAppointments(ID, PatientID, PastAppTime, IsAppear) VALUES(?,?,?,?);"
cursor.execute(query_insert, id_number_pastappointments, id_current_query, self.pastAppointments, self.pastIsAppear)
cnxn.commit()
# If the customer is in the table a message shown that the patient is registered
else:
print("Patient is already registered.")
def modifying_first_name(self):
# Change the first name and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_first_name = UserInput()
change_name = change_first_name.change_first_name()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_first_name = "UPDATE Patient SET FirstName=? WHERE ID=?;"
cursor.execute(query_mod_first_name,change_name,customer)
cnxn.commit()
def modifying_last_name(self):
# Change the last name and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_last_name = UserInput()
change_name = change_last_name.change_last_name()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_last_name = "UPDATE Patient SET LastName=? WHERE ID=?;"
cursor.execute(query_mod_last_name,change_name, customer)
cnxn.commit()
def modifying_phone_number(self):
# Change the phone number and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_phone_number = UserInput()
change_pnumber = change_phone_number.change_phonenumber()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_phone_number = "UPDATE Patient SET PhoneNumber=? WHERE ID=?;"
cursor.execute(query_mod_phone_number, change_pnumber, customer)
cnxn.commit()
def modifying_dob(self):
# Change the date of birth and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_date_of_birth = UserInput()
change_dob = change_date_of_birth.change_dob()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_dob = "UPDATE Patient SET DateOfBirth=? WHERE ID=?;"
cursor.execute(query_mod_dob, change_dob, customer)
cnxn.commit()
def modifying_mother_maiden_name(self):
# Change mother maiden name and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_mother_maiden_name = UserInput()
change_mothername = change_mother_maiden_name.change_mother_maiden_name()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_mother_maiden_name = "UPDATE Patient SET MotherMaidenName=? WHERE ID=?;"
cursor.execute(query_mod_mother_maiden_name, change_mothername, customer)
cnxn.commit()
def modifying_appointment_date(self):
# Change appointment date and update in the table
search = SearchingCustomer()
customer = search.search_customer()
if customer is not None:
change_appointment_date = UserInput()
change_appointmentdate = change_appointment_date.change_appointment_date()
cnxn, cursor = ConnectingToDatabase.connect_database(self)
query_mod_appointment_date = "UPDATE Patient SET AppointmentDate=? WHERE ID=?;"
cursor.execute(query_mod_appointment_date, change_appointmentdate, customer)
cnxn.commit()
<file_sep>/DatabaseConnection.py
import pyodbc
class ConnectingToDatabase:
# Connecting to a database
def connect_database(self):
# Connect to the database
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=.\SQLEXPRESS;"
"Database=PatientRegistry;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
return cnxn, cursor
<file_sep>/SearchCustomer.py
from DatabaseConnection import *
from UserInput import *
class SearchingCustomer:
def __init__(self):
self.firstName = None
self.lastName = None
self.dateOfBirth = None
self.motherMaidenName = None
self.phoneNumber = None
self.appointmentDate = None
self.pastAppDate = None
def upload_for_searching(self, first_name, last_name, date_of_birth, mother_maiden_name, phone_number, appointment_date):
self.firstName = first_name
self.lastName = last_name
self.dateOfBirth = date_of_birth
self.motherMaidenName = mother_maiden_name
self.phoneNumber = phone_number
self.appointmentDate = appointment_date
self.pastAppDate = appointment_date
def search_customer(self):
# Searching customer by first name + last name + mother maiden name + dob return PK ID
# Connect to the database
cnxn, cursor = ConnectingToDatabase.connect_database(self)
# Searching the patient giving back patient not found if there are no records in the table
userin = UserInput()
userin.change_first_name()
userin.change_last_name()
userin.change_dob()
userin.change_mother_maiden_name()
self.upload_for_searching(userin.FirstName,
userin.LastName,
userin.Dob,
userin.MotherMaidenName)
# Querying the result in the patient table
query_search = "SELECT ID FROM Patient WHERE FirstName=? and LastName=? and DateOfBirth=? and MotherMaidenName=?;"
cursor.execute(query_search, self.firstName, self.lastName, self.dateOfBirth, self.motherMaidenName)
row = cursor.fetchone()
try:
id_current_query = row[0]
return id_current_query
except:
return None
def search_customer_duplicate_checker(self):
# Check the new customer if it's already in the table, preventing from upload
# Connect to the database
cnxn, cursor = ConnectingToDatabase.connect_database(self)
userin = UserInput()
userin.adding_new_patient()
self.upload_for_searching(userin.FirstName,
userin.LastName,
userin.Dob,
userin.MotherMaidenName,
userin.Phone_number,
userin.AppointmentDate,
)
# Querying the result in the patient table
query_search = "SELECT ID FROM Patient WHERE FirstName=? and LastName=? and DateOfBirth=? and MotherMaidenName=?;"
cursor.execute(query_search, self.firstName, self.lastName, self.dateOfBirth, self.motherMaidenName)
row = cursor.fetchone()
try:
id_current_query = row[0]
return id_current_query
except:
return None
<file_sep>/main.py
from PatientModify import *
#adding a customer from userinputs input
adding_new_customer = PatientModding()
adding_new_customer.adding_customer()
<file_sep>/Readme.md
Python 3 project for a Patient registry software
###
For new features please read [New features list](https://github.com/RobertPecz/PatientRegistry/projects/1?add_cards_query=is%3Aopen). If you choose to make a new feature, open an issue for it.
| a81bfd3e18d40e341ea052041de38066f38ca93a | [
"Markdown",
"Python"
] | 6 | Python | RobertPecz/PatientRegistry | 0af2255cdb7c6827570b9318779b6496c738ee2a | b5cc3b2542b8167331c807f589dfad5c74c1e4dd | |
refs/heads/master | <repo_name>andrewasheridan/hera_sandbox<file_sep>/aas/Estimating Delays/nn/data_creation/Data_Creator_C.py
"""Summary
"""
# Data_Creator_C
from data_manipulation import *
from Data_Creator import Data_Creator
import numpy as np
class Data_Creator_C(Data_Creator):
"""Data_Creator_C C = Classification
Creates one dimensional inputs and their labels for training
Inputs are simulated angle data generated with true data as their base
- see ????.ipynb for discussion of input data
Labels are one-hot vectors (optionally blurred vectors)
- see ????.ipynb for discussion of labels and blurring
Each input is generated:
- a pair of redundant baselines is randomly chosen
- the ratio of visibilties is constructed (a complex flatness, see discussion)
- a separate target cable delay is applied to each row of the flatness
- targets in the range (-abs_min_max_delay, abs_min_max_delay)
- the angle is computed of the flatness with the applied delay
Each label is generated:
- the smooth range of targets is converted to a series of steps of the desired precision
- see Classifier_Class_Explanation.ipynb for discussion
- each unique step value is assigned a one-hot vector (from min to max)
- each target is assigned its label target
- if blur != 0 blur is applied
- Imagine each one-hot vector as a delta function with area = 1
- blur converts the delta function into a gaussian with area = 1
- see ????.ipynb for discussion
Args:
num_flatnesses (int): number of flatnesses used to generate data.
Number of data samples = 60 * num_flatnesses
bl_data (dict): data source. Output of get_seps_data()
bl_dict (dict): Dictionary of seps with bls as keys. An output of get_or_gen_test_train_red_bls_dicts()
gains (dict): Gains for this data. An output of load_relevant_data()
abs_min_max_delay (float, optional): targets are generated in range(-abs_min_max_delay, abs_min_max_delay)
precision (float, optional): size of the class steps must be from (0.005,0.001,0.0005,0.00025,0.0001)
evaluation (bool, optional): experimental
single_dataset (bool, optional): experimental
singleset_path (None, optional): experimental
blur (float, optional): blur value. Convert a one-hot vector delta function to a gaussian.
Spreads the 1.0 prob of a class over a range of nearby classes.
blur = 0.5 spreads over about 7 classes with a peak prob of 0.5 (varies)
blue = 0.1 spreads over about 40 classes with peak prob ~ 0.06 (varies)
blur = 0.0, no blur
Attributes:
blur (float): Description
evaluation (bool): experimental
precision (float): Description
single_dataset (bool): experimental
singleset_path (bool): experimental
"""
__doc__ += Data_Creator.__doc__
def __init__(self,
num_flatnesses,
bl_data,
bl_dict ,
gains,
abs_min_max_delay = 0.040,
precision = 0.00025,
evaluation = False,
single_dataset = False,
singleset_path = None,
blur = 0.): # try 1, 0.5, 0.10
"""Summary
Args:
num_flatnesses (int): number of flatnesses used to generate data.
Number of data samples = 60 * num_flatnesses
bl_data (dict): data source. Output of get_seps_data()
bl_dict (dict): Dictionary of seps with bls as keys. An output of get_or_gen_test_train_red_bls_dicts()
gains (dict): Gains for this data. An output of load_relevant_data()
abs_min_max_delay (float, optional): targets are generated in range(-abs_min_max_delay, abs_min_max_delay)
precision (float, optional): size of the class steps must be from (0.005,0.001,0.0005,0.00025,0.0001)
evaluation (bool, optional): experimental
single_dataset (bool, optional): experimental
singleset_path (None, optional): experimental
blur (float, optional): blur value. Convert a one-hot vector delta function to a gaussian.
Spreads the 1.0 prob of a class over a range of nearby classes.
blur = 0.5 spreads over about 7 classes with a peak prob of 0.5 (varies)
blue = 0.1 spreads over about 40 classes with peak prob ~ 0.06 (varies)
blur = 0.0, no blur
"""
Data_Creator.__init__(self,
num_flatnesses = num_flatnesses,
bl_data = bl_data,
bl_dict = bl_dict,
gains = gains,
abs_min_max_delay = abs_min_max_delay)
self.precision = precision
self.evaluation = evaluation
self.single_dataset = single_dataset
self.singleset_path = singleset_path
self.blur = blur
def _load_singleset(self):
"""_load_singleset
load a set of specific baseline-pairs
"""
def loadnpz(filename):
"""loadnpz
Args:
filename (str): path
Returns:
numpy array: loaded npz
"""
a = np.load(filename)
d = dict(zip(("data1{}".format(k) for k in a), (a[k] for k in a)))
return d['data1arr_0']
return [[(s[0][0],s[0][1]), (s[1][0],s[1][1])] for s in loadnpz(self.singleset_path)]
def _blur(self, labels):
"""_blur
Convert a one-hot vector delta function to a gaussian.
Spreads the 1.0 prob of a class over a range of nearby classes.
blur = 0.5 spreads over about 7 classes with a peak prob of 0.5
blur = 0.1 spreads over about 40 classes with peak prob ~ 0.06
Args:
labels (list of lists of ints): class labels
Returns:
list of lists of floats: class labels, blurred
"""
for i, label in enumerate(labels):
true_val = np.argmax(label)
mean = true_val; std = self.blur; variance = std**2
x = np.arange(len(label))
f = np.exp(-np.square(x-mean)/2*variance)
labels[i] = f/np.sum(f)
return labels
def _gen_data(self):
"""_gen_data
Generates artiicial flatnesses by combining two redundant visbilites and their gains.
Applies different known delay to each row of the floatnesses.
Scales data for network.
Converts numerical delay valyue to classification label
"""
# scaling tools
# the NN likes data in the range (0,1)
angle_tx = lambda x: (np.asarray(x) + np.pi) / (2. * np.pi)
angle_itx = lambda x: np.asarray(x) * 2. * np.pi - np.pi
delay_tx = lambda x: (np.array(x) + self._tau) / (2. * self._tau)
delay_itx = lambda x: np.array(x) * 2. * self._tau - self._tau
targets = np.random.uniform(low = -self._tau, high = self._tau, size = (self._num * 60, 1))
applied_delay = np.exp(-2j * np.pi * (targets * self._nu + np.random.uniform()))
assert type(self._bl_data) != None, "Provide visibility data"
assert type(self._bl_dict) != None, "Provide dict of baselines"
assert type(self._gains) != None, "Provide antenna gains"
if self._bl_data_c == None:
self._bl_data_c = {key : self._bl_data[key].conjugate() for key in self._bl_data.keys()}
if self._gains_c == None:
self._gains_c = {key : self._gains[key].conjugate() for key in self._gains.keys()}
def _flatness(seps):
"""_flatness
Create a flatness from a given pair of seperations, their data & their gains.
Args:
seps (list of tuples of ints): two redundant separations
Returns:
numpy array of complex floats: visibility ratio flatnesss
"""
a, b = seps[0][0], seps[0][1]
c, d = seps[1][0], seps[1][1]
return self._bl_data[seps[0]] * self._gains_c[(a,'x')] * self._gains[(b,'x')] * \
self._bl_data_c[seps[1]] * self._gains[(c,'x')] * self._gains_c[(d,'x')]
inputs = []
seps = []
singleset_seps = None if self.singleset_path == None else self._load_singleset()
for i in range(self._num):
unique_baseline = random.sample(self._bl_dict.keys(), 1)[0]
if self.singleset_path == None:
two_seps = [random.sample(self._bl_dict[unique_baseline], 2)][0]
elif self.singleset_path != None:
two_seps = singleset_seps[i]
inputs.append(_flatness(two_seps))
for t in range(60):
seps.append(two_seps)
inputs = np.angle(np.array(inputs).reshape(-1,1024) * applied_delay)
permutation_index = np.random.permutation(np.arange(self._num * 60))
# TODO: Quadruple check that rounded_targets is doing what you think it is doing
# rounded_targets is supposed to take the true targets and round their value
# to the value closest to the desired precision. and the absolute.
# pretty sure i have it working for the values below
# classes is supposed to have all the possible unique rounded values
#0.0001 precision - 401 classes
if self.precision == 0.0001:
rounded_targets = np.asarray([np.round(abs(np.round(d * 100,2)/100), 5) for d in targets[permutation_index]]).reshape(-1)
classes = np.arange(0,0.04 + self.precision, self.precision)
#0.00025 precision - 161 classes
if self.precision == 0.00025:
rounded_targets = np.asarray([np.round(abs(np.round(d * 40,2)/40), 5) for d in targets[permutation_index]]).reshape(-1)
classes = np.arange(0,0.04 + self.precision, self.precision)
# 0.0005 precision 81 classes
if self.precision == 0.0005:
rounded_targets = np.asarray([np.round(abs(np.round(d * 20,2)/20), 5) for d in targets[permutation_index]]).reshape(-1)
classes = np.arange(0,0.04 + self.precision, self.precision)
# 0.001 precision - 41 classes
if self.precision == 0.001:
rounded_targets = np.asarray([np.round(abs(np.round(d * 10,2)/10), 5) for d in targets[permutation_index]]).reshape(-1)
classes = np.arange(0,0.04 + self.precision, self.precision)
# for 0.005 precision there should be 9 different classes
if self.precision == 0.005:
rounded_targets = np.asarray([np.round(abs(np.round(d * 2,2)/2), 5) for d in targets[permutation_index]]).reshape(-1)
classes = np.arange(0,0.04 + self.precision, self.precision)
eye = np.eye(len(classes), dtype = int)
classes_labels = {}
for i, key in enumerate(classes):
classes_labels[np.round(key,5)] = eye[i].tolist()
labels = [classes_labels[x] for x in rounded_targets]
labels = labels if self.blur == 0 else self._blur(labels)
if self.evaluation == True:
self._epoch_batch.append((angle_tx(inputs[permutation_index]), labels, targets[permutation_index], np.asarray(seps)[permutation_index]))
if self.single_dataset == True:
self._epoch_batch.append((angle_tx(inputs[permutation_index]), labels, np.asarray(seps)[permutation_index]))
else:
self._epoch_batch.append((angle_tx(inputs[permutation_index]), labels))
<file_sep>/aas/Estimating Delays/nn/network_trainers/CNN_C_Trainer.py
"""Summary
"""
# CNN_C_Trainer
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../modules'))
from NN_Trainer import NN_Trainer
import tensorflow as tf
from tensorflow.python.client import timeline
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import io
import itertools
np.seterr(divide='ignore', invalid='ignore') # for cm div/zero (handled)
class CNN_C_Trainer(NN_Trainer):
"""CNN_C_Trainer
- for training classifcation networks
- see ????.ipynb for discussion
Args:
- sample_keep_prob - Probability of keeping a value from an input row
- conv_keep_prob - Probability of keeping an output value from a convolution
- num_classes - int - Number of classification classes
- make sure this matches the value from the network
- why isnt this number just loaded from the network...
- single_dataset - bool - train on a single fixed dataset
"""
__doc__ += NN_Trainer.__doc__
def __init__(self,
network,
Data_Creator, # Class
num_classes,
num_epochs = 100,
batch_size = 32,
log_dir = '../logs/',
model_save_interval = 25,
pretrained_model_path = None,
metric_names = ['costs', 'accuracies'],
sample_keep_prob = 0.80,
conv_keep_prob = 0.9,
verbose = True,
single_dataset = False):
"""__init__"""
NN_Trainer.__init__(self,
network = network,
Data_Creator = Data_Creator,
num_epochs = num_epochs,
batch_size = batch_size,
log_dir = log_dir,
model_save_interval = model_save_interval,
pretrained_model_path = pretrained_model_path,
metric_names = metric_names,
verbose = verbose)
self.sample_keep_prob = sample_keep_prob
self.conv_keep_prob = conv_keep_prob
self.num_classes = num_classes
self.single_dataset = single_dataset
def add_data(self,train_info, test_info, gains, num_flatnesses = 10, abs_min_max_delay = 0.040, precision = 0.00025, blur = 0):
"""Adds data to the Trainer.
Args
train_info - (tuple : (visibility data, baselines dict)) - The training data
test_info - (tuple : (visibility data, baselines dict)) - The testing data
gains - (dict) - The gains for the visibilites
num_flatnesses - (int) - Number of flatnesses for each epoch
- Number of samples is num_flatnesses * 60
abs_min_max_delay - (float) - The absolute value of the min or max delay for this dataset.
"""
self._abs_min_max_delay = abs_min_max_delay
self._train_batcher = self._Data_Creator(num_flatnesses,
train_info[0],
train_info[1],
gains,
abs_min_max_delay,
precision,
single_dataset = self.single_dataset,
blur = blur)
self._train_batcher.gen_data()
self._test_batcher = self._Data_Creator(num_flatnesses,
test_info[0],
test_info[1],
gains,
abs_min_max_delay,
precision,
single_dataset = self.single_dataset,
blur = blur)
self._test_batcher.gen_data()
def train(self):
self.save_params()
costs = []
accuracies = []
tf.reset_default_graph()
self._network.create_graph()
self._network.save_params()
saver = tf.train.Saver()
with tf.Session() as session:
if self.pretrained_model_path == None:
session.run(tf.global_variables_initializer())
else:
saver.restore(session, self.pretrained_model_path)
archive_loc = self.log_dir + self._network.name
training_writer = tf.summary.FileWriter(archive_loc + '/training', session.graph)
testing_writer = tf.summary.FileWriter(archive_loc + '/testing', session.graph)
self.model_save_location = archive_loc + '/trained_model.ckpt'
self._msg = '\rtraining';self._vprint(self._msg)
try:
for epoch in range(self.num_epochs):
if self.single_dataset == True and epoch == 0:
training_inputs, training_labels, training_bl_dict_singleset = self._train_batcher.get_data(); self._train_batcher.gen_data()
testing_inputs, testing_labels, testing_bl_dict_singleset = self._test_batcher.get_data(); self._test_batcher.gen_data()
np.savez(archive_loc + '/params/train_bl_dict_singleset', training_bl_dict_singleset)
np.savez(archive_loc + '/params/test_bl_dict_singleset', testing_bl_dict_singleset)
if self.single_dataset == False:
training_inputs, training_labels = self._train_batcher.get_data(); self._train_batcher.gen_data()
testing_inputs, testing_labels = self._test_batcher.get_data(); self._test_batcher.gen_data()
training_labels = np.asarray(training_labels)
testing_labels = np.asarray(testing_labels)
# if the division here has a remainde some values are just truncated
batch_size = self.batch_size
num_entries = training_inputs.shape[0]
for j in range(int(num_entries/batch_size)):
self._msg = '\repoch'
self._msg += '- {:5.0f}/{:5.0f}'.format(epoch + 1,self.num_epochs)
self._msg += ' - batch: {:4.0f}/{:4.0f}'.format(j + 1, int(num_entries/batch_size))
training_inputs_batch = training_inputs[j*batch_size:(j + 1)*batch_size].reshape(-1,1,1024,1)
training_labels_batch = training_labels[j*batch_size:(j + 1)*batch_size].reshape(-1,self.num_classes)
feed_dict = {self._network.X: training_inputs_batch,
self._network.labels: training_labels_batch,
self._network.sample_keep_prob : self.sample_keep_prob,
self._network.conv_keep_prob : self.conv_keep_prob,
self._network.is_training : True}
batch_cost, batch_acc, _ = session.run([self._network.cost, self._network.accuracy, self._network.optimizer], feed_dict = feed_dict)
if epoch != 0:
self._msg += " batch cost: {:0.4f}".format(batch_cost)
self._msg += " batch accs: {:2.2f}".format(batch_acc)
self._vprint(self._msg);
train_feed_dict = {self._network.X: training_inputs.reshape(-1,1,1024,1),
self._network.labels: training_labels.reshape(-1,self.num_classes),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.is_training : False}
train_predicts = session.run([self._network.predictions], train_feed_dict)
train_feed_dict[self._network.image_buf] = self.plt_confusion_matrix(training_labels.reshape(-1,self.num_classes), train_predicts)
training_cost, training_acc, training_summary = session.run([self._network.cost,
self._network.accuracy,
self._network.summary],
feed_dict = train_feed_dict)
training_writer.add_summary(training_summary, epoch)
training_writer.flush()
test_feed_dict = {self._network.X: testing_inputs.reshape(-1,1,1024,1),
self._network.labels: testing_labels.reshape(-1,self.num_classes),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.is_training : False}
test_predicts = session.run([self._network.predictions], test_feed_dict)
test_feed_dict[self._network.image_buf] = self.plt_confusion_matrix(testing_labels.reshape(-1,self.num_classes), test_predicts)
testing_cost, testing_acc, testing_summary = session.run([self._network.cost,
self._network.accuracy,
self._network.summary],
feed_dict = test_feed_dict)
testing_writer.add_summary(testing_summary, epoch)
testing_writer.flush()
costs.append((training_cost, testing_cost))
accuracies.append((training_acc, testing_acc))
if (epoch + 1) % self.model_save_interval == 0:
saver.save(session, self.model_save_location, epoch + 1)
self.msg = ''
except KeyboardInterrupt:
self._msg = ' TRAINING INTERUPPTED' # this never prints I dont know why
pass
self._msg += '\rtraining ended'; self._vprint(self._msg)
training_writer.close()
testing_writer.close()
session.close()
self._msg += ' - session closed'; self._vprint(self._msg)
self._msg = ''
self._metrics = [costs, accuracies]
self.save_metrics()
def plt_confusion_matrix(self, labels, pred, normalize=False, title='Confusion matrix'):
"""
Given one-hot encoded labels and preds, displays a confusion matrix.
Arguments:
`labels`:
The ground truth one-hot encoded labels.
`pred`:
The one-hot encoded labels predicted by a model.
`normalize`:
If True, divides every column of the confusion matrix
by its sum. This is helpful when, for instance, there are 1000
'A' labels and 5 'B' labels. Normalizing this set would
make the color coding more meaningful and informative.
"""
labels = [label.argmax() for label in np.asarray(labels).reshape(-1,self.num_classes)] # bc
pred = [label.argmax() for label in np.asarray(pred).reshape(-1,self.num_classes)] #bc
#classes = ['pos','neg']#np.arange(len(set(labels)))
if self.num_classes == 9:
precision = 0.005
if self.num_classes == 41:
precision = 0.001
if self.num_classes == 81:
precision = 0.0005
if self.num_classes == 161:
precision = 0.00025
if self.num_classes == 401:
precision = 0.0001
if self.num_classes == 2:
classes = ['pos','neg']
cm = confusion_matrix(labels, pred)
else:
classes = np.round(np.arange(0,0.04 + precision, precision), 5)
cm = confusion_matrix(labels, pred, np.arange(len(classes)))
#if normalize:
cm = cm.astype('float')*100 / cm.sum(axis=1)[:, np.newaxis]
cm = np.nan_to_num(cm, copy=True)
cm = cm.astype('int')
fig, ax = plt.subplots(figsize = (5,5), dpi = 320)
#plt.figure(figsize=(15,10))
im = ax.imshow(cm, interpolation='nearest', aspect='auto', cmap='Oranges', vmin = 0, vmax = 100)
ax.set_title(title)
cbar = fig.colorbar(im)
if len(classes) <= 161:
tick_marks = np.arange(len(classes))
fs = 4 if self.num_classes <= 41 else 3
ax.set_xticks(tick_marks)
ax.set_xticklabels(classes, fontsize=fs, rotation=-90, ha='center')
ax.set_yticks(tick_marks)
ax.set_yticklabels(classes, fontsize=fs)
ax.xaxis.set_tick_params(width=0.5)
ax.yaxis.set_tick_params(width=0.5)
else:
ax.set_xticks([])
ax.set_yticks([])
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
if self.num_classes <= 41:
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
#s = '{:2.0}'.format(cm[i, j]) if cm[i,j] >= 1 else '.'
ax.text(j, i, format(cm[i, j], 'd') if cm[i,j]!=0 else '.',
horizontalalignment="center", fontsize=5, verticalalignment='center', color= "black")
fig.set_tight_layout(True)
# plt.show()
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi = 320)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
<file_sep>/aas/Estimating Delays/nn/networks/CNN_DS_BN_C.py
"""Summary
"""
# CNN_DS_BN_C
import sys, os
from RestoreableComponent import RestoreableComponent
import tensorflow as tf
import numpy as np
class CNN_DS_BN_C(RestoreableComponent):
"""CNN_DS_BN_C() - Child of RestoreableComponent
CNN: Convolutional Neural Network.
DS: DownSampling. Each layer ends with a downsampling convolution
BN: All non-linearalities have batch-normalization applied.
C: Classification, this network classifies samples as having one of many labels.
Network Structure:
Incoming sample has dropout sample_keep_prob - set with Trainer
Each layer has 4 convolutions, each with 4**(i+1) filters (i = zero based layer index).
- Each convolution:
- is a 1D convolution
- feeds into the next
- has a filter of size (1, fw)
- has biases and a LeakyReLU activation
- has dropout with conv_keep_prob - set with Trainer
- has batch normalization
- Filter widths (fw) of the four convolutions are [3,5,7,9]
TODO: Optional filter widths? (different per layer?)
- Fourth convolution will do 50% downsample (horizontal stride = 2)
Final convolution feeds into fully connected layer as logits
Cost function softmax_cross_entropy_with_logits_v2
Optimizer is Adam with adam_initial_learning_rate
Predictions are softmax probabilites
Usage:
- create object and set args (or load params)
Training :
- pass object into appropriate network Trainer object
- trainer will run create_graph()
Structure Check:
- run create_graph()
- call network._layers to see layer output dimensions
TODO: Make structure check better
- should directly access _layers
- should add save graph for tensorboard ?
Other:
- run create_graph()
- start tensorflow session
Methods:
- create_graph() - Contructs the network graph
Attributes:
accuracy (tensorflow obj): Running accuracy of predictions
adam_initial_learning_rate (tensorflow obj): Adam optimizer initial learning rate
conv_keep_prob (tensorflow obj): Keep prob rate for convolutions
correct_prediction (tensorflow obj): compares predicted label to true, for predictions
cost (tensorflow obj): cost function
dtype (tensorflow obj): Type used for all computations
image_buf (tensorflow obj): buffer for image summaries for tensorboard
is_training (tensorflow obj): flag for batch normalization
labels (tensorflow obj): tensor of sample labels
num_classes (int): Number of different classes
num_downsamples (int): Number of downsample convolutions
optimizer (tensorflow obj): optimization function
pred_cls (tensorflow obj): predicted class index
predictions (tensorflow obj): probability predictions or each class
sample_keep_prob (tensorflow obj): keep rate for incoming sample
summary (tensorflow obj): summary operation for tensorboard
true_cls (tensorflow obj): true class index
X (tensorflow obj): incoming sample
"""
__doc__ += RestoreableComponent.__doc__
def __init__(self,
name,
num_downsamples,
num_classes,
log_dir = '../logs/',
dtype = tf.float32,
adam_initial_learning_rate = 0.0001,
verbose = True):
"""__init__
Args:
name (str): Name of this network
num_downsamples (int): Number of downsample convolutions
num_classes (int): Number of different classes
log_dir (str, optional): Log directory
dtype (tensorboard datatype, optional): datatype for all operations
adam_initial_learning_rate (float, optional): Adam optimizer initial learning rate
verbose (bool, optional): be verbose
"""
RestoreableComponent.__init__(self, name=name, log_dir=log_dir, verbose=verbose)
self.num_downsamples = num_downsamples
self.dtype = dtype
self.adam_initial_learning_rate = adam_initial_learning_rate
self._num_freq_channels = 1024
self._layers = []
self.num_classes = num_classes # classifier...
def create_graph(self):
"""create_graph
Create the network graph for use in a tensorflow session
"""
self._msg = '\rcreating network graph '; self._vprint(self._msg)
tf.reset_default_graph()
self.is_training = tf.placeholder(dtype = tf.bool, shape = [], name = 'is_training')
with tf.variable_scope('keep_probs'):
self._msg += '.'; self._vprint(self._msg)
self.sample_keep_prob = tf.placeholder(self.dtype, name = 'sample_keep_prob')
self.conv_keep_prob = tf.placeholder(self.dtype, name = 'conv_keep_prob')
with tf.variable_scope('sample'):
self._msg += '.'; self._vprint(self._msg)
self.X = tf.placeholder(self.dtype, shape = [None, 1, self._num_freq_channels, 1], name = 'X')
self.X = tf.nn.dropout(self.X, self.sample_keep_prob)
for i in range(self.num_downsamples):
self._msg += '.'; self._vprint(self._msg)
# foc - filter out channels - number of filters
foc = 4**(i+1) # num filters grows with each downsample
with tf.variable_scope('downsample_{}'.format(i)):
layer = self.X if i == 0 else self._layers[-1]
fitlter_widths = [3,5,7,9]
for fw in fitlter_widths:
with tf.variable_scope('conv_1x{}'.format(fw)):
layer = tf.layers.conv2d(inputs = layer,
filters = foc,
kernel_size = (1,fw),
strides = (1,1) if fw != fitlter_widths[-1] else (1,2), # downscale last conv
padding = 'SAME',
activation = tf.nn.leaky_relu,
use_bias = True,
bias_initializer = tf.contrib.layers.xavier_initializer())
layer = tf.nn.dropout(layer, self.conv_keep_prob)
layer = tf.layers.batch_normalization(layer, training = self.is_training)
self._layers.append(layer)
self._msg += ' '
with tf.variable_scope('labels'):
self._msg += '.'; self._vprint(self._msg)
self.labels = tf.placeholder(dtype = self.dtype, shape = [None, self.num_classes], name = 'labels')
self.true_cls = tf.argmax(self.labels, axis = 1)
with tf.variable_scope('logits'):
self._msg += '.'; self._vprint(self._msg)
self._logits = tf.contrib.layers.fully_connected(tf.layers.flatten(self._layers[-1]), self.num_classes, activation_fn = None)
with tf.variable_scope('predictions'):
self._msg += '.'; self._vprint(self._msg)
self.predictions = tf.nn.softmax(self._logits)
self.pred_cls = tf.argmax(self.predictions, axis = 1)
self.correct_prediction = tf.equal(self.pred_cls, self.true_cls)
self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, self.dtype))
with tf.variable_scope('costs'):
self._msg += '.'; self._vprint(self._msg)
self._cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels = self.labels, logits = self._logits)
self.cost = tf.reduce_mean(self._cross_entropy)
# batch normalization requires the update_ops variable and control dependency
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
with tf.variable_scope('train'):
self._msg += '.'; self._vprint(self._msg)
if self.dtype == tf.float16:
epsilon=1e-4 # optimizer outputs NaN otherwise :(
else:
epsilon=1e-8
self.optimizer = tf.train.AdamOptimizer(self.adam_initial_learning_rate, epsilon=epsilon).minimize(self.cost)
with tf.variable_scope('logging'):
self._msg += '.'; self._vprint(self._msg)
with tf.variable_scope('image'):
self.image_buf = tf.placeholder(tf.string, shape=[])
epoch_image = tf.expand_dims(tf.image.decode_png(self.image_buf, channels=4), 0)
tf.summary.scalar(name = 'cost', tensor = self.cost)
tf.summary.scalar(name = 'accuracy', tensor = self.accuracy)
tf.summary.image('confusion_matrix', epoch_image)
self.summary = tf.summary.merge_all()
num_trainable_params = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])
self._msg = '\rnetwork Ready - {} trainable parameters'.format(num_trainable_params); self._vprint(self._msg)
<file_sep>/aas/Estimating Delays/estdel/estdel/__init__.py
from estdel import VratioDelaySign, VratioDelayMagnitude, VratioDelay, DelaySolver
<file_sep>/aas/Estimating Delays/nn/network_trainers/__init__.py
from NN_Trainer import NN_Trainer
from CNN_BC_Trainer import CNN_BC_Trainer
from CNN_C_Trainer import CNN_C_Trainer
from CNN_DS_BN_R_Trainer import CNN_DS_BN_R_Trainer
from CNN_R_Trainer import CNN_R_Trainer
<file_sep>/aas/Estimating Delays/estdel/estdel/tests/test_estdel.py
import unittest
from estdel.estdel import _DelayPredict
import numpy as np
class test_DelayPredict(unittest.TestCase):
def test_init(self):
data = np.exp(-2j*np.pi*np.arange(1024)*0.01).reshape(-1,1024)
delayPredict = _DelayPredict(data)
self.assertEqual(delayPredict._n_freqs, 1024)
np.testing.assert_array_equal(delayPredict._data, data)
data_2 = np.exp(-2j*np.pi*np.arange(1024 + 1)*0.01).reshape(-1,1024 + 1)
self.assertRaises(AssertionError, _DelayPredict, data_2)
if __name__ == '__main__':
unittest.main()
<file_sep>/aas/Estimating Delays/nn/networks/CNN_DS_BN_R.py
"""CNN_DS_BN_R
"""
import sys, os
from RestoreableComponent import RestoreableComponent
import tensorflow as tf
import numpy as np
class CNN_DS_BN_R(RestoreableComponent):
"""CNN_DS_BN_R
Attributes:
accuracy_threshold (float): the value for a target to be considered 'good'
adam_initial_learning_rate (float): Adam optimizer initial learning rate
cost (str): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
downsample_keep_prob (tensorflow obj): keep prob for downsampling layers
dtype (tensorflow obj): type used for all computations
gaussian_shift_scalar (float): value to shift gaussian for 'MISG' cost
image_buf (tensorflow obj): buffer for image summaries for tensorboard
is_training (tensorflow obj): flag for batch normalization
MISG (tensorflow obj): cost function, experimental. Mean Inverse Shifted Gaussian
MQE (tensorflow obj): cost function, experimental. Mean Quad Error
MSE (tensorflow obj): cost function. Mean Squared Error
num_downsamples (int): Number of downsampling layers
optimizer (tensorflow obj): optimization function
predictions (tensorflow obj): predicted outputs
PWT (tensorflow obj): Percent of predictions within threshold
sample_keep_prob (tensorflow obj): keep prob for input samples
summary (tensorflow obj): summary operation for tensorboard
targets (tensorflow obj): true values for optimizer
X (tensorflow obj): input samples
"""
__doc__ += RestoreableComponent.__doc__
def __init__(self,
name,
num_downsamples,
cost = 'MSE',
log_dir = '../logs/',
dtype = tf.float32,
adam_initial_learning_rate = 0.0001,
accuracy_threshold = 0.00625,
gaussian_shift_scalar = 1e-5,
verbose = True):
"""Summary
Args:
name (str): name of network
num_downsamples (int): number of downsampling layers
cost (str, optional): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
log_dir (str, optional): Directory to store network model and params
dtype (tensorflow obj, optional): type used for all computations
adam_initial_learning_rate (float, optional): Adam optimizer initial learning rate
accuracy_threshold (float, optional): the value for a target to be considered 'good'
gaussian_shift_scalar (float, optional): value to shift gaussian for 'MISG' cost
verbose (bool, optional): Be verbose
"""
RestoreableComponent.__init__(self, name=name, log_dir=log_dir, verbose=verbose)
self.num_downsamples = num_downsamples
self.dtype = dtype
self.adam_initial_learning_rate = adam_initial_learning_rate
self.accuracy_threshold = accuracy_threshold
self.gaussian_shift_scalar = gaussian_shift_scalar
self.cost = cost
self._num_freq_channels = 1024
self._layers = []
self._num_outputs = 1 # Regression
def create_graph(self):
"""create_graph
Create the network graph for use in a tensorflow session
"""
self.save_params()
self._msg = '\rcreating network graph '; self._vprint(self._msg)
tf.reset_default_graph()
self.is_training = tf.placeholder(dtype = tf.bool, shape = [], name = 'is_training')
with tf.variable_scope('keep_probs'):
self._msg += '.'; self._vprint(self._msg)
self.sample_keep_prob = tf.placeholder(self.dtype, name = 'sample_keep_prob')
self.downsample_keep_prob = tf.placeholder(self.dtype, name = 'downsample_keep_prob')
with tf.variable_scope('sample'):
self._msg += '.'; self._vprint(self._msg)
self.X = tf.placeholder(self.dtype, shape = [None, 1, self._num_freq_channels, 1], name = 'X')
self.X = tf.nn.dropout(self.X, self.sample_keep_prob)
trainable = lambda shape, name : tf.get_variable(name = name,
dtype = self.dtype,
shape = shape,
initializer = tf.contrib.layers.xavier_initializer())
for i in range(self.num_downsamples):
self._msg += '.'; self._vprint(self._msg)
with tf.variable_scope('conv_layer_{}'.format(i)):
layer = self.X if i == 0 else self._layers[-1]
# filter shape:
fh = 1 # filter height = 1 for 1D convolution
fw = 3 # filter width
fic = 2**(i) # num in channels = number of incoming filters
foc = 2**(i+1) # num out channels = number of outgoing filters
filters = trainable([fh, fw, fic, foc], 'filters')
# stride shape
sN = 1 # batch = 1 (why anything but 1 ?)
sH = 1 # height of stride = 1 for 1D conv
sW = 1 # width of stride = downsampling factor = 1 for no downsampling or > 1 for downsampling
sC = 1 # depth = number of channels the stride walks over = 1 (why anything but 1 ?)
strides_no_downsample = [sN, sH, sW, sC]
layer = tf.nn.conv2d(layer, filters, strides_no_downsample, 'SAME')
# shape of biases = [num outgoing filters]
biases = trainable([foc], 'biases')
layer = tf.nn.bias_add(layer, biases)
layer = tf.nn.leaky_relu(layer)
layer = tf.contrib.layers.batch_norm(layer, is_training = self.is_training)
# downsample
with tf.variable_scope('downsample'):
fw = 5
filters = trainable([fh, fw, foc, foc], 'filters')
sW = 2
strides_no_downsample = [sN, sH, sW, sC]
layer = tf.nn.conv2d(layer, filters, strides_no_downsample, 'SAME')
# shape of biases = [num outgoing filters]
biases = trainable([foc], 'biases')
layer = tf.nn.bias_add(layer, biases)
layer = tf.nn.leaky_relu(layer)
layer = tf.nn.dropout(layer, self.downsample_keep_prob)
layer = tf.contrib.layers.batch_norm(layer, is_training = self.is_training)
self._layers.append(layer)
self._msg += ' '
with tf.variable_scope('targets'):
self._msg += '.'; self._vprint(self._msg)
self.targets = tf.placeholder(dtype = self.dtype, shape = [None, self._num_outputs], name = 'labels')
with tf.variable_scope('predictions'):
self._msg += '.'; self._vprint(self._msg)
self.predictions = tf.contrib.layers.fully_connected(tf.layers.flatten(self._layers[-1]), self._num_outputs)
with tf.variable_scope('costs'):
self._msg += '.'; self._vprint(self._msg)
error = tf.subtract(self.targets, self.predictions, name = 'error')
squared_error = tf.square(error, name = 'squared_difference')
quad_error = tf.square(squared_error, name = 'quad_error' )
with tf.variable_scope('mean_inverse_shifted_gaussian'):
self._msg += '.'; self._vprint(self._msg)
normal_dist = tf.contrib.distributions.Normal(0.0, self.accuracy_threshold, name = 'normal_dist')
gaussian_prob = normal_dist.prob(error, name = 'gaussian_prob')
shifted_gaussian = tf.add(gaussian_prob, self.gaussian_shift_scalar, name = 'shifted_gaussian')
self.MISG = tf.reduce_mean(tf.divide(1.0, shifted_gaussian), name = 'mean_inverse_shifted_gaussian')
with tf.variable_scope('mean_squared_error'):
self._msg += '.'; self._vprint(self._msg)
self.MSE = tf.reduce_mean(squared_error / self.gaussian_shift_scalar)
with tf.variable_scope('mean_quad_error'):
self._msg += '.'; self._vprint(self._msg)
self.MQE = tf.reduce_mean(quad_error / self.gaussian_shift_scalar)
with tf.variable_scope('logging'):
with tf.variable_scope('image'):
self._msg += '.'; self._vprint(self._msg)
self.image_buf = tf.placeholder(tf.string, shape=[])
epoch_image = tf.expand_dims(tf.image.decode_png(self.image_buf, channels=4), 0)
with tf.variable_scope('percent_within_threshold'):
self._msg += '.'; self._vprint(self._msg)
self.PWT = 100.*tf.reduce_mean(tf.cast(tf.less_equal(tf.abs(self.targets - self.predictions), self.accuracy_threshold), self.dtype) )
tf.summary.histogram(name = 'targets', values = self.targets)
tf.summary.histogram(name = 'predictions',values = self.predictions)
tf.summary.scalar(name = 'MSE', tensor = self.MSE)
tf.summary.scalar(name = 'MISG', tensor = self.MISG)
tf.summary.scalar(name = 'MQE', tensor = self.MQE)
tf.summary.scalar(name = 'PWT', tensor = self.PWT)
tf.summary.image('prediction_vs_actual', epoch_image)
self.summary = tf.summary.merge_all()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
with tf.variable_scope('train'):
self._msg += '.'; self._vprint(self._msg)
if self.cost == 'MSE':
cost = self.MSE
if self.cost == 'MQE':
cost = tf.log(self.MQE)
if self.cost == 'MISG':
cost = self.MISG
if self.cost == 'PWT_weighted_MSE':
cost = self.MSE * (100. - self.PWT)
if self.cost == 'PWT_weighted_MISG':
cost = self.MISG * (100. - self.PWT)
self.optimizer = tf.train.AdamOptimizer(self.adam_initial_learning_rate, epsilon=1e-08).minimize(cost)
num_trainable_params = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])
self._msg = '\rNetwork Ready - {} trainable parameters'.format(num_trainable_params); self._vprint(self._msg)<file_sep>/nsk/scripts/sky_image.py
#!/usr/bin/env python2.7
"""
sky_image.py
-------------
sky-based calibration with CASA 5.1.1
run the script as:
casa -c sky_image.py <args>
<NAME>
<EMAIL>
Nov. 2017
"""
import sys
import os
import numpy as np
import argparse
import subprocess
import shutil
import glob
## Set Arguments
# Required Arguments
a = argparse.ArgumentParser(description="Run with casa as: casa -c sky_image.py <args>")
a.add_argument('--script', '-c', type=str, help='name of this script', required=True)
a.add_argument('--msin', default=None, type=str, help='path to a CASA measurement set. if fed a .uvfits, will convert to ms', required=True)
a.add_argument('--source', default=None, type=str, help='source name', required=True)
# IO Arguments
a.add_argument('--out_dir', default=None, type=str, help='output directory')
a.add_argument("--silence", default=False, action='store_true', help="turn off output to stdout")
a.add_argument('--source_ext', default=None, type=str, help="Extension to default source name in output image files")
a.add_argument("--im_stem", default=None, type=str, help="Imagename stem for output images. Default is basename of input MS.")
# Calibration Arguments
a.add_argument("--model_im", default=None, type=str, help="path to model image, if None will look for a {source}.cl file")
a.add_argument('--refant', default=None, type=str, help='reference antenna')
a.add_argument('--ex_ants', default=None, type=str, help='bad antennas to flag')
a.add_argument('--rflag', default=False, action='store_true', help='run flagdata(mode=rflag)')
a.add_argument('--unflag', default=False, action='store_true', help='start by unflagging data')
a.add_argument('--KGcal', default=False, action='store_true', help='perform K (dly) & G (phs) calibration')
a.add_argument("--KGsnr", default=2.0, type=float, help="KG calibration Signal-to-Noise cut")
a.add_argument('--Acal', default=False, action='store_true', help='perform G (amp) calibration')
a.add_argument("--Asnr", default=2.0, type=float, help="G-amplitude calibration Signal-to-Noise cut")
a.add_argument('--BPcal', default=False, action='store_true', help='perform BandPass calibration (phs & amp)')
a.add_argument("--BPsnr", default=2.0, type=float, help="bandpass calibration Signal-to-Noise cut")
a.add_argument('--uvrange', default="", type=str, help="uvrange in meters (baseline length) to use in calibration and imaging")
a.add_argument('--timerange', default=[""], type=str, nargs='*', help="calibration and clean timerange(s)")
a.add_argument('--bpoly', default=False, action='store_true', help="use BPOLY mode in bandpass")
a.add_argument('--degamp', default=4, type=int, help="amplitude polynomial degree for BPOLY")
a.add_argument('--degphase', default=1, type=int, help="phase polynomial degree for BPOLY")
a.add_argument('--calspw', default='0:100~924', type=str, help="Calibration spectral window selection")
a.add_argument('--smodel', default=[], type=float, nargs='*', help="Stokes source model as I Q U V")
# Imaging Arguments
a.add_argument('--image_mfs', default=False, action='store_true', help="make an MFS image across the band")
a.add_argument('--niter', default=50, type=int, help='number of clean iterations.')
a.add_argument('--pxsize', default=300, type=int, help='pixel (cell) scale in arcseconds')
a.add_argument('--imsize', default=500, type=int, help='number of pixels along a side of the output square image.')
a.add_argument('--cleanspw', default="0:100~924", type=str, help="spectral window selection for clean")
a.add_argument('--image_model', default=False, action='store_true', help="image model datacolumn instead of data datacolumn")
a.add_argument('--spec_cube', default=False, action='store_true', help="image spectral cube as well as MFS.")
a.add_argument('--spec_dchan', default=40, type=int, help="number of channel averaging for a single image in the spectral cube.")
a.add_argument('--spec_start', default=100, type=int, help='starting channel for spectral cube')
a.add_argument('--spec_end', default=924, type=int, help='ending channel for spectral cube')
a.add_argument("--stokes", default='I', type=str, help="Stokes parameters to image.")
# Plotting Arguments
a.add_argument("--plot_uvdist", default=False, action='store_true', help='make a uvdist plot')
def echo(message, type=0):
if verbose:
if type == 0:
print(message)
elif type == 1:
print("\n" + message + "\n" + "-"*40)
if __name__ == "__main__":
# parse args
args = a.parse_args()
# get vars
if args.source_ext is None:
args.source_ext = ''
verbose = args.silence is False
# check for .loc and .cl files
if os.path.exists('{}.loc'.format(args.source)) is False:
raise AttributeError("{}.loc file doesn't exist in working directory".format(args.source))
# configure refant
if args.refant is None and (args.KGcal is True or args.Acal is True or args.BPcal is True):
raise AttributeError("if calibrating, refant needs to be specified")
args.refant = "HH" + str(args.refant)
# get phase center
ra, dec = np.loadtxt('{}.loc'.format(args.source), dtype=str)
ra, dec = ra.split(':'), dec.split(':')
fixdir = 'J2000 {}h{}m{}s {}d{}m{}s'.format(*(ra+dec))
msin = args.msin
# get paths
base_ms = os.path.basename(msin)
if args.out_dir is None:
out_dir = os.path.dirname(msin)
else:
out_dir = args.out_dir
# check for uvfits
if base_ms.split('.')[-1] == 'uvfits':
echo("...converting uvfits to ms", type=1)
uvfits = msin
msin = os.path.join(out_dir, '.'.join(base_ms.split('.')[:-1] + ['ms']))
base_ms = os.path.basename(msin)
msfiles = glob.glob("{}*".format(msin))
if len(msfiles) != 0:
for i, msf in enumerate(msfiles):
try:
os.remove(msf)
except OSError:
shutil.rmtree(msf)
importuvfits(uvfits, msin)
echo("{}".format(msin))
# rephase to source
echo("...fix vis to {}".format(fixdir), type=1)
fixvis(msin, msin, phasecenter=fixdir)
# insert source model
if (args.KGcal is True or args.Acal is True or args.BPcal is True) or args.image_model is True:
if args.model_im is None:
echo("...inserting {} as MODEL".format("{}.cl".format(args.source)), type=1)
ft(msin, complist="{}.cl".format(args.source), usescratch=True)
else:
echo("...inserting {} as MODEL".format(args.model_im), type=1)
ft(msin, model=args.model_im, usescratch=True)
# unflag
if args.unflag is True:
echo("...unflagging", type=1)
flagdata(msin, mode='unflag')
# flag autocorrs
echo("...flagging autocorrs", type=1)
flagdata(msin, autocorr=True)
# flag bad ants
if args.ex_ants is not None:
args.ex_ants = ','.join(map(lambda x: "HH"+x, args.ex_ants.split(',')))
echo("...flagging bad ants: {}".format(args.ex_ants), type=1)
flagdata(msin, mode='manual', antenna=args.ex_ants)
# rflag
if args.rflag is True:
echo("...rfi flagging", type=1)
flagdata(msin, mode='rflag')
def KGCAL(msin, gaintables=[]):
## perform per-antenna delay and phase calibration ##
# setup calibration tables
kc = os.path.join(out_dir, base_ms+'.{}.cal'.format('K'))
gpc = os.path.join(out_dir, base_ms+'.{}.cal'.format('Gphs'))
# perform initial K calibration (per-antenna delay)
echo("...performing K gaincal", type=1)
if os.path.exists(kc):
shutil.rmtree(kc)
if os.path.exists("{}.png".format(kc)):
os.remove("{}.png".format(kc))
gaincal(msin, caltable=kc, gaintype="K", solint='inf', refant=args.refant, minsnr=args.KGsnr, spw=args.calspw,
gaintable=gaintables, timerange=cal_timerange, uvrange=args.uvrange)
plotcal(kc, xaxis='antenna', yaxis='delay', figfile='{}.png'.format(kc), showgui=False)
gaintables.append(kc)
# write delays as npz file
tb.open(kc)
delays = tb.getcol('FPARAM')[0, 0]
delay_ants = tb.getcol('ANTENNA1')
delay_flags = tb.getcol('FLAG')[0, 0]
tb.close()
np.savez("{}.npz".format(kc), delay_ants=delay_ants, delays=delays, delay_flags=delay_flags)
echo("...Saving delays to {}.npz".format(kc))
echo("...Saving plotcal to {}.png".format(kc))
# perform initial G calibration for phase (per-spw and per-pol gain)
echo("...performing G gaincal for phase", type=1)
if os.path.exists(gpc):
shutil.rmtree(gpc)
if os.path.exists("{}.png".format(gpc)):
os.remove("{}.png".format(gpc))
gaincal(msin, caltable=gpc, gaintype='G', solint='inf', refant=args.refant, minsnr=args.KGsnr, calmode='p',
spw=args.calspw, gaintable=gaintables, timerange=cal_timerange, uvrange=args.uvrange)
plotcal(gpc, xaxis='antenna', yaxis='phase', figfile='{}.png'.format(gpc), showgui=False)
gaintables.append(gpc)
# write phase to file
tb.open(gpc)
phases = np.angle(tb.getcol('CPARAM')[0, 0])
phase_ants = tb.getcol('ANTENNA1')
phase_flags = tb.getcol('FLAG')[0, 0]
tb.close()
np.savez("{}.npz".format(gpc), phase_ants=phase_ants, phases=phases, phase_flags=phase_flags)
echo("...Saving phases to {}.npz".format(gpc))
echo("...Saving plotcal to {}.png".format(gpc))
return gaintables
def ACAL(msin, gaintables=[]):
# gaincal G amplitude
echo("...performing G gaincal for amplitude", type=1)
gac = msin+'.{}.cal'.format('Gamp')
if os.path.exists(gac):
shutil.rmtree(gac)
if os.path.exists("{}.png".format(gac)):
os.remove("{}.png".format(gac))
gaincal(msin, caltable=gac, gaintype='G', solint='inf', refant=args.refant, minsnr=args.Asnr, calmode='a',
spw=args.calspw, gaintable=gaintables, timerange=cal_timerange, uvrange=args.uvrange)
plotcal(gac, xaxis='antenna', yaxis='amp', figfile='{}.png'.format(gac), showgui=False)
gaintables.append(gac)
# write amp to file
tb.open(gac)
amps = np.abs(tb.getcol('CPARAM')[0, 0])
amp_ants = tb.getcol('ANTENNA1')
amp_flags = tb.getcol('FLAG')[0, 0]
tb.close()
np.savez("{}.npz".format(gac), amp_ants=amp_ants, amps=amps, amp_flags=amp_flags)
echo("...Saving amps to {}.npz".format(gac))
echo('...Saving G amp plotcal to {}.png'.format(gac))
return gaintables
def BPCAL(msin, gaintables=[]):
# calibrated bandpass
echo("...performing B bandpass cal", type=1)
bc = msin+'.{}.cal'.format('B')
Btype = "B"
if args.bpoly:
Btype="BPOLY"
if os.path.exists(bc):
shutil.rmtree(bc)
if os.path.exists("{}.amp.png".format(bc)):
os.remove("{}.amp.png".format(bc))
if os.path.exists("{}.phs.png".format(bc)):
os.remove("{}.phs.png".format(bc))
bandpass(vis=msin, spw="", minsnr=args.BPsnr, bandtype=Btype, degamp=args.degamp, degphase=args.degphase,
caltable=bc, gaintable=gaintables, solint='inf', refant=args.refant, timerange=cal_timerange,
uvrange=args.uvrange, smodel=args.smodel)
plotcal(bc, xaxis='chan', yaxis='amp', figfile="{}.amp.png".format(bc), showgui=False)
plotcal(bc, xaxis='chan', yaxis='phase', figfile="{}.phs.png".format(bc), showgui=False)
gaintables.append(bc)
# write bp to file
if args.bpoly is False:
# get flags and bandpass data
tb.open(bc)
bp = tb.getcol('CPARAM')[0]
bp_ants = tb.getcol("ANTENNA1")
bp_flags = tb.getcol('FLAG')[0]
tb.close()
# load spectral window data
tb.open(bc+"/SPECTRAL_WINDOW")
bp_freqs = tb.getcol("CHAN_FREQ")
tb.close()
# write to file
np.savez("{}.npz".format(bc), bp=bp, bp_ants=bp_ants, bp_flags=bp_flags, bp_freqs=bp_freqs)
echo("...Saving bandpass to {}.npz".format(bc))
echo("...Saving amp plotcal to {}.amp.png".format(bc))
echo("...Saving phs plotcal to {}.phs.png".format(bc))
else:
echo("couldn't access bandpass data. Note BPOLY solutions not currently compatible w/ caltable2calfits.py")
return gaintables
if (args.KGcal is True or args.Acal is True or args.BPcal is True):
## Begin Calibration ##
# init cal_timerange
cal_timerange = ','.join(args.timerange)
# run through various calibration options
gaintables = []
if args.KGcal:
gaintables = KGCAL(msin, gaintables)
if args.Acal:
gaintables = ACAL(msin, gaintables)
if args.BPcal:
gaintables = BPCAL(msin, gaintables)
# apply calibration gaintables
echo("...applying gaintables: \n {}".format('\n'.join(gaintables)), type=1)
applycal(msin, gaintable=gaintables)
ms_split = os.path.join(out_dir, "{}.split".format(base_ms))
files = glob.glob("{}*".format(ms_split))
for f in files:
if os.path.exists(f):
try:
shutil.rmtree(f)
except OSError:
os.remove(f)
split(msin, ms_split, datacolumn="corrected")
fixvis(ms_split, ms_split, phasecenter=fixdir)
else:
echo("...no calibration performed", type=1)
ms_split = msin
if args.image_mfs is True or args.spec_cube is True:
# remove paths
if args.im_stem is None:
im_stem = os.path.join(out_dir, base_ms + '.' + args.source + args.source_ext)
else:
im_stem = args.im_stem
echo("...performing clean for output files:\n{}.*".format(im_stem), type=1)
source_files = glob.glob(im_stem+'*')
if len(source_files) > 0:
for sf in source_files:
if os.path.exists(sf):
try:
shutil.rmtree(sf)
except OSError:
os.remove(sf)
if args.image_model:
model_ms_split = ms_split + ".model"
if args.im_stem is None:
model_im_stem = os.path.join(out_dir, base_ms + '.model.' + args.source + args.source_ext)
else:
model_im_stem = args.im_stem + '.model'
if args.model_im is None:
echo("...inserting {} as MODEL".format("{}.cl".format(args.source)), type=1)
ft(ms_split, complist="{}.cl".format(args.source), usescratch=True)
else:
echo("...inserting {} as MODEL".format(args.model_im), type=1)
ft(ms_split, model=args.model_im, usescratch=True)
split(ms_split, model_ms_split, datacolumn='model')
# create mfs image
if args.image_mfs:
echo("...running MFS clean", type=1)
def image_mfs(msin, im_stem, timerange, cleanspw):
clean(vis=msin, imagename=im_stem, spw=cleanspw, niter=args.niter, weighting='briggs', robust=0, imsize=[args.imsize, args.imsize],
cell=['{}arcsec'.format(args.pxsize)], mode='mfs', timerange=timerange, uvrange=args.uvrange, stokes=args.stokes)
exportfits(imagename='{}.image'.format(im_stem), fitsimage='{}.fits'.format(im_stem))
print("...saving {}".format('{}.fits'.format(im_stem)))
for i, tr in enumerate(args.timerange):
if i == 0:
image_mfs(ms_split, im_stem, tr, args.cleanspw)
if args.image_model:
image_mfs(model_ms_split, model_im_stem, tr, args.cleanspw)
else:
image_mfs(ms_split, im_stem+'_tr{}'.format(i), tr, args.cleanspw)
if args.image_model:
image_mfs(model_ms_split, model_im_stem+'_tr{}'.format(i), tr, args.cleanspw)
# create spectrum
if args.spec_cube:
echo("...running spectral cube clean", type=1)
def spec_cube(msin, im_stem, timerange):
dchan = args.spec_dchan
for i, chan in enumerate(np.arange(args.spec_start, args.spec_end, dchan)):
clean(vis=msin, imagename=im_stem+'.spec{:04d}'.format(chan), niter=0, spw="0:{}~{}".format(chan, chan+dchan-1),
weighting='briggs', robust=0, imsize=[args.imsize, args.imsize], timerange=timerange, uvrange=args.uvrange,
cell=['{}arcsec'.format(args.pxsize)], mode='mfs', stokes=args.stokes)#, mask='circle[[{}h{}m{}s, {}d{}m{}s ], 7deg]'.format(*(ra+dec)))
exportfits(imagename='{}.spec{:04d}.image'.format(im_stem, chan), fitsimage='{}.spec{:04d}.fits'.format(im_stem, chan))
print("...saving {}".format('{}.spec{:04d}.fits'.format(im_stem, chan)))
for i, tr in enumerate(args.timerange):
if i == 0:
spec_cube(ms_split, im_stem, tr)
if args.image_model:
spec_cube(model_ms_split, model_im_stem, tr)
else:
spec_cube(ms_split, im_stem+'_tr{}'.format(i), tr)
if args.image_model:
spec_cube(model_ms_split, model_im_stem+'_tr{}'.format(i), tr)
# make uvdist plot
if args.plot_uvdist:
echo("...plotting uvdistance", type=1)
# add model to ms_split
if args.model_im is None:
ft(ms_split, complist="{}.cl".format(args.source), usescratch=True)
else:
ft(ms_split, model=args.model_im, usescratch=True)
# load visibility amplitudes
ms.open(ms_split)
data = ms.getdata(["amplitude", "antenna1", "antenna2", "uvdist", "axis_info", "flag", "model_amplitude"], ifraxis=True)
amps = data['amplitude']
mamps = data['model_amplitude']
flags = data['flag']
uvdist = data['uvdist']
freqs = data['axis_info']['freq_axis']['chan_freq']
ms.close()
# get rid of autos
select = []
for i, a1 in enumerate(data['antenna1']):
if a1 != data['antenna2'][i]:
select.append(i)
amps = amps[:, :, select, :].squeeze()
mamps = mamps[:, :, select, :].squeeze()
uvdist = uvdist[select, :]
flags = flags[:, :, select, :].squeeze()
# omit flagged data
amps[flags] *= np.nan
mamps[flags] *= np.nan
# average across time
amps = np.nanmean(amps, axis=2)
mamps = np.nanmean(mamps, axis=2)
uvdist = np.nanmean(uvdist, axis=1)
# average into channel bins
freq_bins = np.median(np.split(np.linspace(100., 200., 1024, endpoint=True)[100:924], 4), axis=1)
amps = np.nanmedian(np.split(amps[100:924, :], 4), axis=1)
mamps = np.nanmedian(np.split(mamps[100:924, :], 4), axis=1)
# plot
import matplotlib.pyplot as plt
def plot_uvdist(amp, ext):
fig, ax = plt.subplots(1, 1, figsize=(10,7))
ax.grid(True)
p = ax.plot(uvdist, amp.T, marker='o', markersize=6, alpha=0.8, ls='')
ax.set_xlabel("baseline length (meters)", fontsize=16)
ax.set_ylabel("amplitude (arbitrary units)", fontsize=16)
ax.set_title("{} for {}".format(ext, base_ms))
ax.legend(p, map(lambda x: '{:0.0f} MHz'.format(x), freq_bins))
file_fname = os.path.join(out_dir, "{}.{}.png".format(base_ms, ext))
echo("...saving {}".format(file_fname))
fig.savefig(file_fname, bbox_inches='tight', pad=0.05)
plt.close()
plot_uvdist(amps, "data_uvdist")
plot_uvdist(mamps, "model_uvdist")
<file_sep>/aas/Estimating Delays/nn/data_creation/Data_Creator.py
"""Data_Creator
base class for data creators
"""
import sys, os
from data_manipulation import *
import numpy as np
class Data_Creator(object):
"""Data_Creator - Parent for network style-specific creators
Generates data, in an alternate thread, for training.
Child MUST implement _gen_data()
Args:
num_flatnesses(int): number of flatnesses used to generate data.
- Number of data samples = 60 * num_flatnesses
bl_data : data source. Output of get_seps_data()
bl_dict (dict) - Dictionary of seps with bls as keys. An output of get_or_gen_test_train_red_bls_dicts()
gains(dict): - Gains for this data. An output of load_relevant_data()
"""
def __init__(self,
num_flatnesses,
bl_data,
bl_dict,
gains,
abs_min_max_delay = 0.040):
"""__init__
Args:
num_flatnesses (int): Number of flatnesses to generate
bl_data (dict): keys are baselines, data is complex visibilities
bl_dict (dict): keys are unique redundant baseline, values are baselines in that redudany group
gains (dict): complex antenna gains
abs_min_max_delay (float, optional): MinMax value of delay
"""
self._num = num_flatnesses
self._bl_data = bl_data
self._bl_data_c = None
self._bl_dict = bl_dict
self._gains = gains
self._gains_c = None
self._epoch_batch = []
self._nu = np.arange(1024)
self._tau = abs_min_max_delay
def _gen_data(self):
"""_gen_data
This method is called in a separate thread via gen_data().
Must be overridden
"""
print('Must implement _gen_data()')
def gen_data(self):
"""gen_data
Starts a new thread and generates data there.
"""
self._thread = Thread(target = self._gen_data, args=())
self._thread.start()
def get_data(self, timeout = 10):
"""get_data
Retrieves the data from the thread.
Args:
timeout (int, optional): data generation timeout in seconds
Returns:
(list of complex floats): shape = (num_flatnesses, 60, 1024)
- needs to be reshaped for training
"""
if len(self._epoch_batch) == 0:
self._thread.join(timeout)
return self._epoch_batch.pop(0)<file_sep>/aas/Estimating Delays/nn/network_trainers/CNN_R_Trainer.py
# CNN_R_Trainer
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../modules'))
from NN_Trainer import NN_Trainer
import tensorflow as tf
from tensorflow.python.client import timeline
import numpy as np
class CNN_R_Trainer(NN_Trainer):
def __init__(self,
network,
Data_Creator, # Class
num_epochs = 100,
batch_size = 32,
log_dir = '../logs/',
model_save_interval = 25,
pretrained_model_path = None,
metric_names = ['MISGs', 'MSEs', 'PWTs'],
sample_keep_prob = 0.80,
conv_keep_prob = 0.9,
pred_keep_prob = 0.50,
verbose = True):
NN_Trainer.__init__(self,
network = network,
Data_Creator = Data_Creator,
num_epochs = num_epochs,
batch_size = batch_size,
log_dir = log_dir,
model_save_interval = model_save_interval,
pretrained_model_path = pretrained_model_path,
metric_names = metric_names,
verbose = verbose)
self.sample_keep_prob = sample_keep_prob
self.conv_keep_prob = conv_keep_prob
self.pred_keep_prob = pred_keep_prob
def train(self):
self.save_params()
MISGs = []
MSEs = []
PWTs = []
tf.reset_default_graph()
self._network.create_graph()
saver = tf.train.Saver()
itx = lambda x: np.array(x) * 2. * self._abs_min_max_delay - self._abs_min_max_delay
with tf.Session() as session:
if self.pretrained_model_path == None:
session.run(tf.global_variables_initializer())
else:
saver.restore(session, self.pretrained_model_path)
options = tf.RunOptions(trace_level = tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
archive_loc = self.log_dir + self._network.name
training_writer = tf.summary.FileWriter(archive_loc + '/training', session.graph)
testing_writer = tf.summary.FileWriter(archive_loc + '/testing', session.graph)
self._model_save_location = archive_loc + '/trained_model.ckpt'
try:
for epoch in range(self.num_epochs):
training_inputs, training_targets = self._train_batcher.get_data(); self._train_batcher.gen_data()
testing_inputs, testing_targets = self._test_batcher.get_data(); self._test_batcher.gen_data()
# if the division here has a remainde some values are just truncated
batch_size = self.batch_size
num_entries = training_inputs.shape[0]
for j in range(int(num_entries/batch_size)):
self._msg = '\repoch'
self._msg += '- {:5.0f}/{:5.0f}'.format(epoch + 1,self.num_epochs)
self._msg += ' - batch: {:4.0f}/{:4.0f}'.format(j + 1, int(num_entries/batch_size))
if epoch != 0:
self._msg += ' - (Training, Testing) - '.format(epoch)
self._msg += ' MISG: ({:0.4f}, {:0.4f})'.format(training_MISG, testing_MISG)
self._msg += ' MSE: ({:0.4f}, {:0.4f})'.format(training_MSE, testing_MSE)
self._msg += ' PWT: ({:2.2f}, {:2.2f})'.format(training_PWT, testing_PWT)
training_inputs_batch = training_inputs[j*batch_size:(j + 1)*batch_size].reshape(-1,1,1024,1)
training_targets_batch = training_targets[j*batch_size:(j + 1)*batch_size].reshape(-1,1)
feed_dict = {self._network.samples: training_inputs_batch,
self._network.targets: training_targets_batch,
self._network.sample_keep_prob : self.sample_keep_prob,
self._network.conv_keep_prob : self.conv_keep_prob,
self._network.pred_keep_prob : self.pred_keep_prob,
self._network.is_training : True}
if j == 0 and (epoch + 1) % self.model_save_interval == 0:
session.run([self._network.optimizer], feed_dict = feed_dict,
options = options, run_metadata = run_metadata)
training_writer.add_run_metadata(run_metadata, 'epoch%d' %epoch)
fetched_timeline = timeline.Timeline(run_metadata.step_stats)
chrome_trace = fetched_timeline.generate_chrome_trace_format()
direc = archive_loc + '/timelines/'
if not os.path.exists(direc):
os.makedirs(direc)
with open(direc + 'timeline_{}.json'.format(epoch), 'w') as f:
f.write(chrome_trace)
self._msg += ' saving timeline & metadata'
else:
session.run([self._network.optimizer], feed_dict = feed_dict)
self._vprint(self._msg)
# Prediction: Scaled Train(ing results)
PST = session.run(self._network.predictions,
feed_dict = {self._network.samples: training_inputs.reshape(-1,1,1024,1),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.pred_keep_prob : 1.,
self._network.is_training : False})
train_feed_dict = {self._network.samples: training_inputs.reshape(-1,1,1024,1),
self._network.targets: training_targets.reshape(-1,1),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.pred_keep_prob : 1.,
self._network.image_buf: self.gen_plot(PST, training_targets, itx),
self._network.is_training : False}
training_MISG, training_MSE, training_PWT, training_summary = session.run([self._network.MISG,
self._network.MSE,
self._network.PWT,
self._network.summary],
feed_dict = train_feed_dict)
training_writer.add_summary(training_summary, epoch)
training_writer.flush()
# Prediction: Scaled test(ing results)
PST = session.run(self._network.predictions,
feed_dict = {self._network.samples: testing_inputs.reshape(-1,1,1024,1),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.pred_keep_prob : 1.,
self._network.is_training : False})
test_feed_dict = {self._network.samples: testing_inputs.reshape(-1,1,1024,1),
self._network.targets: testing_targets.reshape(-1,1),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.pred_keep_prob : 1.,
self._network.image_buf: self.gen_plot(PST,testing_targets, itx),
self._network.is_training : False}
testing_MISG, testing_MSE, testing_PWT, testing_summary = session.run([self._network.MISG,
self._network.MSE,
self._network.PWT,
self._network.summary],
feed_dict = test_feed_dict)
testing_writer.add_summary(testing_summary, epoch)
testing_writer.flush()
MISGs.append((training_MISG, testing_MISG))
MSEs.append((training_MSE, testing_MSE))
PWTs.append((training_PWT, testing_PWT))
if (epoch + 1) % self.model_save_interval == 0:
saver.save(session, self._model_save_location, epoch)
except KeyboardInterrupt:
pass
self._msg += '\rtraining ended'; self._vprint(self._msg)
training_writer.close()
testing_writer.close()
session.close()
self._msg += ' - session closed'; self._vprint(self._msg)
self._metrics = [MISGs, MSEs, PWTs]
self.save_metrics()
<file_sep>/aas/Estimating Delays/nn/__init__.py
from networks import *
from network_trainers import *
from data_creation import *
<file_sep>/aas/Estimating Delays/nn/data_creation/Data_Creator_BC.py
# Data_Creator_BC
from data_manipulation import *
from Data_Creator import Data_Creator
import numpy as np
class Data_Creator_BC(Data_Creator):
"""Creates data in an alternate thread. BC for binary classifier.
look at labels variable in _gen_data()
## usage:
## data_maker = Data_Creator_BC(num_flatnesses=250, mode = 'train')
## data_maker.gen_data() #before loop
## inputs, targets = data_maker.get_data() #start of loop
## data_maker.gen_data() #immediately after get_data()
"""
def __init__(self,
num_flatnesses,
bl_data = None,
bl_dict = None,
gains = None,
abs_min_max_delay = 0.040):
"""
Arguments
num_flatnesses : int - number of flatnesses used to generate data.
Number of data samples = 60 * num_flatnesses
bl_data : data source. Output of get_seps_data()
bl_dict : dict - Dictionary of seps with bls as keys. An output of get_or_gen_test_train_red_bls_dicts()
gains : dict - Gains for this data. An output of load_relevant_data()
"""
Data_Creator.__init__(self,
num_flatnesses = num_flatnesses,
bl_data = bl_data,
bl_dict = bl_dict,
gains = gains,
abs_min_max_delay = abs_min_max_delay)
def _gen_data(self):
# scaling tools
# the NN likes data in the range (0,1)
angle_tx = lambda x: (np.asarray(x) + np.pi) / (2. * np.pi)
angle_itx = lambda x: np.asarray(x) * 2. * np.pi - np.pi
delay_tx = lambda x: (np.array(x) + self._tau) / (2. * self._tau)
delay_itx = lambda x: np.array(x) * 2. * self._tau - self._tau
targets = np.random.uniform(low = -self._tau, high = self._tau, size = (self._num * 60, 1))
applied_delay = np.exp(-2j * np.pi * (targets * self._nu + np.random.uniform()))
assert type(self._bl_data) != None, "Provide visibility data"
assert type(self._bl_dict) != None, "Provide dict of baselines"
assert type(self._gains) != None, "Provide antenna gains"
if self._bl_data_c == None:
self._bl_data_c = {key : self._bl_data[key].conjugate() for key in self._bl_data.keys()}
if self._gains_c == None:
self._gains_c = {key : self._gains[key].conjugate() for key in self._gains.keys()}
def _flatness(seps):
"""Create a flatness from a given pair of seperations, their data & their gains."""
a, b = seps[0][0], seps[0][1]
c, d = seps[1][0], seps[1][1]
return self._bl_data[seps[0]] * self._gains_c[(a,'x')] * self._gains[(b,'x')] * \
self._bl_data_c[seps[1]] * self._gains[(c,'x')] * self._gains_c[(d,'x')]
inputs = []
for _ in range(self._num):
unique_baseline = random.sample(self._bl_dict.keys(), 1)[0]
two_seps = [random.sample(self._bl_dict[unique_baseline], 2)][0]
inputs.append(_flatness(two_seps))
inputs = np.angle(np.array(inputs).reshape(-1,1024) * applied_delay)
permutation_index = np.random.permutation(np.arange(self._num * 60))
labels = [[1,0] if d >=0 else [0,1] for d in targets[permutation_index]]
self._epoch_batch.append((angle_tx(inputs[permutation_index]), labels))
<file_sep>/aas/Estimating Delays/nn/data_creation/data_manipulation.py
"""data_manipulation
Collection of data helper files
"""
import numpy as np
from pyuvdata import UVData
import hera_cal as hc
import random
from threading import Thread
from glob import glob
import os
def load_relevant_data(miriad_path, calfits_path):
"""Loads redundant baselines, gains, and data.
Arguments:
miriad_path (str): path to a miriad file for some JD
calfits_path (str): path to a calfits file for the same JD
Returns:
red_bls, gains, uvd
"""
# read the data
uvd = UVData()
uvd.read_miriad(miriad_path)
# get the redundancies for that data
aa = hc.utils.get_aa_from_uv(uvd)
info = hc.omni.aa_to_info(aa)
red_bls = np.array(info.get_reds())
# gains for same data
gains, _ = hc.io.load_cal(calfits_path)
return red_bls, gains, uvd
def get_good_red_bls(red_bls, gain_keys, min_group_len = 4):
"""get_good_red_bls
Select all the good antennas from red_bls
Each baseline group in red_bls will have its bad separations removed.
Groups with less than min_group_len are removed.
Arguments:
red_bls (list of lists of tuples of ints)
- Each sublist is a group of redundant separations for a unique baseline.
gain_keys (dict): gains.keys() from hc.io.load_cal()
min_group_len (int, optional): Minimum number of separations in a 'good' sublist.
- Default = 4, so that both training and testing can take two seps)
Returns:
list of lists: Each sublist is a len >=4 list of separations of good antennas
"""
def ants_good(sep):
"""ants_good
Returns True if both antennas are good.
Because we are using data from firstcal
(is this right? I have trouble rememebring the names
and properties of the different data sources)
we can check for known good or bad antennas by looking to see if the antenna
is represented in gains.keys(). If the antenna is present, its good.
Arguments:
sep (tuple of ints): antenna indices
Returns:
bool: True if both antennas are in gain_keys else False
"""
ants = [a[0] for a in gain_keys]
if sep[0] in ants and sep[1] in ants:
return True
else:
return False
good_redundant_baselines = []
for group in red_bls:
new_group = []
for sep in group:
# only retain seps made from good antennas
if ants_good(sep) == True:
new_group.append(sep)
new_group_len = len(new_group)
# make sure groups are large enough that both the training set
# and the testing set can take two seps
if new_group_len >= min_group_len:
good_redundant_baselines.append(sorted(new_group))
return good_redundant_baselines
def _train_test_split_red_bls(red_bls, training_percent = 0.80):
"""_train_test_split_red_bls
Split a list of redundant baselines into a training set and a testing set.
Each of the two sets has at least one pair of baselines from every group from red_bls.
However, separations from one set will not appear the other.
Arguments:
red_bls (list of lists): Each sublist is a group of redundant separations
for a unique baseline.
Each sublist must have at least 4 separations.
training_percent (float, optional): - *Approximate* portion of the separations that will
appear in the training set.
Returns:
dict, dict :train_red_bls_dict, test_red_bls_dict
"""
training_redundant_baselines_dict = {}
testing_redundant_baselines_dict = {}
# make sure that each set has at least 2 seps from each group
#
thinned_groups_dict = {}
for group in red_bls:
# group key is the sep with the lowest antenna indicies
key = sorted(group)[0]
# pop off seps from group and append them to train or test groups
random.shuffle(group)
training_group = []
training_group.append(group.pop())
training_group.append(group.pop())
testing_group = []
testing_group.append(group.pop())
testing_group.append(group.pop())
# add the new train & test groups into the dicts
training_redundant_baselines_dict[key] = training_group
testing_redundant_baselines_dict[key] = testing_group
# if there are still more seps in the group, save them into a dict for later assignment
if len(group) != 0:
thinned_groups_dict[key] = group
# Shuffle and split the group keys into two sets using
#
thinned_dict_keys = thinned_groups_dict.keys()
random.shuffle(thinned_dict_keys)
# Because we are ensuring that each set has some seps from every group,
# the ratio of train / test gets reduced a few percent.
# This (sort of) accounts for that with an arbitrary shift found by trial and error.
#
# Without this the a setting of training_percent = 0.80 results in a 65/35 split, not 80/20.
#
# I assume there is a better way...
t_pct = np.min([0.95, training_percent + 0.15])
# these 'extra' keys are the keys that each set will extract seps from thinned_groups_dict with
training_red_bls_extra, testing_red_bls_extra = np.split(thinned_dict_keys,
[int(len(thinned_dict_keys)*t_pct)])
# extract seps from thinned_groups_dict and apply to same key in training set
for key in training_red_bls_extra:
key = tuple(key)
group = thinned_groups_dict[key]
training_group = training_redundant_baselines_dict[key]
training_group.extend(group)
training_redundant_baselines_dict[key] = training_group
# extract seps from thinned_groups_dict and apply to same key in testing set
for key in testing_red_bls_extra:
key = tuple(key)
group = thinned_groups_dict[key]
testing_group = testing_redundant_baselines_dict[key]
testing_group.extend(group)
testing_redundant_baselines_dict[key] = testing_group
return training_redundant_baselines_dict, testing_redundant_baselines_dict
def _loadnpz(filename):
"""_loadnpz
Loads up npzs. For dicts do loadnpz(fn)[()]
Args:
filename (str): path to npz to load
Returns:
numpy array: the data in the npz
"""
a = np.load(filename)
d = dict(zip(("data1{}".format(k) for k in a), (a[k] for k in a)))
return d['data1arr_0']
def get_or_gen_test_train_red_bls_dicts(red_bls = None,
gain_keys = None,
training_percent = 0.80,
training_load_path = None,
testing_load_path = None):
"""get_or_gen_test_train_red_bls_dicts
Create or generate baseline dicts for training and testing
Args:
red_bls (list of lists of tuples of ints): List of redundant baselines
gain_keys (list of int): antenna gains
training_percent (float, optional): Approximate portion of data to assign as training data
training_load_path (None, optional): Path to prepared dict of baselines
testing_load_path (None, optional): Path to prepared dict of baselines
Returns:
dict, dict: training_red_bls_dict, testing_red_bls_dict
"""
training_fn = 'data/training_redundant_baselines_dict_{}'.format(int(100*training_percent))
testing_fn = 'data/testing_redundant_baselines_dict_{}'.format(int(100*training_percent))
if training_load_path != None and testing_load_path != None:
training_red_bls_dict = _loadnpz(training_load_path)[()]
testing_red_bls_dict = _loadnpz(testing_load_path)[()]
else:
# if the files exist dont remake them.
if os.path.exists(training_fn + '.npz') and os.path.exists(testing_fn + '.npz'):
training_red_bls_dict = _loadnpz(training_fn + '.npz')[()]
testing_red_bls_dict = _loadnpz(testing_fn + '.npz')[()]
else:
assert type(red_bls) is not None, "Provide a list of redundant baselines"
assert type(gain_keys) is not None, "Provide a list of gain keys"
good_red_bls = get_good_red_bls(red_bls, gain_keys)
training_red_bls_dict, testing_red_bls_dict = _train_test_split_red_bls(good_red_bls,
training_percent = training_percent)
np.savez(training_fn, training_red_bls_dict)
np.savez(testing_fn, testing_red_bls_dict)
return training_red_bls_dict, testing_red_bls_dict
def get_seps_data(red_bls_dict, uvd):
"""get_seps_data
Get the data for all the seps in a redundant baselines dictionary.
Args:
red_bls_dict (dict): leys are unique baselines, values are tuples of antenna indicies
uvd (pyuvdata.UVData:
Returns:
dict: keys are separations (int, int), values are complex visibilitoes
"""
data = {}
for key in red_bls_dict.keys():
for sep in red_bls_dict[key]:
data[sep] = uvd.get_data(sep)
return data
<file_sep>/aas/Estimating Delays/nn/networks/__init__.py
from RestoreableComponent import RestoreableComponent
from CNN_DS_BN_R import CNN_DS_BN_R
from CNN_DS_BN_C import CNN_DS_BN_C
from CNN_DS_BN_BC import CNN_DS_BN_BC
from CNN_DSFC_BN_R import CNN_DSFC_BN_R
from CNN_QP_BN_R import CNN_QP_BN_R
from FNN_BN_R import FNN_BN_R<file_sep>/aas/Estimating Delays/nn/data_creation/__init__.py
from data_manipulation import *
from Data_Creator_C import Data_Creator_C
from Data_Creator_R import Data_Creator_R
from Data_Creator_BC import Data_Creator_BC
from Data_Creator_BC_Odd_Even import Data_Creator_BC_Odd_Even
<file_sep>/aas/Estimating Delays/estdel/setup.py
from setuptools import setup
setup(name='estdel',
version='0.0.1',
description='Estimate interferometer anteanna delays',
url='https://github.com/andrewasheridan/hera_sandbox/tree/master/aas/Estimating%20Delays/estdel',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
package_dir = {'estdel' : 'estdel'},
packages=['estdel'],
install_requires=[
'numpy>=1.2',
'tensorflow>=1.8.0',
],
zip_safe=False,
include_package_data=True)
# AIPY/BLOB/V3 SETUP.PY from import to the function<file_sep>/aas/Estimating Delays/nn/networks/RestoreableComponent.py
"""RestoreableComponent
"""
from pprint import pprint
import numpy as np
import sys
import os
class RestoreableComponent(object):
"""RestoreableComponent
Allows saving / loading of object parameters.
Excludes saving / loading of parameters begining with '_' or parameters that refer to tensorflow objects.
Used for networks and network-trainers to ease recordkeeping.
Args:
name (str): Name of the object
log_dir (str, optional): location to store object parameters.
verbose (bool, optional): Be verbose
Methods:
print_params(): Print the parameters for the object
save_params(): Saves parameters in log_dir/name/params/object_class.npz
load_params(path): Loads parameters from path into existing object
- Retains the name of the existing object
Attributes:
log_dir (str): store params in log_dir/params/CLASS_NAME
name (str): Name of object
"""
def __init__(self, name, log_dir = 'logs/', verbose = True):
"""__init__
Args:
name (str): Name of object
log_dir (str, optional): store params in log_dir/params/CLASS_NAME
verbose (bool, optional): Be verbose
"""
self.name = name
self.log_dir = log_dir
self._vprint = sys.stdout.write if verbose else lambda *a, **k: None # for verbose printing
self._msg = ''
def _gen_params_dict(self):
"""_gen_params_dict
Generate dict of class attributes.
Excludes parameters begininning with '_' or parameters that refer to tensorflow objects.
Returns:
dict: keys are attribute names, values are their values
"""
d = self.__dict__
return {key : d[key] for key in d.keys() if key[0] != '_' if 'tensorflow' not in str(type(d[key]))}
def print_params(self):
"""Prints restoreable parameters"""
pprint(self._gen_params_dict())
def load_params(self, path):
"""load_params
Load in parameters from npz file.
Do not include the .npz suffix in path
Keeps the current object name.
Args:
path (str): path to restoreabale parameters
"""
self._msg = '\rloading parameters';self._vprint(self._msg)
a = np.load(path + '.npz')
d = dict(zip(("data1{}".format(k) for k in a), (a[k] for k in a)))
name = self.name
params = d['data1arr_0'][()]
for key in params:
setattr(self, key, params[key])
self.name = name
self._msg = '\rparams loaded';self._vprint(self._msg)
def save_params(self, direc = None):
"""save_params
Saves the restoreable parameters.
Setting direc will override the default location of log_dir/params/
Args:
direc (str, optional): storeage directory
"""
self._msg += '\rsaving parameters';self._vprint(self._msg)
direc = self.log_dir + self.name + '/params/' if direc is None else direc
if not os.path.exists(direc):
self._msg += '- creating new directory';self._vprint(self._msg)
os.makedirs(direc)
np.savez(direc + self.__class__.__name__, self._gen_params_dict())
self._msg += ' - params saved';self._vprint(self._msg)<file_sep>/nsk/scripts/source_extract.py
#!/usr/bin/env python2.7
"""
source_extract.py
========
get image statistics of FITS file(s)
on a specific source
"""
import astropy.io.fits as fits
from astropy import modeling as mod
import argparse
import os
import sys
import shutil
import glob
import numpy as np
import scipy.stats as stats
a = argparse.ArgumentParser(description="Get FITS image statistics around source at center of image")
a.add_argument("files", type=str, nargs='*', help="filename(s) or glob-parseable string of filename(s)")
a.add_argument("--source", type=str, help="source name, with a <source>.loc file in working directory")
a.add_argument("--radius", type=float, default=2, help="radius in degrees around estimated source position to get source peak")
a.add_argument("--rms_max_r", type=float, default=None, help="max radius in degrees around source to make rms calculation")
a.add_argument("--rms_min_r", type=float, default=None, help="min radius in degrees around source to make rms calculation")
a.add_argument("--outdir", type=str, default=None, help="output directory")
a.add_argument("--ext", type=str, default=".spectrum.tab", help='extension string for spectrum file')
a.add_argument("--overwrite", default=False, action='store_true', help='overwite output')
a.add_argument("--gaussfit_mult", default=1.0, type=float, help="gaussian fit mask area is gaussfit_mult * synthesized_beam")
def source_extract(imfile, source, radius=1, gaussfit_mult=1.0, rms_max_r=None, rms_min_r=None, **kwargs):
# open fits file
hdu = fits.open(imfile)
# get header and data
head = hdu[0].header
data = hdu[0].data.squeeze()
# determine if freq precedes stokes in header
if head['CTYPE3'] == 'FREQ':
freq_ax = 3
stok_ax = 4
else:
freq_ax = 4
stok_ax = 3
# get axes info
npix1 = head["NAXIS1"]
npix2 = head["NAXIS2"]
nstok = head["NAXIS{}".format(stok_ax)]
nfreq = head["NAXIS{}".format(freq_ax)]
# calculate beam area in degrees^2
beam_area = (head["BMAJ"] * head["BMIN"] * np.pi / 4 / np.log(2))
# calculate pixel area in degrees ^2
pixel_area = np.abs(head["CDELT1"] * head["CDELT2"])
Npix_beam = beam_area / pixel_area
# get ra dec coordiantes
ra_axis = np.linspace(head["CRVAL1"]-head["CDELT1"]*head["NAXIS1"]/2, head["CRVAL1"]+head["CDELT1"]*head["NAXIS1"]/2, head["NAXIS1"])
dec_axis = np.linspace(head["CRVAL2"]-head["CDELT2"]*head["NAXIS2"]/2, head["CRVAL2"]+head["CDELT2"]*head["NAXIS2"]/2, head["NAXIS2"])
RA, DEC = np.meshgrid(ra_axis, dec_axis)
# get source coordinates
ra, dec = np.loadtxt('{}.loc'.format(source), dtype=str)
ra, dec = map(float, ra.split(':')), map(float,dec.split(':'))
ra = (ra[0] + ra[1]/60. + ra[2]/3600.) * 15
dec = (dec[0] + np.sign(dec[0])*dec[1]/60. + np.sign(dec[0])*dec[2]/3600.)
# get radius coordinates
R = np.sqrt((RA - ra)**2 + (DEC - dec)**2)
# select pixels
select = R < radius
# get peak brightness within pixel radius
peak = np.max(data[select])
# get rms outside of pixel radius
if rms_max_r is not None and rms_max_r is not None:
rms_select = (R < rms_max_r) & (R > rms_min_r)
rms = np.sqrt(np.mean(data[select]**2))
else:
rms = np.sqrt(np.mean(data[~select]**2))
# get peak error
peak_err = rms / np.sqrt(Npix_beam / 2.0)
# get frequency of image
freq = head["CRVAL3"]
## fit a 2D gaussian and get integrated and peak flux statistics ##
# recenter R array by peak flux point and get thata T array
peak_ind = np.argmax(data[select])
peak_ra = RA[select][peak_ind]
peak_dec = DEC[select][peak_ind]
X = (RA - peak_ra)
Y = (DEC - peak_dec)
R = np.sqrt(X**2 + Y**2)
X[np.where(np.isclose(X, 0.0))] = 1e-5
T = np.arctan(Y / X)
# use synthesized beam as data mask
ecc = head["BMAJ"] / head["BMIN"]
beam_theta = head["BPA"] * np.pi / 180 + np.pi/2
EMAJ = R * np.sqrt(np.cos(T+beam_theta)**2 + ecc**2 * np.sin(T+beam_theta)**2)
fit_mask = EMAJ < (head["BMAJ"] / 2 * gaussfit_mult)
masked_data = data.copy()
masked_data[~fit_mask] = 0.0
# fit 2d gaussian
gauss_init = mod.functional_models.Gaussian2D(peak, ra, dec, x_stddev=head["BMAJ"]/2, y_stddev=head["BMIN"]/2)
fitter = mod.fitting.LevMarLSQFitter()
gauss_fit = fitter(gauss_init, RA[fit_mask], DEC[fit_mask], data[fit_mask])
# get gaussian fit properties
peak_gauss_flux = gauss_fit.amplitude.value
P = np.array([X, Y]).T
beam_theta -= np.pi/2
Prot = P.dot(np.array([[np.cos(beam_theta), -np.sin(beam_theta)], [np.sin(beam_theta), np.cos(beam_theta)]]))
gauss_cov = np.array([[gauss_fit.x_stddev.value**2, 0], [0, gauss_fit.y_stddev.value**2]])
try:
model_gauss = stats.multivariate_normal.pdf(Prot, mean=np.array([0,0]), cov=gauss_cov)
model_gauss *= gauss_fit.amplitude.value / model_gauss.max()
int_gauss_flux = np.nansum(model_gauss.ravel()) / Npix_beam
except:
int_gauss_flux = 0
return peak, peak_err, rms, peak_gauss_flux, int_gauss_flux, freq
if __name__ == "__main__":
# parse args
args = a.parse_args()
# sort files
files = sorted(args.files)
# get filename
if args.outdir is None:
args.outdir = os.path.dirname(os.path.commonprefix(files))
output_fname = os.path.join(args.outdir, os.path.basename(os.path.splitext(os.path.commonprefix(files))[0] + args.ext))
if os.path.exists(output_fname) and args.overwrite is False:
raise IOError("file {} exists, not overwriting".format(output_fname))
# iterate over files
peak_flux = []
peak_flux_err = []
peak_gauss_flux = []
int_gauss_flux = []
freqs = []
for i, fname in enumerate(files):
output = source_extract(fname, **vars(args))
peak_flux.append(output[0])
peak_flux_err.append(output[2])
peak_gauss_flux.append(output[3])
int_gauss_flux.append(output[4])
freqs.append(output[5])
freqs = np.array(freqs)
peak_flux = np.array(peak_flux)
peak_flux_err = np.array(peak_flux_err)
peak_gauss_flux = np.array(peak_gauss_flux)
int_gauss_flux = np.array(int_gauss_flux)
data = np.vstack([freqs/1e6, peak_flux, peak_flux_err, peak_gauss_flux, int_gauss_flux]).T
# save spectrum
print("...saving {}".format(output_fname))
np.savetxt(output_fname, data, fmt="%8.5f", header="freqs (MHz)\t peak flux (Jy/beam)\t flux err\t peak gaussfit (Jy/beam)\t integ gaussfit (Jy)", delimiter='\t')
<file_sep>/aas/Estimating Delays/nn/networks/CNN_DS_BN_BC.py
# CNN_DS_BN_BC
import sys
import numpy as np
import tensorflow as tf
from CNN_DS_BN_C import CNN_DS_BN_C
class CNN_DS_BN_BC(CNN_DS_BN_C):
""" CNN_DS_BN_BC
Downsampling binary classifier
CNN: Convolutional Neural Network.
DS: DownSampling. Each convolution is followed by a downsampling convolution
BN: All non-linearalities have batch-normalization applied.
BC: Binary Classification, this network classifies samples of having one of two labels.
Each layer starts with a 1x3 convolution with 2**i filters (i = layer index) with stride of 1.
This is fed into a 1x5 convolution with the same number of filters, but stride of 2 (50% downsample)
Leaky_ReLU and batch normalization is applied after each convolution. Downsamples convolutions have dropout.
Biases are added before activations.
Output of last layer is fed to fully connected layer (with no activation)
Cost function is softmax cross entropy
"""
__doc__ += CNN_DS_BN_C.__doc__
def __init__(self,
name,
num_downsamples,
log_dir = '../logs/',
dtype = tf.float32,
adam_initial_learning_rate = 0.0001,
verbose = True):
CNN_DS_BN_C.__init__(self,
name=name,
num_downsamples=num_downsamples,
num_classes=2,
log_dir=log_dir,
dtype=dtype,
adam_initial_learning_rate=adam_initial_learning_rate,
verbose=verbose)
<file_sep>/aas/Estimating Delays/nn/network_trainers/CNN_BC_Trainer.py
# CNN_BC_Trainer
import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '../modules'))
from NN_Trainer import NN_Trainer
import tensorflow as tf
from tensorflow.python.client import timeline
import numpy as np
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import io
import itertools
class CNN_BC_Trainer(NN_Trainer):
def __init__(self,
network,
Data_Creator, # Class
num_epochs = 100,
batch_size = 32,
log_dir = '../logs/',
model_save_interval = 25,
pretrained_model_path = None,
metric_names = ['costs', 'accuracies'],
sample_keep_prob = 0.80,
conv_keep_prob = 0.9,
verbose = True,
class_names = ['pos', 'neg']):
NN_Trainer.__init__(self,
network = network,
Data_Creator = Data_Creator,
num_epochs = num_epochs,
batch_size = batch_size,
log_dir = log_dir,
model_save_interval = model_save_interval,
pretrained_model_path = pretrained_model_path,
metric_names = metric_names,
verbose = verbose)
self.sample_keep_prob = sample_keep_prob
self.conv_keep_prob = conv_keep_prob
self.class_names = class_names
def train(self):
self.save_params()
costs = []
accuracies = []
tf.reset_default_graph()
self._network.create_graph()
saver = tf.train.Saver()
with tf.Session() as session:
if self.pretrained_model_path == None:
session.run(tf.global_variables_initializer())
else:
saver.restore(session, self.pretrained_model_path)
archive_loc = self.log_dir + self._network.name
training_writer = tf.summary.FileWriter(archive_loc + '/training', session.graph)
testing_writer = tf.summary.FileWriter(archive_loc + '/testing', session.graph)
self.model_save_location = archive_loc + '/trained_model.ckpt'
self._msg = '\rtraining';self._vprint(self._msg)
try:
for epoch in range(self.num_epochs):
training_inputs, training_labels = self._train_batcher.get_data(); self._train_batcher.gen_data()
testing_inputs, testing_labels = self._test_batcher.get_data(); self._test_batcher.gen_data()
training_labels = np.asarray(training_labels)
testing_labels = np.asarray(testing_labels)
# if the division here has a remainde some values are just truncated
batch_size = self.batch_size
num_entries = training_inputs.shape[0]
for j in range(int(num_entries/batch_size)):
self._msg = '\repoch'
self._msg += '- {:5.0f}/{:5.0f}'.format(epoch + 1,self.num_epochs)
self._msg += ' - batch: {:4.0f}/{:4.0f}'.format(j + 1, int(num_entries/batch_size))
if epoch != 0:
self._msg += ' - (Training, Testing) - '.format(epoch)
self._msg += " costs: ({:0.4f}, {:0.4f})".format(training_cost, testing_cost)
self._msg += " accss: ({:2.2f}, {:2.2f})".format(training_acc, testing_acc)
self._vprint(self._msg);
training_inputs_batch = training_inputs[j*batch_size:(j + 1)*batch_size].reshape(-1,1,1024,1)
training_labels_batch = training_labels[j*batch_size:(j + 1)*batch_size].reshape(-1,2)
feed_dict = {self._network.X: training_inputs_batch,
self._network.labels: training_labels_batch,
self._network.sample_keep_prob : self.sample_keep_prob,
self._network.conv_keep_prob : self.conv_keep_prob,
self._network.is_training : True}
session.run([self._network.optimizer], feed_dict = feed_dict)
train_feed_dict = {self._network.X: training_inputs.reshape(-1,1,1024,1),
self._network.labels: training_labels.reshape(-1,2),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.is_training : False}
train_predicts = session.run([self._network.predictions], train_feed_dict)
train_feed_dict[self._network.image_buf] = self.plt_confusion_matrix(training_labels.reshape(-1,2), train_predicts)
training_cost, training_acc, training_summary = session.run([self._network.cost,
self._network.accuracy,
self._network.summary],
feed_dict = train_feed_dict)
training_writer.add_summary(training_summary, epoch)
training_writer.flush()
test_feed_dict = {self._network.X: testing_inputs.reshape(-1,1,1024,1),
self._network.labels: testing_labels.reshape(-1,2),
self._network.sample_keep_prob : 1.,
self._network.conv_keep_prob : 1.,
self._network.is_training : False}
test_predicts = session.run([self._network.predictions], test_feed_dict)
test_feed_dict[self._network.image_buf] = self.plt_confusion_matrix(testing_labels.reshape(-1,2), test_predicts)
testing_cost, testing_acc, testing_summary = session.run([self._network.cost,
self._network.accuracy,
self._network.summary],
feed_dict = test_feed_dict)
testing_writer.add_summary(testing_summary, epoch)
testing_writer.flush()
costs.append((training_cost, testing_cost))
accuracies.append((training_acc, testing_acc))
if (epoch + 1) % self.model_save_interval == 0:
saver.save(session, self.model_save_location, epoch + 1)
self.msg = ''
except KeyboardInterrupt:
self._msg = ' TRAINING INTERUPPTED' # this never prints I dont know why
pass
self._msg += '\rtraining ended'; self._vprint(self._msg)
training_writer.close()
testing_writer.close()
session.close()
self._msg += ' - session closed'; self._vprint(self._msg)
self._msg = ''
self._metrics = [costs, accuracies]
self.save_metrics()
def plt_confusion_matrix(self, labels, pred, normalize=False, title='Confusion matrix'):
"""
Given one-hot encoded labels and preds, displays a confusion matrix.
Arguments:
`labels`:
The ground truth one-hot encoded labels.
`pred`:
The one-hot encoded labels predicted by a model.
`normalize`:
If True, divides every column of the confusion matrix
by its sum. This is helpful when, for instance, there are 1000
'A' labels and 5 'B' labels. Normalizing this set would
make the color coding more meaningful and informative.
"""
labels = [label.argmax() for label in np.asarray(labels).reshape(-1,2)] # bc
pred = [label.argmax() for label in np.asarray(pred).reshape(-1,2)] #bc
classes = self.class_names
cm = confusion_matrix(labels, pred)
#if normalize:
cm = cm.astype('float')*100 / cm.sum(axis=1)[:, np.newaxis]
cm = np.nan_to_num(cm, copy=True)
cm = cm.astype('int')
fig, ax = plt.subplots(figsize = (5,5), dpi = 144)
im = ax.imshow(cm, interpolation='nearest', aspect='auto', cmap=plt.cm.Oranges, vmin = 0, vmax = 100)
ax.set_title(title)
cbar = fig.colorbar(im)
tick_marks = np.arange(len(classes))
ax.set_xticks(tick_marks)
ax.set_xticklabels(classes)
ax.set_yticks(tick_marks)
ax.set_yticklabels(classes)
ax.set_ylabel('True label')
ax.set_xlabel('Predicted label')
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
#s = '{:2.0}'.format(cm[i, j]) if cm[i,j] >= 1 else '.'
ax.text(j, i, format(cm[i, j], 'd') if cm[i,j]!=0 else '.',
horizontalalignment="center", fontsize=15, verticalalignment='center', color= "black")
# plt.show()
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi = 144)
plt.close(fig)
buf.seek(0)
return buf.getvalue()<file_sep>/aas/Estimating Delays/README.md
# Estimating Delays
## ML experiments for HERA RedCal
Can we use ML to aid redcal? We use tensorflow to find out.
See `wrap_unwrap_initial_exploration.ipynb` for a brief overview of the problem of computing cable delays from complex data.
## Prereqs
```
numpy
matplotlib
tensorflow
pyuvdata
hera_cal
```
- and all their prereqs
## Data
Data is built with NRAO IDR-2 miriad / firstcal files (is this description correct?).
Specific files used cover one ten minute window:
`zen_data/zen.2458098.58037.xx.HH.uv` &
`zen_data/zen.2458098.58037.xx.HH.uv.abs.calfits`
TODO: Add description of how data is manipulated. For now see `estdel/nn/data_manipulation.py`
## Directory Contents
`estdel/` - package for estimating delays
`experiments/` - Experiments in training different networks, solving Ax = b, and doing other things.<file_sep>/aas/Estimating Delays/estdel/estdel/estdel.py
"""estdel - for estimating delays
- <NAME> <EMAIL>
Estimate the overcall cable delay in visibility ratios.
For each list of 60 x 1024 complex visibility ratios produce 60 estimated cable delays.
Passes each row through one of (or both of) two trained neural networks.
Sign network classifies the sign of the delay as being positive or negative.
Magnitude network classfies the magnitude of the delay as being in one of 401 classes.
- 401 classes from 0.00 to 0.0400, each of width 0.0001
- default conversion to 401 classes from 0 to ~ 400 ns
VratioDelaySign estimates the sign of the delay (< 0 or >= 0)
VratioDelayMagnitude estimates the magnitude of the delay
VratioDelay provides Delay_Sign * Delay_Magnitude
tau = # slope in range -0.0400 to 0.0400
nu = np.arange(1024) # unitless frequency channels
phi = # phase in range 0 to 1
data = np.exp(-2j*np.pi*(nu*tau + phi))
estimator = estdel.VratioDelay(data)
prediction = estimator.predict()
# prediction should output tau
"""
import pkg_resources
import numpy as np
import tensorflow as tf
# suppress tensorflow INFO messages
tf.logging.set_verbosity(tf.logging.WARN)
_TRAINED_MODELS_DIR = 'trained_models'
# fn for best postive-negative classifier
_SIGN_PATH = 'sign_NN_frozen.pb'
# fn for best magnitude classifier
_MAG_PATH = 'mag_NN_frozen.pb'
# number of frequency channels
N_FREQS = 1024
class _DelayPredict(object):
"""_DelayPredict
Base class for predictions.
Data processing and predictions.
"""
def __init__(self, data):
"""__init__
Constants:
_n_freqs = 1024
Args:
data (list of complex floats): Visibliity data
"""
self._data = data
self._n_freqs = N_FREQS
assert(self._data.shape[-1] == self._n_freqs)
def _angle_tx(self, x):
"""_angle_tx
Scales (-pi, pi) to (0, 1)
Args:
x (numpy array of floats): Angle data in range -pi to pi
Returns:
numpy array of floats: scaled angle data
"""
return (x + np.pi) / (2. * np.pi)
def _preprocess_data(self):
"""_preprocess_data
Converts data from complex to real (angle), scales, and reshapes
Returns:
numpy array of floats: Scaled and reshaped angle data
"""
return self._angle_tx(np.angle(self._data)).reshape(-1,1,self._n_freqs,1)
def _predict(self):
"""_predict
Import frozen tensorflow network, activate graph,
feed data, and make prediction.
"""
resource_package = __name__
resource_path = '/'.join((_TRAINED_MODELS_DIR, self._model_path))
path = pkg_resources.resource_filename(resource_package, resource_path)
with tf.gfile.GFile(path, "rb") as f:
restored_graph_def = tf.GraphDef()
restored_graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(restored_graph_def, input_map=None, return_elements=None, name="")
sample_keep_prob = graph.get_tensor_by_name('keep_probs/sample_keep_prob:0')
conv_keep_prob = graph.get_tensor_by_name('keep_probs/conv_keep_prob:0')
is_training = graph.get_tensor_by_name('is_training:0')
X = graph.get_tensor_by_name('sample/X:0')
# add hook to output operation
pred_cls = graph.get_tensor_by_name('predictions/ArgMax:0')
with tf.Session(graph=graph) as sess:
feed_dict = {sample_keep_prob : 1.,
conv_keep_prob : 1.,
is_training : False,
X: self.data}
# collect prediction
self._pred_cls = sess.run(pred_cls, feed_dict = feed_dict)
sess.close()
class VratioDelaySign(_DelayPredict):
"""VratioDelaySign
Estimates visibility ratio cable delay sign by using two pretrained neural networks.
Methods:
predict()
- call to make sign prediction for data
Attributes:
data (numpy array of floats): Input data of redundant visibility ratios is processed for predictions
predictions (numpy array of floats): The converted raw magnitude predictions (see predict())
raw_predictions (list of floats): The raw magnitude predictions from the network
"""
def __init__(self, data):
"""__init__
Preprocesses data for prediction.
- converts complex data to angle
- scales angles to range preferred by networks
- reshapes 2D data to 4D tensor
Args:
data (list of complex): shape = (N, 1024)
- redundant visibility ratios
"""
_DelayPredict.__init__(self, data = data)
self.data = self._preprocess_data()
self._model_path = _SIGN_PATH
def _pred_cls_to_sign(self):
"""_pred_cls_to_sign
Convert index of predicted class index to value
1 if class is postive
-1 if class is negative
Returns:
list of ints:
"""
return [1 if x == 0 else -1 for x in self._pred_cls]
def predict(self):
"""predict
Returns:
numpy array of floats: sign predictions
"""
self._predict()
self.raw_predictions = self._pred_cls_to_sign()
self.predictions = np.array(self.raw_predictions)
return self.predictions
def _default_conversion_fn(x):
"""_default_conversion_fn
Convert unitless predictions to nanoseconds
Based on 1024 channels and
0.100 GHz - 0.200 GHz range
Args:
x (numpy array of floats): Predicted values in range 0.000 to 0.040
Returns:
numpy array of floats: Converted predicted value
"""
freqs = np.linspace(0.100,0.200,N_FREQS)
channel_width_in_GHz = np.mean(np.diff(freqs))
return np.array(x) / channel_width_in_GHz
class VratioDelayMagnitude(_DelayPredict):
"""VratioDelayMagnitude
Estimates visibility ratio total cable delay by using two pretrained neural networks.
Methods:
predict()
- call to make prediction
Attributes:
data (list of complex floats): Visibility ratios
predictions (numpy array of floats): The converted raw magnitude predictions (see predict())
raw_predictions (list of floats): The raw magnitude predictions from the network
"""
def __init__(self, data):
"""Preprocesses data for prediction.
- converts complex data to angle
- scales angles to range preferred by networks
- reshapes 2D data to 4D tensor
Args:
data (list of complex floats): shape = (N, 1024)
- redundant visibility ratios
"""
_DelayPredict.__init__(self, data = data)
self.data = self._preprocess_data()
self._model_path = _MAG_PATH
def _pred_cls_to_magnitude(self):
"""_pred_cls_to_magnitude
Convert predicted label index to magnitude
Returns:
list of floats: Magnitudes
"""
magnitudes = np.arange(0,0.04 + 0.0001, 0.0001)
return [magnitudes[x] for x in self._pred_cls]
def predict(self, conversion_fn='default'):
"""predict
Args:
conversion_fn (None, str, or function): - None - Do no conversion, output predictions are the raw predictions
- 'default' - convert raw predictions to ns by using frequencies
with a 100MHz range over 1024 channels
- OR provide your own function to do the conversion
- one required argument, the raw predictions
Returns:
numpy array of floats or list of floats: predictions
"""
self._conversion_fn = conversion_fn
self._predict()
self.raw_predictions = self._pred_cls_to_magnitude()
if self._conversion_fn is None:
self.predictions = self.raw_predictions
if self._conversion_fn == 'default':
self.predictions = _default_conversion_fn(self.raw_predictions)
else:
self.predictions = self._conversion_fn(self.raw_predictions)
return np.array(self.predictions)
class VratioDelay(object):
"""VratioDelay
Estimates visibility ratio total cable delay by using two pretrained neural networks.
Methods:
predict()
- call to make prediction
Attributes:
raw_predictions (list of floats): The raw predictions from the network
predictions (numpy array of floats or list of floats) = The converted raw predictions
"""
def __init__(self, data):
"""__init__
Preprocesses data for prediction.
- converts complex data to angle
- scales angles to range preferred by networks
- reshapes 2D data to 4D tensor
Args:
data (list of complex floats): shape = (N, 1024)
- redundant visibility ratios
"""
self._mag_evaluator = VratioDelayMagnitude(data)
self._sign_evaluator = VratioDelaySign(data)
def predict(self, conversion_fn='default'):
"""predict
Make predictions
Args:
conversion_fn (str, optional): Description
conversion_fn (None, 'default', or function
- None - Do no conversion, output predictions are the raw predictions
- 'default' - convert raw predictions to ns by using frequencies
with a 100MHz range over 1024 channels
- OR provide your own function to do the conversion
- takes in one argument, the raw predictions
Returns:
numpy array of floats or list of floats: Predicted values
"""
signs = self._sign_evaluator.predict()
mags = self._mag_evaluator.predict(conversion_fn=conversion_fn)
self.raw_predictions = [self._mag_evaluator.raw_predictions[i]*signs[i] for i in range(len(signs))]
self.predictions = signs*mags
return self.predictions
class DelaySolver(object):
"""DelaySolver
Args:
list_o_sep_pairs (list of lists of tuples): shape = (N, 2, 2)
ex: list_o_sep_pairs[0] = [(1, 2), (3, 4)]
each length 2 sublist is made of two redundant separations, one in each tuple
v_ratios (list of complex floats): shape = (N, 60, 1024)
Complex visibility ratios made from the the corresponding redundant sep pairs in list_o_sep_pairs
true_ant_delays (dict): dict of delays with antennas as keys,
ex : true_ant_delays[143] = 1.2
if conversion_fn == 'default', ant delays should be in ns
Attributes:
A (numpy array of ints): The matrix representing the redundant visibility ratios
b (numpy array of floats): A times x
unique_ants (numpy array of ints): All the unique antennas in list_o_sep_pairs
v_ratio_row_predictions (numpy array of floats or list of floats): Predicted values
v_ratio_row_predictions_raw (list of floats): Predicted values with no conversion
x (list floats): True delays in order of antenna
"""
def __init__(self,
list_o_sep_pairs,
v_ratios,
conversion_fn='default',
true_ant_delays={}, # dict {ant_idx : delay}
):
"""__init__
Preprocess data, make predictions, covert data to ns,
construct A matrix.
"""
self._list_o_sep_pairs = list_o_sep_pairs # shape = (N, 2, 2)
self._v_ratios = v_ratios # complex, shape = (N, 60, 1024) # will be reshaped to (-1, 1, 1024, 1)
self._true_ant_delays = true_ant_delays
self._conversion_fn = conversion_fn
self.unique_ants = np.unique(list_o_sep_pairs)
self._max_ant_idx = np.max(self.unique_ants) + 1
self._make_A_from_list_o_sep_pairs()
self._predictor = VratioDelay(v_ratios)
self._predictor.predict(conversion_fn=conversion_fn)
self.v_ratio_row_predictions = self._predictor.predictions
self.v_ratio_row_predictions_raw = self._predictor.raw_predictions
def _get_A_row(self, sep_pair):
"""_get_A_row
constructs a single row of A from a sep pair
Args:
sep_pair (tuple of ints): Antennas for this visibility
Returns;
list of ints: a row of A
"""
a = np.array(list(sum(sep_pair, () ))) # [(1,2) , (3, 4)] -> [1, 2, 3, 4]
# construct the row
# https://stackoverflow.com/a/29831596
# row is 4 x _max_ant_idx, all zeros
row = np.zeros((a.size, self._max_ant_idx), dtype = int)
# for each element in sep_pair, got to the corresponding row
# and assign the corresponding antenna the value 1
row[np.arange(a.size),a] = 1
# flip the sign of the middle two rows
row[1] *= -1
row[2] *= -1
# add the rows, row is now 1 x _max_ant_idx
row = np.sum(row, axis = 0)
return row
def _make_A_from_list_o_sep_pairs(self):
"""_make_A_from_list_o_sep_pairs
Construct A row by row
"""
self.A = []
for sep_pair in self._list_o_sep_pairs:
# each visibility ratio of height 60 has one sep_pair
# so make 60 idential rows in A for each visibility
# so that A is the correct shape
# (because the prediction will output a unique prediction
# for each row in the visibility ratio)
self.A.append(np.tile(self._get_A_row(sep_pair), (60,1)))
self.A = np.asarray(self.A).reshape(-1, self._max_ant_idx)
def true_b(self):
""" true_b
do A times x to find the true values for each visibility
where x is a list of the true antenna delays in order of antenna
Returns:
numpy array of floats
"""
self.x = [self._true_ant_delays[ant] for ant in self.unique_ants]
self.b = np.matmul(self.A[:, self.unique_ants], self.x)
return self.b
<file_sep>/aas/Estimating Delays/experiments/README.md
# experiments
The notebooks `CNN_*` and `FNN_*` are where I try training netowrks with different hyperparameters to see how they can learn the data.
`Classifier_Class_Explanation` is where I explain of how I convert this regression problem into a classification problem.
`Classification_Evaluator` is where I try see how well trained classifcation networks perform.
`Solver` is where I try to solve Ax=b<file_sep>/nsk/scripts/skynpz2calfits.py
#!/usr/bin/env python2.7
"""
skynpz2calfits.py
---------------
convert sky_image.py calibration
solution output in .npz format
(originally from CASA .cal/ tables)
into pyuvdata .calfits format
<NAME>
Dec. 2017
"""
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from pyuvdata import UVCal, UVData
import numpy as np
import argparse
import os
import scipy.signal as signal
from sklearn import gaussian_process as gp
import copy
import hera_cal as hc
a = argparse.ArgumentParser(description="Turn CASA calibration solutions in {}.npz files from sky_image.py script into .calfits files")
# Required Parameters
a.add_argument("--fname", type=str, help="output calfits filename.", required=True)
a.add_argument("--uv_file", type=str, help="Path to original miriad uv file of data.", required=True)
# Delay Solution Parameters
a.add_argument("--dly_files", type=str, default=None, nargs='*', help="Path to .npz file(s) with antenna delay output from sky_image.py (CASA K cal)")
a.add_argument("--TTonly", default=False, action="store_true", help="only store Tip-Tilt slopes of delay solution.")
a.add_argument("--plot_dlys", default=False, action="store_true", help="plot delay solutions across array.")
# Phase Solution Parameters
a.add_argument("--phs_files", type=str, default=None, nargs='*', help="Path to .npz file(s) with phase output from sky_image.py (CASA G phscal)")
a.add_argument("--plot_phs", default=False, action="store_true", help="plot phase solutions across array.")
# Amplitude Solution Parameters
a.add_argument("--amp_files", type=str, default=None, nargs='*', help="Path to .npz file(s) with amplitude output from sky_image.py (CASA G ampcal)")
a.add_argument("--plot_amp", default=False, action='store_true', help='plot amp solution across array.')
a.add_argument("--gain_amp_antavg", default=False, action='store_true', help="average gain amplitudes across antennas")
# Bandpass Solution Parameters
a.add_argument("--bp_files", type=str, default=None, nargs='*', help="Path to .npz file(s) with antenna complex bandpass output from sky_image.py (CASA bandpass)")
a.add_argument("--bp_flag_frac", type=float, default=0.5, help="at each freq bin, fraction of antennas flagged needed to broadcast flag to all ants.")
a.add_argument("--bp_broad_flags", default=False, action='store_true', help="broadcast flags at freq channels that satisfy bp_flag_frac")
a.add_argument("--noBPamp", default=False, action='store_true', help="set BP amplitude solutions to zero.")
a.add_argument("--noBPphase", default=False, action='store_true', help="set BP phase solutions to zero.")
a.add_argument('--bp_medfilt', default=False, action='store_true', help="median filter bandpass solutions")
a.add_argument('--medfilt_flag', default=False, action='store_true', help='use median filter to flag bad BP solutions in frequency')
a.add_argument('--medfilt_kernel', default=7, type=int, help="kernel size (channels) for BP median filter")
a.add_argument('--bp_amp_antavg', default=False, action='store_true', help="average bandpass amplitudes across antennas")
a.add_argument('--bp_TTonly', default=False, action='store_true', help="use only tip-tilt phase mode in bandpass solution")
a.add_argument('--plot_bp', default=False, action='store_true', help="plot final bandpass solutions")
a.add_argument('--bp_gp_smooth', default=False, action='store_true', help='smooth bandpass w/ gaussian process. Recommended to precede w/ bp_medfilt.')
a.add_argument('--bp_gp_max_dly', default=200.0, type=float, help="maximum delay in nanosec allowed for gaussian process fit")
a.add_argument('--bp_gp_nrestart', default=1, type=int, help='number of restarts for GP hyperparameter gradient descent.')
a.add_argument('--bp_gp_thin', default=2, type=int, help="thinning factor for freq bins in GP smooth fit")
# Misc
a.add_argument("--out_dir", default=None, type=str, help="output directory for calfits file. Default is working directory path")
a.add_argument("--overwrite", default=False, action="store_true", help="overwrite output calfits file if it exists")
a.add_argument("--multiply_gains", default=False, action="store_true", help="change gain_convention from divide to multiply.")
a.add_argument('--silence', default=False, action='store_true', help="silence output to stdout")
def echo(message, type=0, verbose=True):
if verbose:
if type == 0:
print(message)
elif type == 1:
print('\n{}\n{}'.format(message, '-'*40))
def skynpz2calfits(fname, uv_file, dly_files=None, amp_files=None, bp_files=None, out_dir=None, phs_files=None, overwrite=False,
TTonly=True, plot_dlys=False, plot_phs=False, gain_convention='multiply', plot_bp=False, noBPphase=False,
noBPamp=False, bp_TTonly=False, bp_medfilt=False, medfilt_kernel=5, bp_amp_antavg=False, bp_flag_frac=0.3,
bp_broad_flags=False, medfilt_flag=False, bp_gp_smooth=False, bp_gp_max_dly=500.0, bp_gp_nrestart=1, bp_gp_thin=2,
plot_amp=False, gain_amp_antavg=False, verbose=True):
"""
Convert *.npz output from sky_image.py into single-pol calfits file.
uv_file must be single-pol.
"""
# get out_dir
if out_dir is None:
out_dir = "./"
# load UVData
echo("...loading uv_file", verbose=verbose)
uvd = UVData()
uvd.read_miriad(uv_file)
# get ants and antpos
antpos, ants = uvd.get_ENU_antpos(center=True, pick_data_ants=True)
ants = list(ants)
# get freqs, times, jones
freqs = np.unique(uvd.freq_array)
times = np.unique(uvd.time_array)
Nfreqs = len(freqs)
Nants = len(ants)
jones = uvd.polarization_array
num2str = {-5: 'x', -6: 'y', -7: 'jxy', -8: 'jyx'}
str2num = {'x': -5, 'y': -6, 'jxy': -7, 'jyx': -8}
pols = np.array(map(lambda j: num2str[j], jones))
# construct blank gains and flags
gains = np.ones((Nants, Nfreqs, 1, 1), dtype=np.complex)
flags = np.zeros((Nants, Nfreqs, 1, 1), dtype=np.bool)
flagged_ants = np.zeros(Nants, dtype=np.bool)
# process delays if available
if dly_files is not None:
echo("...processing delays", verbose=verbose, type=1)
delays = np.zeros_like(ants, dtype=np.float)
delay_flags = np.zeros_like(ants, dtype=np.bool)
for dly_file in dly_files:
echo("...processing {}".format(dly_file))
# get CASA delays and antennas
dly_data = np.load(dly_file)
dly_ants = dly_data['delay_ants']
dlys = dly_data['delays']
dly_flags = dly_data['delay_flags']
dly_ants = dly_ants.tolist()
dlys *= 1e-9
# reorder antennas to be consistant w/ ants array
dlys = np.array(map(lambda a: dlys[dly_ants.index(a)] if a in dly_ants else 0.0, ants))
dly_flags = np.array(map(lambda a: dly_flags[dly_ants.index(a)] if a in dly_ants else True, ants))
# keep only limited information
if TTonly:
echo("...keeping only TT component of delays", verbose=verbose)
A = np.vstack([antpos[:, 0], antpos[:, 1]]).T
fit = np.linalg.pinv(A.T.dot(A)).dot(A.T).dot(dlys)
dlys = A.dot(fit)
# add to delay array
delays += dlys
delay_flags += dly_flags
flagged_ants += dly_flags
# turn into complex gains
dly_gains = np.exp(2j*np.pi*(freqs-freqs.min())*delays.reshape(-1, 1))[:, :, np.newaxis, np.newaxis]
dly_gain_flags = delay_flags[:, np.newaxis, np.newaxis, np.newaxis]
# multiply into gains
gains *= dly_gains
# add into flags
flags += dly_gain_flags
# process overall phase if available
if phs_files is not None:
echo("...processing gain phase", verbose=verbose, type=1)
phases = np.zeros_like(ants, dtype=np.float)
phase_flags = np.zeros_like(ants, dtype=np.bool)
for phs_file in phs_files:
echo("...processing {}".format(phs_file))
# get phase antennas and phases
phs_data = np.load(phs_file)
phs_ants = phs_data['phase_ants']
phs = phs_data['phases']
phs_flags = phs_data['phase_flags']
phs_ants = phs_ants.tolist()
# reorder to match ants
phs = np.array([phs[phs_ants.index(a)] if a in phs_ants else 0.0 for a in ants])
phs_flags = np.array(map(lambda a: phs_flags[phs_ants.index(a)] if a in phs_ants else True, ants))
# add to phases
phases += phs
phase_flags += phs_flags
flagged_ants += phs_flags
# construct gains
phase_gains = np.exp(1j * phases)
phase_gains = phase_gains[:, np.newaxis, np.newaxis, np.newaxis]
phase_gain_flags = phase_flags[:, np.newaxis, np.newaxis, np.newaxis]
# mult into gains
gains *= phase_gains
# add into flags
flags += phase_gain_flags
# process overall amplitude if available
if amp_files is not None:
echo("...processing gain amp", verbose=verbose, type=1)
amplitudes = np.ones_like(ants, dtype=np.float)
amplitude_flags = np.zeros_like(ants, dtype=np.bool)
for amp_file in amp_files:
echo("...processing {}".format(amp_file))
# get amp antenna and amps
amp_data = np.load(amp_file)
amp_ants = amp_data['amp_ants']
amps = amp_data['amps']
amp_flags = amp_data['amp_flags']
amp_ants = amp_ants.tolist()
# reorder to match ants
amps = np.array([amps[amp_ants.index(a)] if a in amp_ants else 1.0 for a in ants])
amp_flags = np.array(map(lambda a: amp_flags[amp_ants.index(a)] if a in amp_ants else True, ants))
# add to amplitudes
amplitudes *= amps
amplitude_flags += amp_flags
flagged_ants += amp_flags
# average across ants if desired
if gain_amp_antavg:
echo("...averaging antenna gain amplitudes", verbose=verbose)
avg_amp = np.median(amplitudes[~amplitude_flags])
amplitudes *= avg_amp / amplitudes
# construct gains
amplitude_gains = amplitudes
amplitude_gains = amplitude_gains[:, np.newaxis, np.newaxis, np.newaxis]
amplitude_flags = amplitude_flags[:, np.newaxis, np.newaxis, np.newaxis]
# mult into gains
gains *= amplitude_gains
# add into flags
flags += amplitude_flags
# process bandpass if available
if bp_files is not None:
echo("...processing bandpass", verbose=verbose, type=1)
for ii, bp_file in enumerate(bp_files):
echo("...processing {}".format(bp_file))
# get bandpass and form complex gains
bp_data = np.load(bp_file)
bp_freqs = bp_data['bp_freqs']
bp_Nfreqs = len(bp_freqs)
bandp_gains = bp_data['bp']
bandp_flags = bp_data['bp_flags']
bp_ants = bp_data['bp_ants'].tolist()
# reorder to match ants
bandp_gains = np.array([bandp_gains[:, bp_ants.index(a)].squeeze() if a in bp_ants else np.ones((bp_Nfreqs), dtype=np.complex) for a in ants])
bandp_flags = np.array([bandp_flags[:, bp_ants.index(a)].squeeze() if a in bp_ants else np.ones((bp_Nfreqs), dtype=np.bool) for a in ants])
# broadcast flags to all antennas at freq channels that satisfy bp_flag_frac
flag_broadcast = (np.sum(bandp_flags, axis=0) / float(bandp_flags.shape[0])) > bp_flag_frac
if bp_broad_flags:
bandp_flags += np.repeat(flag_broadcast.reshape(1, -1).astype(np.bool), Nants, 0)
# configure gains and flags shapes
bandp_gains = bandp_gains[:, :, np.newaxis, np.newaxis]
bandp_flags = bandp_flags[:, :, np.newaxis, np.newaxis]
if ii == 0:
bp_gains = bandp_gains
bp_flags = bandp_flags
else:
bp_gains *= bandp_gains
bp_flags += bandp_flags
# median filter if desired
if bp_medfilt or medfilt_flag:
echo("...median filtering", verbose=verbose)
bp_gains_medfilt = signal.medfilt(bp_gains.real, kernel_size=(1, medfilt_kernel, 1, 1)) + 1j*signal.medfilt(bp_gains.imag, kernel_size=(1, medfilt_kernel, 1, 1))
if medfilt_flag:
echo("...solving for BP flags w/ medfilt data")
# get residual and MAD from unfiltered and filtered data
residual = (np.abs(bp_gains) - np.abs(bp_gains_medfilt))
residual[bp_flags] *= np.nan
residual = residual.squeeze()
resid_std = np.nanmedian(np.abs(residual - np.nanmedian(residual, axis=1)[:, np.newaxis]), axis=1) * 1.5
# identify outliers as greater than 10-sigma
bad = np.array([np.abs(residual[i]) > resid_std[i]*10 for i in range(residual.shape[0])])
bp_flags += bad[:, :, np.newaxis, np.newaxis]
if bp_medfilt:
echo("...bandpass is the median filtered bandpass")
bp_gains = bp_gains_medfilt
# average amplitude across antenna if desired
if bp_amp_antavg:
echo("...averaging bandpass amplitude across antennas", verbose=verbose)
amp_avg = np.nanmedian(np.abs(bp_gains), axis=0).reshape(1, -1, 1, 1)
bp_gains *= amp_avg / np.abs(bp_gains)
# smooth bandpass w/ gaussian process if desired
if bp_gp_smooth:
echo("...smoothing with gaussian process", verbose=verbose)
freq_lambda = 1. / (bp_gp_max_dly*1e-3) # MHz
kernel = 1**2 * gp.kernels.RBF(freq_lambda + 10, (freq_lambda, 200.0)) + gp.kernels.WhiteKernel(1e-4, (1e-8, 1e0))
# configure data
X = bp_freqs / 1e6
bp_gains_real = []
bp_gains_imag = []
# iterate over antennas
for i, a in enumerate(ants):
if i % 10 == 0: echo("{}/{} ants".format(i, len(ants)), verbose=verbose)
# skip flagged ants
if np.min(bp_flags[i, :]):
bp_gains_real.append(np.ones_like(X.squeeze()))
bp_gains_imag.append(np.zeros_like(X.squeeze()))
continue
GP = gp.GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=bp_gp_nrestart)
xdata = X[~bp_flags[i].squeeze(), :][::bp_gp_thin]
yreal = bp_gains[i].squeeze()[~bp_flags[i].squeeze()][::bp_gp_thin].real
yimag = bp_gains[i].squeeze()[~bp_flags[i].squeeze()][::bp_gp_thin].imag
ydata = np.vstack([yreal, yimag]).T
ydata_med = np.median(ydata, axis=0)
ydata -= ydata_med
GP.fit(xdata, ydata)
ypred = GP.predict(X) + ydata_med
bp_gains_real.append(ypred[:, 0])
bp_gains_imag.append(ypred[:, 1])
# reconstruct bp gains
bp_gains = (np.array(bp_gains_real) + 1j*np.array(bp_gains_imag))[:, :, np.newaxis, np.newaxis]
# take only tip-tilt if desired
if bp_TTonly:
echo("...distilling bandpass to only tip-tilt phase", verbose=verbose)
# get bandpass phase array
bp_phs = np.angle(bp_gains).reshape(Nants, bp_Nfreqs)
# form least squares estimate of phase slopes along X and Y
A = np.vstack([antpos[:, 0], antpos[:, 1]]).T
fit = np.linalg.pinv(A.T.dot(A)).dot(A.T).dot(bp_phs)
# median filter
fit = signal.medfilt(fit, kernel_size=(1, 11))
# smooth across frequency via FFT
window = signal.windows.gaussian(fit.shape[1], fit.shape[1]/50.0)
fit_smooth = signal.fftconvolve(fit, window.reshape(1, -1), mode='same') / np.sum(window)
# make prediction to get tip-tilt estimates
bp_TT_phs = A.dot(fit_smooth).reshape(Nants, bp_Nfreqs, 1, 1)
# update bandpass gains
bp_gains *= np.exp(1j*bp_TT_phs - 1j*np.angle(bp_gains))
# suppress amp and/or phase if desired
if noBPamp:
echo("...eliminating BP amplitudes", verbose=verbose)
bp_gains /= np.abs(bp_gains)
if noBPphase:
echo("...eliminating BP phases", verbose=verbose)
bp_gains /= np.exp(1j*np.angle(bp_gains))
# mult into gains
bp_freq_select = np.array([np.argmin(np.abs(freqs-x)) for x in bp_freqs])
gains[:, bp_freq_select, :, :] *= bp_gains
flags[:, bp_freq_select, :, :] += bp_flags
bp_flagged_ants = np.min(bp_flags, axis=1).squeeze()
flagged_ants += bp_flagged_ants
# check filename
if fname.split('.')[-1] != "calfits":
fname += ".calfits"
# make into calfits
gain_dict = {}
flag_dict = {}
for i, a in enumerate(ants):
gain_dict[(a, pols[0])] = gains[i, :, :, 0].T
flag_dict[(a, pols[0])] = flags[i, :, :, 0].T
if flagged_ants[i]:
flag_dict[(a, pols[0])] += True
uvc = hc.io.write_cal(fname, gain_dict, freqs, times[:1], flags=flag_dict, outdir=out_dir,
overwrite=overwrite, gain_convention=gain_convention)
# plot dlys
if plot_dlys:
fig, ax = plt.subplots(1, figsize=(8,6))
ax.grid(True)
dly_max = np.max(np.abs(delays*1e9))
dly_min = -dly_max
for i, a in enumerate(ants):
if flagged_ants[i] == True:
continue
cax = ax.scatter(antpos[i, 0], antpos[i, 1], c=delays[i]*1e9, s=200, cmap='coolwarm', vmin=dly_min, vmax=dly_max)
ax.text(antpos[i,0]+1, antpos[i,1]+2, str(a), fontsize=12)
cbar = fig.colorbar(cax)
cbar.set_label("delay [nanosec]", size=16)
ax.set_xlabel("X [meters]", fontsize=14)
ax.set_ylabel("Y [meters]", fontsize=14)
ax.set_title("delay solutions for {}".format(os.path.basename(dly_files[0])), fontsize=10)
fig.savefig(dly_files[0]+'.png', dpi=100, bbox_inches='tight', pad=0.05)
plt.close()
# plot phs
if plot_phs:
fig, ax = plt.subplots(1, figsize=(8,6))
ax.grid(True)
phs_max = np.pi
phs_min = -np.pi
for i, a in enumerate(ants):
if flagged_ants[i] == True:
continue
cax = ax.scatter(antpos[i, 0], antpos[i, 1], c=phases[i], s=200, cmap='viridis', vmin=phs_min, vmax=phs_max)
ax.text(antpos[i,0]+1, antpos[i,1]+2, str(a), fontsize=12)
cbar = fig.colorbar(cax)
cbar.set_label("phase [radians]", size=16)
ax.set_xlabel("X [meters]", fontsize=14)
ax.set_ylabel("Y [meters]", fontsize=14)
ax.set_title("phase solutions for {}".format(os.path.basename(phs_files[0])), fontsize=10)
fig.savefig(phs_files[0]+'.png', dpi=100, bbox_inches='tight', pad=0.05)
plt.close()
# plot amp
if plot_amp:
fig, ax = plt.subplots(1, figsize=(8,6))
ax.grid(True)
amp_med = np.nanmedian(amplitudes[~amplitude_flags.squeeze()])
amp_std = np.std(amplitudes[~amplitude_flags.squeeze()])
amp_max = amp_med + amp_std * 2
amp_min = amp_med - amp_std * 2
for i, a in enumerate(ants):
if flagged_ants[i] == True:
continue
cax = ax.scatter(antpos[i, 0], antpos[i, 1], c=amplitudes[i], s=200, cmap='rainbow', vmin=amp_min, vmax=amp_max)
ax.text(antpos[i,0]+1, antpos[i,1]+2, str(a))
cbar = fig.colorbar(cax)
cbar.set_label("amplitude", size=16)
ax.set_xlabel("X [meters]", fontsize=14)
ax.set_ylabel("Y [meters]", fontsize=14)
ax.set_title("amplitude solutions for {}".format(os.path.basename(amp_files[0])), fontsize=10)
fig.savefig(amp_files[0]+'.png', dpi=100, bbox_inches='tight', pad=0.05)
plt.close()
# plot bandpass
if plot_bp:
fig, axes = plt.subplots(2, 1, figsize=(12,6))
fig.subplots_adjust(hspace=0.3)
# amplitude
ax = axes[0]
ax.grid(True)
bp_gains[bp_flags] *= np.nan
pls = []
bp_ant_select = []
ant_sort = np.argsort(ants)
for i, a in enumerate(np.array(ants)[ant_sort]):
if flagged_ants[ant_sort][i] == True:
continue
p, = ax.plot(bp_freqs / 1e6, np.abs(bp_gains).squeeze()[ants.index(a)], marker='.', ls='')
pls.append(p)
ax.set_xlabel("Frequency [MHz]", fontsize=12)
ax.set_ylabel("Amplitude", fontsize=12)
ax.set_title("bandpass for {}".format(bp_file), fontsize=10)
# phase
ax = axes[1]
ax.grid(True)
plot_ants = []
for i, a in enumerate(np.array(ants)[ant_sort]):
if flagged_ants[ant_sort][i] == True:
continue
plot_ants.append(a)
ax.plot(bp_freqs / 1e6, np.angle(bp_gains).squeeze()[ants.index(a)], marker='.', ls='')
ax.set_xlabel("Frequency [MHz]", fontsize=12)
ax.set_ylabel("Phase [radians]", fontsize=12)
lax = fig.add_axes([1.01, 0.1, 0.05, 0.8])
lax.axis('off')
lax.legend(pls, plot_ants, ncol=2)
fig.savefig(bp_file+'.png', dpi=100, bbox_inches='tight', pad=0.05)
plt.close()
if __name__ == "__main__":
args = a.parse_args()
gain_convention = 'divide'
if args.multiply_gains:
gain_convention = 'multiply'
kwargs = copy.copy(args).__dict__
kwargs.pop('fname')
kwargs.pop('uv_file')
kwargs.pop('multiply_gains')
kwargs['verbose'] = args.silence == False
kwargs.pop('silence')
kwargs['gain_convention'] = gain_convention
skynpz2calfits(args.fname, args.uv_file, **kwargs)
<file_sep>/aas/Estimating Delays/nn/network_trainers/NN_Trainer.py
import sys, os
from estdel.nn.networks import RestoreableComponent
# NN_Trainer
import matplotlib.pyplot as plt
import numpy as np
import os, io
class NN_Trainer(RestoreableComponent):
""" Parent for restoreable neural network trainer (does not include training method).
Add train method particular to network.
Args:
network - (one of the network classes from this repo) - The network to train
Data_Creator - (one of the Data_Creator_* classes from this repo) - Creates data..
num_epochs - (int) - Number of training epochs
batch_size - (int) - Number of samples in each batch
- Number of batches = int(number_of_samples/batch_size)
log_dir - (string) - Directory to store logs & parameters
model_save_interval - (int) - Save model every (this many) epochs
pretrained_model_path - (string) - Path to previously trained model
metric_names - (list of strings) - Names of the various metrics for this trainer
verbose - (bool) - Be verbose.
"""
__doc__ += RestoreableComponent.__doc__
def __init__(self,
network,
Data_Creator, # Class
num_epochs,
batch_size,
log_dir,
model_save_interval,
pretrained_model_path,
metric_names,
verbose = True):
RestoreableComponent.__init__(self, name=network.name, log_dir=log_dir, verbose=verbose)
self._network = network
self._Data_Creator = Data_Creator
self.num_epochs = num_epochs
self.batch_size = batch_size
self.model_save_interval = model_save_interval
self.pretrained_model_path = pretrained_model_path
self._metrics = [] # list of lists
self.metric_names = metric_names # list of strings, one per metric
def add_data(self,train_info, test_info, gains, num_flatnesses = 10, abs_min_max_delay = 0.040):
"""Adds data to the Trainer.
Args
train_info - (tuple : (visibility data, baselines dict)) - The training data
test_info - (tuple : (visibility data, baselines dict)) - The testing data
gains - (dict) - The gains for the visibilites
num_flatnesses - (int) - Number of flatnesses for each epoch
- Number of samples is num_flatnesses * 60
abs_min_max_delay - (float) - The absolute value of the min or max delay for this dataset.
"""
self._abs_min_max_delay = abs_min_max_delay
self._train_batcher = self._Data_Creator(num_flatnesses,
train_info[0],
train_info[1],
gains,
abs_min_max_delay)
self._train_batcher.gen_data()
self._test_batcher = self._Data_Creator(num_flatnesses,
test_info[0],
test_info[1],
gains,
abs_min_max_delay)
self._test_batcher.gen_data()
def save_metrics(self):
"""Saves the recorded metrics to disk"""
self._msg = '\rsaving metrics'; self._vprint(self._msg)
direc = self.log_dir + self._network.name + '/'
if not os.path.exists(direc): # should already exist by this point buuuuuut
self._msg += ' - creating new directory ';self._vprint(self._msg)
os.makedirs(direc)
np.savez(direc + 'metrics', self.get_metrics())
self._msg += ' - saved';self._vprint(self._msg)
def get_metrics(self):
"""Returns the recorded metrics (list of lists)"""
return {self.metric_names[i] : self._metrics[i] for i in range(len(self._metrics))}
def plot_metrics(self,figsize = (8,6) ):
"""Plots the recorded metrics"""
num_vals = np.min([len(metric) for metric in self._metrics])
xvals = np.arange(num_vals)
fig, axes = plt.subplots(len(self._metrics), 1, figsize = figsize, dpi = 144)
for i, ax in enumerate(axes.reshape(-1)):
if i == 0:
ax.set_title('{}'.format(self._network.name))
ax.plot(xvals[:num_vals], self._metrics[i][:num_vals], lw = 0.5)
ax.set_xlabel('Epoch')
ax.set_ylabel(self.metric_names[i])
plt.tight_layout()
plt.show()
def gen_plot(self, predicted_values, actual_values, itx):
"""Create a prediction plot and save to byte string. For tensorboard images tab."""
prediction_unscaled = itx(predicted_values)
actual_unscaled = itx(actual_values)
sorting_idx = np.argsort(actual_unscaled.T[0])
fig, ax = plt.subplots(figsize = (5, 3), dpi = 144)
ax.plot(prediction_unscaled.T[0][sorting_idx],
linestyle = 'none', marker = '.', markersize = 1,
color = 'darkblue')
ax.plot(actual_unscaled.T[0][sorting_idx],
linestyle = 'none', marker = '.', markersize = 1, alpha = 0.50,
color = '#E50000')
ax.set_title('std: %.9f' %np.std(prediction_unscaled.T[0][sorting_idx] - actual_unscaled.T[0][sorting_idx]))
buf = io.BytesIO()
fig.savefig(buf, format='png', dpi = 144)
plt.close(fig)
buf.seek(0)
return buf.getvalue()
<file_sep>/aas/Estimating Delays/estdel/README.md
# estdel
## Prereqs
```
numpy
tensorflow
```
<file_sep>/aas/Estimating Delays/nn/data_creation/Data_Creator_BC_Odd_Even.py
# Data_Creator_BC_Odd_Even
from data_manipulation import *
from Data_Creator import Data_Creator
import numpy as np
class Data_Creator_BC_Odd_Even(Data_Creator):
def __init__(self,
num_flatnesses,
bl_data = None,
bl_dict = None,
gains = None,
abs_min_max_delay = 0.040):
Data_Creator.__init__(self,
num_flatnesses = num_flatnesses,
bl_data = bl_data,
bl_dict = bl_dict,
gains = gains,
abs_min_max_delay = abs_min_max_delay)
def _gen_data(self):
# scaling tools
# the NN likes data in the range (0,1)
angle_tx = lambda x: (np.asarray(x) + np.pi) / (2. * np.pi)
angle_itx = lambda x: np.asarray(x) * 2. * np.pi - np.pi
delay_tx = lambda x: (np.array(x) + self._tau) / (2. * self._tau)
delay_itx = lambda x: np.array(x) * 2. * self._tau - self._tau
targets = np.random.uniform(low = -self._tau, high = self._tau, size = (self._num * 60, 1))
applied_delay = np.exp(-2j * np.pi * (targets * self._nu + np.random.uniform()))
assert type(self._bl_data) != None, "Provide visibility data"
assert type(self._bl_dict) != None, "Provide dict of baselines"
assert type(self._gains) != None, "Provide antenna gains"
if self._bl_data_c == None:
self._bl_data_c = {key : self._bl_data[key].conjugate() for key in self._bl_data.keys()}
if self._gains_c == None:
self._gains_c = {key : self._gains[key].conjugate() for key in self._gains.keys()}
def _flatness(seps):
"""Create a flatness from a given pair of seperations, their data & their gains."""
a, b = seps[0][0], seps[0][1]
c, d = seps[1][0], seps[1][1]
return self._bl_data[seps[0]] * self._gains_c[(a,'x')] * self._gains[(b,'x')] * \
self._bl_data_c[seps[1]] * self._gains[(c,'x')] * self._gains_c[(d,'x')]
inputs = []
for _ in range(self._num):
unique_baseline = random.sample(self._bl_dict.keys(), 1)[0]
two_seps = [random.sample(self._bl_dict[unique_baseline], 2)][0]
inputs.append(_flatness(two_seps))
inputs = np.angle(np.array(inputs).reshape(-1,1024) * applied_delay)
permutation_index = np.random.permutation(np.arange(self._num * 60))
# convert 0.0149 to 149 etc, for finding odd or even
rounded_targets = 10000*np.asarray([np.round(abs(np.round(d * 100,2)/100), 5) for d in targets[permutation_index]]).reshape(-1)
labels = [[1,0] if x%2 == 0 else [0,1] for x in rounded_targets]
self._epoch_batch.append((angle_tx(inputs[permutation_index]), labels))
<file_sep>/aas/Estimating Delays/nn/networks/FNN_BN_R.py
"""FNN_BN_R
"""
import sys, os
from RestoreableComponent import RestoreableComponent
import tensorflow as tf
import numpy as np
class FNN_BN_R(RestoreableComponent):
"""FNN_BN_R
A neural network of fully connected layers.
Attributes:
accuracy_threshold (float): the value for a target to be considered 'good'
adam_initial_learning_rate (float): Adam optimizer initial learning rate
cost (str): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
dtype (tensorflow obj): type used for all computations
fcl_keep_prob (tensorflow obj): keep prob for fully connected layers
gaussian_shift_scalar (float): value to shift gaussian for 'MISG' cost
image_buf (tensorflow obj): buffer for image summaries for tensorboard
is_training (tensorflow obj): flag for batch normalization
layer_nodes (list of ints): numbers of nodes in each layer
MISG (tensorflow obj): cost function, experimental. Mean Inverse Shifted Gaussian
MQE (tensorflow obj): cost function, experimental. Mean Quad Error
MSE (tensorflow obj): cost function. Mean Squared Error
optimizer (tensorflow obj): optimization function
predictions (tensorflow obj): predicted outputs
PWT (tensorflow obj): Percent of predictions within threshold
sample_keep_prob (tensorflow obj): keep prob for input samples
summary (tensorflow obj): summary operation for tensorboard
targets (tensorflow obj): true values for optimizer
X (tensorflow obj): input samples
"""
__doc__ += RestoreableComponent.__doc__
def __init__(self,
name,
layer_nodes,
cost = 'MSE',
log_dir = '../logs/',
dtype = tf.float32,
adam_initial_learning_rate = 0.0001,
accuracy_threshold = 0.00625,
gaussian_shift_scalar = 1e-5,
verbose = True):
"""__init__
Args:
name (str): name of network
layer_nodes (list of ints): numbers of nodes in each layer
cost (str, optional): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
log_dir (str, optional): Directory to store network model and params
dtype (tensorflow obj, optional): type used for all computations
adam_initial_learning_rate (float, optional): Adam optimizer initial learning rate
accuracy_threshold (float, optional): the value for a target to be considered 'good'
gaussian_shift_scalar (float, optional): value to shift gaussian for 'MISG' cost
verbose (bool, optional): Be verbose
"""
RestoreableComponent.__init__(self, name=name, log_dir=log_dir, verbose=verbose)
self.layer_nodes = layer_nodes
self.dtype = dtype
self.adam_initial_learning_rate = adam_initial_learning_rate
self.accuracy_threshold = accuracy_threshold
self.gaussian_shift_scalar = gaussian_shift_scalar
self.cost = cost
self._num_freq_channels = 1024
self._layers = []
self._num_outputs = 1 # Regression
def create_graph(self):
"""create_graph
Create the network graph for use in a tensorflow session
"""
self.save_params()
self._msg = '\rcreating network graph '; self._vprint(self._msg)
tf.reset_default_graph()
self.is_training = tf.placeholder(dtype = tf.bool, shape = [], name = 'is_training')
with tf.variable_scope('keep_probs'):
self._msg += '.'; self._vprint(self._msg)
self.sample_keep_prob = tf.placeholder(self.dtype, name = 'sample_keep_prob')
self.fcl_keep_prob = tf.placeholder(self.dtype, name = 'fcl_keep_prob')
with tf.variable_scope('sample'):
self._msg += '.'; self._vprint(self._msg)
self.X = tf.placeholder(self.dtype, shape = [None,self._num_freq_channels], name = 'X')
self.X = tf.nn.dropout(self.X, self.sample_keep_prob)
with tf.variable_scope('input_layer'):
b = tf.get_variable(name = 'biases', shape = [self.layer_nodes[0]],
initializer = tf.contrib.layers.xavier_initializer())
w = tf.get_variable(name = 'weights', shape = [1024, self.layer_nodes[0]],
initializer = tf.contrib.layers.xavier_initializer())
layer = tf.nn.leaky_relu(tf.matmul(self.X, w) + b)
layer = tf.contrib.layers.batch_norm(layer, is_training = self.is_training)
layer = tf.nn.dropout(layer, self.fcl_keep_prob)
self._layers.append(layer)
for i in range(len(self.layer_nodes)):
if i > 0:
with tf.variable_scope('layer_%d' %(i)):
layer = tf.contrib.layers.fully_connected(self._layers[i-1], self.layer_nodes[i])
layer = tf.contrib.layers.batch_norm(layer, is_training = self.is_training)
self._layers.append(layer)
self._msg += ' '
with tf.variable_scope('targets'):
self._msg += '.'; self._vprint(self._msg)
self.targets = tf.placeholder(dtype = self.dtype, shape = [None, self._num_outputs], name = 'labels')
with tf.variable_scope('predictions'):
self._msg += '.'; self._vprint(self._msg)
self.predictions = tf.contrib.layers.fully_connected(tf.layers.flatten(self._layers[-1]), self._num_outputs)
with tf.variable_scope('costs'):
self._msg += '.'; self._vprint(self._msg)
error = tf.subtract(self.targets, self.predictions, name = 'error')
squared_error = tf.square(error, name = 'squared_difference')
quad_error = tf.square(squared_error, name = 'quad_error' )
with tf.variable_scope('mean_inverse_shifted_gaussian'):
self._msg += '.'; self._vprint(self._msg)
normal_dist = tf.contrib.distributions.Normal(0.0, self.accuracy_threshold, name = 'normal_dist')
gaussian_prob = normal_dist.prob(error, name = 'gaussian_prob')
shifted_gaussian = tf.add(gaussian_prob, self.gaussian_shift_scalar, name = 'shifted_gaussian')
self.MISG = tf.reduce_mean(tf.divide(1.0, shifted_gaussian), name = 'mean_inverse_shifted_gaussian')
with tf.variable_scope('mean_squared_error'):
self._msg += '.'; self._vprint(self._msg)
self.MSE = tf.reduce_mean(squared_error / self.gaussian_shift_scalar)
with tf.variable_scope('mean_quad_error'):
self._msg += '.'; self._vprint(self._msg)
self.MQE = tf.reduce_mean(quad_error / self.gaussian_shift_scalar)
with tf.variable_scope('logging'):
with tf.variable_scope('image'):
self._msg += '.'; self._vprint(self._msg)
self.image_buf = tf.placeholder(tf.string, shape=[])
epoch_image = tf.expand_dims(tf.image.decode_png(self.image_buf, channels=4), 0)
with tf.variable_scope('percent_within_threshold'):
self._msg += '.'; self._vprint(self._msg)
self.PWT = 100.*tf.reduce_mean(tf.cast(tf.less_equal(tf.abs(self.targets - self.predictions), self.accuracy_threshold), self.dtype) )
tf.summary.histogram(name = 'targets', values = self.targets)
tf.summary.histogram(name = 'predictions',values = self.predictions)
tf.summary.scalar(name = 'MSE', tensor = self.MSE)
tf.summary.scalar(name = 'MISG', tensor = self.MISG)
tf.summary.scalar(name = 'MQE', tensor = self.MQE)
tf.summary.scalar(name = 'PWT', tensor = self.PWT)
tf.summary.image('prediction_vs_actual', epoch_image)
self.summary = tf.summary.merge_all()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
with tf.variable_scope('train'):
self._msg += '.'; self._vprint(self._msg)
if self.cost == 'MSE':
cost = self.MSE
if self.cost == 'MQE':
cost = tf.log(self.MQE)
if self.cost == 'MISG':
cost = self.MISG
if self.cost == 'PWT_weighted_MSE':
cost = self.MSE * (100. - self.PWT)
if self.cost == 'PWT_weighted_MISG':
cost = self.MISG * (100. - self.PWT)
self.optimizer = tf.train.AdamOptimizer(self.adam_initial_learning_rate, epsilon=1e-08).minimize(cost)
num_trainable_params = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])
self._msg = '\rNetwork Ready - {} trainable parameters'.format(num_trainable_params); self._vprint(self._msg)<file_sep>/aas/Estimating Delays/nn/networks/CNN_QP_BN_R.py
"""CNN_QP_BN_R
"""
import sys, os
from RestoreableComponent import RestoreableComponent
import tensorflow as tf
import numpy as np
class CNN_QP_BN_R(RestoreableComponent):
"""CNN_QP_BN_R
CNN: Convolutional neural network.
QP: Each computational layer is a quad-path layer.
BN: All non-linearalities have batch-normalization applied.
R: Regression, this network predicts a single value for each input.
Attributes:
accuracy (tensorflow obj): Running accuracy of predictions
adam_initial_learning_rate (float): Adam optimizer initial learning rate
conv_keep_prob (tensorflow obj): Keep prob rate for convolutions
cost (str): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
dtype (tensorflow obj): Type used for all computations
gaussian_shift_scalar (float): value to shift gaussian for 'MISG' cost
image_buf (tensorflow obj): buffer for image summaries for tensorboard
is_training (tensorflow obj): flag for batch normalization
layer_downsampling_factors (list of ints): factors to downsample each layer
MISG (tensorflow obj): cost function, experimental. Mean Inverse Shifted Gaussian
MSE (tensorflow obj): cost function. Mean Squared Error
num_1x1_conv_filters_per_layer (list of ints): number of 1x1 convolutions for each layer
num_freq_channels (int): Number of frequency channels
optimizer (tensorflow obj): optimization function
pred_keep_prob (TYPE): prediction keep prob
predictions (tensorflow obj): predicted outputs
PWT (tensorflow obj): Percent of predictions within threshold
sample_keep_prob (tensorflow obj): keep prob for input samples
samples (TYPE): input samples
summary (tensorflow obj): summary operation for tensorboard
targets (tensorflow obj): true values for optimizer
wide_convolution_filter_widths (list of ints): widths of each laters wide convolutions
"""
__doc__ += RestoreableComponent.__doc__
def __init__(self,
name,
wide_convolution_filter_widths,
layer_downsampling_factors,
num_1x1_conv_filters_per_layer,
log_dir = '../logs/',
dtype = tf.float32,
adam_initial_learning_rate = 0.0001,
cost = 'MSE',
accuracy_threshold = 0.00625,
gaussian_shift_scalar = 1e-5,
verbose = True):
"""__init__
Args:
name (str): name of network
wide_convolution_filter_widths (list of ints): widths of each laters wide convolutions
layer_downsampling_factors (list of ints): factors to downsample each layer
num_1x1_conv_filters_per_layer (list of ints): number of 1x1 convolutions for each layer
log_dir (str, optional): directory to store network model and params
dtype (tensorflow obj): Type used for all computations
adam_initial_learning_rate (tensorflow obj): Adam optimizer initial learning rate
cost (str): name of cost function. 'MSE', 'MQE', 'MISG', 'PWT_weighted_MSE', 'PWT_weighted_MISG'
- use 'MSE', others experimental
accuracy_threshold (float, optional): Threshold to count a prediction as being on target
gaussian_shift_scalar (float): value to shift gaussian for 'MISG' cost
verbose (bool, optional): be verbose
"""
RestoreableComponent.__init__(self, name=name, log_dir=log_dir, verbose=verbose)
self.wide_convolution_filter_widths = wide_convolution_filter_widths
self.layer_downsampling_factors = layer_downsampling_factors
self.dtype = dtype
self.adam_initial_learning_rate = adam_initial_learning_rate
self.cost = cost
self.accuracy_threshold = accuracy_threshold
self.gaussian_shift_scalar = gaussian_shift_scalar
self.num_1x1_conv_filters_per_layer = num_1x1_conv_filters_per_layer
self.num_freq_channels = 1024
def create_graph(self):
"""create_graph
Create the network graph for use in a tensorflow session
"""
self.save_params()
self._msg = '\rcreating network graph '; self._vprint(self._msg)
tf.reset_default_graph()
self.is_training = tf.placeholder(dtype = tf.bool, name = 'is_training', shape = [])
with tf.variable_scope('keep_probs'):
self._msg += '.'; self._vprint(self._msg)
self.sample_keep_prob = tf.placeholder(self.dtype, name = 'sample_keep_prob')
self.conv_keep_prob = tf.placeholder(self.dtype, name = 'conv_keep_prob')
self.pred_keep_prob = tf.placeholder(self.dtype, name = 'pred_keep_prob')
with tf.variable_scope('samples'):
self._msg += '.'; self._vprint(self._msg)
self.samples = tf.placeholder(self.dtype, shape = [None, 1, self.num_freq_channels, 1], name = 'samples')
self.samples = tf.nn.dropout(self.samples, self.sample_keep_prob)
self._layers = []
num_layers = len(self.wide_convolution_filter_widths)
layer_names = ['layer_{}'.format(i) for i in range(num_layers)]
for i in range(num_layers):
self._msg += '.'; self._vprint(self._msg)
# previous layer is input for current layer
layer = self.samples if i == 0 else self._layers[i - 1]
layer = Quad_Path_Layer(layer,
layer_names[i],
self.wide_convolution_filter_widths[i],
self.layer_downsampling_factors[i],
self.num_1x1_conv_filters_per_layer[i],
self.conv_keep_prob,
self.is_training,
self.dtype)
layer = layer.process()
self._layers.append(layer)
with tf.variable_scope('prediction'):
self._msg += '.'; self._vprint(self._msg)
reshaped_final_layer = tf.contrib.layers.flatten(self._layers[-1])
reshaped_final_layer = tf.nn.dropout(reshaped_final_layer, self.pred_keep_prob)
prediction_weight = tf.get_variable(name = 'weight',
shape = [reshaped_final_layer.get_shape()[-1], 1],
dtype = self.dtype,
initializer = tf.contrib.layers.xavier_initializer())
self.predictions = tf.matmul(reshaped_final_layer, prediction_weight)
with tf.variable_scope('targets'):
self._msg += '.'; self._vprint(self._msg)
self.targets = tf.placeholder(dtype = self.dtype, shape = [None, 1], name = 'targets')
with tf.variable_scope('costs'):
self._msg += '.'; self._vprint(self._msg)
error = tf.subtract(self.targets, self.predictions, name = 'error')
squared_error = tf.square(error, name = 'squared_difference')
with tf.variable_scope('mean_inverse_shifted_gaussian'):
self._msg += '.'; self._vprint(self._msg)
normal_dist = tf.contrib.distributions.Normal(0.0, self.accuracy_threshold, name = 'normal_dist')
gaussian_prob = normal_dist.prob(error, name = 'gaussian_prob')
shifted_gaussian = tf.add(gaussian_prob, self.gaussian_shift_scalar, name = 'shifted_gaussian')
self.MISG = tf.reduce_mean(tf.divide(1.0, shifted_gaussian), name = 'mean_inverse_shifted_gaussian')
with tf.variable_scope('mean_squared_error'):
self._msg += '.'; self._vprint(self._msg)
self.MSE = tf.reduce_mean(squared_error)
with tf.variable_scope('logging'):
with tf.variable_scope('image'):
self._msg += '.'; self._vprint(self._msg)
self.image_buf = tf.placeholder(tf.string, shape=[])
epoch_image = tf.expand_dims(tf.image.decode_png(self.image_buf, channels=4), 0)
with tf.variable_scope('percent_within_threshold'):
self._msg += '.'; self._vprint(self._msg)
self.PWT = 100.*tf.reduce_mean(tf.cast(tf.less_equal(tf.abs(self.targets - self.predictions), self.accuracy_threshold), self.dtype) )
tf.summary.histogram(name = 'targets', values = self.targets)
tf.summary.histogram(name = 'predictions',values = self.predictions)
tf.summary.scalar(name = 'MSE', tensor = self.MSE)
tf.summary.scalar(name = 'MISG', tensor = self.MISG)
tf.summary.scalar(name = 'PWT', tensor = self.PWT)
tf.summary.image('prediction_vs_actual', epoch_image)
self.summary = tf.summary.merge_all()
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
with tf.variable_scope('train'):
self._msg += '.'; self._vprint(self._msg)
if self.cost == 'MSE':
cost = self.MSE
if self.cost == 'MISG':
cost = self.MISG
if self.cost == 'PWT_weighted_MSE':
cost = self.MSE * (100. - self.PWT)
if self.cost == 'PWT_weighted_MISG':
cost = self.MISG * (100. - self.PWT)
self.optimizer = tf.train.AdamOptimizer(self.adam_initial_learning_rate, epsilon=1e-08).minimize(cost)
num_trainable_params = np.sum([np.prod(v.get_shape().as_list()) for v in tf.trainable_variables()])
self._msg = '\rNetwork Ready - {} trainable parameters'.format(num_trainable_params); self._vprint(self._msg)
class Quad_Path_Layer(object):
"""A layer for a convolutional network. Layer is made of four paths: Average, Max, Wide, Narrow.
Average - Average pool followed by a 1x1 convolution.
Max - Max pool followed by a 1x1 convolution.
Wide - 1x1 convolution followed by 1xWide convoltuion.
Narrow - 1x1 convolution followed 1x(Wide/2) convolution.
Attributes:
conv_keep_prob (float): keep prob for convolutions
dtype (tensorflow obj): type used for all computations
is_training (tensorflow obj): flag for batch normalization
layer_name (str): name of layer
num_1x1_conv_filters (int): Number of 1x1 convolution filters
strides (list of ints): stride for this layer
t (tensor): tensor to process
wide_convolution_filter_width (int): Width of the wide convolution filter
"""
def __init__(self,
t,
layer_name,
wide_convolution_filter_width,
layer_downsampling_factor,
num_1x1_conv_filters = 4,
conv_keep_prob = 0.90,
is_training = True,
dtype = tf.float32):
"""Summary
Args:
t (tensor): tensor to process
layer_name (str): name of layer
wide_convolution_filter_width (int): Width of the wide convolution filter
layer_downsampling_factor (int): Factor to downsample by
num_1x1_conv_filters (int, optional): Number of 1x1 convolution filters
conv_keep_prob (float, optional): keep prob for convolutions
is_training (bool, optional): flag for batch normalization
dtype (tensorflow obj, optional): type used for all computations
"""
self.t = t
self.layer_name = layer_name
self.wide_convolution_filter_width = wide_convolution_filter_width
self.strides = [1,1,layer_downsampling_factor, 1]
self.num_1x1_conv_filters = num_1x1_conv_filters
self.conv_keep_prob = conv_keep_prob
self.is_training = is_training
self.dtype = dtype
def process(self):
"""process
Creates the quad path layer
Returns:
tensor: concatenated filtes after processing
"""
with tf.variable_scope(self.layer_name):
narrow_convolution_filter_width = self.wide_convolution_filter_width / 2
num_narrow_conv_filters = np.max([self.num_1x1_conv_filters / 2, 2])
num_wide_conv_filters = np.max([num_narrow_conv_filters / 2, 1])
path_A = self._avg_scope()
path_B = self._max_scope()
path_C_and_D = self._1x1_conv(self.t)
path_C = self._conv_scope(path_C_and_D,
[1,
narrow_convolution_filter_width,
path_C_and_D.get_shape().as_list()[3],
num_narrow_conv_filters],
self.strides,
scope_name = 'narrow')
path_D = self._conv_scope(path_C_and_D,
[1,
self.wide_convolution_filter_width,
path_C_and_D.get_shape().as_list()[3],
num_wide_conv_filters],
self.strides,
scope_name = 'wide')
t = self._filter_cat_scope([path_A, path_B, path_C, path_D])
return t
def _trainable(self, name, shape):
"""_trainable
Wrapper for tensorflow.get_variable(), xavier initialized
Args:
name (str): name of variable
shape (int or list of ints): shape for vairable
Returns:
tensorflow obj: trainable variable
"""
return tf.get_variable(name = name,
dtype = self.dtype,
shape = shape,
initializer = tf.contrib.layers.xavier_initializer())
def _bias_add_scope(self, t, shape):
"""_bias_add_scope
Creates a scope around a trainable bias and its addition to input
Args:
t (tensor): tensor to add biases to
shape (int): number of biases to add
Returns:
tensor: tensor with biases added to it
"""
with tf.variable_scope('add_bias'):
biases = self._trainable('biases', shape)
t = tf.nn.bias_add(t, biases)
return t
def _conv_scope(self,t, filter_shape, strides, scope_name = 'convolution'):
"""_conv_scope
Creates a scope around a convolution layer.
t = dropout( batch_norm( relu( conv2d(t) + bias )))
Args:
t (tensor): tensor to process
filter_shape (list of ints): Shape of convolution filters
strides (list of ints): Convolution strides
scope_name (str, optional): name of scope (for graph organization)
Returns:
tensor: processed tensor
"""
with tf.variable_scope(scope_name):
t = tf.nn.conv2d(t, self._trainable('filters', filter_shape),strides,'SAME')
t = self._bias_add_scope(t, [filter_shape[-1]])
t = tf.nn.relu(t)
t = tf.contrib.layers.batch_norm(t, is_training = self.is_training)
t = tf.nn.dropout(t, self.conv_keep_prob)
return t
def _1x1_conv(self, t):
"""_1x1_conv
1x1 convolution with strides = 1 and num_1x1_conv_filters filters
Args:
t (tensor): tensor to convolve
Returns:
tensor: convolved tensor
"""
return self._conv_scope(t,
[1,1,t.get_shape().as_list()[3],self.num_1x1_conv_filters],
[1,1,1,1],
"1x1_conv")
def _avg_scope(self):
"""_avg_scope
Creates a scope around the average-pool path.
Returns:
tensor: tensor after average pool and 1x1 convolution
"""
with tf.variable_scope('average'):
t = tf.nn.avg_pool(self.t, self.strides, self.strides, padding = "SAME")
t = self._1x1_conv(t)
return t
def _max_scope(self):
"""_max_scope
Creates a scope around the max-pool path
Returns:
tensor: tensor after max pool and 1x1 convolution
"""
with tf.variable_scope('max'):
t = tf.nn.max_pool(self.t, self.strides, self.strides, padding = "SAME")
t = self._1x1_conv(t)
return t
def _filter_cat_scope(self,t_list):
"""_filter_cat_scope
Creates a scope around filter concatation (layer output)
Args:
t_list (list of tensors): filters to concatenate
Returns:
tensor: concatenated tensors
"""
with tf.variable_scope('filter_cat'):
t = tf.concat(t_list, 3)
return t | b67a1b1e8b9c027ad3456866803fee8298408da2 | [
"Markdown",
"Python"
] | 29 | Python | andrewasheridan/hera_sandbox | 8af4f1f91d47121577a1eb8d16d1bc530bf6a671 | 216a112ebc365d62bb113fba6a9bc9523921faad | |
refs/heads/master | <file_sep>using PaginaTridentto.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PaginaTridentto.Controllers
{
public class SeguridadController : Controller
{
private string _strMensaje;
// GET: Seguridad
public ActionResult Index()
{
ViewBag.Error = "";
ViewBag.mensaje = "";
return View();
}
[HttpPost]
public ActionResult Index(Usuario modelo)
{
/*Validamos si tiene datos para cargar*/
if (string.IsNullOrEmpty(modelo.StrEmail) & string.IsNullOrEmpty(modelo.StrNombre) & string.IsNullOrEmpty(modelo.StrPassword))
{
ViewBag.Error = "Debe de ingresar los datos correctamenta";
}
else
{
var vc = new Clases.SeguridadDao();
var res = vc.AddUsuario(modelo, out _strMensaje);
if (res)
{
ViewBag.mensaje = _strMensaje;
}
else
{
ViewBag.Error = _strMensaje;
}
}
return View();
}
public ActionResult ValidarUser(string usuario,string password)
{
var vc = new Clases.SeguridadDao();
var datos = vc.ValidarUsuario(usuario, password, out _strMensaje);
if (datos != null)
{
Session["idUsuario"] = datos.Id;
Session["usuario"] = datos.StrUsuario;
Session["nombre"] = datos.StrNombre;
Session["email"] = datos.StrEmail;
Session["grupo"] = datos.IdGrupo;
if (datos != null)
{
return Json(new
{
datos = datos
});
}
else
{
return Json(new
{
Error = _strMensaje
});
}
}
else
{
return Json(new
{
Error = _strMensaje
});
}
}
public ActionResult Cuentas()
{
/*Validamos si esta logueado si no lo redireccionamos al login*/
string usuario = Session["usuario"].ToString();
if (usuario != "")
{
/*Cargamos los paise*/
/*Cargamos Los Departamentos Primero*/
var vc = new Clases.MaestrosDao();
var paises = vc.ListaPaises();
var dpt = vc.ListaDepartamentos();
ViewData["paises"] = paises;
ViewData["departamentos"] = dpt;
ViewBag.usuario = Session["usuario"].ToString();
ViewBag.nombre = Session["nombre"].ToString();
return View();
}
else
{
return RedirectToAction("Index", "Seguridad");
}
/*Fin*/
}
[HttpPost]
public ActionResult AddOtrosDatosUsuario(DatosComplemenatriosUsuario modelo)
{
var vc = new Clases.MaestrosDao();
var paises = vc.ListaPaises();
var dpt = vc.ListaDepartamentos();
ViewData["paises"] = paises;
ViewData["departamentos"] = dpt;
ViewBag.usuario = Session["usuario"].ToString();
ViewBag.nombre = Session["nombre"].ToString();
/*Actualizamos la informacion*/
Int64 idUsuario =Convert.ToInt64(Session["idUsuario"]);
modelo.IdUsuario = idUsuario;
var res = vc.AddDatosComplementariosUsuario(modelo, out _strMensaje);
if (res)
{
return Json(new
{
mensaje = _strMensaje
});
}
else
{
return Json(new
{
Error = _strMensaje
});
}
}
public ActionResult ConsultaOtrosDatosUsuario(Int64 idUsuario)
{
var vc = new Clases.MaestrosDao();
var datos = vc.ConsultaOtrosDatosUsuario(idUsuario);
if (datos != null)
{
return Json(new
{
xdato = datos
});
}
else
{
return Json(new
{
xdato = string.Empty
});
}
}
public ActionResult CambioPassword()
{
return View();
}
[HttpPost]
public ActionResult CambioPassword(string passNew,string passConfirmar)
{
var vc = new Clases.SeguridadDao();
var validar = passNew.Equals(passConfirmar);
if (!validar)
{
return Json(new
{
Error = "Los dos Pasword no coinciden"
});
}
else
{
Int64 idUsuario = Convert.ToInt64(Session["idUsuario"]);
var res = vc.CambioPassword(idUsuario, passNew, out _strMensaje);
if (res)
{
return Json(new
{
mensaje = _strMensaje
});
}
else
{
return Json(new
{
Error = _strMensaje
});
}
}
}
public ActionResult Direcciones()
{
return View();
}
public ActionResult OrdenesUsuario()
{
return View();
}
[HttpPost]
public ActionResult Ciudades(int id)
{
var vc = new Clases.MaestrosDao();
var lista = vc.ListaCiudades(id);
if (lista != null)
{
return Json(new
{
xlista=lista
});
}
else
{
return Json(new
{
Error = "No hay datos para cargar"
});
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Models
{
public class pedidos_modelo
{
}
public class Pagos
{
public int merchantId { get; set; }
/*Numero de la Factura o cedula del comprador*/
public string referenceCode { get; set; }
public string description { get; set; }
/*Valor de la comra*/
public double amount { get; set; }
/*Iva*/
public int tax { get; set; }
/*Base para liquidar el iva*/
public double taxReturnBase { get; set; }
/*Llave Publica*/
public string signature { get; set; }
public int accountId { get; set; }
/*Moneda*/
public string currency { get; set; }
/*Nombre del comprador*/
public string buyerFullName { get; set; }
/*Email*/
public string buyerEmail { get; set; }
/*Direccion de entrega de la mercancia*/
public string shippingAddress { get; set; }
/*Ciudad de Entrega*/
public string shippingCity { get; set; }
/*Pais de Entrega*/
public string shippingCountry { get; set; }
/*Telefono del Comprador*/
public string telephone { get; set; }
}
}
<file_sep>using MySql.Data.MySqlClient;
using PaginaTridentto.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Clases
{
public class MaestrosDao
{
private DataHelper _dataHelper;
public MaestrosDao()
{
_dataHelper = new DataHelper();
}
public List<Paises> ListaPaises()
{
try
{
var dt = _dataHelper.EjecutarSp<DataTable>("ma_spListaPaises", null);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
var lista = new List<Paises>();
for (int i = 0; i < dt.Rows.Count; i++)
{
lista.Add(new Paises { Id = Convert.ToInt16(dt.Rows[i]["id"]), StrNombre = dt.Rows[i]["strNombre"].ToString() });
}
return lista;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
public List<Departamentos> ListaDepartamentos()
{
try
{
var dt = _dataHelper.EjecutarSp<DataTable>("ma_spListaDepartamentos", null);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
var listado = new List<Departamentos>();
for (int i = 0; i < dt.Rows.Count; i++)
{
listado.Add(new Departamentos { Id = Convert.ToInt16(dt.Rows[i]["id"]), StrNombre = dt.Rows[i]["strNombre"].ToString() });
}
return listado;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
public List<Ciudades> ListaCiudades(int idDepartamento)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("dtp",idDepartamento)
};
var dt = _dataHelper.EjecutarSp<DataTable>("ma_spCiudades", parametros);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
var lista = new List<Ciudades>();
for (int i = 0; i < dt.Rows.Count; i++)
{
lista.Add(new Ciudades { Id = Convert.ToInt16(dt.Rows[i]["id"]),IdDepartamento= Convert.ToInt16(dt.Rows[i]["iddpt"]),StrNombre=dt.Rows[i]["strNombre"].ToString() });
}
return lista;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
public bool AddDatosComplementariosUsuario(DatosComplemenatriosUsuario modelo,out string strMensaje)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("usuario",modelo.IdUsuario),
new MySqlParameter("pais",modelo.IdPais),
new MySqlParameter("departamento",modelo.IdDepartamento),
new MySqlParameter("ciudad",modelo.IdCiudad),
new MySqlParameter("telefono",modelo.StrTelefono),
new MySqlParameter("mobil",modelo.StrMobil)
};
var mensaje = new MySqlParameter("mensaje", MySqlDbType.VarChar, 100) { Direction = ParameterDirection.Output };
var log_respuesta = new MySqlParameter("log_respuesta", MySqlDbType.Bit) { Direction = ParameterDirection.Output };
parametros.Add(mensaje);
parametros.Add(log_respuesta);
var res = _dataHelper.EjecutarSp<int>("sg_spAddDatosComplementariosUsuario", parametros);
if (res >= 0)
{
strMensaje = mensaje.Value.ToString();
return Convert.ToBoolean(log_respuesta.Value);
}
else
{
strMensaje = "No hay conexion con el servidor";
return false;
}
}
catch (Exception ex)
{
strMensaje = ex.Message;
return false;
}
}
public DatosComplemenatriosUsuario ConsultaOtrosDatosUsuario(Int64 idUsuario)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("usuario",idUsuario)
};
var dt = _dataHelper.EjecutarSp<DataTable>("sg_spConsultaOtros_Datos", parametros);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
var datos = new DatosComplemenatriosUsuario();
datos.IdUsuario = Convert.ToInt64(dt.Rows[0]["idUsuario"]);
datos.IdPais = Convert.ToInt16(dt.Rows[0]["idPais"]);
datos.IdDepartamento = Convert.ToInt16(dt.Rows[0]["idDepartamento"]);
datos.IdCiudad = Convert.ToInt16(dt.Rows[0]["idCiudad"]);
datos.StrTelefono = dt.Rows[0]["strTelefonoFijo"].ToString();
datos.StrMobil = dt.Rows[0]["strMobil"].ToString();
return datos;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Models
{
public class Maestros
{
}
public class Paises
{
public int Id { get; set; }
public string StrNombre { get; set; }
}
public class Departamentos
{
public int Id { get; set; }
public string StrNombre { get; set; }
}
public class Ciudades
{
public int Id { get; set; }
public int IdDepartamento { get; set; }
public string StrNombre { get; set; }
}
public class DatosComplemenatriosUsuario
{
public Int64 IdUsuario { get; set; }
public int IdPais { get; set; }
public int IdDepartamento { get; set; }
public int IdCiudad { get; set; }
public string StrTelefono { get; set; }
public string StrMobil { get; set; }
}
}
<file_sep>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Clases
{
public class DataHelper
{
private MySqlConnection _connection;
private bool _connection_open;
public DataHelper()
{
}
public T EjecutarSp<T>(string spName, List<MySqlParameter> parametros)
{
GetConnection();
try
{
var cmd = new MySqlCommand(spName, _connection) { CommandType = System.Data.CommandType.StoredProcedure };
cmd.CommandTimeout = 0;
if (parametros != null)
{
cmd.Parameters.AddRange(parametros.ToArray());
}
//Validamos el tipo de dato a retornar
if (typeof(T) == typeof(DataSet))
{
var ds = new DataSet();
using (var adapter = new MySqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
return (T)(Object)ds;
}
if (typeof(T) == typeof(DataTable))
{
var dt = new DataTable();
using (var adapter = new MySqlDataAdapter(cmd))
{
adapter.Fill(dt);
}
return (T)(Object)dt;
}
if (typeof(T) == typeof(MySqlDataReader))
{
var reader = cmd.ExecuteReader();
return (T)(Object)reader;
}
if (typeof(T) == typeof(int))
{
var entero = cmd.ExecuteNonQuery();
return (T)(Object)entero;
}
if (typeof(T) == typeof(bool))
{
bool retorno = Convert.ToBoolean(cmd.ExecuteNonQuery());
return (T)(Object)retorno;
}
else
{
throw new NotSupportedException(string.Format("El tipo {0} no es soportado", typeof(T).Name));
}
}
finally
{
if (_connection_open == true)
{
_connection.Close();
_connection_open = false;
}
}
}
private void GetConnection()
{
_connection_open = false;
_connection = new MySqlConnection();
_connection.ConnectionString = Properties.Settings.Default.conexion_datos;
if (Open_Local_Connection())
{
_connection_open = true;
}
}
private bool Open_Local_Connection()
{
try
{
_connection.Open();
return true;
}
catch (Exception)
{
return false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PaginaTridentto.Controllers
{
public class PedidosController : Controller
{
// GET: Pedidos
public ActionResult Index()
{
return View();
}
public ActionResult Pago()
{
return View();
}
public ActionResult Carro_Compras()
{
return View();
}
public ActionResult ConfirmarDireccion()
{
return View();
}
public ActionResult AddProducto()
{
return View();
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PaginaTridentto.Controllers
{
public class MaestrosController : Controller
{
// GET: Maestros
public ActionResult Index()
{
return View();
}
public ActionResult Productos()
{
return View();
}
}
}<file_sep>using MySql.Data.MySqlClient;
using PaginaTridentto.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Clases
{
public class SeguridadDao
{
private DataHelper _dataHelper;
public SeguridadDao()
{
_dataHelper = new DataHelper();
}
public bool AddUsuario(Usuario modelo,out string strMensaje)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("usuario",modelo.StrEmail),
new MySqlParameter("password",modelo.StrPassword),
new MySqlParameter("nombre",modelo.StrNombre),
new MySqlParameter("grupo",5),
new MySqlParameter("email",modelo.StrEmail)
};
var mensaje = new MySqlParameter("mensaje", MySqlDbType.VarChar, 100) { Direction = ParameterDirection.Output };
var log_respuesta = new MySqlParameter("log_respuesta", MySqlDbType.Bit) { Direction = ParameterDirection.Output };
parametros.Add(mensaje);
parametros.Add(log_respuesta);
var res = _dataHelper.EjecutarSp<int>("sg_spAddUsuario", parametros);
if (res >= 0)
{
strMensaje = mensaje.Value.ToString();
return Convert.ToBoolean(log_respuesta.Value);
}
else
{
strMensaje = "La operación no se pudo realizar no hay conexion xon el servidor";
return false;
}
}
catch (Exception ex)
{
strMensaje = ex.Message;
return false;
}
}
public Usuario ValidarUsuario(string usuario,string password,out string strMensaje)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("usuario",usuario),
new MySqlParameter("password",<PASSWORD>)
};
var dt = _dataHelper.EjecutarSp<DataTable>("sg_spValidar_Usuario", parametros);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
var log_respuesta = Convert.ToBoolean(dt.Rows[0]["logRespuesta"]);
if (log_respuesta)
{
var datos = new Usuario();
datos.Id = Convert.ToInt64(dt.Rows[0]["id"]);
datos.StrUsuario = dt.Rows[0]["strUsuario"].ToString();
datos.StrNombre = dt.Rows[0]["strNombre"].ToString();
datos.IdGrupo = Convert.ToInt16(dt.Rows[0]["idGrupo"]);
datos.StrNombreGrupo = dt.Rows[0]["Nombre_Grupo"].ToString();
strMensaje = "";
return datos;
}
else
{
strMensaje = dt.Rows[0]["Mensaje"].ToString();
return null;
}
}
else
{
strMensaje = "El usuario no existe";
return null;
}
}
else
{
strMensaje = "No hay conexion con el servidor";
return null;
}
}
catch (Exception ex)
{
strMensaje = ex.Message;
return null;
}
}
public bool CambioPassword(Int64 idUsuario,string strPassword,out string strMensaje)
{
try
{
var parametros = new List<MySqlParameter>()
{
new MySqlParameter("usuario",idUsuario),
new MySqlParameter("pass",strPassword)
};
var mensaje = new MySqlParameter("mensaje", MySqlDbType.VarChar, 100) { Direction = ParameterDirection.Output };
var log_res = new MySqlParameter("log_respuesta", MySqlDbType.Bit) { Direction = ParameterDirection.Output };
parametros.Add(mensaje);
parametros.Add(log_res);
var res = _dataHelper.EjecutarSp<int>("sg_spCambioPass", parametros);
if (res >= 0)
{
strMensaje = mensaje.Value.ToString();
return Convert.ToBoolean(log_res.Value);
}
else
{
strMensaje = "No hay conexion con la base de datos";
return false;
}
}
catch (Exception ex)
{
strMensaje = ex.Message;
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaginaTridentto.Models
{
public class Seguridad
{
}
public class Usuario
{
public Int64 Id { get; set; }
public string StrUsuario { get; set; }
public string StrPassword { get; set; }
public string StrNombre { get; set; }
public int IdGrupo { get; set; }
public string StrNombreGrupo { get; set; }
public string StrEmail { get; set; }
public bool LogActivo { get; set; }
public DateTime DtmFechaCreacion { get; set; }
}
}
| bca1c88b4151f6dcc705d3a9e8111e5eeac00f6b | [
"C#"
] | 9 | C# | pcqmpa/PaginaWeb_Tridentto | 40190edabc6ae78fb8a4522aff648ed411ae9f7d | 8d3525b1b9f2b118508a4404bd7c4f2670ec11aa | |
refs/heads/master | <file_sep>let ta = document.getElementById('txtarea')
let b = document.getElementById('button')
let w = document.getElementById('warning')
let l = document.getElementById('list')
| a00678c6de199d53c8726155dea0a0667b9a5871 | [
"JavaScript"
] | 1 | JavaScript | codellege/Tarea28 | 36361283fb1ecfd152113017582d314e0c79648e | 5ba417feb3d9ba27681ac666e09f2bc5b2701b71 | |
refs/heads/main | <file_sep>export default function isNumStr(str: string) {
return /^[0-9]+$/.test(str);
}
<file_sep>export default {
smaps: [
{
address: '00400000-00401000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1569254',
pathname: '/usr/bin/node',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw sd',
},
},
{
address: '00401000-00402000',
perms: 'r-xp',
offset: '00001000',
dev: '08:01',
inode: '1569254',
pathname: '/usr/bin/node',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me dw sd',
},
},
{
address: '00402000-00403000',
perms: 'r--p',
offset: '00002000',
dev: '08:01',
inode: '1569254',
pathname: '/usr/bin/node',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw sd',
},
},
{
address: '00403000-00404000',
perms: 'r--p',
offset: '00002000',
dev: '08:01',
inode: '1569254',
pathname: '/usr/bin/node',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw ac sd',
},
},
{
address: '00404000-00405000',
perms: 'rw-p',
offset: '00003000',
dev: '08:01',
inode: '1569254',
pathname: '/usr/bin/node',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me dw ac sd',
},
},
{
address: '00ba9000-00d64000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
pathname: '[heap]',
d: {
size: '1772 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '1456 kb',
pss: '1456 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '1456 kb',
referenced: '1456 kb',
anonymous: '1456 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: 'b5b6e00000-b5b6e80000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '5cb91a80000-5cb91b00000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '9d0c6780000-9d0c6800000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '248 kb',
private_dirty: '264 kb',
referenced: '264 kb',
anonymous: '512 kb',
lazyfree: '248 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: 'b1357480000-b1357500000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: 'baefbf80000-baefc000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: 'c496a280000-c496a283000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: 'c496a283000-c496a300000',
perms: 'r--p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '500 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '32 kb',
pss: '32 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '32 kb',
referenced: '32 kb',
anonymous: '32 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me nr sd',
},
},
{
address: '10e923080000-10e923100000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '11b12e280000-11b12e300000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '131c7e980000-131c7ea00000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '1644fe280000-1644fe300000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '16e6e1680000-16e6e1700000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '179a1f000000-179a1f080000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '116 kb',
pss: '116 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '116 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '116 kb',
lazyfree: '116 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '19e64c280000-19e64c300000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '1b0629780000-1b0629800000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '1f9113900000-1f9113980000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '508 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '20cfc4700000-20cfc4780000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '2a1e20580000-2a1e20600000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '2a72ba200000-2a72ba280000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '2b6fa4f00000-2b6fa4f80000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '2c0fbe300000-2c0fbe380000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '2e0f54c00000-2e0f54c80000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '12 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '12 kb',
lazyfree: '12 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '2ec0a7100000-2ec0a7180000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '504 kb',
pss: '504 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '504 kb',
referenced: '504 kb',
anonymous: '504 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '30be06ff3000-30be07000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '52 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07000000-30be07003000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '30be07003000-30be07004000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07004000-30be0707f000',
perms: 'r-xp',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '492 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '492 kb',
pss: '492 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '492 kb',
referenced: '492 kb',
anonymous: '492 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me nr sd',
},
},
{
address: '30be0707f000-30be07080000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07080000-30be07083000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '30be07083000-30be07084000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07084000-30be070ff000',
perms: 'r-xp',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '492 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '492 kb',
pss: '492 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '492 kb',
referenced: '488 kb',
anonymous: '492 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me nr sd',
},
},
{
address: '30be070ff000-30be07100000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07100000-30be07103000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '30be07103000-30be07104000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07104000-30be0717f000',
perms: 'r-xp',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '492 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '492 kb',
pss: '492 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '492 kb',
referenced: '492 kb',
anonymous: '492 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me nr sd',
},
},
{
address: '30be0717f000-30be07180000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07180000-30be07183000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '30be07183000-30be07184000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '30be07184000-30be071ff000',
perms: 'r-xp',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '492 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '36 kb',
pss: '36 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '36 kb',
referenced: '36 kb',
anonymous: '36 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me nr sd',
},
},
{
address: '30be071ff000-30be0eff3000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '128976 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '311cd6e80000-311cd6f00000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '3142ff200000-3142ff280000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '512 kb',
referenced: '512 kb',
anonymous: '512 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '377ccef6c000-377ccef74000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '32 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '32 kb',
pss: '32 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '32 kb',
referenced: '32 kb',
anonymous: '32 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '38ad3c000000-38ad3c080000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '336 kb',
pss: '336 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '336 kb',
referenced: '336 kb',
anonymous: '336 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '3d7a78780000-3d7a78800000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '492 kb',
pss: '492 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '492 kb',
referenced: '492 kb',
anonymous: '492 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '3d8588e00000-3d8588e80000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '496 kb',
pss: '496 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '496 kb',
referenced: '496 kb',
anonymous: '496 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '3ef9f5d80000-3ef9f5e00000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '512 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '512 kb',
pss: '512 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '512 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '512 kb',
lazyfree: '512 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0c9effe000-7f0c9efff000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0c9efff000-7f0c9f7ff000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0c9f7ff000-7f0c9f800000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0c9f800000-7f0ca0000000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0ca0000000-7f0ca015c000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '1392 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '876 kb',
pss: '876 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '876 kb',
referenced: '876 kb',
anonymous: '876 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '7f0ca015c000-7f0ca4000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '64144 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0ca4000000-7f0ca4159000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '1380 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '776 kb',
pss: '776 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '776 kb',
referenced: '776 kb',
anonymous: '776 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '7f0ca4159000-7f0ca8000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '64156 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0ca8000000-7f0ca807a000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '488 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '292 kb',
pss: '292 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '292 kb',
referenced: '292 kb',
anonymous: '292 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '7f0ca807a000-7f0cac000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '65048 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0cac000000-7f0cac072000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '456 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '288 kb',
pss: '288 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '288 kb',
referenced: '288 kb',
anonymous: '288 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '7f0cac072000-7f0cb0000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '65080 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0cb0000000-7f0cb0021000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '132 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me nr sd',
},
},
{
address: '7f0cb0021000-7f0cb4000000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '65404 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me nr sd',
},
},
{
address: '7f0cb432c000-7f0cb432d000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb432d000-7f0cb4b2d000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb4b2d000-7f0cb4b2e000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb4b2e000-7f0cb532e000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb532e000-7f0cb532f000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb532f000-7f0cb5b2f000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb5b2f000-7f0cb5b56000',
perms: 'r--s',
offset: '00000000',
dev: '08:01',
inode: '393996',
pathname: '/usr/share/zoneinfo-icu/44/le/zoneinfo64.res',
d: {
size: '156 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '88 kb',
pss: '88 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '88 kb',
private_dirty: '0 kb',
referenced: '88 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr me ms sd',
},
},
{
address: '7f0cb5b56000-7f0cb5b57000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb5b57000-7f0cb6357000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '16 kb',
pss: '16 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '16 kb',
referenced: '16 kb',
anonymous: '16 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb6357000-7f0cb6358000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb6358000-7f0cb6b58000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '20 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '20 kb',
referenced: '20 kb',
anonymous: '20 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb6b58000-7f0cb6b59000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb6b59000-7f0cb7359000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '20 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '20 kb',
referenced: '20 kb',
anonymous: '20 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb7359000-7f0cb735a000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb735a000-7f0cb7b5a000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8192 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '20 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '20 kb',
referenced: '20 kb',
anonymous: '20 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb7b5a000-7f0cb7b5b000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cb7b5b000-7f0cb8371000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8280 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '96 kb',
pss: '96 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '96 kb',
referenced: '96 kb',
anonymous: '96 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb8371000-7f0cb8372000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1575272',
pathname: '/usr/lib/x86_64-linux-gnu/libicudata.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb8372000-7f0cb8373000',
perms: 'r-xp',
offset: '00001000',
dev: '08:01',
inode: '1575272',
pathname: '/usr/lib/x86_64-linux-gnu/libicudata.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cb8373000-7f0cb9e30000',
perms: 'r--p',
offset: '00002000',
dev: '08:01',
inode: '1575272',
pathname: '/usr/lib/x86_64-linux-gnu/libicudata.so.66.1',
d: {
size: '27380 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '192 kb',
pss: '192 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '192 kb',
private_dirty: '0 kb',
referenced: '192 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb9e30000-7f0cb9e31000',
perms: 'r--p',
offset: '01abe000',
dev: '08:01',
inode: '1575272',
pathname: '/usr/lib/x86_64-linux-gnu/libicudata.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cb9e31000-7f0cb9e32000',
perms: 'rw-p',
offset: '01abf000',
dev: '08:01',
inode: '1575272',
pathname: '/usr/lib/x86_64-linux-gnu/libicudata.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb9e32000-7f0cb9e35000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568900',
pathname: '/usr/lib/x86_64-linux-gnu/libgcc_s.so.1',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '6 kb',
shared_clean: '12 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '12 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb9e35000-7f0cb9e47000',
perms: 'r-xp',
offset: '00003000',
dev: '08:01',
inode: '1568900',
pathname: '/usr/lib/x86_64-linux-gnu/libgcc_s.so.1',
d: {
size: '72 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '64 kb',
pss: '34 kb',
shared_clean: '60 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '64 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cb9e47000-7f0cb9e4b000',
perms: 'r--p',
offset: '00015000',
dev: '08:01',
inode: '1568900',
pathname: '/usr/lib/x86_64-linux-gnu/libgcc_s.so.1',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '16 kb',
pss: '8 kb',
shared_clean: '16 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '16 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb9e4b000-7f0cb9e4c000',
perms: 'r--p',
offset: '00018000',
dev: '08:01',
inode: '1568900',
pathname: '/usr/lib/x86_64-linux-gnu/libgcc_s.so.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cb9e4c000-7f0cb9e4d000',
perms: 'rw-p',
offset: '00019000',
dev: '08:01',
inode: '1568900',
pathname: '/usr/lib/x86_64-linux-gnu/libgcc_s.so.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb9e4d000-7f0cb9e5c000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568907',
pathname: '/usr/lib/x86_64-linux-gnu/libm-2.31.so',
d: {
size: '60 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '56 kb',
pss: '18 kb',
shared_clean: '56 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '56 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb9e5c000-7f0cb9f03000',
perms: 'r-xp',
offset: '0000f000',
dev: '08:01',
inode: '1568907',
pathname: '/usr/lib/x86_64-linux-gnu/libm-2.31.so',
d: {
size: '668 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '280 kb',
pss: '280 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '280 kb',
private_dirty: '0 kb',
referenced: '280 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cb9f03000-7f0cb9f9a000',
perms: 'r--p',
offset: '000b6000',
dev: '08:01',
inode: '1568907',
pathname: '/usr/lib/x86_64-linux-gnu/libm-2.31.so',
d: {
size: '604 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '172 kb',
pss: '122 kb',
shared_clean: '100 kb',
shared_dirty: '0 kb',
private_clean: '72 kb',
private_dirty: '0 kb',
referenced: '172 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cb9f9a000-7f0cb9f9b000',
perms: 'r--p',
offset: '0014c000',
dev: '08:01',
inode: '1568907',
pathname: '/usr/lib/x86_64-linux-gnu/libm-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cb9f9b000-7f0cb9f9c000',
perms: 'rw-p',
offset: '0014d000',
dev: '08:01',
inode: '1568907',
pathname: '/usr/lib/x86_64-linux-gnu/libm-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cb9f9c000-7f0cba032000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '600 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '600 kb',
pss: '568 kb',
shared_clean: '64 kb',
shared_dirty: '0 kb',
private_clean: '536 kb',
private_dirty: '0 kb',
referenced: '600 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba032000-7f0cba122000',
perms: 'r-xp',
offset: '00096000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '960 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '684 kb',
pss: '506 kb',
shared_clean: '356 kb',
shared_dirty: '0 kb',
private_clean: '328 kb',
private_dirty: '0 kb',
referenced: '684 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba122000-7f0cba16b000',
perms: 'r--p',
offset: '00186000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '292 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '64 kb',
pss: '32 kb',
shared_clean: '64 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '64 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba16b000-7f0cba16c000',
perms: '---p',
offset: '001cf000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cba16c000-7f0cba177000',
perms: 'r--p',
offset: '001cf000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '44 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '44 kb',
pss: '44 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '44 kb',
referenced: '44 kb',
anonymous: '44 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba177000-7f0cba17a000',
perms: 'rw-p',
offset: '001da000',
dev: '08:01',
inode: '1568893',
pathname: '/usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.28',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba17a000-7f0cba17f000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '20 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '20 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '20 kb',
referenced: '20 kb',
anonymous: '20 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba17f000-7f0cba180000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568906',
pathname: '/usr/lib/x86_64-linux-gnu/libdl-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '0 kb',
shared_clean: '4 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba180000-7f0cba182000',
perms: 'r-xp',
offset: '00001000',
dev: '08:01',
inode: '1568906',
pathname: '/usr/lib/x86_64-linux-gnu/libdl-2.31.so',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '0 kb',
shared_clean: '8 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '8 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba182000-7f0cba183000',
perms: 'r--p',
offset: '00003000',
dev: '08:01',
inode: '1568906',
pathname: '/usr/lib/x86_64-linux-gnu/libdl-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba183000-7f0cba184000',
perms: 'r--p',
offset: '00003000',
dev: '08:01',
inode: '1568906',
pathname: '/usr/lib/x86_64-linux-gnu/libdl-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba184000-7f0cba185000',
perms: 'rw-p',
offset: '00004000',
dev: '08:01',
inode: '1568906',
pathname: '/usr/lib/x86_64-linux-gnu/libdl-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba185000-7f0cba1ea000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '404 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '404 kb',
pss: '404 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '404 kb',
private_dirty: '0 kb',
referenced: '404 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba1ea000-7f0cba2cf000',
perms: 'r-xp',
offset: '00065000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '916 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '280 kb',
pss: '221 kb',
shared_clean: '108 kb',
shared_dirty: '0 kb',
private_clean: '172 kb',
private_dirty: '0 kb',
referenced: '280 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba2cf000-7f0cba355000',
perms: 'r--p',
offset: '0014a000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '536 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '252 kb',
pss: '208 kb',
shared_clean: '88 kb',
shared_dirty: '0 kb',
private_clean: '164 kb',
private_dirty: '0 kb',
referenced: '252 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba355000-7f0cba356000',
perms: '---p',
offset: '001d0000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cba356000-7f0cba368000',
perms: 'r--p',
offset: '001d0000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '72 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '72 kb',
pss: '72 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '72 kb',
referenced: '72 kb',
anonymous: '72 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba368000-7f0cba369000',
perms: 'rw-p',
offset: '001e2000',
dev: '08:01',
inode: '1575282',
pathname: '/usr/lib/x86_64-linux-gnu/libicuuc.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba369000-7f0cba36b000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba36b000-7f0cba454000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '932 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '928 kb',
pss: '928 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '928 kb',
private_dirty: '0 kb',
referenced: '928 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba454000-7f0cba5d1000',
perms: 'r-xp',
offset: '000e9000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '1524 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '212 kb',
pss: '173 kb',
shared_clean: '72 kb',
shared_dirty: '0 kb',
private_clean: '140 kb',
private_dirty: '0 kb',
referenced: '212 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba5d1000-7f0cba657000',
perms: 'r--p',
offset: '00266000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '536 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '60 kb',
pss: '30 kb',
shared_clean: '60 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '60 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba657000-7f0cba658000',
perms: '---p',
offset: '002ec000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cba658000-7f0cba668000',
perms: 'r--p',
offset: '002ec000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '64 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '64 kb',
pss: '64 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '64 kb',
referenced: '64 kb',
anonymous: '64 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba668000-7f0cba669000',
perms: 'rw-p',
offset: '002fc000',
dev: '08:01',
inode: '1575274',
pathname: '/usr/lib/x86_64-linux-gnu/libicui18n.so.66.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba669000-7f0cba66a000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba66a000-7f0cba686000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '112 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '112 kb',
pss: '112 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '112 kb',
private_dirty: '0 kb',
referenced: '112 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba686000-7f0cba6d5000',
perms: 'r-xp',
offset: '0001c000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '316 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '60 kb',
pss: '60 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '60 kb',
private_dirty: '0 kb',
referenced: '60 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba6d5000-7f0cba6ef000',
perms: 'r--p',
offset: '0006b000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '104 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba6ef000-7f0cba6f0000',
perms: '---p',
offset: '00085000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cba6f0000-7f0cba6f9000',
perms: 'r--p',
offset: '00085000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '36 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '36 kb',
pss: '36 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '36 kb',
referenced: '36 kb',
anonymous: '36 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba6f9000-7f0cba6fd000',
perms: 'rw-p',
offset: '0008e000',
dev: '08:01',
inode: '1575805',
pathname: '/usr/lib/x86_64-linux-gnu/libssl.so.1.1',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '16 kb',
pss: '16 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '16 kb',
referenced: '16 kb',
anonymous: '16 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba6fd000-7f0cba775000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1574823',
pathname: '/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1',
d: {
size: '480 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '480 kb',
pss: '480 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '480 kb',
private_dirty: '0 kb',
referenced: '480 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba775000-7f0cba910000',
perms: 'r-xp',
offset: '00078000',
dev: '08:01',
inode: '1574823',
pathname: '/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1',
d: {
size: '1644 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '556 kb',
pss: '556 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '556 kb',
private_dirty: '0 kb',
referenced: '556 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba910000-7f0cba9a1000',
perms: 'r--p',
offset: '00213000',
dev: '08:01',
inode: '1574823',
pathname: '/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1',
d: {
size: '580 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '124 kb',
pss: '124 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '124 kb',
private_dirty: '0 kb',
referenced: '124 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba9a1000-7f0cba9cd000',
perms: 'r--p',
offset: '002a3000',
dev: '08:01',
inode: '1574823',
pathname: '/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1',
d: {
size: '176 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '176 kb',
pss: '176 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '176 kb',
referenced: '176 kb',
anonymous: '176 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba9cd000-7f0cba9cf000',
perms: 'rw-p',
offset: '002cf000',
dev: '08:01',
inode: '1574823',
pathname: '/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba9cf000-7f0cba9d3000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba9d3000-7f0cba9d8000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1575481',
pathname: '/usr/lib/x86_64-linux-gnu/libnghttp2.so.14.19.0',
d: {
size: '20 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '20 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '20 kb',
private_dirty: '0 kb',
referenced: '20 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba9d8000-7f0cba9eb000',
perms: 'r-xp',
offset: '00005000',
dev: '08:01',
inode: '1575481',
pathname: '/usr/lib/x86_64-linux-gnu/libnghttp2.so.14.19.0',
d: {
size: '76 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '76 kb',
pss: '76 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '76 kb',
private_dirty: '0 kb',
referenced: '76 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cba9eb000-7f0cba9f8000',
perms: 'r--p',
offset: '00018000',
dev: '08:01',
inode: '1575481',
pathname: '/usr/lib/x86_64-linux-gnu/libnghttp2.so.14.19.0',
d: {
size: '52 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cba9f8000-7f0cba9fb000',
perms: 'r--p',
offset: '00024000',
dev: '08:01',
inode: '1575481',
pathname: '/usr/lib/x86_64-linux-gnu/libnghttp2.so.14.19.0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cba9fb000-7f0cba9fc000',
perms: 'rw-p',
offset: '00027000',
dev: '08:01',
inode: '1575481',
pathname: '/usr/lib/x86_64-linux-gnu/libnghttp2.so.14.19.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba9fc000-7f0cba9fe000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cba9fe000-7f0cbaa00000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1569251',
pathname: '/usr/lib/x86_64-linux-gnu/libcares.so.2.3.0',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '8 kb',
private_dirty: '0 kb',
referenced: '8 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa00000-7f0cbaa0d000',
perms: 'r-xp',
offset: '00002000',
dev: '08:01',
inode: '1569251',
pathname: '/usr/lib/x86_64-linux-gnu/libcares.so.2.3.0',
d: {
size: '52 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '52 kb',
pss: '52 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '52 kb',
private_dirty: '0 kb',
referenced: '52 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbaa0d000-7f0cbaa10000',
perms: 'r--p',
offset: '0000f000',
dev: '08:01',
inode: '1569251',
pathname: '/usr/lib/x86_64-linux-gnu/libcares.so.2.3.0',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa10000-7f0cbaa11000',
perms: 'r--p',
offset: '00011000',
dev: '08:01',
inode: '1569251',
pathname: '/usr/lib/x86_64-linux-gnu/libcares.so.2.3.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbaa11000-7f0cbaa12000',
perms: 'rw-p',
offset: '00012000',
dev: '08:01',
inode: '1569251',
pathname: '/usr/lib/x86_64-linux-gnu/libcares.so.2.3.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbaa12000-7f0cbaa1b000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '36 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '36 kb',
pss: '36 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '36 kb',
private_dirty: '0 kb',
referenced: '36 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa1b000-7f0cbaa36000',
perms: 'r-xp',
offset: '00009000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '108 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '108 kb',
pss: '108 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '108 kb',
private_dirty: '0 kb',
referenced: '108 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbaa36000-7f0cbaa40000',
perms: 'r--p',
offset: '00024000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '40 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '40 kb',
pss: '40 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '40 kb',
private_dirty: '0 kb',
referenced: '40 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa40000-7f0cbaa41000',
perms: '---p',
offset: '0002e000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cbaa41000-7f0cbaa42000',
perms: 'r--p',
offset: '0002e000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbaa42000-7f0cbaa43000',
perms: 'rw-p',
offset: '0002f000',
dev: '08:01',
inode: '1574851',
pathname: '/usr/lib/x86_64-linux-gnu/libuv.so.1.0.0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbaa43000-7f0cbaa45000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '8 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '0 kb',
shared_clean: '8 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '8 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa45000-7f0cbaa56000',
perms: 'r-xp',
offset: '00002000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '68 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '64 kb',
pss: '9 kb',
shared_clean: '60 kb',
shared_dirty: '0 kb',
private_clean: '4 kb',
private_dirty: '0 kb',
referenced: '64 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbaa56000-7f0cbaa5c000',
perms: 'r--p',
offset: '00013000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '24 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa5c000-7f0cbaa5d000',
perms: '---p',
offset: '00019000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cbaa5d000-7f0cbaa5e000',
perms: 'r--p',
offset: '00019000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbaa5e000-7f0cbaa5f000',
perms: 'rw-p',
offset: '0001a000',
dev: '08:01',
inode: '1576072',
pathname: '/usr/lib/x86_64-linux-gnu/libz.so.1.2.11',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbaa5f000-7f0cbaa84000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '148 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '140 kb',
pss: '10 kb',
shared_clean: '140 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '140 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbaa84000-7f0cbabfc000',
perms: 'r-xp',
offset: '00025000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '1504 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '1416 kb',
pss: '120 kb',
shared_clean: '1416 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '1416 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbabfc000-7f0cbac46000',
perms: 'r--p',
offset: '0019d000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '296 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '140 kb',
pss: '8 kb',
shared_clean: '140 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '140 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbac46000-7f0cbac47000',
perms: '---p',
offset: '001e7000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cbac47000-7f0cbac4a000',
perms: 'r--p',
offset: '001e7000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbac4a000-7f0cbac4d000',
perms: 'rw-p',
offset: '001ea000',
dev: '08:01',
inode: '1568905',
pathname: '/usr/lib/x86_64-linux-gnu/libc-2.31.so',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '12 kb',
pss: '12 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '12 kb',
referenced: '12 kb',
anonymous: '12 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbac4d000-7f0cbac51000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '16 kb',
pss: '16 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '16 kb',
referenced: '16 kb',
anonymous: '16 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbac51000-7f0cbac58000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568922',
pathname: '/usr/lib/x86_64-linux-gnu/libpthread-2.31.so',
d: {
size: '28 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '28 kb',
pss: '2 kb',
shared_clean: '28 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '28 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbac58000-7f0cbac69000',
perms: 'r-xp',
offset: '00007000',
dev: '08:01',
inode: '1568922',
pathname: '/usr/lib/x86_64-linux-gnu/libpthread-2.31.so',
d: {
size: '68 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '68 kb',
pss: '4 kb',
shared_clean: '68 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '68 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbac69000-7f0cbac6e000',
perms: 'r--p',
offset: '00018000',
dev: '08:01',
inode: '1568922',
pathname: '/usr/lib/x86_64-linux-gnu/libpthread-2.31.so',
d: {
size: '20 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '20 kb',
pss: '2 kb',
shared_clean: '20 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '20 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbac6e000-7f0cbac6f000',
perms: 'r--p',
offset: '0001c000',
dev: '08:01',
inode: '1568922',
pathname: '/usr/lib/x86_64-linux-gnu/libpthread-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbac6f000-7f0cbac70000',
perms: 'rw-p',
offset: '0001d000',
dev: '08:01',
inode: '1568922',
pathname: '/usr/lib/x86_64-linux-gnu/libpthread-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbac70000-7f0cbac74000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbac74000-7f0cbb14f000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '4972 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4716 kb',
pss: '4716 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '4716 kb',
private_dirty: '0 kb',
referenced: '4716 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbb14f000-7f0cbbc96000',
perms: 'r-xp',
offset: '004db000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '11548 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '9596 kb',
pss: '9596 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '9596 kb',
private_dirty: '0 kb',
referenced: '9596 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me sd',
},
},
{
address: '7f0cbbc96000-7f0cbc1b9000',
perms: 'r--p',
offset: '01022000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '5260 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '3112 kb',
pss: '3112 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '3112 kb',
private_dirty: '0 kb',
referenced: '3112 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me sd',
},
},
{
address: '7f0cbc1b9000-7f0cbc1ba000',
perms: '---p',
offset: '01545000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cbc1ba000-7f0cbc218000',
perms: 'r--p',
offset: '01545000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '376 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '376 kb',
pss: '376 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '376 kb',
referenced: '376 kb',
anonymous: '376 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me ac sd',
},
},
{
address: '7f0cbc218000-7f0cbc220000',
perms: 'rw-p',
offset: '015a3000',
dev: '08:01',
inode: '1569253',
pathname: '/usr/lib/x86_64-linux-gnu/libnode.so.64',
d: {
size: '32 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '32 kb',
pss: '32 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '32 kb',
referenced: '32 kb',
anonymous: '32 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbc220000-7f0cbc236000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '88 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '88 kb',
pss: '88 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '88 kb',
referenced: '88 kb',
anonymous: '88 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbc243000-7f0cbc244000',
perms: '---p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'mr mw me sd',
},
},
{
address: '7f0cbc244000-7f0cbc248000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '16 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '8 kb',
pss: '8 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '8 kb',
referenced: '8 kb',
anonymous: '8 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7f0cbc248000-7f0cbc249000',
perms: 'r--p',
offset: '00000000',
dev: '08:01',
inode: '1568901',
pathname: '/usr/lib/x86_64-linux-gnu/ld-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '0 kb',
shared_clean: '4 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw sd',
},
},
{
address: '7f0cbc249000-7f0cbc26c000',
perms: 'r-xp',
offset: '00001000',
dev: '08:01',
inode: '1568901',
pathname: '/usr/lib/x86_64-linux-gnu/ld-2.31.so',
d: {
size: '140 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '140 kb',
pss: '9 kb',
shared_clean: '140 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '140 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me dw sd',
},
},
{
address: '7f0cbc26c000-7f0cbc274000',
perms: 'r--p',
offset: '00024000',
dev: '08:01',
inode: '1568901',
pathname: '/usr/lib/x86_64-linux-gnu/ld-2.31.so',
d: {
size: '32 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '32 kb',
pss: '2 kb',
shared_clean: '32 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '32 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw sd',
},
},
{
address: '7f0cbc275000-7f0cbc276000',
perms: 'r--p',
offset: '0002c000',
dev: '08:01',
inode: '1568901',
pathname: '/usr/lib/x86_64-linux-gnu/ld-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr mw me dw ac sd',
},
},
{
address: '7f0cbc276000-7f0cbc277000',
perms: 'rw-p',
offset: '0002d000',
dev: '08:01',
inode: '1568901',
pathname: '/usr/lib/x86_64-linux-gnu/ld-2.31.so',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me dw ac sd',
},
},
{
address: '7f0cbc277000-7f0cbc278000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '4 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '4 kb',
referenced: '4 kb',
anonymous: '4 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me ac sd',
},
},
{
address: '7ffec0216000-7ffec0237000',
perms: 'rw-p',
offset: '00000000',
dev: '00:00',
inode: '0',
pathname: '[stack]',
d: {
size: '132 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '64 kb',
pss: '64 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '64 kb',
referenced: '64 kb',
anonymous: '64 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd wr mr mw me gd ac',
},
},
{
address: '7ffec0285000-7ffec0288000',
perms: 'r--p',
offset: '00000000',
dev: '00:00',
inode: '0',
pathname: '[vvar]',
d: {
size: '12 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd mr pf io de dd sd',
},
},
{
address: '7ffec0288000-7ffec0289000',
perms: 'r-xp',
offset: '00000000',
dev: '00:00',
inode: '0',
pathname: '[vdso]',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '4 kb',
pss: '0 kb',
shared_clean: '4 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '4 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'rd ex mr mw me de sd',
},
},
{
address: 'ffffffffff600000-ffffffffff601000',
perms: '--xp',
offset: '00000000',
dev: '00:00',
inode: '0',
pathname: '[vsyscall]',
d: {
size: '4 kb',
kernelpagesize: '4 kb',
mmupagesize: '4 kb',
rss: '0 kb',
pss: '0 kb',
shared_clean: '0 kb',
shared_dirty: '0 kb',
private_clean: '0 kb',
private_dirty: '0 kb',
referenced: '0 kb',
anonymous: '0 kb',
lazyfree: '0 kb',
anonhugepages: '0 kb',
shmempmdmapped: '0 kb',
filepmdmapped: '0 kb',
shared_hugetlb: '0 kb',
private_hugetlb: '0 kb',
swap: '0 kb',
swappss: '0 kb',
locked: '0 kb',
thpeligible: '0',
vmflags: 'ex',
},
},
],
};
<file_sep>{
// file inclusion
"include": [
"src/**/*.ts"
],
"exclude": [
"src/**/doc.ts"
],
"typeAcquisition": {
"enable": true
},
"compilerOptions": {
// project options
"allowJs": true,
"checkJs": true,
/* composite works with:
- rootDir set it explicitly
- all files must be in the "include" or "files" property
- set declaration to "true"
! cannot be specified with "noEmit"
*/
"composite": false,
"declaration": true, // generate decleration files, make sure they go into a declarationDir
"declarationMap": true, // make map files for .d.ts files
"downlevelIteration": false, // let babble handle it
// import helpers
// https://www.typescriptlang.org/tsconfig#importHelpers
"importHelpers": false, // babble domain
"incremental": true,
// warn for potential cross-module transpile problems
// example: ambient const enum member generate errors
// https://www.typescriptlang.org/tsconfig#isolatedModules
"isolatedModules": true,
// "jsx": --> "undefined",
//
// this is not the transpilation target
"lib": [
"ES2019",
"ES2020.Promise",
],
"module": "ES2020",
"noEmit": false,
"outDir": "es6", // babel will take it from here and move to /bin
//"outFile" , non modules files get concatenated to this file
//"plugins":[...] for vscode editor, already included in package.json "contributes" field
"removeComments": false, // babel should handle it
"rootDir": "./src",
"sourceMap": true, // not sure if this should be turned on if you use babel
"target": "ES2019", // no down transpiling , that is for babel
//"tsBuildInfoFile": 'build', we dont use composite projects
/* STRICT CHECKS
https://www.typescriptlang.org/tsconfig#Strict_Type_Checking_Options_6173 */
// strictness
/*
"strict": true sets all below to true aswell
alwaysStrict,
strictNullChecks,
strictBindCallApply,
strictFunctionTypes,
strictPropertyInitialization,
noImplicitAny,
noImplicitThis
*/
"strict": true,
"alwaysStrict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"strictBindCallApply": true,
"strictFunctionTypes": true,
"strictNullChecks": true,
"strictPropertyInitialization": true,
/* MODULE RESOLUTION */
/* MODULE RESOLUTION */
/* MODULE RESOLUTION */
//https://www.typescriptlang.org/tsconfig#Module_Resolution_Options_6174
//
"allowSyntheticDefaultImports": false,
"allowUmdGlobalAccess": false,
"baseUrl": "./", // because src needs to be accessible by test
"esModuleInterop": false, // let babble handle this issue
// this is how modules are resolved at build time
// we dont use dynamic module loading or the ES6 module spec
"moduleResolution": "node",
/* "paths": { // we can use this for the test to pick up the module
"@blasjs/*": [
"src/lib/*"
]
},*/ // maybe use later, if you decide to use this, specify baseurl
// source maps
"preserveSymlinks": true, // keep it around just in case
/**
dont use it yet, does NOT affect typescript transpilation
"rootDirs":[] dont use it yet, does NOT affect typescript transpilation
can be used to trigger resolution of non js assets css etc
like import { appClass } from "./main.css"
main.css in src/css/main.css can by found by rootDirs:[ "src/css" ]
**/
// rootDirs:[something]
/*
Where to find typefiles, normally "./node_modules/@types"
all types are relative to tsconfig.json
*/
// "typeRoots":['./vender/types','./node_modules/@types']
/*
only these packages will be included in global scope
(sliced out of what is allowed by typeRoots),
note this is only global types (without import statement)
types included by "import" statements will not be affected by this setting
*/
// types:["node","jest","express"]
/* SOURCE MAPS */
/* SOURCE MAPS */
/* SOURCE MAPS */
// https://www.typescriptlang.org/tsconfig#Source_Map_Options_6175
"inlineSourceMap": false,
"inlineSources": false,
/* url that is included in the source map verbatim!
location of the sourcemap
*/
// "mapRoot": "http://someurl/debug/sourcemaps" use it? will be handled by babble?
/* "sourceRoot" will be the url needed to find the original ts files
this allows for debugging through original ts files
*/
// "sourceRoot: "http://someurl/debug/sources" use it? will be handled by babble?
/* LINTER CHECKS */
/* LINTER CHECKS */
/* LINTER CHECKS */
// https://www.typescriptlang.org/tsconfig#Source_Map_Options_6175
"noImplicitReturns": false, // allow for it
// DOESNT EXIST? "noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
/* EXPERIMENTAL */
/* EXPERIMENTAL */
/* EXPERIMENTAL */
"emitDecoratorMetadata": false, // babble for sure should handle it
"experimentalDecorators": true,
/* ADVANCED */
/* ADVANCED */
/* ADVANCED */
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"assumeChangesOnlyAffectDirectDependencies": false, // be on the safe side, you might not see all compiler errors otherwise
// "bundledPackageName": "blasjs", // ts-node problem i think, the bundled package name if you want to export types like "blasjs/typedArrayReal",
"noFallthroughCasesInSwitch": false, // fall through is ok
"declarationDir": "./es6/types", // emit types here
//"disableReferencedProjectLoad": true, handy for "projects" based setup
"disableSizeLimit": true,
"disableSolutionSearching": false, // i want my IDE to find decl's
// from ts 3.7 the source of truth is the ts files themselves,
"disableSourceOfProjectReferenceRedirect": false,
"emitBOM": false, //omg no
"emitDeclarationOnly": false, // should this be true if i am using babble?
"extendedDiagnostics": true, //always
"forceConsistentCasingInFileNames": true, // fuck windows, enforce casing!
// "generateCpuProfile": true, not sure to use this, or how
"importsNotUsedAsValues": "remove", // remove import type when transpiling
// "jsxFactory": "preact.h" not used
// "jsxFragmentFactory": "Fragment" // not used
// "jsxImportSource": "react" // not used
/*
print names of generated files to the terminal
make sure the include/exclude settings are ok
*/
"listEmittedFiles": true, //change back to true print names of generated files to the terminal
// also list files from node_modules ec (according to documentation,never checked it)
"listFiles": true, //change back to true
// list files
"maxNodeModuleJsDepth": 0, // no limitation on search dept, ..ever
"newLine": "LF", // unix
"noEmitHelpers": true, // dont emit helpers, babble should handle it
"noErrorTruncation": false, // the doc dont show the diff between true or false
"noImplicitUseStrict": false, // let ts emit "use strict" prologue at top of emitted files
"noLib": false, // dont ignore "lib" setting, false= enable automatic inclusion of library (d.ts?) files
"noResolve": false, // add resolved files (import, <reference) to the program
"noStrictGenericChecks": false, // do not disable this check
"preserveConstEnums": false, // do not preserve the enum at runtime
//"reactNamespace": "React", not used here
"resolveJsonModule": true, // infer type of json data when imported
"skipDefaultLibCheck": false, // always type check default libs
"skipLibCheck": true, // only type check the stuff you import from other libs
"stripInternal": true, // exports marked @internal (in their jsdoc) will not have their type exported
"suppressExcessPropertyErrors": false, // do not suppress
"suppressImplicitAnyIndexErrors": false, // absolutely not suppress
"traceResolution": false, // only use if you want to debug/trace why a file was (not) included (module resolution)
"useDefineForClassFields": true // switch to using class definition of TC39 not what typescript implementation
}
}<file_sep>export default function buddyInfo(text: string) {
/**
* Node 0, zone DMA 1 1 1 0 2 1 1 0 1 1 3
Node 0, zone DMA32 65 47 4 81 52 28 13 10 5 1 404
Node 0, zone Normal 216 55 189 101 84 38 37 27 5 3 587
*
*/
const result: Record<string, Record<string, number[]>> = {};
const lines = text.split('\n').filter((f) => f);
if (!lines.length) {
return;
}
let pos = 0;
for (const line of lines) {
// get the node
let nodeName;
let zoneName;
pos = 0;
{
const node = line.match(/^([^,]+),/);
if (!node) {
continue;
}
nodeName = node[1];
pos = node[0].length;
}
// get the zone
{
const zone = line.slice(pos).match(/^\s*zone\s+([^\s]+)/);
if (!zone) {
continue;
}
zoneName = zone[1];
pos += zone[0].length;
}
// get the numbers
const numbers = line
.slice(pos)
.split(/\s+/)
.filter((f) => f)
.map((s) => parseInt(s, 10));
if (!numbers.length) {
continue;
}
//
result[nodeName] = result[nodeName] || {};
result[nodeName][zoneName] = numbers;
}
return Object.keys(result).length ? result : undefined;
}
<file_sep>'use strict';
import { constants as CO } from '../src';
import { getProcReports, handlerMap } from '../src';
import expectedResult from './fixtures/result_smaps';
// remap handlers to fun and profit
const { cpuinfo } = handlerMap[CO.CPUINFO];
const { loadavg } = handlerMap[CO.LOADAVG];
const { meminfo } = handlerMap[CO.MEMINFO];
const { uptime } = handlerMap[CO.UPTIME];
const { buddy } = handlerMap[CO.BUDDYINFO];
const { io } = handlerMap[CO.SELF_IO];
const { smaps } = handlerMap[CO.SELF_SMAPS];
const { statm } = handlerMap[CO.SELF_STATM];
const { status } = handlerMap[CO.SELF_STATUS];
const { limits } = handlerMap[CO.SELF_LIMITS];
const { netDev } = handlerMap[CO.SELF_NET_DEV];
const { stat } = handlerMap[CO.SELF_STAT];
const C = {};
// point to fixtures instead
C[CO.CPUINFO] = require.resolve('./fixtures/cpuinfo.txt');
C[CO.LOADAVG] = require.resolve('./fixtures/loadavg.txt');
C[CO.MEMINFO] = require.resolve('./fixtures/meminfo.txt');
C[CO.UPTIME] = require.resolve('./fixtures/uptime.txt');
C[CO.BUDDYINFO] = require.resolve('./fixtures/buddyinfo.txt');
C[CO.SELF_IO] = require.resolve('./fixtures/self_io.txt');
C[CO.SELF_SMAPS] = require.resolve('./fixtures/self_smaps.txt');
C[CO.SELF_STATM] = require.resolve('./fixtures/self_statm.txt');
C[CO.SELF_STATUS] = require.resolve('./fixtures/self_status.txt');
C[CO.SELF_LIMITS] = require.resolve('./fixtures/self_limits.txt');
C[CO.SELF_STAT] = require.resolve('./fixtures/self_stat.txt');
C[CO.SELF_NET_DEV] = require.resolve('./fixtures/self_net_dev.txt');
const fixtureMap = {
[C[CO.CPUINFO]]: { cpuinfo },
[C[CO.LOADAVG]]: { loadavg },
[C[CO.MEMINFO]]: { meminfo },
[C[CO.UPTIME]]: { uptime },
[C[CO.BUDDYINFO]]: { buddy },
[C[CO.SELF_STAT]]: { stat },
[C[CO.SELF_IO]]: { io },
[C[CO.SELF_SMAPS]]: { smaps },
[C[CO.SELF_STATM]]: { statm },
[C[CO.SELF_STATUS]]: { status },
[C[CO.SELF_LIMITS]]: { limits },
[C[CO.SELF_NET_DEV]]: { netDev },
};
describe('proc', () => {
// point to fixtures
it('/proc/cpuinfo', async () => {
const result = await getProcReports(fixtureMap, C[CO.CPUINFO]);
console.log(result.cpuinfo.length);
/*expect(result).to.deep.equal({
cpuinfo: [
{
'processor': '0',
'cpu family': '6',
'model name': 'Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz',
'cache size': '4096 KB',
'physical id': '0',
'siblings': '1',
'cpu cores': '1'
}
]
});*/
});
it('/proc/loadavg', async () => {
const result = await getProcReports(fixtureMap, C[CO.LOADAVG]);
expect(result).toEqual({
loadavg: { '1m': 0.37, '5m': 0.51, '10m': 0.75, crp: 6, trp: 688, lpu: 87233 },
});
});
it('/proc/meminfo', async () => {
const result = await getProcReports(fixtureMap, C[CO.MEMINFO]);
expect(result).toEqual({
meminfo: {
MemTotal: '2919216 kB',
MemFree: '91460 kB',
MemAvailable: '893796 kB',
Buffers: '83040 kB',
Cached: '722300 kB',
SwapCached: '10512 kB',
Active: '1630436 kB',
Inactive: '953648 kB',
'Active(anon)': '1166192 kB',
'Inactive(anon)': '512992 kB',
'Active(file)': '464244 kB',
'Inactive(file)': '440656 kB',
Unevictable: '48 kB',
Mlocked: '48 kB',
SwapTotal: '1368676 kB',
SwapFree: '520080 kB',
Dirty: '68 kB',
Writeback: '0 kB',
AnonPages: '1768724 kB',
Mapped: '309828 kB',
Shmem: '70952 kB',
KReclaimable: '64876 kB',
Slab: '146820 kB',
SReclaimable: '64876 kB',
SUnreclaim: '81944 kB',
KernelStack: '11024 kB',
PageTables: '36592 kB',
NFS_Unstable: '0 kB',
Bounce: '0 kB',
WritebackTmp: '0 kB',
CommitLimit: '2828284 kB',
Committed_AS: '8257020 kB',
VmallocTotal: '34359738367 kB',
VmallocUsed: '35808 kB',
VmallocChunk: '0 kB',
Percpu: '768 kB',
HardwareCorrupted: '0 kB',
AnonHugePages: '0 kB',
ShmemHugePages: '0 kB',
ShmemPmdMapped: '0 kB',
FileHugePages: '0 kB',
FilePmdMapped: '0 kB',
CmaTotal: '0 kB',
CmaFree: '0 kB',
HugePages_Total: '0',
HugePages_Free: '0',
HugePages_Rsvd: '0',
HugePages_Surp: '0',
Hugepagesize: '2048 kB',
Hugetlb: '0 kB',
DirectMap4k: '229312 kB',
DirectMap2M: '2768896 kB',
},
});
});
it('/proc/uptime', async () => {
const result = await getProcReports(fixtureMap, C[CO.UPTIME]);
expect(result).toEqual({ uptime: { system: 778611.5, idle: 489146.81 } });
});
it('/proc/self/io', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_IO]);
expect(result).toEqual({
io: {
rchar: 4292,
wchar: 0,
syscr: 13,
syscw: 0,
read_bytes: 0,
write_bytes: 0,
cancelled_write_bytes: 0,
},
});
});
it('/proc/self/smaps', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_SMAPS]);
expect(result).toEqual(expectedResult);
});
it('/proc/self/statm', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_STATM]);
expect(result).toEqual({ statm: { size: 155437, resident: 10461, share: 6356, text: 2, data: 23709 } });
});
it('/proc/self/status', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_STATUS]);
expect(result).toEqual({
status: {
name: 'node',
umask: '0002',
state: 's (sleeping)',
tgid: '86383',
ngid: '0',
pid: '86383',
ppid: '86371',
tracerpid: '0',
fdsize: '256',
nstgid: '86383',
nspid: '86383',
nspgid: '86383',
nssid: '86371',
vmpeak: '621752 kb',
vmsize: '621748 kb',
vmlck: '0 kb',
vmpin: '0 kb',
vmhwm: '41868 kb',
vmrss: '41844 kb',
rssanon: '16420 kb',
rssfile: '25424 kb',
rssshmem: '0 kb',
vmdata: '94704 kb',
vmstk: '132 kb',
vmexe: '8 kb',
vmlib: '21644 kb',
vmpte: '536 kb',
vmswap: '0 kb',
hugetlbpages: '0 kb',
coredumping: '0',
thp_enabled: '1',
threads: '11',
nonewprivs: '0',
speculation_store_bypass: 'vulnerable',
cpus_allowed: '1',
cpus_allowed_list: '0',
mems_allowed:
'00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001',
mems_allowed_list: '0',
voluntary_ctxt_switches: '1141',
nonvoluntary_ctxt_switches: '1731',
},
});
});
it('/proc/buddyinfo', async () => {
const result = await getProcReports(fixtureMap, C[CO.BUDDYINFO]);
expect(result).toEqual({
buddy: {
'Node 0': {
DMA: [49, 18, 10, 4, 4, 1, 2, 2, 3, 1, 1],
DMA32: [3902, 2199, 335, 482, 125, 68, 11, 5, 1, 1, 1],
},
},
});
});
it('/proc/self/limits', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_LIMITS]);
expect(result).toEqual({
limits: {
'max cpu time': { soft: 'unlimited', hard: 'unlimited', unit: 'seconds' },
'max file size': { soft: 'unlimited', hard: 'unlimited', unit: 'bytes' },
'max data size': { soft: 'unlimited', hard: 'unlimited', unit: 'bytes' },
'max stack size': { soft: 8388608, hard: 'unlimited', unit: 'bytes' },
'max core file size': { soft: 0, hard: 'unlimited', unit: 'bytes' },
'max resident set': { soft: 'unlimited', hard: 'unlimited', unit: 'bytes' },
'max processes': { soft: 11182, hard: 11182, unit: 'processes' },
'max open files': { soft: 1048576, hard: 1048576, unit: 'files' },
'max locked memory': { soft: 67108864, hard: 67108864, unit: 'bytes' },
'max address space': { soft: 'unlimited', hard: 'unlimited', unit: 'bytes' },
'max file locks': { soft: 'unlimited', hard: 'unlimited', unit: 'locks' },
'max pending signals': { soft: 11182, hard: 11182, unit: 'signals' },
'max msgqueue size': { soft: 819200, hard: 819200, unit: 'bytes' },
'max nice priority': { soft: 0, hard: 0 },
'max realtime priority': { soft: 0, hard: 0 },
'max realtime timeout': { soft: 'unlimited', hard: 'unlimited', unit: 'us' },
},
});
});
it('/proc/self/stat', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_STAT]);
expect(result).toEqual({
stat: {
pid: 86383,
comm: '(node)',
state: 'S',
ppid: 86371,
pgrp: 86383,
session: 86371,
tty_nr: 34817,
cminflt: 0,
majflt: 14,
cmajflt: 0,
utime: 123,
stime: 91,
cutime: 0,
cstime: 0,
priority: 20,
nice: 0,
num_threads: 11,
start_time: 6881749,
vsize: 636669952,
rss: 10461,
rsslim: 18446744073709552000,
processor: 0,
guest_time: 0,
cguest_time: 0,
},
});
});
it('/proc/self/net/dev', async () => {
const result = await getProcReports(fixtureMap, C[CO.SELF_NET_DEV]);
expect(result).toEqual({
netDev: {
lo: {
receive: {
bytes: 5548092,
packets: 85227,
errs: 0,
drop: 0,
fifo: 0,
frame: 0,
compressed: 0,
multicast: 0,
},
transmit: {
bytes: 5548092,
packets: 85227,
errs: 0,
drop: 0,
fifo: 0,
colls: 0,
carrier: 0,
compressed: 0,
},
},
enp0s3: {
receive: {
bytes: 1069906047,
packets: 813995,
errs: 0,
drop: 0,
fifo: 0,
frame: 0,
compressed: 0,
multicast: 0,
},
transmit: {
bytes: 14541176,
packets: 101662,
errs: 0,
drop: 0,
fifo: 0,
colls: 0,
carrier: 0,
compressed: 0,
},
},
},
});
});
});
<file_sep># proc-reports
reports from /proc filesystem as json files
<file_sep>export default function netDev(text: string) {
const lines = text
.split('\n')
.slice(2)
.filter((f) => f); // skip first 2 lines (its a headers)
///
const result: Record<string, Record<string, unknown>> = {};
for (const line of lines) {
const s = line.indexOf(':');
if (s < 0) {
continue;
}
const entry = line.slice(0, s).trim();
const vals = line
.slice(s + 1)
.split(/\s+/)
.filter((f) => f)
.map((v) => parseInt(v, 10));
// receive part
result[entry] = {};
result[entry].receive = {
bytes: vals[0],
packets: vals[1],
errs: vals[2],
drop: vals[3],
fifo: vals[4],
frame: vals[5],
compressed: vals[6],
multicast: vals[7],
};
result[entry].transmit = {
bytes: vals[8],
packets: vals[9],
errs: vals[10],
drop: vals[11],
fifo: vals[12],
colls: vals[13],
carrier: vals[14],
compressed: vals[15],
};
}
return Object.keys(result).length ? result : undefined;
}
<file_sep>export default function uptime(text: string) {
const [system, idle] = text
.split(/\s+/)
.filter((f) => f)
.map((v) => parseFloat(v));
return {
system,
idle,
};
}
<file_sep>export default function selfStatm(text: string) {
const values = text.split(/\s+/).map((n) => parseInt(n, 10));
const result = ['size', 'resident', 'share', 'text', 'lib', 'data', 'dt'].reduce((c, s, i) => {
c[s] = values[i];
return c;
}, {} as Record<string, unknown>);
delete result.lib;
delete result.dt;
return result;
}
<file_sep>export default function (text: string) {
const keys = [
'processor',
'vendor_id',
'cpu family',
'model name',
'physical id',
'siblings',
'cpu MHz',
'cache size',
'cpu cores',
'apicid',
];
const results: Record<string, unknown>[] = [];
for (const processor of text.split(/\n{2,}/).filter((f) => f)) {
const entryLines = processor.split('\n').filter((f) => f);
const cpu: Record<string, unknown> = {};
for (const line of entryLines) {
const [key, value] = line.split(':').map((s) => s.trim());
if (keys.includes(key) && value) {
cpu[key] = value;
}
}
if (Object.keys(cpu).length === keys.length) {
results.push(cpu);
}
}
return results;
}
<file_sep>import isNumStr from './isNumStr';
export default function selfLimits(text: string) {
const lines = text
.split('\n')
.filter((f) => f)
.map((s) => s.toLowerCase());
// get position from headers
if (lines.length === 0) {
return;
}
const header = lines.shift() as string;
const p2 = header.search(/soft limit/);
const p3 = header.search(/hard limit/);
const p4 = header.search(/units/);
const result: Record<string, any> = {};
for (const line of lines) {
const name = line.slice(0, p2).trim();
const soft = line.slice(p2, p3).trim();
const hard = line.slice(p3, p4).trim();
const unit = line.slice(p4).trim();
result[name] = {
soft: isNumStr(soft) ? parseInt(soft, 10) : soft,
hard: isNumStr(hard) ? parseInt(hard, 10) : hard,
};
if (unit) {
result[name].unit = unit;
}
}
return Object.keys(result).length ? result : undefined;
}
<file_sep>export default function memInfo(text: string) {
const lines = text.split('\n').filter((f) => f);
const result: Record<string, unknown> = {};
for (const line of lines) {
const [prop, value] = line.split(':').map((s) => s.trim());
if (prop && value) {
result[prop] = value;
}
}
return result;
}
<file_sep>export default function selfSmaps(text: string) {
let cursor = 0;
const lines = text.split('\n').filter((f) => f);
const regExpHeaders = /^([0-9A-Za-z]+\-[0-9A-Za-z]+)\s+([rwxsp-]+)\s([0-9A-Za-z]+)\s+([0-9:]+)\s+([0-9]+)\s+([^\s]+)?/;
const mods: Record<string, any>[] = [];
function* moduleLines() {
while (cursor < lines.length && lines[cursor]) {
if (lines[cursor].match(regExpHeaders) !== null) {
return;
}
const [key, value] = lines[cursor].split(':').map((s) => s.trim().toLowerCase());
yield [key, value];
cursor++;
}
}
while (cursor < lines.length && lines[cursor]) {
const mod = lines[cursor].match(regExpHeaders);
if (mod !== null) {
const info = ['address', 'perms', 'offset', 'dev', 'inode', 'pathname'].reduce((c, prop, i) => {
if (mod[i + 1]) {
c[prop] = mod[i + 1];
}
return c;
}, {} as Record<string, any>);
info.d = {};
cursor++;
for (const [key, value] of moduleLines()) {
info.d[key] = value;
}
mods.push(info);
continue;
}
cursor++;
}
return mods;
}
<file_sep>import * as fs from 'fs';
import cpuinfo from './cpuInfo';
import io from './io';
import smaps from './smaps';
import statm from './statm';
import status from './status';
import buddy from './buddy';
import loadavg from './loadavg';
import meminfo from './memInfo';
import netDev from './netDev';
import uptime from './uptime';
import limits from './limits';
import stat from './stat';
enum C {
CPUINFO = '/proc/cpuinfo',
MEMINFO = '/proc/meminfo',
LOADAVG = '/proc/loadavg',
UPTIME = '/proc/uptime',
BUDDYINFO = '/proc/buddyinfo',
SELF_IO = '/proc/self/io',
SELF_STAT = '/proc/self/stat',
SELF_SMAPS = '/proc/self/smaps',
SELF_STATM = '/proc/self/statm',
SELF_STATUS = '/proc/self/status',
SELF_LIMITS = '/proc/self/limits',
SELF_NET_DEV = '/proc/self/net/dev',
}
export { C as constants };
export const handlerMap = {
[C.CPUINFO]: { cpuinfo },
[C.LOADAVG]: { loadavg },
[C.MEMINFO]: { meminfo },
[C.UPTIME]: { uptime },
[C.SELF_STAT]: { stat },
[C.SELF_IO]: { io },
[C.SELF_SMAPS]: { smaps },
[C.SELF_STATM]: { statm },
[C.SELF_STATUS]: { status },
[C.BUDDYINFO]: { buddy },
[C.SELF_LIMITS]: { limits },
[C.SELF_NET_DEV]: { netDev },
};
function loadFile(path: string): Promise<string> {
const readable = fs.createReadStream(path, { flags: 'r', emitClose: true, start: 0 });
readable.setEncoding('utf8');
return new Promise((resolve, reject) => {
const chunks: string[] = [];
readable.on('data', (chunk: string) => {
chunks.push(chunk);
});
readable.on('close', () => {
resolve(chunks.join(''));
});
readable.on('end', () => {
resolve(chunks.join(''));
});
readable.on('error', (err) => {
reject(err);
});
});
}
export type Slice<X extends Record<string, unknown>> = {
[P in keyof X]: X[P];
};
type Handler = (s: string) => Record<string, any>;
export function getProcReports<T extends Record<string, unknown>>(handlers: Slice<T>, ...procList: (keyof T)[]) {
const promises: Promise<string>[] = [];
if (procList.length === 0) {
procList = Object.keys(handlers);
}
for (let i = 0; i < procList.length; i++) {
promises.push(loadFile(procList[i] as string));
}
return Promise.allSettled(promises).then((allSettled) => {
// process all raw data
const result: Record<string, any | Handler> = {};
allSettled.reduce((final, settle, i) => {
const [[shortName, handler]] = Object.entries<Handler>(handlers[procList[i]] as any);
if (settle.status === 'rejected') {
final[shortName] = String(settle.reason);
} else {
const resultObj = handler(settle.value);
if (resultObj) {
final[shortName] = resultObj;
}
}
return final;
}, result);
return result;
});
}
<file_sep>export default //0.37 0.51 0.75 6/688 87233
function loadAverage(text: string) {
const vals = text.split(/\s+/).filter((f) => f);
if (!vals.length) {
return;
}
// running processes
let crp = -1;
let trp = -1;
{
const prs = vals[3].match(/([0-9]+)\/([0-9]+)/);
if (prs) {
crp = parseInt(prs[1], 10);
trp = parseInt(prs[2], 10);
}
}
return {
'1m': parseFloat(vals[0]),
'5m': parseFloat(vals[1]),
'10m': parseFloat(vals[2]),
crp,
trp,
lpu: parseInt(vals[4]),
};
}
<file_sep>export default function selfstat(text: string) {
//86383, pid 1
// (node) , comm
//S , state
// 86371 , ppid
// 86383 , pgrp 5
// 86371 , session
// 34817 , tty_nr
// 86383 , tpgid
// 4194304 , flags
// 13348 , minflt 10
// 0 , cminflt
//14 , majflt
// 0 , cmajflt
//123 , utime
//91 , stime 15
//0 , cutime,
//0 , cstime,
//20, priority ,
//0 nice
//11 num_threads 20
//0 itrealvalue
//6881749 starttime (expressed in cock ticks)
//636669952 vsize (virtual memory size in bytes)
//10461 rss (resident set size, in nr of pages)
//18446744073709551615 rsslim (soft limit of the rss of the process) 25
//4194304 (startcode)
//4199205 (endcode)
//140732121962768 (startstack) address bottom of the stack
//0 kstkesp current value of esp (stack pointer)
//0 kstkeip (EIP pointer) 30
//0 signal obsolete
//0 blocked obsolete
//4096 sigignore obsolete
//134234626 sigcatch obsolete
//0 wchan (place in the kernel where the process is sleeping) 35
//0
//0
//17 exit-signal
//0 processor
//0 rt_priority 40
//0 policy
//3 block io delays in clock ticks
//0 guest time
//0 (cguest_time)
//4210024 45
//4210704
//12226560
//140732121964672
//140732121964677
//140732121964677 50
//140732121968618
//0 52
const lines = text.split('\n').filter((f) => f);
const result: Record<string, unknown> = {};
// there should be one line
if (!lines.length) {
return result;
}
const fields = lines[0].split(/\s+/).map((s) => {
const trial = Number.parseInt(s, 10);
if (isNaN(trial)) {
return s;
}
return trial;
});
// stat
result.pid = fields[0]; //86383
result.comm = fields[1]; // (node)
result.state = fields[2]; // S
result.ppid = fields[3]; // 86371
result.pgrp = fields[4]; // 86383
result.session = fields[5]; // 86371
result.tty_nr = fields[6]; // 34817
result.cminflt = fields[10];
result.majflt = fields[11];
result.cmajflt = fields[12];
result.utime = fields[13];
result.stime = fields[14];
result.cutime = fields[15];
result.cstime = fields[16];
result.priority = fields[17];
result.nice = fields[18];
result.num_threads = fields[19];
// skipped
result.start_time = fields[21];
result.vsize = fields[22];
result.rss = fields[23];
result.rsslim = fields[24];
// skipped
result.processor = fields[38];
// skipped
result.guest_time = fields[42];
result.cguest_time = fields[43];
return result;
}
<file_sep>export default function selfStatus(text: string) {
const lines = text.split('\n').filter((f) => f);
const result: Record<string, unknown> = {};
for (const line of lines) {
const [key, value] = line.split(':').map((s) => s.trim().toLowerCase());
if (
[
'uid',
'gid',
'groups',
'sigq',
'sigpnd',
'shdpnd',
'sigblk',
'sigign',
'sigcgt',
'capinh',
'capprm',
'capeff',
'capbnd',
'capamb',
'seccomp',
].includes(key)
) {
continue;
}
result[key] = value;
}
return result;
}
<file_sep>export default function selfIo(text: string) {
const lines = text.split('\n').filter((f) => f);
const results = lines.reduce((c, line) => {
const [key, value] = line.split(':').map((s) => s.trim());
if (value) {
c[key] = parseInt(value, 10);
}
return c;
}, {} as Record<string, unknown>);
return results;
}
| 362c1f08ba4a0e05f49599f0b8d22fe2ee85729d | [
"Markdown",
"TypeScript",
"JSON with Comments"
] | 18 | TypeScript | jacobbogers/proc-reports | 39157405ebd8ba3560551926e65d13b4a5a1d611 | f955a6465eed4d58e50a950fb1c2e8da7f281e8f | |
refs/heads/main | <repo_name>SwordOfSouls/BungeeKick<file_sep>/src/main/java/net/ultibuild/UpdateChecker.java
package net.ultibuild;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Scanner;
import java.util.logging.Level;
public class UpdateChecker {
private static String ver = "1.2";
public static void checkForUpdates() {
if(getLatestVersion() != "") {
if(!Objects.equals(ver, getLatestVersion())) {
Main.getInstance().getLogger().log(Level.INFO,"A new version is avalible!");
Main.getInstance().getLogger().log(Level.INFO,"Your version: " + ver + " Newest: " + getLatestVersion());
Main.getInstance().getLogger().log(Level.INFO,"Update here: https://www.spigotmc.org/resources/94728");
}
} else {
Main.getInstance().getLogger().log(Level.INFO,"An error occurred getting latest version!");
}
}
public static String getLatestVersion() {
try {
URL url = new URL("https://api.spigotmc.org/legacy/update.php?resource=94728");
InputStream inputStream = url.openStream();
Scanner scanner = new Scanner(inputStream);
String string = scanner.nextLine();
return string;
} catch (Throwable io) {
return "";
}
}
}
<file_sep>/src/main/java/net/ultibuild/Commands/kick.java
package net.ultibuild.Commands;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
public class kick extends Command {
public kick() {
super("kick");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) {
if(args.length >= 2) {
try {
ProxiedPlayer p = ProxyServer.getInstance().getPlayer(args[0]);
TextComponent text = new TextComponent("");
for(int i = 1; i < args.length; i++) {
TextComponent reason = new TextComponent(ChatColor.translateAlternateColorCodes('&',args[i] + " "));
text.addExtra(reason);
}
text.setColor(ChatColor.RED);
p.disconnect(text);
System.out.println("Successfully kicked user " + p.getDisplayName() + " for reason: " + text.toPlainText());
} catch (Throwable ie) {
System.out.println("An error occured processing kick!");
}
} else {
System.out.println("Not enough args for kick! (/kick <playername> <reason>)");
}
}
}
}<file_sep>/README.md
# BungeeKick
| 2caeb765fe3a95047949d43195247ccbc5809da6 | [
"Markdown",
"Java"
] | 3 | Java | SwordOfSouls/BungeeKick | 30cbd3925f9f0e69c41ed43b13edf42443020443 | 808ebc3b6c1eedf435dbf4e548401f08f04eb94a | |
refs/heads/main | <repo_name>Ibbs620/HowlerPod<file_sep>/wolfhacks_code.ino
#include <Servo.h>
#include <Wire.h>
#include <ds3231.h>
#include "DHT.h"
#include <LiquidCrystal_I2C.h>
//Import Libraries
#define DHTTYPE DHT11 //Define type of temperature sensor being used
Servo water;
DHT dht(2, DHTTYPE);
LiquidCrystal_I2C lcd(0x27,16,2);
//Declare LCD, servo, DHT sensor
struct ts t;
void setup() {
water.attach(3); //Set servo as pin 3
DS3231_init(DS3231_CONTROL_INTCN); //Start up temperature sensor
Wire.begin();
dht.begin();
lcd.init();
lcd.backlight();
//start up components
}
void loop() {
DS3231_get(&t); //get time variable from clock
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
int val = map(analogRead(A0),550,0,0,100) + 100; //Read soil moisture sensor and fix readings
lcd.setCursor(0,0);
lcd.print(printDateTime());
lcd.setCursor(0,1);
lcd.print(t);
lcd.setCursor(4,1);
lcd.print("C");
lcd.setCursor(9,1);
lcd.print("Mstr:");
lcd.setCursor(14,1);
lcd.print(val);
//print information to LCD
if(val < 18){ //water plants when soil is dry
waterPlants();
}
delay(1000); //delay
}
void waterPlants(){ //Waters the plants with the servo
for(int i = 90; i < 180; i++){ //slowly push servo. If pushed fast, the water will shoot out too fast
water.write(i);
delay(50);
}
water.write(180); //return servo to original position
delay(1000);
water.write(90);
}
String printDateTime(){ //format date and time for LCD display
return String(t.mon) + "/" + String(t.mday) + "/" + String(t.year) + " " + String(t.hour) + ":" + String(t.min);
}
<file_sep>/README.md
# HowlerPod
A Minecraft model of the HowlerPod and code for the watering system.
Edit: HowlerPod won WolfHacks 2021!
Check out the devpost: https://devpost.com/software/howlerpod
| 8f6461431daad38a6b159e160a2bb0213276308a | [
"Markdown",
"C++"
] | 2 | C++ | Ibbs620/HowlerPod | 1c596627d7340e1033cba6fd9d93bae31aa1dc7f | c590c5aabcd908af581b933c626675db71a8c2e2 | |
refs/heads/master | <file_sep># <NAME> - Data Analytics for Business - Final Project (Project Rubric) - Script 2 Charts & Presentation
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# File import and treatment section
# Assign filename: file
file = 'output.csv'
# Import file: data
medals = pd.read_csv(file, sep=',', na_values=['Nothing'])
print(medals['Year'].unique())
print(medals['Country'].unique())
print(medals.columns)
print(medals.isnull().sum())
# File review and summary section
# Display sample data of the DataFrame
print(medals.head(5))
# Display max medals count by country
print("Max amount of gold medals by one country at any one Olympic games: " + str((medals["Gold"].max())))
print("Max amount of silver medals by one country at any one Olympic games: " + str((medals["Silver"].max())))
print("Max amount of bronze medals by one country at any one Olympic games: " + str((medals["Bronze"].max())))
#Display countries with the most Gold medals
top_10_countries_by_year = medals.groupby('Country')['Gold'].sum().sort_values(ascending=False).head(10)
print(top_10_countries_by_year)
yearly_view = (medals.pivot_table (index = "Country", columns="Year",values=['Gold'], fill_value=0))
print(yearly_view)
# Display Gold medal wins by reference to the relative wealth of countries
medals.groupby(["GDP_Strata", "Gold"]).sum()
wealthiest_countries = (medals.pivot_table (index = "Country", columns="GDP_Strata",values=['Gold'], fill_value="0"))
print(wealthiest_countries)
# Display Gold Medal wins by reference to the most populous countries
medals.groupby(["Population_Strata", "Gold"]).sum()
populous_countries = (medals.pivot_table (index = "Country", columns="Population_Strata",values=['Gold'], fill_value="0"))
print(populous_countries)
#Display Charts section
# List top performing countries by ref to gold medals
top_countries = ['USA', 'URS', 'GBR', 'CHN', 'JPN'] # Note Japan only entered top 4 only when Olympics were in Japan 2020
team_medals = pd.pivot_table(medals,index = 'Year',columns = 'Country',values = 'Gold',aggfunc = 'sum')[top_countries]
team_medals.plot(linestyle = '-', marker = 's', linewidth = 3)
plt.xlabel('Olympic Year')
plt.ylabel('Number of Medals')
plt.title('Top Countries - Olympic Performance Comparison')
plt.grid()
plt.show()
#Display medal wins against population level of the countries
plt.figure
sns.catplot(x='Population_Strata',kind='count',data=medals, order=medals.Population_Strata.value_counts().index)
plt.title('Gold Medal wins versus population level',fontsize=16)
plt.grid()
plt.show()
#Display medal wins against relative wealth level of the countries
plt.figure
sns.catplot(x='GDP_Strata',kind='count',data=medals, order=medals.GDP_Strata.value_counts().index)
plt.title('Gold Medal wins versus GDP per capita',fontsize=12)
plt.grid()
plt.show()
medals.groupby('GDP_Strata')[['Gold','Bronze','Silver']].sum().plot.bar(color=['gold','red','grey'])
plt.xlabel('Country',fontsize=12)
plt.ylabel('Medal Count',fontsize=12)
plt.title('All Countries All medals by GDP per capita',fontsize=14)
plt.grid()
plt.show()
# Focus on Ireland performance
# Display ALL Irish medal wins
medals[medals['Country']=='IRL'][['Gold','Bronze','Silver']].sum().plot.bar(color=['gold','red','grey'])
plt.xlabel('IRELAND OLYMPIC MEDALS TOTAL',fontsize=10)
plt.ylabel('TOTAL MEDALS',fontsize=10)
plt.title('Total Irish Olympic Medal Wins',fontsize=14)
plt.grid()
plt.show()
# Display ALL Irish medal wins
ireland_results = medals[medals['Country']=='IRL'].sort_values(['Year'], ascending=True)
print (ireland_results)
sns.barplot(y='Gold', x='Year' , data=ireland_results.sort_values(['Gold']),color="green")
plt.xlabel('Ireland performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All Irish Gold Medal Wins by year',fontsize=14)
plt.grid()
plt.show()
# Focus on USA performance at 1904 and 1984 games
USA_results = medals[medals['Country']=='USA'].sort_values(['Year'], ascending=True)
print (USA_results)
sns.barplot(y='Gold', x='Year' , data=USA_results.sort_values(['Gold']),color="blue")
plt.xlabel('USA performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All USA Gold Medal Wins by year',fontsize=14)
plt.grid()
plt.show()
# Focus on China performance since 1984
# Display ALL Chinese medal wins
china_results = medals[medals['Country']=='CHN'].sort_values(['Year'], ascending=True)
print (china_results)
sns.barplot(y='Gold', x='Year' , data=china_results.sort_values(['Gold']),color="red")
plt.xlabel('China performance by year',fontsize=10)
plt.ylabel('Year',fontsize=10)
plt.title('All Chinese Gold Medal Wins since 1984',fontsize=14)
plt.grid()
plt.show()
<file_sep># <NAME> - Data Analytics for Business - Final Project (Project Rubric) - Script 1
import csv
import pandas as pd
import numpy as np
# import olympic medals base data
def get_medals_dict():
with open('Country_Medals_New.csv', mode='r') as infile:
next(infile) # skip header
reader = csv.reader(infile)
# key is Country_Code & Year as integer value with each of medal count. Return True where country is host
return {tuple([rows[1][1:-1], int(rows[0])]): [rows[5], rows[6], rows[7], rows[2] == rows[4]] for rows in
reader}
# identify all Olympic years
olympic_year_list = ['1952', '1956', '1960', '1964', '1968', '1972', '1976', '1980', '1984', '1988', '1992', '1996', '2000', '2004', '2008', '2012',
'2016', '2020']
# extract a GDP figure for the nearest Olympic year
def get_gdp_dict():
with open('gdp.csv', mode='r') as infile: #
next(infile) #skip header
reader = csv.reader(infile)
gdp_dict = {}
for rows in reader:
year = get_closest_olympic_year(rows[5])
gdp_dict[tuple([rows[0], year])] = (int(rows[6]))
if rows[0] is not None and rows[6] is not None:
gdp_dict[tuple([rows[0], int(rows[5])])] = (int(rows[6]))
return gdp_dict
# Extract a Population figure for the nearest Olympic year
def get_pop_dict():
with open('pop.csv', mode='r') as infile: #
next(infile) #skip header
reader = csv.reader(infile)
pop_dict = {}
for rows in reader:
year = get_closest_olympic_year(rows[5])
pop_dict[tuple([rows[0], year])] = (int(rows[6]))
if rows[0] is not None and rows[6] is not None:
pop_dict[tuple([rows[0], int(rows[5])])] = (int(rows[6]))
return pop_dict
# apply reusable logic to matching up olympic years, subject to defined olympic year list
def get_closest_olympic_year(year):
count = 0
while count + 1 < len(olympic_year_list) and year >= olympic_year_list[count + 1]:
count += 1
return olympic_year_list[count]
# write results in useful format to an output .CSV file
def write_results(output_dict):
with open('mycsvfile.csv', 'w') as f:
w = csv.DictWriter(f, output_dict.keys())
#w.writeheader()
#w.writerow(output_dict)
dataframe = pd.DataFrame(output_dict)
dataframe.transpose().to_csv('output.csv')
#def merge_dictionaries(d1, d2):
#for key, value in d1.items():
#if key in d2:
#value.extend(d2[key])
#else:
#value.extend([None])
#return d1
def run():
gdp = get_gdp_dict()
pop = get_pop_dict()
merged_dictionaries = (gdp, pop)
#merged_dictionaries = merge_dictionaries(gdp, pop)
medals = get_medals_dict()
for key, value in medals.items():
if key[0] in merged_dictionaries:
if len(key[0]) == 3:
value.extend(merged_dictionaries[key[0]])
else:
print(key[0])
else:
value.extend(['Monkey', 'Bananas'])
#value.extend(merged_dictionaries[key[0]] if key[0] in merged_dictionaries else [None, None]) #add population and gdp
#print(merged_dictionaries)
#print(medals)
write_results(medals)
run()
print("Processing Completed")
| 1e2af398812727f3ea1a6a34ae943ca206cb3c58 | [
"Python"
] | 2 | Python | DonalRynne/ucd_l3 | 19b545be387b0e18a30ecd8a8d4a29be025570e6 | 3aaa75ff0a0b12bafb3076589afa4bd7e5d881b9 | |
refs/heads/master | <file_sep>#!/usr/bin/env python
import re
from setuptools import setup, find_packages
def read_version():
with open("pytd/version.py") as f:
m = re.match(r'__version__ = "([^\"]*)"', f.read())
return m.group(1)
setup(
name="pytd",
version=read_version(),
description="Python wrappers for TD",
author="<NAME>",
author_email="<EMAIL>",
url="https://github.com/k24d/pytd",
install_requires=open("requirements.txt").read().splitlines(),
packages=find_packages(),
license="Apache License 2.0",
platforms="Posix; MacOS X; Windows",
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Topic :: Software Development",
],
)
| 1225fc5d3cc532644a9025d9113fbb1d6ad167d8 | [
"Python"
] | 1 | Python | nahi/pytd | ab866ef945ed6f6f287a87b2973f8a66846d920c | e9a8f9d2493bd4bebf6718831fdb633b66d0c377 | |
refs/heads/main | <file_sep>
#!/bin/bash
echo "date of loss"
read date
echo "time of loss"
read time
echo "am or pm"
read time_2
date2=$date*
#echo $date2
grep -e $date -e $time $date2 | grep -ie $time_2 | awk -F ' ' '{print $1,$2,$5,$6}'
<file_sep>#!/bin/bash
awk -F"$" '{print $2}' dealers_sorted | sed 's/[0-9]//g;s/-$,//g;s/,/\n/g;s/ //g' | sort | uniq -c | sort
<file_sep>#!/bin/bash
grep '-' 0310_win_loss_player_data 0312_win_loss_player_data 0315_win_loss_player_data | sed 's/\t/ /g' | sed 's/ //g' | awk -F '$' '{print $2}'
<file_sep># ELK-Stack-Project-1
The first cybersecurity project detailing the creation, install, and setup of an ELK stack VM Network.
## Automated ELK Stack Deployment
The files in this repository were used to configure the network depicted below.
https://github.com/dknicholson1990/ELK-Stack-Project-1/blob/main/Diagrams/ELK%20UPDATE.drawio.png
These files have been tested and used to generate a live ELK deployment on Azure. They can be used to either recreate the entire deployment pictured above. Alternatively, select portions of the _____ file may be used to install only certain pieces of it, such as Filebeat.
https://github.com/dknicholson1990/ELK-Stack-Project-1/blob/main/Ansible/ansible%20playbook.txt
This document contains the following details:
- Description of the Topologu
- Access Policies
- ELK Configuration
- Beats in Use
- Machines Being Monitored
- How to Use the Ansible Build
### Description of the Topology
The main purpose of this network is to expose a load-balanced and monitored instance of DVWA, the D*mn Vulnerable Web Application.
Load balancing ensures that the application will be highly _____, in addition to restricting _____ to the network.
- _TODO: What aspect of security do load balancers protect? What is the advantage of a jump box?_ Load balancers protect the servers from a denial of service attack.
- using a jump box protects your virtual machines from public exposure
Integrating an ELK server allows users to easily monitor the vulnerable VMs for changes to the _____ and system _____.
- _TODO: What does Filebeat watch for?_ Logfiles
- _TODO: What does Metricbeat record?_ Activity Metrics
The configuration details of each machine may be found below.
_Note: Use the [Markdown Table Generator](http://www.tablesgenerator.com/markdown_tables) to add/remove values from the table_.
| Name | Function | IP Address | Operating System |
|----------|----------|------------|------------------|
| Jump Box | Gateway | 10.0.0.4 | Linux |
| Web-1 | DVWA/Beat| 10.0.0.5 | Linux |
| Web-2 | DVWA/Beat| 10.0.0.6 | Linux |
| ELK | Monitor | 10.1.0.4 | Linux |
### Access Policies
The machines on the internal network are not exposed to the public Internet.
Only the Jumpbox machine can accept connections from the Internet. Access to this machine is only allowed from the following IP addresses:
- HOSTIP
Machines within the network can only be accessed by _____.
-HOSTIP
A summary of the access policies in place can be found in the table below.
| Name | Publicly Accessible | Allowed IP Addresses |
|----------|---------------------|----------------------|
| Jump Box | Yes | HOSTIP |
| Elk | Yes | HOstIP |
| | | |
### Elk Configuration
Ansible was used to automate configuration of the ELK machine. No configuration was performed manually, which is advantageous because...
- Ease of access as well as deployability, If new Virtual Machines need to be added the Deployment takes minutes.
The playbook implements the following tasks:
- Install the docker container to new vm
- Start install playbook to initialize ELK install and setup
- Install Filebeat for Logs
- Install Metricbeat for Metric data and monitoring
The following screenshot displays the result of running `docker ps` after successfully configuring the ELK instance.
https://github.com/dknicholson1990/ELK-Stack-Project-1/blob/main/Ansible/docker%20ps.png
### Target Machines & Beats
This ELK server is configured to monitor the following machines:
- 10.0.0.5
- 10.0.0.6
We have installed the following Beats on these machines:
-FileBeat
Metricbeat
These Beats allow us to collect the following information from each machine:
-Filebeat collects log information. This allows you to research, catagorize and evaluate specific information down to the day and time of your choice.
-Metricbeat is used to collect and ship operating system and service metrics to one or more destinations. This allows you to see how the system is running and what is using the most or least resources.
### Using the Playbook
In order to use the playbook, you will need to have an Ansible control node already configured. Assuming you have such a control node provisioned:
SSH into the control node and follow the steps below:
- Copy the _____ file to _____.
- Update the _____ file to include...
- Run the playbook, and navigate to ____ to check that the installation worked as expected.
_TODO: Answer the following questions to fill in the blanks:_
- _Which file is the playbook? Where do you copy it?_ The playbook files are always in .yml format. and you can copy form the host machine to the virtual machine.
- _Which file do you update to make Ansible run the playbook on a specific machine? How do I specify which machine to install the ELK server on versus which to install Filebeat on?_ You will need to makesure in the .yml file you have the machine specified in the HOSTS section. You will make a seperate playbook and specify the hosts machine.
- _Which URL do you navigate to in order to check that the ELK server is running? http://[your.VM.IP]:5601/app/kibana
_As a **Bonus**, provide the specific commands the user will need to run to download the playbook, update the files, etc._
ssh jumpbox@ ip address
start and attach container
curl (git clone location of updated files)
cd /etc/ansible
nano hosts (add vms ip to webserver and new section ELK for elk vm)
nano ansible.conf to add the remote user to server
| 3a22513d2e88241855e8140133629f5f88892097 | [
"Markdown",
"Shell"
] | 4 | Shell | dknicholson1990/ELK-Stack-Project-1 | 6bca422b164e4e79520985f3b82b468e4e77dd4f | cfdc38cc6d3bf3293930a2116d5edfaec837b1b2 | |
refs/heads/master | <repo_name>NET-OF-BEING/coinspot-py<file_sep>/main.py
#!/usr/bin/python3
from coinspot import CoinSpot
import sys, pprint, subprocess, config
sys.path.append(".")
_api_key = config._api_key
_api_secret = config._api_secret
coin=CoinSpot(_api_key,_api_secret)
print('''
~██████╗~██████╗~██╗███╗~~~██╗███████╗██████╗~~██████╗~████████╗~~~~~█████╗~██████╗~██╗
██╔════╝██╔═══██╗██║████╗~~██║██╔════╝██╔══██╗██╔═══██╗╚══██╔══╝~~~~██╔══██╗██╔══██╗██║
██║~~~~~██║~~~██║██║██╔██╗~██║███████╗██████╔╝██║~~~██║~~~██║~~~~~~~███████║██████╔╝██║
██║~~~~~██║~~~██║██║██║╚██╗██║╚════██║██╔═══╝~██║~~~██║~~~██║~~~~~~~██╔══██║██╔═══╝~██║
╚██████╗╚██████╔╝██║██║~╚████║███████║██║~~~~~╚██████╔╝~~~██║~~~~~~~██║~~██║██║~~~~~██║
~╚═════╝~╚═════╝~╚═╝╚═╝~~╚═══╝╚══════╝╚═╝~~~~~~╚═════╝~~~~╚═╝~~~~~~~╚═╝~~╚═╝╚═╝~~~~~╚═╝
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
''')
print("---------------------------------")
print("Select an option:")
print("---------------------------------\n")
print("1. Coin Address")
print("2. Open Orders")
print("3. Transactions")
print("4. Buy/Sell Orders")
print("5. Coin Transactions")
print("6. Cancel Sell Order")
print("7. Cancel Buy Order")
print("8. latest prices")
print("9. Buy quote")
print("a. Affiliate Payments")
print("0. Sell quote")
print("o. My Orders")
print("h. Orders History")
print("b. My Balances")
print("g. Place Buy Order")
print("r. Coin Balance")
print("p. Place Sell Order")
print("q. Quit\n\n")
print("----------------------------------\n")
def CoinDepositAddress():
subprocess.call('clear')
print("Enter Coin Ticker:")
address = input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("Coin Deposit Address for" ,address)
print("----------------------------------------------------------\n")
pprint.pprint(coin.my_coin_deposit(address))
print("\n----------------------------------------------------------\n")
print("\n\n")
def AffiliatePayments():
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("Affiliate Payments")
print("----------------------------------------------------------\n")
pprint.pprint(coin.affiliate_payments())
print("\n----------------------------------------------------------\n")
print("\n\n")
def DisplayMyOrders():
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("My Orders")
print("----------------------------------------------------------\n")
pprint.pprint(coin.my_orders())
print("\n----------------------------------------------------------\n")
print("\n\n")
def CoinBalance():
subprocess.call('clear')
crypto=input("Enter Coin: ")
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("Coin Balance for ", crypto)
print("\n----------------------------------------------------------\n")
pprint.pprint(coin.my_coin_balance(crypto))
print("\n----------------------------------------------------------\n")
print("\n\n")
def DisplayOrdersHistory():
subprocess.call('clear')
cointype = input("Enter Coin: ")
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("Order History")
print("----------------------------------------------------------\n")
pprint.pprint(coin.orders_history(cointype))
print("----------------------------------------------------------\n")
def DisplayBalance():
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("My Balance")
print("----------------------------------------------------------\n")
pprint.pprint(coin.my_balances())
print("\n----------------------------------------------------------\n")
print("\n\n")
def DisplayOpenOrders():
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
cointype = input("Enter Coin: ")
subprocess.call('clear')
print("----------------------------------------------------------\n")
print("Open Orders")
print("----------------------------------------------------------\n")
pprint.pprint(coin.orders(cointype))
print("\n----------------------------------------------------------\n")
print("\n\n")
def DisplayTransactions():
subprocess.call('clear')
print("Enter Start date (YYYY-MM-DD:)")
start_date = input()
print("Enter End date (YYYY-MM-DD:)")
end_date = input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("\nTransactions")
print("\n----------------------------------------------------------\n")
pprint.pprint(coin.my_transactions(start_date,end_date))
print("\n----------------------------------------------------------\n")
print("\n\n")
def PlaceBuyOrder():
subprocess.call('clear')
print("Enter Coin:")
crypto=input()
print("Enter Amount:")
amount=input()
print("Enter Rate:")
rate=input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("\nNew Buy Order")
print("----------------------------------------------------------\n")
pprint.pprint(coin.my_buy(crypto,amount,rate))
print("\n----------------------------------------------------------\n")
print("\n\n")
def PlaceSellOrder():
subprocess.call('clear')
print("Enter Coin")
crypto=input()
print("Enter Amount")
amount=input()
print("Enter Rate")
rate=input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("\nNew Sell Order")
print("\n----------------------------------------------------------\n")
pprint.pprint(coin.my_sell(crypto,amount,rate))
print("\n----------------------------------------------------------\n")
print("\n\n")
def CancelSellOrder():
subprocess.call('clear')
print("Enter Order ID")
id = input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("\nCancel Sell Order")
print("----------------------------------------------------------\n")
pprint.pprint(coin.my_sell_cancel(id))
print("\n----------------------------------------------------------\n")
print("\n\n")
def CancelBuyOrder():
subprocess.call('clear')
print("Enter Order ID")
id = input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
pprint.pprint(coin.my_buy_cancel(id))
print("\n----------------------------------------------------------\n")
print("\n\n")
def ShowOrders():
subprocess.call('clear')
print("\n\n----------------------------------------------------------\n")
print("\nMy Buy/Sell Orders")
print("----------------------------------------------------------")
pprint.pprint(coin.my_orders())
print("\n----------------------------------------------------------\n")
print("\n\n")
def DisplayCoinTransactions():
subprocess.call('clear')
print("Enter Coin:")
cointype=input()
print("Enter Start date (YYYY-MM-DD:)")
start_date = input()
print("Enter End date (YYYY-MM-DD:)")
end_date = input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------")
print("\nCoin Transactions for ", cointype)
print("----------------------------------------------------------\n")
pprint.pprint(coin.coin_transactions(cointype,start_date,end_date))
print("\n----------------------------------------------------------\n")
print("\n\n")
def ShowLatest():
subprocess.call('clear')
print("\n\n----------------------------------------------------------")
print("\nLatest Coin prices\n\n")
print("----------------------------------------------------------")
pprint.pprint(coin.latest())
print("\n----------------------------------------------------------\n")
print("\n\n")
def BuyQuote():
subprocess.call('clear')
print("Enter Coin:")
crypto=input()
print("Enter Amount:")
amount=input()
subprocess.call('clear')
print("----------------------------------------------------------")
print("Buy Quotes for ",amount , " ", crypto)
print("----------------------------------------------------------")
pprint.pprint(coin.quote_buy(crypto,amount))
print("\n----------------------------------------------------------\n")
print("\n\n")
def MyBuy():
subprocess.call('clear')
print("Enter Coin:")
crypto=input()
print("Enter Amount:")
amount=input()
print("Enter Rate:")
rate=input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------")
print("\nPlacing Buy Order for ", amount, " ", crypto)
print("\n----------------------------------------------------------")
pprint.pprint(coin.my_buy(crypto, amount, rate))
print("\n----------------------------------------------------------")
print("\n\n")
def MySell():
subprocess.call('clear')
print("Enter Coin:")
crypto=input()
print("Enter Amount:")
amount=input()
print("Enter Rate:")
rate=input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------")
print("\nSelling ", amount, crypto)
print("\n----------------------------------------------------------")
pprint.pprint(coin.my_sell(crypto, amount, rate))
print("\n----------------------------------------------------------")
print("\n\n")
def SellQuote():
subprocess.call('clear')
print("Enter Coin:")
crypto=input()
print("Enter Amount:")
amount=input()
subprocess.call('clear')
print("\n\n----------------------------------------------------------")
print("Quotes to sell Coin")
print("----------------------------------------------------------")
pprint.pprint(coin.quote_sell(crypto,amount))
print("\n----------------------------------------------------------\n")
print("\n\n")
def CleanupAndQuit():
print("byez")
menuchoices = {'1':CoinDepositAddress, '2':DisplayOpenOrders, '3':DisplayTransactions, '4':ShowOrders, '5':DisplayCoinTransactions, '6':CancelSellOrder, '7':CancelBuyOrder, '8':ShowLatest, '9':BuyQuote, '0':SellQuote, 'h':DisplayOrdersHistory, 'o':DisplayMyOrders, 'b':DisplayBalance, 'q':CleanupAndQuit, 'g': MyBuy, 'p' :MySell, 'r':CoinBalance,'a': AffiliatePayments }
ret = menuchoices[input("Option: ")]()
#if ret is None:
#print("Please enter a valid menu choice!")
#menuchoices['q']()
<file_sep>/config.py
_api_key=''
_api_secret=''
| c98561ae6260ad11b36bda7f9d687a0db9586ae9 | [
"Python"
] | 2 | Python | NET-OF-BEING/coinspot-py | 660dceb9094cfb043e45bef768fab2898777f4c0 | b55a2cb2cbac73c589715f408db399cfa8c38e61 | |
refs/heads/master | <repo_name>ajsherrell/Sunset<file_sep>/app/src/main/java/com/ajsherrell/sunset/MainActivity.kt
package com.ajsherrell.sunset
import android.animation.AnimatorSet
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.AccelerateInterpolator
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
//use Kotlin Android Extensions instead here
// private lateinit var sceneView: View
// private lateinit var sunView: View
// private lateinit var skyView: View
private var isDown: Boolean = false
private val blueSkyColor: Int by lazy {
ContextCompat.getColor(this, R.color.blue_sky)
}
private val sunsetSkyColor: Int by lazy {
ContextCompat.getColor(this, R.color.sunset_sky)
}
private val nightSkyColor: Int by lazy {
ContextCompat.getColor(this, R.color.night_sky)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//use Kotlin Android Extensions instead here
// sceneView = findViewById(R.id.scene)
// sunView = findViewById(R.id.sun)
// skyView = findViewById(R.id.sky)
//when user presses anywhere in the scene view
scene.setOnClickListener {
if (isDown) {
startUpAnimation()
} else {
startAnimation()
}
}
}
private fun startAnimation() {
val sunYStart = sun.top.toFloat()
val sunYEnd = sky.height.toFloat()
val heightAnimator = ObjectAnimator
.ofFloat(sun, "y", sunYStart, sunYEnd)
.setDuration(3000)
heightAnimator.interpolator = AccelerateInterpolator()
val sunsetSkyAnimator = ObjectAnimator
.ofInt(sky, "backgroundColor", blueSkyColor, sunsetSkyColor)
.setDuration(3000)
sunsetSkyAnimator.setEvaluator(ArgbEvaluator())
val nightSkyAnimator = ObjectAnimator
.ofInt(sky, "backgroundColor", sunsetSkyColor, nightSkyColor)
.setDuration(1500)
nightSkyAnimator.setEvaluator(ArgbEvaluator())
val animatorSet = AnimatorSet()
animatorSet.play(heightAnimator)
.with(sunsetSkyAnimator)
.before(nightSkyAnimator)
animatorSet.start()
isDown = true
}
private fun startUpAnimation() {
val sunYStart = sky.height.toFloat()
val sunYEnd = sun.top.toFloat()
val heightAnimator = ObjectAnimator
.ofFloat(sun, "y", sunYStart, sunYEnd)
.setDuration(3000)
heightAnimator.interpolator = AccelerateInterpolator()
val sunsetSkyAnimator = ObjectAnimator
.ofInt(sky, "backgroundColor", sunsetSkyColor, blueSkyColor)
.setDuration(750)
sunsetSkyAnimator.setEvaluator(ArgbEvaluator())
val nightSkyAnimator = ObjectAnimator
.ofInt(sky, "backgroundColor", nightSkyColor, sunsetSkyColor)
.setDuration(3000)
nightSkyAnimator.setEvaluator(ArgbEvaluator())
val animatorSet = AnimatorSet()
animatorSet.play(heightAnimator)
.with(nightSkyAnimator)
.before(sunsetSkyAnimator)
animatorSet.start()
isDown = false
}
}
<file_sep>/README.md
# Sunset
- An app that uses property animation to create a sunset over the water. Touch once to start sunset, touch again to start sunrise.
### Components
- Custom drawables
- Object Animation
- Kotlin Android Extensions
- TimeInterpolator
### Before Color Change Images
<img src="images/daytime.png" width="300"> <img src="images/sunset.png" width="300">
<img src="images/sundown.png" width="300">
### After Color Change Images
<img src="images/startSet.png" width="300"> <img src="images/middleSet.png" width="300">
<img src="images/set.png" width="300"> <img src="images/endSet.png" width="300">
<img src="images/down.png" width="300"> <img src="images/night.png" width="300"> | 6a74d68eb76a6e446b8cf29176f6c9060dae36e4 | [
"Markdown",
"Kotlin"
] | 2 | Kotlin | ajsherrell/Sunset | 772a731347a466ee5270e8b99211b5d2123bcdcc | c9f3e8874b022c2275b50827bdfddbbdb754d6cc | |
refs/heads/master | <repo_name>dakl/screen-handler<file_sep>/run.py
import json
import paho.mqtt.client as mqtt
import structlog
from app import config
from app.accessory.screen import Screen
logger = structlog.getLogger(__name__)
# The callback for when the client receives a CONNACK response from the server.
logger.info("Starting screen-handler")
screen = Screen(name="raspi-touchscreen")
if not config.TOPIC_NAME:
raise ValueError("The environment variable 'TOPIC_NAME' needs to be set.")
def on_connect(client, userdata, flags, rc):
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
topic = f"commands/{config.TOPIC_NAME}/#"
logger.info("Subscribing", topic=topic)
client.subscribe(topic)
logger.info("Connected", rc=str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, message):
payload = str(message.payload.decode("utf-8")).strip()
logger.info("Handling message", topic=message.topic, payload=payload)
screen.handle(payload=json.loads(payload))
publish_topic = f"events/{config.TOPIC_NAME}"
logger.info("Publishing state update message", topic=publish_topic, payload=payload)
client.publish(topic=publish_topic, payload=payload, retain=True)
logger.info("Connecting to MQTT")
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(config.BROKER, 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()
<file_sep>/.flake8
[flake8]
max-line-length = 100
import-order-style=smarkets
application-import-names=recommender,tests
ignore = W503,E203,E231,E501,S101
<file_sep>/app/accessory/screen.py
from app import config
import structlog
from .base import Accessory
logger = structlog.getLogger(__name__)
STATE_MAP = {
"ON": 1,
"OFF": 0,
}
class Screen(Accessory):
def __init__(
self,
name: str,
read_handle: str = None,
write_handle: str = None,
):
self.name = name
self.read_handle = read_handle or config.READ_HANDLE
self.write_handle = write_handle or config.WRITE_HANDLE
def set_state(self, state: int) -> None:
if state == 0:
self.set_brightness(0)
elif state == 1:
self.set_brightness(255)
def get_state(self) -> int:
brightness = self.get_brightness()
if brightness > 0:
return 1
else:
return 0
def set_brightness(self, value: int) -> None:
""" Brightness is expected to come in as an int in the range 0-255."""
with open(self.write_handle, "w") as f:
f.write(str(value) + "\n")
def get_brightness(self) -> int:
with open(self.read_handle, "r") as f:
return int(f.read().strip())
def handle(self, payload):
if "brightness" in payload:
b = int(payload.get("brightness"))
self.set_brightness(b)
elif "state" in payload:
if payload.get("state") == "OFF":
self.set_brightness(0)
elif payload.get("state") == "ON":
self.set_brightness(255)
<file_sep>/requirements-dev.txt
-r requirements.txt
flake8
ipdb
mypy
pytest
watchdog
black
<file_sep>/app/accessory/mock.py
from .base import Accessory
class MockAccessory(Accessory):
def set_state(self, state):
return 1
def get_status(self):
return 0
<file_sep>/app/accessory/base.py
from abc import ABC, abstractmethod
class Accessory(ABC):
name: str
def __init__(self, name):
self.name = name
@abstractmethod
def set_state(self, state: int) -> None:
raise NotImplementedError()
@abstractmethod
def get_state(self) -> int:
raise NotImplementedError()
def handler(self, payload):
self.set_state(payload)
<file_sep>/README.md
# Screen Handler
Sets the screen on a raspberry pi touchscreen based on HomeAssistant events on MQTT.
# Run
~~~bash
make run
~~~
<file_sep>/Makefile
run-dev:
watchmedo auto-restart python run.py --patterns="*.py" --recursive
run:
WRITE_HANDLE=/sys/class/backlight/rpi_backlight/brightness \
READ_HANDLE=/sys/class/backlight/rpi_backlight/actual_brightness \
python3 run.py
lint:
flake8 app/
mypy --ignore-missing-imports app/
test: lint
<file_sep>/Dockerfile
FROM dakl/arm32-python-alpine-qemu:3.7.1-slim
COPY requirements.txt /tmp/
RUN pip install --no-cache-dir -r /tmp/requirements.txt
WORKDIR /code
COPY . /code
CMD ["python", "run.py"]<file_sep>/app/config.py
import os
class Config:
WRITE_HANDLE = os.getenv(
"WRITE_HANDLE", "/tmp/brightness"
) # "/sys/class/backlight/rpi_backlight/brightness"
READ_HANDLE = os.getenv(
"READ_HANDLE", "/tmp/actual_brightness"
) # "/sys/class/backlight/rpi_backlight/actual_brightness"
DEBUG = os.getenv("DEBUG", False)
BROKER = os.getenv("BROKER", "worker0.local")
TOPIC_NAME = os.getenv("TOPIC_NAME", "screen")
<file_sep>/app/__init__.py
import logging
from app.config import Config
def setup_logging():
if config.DEBUG:
level = logging.DEBUG
else:
level = logging.INFO
logging.basicConfig(level=level)
config = Config()
setup_logging()
| 43a5402d856f1634404e620d65e96c4eedcdeb02 | [
"Markdown",
"Makefile",
"INI",
"Python",
"Text",
"Dockerfile"
] | 11 | Python | dakl/screen-handler | d027eaa5662bc4bbf4576aa8045427a9e2c6d601 | 3195a0356d7daee8880d3e08bbc9a2fa82153fd3 | |
refs/heads/master | <repo_name>Stephen1324/Online-Library<file_sep>/README.md
# Online-Library
I have created an ecommerce website using PHP in HUW111 class. It has three categories Music,Movies, and Books
<file_sep>/Final-Online-Library/inc/data.php
<?php
$catalog = [];
//Books
$catalog[101] = [
"title" => "The Hunger Game",
"img" => "img/media/thehungergames.jpg",
"genre" => "Epic Poetry",
"format" => "Hardcover",
"year" => 2000,
"category" => "Books",
"authors" => [
"<NAME>"
],
"publisher" => "Farrar, Straus and Giroux",
"isbn" => '9780374111199'
];
$catalog[102] = [
"title" => "The Outsiders",
"img" => "img/media/theoutsiders.jpg",
"genre" => "Fiction",
"format" => "Paperback",
"year" => 2004,
"category" => "Books",
"authors" => [
"<NAME>"
],
"publisher" => "Scribner",
"isbn" => '9780743273565'
];
$catalog[103] = [
"title" => "The Maze Runner",
"img" => "img/media/mazerunner.jpg",
"genre" => "Gothic Fiction",
"format" => "Paperback",
"year" => 2007,
"category" => "Books",
"authors" => [
"<NAME>"
],
"publisher" => "Barnes & Noble",
"isbn" => '9781593082499'
];
$catalog[104] = [
"title" => "Scorch Trials",
"img" => "img/media/scorchtrials.jpg",
"genre" => "Horror",
"format" => "Paperback",
"year" => 2005,
"category" => "Books",
"authors" => [
"<NAME>"
],
"publisher" => "Barnes & Noble",
"isbn" => '9781593081157'
];
//Movies
$catalog[201] = [
"title" => "<NAME>",
"img" => "img/media/johnwick3.jpg",
"genre" => "Action",
"format" => "DVD/Streaming",
"year" => 2019,
"category" => "Movies",
"director" => "<NAME>",
"writers" => [
"<NAME>",
],
"stars" => [
"<NAME>",
"<NAME>",
"<NAME>",
]
];
$catalog[202] = [
"title" => "How To Train A dragon Hidden World",
"img" => "img/media/hiddenworld.jpg",
"genre" => "Fantasy",
"format" => "DVD/Streaming",
"year" => 2019,
"category" => "Movies",
"director" => "<NAME>",
"writers" => [
"<NAME>",
],
"stars" => [
"<NAME>",
"<NAME>",
"<NAME>"
]
];
$catalog[203] = [
"title" => "The Avengers Endgames",
"img" => "img/media/avengersendgame.jpg",
"genre" => "Action",
"format" => "DVD",
"year" => 2019,
"category" => "Movies",
"director" => "<NAME>",
"writers" => [
"<NAME>",
"<NAME>"
],
"stars" => [
"<NAME>r.",
"<NAME>",
"<NAME>"
]
];
$catalog[204] = [
"title" => "The house with a Clock in it Wall",
"img" => "img/media/thehouswithaclock.jpg",
"genre" => "Drama, Fantasy, Adventure",
"format" => "DVD/Streaming",
"year" => 2019,
"category" => "Movies",
"director" => "<NAME>",
"writers" => [
"<NAME>"
],
"stars" => [
"<NAME> ",
"<NAME>",
"<NAME>"
]
];
//Music
$catalog[301] = [
"title" => "Eminem",
"img" => "img/media/Eminem.jpg",
"genre" => "Hip-Hop, Rap",
"format" => "CD",
"year" => 2008,
"category" => "Music",
"artist" => "Eminem"
];
$catalog[302] = [
"title" => "The Carter IV",
"img" => "img/media/LilWayne.jpg",
"genre" => " Hip-Hop, Rap",
"format" => "Streaming Services",
"year" => 2019,
"category" => "Music",
"artist" => "<NAME>"
];
$catalog[303] = [
"title" => "N.W.A",
"img" => "img/media/NWA.jpg",
"genre" => " Hip-Hop, Rap",
"format" => "CD, Streaming Services",
"year" => 1996,
"category" => "Music",
"artist" => "N.W.A"
];
$catalog[304] = [
"title" => "50 Cent: Get Rich or Die Tryin ",
"img" => "img/media/50Cent.jpeg",
"genre" => "Hip-Hop, Rap",
"format" => "CD, Streaming Services",
"year" => 2005,
"category" => "Music",
"artist" => "50 Cent"
];
?>
| 4f007950e0f197922f321d21e8ec80cc31e63237 | [
"Markdown",
"PHP"
] | 2 | Markdown | Stephen1324/Online-Library | 85b4646d62cf2572c4001ea643b71aa2462e0340 | d66e4cd2f5c4c3d0d540891c49be19f7f6841ca5 | |
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 Admin4You
{
public partial class RestBookingPerDate : Form
{
private Models.RestaurantModel restToUse;
public void SetRestToUse(Models.RestaurantModel rest)
{
restToUse = rest;
}
static private RestBookingPerDate _instance;
static public RestBookingPerDate getInstance()
{
if (_instance == null)
_instance = new RestBookingPerDate();
return _instance;
}
public RestBookingPerDate()
{
InitializeComponent();
}
private void RestBookingPerDate_VisibleChanged(object sender, EventArgs e)
{
label_show_id.Text = restToUse.id.ToString();
}
private void RestBookingPerDate_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
private void btOk_Click(object sender, EventArgs e)
{
dataGridView_ShowBookings.DataSource = BusinessLayer.RestBL.GetBookingByRestIDandDate(restToUse.id, dateTimePicker_ShowBooking.Value.Date);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Models;
using System.Data;
namespace BusinessLayer
{
public class RestBL
{
public static RestaurantModel GetRestaurantByIDBL(int idRestToUse)
{
return DataAcessLayer.RestDAL.GetRestByIdDAL(idRestToUse);
}
public static DataView GetTableByRestIDandDate(int pRestID, DateTime pDate)
{
return DataAcessLayer.RestDAL.GetTablesByRestIDandDateDAL(pRestID, pDate);
}
public static DataView GetBookingByRestIDandDate(int pRestID, DateTime pDate)
{
return DataAcessLayer.RestDAL.GetBookingByRestIDandDateDAL(pRestID, pDate);
}
public static DataView GetMealByRestIDBL(int pRestID)
{
return DataAcessLayer.RestDAL.GetMealsByRestIDDAL(pRestID);
}
public static DataView GetRefMealByGroupIDBL(int pGroupID)
{
return DataAcessLayer.RestDAL.GetRefMByGroupIDDAL(pGroupID);
}
public static void InsertOrUpdateNewAvailableDishBL(int pREFM_ID, int pREST_ID, int pMEALREST_Price)
{
DataAcessLayer.RestDAL.InsertOrUpdateNewAvailableDishDAL(pREFM_ID, pREST_ID, pMEALREST_Price);
}
static public DataTable GetMealsByRestIDandTypeBL(int pRestID, int pTypeID)
{
return DataAcessLayer.RestDAL.GetMealsByRestIDandTypeDAL(pRestID, pTypeID);
}
public static DataView GetComboByRestIDBL(int pRestID)
{
return DataAcessLayer.RestDAL.GetComboByRestIDDAL(pRestID);
}
public static void InsertOrUpdateComboBL(int pRestID, int pStarterID, int pMainCourseID, int pDessertID, string pName)
{
//Pour déterminer le prix du combo qui doit être égal au MSRP des produits - 10% arrondi à l'unité inférieur, on appelle la DAL pour qu'elle nous fournisse ces prix.
DataView oDataView = DataAcessLayer.FunctionTestDAL.GetPriceWithREFMDAL(pStarterID, pMainCourseID, pDessertID);
DataRowView oRow = (DataRowView)oDataView[0];
int pPrice = (Convert.ToInt32(oRow.Row[0]) + Convert.ToInt32(oRow.Row[1]) + Convert.ToInt32(oRow.Row[2])); // le prix du combo est celui de la somme de ses msrp avec la réduction de la ligne suivante
pPrice = pPrice - (int)Math.Ceiling(pPrice/10.0); // Utilisation de la fonction Math.Ceiling pour obtenir un arrondi inférieur qui est casté en int afin de pouvoir le soustraire au prix et obtenir la réduction.
DataAcessLayer.FunctionTestDAL.InsertOrUpdateComboDAL(pRestID, pStarterID, pMainCourseID, pDessertID, pPrice, pName);
}
}
}
<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;
namespace DataAcessLayer
{
public static class GroupDAL
{
//Permet de récupérer un Group en utilisant seulement son ID
public static Models.GroupModel GetGroupByIdDAL(int pId)
{
Models.GroupModel groupToReturn = new Models.GroupModel();
try
{
using (SqlConnection oConnect = new SqlConnection(Utils._connectionString))
{
SqlCommand oComm = new SqlCommand();
SqlParameter oParam = new SqlParameter("@GrId", pId);
oComm.Parameters.Add(oParam);
oComm.Connection = oConnect;
oComm.CommandType = System.Data.CommandType.StoredProcedure;
oComm.CommandText = "SelectGroupById";
oConnect.Open();
SqlDataReader reader = oComm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
groupToReturn.id = reader.GetInt32(0);
groupToReturn.Name = reader.GetString(1);
}
//Console.WriteLine("Connection successfull and reader has rows."); //Debug
}
else groupToReturn = null;
oConnect.Close();
}
}
catch { }
return groupToReturn;
}
static public DataView GetPrices(DateTime date, int RestId)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("SelectPreoIDByRestAndDate", oConn);
SqlParameter oParam1 = new SqlParameter("@Date", date.Date);
SqlParameter oParam2 = new SqlParameter("@RestId", RestId);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("Preo");
oConn.Open();
oDataAdapter.Fill(oDataSet, "Preo");
//Console.WriteLine("DataSet OK !");
oConn.Close();
return oDataSet.Tables["Preo"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public DataView GetRestaurantsByGroupId(int pGrId)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("SelectRestByGroupId", oConn);
SqlParameter oParam2 = new SqlParameter("@GrId", pGrId);
oComm.Parameters.Add(oParam2);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("RESTAURANTS");
oConn.Open();
oDataAdapter.Fill(oDataSet, "RESTAURANTS");
Console.WriteLine("DataSet OK !");
oConn.Close();
return oDataSet.Tables["RESTAURANTS"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public int GetComboPriceDAL(int pComboId)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
int priceToReturn = -1;
try
{
SqlCommand oComm = new SqlCommand("GetComboPriceByID", oConn);
oComm.CommandType = CommandType.StoredProcedure;
SqlParameter oParam1 = new SqlParameter("@ComboId", pComboId);
oComm.Parameters.Add(oParam1);
oConn.Open();
SqlDataReader reader = oComm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
priceToReturn = reader.GetInt32(0);
}
Console.WriteLine("Connection successfull and reader has rows."); //Debug
}
oConn.Close();
}
catch { }
return priceToReturn;
}
}
}
}
<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 Admin4You
{
public partial class RestTablePerDate : Form
{
private Models.RestaurantModel restToUse;
public void SetRestToUse(Models.RestaurantModel rest)
{
restToUse = rest;
}
static private RestTablePerDate _instance;
static public RestTablePerDate getInstance()
{
if (_instance == null)
_instance = new RestTablePerDate();
return _instance;
}
public RestTablePerDate()
{
InitializeComponent();
}
private void RestTablePerDate_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
private void btOk_Click(object sender, EventArgs e)
{
dataGridView_ShowTable.DataSource = BusinessLayer.RestBL.GetTableByRestIDandDate(restToUse.id, dateTimePicker_ShowTable.Value.Date);
}
private void RestTablePerDate_VisibleChanged(object sender, EventArgs e)
{
label_show_id.Text = restToUse.id.ToString();
}
}
}
<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 Admin4You
{
public partial class RestComboMaker : Form
{
//Implémentation du principe de singleton. On n'instancie pas quand on utilise mais on fais le getInstance(),
// cela permet de n'avoir qu'une seule instance de la fenêtre à la fois.
static private RestComboMaker _instance;
static public RestComboMaker getInstance()
{
if (_instance == null)
_instance = new RestComboMaker();
return _instance;
}
//Mise en place d'un objet Restaurant model propre à la form. sera attribué lors de l'appel à l'affichage. Détermine quel restaurant est administré ici.
private Models.RestaurantModel restToAdmin;
public void SetRestToAdmin(Models.RestaurantModel rest) { restToAdmin = rest; }
public RestComboMaker()
{
InitializeComponent();
}
//Application du principe de singleton, on ne détruit plus la form mais on la cache.
private void RestComboMaker_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
comboBox_Starter.Update();
this.Hide();
}
//Mise à jour des infos à chaque affichage, application du principe de singleton.
private void RestComboMaker_VisibleChanged(object sender, EventArgs e)
{
label_show_RestID.Text = restToAdmin.id.ToString();
dataGridView_ShowCombo.DataSource = BusinessLayer.RestBL.GetComboByRestIDBL(restToAdmin.id);
comboBox_Starter.DataSource = BusinessLayer.RestBL.GetMealsByRestIDandTypeBL(restToAdmin.id, 1); //Attente de l'implémentation de la BL -> DAL -> SP
comboBox_MainCourse.DataSource = BusinessLayer.RestBL.GetMealsByRestIDandTypeBL(restToAdmin.id, 2);
comboBox_Dessert.DataSource = BusinessLayer.RestBL.GetMealsByRestIDandTypeBL(restToAdmin.id, 3);
comboBox_Starter.DisplayMember = "Nom du plat"; comboBox_Starter.ValueMember = "REFM_Name";
comboBox_MainCourse.DisplayMember = "Nom du plat"; comboBox_MainCourse.ValueMember = "REFM_Name";
comboBox_Dessert.DisplayMember = "Nom du plat"; comboBox_Dessert.ValueMember = "REFM_Name";
}
private void bt_Add_Click(object sender, EventArgs e)
{
int pRestId = restToAdmin.id;
int pStarterID = (int)((DataRowView)comboBox_Starter.SelectedItem).Row[0];
int pMainCourseID = (int)((DataRowView)comboBox_MainCourse.SelectedItem).Row[0];
int pDessertID = (int)((DataRowView)comboBox_Dessert.SelectedItem).Row[0];
BusinessLayer.RestBL.InsertOrUpdateComboBL(pRestId, pStarterID, pMainCourseID, pDessertID, textBox_ComboName.Text);
dataGridView_ShowCombo.DataSource = BusinessLayer.RestBL.GetComboByRestIDBL(restToAdmin.id);
}
}
}
<file_sep>using Models;
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;
/* ATTENTION A LA GESTION D'ERREUR
* -> N'est pas traité : entré d'un id de groupe qui ne corresponds pas !
*/
namespace Admin4You
{
public partial class GroupAdmin : Form
{
private GroupModel groupToAdmin;
private static GroupAdmin _instance;
//Implémentation du principe de singleton. On n'instancie pas quand on utilise mais on fais le getInstance(),
// cela permet de n'avoir qu'une seule instance de la fenêtre à la fois.
public static GroupAdmin getGrAdmin()
{
if (_instance == null)
_instance = new GroupAdmin();
return _instance;
}
public void setGrouptoAdmin(GroupModel grToAdmin)
{
groupToAdmin = grToAdmin;
}
public GroupAdmin()
{
InitializeComponent();
}
private void GroupAdmin_FormClosing(object sender, FormClosingEventArgs e)
{//Application du principe de singleton, on ne détruit plus la form mais on la cache.
e.Cancel = true;
this.Hide();
}
private void voirLeChiffreDuRestaurantÀUneDateDonnéeToolStripMenuItem_Click(object sender, EventArgs e)
{
int restaurantSelected = Convert.ToInt32(dataGridView_restaurant.SelectedCells[0].Value);
label_show_MoneyMade.Text = BusinessLayer.GroupBL.GetPreoPriceBL(dtp_dayToWatch.Value.Date, restaurantSelected).ToString();
}
//Vu le principe de singleton, ceci permet qu'à chaque fois que la form est ouverte, on affiche des données mises à jour.
private void GroupAdmin_VisibleChanged(object sender, EventArgs e)
{
dataGridView_restaurant.DataSource = BusinessLayer.GroupBL.GetRestByGroupIDBL(groupToAdmin.id);
}
}
}
<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;
namespace DataAcessLayer
{
public class RestDAL
{
public static Models.RestaurantModel GetRestByIdDAL(int pId)
{
Models.RestaurantModel restToReturn = new Models.RestaurantModel();
try
{
using (SqlConnection oConnect = new SqlConnection(Utils._connectionString))
{
SqlCommand oComm = new SqlCommand();
SqlParameter oParam = new SqlParameter("@RestID", pId);
oComm.Parameters.Add(oParam);
oComm.Connection = oConnect;
oComm.CommandType = System.Data.CommandType.StoredProcedure;
oComm.CommandText = "GetRestByID";
oConnect.Open();
SqlDataReader reader = oComm.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
restToReturn.id = reader.GetInt32(0);
restToReturn.grId = reader.GetInt32(1);
restToReturn.place = reader.GetInt32(2);
restToReturn.name = reader.GetString(3);
}
Console.WriteLine("Connection successfull and reader has rows."); //Debug
}
else restToReturn = null;
oConnect.Close();
}
}
catch { }
return restToReturn;
}
static public DataView GetTablesByRestIDandDateDAL(int pRestID, DateTime pDate)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetTableByDateAndRestID", oConn);
SqlParameter oParam1 = new SqlParameter("@RestID", pRestID);
SqlParameter oParam2 = new SqlParameter("@Date", pDate);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("TableByRestIDandDate");
oConn.Open();
oDataAdapter.Fill(oDataSet, "TableByRestIDandDate");
Console.WriteLine("DataSet tables OK !");
oConn.Close();
return oDataSet.Tables["TableByRestIDandDate"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public DataView GetBookingByRestIDandDateDAL(int pRestID, DateTime pDate)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetBookingByRestIDandDate", oConn);
SqlParameter oParam1 = new SqlParameter("@RestID", pRestID);
SqlParameter oParam2 = new SqlParameter("@Date", pDate);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("BookByRestIDandDate");
oConn.Open();
oDataAdapter.Fill(oDataSet, "BookByRestIDandDate");
Console.WriteLine("DataSet book OK !");
oConn.Close();
return oDataSet.Tables["BookByRestIDandDate"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public DataView GetMealsByRestIDDAL(int pRestID)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetAllMealRestByRestID", oConn);
SqlParameter oParam1 = new SqlParameter("@RestID", pRestID);
oComm.Parameters.Add(oParam1);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("MealByRestID");
oConn.Open();
oDataAdapter.Fill(oDataSet, "MealByRestID");
Console.WriteLine("DataSet meals OK !"); // DEBUG
oConn.Close();
return oDataSet.Tables["MealByRestID"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public DataView GetRefMByGroupIDDAL(int pGroupID)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetREFMavailablebyGroupID", oConn);
SqlParameter oParam1 = new SqlParameter("@GroupID", pGroupID);
oComm.Parameters.Add(oParam1);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("RefMealByGroupID");
oConn.Open();
oDataAdapter.Fill(oDataSet, "RefMealByGroupID");
Console.WriteLine("DataSet refmeals OK !"); // DEBUG
oConn.Close();
return oDataSet.Tables["RefMealByGroupID"].DefaultView;
}
catch { return null; }
finally { }
}
}
public static DataView GetComboByRestIDDAL(int pRestID)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetComboByRestID", oConn);
SqlParameter oParam1 = new SqlParameter("@RestID", pRestID);
oComm.Parameters.Add(oParam1);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("ComboByRestID");
oConn.Open();
oDataAdapter.Fill(oDataSet, "ComboByRestID");
Console.WriteLine("DataSet combo OK !"); // DEBUG
oConn.Close();
return oDataSet.Tables["ComboByRestID"].DefaultView;
}
catch { return null; }
finally { }
}
}
static public void InsertOrUpdateNewAvailableDishDAL(int pREFM_ID, int pREST_ID, int pMEALREST_Price)
{// ATTENTION ! UN SCOPE DOIT ÊTRE PLACÉ ICI !!!!!
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
//Mise en place de la commande SP
SqlCommand oComm = new SqlCommand("InsertOrUpdateNewAvailableDish", oConn);
oComm.CommandType = CommandType.StoredProcedure;
SqlParameter oParam1 = new SqlParameter("@REFM_ID", pREFM_ID);
SqlParameter oParam2 = new SqlParameter("@REST_ID", pREST_ID);
SqlParameter oParam3 = new SqlParameter("@MEALREST_Price", pMEALREST_Price);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.Parameters.Add(oParam3);
oConn.Open();
oComm.ExecuteNonQuery();
oConn.Close();
}
catch { }
finally { }
}
}
static public DataTable GetMealsByRestIDandTypeDAL(int pRestID, int pTypeID)
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
SqlCommand oComm = new SqlCommand("GetMealsByRestIDandType", oConn);
SqlParameter oParam1 = new SqlParameter("@RestID", pRestID);
SqlParameter oParam2 = new SqlParameter("@TypeID", pTypeID);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter oDataAdapter = new SqlDataAdapter(oComm);
DataSet oDataSet = new DataSet("MealsByRestIDandType");
oConn.Open();
oDataAdapter.Fill(oDataSet, "MealsByRestIDandType");
Console.WriteLine("DataSet refmeals OK !"); // DEBUG
oConn.Close();
return oDataSet.Tables["MealsByRestIDandType"];
}
catch { return null; }
finally { }
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataAcessLayer;
namespace BusinessLayer
{
public static class GroupBL
{
public static Models.GroupModel GetGroupByIdBL(int pId)
{
return DataAcessLayer.GroupDAL.GetGroupByIdDAL(pId);
}
public static int GetPreoPriceBL(DateTime date, int RestId)
{
DataView oDataView = DataAcessLayer.GroupDAL.GetPrices(date, RestId);
int Money = 0;
foreach (DataRowView oRow in oDataView)
{
int comboId = 0;
if (int.TryParse(oRow[1].ToString(), out comboId))
DataAcessLayer.GroupDAL.GetComboPriceDAL(comboId);
else
Money += Convert.ToInt32(oRow["Total"]);
}
return Money;
}
public static DataView GetRestByGroupIDBL(int pGrId)
{
return DataAcessLayer.GroupDAL.GetRestaurantsByGroupId(pGrId);
}
}
}
<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;
namespace DataAcessLayer
{
public class FunctionTestDAL
{
static public void InsertOrUpdateComboDAL(int pRestID, int pStarterID, int pMainCourseID, int pDessertID, int pPrice, string pName)
{// ATTENTION ! UN SCOPE DOIT ÊTRE PLACÉ ICI !!!!!
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
try
{
//Mise en place de la commande SP
SqlCommand oComm = new SqlCommand("InsertOrUpdateCombo ", oConn);
oComm.CommandType = CommandType.StoredProcedure;
SqlParameter oParam1 = new SqlParameter("REFM_ID_Starter", pStarterID);
SqlParameter oParam2 = new SqlParameter("REFM_ID_MainCourse", pMainCourseID);
SqlParameter oParam3 = new SqlParameter("REFM_ID_Dessert", pDessertID);
SqlParameter oParam4 = new SqlParameter("@COMBO_Price", pPrice);
SqlParameter oParam5 = new SqlParameter("@COMBO_REST_ID", pRestID);
SqlParameter oParam6 = new SqlParameter("@COMBO_Name", pName);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.Parameters.Add(oParam3);
oComm.Parameters.Add(oParam4);
oComm.Parameters.Add(oParam5);
oComm.Parameters.Add(oParam6);
//Execution de la SP
oConn.Open();
oComm.ExecuteNonQuery();
oConn.Close();
}
catch {}
finally { }
}
}
static public DataView GetPriceWithREFMDAL(int pStarterID, int pMainCourseID, int pDessertID)
{
try
{
using (SqlConnection oConn = new SqlConnection(Utils._connectionString))
{
SqlCommand oComm = new SqlCommand("GetREFM_MSRPbyREFMID", oConn);
SqlParameter oParam1 = new SqlParameter("@REFM_Starter_ID", pStarterID);
SqlParameter oParam2 = new SqlParameter("@REFM_MainCourse_ID", pMainCourseID);
SqlParameter oParam3 = new SqlParameter("@REFM_Dessert_ID", pDessertID);
oComm.Parameters.Add(oParam1);
oComm.Parameters.Add(oParam2);
oComm.Parameters.Add(oParam3);
oComm.CommandType = CommandType.StoredProcedure;
DataSet oDataSet = new DataSet("MSRP");
SqlDataAdapter oAdapter = new SqlDataAdapter(oComm);
oConn.Open();
oAdapter.Fill(oDataSet,"MSRP");
oConn.Close();
return oDataSet.Tables["MSRP"].DefaultView;
}
}
catch { return null; }
finally { }
}
}
}
<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;
using BusinessLayer;
namespace Admin4You
{
public partial class RestID : Form
{
//Implémentation du principe de singleton. On n'instancie pas quand on utilise mais on fais le getInstance(),
// cela permet de n'avoir qu'une seule instance de la fenêtre à la fois.
static private RestID _instance;
static public RestID GetInstance()
{
if (_instance == null)
_instance = new RestID();
return _instance;
}
//Permet de savoir ce qui va être fait ensuite. Set dans la form appellante.
private int whatToDoNext;
public void SetWhatToDoNext(int wtdn) { whatToDoNext = wtdn; }
public RestID()
{
InitializeComponent();
}
//Application du principe de singleton, on ne détruit plus la form mais on la cache.
private void btCancel_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btOk_Click(object sender, EventArgs e)
{
int idRestToUse;
if(int.TryParse(txtRestId.Text, out idRestToUse))//Rentre dans le if si on arrive à extraire la valeur du TextBox.
{
Models.RestaurantModel restToAdmin = BusinessLayer.RestBL.GetRestaurantByIDBL(idRestToUse);
if (restToAdmin == null) // Dans le cas ou on ne récupère pas un ID de restau valide, on envoie un messagebox qui clear la textbox et qui averti l'utilisateur du problème.
{
MessageBox.Show("L'id que vous avez rentré ne corresponds pas.", "ERREUR", MessageBoxButtons.OK);
txtRestId.Text = "";
}
else // Si on a bien récupéré un restau
{
switch (whatToDoNext) // Va ouvrir la form tel que prévu par le switch, whatToDoNext ayant été set lors du clic sur le menustrip correspondant.
{
case 1: // gererLesPlatsDisponibles
RestDishAvailable restDish = RestDishAvailable.getInstance();
restDish.setRestToAdmin(restToAdmin);
restDish.MdiParent = this.MdiParent;
restDish.Hide();
restDish.Show();
this.Hide();
break;
case 2:
RestComboMaker restCombo = RestComboMaker.getInstance();
restCombo.SetRestToAdmin(restToAdmin);
restCombo.MdiParent = this.MdiParent;
restCombo.Hide();
restCombo.Show();
this.Hide();
break;
case 3: // voirLesReservationsParDate
RestBookingPerDate restBook = RestBookingPerDate.getInstance();
restBook.SetRestToUse(restToAdmin);
restBook.MdiParent = this.MdiParent;
restBook.Hide();
restBook.Show();
this.Hide();
break;
case 4: // voirLesTablesParDates
RestTablePerDate restTable = RestTablePerDate.getInstance();
restTable.SetRestToUse(restToAdmin);
restTable.MdiParent = this.MdiParent;
restTable.Hide();
restTable.Show();
this.Hide();
break;
default: //Si il y a une erreur et qu'il y a une mauvaise valeur set, on envoie un messagebox explicant qu'une erreur est survenue. On ne devrait jamais être confronté au cas mais on sait jamais.
MessageBox.Show("Une erreur est survenue.", "ERREUR", MessageBoxButtons.OK);
break;
}
}
}
}
//Application du principe de singleton, on ne détruit plus la form mais on la cache.
private void RestID_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
}
}
<file_sep>Liste des contraintes d'unicité :
- Customer : Name+LastName+DateOfBirth
- Group : Name
- Restaurant : Name+Place
- RefMeal : Name+Grou_Id+Type_Id
Tables populées :
- Customer
- Table
- Group
- Restaurant
- Type
- RefMeal
--> a populer : MealRest +-, Combo, Preor+-, Book+-<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 Admin4You
{
public partial class GroupId : Form
{
//Implémentation du principe de singleton. On n'instancie pas quand on utilise mais on fais le getInstance(),
// cela permet de n'avoir qu'une seule instance de la fenêtre à la fois.
static private GroupId _instance;
static public GroupId getInstance()
{
if (_instance == null)
_instance = new GroupId();
return _instance;
}
public GroupId()
{
InitializeComponent();
}
//Application du principe de singleton, on ne détruit plus la form mais on la cache.
private void btCancel_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btOk_Click(object sender, EventArgs e)
{
int idGroupToUse;
if (int.TryParse(txtGroupId.Text, out idGroupToUse))
{
Models.GroupModel grToAdmin = BusinessLayer.GroupBL.GetGroupByIdBL(idGroupToUse); //Récupère le Group Exact via une Sp.
if(grToAdmin == null) //Dans le cas ou le group n'a pu être récupéré, renvoie une messageBox avec une erreur. Reset du TextBox.
{
MessageBox.Show("L'ID que vous avez rentré ne corresponds pas.", "ERREUR", MessageBoxButtons.OK);
txtGroupId.Text = "";
}
else
{
GroupAdmin grad = GroupAdmin.getGrAdmin(); //Sinon on ouvre la nouvelle form (principe singleton) et on set le group qu'on a trouvé.
grad.setGrouptoAdmin(grToAdmin);
grad.MdiParent = this.MdiParent;
grad.Hide();
grad.Show();
}
this.Hide();
}
else
{ //Si le textbox n'a pu être parsé, on envoie une message box et on reset le Textbox
MessageBox.Show("Veuillez rentrer un nombre dans le champ SVP", "ERREUR", MessageBoxButtons.OK);
txtGroupId.Text = "";
}
}
private void GroupId_FormClosing(object sender, FormClosingEventArgs e)
{ //Application du principe de singleton, on ne détruit plus la form mais on la cache.
e.Cancel = true;
this.Hide();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataAcessLayer
{
static class Utils
{
static public string _connectionString = "Data Source=DESKTOP-63FMG3J;Initial Catalog=Resto4You;User ID=sa;Password=<PASSWORD>";
}
}
<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 Admin4You
{
public partial class RestAdmin4YouForm : Form
{
//A chaque fois on gardera cette form-ci comme MdiParent, meme pour les forms ouvertes par la suite.
public RestAdmin4YouForm()
{
InitializeComponent();
}
//Partie de la gestion du groupe.
private void voirLesChiffresParDateToolStripMenuItem_Click(object sender, EventArgs e)
{
GroupId groupAuth = GroupId.getInstance();
groupAuth.MdiParent = this;
groupAuth.Show();
}
//Partie de la gestion du Restaurant. En fonction du menustrip cliqué, va set le WhatToDoNext de la form RestID appellée afin qu'il sache ouvrir la form correspondante.
//Ceci permet d'utiliser une seule fenêtre d'identification du restaurant.
private void gererLesPlatsDisponiblesToolStripMenuItem_Click(object sender, EventArgs e)
{
RestID restAuth = RestID.GetInstance();
restAuth.SetWhatToDoNext(1);
restAuth.MdiParent = this;
restAuth.Show();
}
private void gererLesMenusDisponiblesToolStripMenuItem_Click(object sender, EventArgs e)
{
RestID restAuth = RestID.GetInstance();
restAuth.SetWhatToDoNext(2);
restAuth.MdiParent = this;
restAuth.Show();
}
private void voirLesReservationsParDateToolStripMenuItem_Click(object sender, EventArgs e)
{
RestID restAuth = RestID.GetInstance();
restAuth.SetWhatToDoNext(3);
restAuth.MdiParent = this;
restAuth.Show();
}
private void voirLesTablesParDatesToolStripMenuItem_Click(object sender, EventArgs e)
{
RestID restAuth = RestID.GetInstance();
restAuth.SetWhatToDoNext(4);
restAuth.MdiParent = this;
restAuth.Show();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class RestaurantModel
{
public int id { get; set; }
public int grId { get; set; }
public int place { get; set; }
public string name { get; set; }
}
}
<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 Admin4You
{
public partial class RestDishAvailable : Form
{
//Mise en place d'un objet Restaurant model propre à la form. sera attribué lors de l'appel à l'affichage. Détermine quel restaurant est administré ici.
private Models.RestaurantModel restToAdmin;
public void setRestToAdmin(Models.RestaurantModel rest)
{
restToAdmin = rest;
}
//Implémentation du principe de singleton. On n'instancie pas quand on utilise mais on fais le getInstance(),
// cela permet de n'avoir qu'une seule instance de la fenêtre à la fois.
static private RestDishAvailable _instance;
static public RestDishAvailable getInstance()
{
if (_instance == null)
_instance = new RestDishAvailable();
return _instance;
}
public RestDishAvailable()
{
InitializeComponent();
}
private void RestDishAvailable_VisibleChanged(object sender, EventArgs e)
{//Charge les différents affichage de la form. vu le principe de singleton permet de garder les informations à jour à chaque affichage de la form.
label_show_RestID.Text = restToAdmin.id.ToString();
dataGridView_ShowDishesAvailableInTheRestau.DataSource = BusinessLayer.RestBL.GetMealByRestIDBL(restToAdmin.id);
dataGridView_ShowDishesAvailableForTheGroup.DataSource = BusinessLayer.RestBL.GetRefMealByGroupIDBL(restToAdmin.grId);
}
private void bt_Add_Click(object sender, EventArgs e)
{
int pPrice;
if (int.TryParse(textBox_Price.Text, out pPrice)) //if conditionné sur la récupération du prix dans la textbox.
{//remonte => BL => DAL => Sp pour inserer le nouveau plat proposé, utilisant la ligne sélectionné dans la Grid avec les plats du group, l'ID du restau et le prix de la box.
BusinessLayer.RestBL.InsertOrUpdateNewAvailableDishBL(Convert.ToInt32(dataGridView_ShowDishesAvailableForTheGroup.SelectedCells[0].Value), restToAdmin.id, pPrice);
dataGridView_ShowDishesAvailableInTheRestau.DataSource = BusinessLayer.RestBL.GetMealByRestIDBL(restToAdmin.id);
}
else //Si récupération impossible envoie un message box et reset le text du TextBox.
{
MessageBox.Show("Une erreur est survenue.", "ERREUR", MessageBoxButtons.OK);
textBox_Price.Text = "";
}
}
//Application du principe de singleton, on ne détruit plus la form mais on la cache.
private void RestDishAvailable_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
}
}
| dce6c9376c515a5b74313e5182d21c943f6ff7e5 | [
"C#",
"Text"
] | 16 | C# | Neskyte/Resto4You | 0ebc3715846a5c0bedb10487e7f36099efbe14e0 | 2553c81c65339c15e3924f1cc98a4a89ea7e8035 | |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-breadcrumb',
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.scss']
})
export class BreadcrumbComponent implements OnInit {
constructor(private router: Router) { }
route: String = "/management"
routeName: String = this.parseRoute(this.router.url)
parseRoute(route: String): String {
switch (route) {
case '/management':
this.route = '/management'
return '> Painel de Gestão'
break;
case '/account':
this.route = '/account'
return '> Conta Digital'
break;
case '/anticipation':
this.route = '/anticipation'
return '> Ant. de Recebíveis'
break;
}
}
ngOnInit() {
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { DashboardManagementComponent } from '../views/dashboard-management/dashboard-management.component';
import { DigitalAccountComponent } from '../views/digital-account/digital-account.component';
import { AnticipationOfReceivablesComponent } from '../views/anticipation-of-receivables/anticipation-of-receivables.component';
const routes: Routes = [
{
path: '',
redirectTo: 'management',
pathMatch: 'full'
},
{
path: 'management',
component: DashboardManagementComponent
},
{
path: 'account',
component: DigitalAccountComponent
},
{
path: 'anticipation',
component: AnticipationOfReceivablesComponent
}
]
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
constructor() { }
ngOnInit() {
}
openSelect() {
const select = document.getElementById('select')
select.click();
}
logo = require('src/assets/images/logo.png')
user = require('src/assets/images/user.png')
bell = require('src/assets/images/bell.png')
arrows = require('src/assets/images/down-icon.png')
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './router/app-routing.module';
import { SidenavComponent } from './components/sidenav/sidenav.component';
import { DashboardManagementComponent } from './views/dashboard-management/dashboard-management.component'
import { DigitalAccountComponent } from './views/digital-account/digital-account.component';
import { AnticipationOfReceivablesComponent } from './views/anticipation-of-receivables/anticipation-of-receivables.component';
import { HeaderComponent } from './components/header/header.component';
import { BreadcrumbComponent } from './components/breadcrumb/breadcrumb.component';
import { ShortcutsComponent } from './components/shortcuts/shortcuts.component';
import { AlertsComponent } from './components/alerts/alerts.component';
@NgModule({
declarations: [
AppComponent,
SidenavComponent,
DashboardManagementComponent,
DigitalAccountComponent,
AnticipationOfReceivablesComponent,
HeaderComponent,
BreadcrumbComponent,
ShortcutsComponent,
AlertsComponent
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-anticipation-of-receivables',
templateUrl: './anticipation-of-receivables.component.html',
styleUrls: ['./anticipation-of-receivables.component.scss']
})
export class AnticipationOfReceivablesComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
| 568f38345c37d5425fa461fd6d8024db1dca0991 | [
"TypeScript"
] | 5 | TypeScript | octaviocarpes/SRM-Asset | 7ac72526076364577bd7c4f2847d26a3a1b23b27 | d9fc57d25052804444d2981c4959c85079519813 | |
refs/heads/master | <file_sep>import React from "react";
import "./styles.css";
const loading = props =>
props.loading && (
<div
style={{ width: `${props.size}px`, height: `${props.size}px` }}
className="spinner"
></div>
);
export default loading;
<file_sep>import React, { Component } from "react";
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { creators as authActions } from '../../../store/ducks/auth'
import HoursOfDayForm from "./components/HoursOfDayForm";
import Menu from './components/Menu'
import Result from './components/Result/Result'
import List from "./components/List";
import Loading from '../../shared/loading'
class CompTime extends Component {
render() {
return (
<section className="container">
{this.props.auth.user.email &&
<div className="row">
<div className="grid-item-6 align-center content-center">
Logado como: {this.props.auth.user.email} <button onClick={() => this.props.logOut()}>Sair</button>
</div>
</div>
}
<HoursOfDayForm />
<div className="row align-center space-between">
<div className="grid-item-4 block">
<Menu/>
</div>
<div className="grid-item-2">
<Result/>
</div>
</div>
<List/>
</section>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
loading: state.global.loading
});
const mapDispatchToProps = dispatch =>
bindActionCreators(authActions, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(CompTime)
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './static/css/setup.css'
import './static/icons/style.css'
import './static/css/layout.css'
import './static/css/utils.css'
import './static/css/form.css'
import './static/css/button.css'
ReactDOM.render(<App />, document.getElementById('root'));
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { creators as comptimeCreators } from "../../../../store/ducks/comptime";
class components extends Component {
changeYear = e => {
this.props.setMonthSelected("");
this.props.setYearSelected(e.target.value);
};
changeMonth = e => {
let month = `${e.target.value < 10 ? "0" : ""}${e.target.value}`;
this.props.setMonthSelected(month);
if (!!month == false) return;
this.props.getComptimeList(this.props.auth.user.userId, this.props.yearSelected, month);
};
pastYears = () => {
let years = []
let currentYear = new Date().getFullYear()
let startYear = 2019
while ( startYear <= currentYear ) {
years.push(startYear++);
}
return years
}
pastMonths = () => {
let currentDate = new Date()
let currentMonth = this.props.yearSelected == currentDate.getFullYear() ? currentDate.getMonth() + 1 : 12
let months = []
let monthsRaw = [
{key: "1", label: "Janeiro"},
{key: "2", label: "Fevereiro"},
{key: "3", label: "Março"},
{key: "4", label: "Abril"},
{key: "5", label: "Maio"},
{key: "6", label: "Junho"},
{key: "7", label: "Julho"},
{key: "8", label: "Agosto"},
{key: "9", label: "Setembro"},
{key: "10", label: "Outubro"},
{key: "11", label: "Novembro"},
{key: "12", label: "Dezembro"}
]
for (let index = 1; index <= currentMonth; index++) {
months.push(monthsRaw[index-1])
}
return months
}
render() {
return (
<form noValidate className="row block">
<div className="grid-item-6 pt-4">
<div className="input-box">
<label>Ano</label>
<select
value={this.props.yearSelected}
onChange={e => this.changeYear(e)}
>
<option value="">Selecione uma opção</option>
{
this.pastYears().map( (year, index) => <option key={index} value={year}>{year}</option>)
}
</select>
</div>
</div>
<div className="grid-item-6 pt-4">
<div className="input-box">
<label>Mês</label>
<select
value={this.props.monthSelected}
disabled={!!this.props.yearSelected == false}
onChange={e => this.changeMonth(e)}
>
<option value="">Selecione uma opção</option>
{
this.pastMonths().map( (month, index) => <option key={index} value={month.key}>{month.label}</option>)
}
</select>
</div>
</div>
</form>
);
}
}
const mapStateToProps = state => ({
auth: state.auth,
yearSelected: state.comptime.yearSelected,
monthSelected: state.comptime.monthSelected,
});
const mapDispatchToProps = dispatch =>
bindActionCreators(comptimeCreators, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(components);
<file_sep>import React from 'react';
import './styles.css'
const Card = (props) => (
<div className="card">
<div className="card__inner">
{props.withHeader &&
<div className="card__header">
{props.withHeader}
</div>}
<div className="card__content">
{props.children}
</div>
{props.withFooter &&
<div className="card__footer">
{props.withFooter}
</div>}
</div>
</div>
);
export default Card;
<file_sep>import { combineReducers } from 'redux'
import { connectRouter } from 'connected-react-router'
import history from '../../history'
import global from './_global'
import auth from './auth'
import comptime from './comptime'
export default combineReducers({
global,
auth,
comptime,
router: connectRouter(history)
})<file_sep>import { takeLatest, put, call, delay } from "redux-saga/effects";
import { creators as globalCreators } from "../../ducks/_global";
import { types as comptimeTypes } from "../../ducks/comptime";
import { creators as comptimeCreators } from "../../ducks/comptime";
import rsfb from "../../services/firebaseConfig";
import { push } from "connected-react-router";
function* getComptimeList(action) {
yield put(comptimeCreators.setComptimeList([]));
let { idUsuario, ano, mes } = action.payload;
yield put(globalCreators.loading(true));
const querySnapshot = yield call(
rsfb.firestore.getCollection,
`usuarios/${idUsuario}/${ano}${mes}`
);
let comptimeList = [];
let comptimeId = "";
querySnapshot.forEach(res => {
let comptime = res.data().comptimeList;
comptimeId = res.id;
comptimeList = [...comptimeList, ...comptime];
});
// console.log(comptimeId)
// console.log(comptimeList)
if (!!comptimeList.length) {
yield put(comptimeCreators.setComptimeListId(comptimeId));
yield put(comptimeCreators.setComptimeList(comptimeList));
yield calcTotalHoursBank(comptimeList);
} else {
console.log("no comptimelist, creating a new one");
yield createNewComptimeList(action, idUsuario, ano, mes);
}
yield put(globalCreators.loading(false));
}
function* calcTotalHoursBank(comptimeList) {
if (!!comptimeList.length == false) return false;
let hours = 0,
minutes = 0,
negativeMinutes = false;
comptimeList.map(item => {
hours = item.difference.hours + hours;
minutes = item.difference.minutes + minutes;
});
minutes < 0 ? negativeMinutes = true : negativeMinutes = false
if (Math.abs(minutes) > 59 && negativeMinutes) {
let convertedTime = yield timeConvert(Math.abs(minutes));
hours = hours - convertedTime.hours;
minutes = convertedTime.minutes;
} else if (Math.abs(minutes) > 59 && (negativeMinutes == false)) {
let convertedTime = yield timeConvert(Math.abs(minutes));
hours = hours + convertedTime.hours;
minutes = convertedTime.minutes;
}
if (hours > 0 && negativeMinutes) {
hours = hours - 1
hours = `${hours < 10 ? "0" : ""}${hours}`
minutes = 60 - (Math.abs(minutes));
} else if(hours < 0 && negativeMinutes) {
hours = hours = `-${hours < 10 ? "0" : ""}${Math.abs(hours)}`
minutes = `${Math.abs(minutes) < 10 ? "0" : ""}${Math.abs(minutes)}`
} else if(hours < 0 && !negativeMinutes) {
hours = hours = `-${hours < 10 ? "0" : ""}${Math.abs(hours)}`
} else if(hours == 0 && negativeMinutes) {
hours = `-${hours < 10 ? "0" : ""}${Math.abs(hours)}`
minutes = `${Math.abs(minutes) < 10 ? "0" : ""}${Math.abs(minutes)}`
} else {
hours = `${hours < 10 ? "0" : ""}${hours}`
minutes = `${Math.abs(minutes) < 10 ? "0" : ""}${Math.abs(minutes)}`
}
let hoursBank = {
hours,
minutes
};
yield put(comptimeCreators.setHoursBank(hoursBank));
}
function* timeConvert(n) {
var num = n;
var hours = (num / 60);
var rhours = Math.floor(hours);
var minutes = (hours - rhours) * 60;
var rminutes = Math.round(minutes);
return {
hours: rhours,
minutes: rminutes
};
}
function* putComptimeList(action) {
yield put(globalCreators.loading(true));
let { idUsuario, ano, mes, id, comptimeList } = action.payload;
// console.log(id)
yield call(
rsfb.firestore.updateDocument,
`usuarios/${idUsuario}/${ano}${mes}/${id}`,
{ comptimeList }
);
yield put(
globalCreators.message({ type: "positive", text: "Comptime List updated!" })
);
yield delay(1000);
yield put(globalCreators.message({ type: "", text: "" }));
yield getComptimeList(action);
yield put(comptimeCreators.setShowingForm(false));
}
function* createNewComptimeList(action) {
let { idUsuario, ano, mes } = action.payload;
let numberOfDays = new Date(ano, mes, 0).getDate();
let comptimeList = [];
for (let i = 1; i <= numberOfDays; i++) {
let item = {
day: `${i < 10 ? "0" : ""}${i}/${mes}/${ano}`,
startingTime: "08:00",
lunchStart: "12:00",
lunchEnd: "13:00",
stoppingTime: "17:00",
difference: {
hours: 0,
minutes: 0
}
};
comptimeList.push(item);
}
yield call(rsfb.firestore.addDocument, `usuarios/${idUsuario}/${ano}${mes}`, {
comptimeList
});
yield getComptimeList(action);
}
export default [
takeLatest(comptimeTypes.GET_COMPTIMELIST, getComptimeList),
takeLatest(comptimeTypes.PUT_COMPTIMELIST, putComptimeList)
];
<file_sep>import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { creators as comptimeCreators } from '../../../../store/ducks/comptime'
import TimeInput from 'react-keyboard-time-input';
import Modal from '../../../shared/modal'
import Loading from '../../../shared/loading'
class components extends Component {
handleInputChange = (e, field) => {
if( (typeof e == 'string') && Number(e.substr(0,2)) > 23) return false
const comptime = { ...this.props.comptime }
comptime[field] = e
this.props.setComptime(comptime)
}
updateComptime = async (e) => {
e.preventDefault()
if(this.checkTime('startingTime') == false ) return false
if(this.checkTime('lunchStart') == false ) return false
if(this.checkTime('lunchEnd') == false ) return false
if(this.checkTime('stoppingTime') == false ) return false
let id = this.props.comptimeListId
let comptimeList = [...this.props.comptimeList]
let comptimeIndex = comptimeList.findIndex( item => item.day == this.props.comptime.day)
let hoursBank = await this.calcHoursBankOfDay(this.props.comptime)
await this.handleInputChange(hoursBank, 'difference')
comptimeList[comptimeIndex] = { ...comptimeList[comptimeIndex], ...this.props.comptime }
this.props.putComptimeList(
this.props.auth.user.userId,
this.props.yearSelected,
this.props.monthSelected,
id,
comptimeList
);
console.log(comptimeList)
}
americanDate(date) {
let datePart = date.match(/\d+/g),
year = datePart[0].substring(0),
month = datePart[1], day = datePart[2];
return day+'-'+month+'-'+year;
}
calcHoursBankOfDay(comptime) {
let workSchedule = 8 //in hours
let startingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['startingTime']}:00`)
let stoppingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['stoppingTime']}:00`)
let lunchStart = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchStart']}:00`)
let lunchEnd = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchEnd']}:00`)
let diffMsStartStop = (stoppingTime - startingTime);
let diffMsLunchTime = (lunchEnd - lunchStart);
let hoursDoneLunch = Math.floor((diffMsLunchTime % 86400000) / 3600000)
let minutesDoneLunch = Math.round(((diffMsLunchTime % 86400000) % 3600000) / 60000)
//anulando o banco de horas gerado por bater a volta do almoço mais cedo do que 1 hora
if(hoursDoneLunch < 1) {
hoursDoneLunch = 1
minutesDoneLunch = 0
}
let hoursDone = (Math.floor((diffMsStartStop % 86400000) / 3600000) ) - (hoursDoneLunch)
let minutesDone = Math.round(((diffMsStartStop % 86400000) % 3600000) / 60000) - (minutesDoneLunch)
let totalDone = {
hours: Number,
minutes: Number
}
if((hoursDone >= workSchedule) || minutesDone == '00') {
totalDone.hours = hoursDone - workSchedule
totalDone.minutes = minutesDone
} else {
totalDone.hours = (hoursDone - workSchedule) + 1
totalDone.minutes = (60 - minutesDone) * -1
}
return totalDone
}
checkTime = (field) => {
const comptime = { ...this.props.comptime }
switch(field) {
case 'startingTime':
var startingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['startingTime']}:00`)
var lunchStart = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchStart']}:00`)
if(startingTime > lunchStart)
{
alert('O horário de entrada deve ser anterior à hora de entrada do almoço.')
return false
}
break
case 'lunchStart':
var lunchStart = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchStart']}:00`)
var startingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['startingTime']}:00`)
var lunchEnd = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchEnd']}:00`)
if(lunchStart < startingTime)
{
alert('O horário de almoço deve ser depois da hora de entrada.')
return false
}
if(lunchStart > lunchEnd)
{
alert('O horário de entrada do almoço deve ser anterior a hora de saida do almoço.')
return false
}
break
case 'lunchEnd':
var lunchEnd = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchEnd']}:00`)
var lunchStart = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchStart']}:00`)
var stoppingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['stoppingTime']}:00`)
if(lunchEnd < lunchStart)
{
alert('O horário de saída do almoço deve ser depois da hora de entrada do almoço.')
return false
}
if(lunchEnd > stoppingTime)
{
alert('O horário de saída do almoço deve ser anterior à hora de saída.')
return false
}
break
case 'stoppingTime':
var stoppingTime = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['stoppingTime']}:00`)
var lunchEnd = new Date(`${this.americanDate(this.props.comptime.day)} ${comptime['lunchEnd']}:00`)
if(stoppingTime < lunchEnd)
{
alert('O horário de saída deve ser maior que o horário de saída do almoço.')
return false
}
break
default:
return true
}
}
render() {
return <div>
<Modal showing={this.props.showingForm}
close={() => this.props.setShowingForm(false)}>
<h1>{this.props.comptime.day}</h1>
<form noValidate onSubmit={(e) => this.updateComptime(e)}>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Entrada</label>
<TimeInput value={this.props.comptime.startingTime} onChange={(e) => this.handleInputChange(e, 'startingTime')}/>
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Entrada do almoço</label>
<TimeInput value={this.props.comptime.lunchStart}
onChange={(e) => this.handleInputChange(e, 'lunchStart')} type="text"/>
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Saída do almoço</label>
<TimeInput value={this.props.comptime.lunchEnd}
onChange={(e) => this.handleInputChange(e, 'lunchEnd')} type="text"/>
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Saída</label>
<TimeInput value={this.props.comptime.stoppingTime}
onChange={(e) => this.handleInputChange(e, 'stoppingTime')} type="text"/>
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
{this.props.loading ? <Loading loading={this.props.loading} size={22}/> : <button className="block">Salvar</button>}
</div>
</div>
</form>
</Modal>
</div>;
}
}
const mapStateToProps = state => ({
auth: state.auth,
yearSelected: state.comptime.yearSelected,
monthSelected: state.comptime.monthSelected,
comptime: state.comptime.comptime,
comptimeList: state.comptime.comptimeList,
comptimeListId: state.comptime.comptimeListId,
showingForm: state.comptime.showingForm,
loading: state.global.loading
});
const mapDispatchToProps = dispatch =>
bindActionCreators(comptimeCreators, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(components);
<file_sep>export const types = {
//saga types
GET_COMPTIMELIST: "comptime/ASYNC_GET_COMPTIMELIST",
PUT_COMPTIMELIST: "comptime/ASYNC_PUT_COMPTIMELIST",
//normal types
SET_YEAR: 'comptime/SET_YEAR',
SET_MONTH: 'comptime/SET_MONTH',
SET_COMPTIMELIST_ID: 'comptime/SET_COMPTIMELIST_ID',
SET_COMPTIMELIST: "comptime/SET_COMPTIMELIST",
SET_HOURSBANK: "comptime/SET_HOURSBANK",
SET_SHOWINGFORM: "comptime/SET_SHOWINGFORM",
SET_COMPTIME: "comptime/SET_COMPTIME",
}
export const creators = {
//saga creators
getComptimeList: (idUsuario, ano, mes) => ({
type: types.GET_COMPTIMELIST,
payload: {
idUsuario,
ano,
mes
}
}),
putComptimeList: (idUsuario, ano, mes, id, comptimeList, onClose) => ({
type: types.PUT_COMPTIMELIST,
payload: {
idUsuario,
ano,
mes,
id,
comptimeList,
onClose
}
}),
//normal creators
setYearSelected:(year) => ({
type: types.SET_YEAR,
payload: year
}),
setMonthSelected:(month) => ({
type: types.SET_MONTH,
payload: month
}),
setComptimeListId:(id) => ({
type: types.SET_COMPTIMELIST_ID,
payload: id
}),
setComptimeList:(comptimeList) => ({
type: types.SET_COMPTIMELIST,
payload: comptimeList
}),
setHoursBank:(hoursBank) => ({
type: types.SET_HOURSBANK,
payload: hoursBank
}),
setShowingForm:(boolean) => ({
type: types.SET_SHOWINGFORM,
payload: boolean
}),
setComptime:(comptime) => ({
type: types.SET_COMPTIME,
payload: comptime
}),
}
const INITIAL_STATE = {
yearSelected: '',
monthSelected: '',
comptimeListId: '',
comptimeList: [],
hoursBank: {
hours: '',
minutes: '',
},
showingForm: false,
comptime: {
day: '',
startingTime: '',
lunchStart: '',
lunchEnd: '',
stoppingTime: '',
difference: {
hours: 0,
minutes: 0
}
}
}
export default function comptime(state = INITIAL_STATE, action) {
switch (action.type) {
case types.SET_YEAR:
return { ...state, yearSelected: action.payload }
case types.SET_MONTH:
return { ...state, monthSelected: action.payload }
case types.SET_COMPTIMELIST_ID:
return { ...state, comptimeListId: action.payload }
case types.SET_SHOWINGFORM:
return { ...state, showingForm: action.payload }
case types.SET_COMPTIMELIST:
return { ...state, comptimeList: action.payload }
case types.SET_HOURSBANK:
return { ...state, hoursBank: action.payload }
case types.SET_COMPTIME:
return { ...state, comptime: action.payload }
default:
return state
}
}<file_sep>import { createStore, applyMiddleware, compose } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'
import history from '../history'
import createSagaMiddleware from 'redux-saga'
import rootSaga from './sagas'
import rootReducer from './ducks'
const sagaMiddleware = createSagaMiddleware()
const middlewares = [
sagaMiddleware,
routerMiddleware(history),
]
//sem redux devtools
//const store = createStore(rootReducer, applyMiddleware(sagaMiddleware), )
//utilizando o redux devtools
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(connectRouter(history)(rootReducer), composeEnhancers(
applyMiddleware(...middlewares)
));
sagaMiddleware.run(rootSaga)
export default store<file_sep>import React, {Component} from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Creators as todolistActions } from '../../../store/ducks/todos'
import Header from '../../shared/header'
import Loading from '../../shared/loading'
class SecondaryPage extends Component {
state = {
navItems: [
{ type: "routerlink", link: "/test0", title: "title0" },
{ type: "routerlink", link: "/test1", title: "title1" },
{ type: "anchor", link: "/test2", title: "title2" }
]
}
render() {
return (
<div>
<Header title="Template" navItems={this.state.navItems} />
<div className="container">
<button className="content-center align-center" onClick={() => this.props.getTodolist()}>
{this.props.loading ? <div className="flex"><span>Loading... </span><Loading loading={true} size={20} /></div> : "Load Todolist"}
</button>
{this.props.todoList.map( item =>
<div className="row" key={item.id}>
<div className="grid-item-6">
--- {item.title}
</div>
</div>
)}
</div>
</div>
)
}
}
const mapStateToProps = state => ({
todoList: state.todos.todoList,
loading: state.global.loading
});
const mapDispatchToProps = dispatch =>
bindActionCreators(todolistActions, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(SecondaryPage)<file_sep>export const types = {
LOADING: "_global/LOADING",
MESSAGE: "_global/MESSAGE",
ERROR: "_global/ERROR"
};
export const creators = {
loading: (bool) => ({
type: types.LOADING,
payload: bool
}),
message: message => ({
type: types.MESSAGE,
payload: message
}),
error: () => ({ type: types.ERROR })
};
const INITIAL_STATE = {
message: { type: "", text: "" },
loading: false,
error: false
};
export default function global(state = INITIAL_STATE, action) {
switch (action.type) {
case types.LOADING:
return { ...state, loading: action.payload };
case types.MESSAGE:
return { ...state, message: action.payload };
case types.ERROR:
return { ...state, error: !state.error };
default:
return state;
}
}
<file_sep>import React, { Component } from "react";
import "./styles.css";
export default class Header extends Component {
state = {
active: true,
statusClasses: ''
}
componentDidMount() {
window.innerWidth >= 555 ? this.setState({ statusClasses: '' }) : this.setState({ statusClasses: 'slideFadeHeader-off' })
window.addEventListener('resize', () => {
if(window.innerWidth >= 555) {
this.setState({ statusClasses: '' })
} else {
this.setState({ statusClasses: 'slideFadeHeader-off' })
}
});
}
transitionClass() {
this.setState({ active: !this.state.active })
this.state.active ? this.setState({ statusClasses: 'slideFadeHeader-on' }) : this.setState({ statusClasses: 'slideFadeHeader-off' })
}
render() {
return (
<div className="header">
<div className="header__titleContainer">
<h1 className="header__title">{this.props.title}</h1>
{
this.props.navItems &&
<button
className="header__navButton"
onClick={() => this.transitionClass()}>
<span className="icon-menu"></span>
</button>
}
</div>
<div
className={`header__navbar ${this.state.statusClasses}`}
>
<ul>
{!!this.props.navItems && this.props.navItems.map( (item,index) =>
{
return (
<li key={index}>
{
item.type !== 'routerlink' ?
<a href={item.link}>{item.title}</a> :
<a href="" onClick={() => this.props.history.push(item.link)}>{item.title}</a>
}
</li>
)
}
)}
</ul>
</div>
</div>
);
}
}
<file_sep>import React, { Component } from 'react';
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { creators as authActions } from '../../../../store/ducks/auth'
import Loading from '../../../shared/loading'
class Signup extends Component {
state = {
passwordError: "",
emailError: ""
}
handleInputChange = (e, field) => {
const { user } = this.props.auth
user[field] = e.target.value
this.props.user(user)
if(field == 'email') this.validateEmail()
if(field == 'password') this.validatePassword()
}
validateEmail = () => {
let email = this.props.auth.user.email
if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
this.setState({ emailError: "" })
} else {
this.setState({ emailError: "Por favor, digite um e-mail válido." })
}
}
validatePassword = () => {
let password = this.props.auth.user.password
if(password.length >= 6) {
this.setState({ passwordError: "" })
} else {
this.setState({ passwordError: "A senha deve ter, pelo menos, 6 caracteres." })
}
}
validateAndSignUp = (e) => {
e.preventDefault()
if(this.validateEmail() ) return false
if(this.validatePassword() ) return false
this.props.signUp()
}
render() {
return <div className="flex flex-1 content-center align-center">
<div className="container container-sm mb-4">
<h1 className="text-center pt-4">Cadastro</h1>
{this.props.message &&
<div className="text-center pt-4">
<span>{this.props.message}</span>
</div>}
<form noValidate onSubmit={(e) => this.validateAndSignUp(e)}>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Digite um Email</label>
<input value={this.props.auth.user.email} onChange={(e) => this.handleInputChange(e, 'email')}/>
{ this.state.emailError && <span className="errorMsg">{this.state.emailError}</span>}
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
<div className="input-box">
<label>Digite uma Senha</label>
<input type="password" value={this.props.auth.user.password} onChange={(e) => this.handleInputChange(e, 'password')}/>
{ this.state.passwordError && <span className="errorMsg">{this.state.passwordError}</span>}
</div>
</div>
</div>
<div className="row">
<div className="grid-item-6">
<div style={{ alignSelf: 'center' }}>
{this.props.loading ? <Loading loading={this.props.loading} size={22}/> : <button className="primary">Cadastrar</button>}
</div>
<div>
<button type="button" onClick={() => this.props.history.push("/signin")}>Já possui cadastro?</button>
</div>
</div>
</div>
</form>
</div>
</div>
}
}
const mapStateToProps = state => ({
auth: state.auth,
message: state.global.message.text,
loading: state.global.loading
});
const mapDispatchToProps = dispatch =>
bindActionCreators(authActions, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(Signup)
| b82055ba57f9489252f6675bc059fe4cbbc8afea | [
"JavaScript"
] | 14 | JavaScript | yarnando/banco-de-horas | 2c42740be3d5f09bc6ab00a114b7f117752cdada | 3b4e256addf5b07e62dbfd2aeaeda1b8b0daba01 | |
refs/heads/master | <repo_name>lnicholsonmesm/earthquakes-leaflet<file_sep>/assets/js/logic.js
// Map Logic
/* In this example we’ll use the mapbox/streets-v11 tiles from Mapbox’s Static Tiles API (in order to use tiles from Mapbox, you must also request an access token). Because this API returns 512x512 tiles by default (instead of 256x256), we will also have to explicitly specify this and offset our zoom by a value of -1.*/
//USGS API:
var url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson';
var geoJson;
/* ______*1. INSTANTIATE MAP *_________*_________*_________*_________*________*/
//var map = L.map('mapid').setView([51.505, -0.09], 13);
var map = L.map('mapid', {
//center: [20, 0],
center: [21.445594, -159.7501637],
zoom: 2,
worldCopyJump: true,
//maxBounds: ([[70, - 7], [-30, -6.99999]])
});
//map.setView([biggestEarthquakeLat, biggestEarthquakeLon]);
//var map = L.map('mapid').setView([0.445594, 0.7501637], 5)
/* ______*2. ADD TILE LAYER *_________*_________*_________*_________*________*/
L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/satellite-streets-v11',
tileSize: 512,
zoomOffset: -1,
//accessToken: process.env.apiKey
//accessToken: apiKey //'your.mapbox.access.token'
accessToken: '<KEY>'
}).addTo(map);
/* ______* FUNCTION: GET COLOR BREAKS _*_________*_________*_________*________*/
function getColor(d) {
return d > 8.5 ? '#d73027' :
d > 6.0 ? '#fc8d59' :
d > 4.5 ? '#fee090' :
d > 2.5 ? '#e0f3f8' :
d > 1.0 ? '#91bfdb' :
'#4575b4';
};
/* ______* GET DATA + ADD TO MAP ______*_________*_________*_________*________*/
////////////////////////////////////////////////////////////
d3.json(url).then(function (response) {
var featureArray = response.features;
let adjusted = [];
let mag = [];
featureArray.forEach((data) => {
//console.log(data.geometry);
if (data.geometry.coordinates[0] > 0) {
var less = data.geometry.coordinates[0] - 360;
//var coords = l.latLng(data.geometry[1], less)
//console.log(data.geometry.coordinates[0]);
return L.circleMarker({ lon: less, lat: data.geometry.coordinates[1] }, {
radius: data.properties.mag * data.properties.mag / (0.5 + 0.4 * data.properties.mag),
onEachFeature: rainbows,
fillColor: getColor(parseFloat(data.properties.mag)),
color: '#0185aa',
weight: 0.6,
opacity: 0.7,
fillOpacity: 0.8
}).addTo(map)
/*.bindPopup("<ul><li>Magnitude: " +
feature.properties.mag + "</li>" +
"<li>Depth: " +
feature.properties.mag + " " + feature.properties.magType + "</li>" +
"<li>TsunamiPotential: " +
feature.properties.tsunami + "</li>" +
"</ul>");*/
}
});
console.log(response);
// set variables
var geoJsonFeature = response;
//read in geoJSON data to Leaflet
L.geoJSON(geoJsonFeature, {
style: function (feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: rainbows,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, {
radius: feature.properties.mag * feature.properties.mag / (0.5 + 0.4 * feature.properties.mag),
fillColor: getColor(feature.properties.mag),
color: getColor(feature.properties.mag),
//radius: Math.pow(parseFloat(feature.properties.mag), 1.5),
//fillColor: getColor(parseFloat(feature.properties.mag)),
color: '#0185aa', //getColor(parseFloat(feature.properties.mag)),
weight: 0.6,
opacity: 0.7,
fillOpacity: 0.8
}).addTo(map).bindPopup("I am a circle.");;
}
});
// Set up the legend
var legend = L.control({ position: "bottomright" });
legend.onAdd = function () {
var div = L.DomUtil.create("div", "info legend");
//var limits = geojson.options.limits;
var colors = ['#d73027', '#fc8d59', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4'];
var breaks = ['8.5+', '6.0', '4.5', '2.5', '1.0'];
var colorLabels = [];
var labels = [];
div.innerHTML = "";
//div.innerHTML = "<p>Magnitude</p>";
breaks.forEach(function (limit, index) {
colorLabels.push('<i style="background:' + colors[index] + ';"></i>' + ' ' + breaks[index]);
labels.push(' ' + breaks[index] + ' ');
});
div.innerHTML += colorLabels.join("<br>");
//div.innerHTML += "<br>"
//div.innerHTML += labels.join("");
return div;
};
//Adding legend to the map
legend.addTo(map);
});
/*
legend.onAdd = function (map) {
var div = L.DomUtil.create('div', 'info legend'),
grades = [0, 10, 20, 50, 100, 200, 500, 1000],
labels = [];
// loop through our density intervals and generate a label with a colored square for each interval
for (var i = 0; i < grades.length; i++) {
div.innerHTML +=
'<i style="background:' + getColor(grades[i] + 1) + '"></i> ' +
grades[i] + (grades[i + 1] ? '–' + grades[i + 1] + '<br>' : '+');
}
return div;
/* ______*5. EVENT HANDLING *_________*_________*_________*_________*________*/
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 5,
color: '#666',
dashArray: '',
fillOpacity: 0.7
});
if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
layer.bringToFront();
}
};
// make it a popup:
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(map);
}
map.on('click', onMapClick);
function rainbows(feature, layer) {
var popupContent = "<ul><li>Magnitude: " +
feature.properties.mag + "</li>" +
"<li>Depth: " +
feature.properties.mag + " " + feature.properties.magType + "</li>" +
"<li>TsunamiPotential: " +
feature.properties.tsunami + "</li>" +
"</ul>"
;
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
};<file_sep>/README.md
# earthquakes-leaflet
Leaflet (js) demonstration using earthquake data
<file_sep>/assets/js/geojson.js
//geojson.js
/*
Leaflet supports all of the GeoJSON types above, but Features and FeatureCollections work best as they allow you to describe features with a set of properties. We can even use these properties to style our Leaflet vectors. Here's an example of a simple GeoJSON feature:
*/
var geojsonFeature = {
"type": "Feature",
"properties": {
"name": "<NAME>",
"amenity": "Baseball Stadium",
"popupContent": "This is where the Rockies play!"
},
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
}; | 729f13a67f34cf8b4b849bf62cbdca34f8eb51fd | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | lnicholsonmesm/earthquakes-leaflet | 864dd0ae80707d36225787d5133d637107d963a5 | 76992f43d574318b15ff876c88b9eba923e1ad72 | |
refs/heads/master | <repo_name>thegriglat/acm.timus.ru<file_sep>/unsolved/1153.py
#!/usr/bin/python
N = input()
<file_sep>/unsolved/1306.py
#!/usr/bin/python
import sys
def getMediana(A,sorted=False):
if not sorted:
A.sort()
if len(A) % 2 != 0:
return A[len(A) // 2]
else:
return 0.5 * (A[len(A)//2 - 1] + A[len(A) // 2])
sys.stdin = open("1306.txt")
N = input()
n = []
for i in xrange(N):
temp = input()
n.append(temp)
print getMediana(n) if N < 100 else print 0<file_sep>/solved_2.6/1014.py
#!/usr/bin/python
def deliteli(N):
d = {}
for i in xrange(10):
d[i] = 0
if N == 0:
return ([],True)
for i in xrange(2, 10,1):
while N % i == 0:
d[i] += 1
N = N / i
if N == 1:
return (d,True)
else:
return (d,False)
def getN(d):
s = ""
for i in d.iterkeys():
for j in xrange(d[i]):
s += str(i)
if s != "":
return s
else:
return 1
def SafePlus(key,value):
global d
if d.get(key) != None:
d[key] += value
else:
d[key] = value
def RemZero():
global d
for i in xrange(10):
if i in d.keys() and d[i] <= 0:
del d[i]
def RemDupl():
global d
if d.get(2) >= 3:
SafePlus(8,1)
d[2] -= 3
if d.get(3) >= 2:
SafePlus(9,1)
d[3] -= 2
if d.get(4) >= 1 and d.get(2) >= 1:
SafePlus(8,1)
d[4] -= 1
d[2] -= 1
if d.get(2) >= 1 and d.get(3) >= 1:
SafePlus(6,1)
d[3] -= 1
d[2] -= 1
if d.get(2) >= 2:
SafePlus(4,1)
d[2] -= 2
N = int(raw_input().rstrip())
(d,stat) = deliteli(N)
ans = 10
if d != [] and stat == True :
oldd = None
while oldd != d:
oldd = d.copy()
RemDupl()
RemZero()
ans = getN(d)
if N == 0:
ans = 10
if 1 <= N <= 9:
ans = N
if stat == False:
ans = -1
if ans == 0:
ans = -1
print ans
<file_sep>/unsolved/1413.py
#!/ust/bin/python
import sys
sqr2 = 0.70710678118654757
def Goxy(num):
global x, y,sqr2
if num == 8:
y += 1
elif num == 2:
y -= 1
elif num == 6:
x += 1
elif num == 4:
x -= 1
elif num == 9:
x += sqr2
y += sqr2
elif num == 7:
x -= sqr2
y += sqr2
elif num == 3:
x += sqr2
y -= sqr2
elif num == 1:
x -= sqr2
y -= sqr2
def Go(num,mode=None):
global sqr2
x = 0
y = 0
if num == 8:
y += 1
elif num == 2:
y -= 1
elif num == 6:
x += 1
elif num == 4:
x -= 1
elif num == 9:
x += sqr2
y += sqr2
elif num == 7:
x -= sqr2
y += sqr2
elif num == 3:
x += sqr2
y -= sqr2
elif num == 1:
x -= sqr2
y -= sqr2
elif num == 0:
pass
if mode == "x":
return x
elif mode == "y":
return y
Mx = [[ Go(i,"x") + Go(j,"x") for j in xrange(0,10)] for i in xrange(0,10)]
My = [[ Go(i,"y") + Go(j,"y") for j in xrange(0,10)] for i in xrange(0,10)]
Mx[0] = [0] * len(Mx[0])
My[0] = [0] * len(My[0])
#sys.stdin = open("1413.txt")
s = sys.stdin.readline().rstrip()
x = 0
y = 0
i = 0
N = len(s)
while i < N:
num = s[i:i+2]
if len(num) == 1:
Goxy(int(num))
break
istep,jstep = num
istep = int(istep)
jstep = int(jstep)
x += Mx[istep][jstep]
y += My[istep][jstep]
i += 2
if istep == 0 or jstep == 0 :
break
print "%.10f %.10f" % (x,y)<file_sep>/unsolved/1002.py
#!/usr/bin/python
import sys,math,itertools,re
sys.stdin = open("1002.txt","r")
def getstdin(Type="str"):
line = sys.stdin.readline().rstrip()
if Type == "str":
return line
elif Type == "int":
return int(line)
elif Type == "float":
return float(line)
elif Type == "long":
return long(line)
def getwords(n):
global tel
itn = iter(n)
tell = []
words = []
for c in itn:
tell.append(tel[int(c)])
telcomb = itertools.product(*tell)
for i in telcomb:
s = ""
for c in i:
s += c
words.append(s)
return words
def getdata():
n = getstdin("str")
if n == "-1":sys.exit(0)
words = getwords(n)
dictN = getstdin("int")
dct = []
for i in xrange(dictN):
dct.append(getstdin("str"))
return (words,dct)
def splitword(word,dct):
w = word
tempd = dct
s = "("
for i in dct:
s += i + "|"
s = s[:-1]
s += ")?"
res = []
s = s * len(dct)
for d in dct:
dct = tempd
for w1 in w:
if d not in w1: del dct[dct.index(d)]
for i in re.findall(s,w1):
result = []
for j in i:
if j != "": result.append(j)
res.append( str(result)[1:-1].replace(",","").replace("'",""))
while "" in res: res.remove("")
res = list(set(res))
mini = 1000
minit = ""
for i in res:
if len(i.split()) <= mini:
mini = len(i.split())
minit = i
return minit
def resultword(words,dct):
resultword = []
for w in words:
temp = w
for d in dct:
temp = temp.replace(d,"")
if len(temp) == 0:
resultword.append(w)
return resultword
tel = [("o","q","z"),
("i","j"),
("a","b","c"),
("d","e","f"),
("g","h"),
("k","l"),
("m","n"),
("p","r","s"),
("t","u","v"),
("w","x","y")]
while True:
(words,dct) = getdata()
rword = resultword(words,dct)
del words
if len(rword) == 0:
print "No solution."
else:
print splitword(rword,dct)
<file_sep>/solved_2.6/1794.py
#!/usr/bin/python
from sys import stdin
dict
N = int(stdin.readline().rstrip())
a = [int(x) for x in stdin.readline().rstrip().split(" ")]
mini = 1e10
b = [0 for i in xrange(len(a))]
for i in xrange(len(a)):
j = i - a[i] + 1
if j < 0:
j += len(a)
b[j] += 1
print b.index(max(b)) + 1
<file_sep>/solved_2.6/1079.py
#!/usr/bin/python
import sys
def addai(key,value):
global ai
if key in ai.keys():
return None
else:
ai[key] = value
def getai(n):
global ai
if n in ai.keys():
return ai[n]
if n == 0:
return 0
if n == 1:
return 1
if n % 2 == 0:
i = int(n / 2)
temp = getai(i)
addai(n,temp)
return temp
else:
i = n // 2
temp = getai(i) +getai(i+1)
addai(n,temp)
return temp
line = int(sys.stdin.readline().rstrip())
a = []
a.append(line)
while (line != 0):
line = int(sys.stdin.readline().rstrip())
a.append(line)
ai = {0:0,1:1}
a.pop(len(a) - 1)
for i in xrange(2,max(a) + 1):
if i % 2 == 0:
ai[i] = ai[int(i//2)]
else:
ai[i] = ai[int(i//2)] + ai[int(i//2)+1]
for test in a:
maxi = 0
for i in xrange(0,test + 1):
t = ai[i]
if t > maxi:
maxi = t
print maxi
<file_sep>/solved_2.6/1047.py
#!/usr/bin/python
import sys
def M2T():
global B
global N
k = 0
a = 2
for i in xrange(N - 2,-1,-1):
a = 2 + k
k = -1 / (a + 0.0)
B[i] -= k * B[i+1]
k = -1 / (0.0 + a)
if N != 1: a = 2 + k
return B[0] / (0.0 + a )
sys.stdin = open("1047.txt", "r")
N = int(sys.stdin.readline())
a0 = float(sys.stdin.readline())
an1 = float(sys.stdin.readline())
B = [float(sys.stdin.readline()) * (-2) for x in xrange(0,N)]
B[0] += a0
B[N-1] += an1
print "%.2f" % (M2T())<file_sep>/solved_2.6/1005.py
#!/usr/bin/python
import sys
l1 = sys.stdin.readline()
del l1
line = sys.stdin.readline().rstrip()
a = line.split()
b = []
for i in a:
b.append(int(i))
del a
b.sort()
sl = []
m1,m2 = 0,0
c = []
c += b
m1 = b.pop(len(b) - 1)
while len(b) != 0:
if m1 >= m2:
m2 += b.pop(len(b) - 1)
else:
m1 += b.pop(len(b) - 1)
for i in xrange(len(c)):
sl.append(abs(sum(c[i:]) - sum(c[:i])))
if abs(m2-m1) < min(sl):
print abs(m2-m1)
else:
print min(sl)
<file_sep>/unsolved/1297.py
#!/usr/bin/python
import sys
a = sys.stdin.readline().rstrip()
a = "ThesampletextthatcouldbereadedthesameinbothordersArozaupalanalapuazorA"
a = " " + a + " "
d = []
for i in xrange(len(a)):
for j in xrange(len(a)):
if a[i:j] == a[j-1:i-1:-1] and a[i:j] != "":
d.append(a[i:j])
maxl = max(len(s) for s in d)
q = []
for i in d:
if len(i) == maxl:
q.append(i)
del d
idx = []
for i in q:
idx.append(a.index(i))
print q[idx.index(min(idx))]<file_sep>/solved_2.6/1336.py
#!/usr/bin/python
#m**2 = k**3 * N
n = input()
print long(n **2 )
print long(n)
<file_sep>/unsolved/1073.py
#!/usr/bin/python
import sys,math
def getL(n):
"""
Decomposition of n by Lagrange theorem.
n = a**2 + b**2 + c**2 + d**2
"""
if int(math.sqrt(n)) ** 2 == N:
return 1
i = 0
a = 5
while a > 0:
a = int(math.sqrt(n)) - i
b = math.sqrt(n - a ** 2)
if a < b: break #Optimize 2x
#print a, b
if int(b) == b:
return 2
i += 1
stop = int(math.sqrt(n)) + 1
m = 0
i = [0] * 3
speed = 3
if N < 81:
speed = 1
for i[0] in xrange(1,stop // speed):
for i[1] in xrange(i[0],stop // speed):
for i[2] in xrange(i[1],stop):
#print i
if sum([i[x] ** 2 for x in xrange(3)]) == n:
return 3
return 4
N = input()
print getL(N)
<file_sep>/solved_2.6/1020.py
#!/usr/bin/python
import sys
import math
def getLine(p1,p2):
(x1,y1) = p1
(x2,y2) = p2
if x2 - x1 != 0:
k = (y2 - y1) / float(x2 - x1)
else :
k = 0
b = y1 - k * x1
return (k,b)
def getAddB(k, R):
phi = math.atan(k)
return R * math.cos(phi)
def getConnect(p1,R1,p2):
(x,y) = p1
addb = getAddB(getLine(p1,p2)[0],R1)
xc = math.sqrt(R1**2 - addb ** 2) + x
yc = addb + y
return (xc,yc)
def getDist(p1,p2):
(x1,y1) = p1
(x2,y2) = p2
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
def getLineSector(Opoint,p1,p2,R):
k1 = getLine(Opoint,p1)[0]
k2 = getLine(Opoint,p2)[0]
k = abs(k2 - k1)
if k == 0 and getLine(p1,p2)[0] == 0:
return math.pi * R
elif k == 0:
return math.pi * R * 0.5
return R * math.atan(k)
sys.stdin = open("1020.txt","r")
(N,R) = sys.stdin.readline().rstrip().split()
N = int(N)
R = float(R)
coord = []
for i in xrange(N):
x,y = sys.stdin.readline().rstrip().split()
x = float(x)
y = float(y)
coord.append((x,y))
sumline = 0
for i in xrange(N):
j = i + 1
n = i - 1
if i + 1 >= N: j = 0
if i - 1 < 0: n = N - 1
sumline += getDist(
getConnect(
coord[i],
R,
coord[j]),
getConnect(
coord[j],
R,
coord[i]))
# sumline += 0.5 * getLineSector(
# coord[i],
# getConnect(
# coord[i],
# R,
# coord[j]
# ),
# getConnect(
# coord[i],
# R,
# coord[n]
# ),R)
sumline += 2 * math.pi * R
print("%.2f" % sumline)
<file_sep>/solved_2.6/1086.py
#!/usr/bin/python
import sys
import math
def issimple(i):
for j in xrange(2,math.trunc(math.sqrt(i)) + 1):
if i % j == 0:
return False
return True
countN = int(sys.stdin.readline().rstrip())
N = []
for i in xrange(countN):
N.append(int(sys.stdin.readline().rstrip()))
simple = [1,2,3]
i = 5
while len(simple) <= 15000:
if issimple(i):
simple.append(i)
i += 2
for i in N:
print simple[i]
<file_sep>/unsolved/1195.py
#!/usr/bin/python
import sys
sys.stdin = open("1195.txt")
a = [[[]*3]*3]*3
t = sys.stdin.readlines()
print t
idx = -1
for i in t:
idx += 1
(a[idx][0],a[idx][1],a[idx][2] )= i.rstrip()
print a<file_sep>/solved_2.6/1083.py
#!/usr/bin/python
import sys,math
line = sys.stdin.readline().rstrip()
(n,kf) = line.split()
k = len(kf)
n = int(n)
del kf
N = 1
i = 0
for i in xrange(n // k):
N *= (n - i * k)
if n % k != 0:
N *= n % k
print N
<file_sep>/unsolved/1302.py
#!/usr/bin/python
import math
def layer(n):
if int(math.sqrt(n)) ** 2 == n:
return int(math.sqrt(n))
else:
return int(math.sqrt(n)) + 1
def gethorlayer(n):
return (layer(n) ** 2 - n) // 2 + 1
def moveLeft(i):
if i != (layer(i) - 1) ** 2 + 1:
return i - 1
else:
return None
def moveRight(i):
if i != layer(i) ** 2:
return i + 1
else:
return None
def moveUp(i):
return (layer(i) - 2) ** 2 + i - (layer(i) - 1) ** 2 - 1
def moveDLeft(i):
if (i - (layer(i) - 1) ** 2) % 2 == 0:
return moveUp(i)
else:
return moveUp(moveLeft(i))
def moveDRight(i):
if (i - (layer(i) - 1) ** 2) % 2 == 0:
return moveUp(i)
else:
return moveUp(moveRight(i))
a = raw_input().rstrip().split(" ")
for i in xrange(len(a)):
a[i] = int(a[i])
n = max(a)
m = min(a)
del a
lm = layer(m)
ln = layer(n)
i = n
step = 0
# GET split level of n
##d = []
##for L in xrange(1,ln + 1):
## l = gethorlayer(n)
## if l <= L:
## d.append(L**2 - 2*(l - 1))
## if l != L:
## d.append(L**2 - 2*(l - 1) - 1)
##del d[d.index(n)]
##d.sort()
###print d
##a = [abs(x - m) for x in d]
##step = len(a[a.index(min(a)):]) + min(a)
###print min(a), a[a.index(min(a))]
# ERRO<file_sep>/unsolved/1118.py
#!/usr/bin/python
import math
def getTriv(N):
ans = []
for i in xrange(1,N // 2 + 1):
if N % i == 0:
ans.append(i)
return sum(ans) / (0.0 + N)
def getDelit(N):
ans = [1]
M = N
m = int(math.sqrt(N)) + 1
i = 2
while 2 <= i <= m:
while M % i == 0:
ans.append(i)
M = M / i
i += 1
if M != N:
ans += [M]
tans = []
while tans != ans:
tans = ans[:]
ans = expand(ans,N)
#print "N = ",N," M = ",M," ans = ",ans
return ans
def expand(d,N):
#d = list(set(d))
#print d
l = len(d)
a = d[:]
for i in xrange(1,l):
for j in xrange(i,l):
if N % (d[i] * d[j]) == 0 and d[i] * d[j] < N:
a.append(d[i] * d[j])
return sorted(list(set(a)))
(I, J) = raw_input().rstrip().split(" ")
I = int(I)
J = int(J)
minn = None
mint = 10000
i = J
step = -1
while I <= i <= J:
#print i
if I == 1:
minn = 1
break
delit = getDelit(i)
if len(delit) == 1:
if (1 / (1.0 + i) <= mint):
minn = i
break
triv = sum(delit) / (0.0 + i)
#print i, delit,triv
if triv <= mint:
mint = triv
minn = i
if i % 2 != 0 and step != -2:
step = -2
i += -1
print minn
<file_sep>/solved_2.6/1025.py
#!/usr/bin/python
import sys
sys.stdin = open("1025.txt","r")
N = input()
p = [int(x) for x in raw_input().rstrip().split(" ")]
p.sort()
ans = 0
sp = sum(p)
lp = len(p)
t = 0
while t < 0.5 * lp:
j = p.pop(0)
ans += j // 2 + 1
t += 1
print ans
<file_sep>/solved_2.6/1001.py
#!/usr/bin/python
import sys,math,re
sys.stdin = open("1001.txt","r")
a = re.sub("\s+"," ",sys.stdin.read().replace("\n"," ")).split(" ")
while "" in a:
del a[a.index("")]
for i in xrange(len(a) - 1,-1,-1):
print "%.4f" % math.sqrt(float(a[i]))
<file_sep>/unsolved/1506.py
#!/usr/bin/python
import sys
#sys.stdin = open("1506.txt")
def tospace(s):
return " " * (4 - len(s)) + s
(N,K) = sys.stdin.readline().rstrip().split(" ")
N = int(N)
K = int(K)
arr = sys.stdin.readline().rstrip().split(" ")
for i in xrange(len(arr)):
arr[i] = tospace(arr[i])
#print arr
i = 0
stolb = 1
for i in xrange(1,N):
if i * K >= N:
stolb = i
break
#print stolb
i = 0
if K == 1:
stolb = N
while i < stolb:
#for i in xrange(K):
s = ""
j = 0
while i + j * stolb < N:
# join all arr[i + K * j]
try:
s = s + arr[i + j * stolb]
except:
pass
#print i + (N//K) * j, arr[i + (N // K) * j]
j += 1
print s
i += 1
<file_sep>/unsolved/1642.py
#!/usr/bin/python
import sys
def getDistSimple(path,ppr,ppl):
global x
coord = 0
i = 0
if path == 1:
pp = 1
else:
pp = -1
while coord != x:
if pp == 1:
bord = ppr
else:
bord = ppl
while coord != bord :
coord += pp
i += 1
if coord == x:
break
pp *= -1
return i
#sys.stdin = open("1642.txt","r")
(n,x) = (int(x) for x in sys.stdin.readline().rstrip().split(" "))
p = [int(j) for j in sys.stdin.readline().split()]
ppr = 1000
ppl = -1000
for i in xrange(len(p)):
if p[i] < ppr and p[i] > 0:
ppr = p[i]
if p[i] > ppl and p[i] < 0:
ppl = p[i]
dist = 0
if x > ppr or x < ppl:
print "Impossible"
else:
print getDistSimple(1,ppr,ppl), getDistSimple(-1,ppr,ppl)
| 9b13fce7b7a368541675970c3f85feb565e7882f | [
"Python"
] | 22 | Python | thegriglat/acm.timus.ru | d749ee20ba1bb17abd895694fec0e7a21c51544b | 18d76015d05c3105fca075366db53db2ff003e5f | |
refs/heads/master | <repo_name>DodgerFox/PlayableADS<file_sep>/Forex/main.js
'use strict'
window.onload = function () {
app()
}
function app() {
var items = document.querySelectorAll('.choise-item'),
buttons = document.querySelectorAll('.modal__button'),
peoples = document.querySelectorAll('.people__item'),
tool = document.querySelector('.modal_tool'),
trade = document.querySelector('.modal_trade'),
title = document.querySelector('.title'),
lastwindow = document.querySelector('.screen'),
index = 0;
console.log(peoples[1]);
items.forEach((element) => {
element.addEventListener('click', () => {
var thisEl = event.target;
thisEl.classList.add('open')
title.classList.remove('open')
items[0].classList.add('disabled')
items[1].classList.add('disabled')
setTimeout(() => {
if (thisEl.classList.contains('choise-item_tool')) {
tool.classList.add('open')
}else{
trade.classList.add('open')
}
}, 1000)
})
});
buttons.forEach((element) => {
element.addEventListener('click', () => {
event.target.parentElement.parentElement.classList.remove('open');
items[0].classList.remove('disabled')
items[1].classList.remove('disabled')
index++
if (index === 2) {
lastwindow.classList.add('open')
}else{
title.classList.add('open')
}
if (index === 1) {
peoples[1].classList.add('open')
peoples[0].classList.remove('open')
}
})
});
}
| aac5e386324cffd81fcbe54719585aa5edce3f00 | [
"JavaScript"
] | 1 | JavaScript | DodgerFox/PlayableADS | c55a0f13cdfab7b3bbbecf3c7addb2454fee97d5 | 4f1af87ef5010bf369938b7ba9a064fe59047b39 | |
refs/heads/master | <file_sep>//
// MapViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/29/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
class MapViewController: UIViewController {
@IBAction func backButton(sender: AnyObject) {
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("activityView")
self.showViewController(vc as! UIViewController, sender: vc)
}
}<file_sep>//
// HealthTipController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/29/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class HealthTipController: UIViewController, PlayerDelegate {
let videoUrl = NSURL(string: "https://v.cdn.vine.co/r/videos/AA3C120C521177175800441692160_38f2cbd1ffb.1.5.13763579289575020226.mp4")!
private var player: Player!
@IBOutlet weak var menuButton: UIBarButtonItem!
override func viewDidLoad() {
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.view.autoresizingMask = ([UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight])
self.player = Player()
self.player.delegate = self
self.player.view.frame = self.view.bounds
self.addChildViewController(self.player)
self.view.addSubview(self.player.view)
self.player.didMoveToParentViewController(self)
self.player.setUrl(videoUrl)
self.player.playbackLoops = true
let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTapGestureRecognizer:")
tapGestureRecognizer.numberOfTapsRequired = 1
self.player.view.addGestureRecognizer(tapGestureRecognizer)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.player.playFromBeginning()
}
// MARK: UIGestureRecognizer
func handleTapGestureRecognizer(gestureRecognizer: UITapGestureRecognizer) {
switch (self.player.playbackState.rawValue) {
case PlaybackState.Stopped.rawValue:
self.player.playFromBeginning()
case PlaybackState.Paused.rawValue:
self.player.playFromCurrentTime()
case PlaybackState.Playing.rawValue:
self.player.pause()
case PlaybackState.Failed.rawValue:
self.player.pause()
default:
self.player.pause()
}
}
func playerReady(player: Player) {
}
func playerPlaybackStateDidChange(player: Player) {
}
func playerBufferingStateDidChange(player: Player) {
}
func playerPlaybackWillStartFromBeginning(player: Player) {
}
func playerPlaybackDidEnd(player: Player) {
}
}<file_sep>//
// SharingViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/18/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class SharingViewController: UITableViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBAction func backButton(sender: AnyObject) {
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("welcomeCenter")
self.showViewController(vc as! UIViewController, sender: vc)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
override func tableView(tableView: UITableView, shouldIndentWhileEditingRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
@IBAction func postButton(sender: AnyObject) {
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("shareView")
self.showViewController(vc as! UIViewController, sender: vc)
}
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
}
<file_sep>//
// DetailViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/29/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
<file_sep>//
// PostViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/29/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class PostViewController: UIViewController {
override func viewDidLoad() {
}
@IBAction func backButton(sender: AnyObject) {
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("healthView")
self.showViewController(vc as! UIViewController, sender: vc)
}
@IBAction func shareButton(sender: AnyObject) {
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("healthView")
self.showViewController(vc as! UIViewController, sender: vc)
}
}<file_sep>//
// ProfileViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/18/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class ProfileViewController: UIViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
override func viewDidLoad() {
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
@IBAction func updateButton() {
alert()
}
@IBAction func alert() {
let alertController = UIAlertController(title: "Profile updated", message: "Profile has been updated", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default)
{ action -> Void in
// Put your code here
//changes view programatically
}
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
}
}
<file_sep>//
// SharingViewController.swift
// HealthMark v1.0
//
// Created by <NAME> on 1/18/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import Foundation
import UIKit
class SharingViewController: UIViewController {
@IBOutlet weak var menuButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
}
}
| d46955d4c265e2ea26feffe4112f9152c32d0457 | [
"Swift"
] | 7 | Swift | r36745/healthmark | 0089593b726ef883a73d6e73657c0c04c7c628cd | a8eafea4147c770b75ebae19b30283c0ae980016 | |
refs/heads/master | <file_sep>Temperature Logger for Raspberry Pi
This uses the DS18B20 digital temperature sensor to log data to an sqlite3 database
<file_sep>import plotly.plotly as py
from plotly.graph_objs import Scatter, Layout, Figure
import os
import time
import datetime
import temp
username = os.environ['PLOTLY_USERNAME']
api_key = os.environ['PLOTLY_API_KEY']
stream_token = os.environ['PLOTLY_STREAM_TOKEN']
py.sign_in(username, api_key)
trace1 = Scatter(
x=[],
y=[],
stream=dict(
token=stream_token,
maxpoints=20000
)
)
layout = Layout(
title = 'Raspberry Pi Temperature Log'
)
fig = Figure(data=[trace1], layout=layout)
print py.plot(fig, filename='Raspberry Pi Temperature Stream')
stream = py.Stream(stream_token)
stream.open()
while True:
temperature = temp.toF(temp.readTemp())
stream.write({'x': datetime.datetime.now(), 'y': temperature})
temp.logData(temperature)
time.sleep(60)
<file_sep>import time
import datetime
import sqlite3 as lite
import sys
def readTemp():
tempfile = open("/sys/bus/w1/devices/28-0000065d9c99/w1_slave")
text = tempfile.read().split("\n")[1].split(" ")[9]
tempfile.close()
temp = float(text[2:])/1000
return temp
def toF(temp):
return temp * (9.0/5.0) + 32.0
def logData(temp):
conn = lite.connect('temp.db')
cur = conn.cursor()
try:
cur.execute("INSERT INTO tbl VALUES (? , ?)",[toF(readTemp()),datetime.datetime.now()])
conn.commit()
except lite.Error, e:
if conn:
conn.rollback()
print "Error %s:" % e.args[0]
sys.exit(1)
finally:
if conn:
conn.close()
| 0bc3da63c7f58fe5c39258316457a5c30d1925de | [
"Markdown",
"Python"
] | 3 | Markdown | waltertan12/temp-stream | 3a03219f4d3c36af43badbcfdf71ea7a3c9d2483 | 7ceb46f9e6bd2e62fd6b546c2baab71548ba0188 | |
refs/heads/main | <file_sep>import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';
import { UserModule } from './../middleware/validation/user.module';
import { StudentTeacherModule } from './../schemas/student-teacher.module';
import { StudentModule } from './../schemas/student.module';
import { TeacherModule } from './../schemas/teacher.module';
@Module({
imports: [
StudentTeacherModule,
TeacherModule,
StudentModule,
ConfigModule.forRoot(),
MongooseModule.forRoot(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}/${process.env.DB_NAME}?retryWrites=true&w=majority`,
),
],
controllers: [],
providers: [],
})
export class AppModule {}
<file_sep>import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from './user.schema';
import { VaildateUserService } from './vaildate-user.service';
@Module({
providers: [VaildateUserService],
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
],
exports: [VaildateUserService],
})
export class UserModule {}
<file_sep>import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { StudentController } from 'src/controllers/students/student.controller';
import { UserModule } from 'src/middleware/validation/user.module';
import { ValidUserMiddleware } from 'src/middleware/validation/valid-user.middleware';
import { StudentService } from 'src/services/student.service';
import { Student, StudentSchema } from './student.schema';
@Module({
controllers: [StudentController],
providers: [StudentService],
imports: [
MongooseModule.forFeature([{ name: Student.name, schema: StudentSchema }]),
UserModule,
],
exports: [StudentService],
})
export class StudentModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(ValidUserMiddleware).forRoutes(StudentController);
}
}
<file_sep>export class StudentDTO {
name: string;
teacher: string;
}
export class CreateStudentDTO extends StudentDTO {
studentNumber: string;
}
<file_sep>import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
Post,
Put,
Response,
} from '@nestjs/common';
import { StudentService } from 'src/services/student.service';
import { StudentDTO } from 'src/web/model/student.dto';
import * as bcrypt from 'bcrypt';
@Controller('students')
export class StudentController {
constructor(private readonly studentService: StudentService) {}
@Get()
async getStudents() {
return await this.studentService.getStudents();
}
@Get('/:id')
async getStudentById(@Param('id') id: string, @Response() res) {
const student = await this.studentService.getStudentById(id);
console.log(student);
if (student === null) {
return res.status(404).send('Resource Not Found');
}
return res.json(student).end();
}
@Post()
@HttpCode(201)
async createStudent(@Body() studentDTO: StudentDTO) {
return await this.studentService.createStudent(studentDTO);
}
@Put('/:id')
async updateStudent(@Param('id') id: string, @Body() studentDTO: StudentDTO) {
await this.studentService.updateStudent(id, studentDTO);
}
@Delete('/:id')
async deleteStudent(@Param('id') id: string) {
await this.studentService.deleteStudent(id);
}
}
<file_sep>import { HttpException, Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { VaildateUserService } from './vaildate-user.service';
@Injectable()
export class ValidUserMiddleware implements NestMiddleware {
constructor(private readonly validateUserService: VaildateUserService) {}
async use(req: Request, res: Response, next: NextFunction) {
const isValidUser = await this.validateUserService.getUser(
req.header('username'),
req.header('password'),
);
if (isValidUser) {
// console.log(user);
next();
} else {
throw new HttpException('Invalid Autherization', 400);
}
}
}
<file_sep>import { StudentDTO } from 'src/web/model/student.dto';
export interface IStudentService<T> {
getStudents(): Promise<T[]>;
getStudentById(id: string): Promise<T>;
createStudent(t: StudentDTO): Promise<T>;
updateStudent(id: string, t: StudentDTO): Promise<void>;
deleteStudent(id: string): Promise<void>;
}
<file_sep>import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type TeacherDocument = Teacher & Document;
@Schema({
// timestamp: true
})
export class Teacher {
@Prop({ required: true })
name: string;
@Prop()
surname: string;
}
export const TeacherSchema = SchemaFactory.createForClass(Teacher);
<file_sep>/*
https://docs.nestjs.com/modules
*/
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { TeacherController } from 'src/controllers/teacher/teacher.controller';
import { TeacherService } from 'src/services/teacher.service';
import { Teacher, TeacherSchema } from './teacher.schema';
@Module({
controllers: [TeacherController],
providers: [TeacherService],
imports: [
MongooseModule.forFeature([{ name: Teacher.name, schema: TeacherSchema }]),
],
exports: [TeacherService],
})
export class TeacherModule {}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { v4 as uuid } from 'uuid';
import { Teacher, TeacherDocument } from 'src/schemas/teacher.schema';
import { TeacherDTO } from 'src/web/model/teacher.dto';
import { ITeacherService } from './teacher.interface';
@Injectable()
export class TeacherService implements ITeacherService<Teacher, TeacherDTO> {
constructor(
@InjectModel(Teacher.name) private readonly model: Model<TeacherDocument>,
) {}
async getTeachers(): Promise<Teacher[]> {
return await this.model.find().exec();
}
async getTeacherById(id: string): Promise<Teacher> {
return await this.model.findById(id).exec();
}
async createTeacher(teacherDTO: TeacherDTO): Promise<Teacher> {
return await new this.model({
id: uuid(),
...teacherDTO,
createdDate: new Date().getTime(),
}).save();
}
async updateTeacher(id: string, teacherDTO: TeacherDTO): Promise<void> {
await this.model.findByIdAndUpdate(id, teacherDTO).exec();
}
async deleteTeacher(id: string): Promise<void> {
await this.model.findByIdAndDelete(id).exec();
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Student, StudentDocument } from 'src/schemas/student.schema';
import { CreateStudentDTO, StudentDTO } from 'src/web/model/student.dto';
import { uuid } from 'uuidv4';
import { IStudentService } from './student.interface';
@Injectable()
export class StudentService implements IStudentService<Student> {
constructor(
@InjectModel(Student.name) private readonly model: Model<StudentDocument>,
) {}
async getStudents(): Promise<Student[]> {
return await this.model.find().exec();
}
async getStudentById(id: string): Promise<Student> {
return await this.model.findById(id).exec();
}
async createStudent(studentDTO: StudentDTO): Promise<Student> {
const newStudent: CreateStudentDTO = {
...studentDTO,
studentNumber: uuid().toString(),
};
return await new this.model({
...newStudent,
createdDate: new Date().getTime(),
}).save();
}
async updateStudent(id: string, studentDTO: StudentDTO): Promise<void> {
await this.model.findByIdAndUpdate(id, studentDTO).exec();
}
async deleteStudent(id: string): Promise<void> {
await this.model.findByIdAndDelete(id).exec();
}
}
<file_sep>import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
Post,
Put,
} from '@nestjs/common';
import { TeacherService } from 'src/services/teacher.service';
import { TeacherDTO } from 'src/web/model/teacher.dto';
@Controller('teachers')
export class TeacherController {
constructor(private readonly teacherService: TeacherService) {}
@Get()
async getTeachers() {
return await this.teacherService.getTeachers();
}
@Get('/:id')
async getTeacherById(@Param('id') id: string) {
return await this.teacherService.getTeacherById(id);
}
@Post()
@HttpCode(201)
async createTeacher(@Body() teachertDTO: TeacherDTO) {
return await this.teacherService.createTeacher(teachertDTO);
}
@Put('/:id')
async updateTeacher(@Param('id') id: string, @Body() teacherDTO: TeacherDTO) {
await this.teacherService.updateTeacher(id, teacherDTO);
}
@Delete('/:id')
async deleteTeacher(@Param('id') id: string) {
await this.teacherService.deleteTeacher(id);
}
}
<file_sep>import { Injectable } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { UserDTO } from './user.dto';
import { User, UserDocument } from './user.schema';
@Injectable()
export class VaildateUserService {
constructor(
@InjectModel(User.name) private readonly userModel: Model<UserDocument>,
) {}
//todo Convert to token authentication
async getUser(username: string, password: string): Promise<UserDTO> {
const user = await this.userModel
.findOne(
{ username: username },
{
_id: 0,
email: 1,
password: 1,
username: 1,
firstname: 1,
},
)
.exec();
return user && (await bcrypt.compare(password, user.password));
}
}
<file_sep>import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type StudentDocument = Student & Document;
@Schema({
// timestamp: true
})
export class Student {
@Prop({ required: true })
name: string;
@Prop()
teacher: string;
@Prop({ required: true })
studentNumber: string;
@Prop({ required: true })
createdDate: string;
}
export const StudentSchema = SchemaFactory.createForClass(Student);
<file_sep>import { Body, Controller, Get, Param, Put } from '@nestjs/common';
import { StudentTeacherService } from 'src/services/student-teacher.service';
import { StudentDTO } from 'src/web/model/student.dto';
@Controller('teachers/:id/students')
export class StudentController {
constructor(private readonly studentTeacherService: StudentTeacherService) {}
@Get()
async getStudents(@Param('id') id: string) {
return await this.studentTeacherService.getTeacherStudents(id);
}
@Put('/:studentId')
async updateStudentById(@Param() params, @Body() studentDTO: StudentDTO) {
await this.studentTeacherService.updateStudentByTeacherAndStudentId(
params.id,
params.studentId,
studentDTO,
);
}
}
<file_sep>export interface ITeacherService<T, TDTO> {
getTeachers(): Promise<T[]>;
getTeacherById(id: string): Promise<T>;
createTeacher(tDTO: TDTO): Promise<T>;
updateTeacher(id: string, tDTO: TDTO): Promise<void>;
deleteTeacher(id: string): Promise<void>;
}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Student, StudentDocument } from 'src/schemas/student.schema';
import { Teacher, TeacherDocument } from 'src/schemas/teacher.schema';
import { StudentDTO } from 'src/web/model/student.dto';
@Injectable()
export class StudentTeacherService {
constructor(
@InjectModel(Student.name)
private readonly studentModel: Model<StudentDocument>,
@InjectModel(Teacher.name)
private readonly teacherModel: Model<TeacherDocument>,
) {}
async getTeacherStudents(id: string): Promise<Student[]> {
const teacher = await this.teacherModel.findById(id).exec();
if (teacher === null) {
return null;
}
return await this.studentModel.find({ teacher: teacher.name }).exec();
}
async updateStudentByTeacherAndStudentId(
teacherId: string,
studentId: string,
studentDTO: StudentDTO,
): Promise<void> {
const teacher = await this.teacherModel.findById(teacherId).exec();
if (teacher === null) {
return null;
}
await this.studentModel.findByIdAndUpdate(studentId, studentDTO).exec();
}
}
<file_sep>import { StudentTeacherService } from './../services/student-teacher.service';
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { StudentController } from 'src/controllers/teacher/student.controller';
import { Student, StudentSchema } from './student.schema';
import { Teacher, TeacherSchema } from './teacher.schema';
@Module({
controllers: [StudentController],
providers: [StudentTeacherService],
imports: [
MongooseModule.forFeature([{ name: Teacher.name, schema: TeacherSchema }]),
MongooseModule.forFeature([{ name: Student.name, schema: StudentSchema }]),
],
exports: [StudentTeacherService],
})
export class StudentTeacherModule {}
| ba60b1e345684b41450a1b5e25b9cdd44a0204e9 | [
"TypeScript"
] | 18 | TypeScript | Moses-Everlytic/nestjs-api | a9e611de1d12c07243835392a7918aeefeee66a4 | 910408c58469f6062022d143cb4a496c6e0a61f7 | |
refs/heads/master | <repo_name>kevinxu96/test<file_sep>/error.py
def compute_error_for_linie_given_points(b,w,points):
totalError = 0
for i in range(0,len(points)):
x = points[i,0]
y = points[i,1]
totalError += (y - (w*x+b))**2
return totalError / float(len(points))
<file_sep>/Iterate.py
def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):
b = starting_b
m = starting_m
for i in range(num_iterations):
b , m = step_gradient(b, m, np.array(points), learning_rate)
return [b, m]<file_sep>/gd.py
import numpy as np
def compute_error_for_linie_given_points(b,w,points):
totalError = 0
for i in range(0,len(points)):
x = points[i,0]
y = points[i,1]
totalError += (y - (w*x+b))**2
return totalError / float(len(points))
def step_gradient(b_current, w_current, points, laerningRate):
b_gradient = 0
w_gradient = 0
N = float(len(points))
for i in range(0, len(points)):
x = points[i,0]
y = points[i,1]
b_gradient += -(2/N) * (y - (w_current*x + b_current))
w_gradient += -(2/N) * x * (y - (w_current*x + b_current))
new_b = b_current - (laerningRate * b_gradient)
new_w = w_current - (laerningRate * w_gradient)
return [new_b,new_w]
| 3e23fd9ca5c7bf41c3654d6c25823df3cc0cdefd | [
"Python"
] | 3 | Python | kevinxu96/test | 8c1af08386517c8303f0ac4bb45e720e7cf28e34 | 299670a438c7bd8bcab722c4d78d413f7b2591c8 | |
refs/heads/master | <repo_name>elenandreea/mpi<file_sep>/mpiGraph1.c
#include<mpi.h>
#include<stdio.h>
/**
* @author cristian.chilipirea
* Run: mpirun -np 12 ./a.out
*/
int graph[][2] = { { 0, 1 }, { 1, 2 }, { 2, 3 },
{ 3, 4 }, { 4, 11 }, { 11, 5 },
{ 5, 6 }, { 6, 7 }, { 7, 8 },
{ 8, 9 }, { 9, 10 }, { 10, 9 },
{ 9, 8 }, { 8, 7 }, { 7, 6 },
{ 6, 5 }, { 5, 11 }, { 11, 4 },
{ 4, 3 }, { 3, 2 }, { 2, 1 },
{ 1, 0 }, { 9, 5 }, { 5, 9 },
{ 5, 3 }, { 3, 5 }, { 0, 2 },
{ 2, 0 }, { 9, 7 }, { 7, 9 } };
int main(int argc, char * argv[]) {
int rank;
int nProcesses;
MPI_Init(&argc, &argv);
MPI_Status status;
MPI_Request request;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &nProcesses);
//printf("Hello from %i/%i\n", rank, nProcesses);
int leader = rank;
int recvLeader;
int primesc = 0;
int n = 200;
while(n) {
for (int i = 0; i < 30; i++) {
if (graph[i][0] == rank) {
MPI_Send(&leader, 1, MPI_INT, graph[i][1], 0, MPI_COMM_WORLD);
primesc++;
}
}
while(primesc) {
MPI_Recv(&recvLeader, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
if (recvLeader < leader) {
leader = recvLeader;
}
primesc--;
}
n--;
}
printf("%d %d\n",rank, leader);
//printf("Bye from %i/%i\n", rank, nProcesses);
MPI_Finalize();
return 0;
} | 7ef29181597dd10fba7800c3c6f51f8ef4590044 | [
"C"
] | 1 | C | elenandreea/mpi | 6bd0ebd70ce8bd7466e79fabbceb14fbd4ed1a3c | db1ed9e918676c07ed49d7bbf951e2fdc79cae5e | |
refs/heads/master | <file_sep>package ru.gorshkov.agrotask.features.map.repositories
import com.google.android.gms.maps.model.LatLng
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.data.pojo.AgroField
import ru.gorshkov.agrotask.utils.DateUtils
import java.util.*
class LocalFieldsRepositoryImpl constructor(private val dateUtils: DateUtils) : FieldsRepository {
override fun getYears(): List<String> {
return getFields()
.map { dateUtils.getYear(it.dateEnd) }
.distinct()
}
override fun onSearchChanged(text: String): List<AgroField> {
return getFields()
.filter { it.name.toLowerCase(Locale.getDefault()).contains(text) }
}
override fun onFilterSelected(year: String?): List<AgroField> {
return if (year.isNullOrEmpty()) {
getFields()
} else {
getFields()
.filter { dateUtils.getYear(it.dateEnd).contains(year) }
}
}
override fun getFields(): List<AgroField> {
val fields = mutableListOf<AgroField>()
fields.add(
AgroField(
310101001,
130,
"<NAME>",
"Скипетр РС1",
1429736400000,
1442955600000,
R.color.green_40,
getFirstField()
)
)
fields.add(
AgroField(
310101002,
96,
"Соя",
"Кофу РС2",
1431637200000,
1444856400000,
R.color.blue_40,
getSecondField()
)
)
fields.add(
AgroField(
310101003,
212,
"<NAME>",
"Крокодил F1",
1457557200000,
1476046800000,
R.color.red_40,
getThirdField()
)
)
fields.add(
AgroField(
310101004,
96,
"<NAME>",
"Скипетр РС1",
1459803600000,
1478293200000,
R.color.orange_40,
getFourthField()
)
)
fields.add(
AgroField(
310101005,
110,
"Кукуруза",
"Скипетр РС3",
1519851600000,
1538341200000,
R.color.yellow_40,
getFifthField()
)
)
fields.add(
AgroField(
310101006,
300,
"<NAME>",
"Скипетр РС4",
1526590800000,
1542488400000,
R.color.violin_40,
getSixthField()
)
)
fields.add(
AgroField(
310101007,
50,
"Лен",
"Скипетр РС5",
1521666000000,
1537563600000,
R.color.pink_40,
getSeventhField()
)
)
return fields
}
private fun getFirstField(): List<LatLng> {
return listOf(
LatLng(61.80384840739244, 39.29752572015718),
LatLng(61.768789522352435, 39.41562874750093),
LatLng(61.834978305380716, 39.44309456781343),
LatLng(61.904905227594, 39.36069710687593),
LatLng(61.891967838990254, 39.17942269281343)
)
}
private fun getSecondField(): List<LatLng> {
return listOf(
LatLng(61.79735903774938, 39.51450570062593),
LatLng(61.742794189868945, 39.53098519281343),
LatLng(61.742794189868945, 39.76169808343843),
LatLng(61.81941730253335, 39.74521859125093)
)
}
private fun getThirdField(): List<LatLng> {
return listOf(
LatLng(62.03011428809841, 39.61338265375093),
LatLng(62.00820756072283, 39.77543099359468),
LatLng(61.96047369035458, 39.73697884515718),
LatLng(61.98241475021735, 39.53647835687593),
LatLng(62.0378423106961, 39.50351937250093)
)
}
private fun getFourthField(): List<LatLng> {
return listOf(
LatLng(61.86996172037123, 39.77817757562593),
LatLng(61.84923562726734, 39.90177376703218),
LatLng(61.91783714634502, 39.91276009515718)
)
}
private fun getFifthField(): List<LatLng> {
return listOf(
LatLng(61.75319495756062, 39.92099984125093),
LatLng(61.828495513144205, 39.98417122796968),
LatLng(61.81941730253335, 40.12424691156343),
LatLng(61.755794600533115, 40.23136361078218),
LatLng(61.72588544747111, 40.14621956781343)
)
}
private fun getSixthField(): List<LatLng> {
return listOf(
LatLng(62.05972771569589, 39.95945198968843),
LatLng(61.97725356777783, 39.96769173578218),
LatLng(62.00691843868552, 40.28080208734468),
LatLng(62.08031135584757, 40.14621956781343),
LatLng(62.07645298575181, 39.99241097406343)
)
}
private fun getSeventhField(): List<LatLng> {
return listOf(
LatLng(61.91913003744191, 39.51175911859468),
LatLng(61.88808555554062, 39.53373177484468),
LatLng(61.85830501784389, 39.62711556390718),
LatLng(61.90878537747861, 39.61612923578218),
LatLng(61.92947119786394, 39.58042366937593)
)
}
}<file_sep>package ru.gorshkov.agrotask.features.map.repositories
import ru.gorshkov.agrotask.data.pojo.AgroField
interface FieldsRepository {
fun getFields(): List<AgroField>
fun onSearchChanged(text: String): List<AgroField>
fun onFilterSelected(year: String?): List<AgroField>
fun getYears() : List<String>
}<file_sep>package ru.gorshkov.agrotask
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import ru.gorshkov.agrotask.di.appModule
import ru.gorshkov.agrotask.di.mapModule
class AgroApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@AgroApp)
modules(listOf(appModule, mapModule))
}
}
}<file_sep>package ru.gorshkov.agrotask.features.filter.recycler
import android.view.View
import kotlinx.android.synthetic.main.holder_filter.view.*
import ru.gorshkov.agrotask.base.adapter.BaseViewHolder
class FilterHolder(private val view: View) : BaseViewHolder<String>(view) {
override fun bind(item: String) {
view.filter_item.text = item
}
}<file_sep>package ru.gorshkov.agrotask.base.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<Item, Holder : BaseViewHolder<Item>> constructor() : RecyclerView.Adapter<Holder>() {
constructor(items: List<Item>) : this() {
this.items = items
}
protected var items: List<Item> = listOf()
var onClickListener: AdapterClickListener<Item>? = null
override fun onCreateViewHolder(
viewGroup: ViewGroup, layoutId: Int
): Holder {
val holder = item(
LayoutInflater.from(viewGroup.context).inflate(layoutId, viewGroup, false)
)
holder.itemView.setOnClickListener {
onClickListener?.onClick(it.tag as Item)
}
return holder
}
abstract fun item(itemView: View): Holder
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: Holder, position: Int) {
val item = items[position]
holder.bind(item)
holder.itemView.tag = item
}
}<file_sep>package ru.gorshkov.agrotask.features.filter.recycler
import android.view.View
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.base.adapter.BaseAdapter
class FilterAdapter(items : List<String>) : BaseAdapter<String, FilterHolder>(items) {
override fun item(itemView: View) = FilterHolder(itemView)
override fun getItemViewType(position: Int) = R.layout.holder_filter
}<file_sep>package ru.gorshkov.agrotask.di
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
import ru.gorshkov.agrotask.features.map.MapViewModel
import ru.gorshkov.agrotask.features.map.interactors.FieldsInteractor
import ru.gorshkov.agrotask.features.map.repositories.FieldsRepository
import ru.gorshkov.agrotask.features.map.repositories.LocalFieldsRepositoryImpl
import ru.gorshkov.agrotask.utils.DateUtils
import ru.gorshkov.agrotask.utils.MapUtils
val mapModule = module {
viewModel { MapViewModel(get()) }
single { FieldsInteractor(get()) }
single { LocalFieldsRepositoryImpl(get()) as FieldsRepository }
}
val appModule = module {
single { DateUtils() }
single { MapUtils(androidContext()) }
}<file_sep>package ru.gorshkov.agrotask.data.pojo
import androidx.annotation.ColorRes
import com.google.android.gms.maps.model.LatLng
data class AgroField(
val id: Long = 0L,
val size: Int = 0,
val name: String = "",
val description: String = "",
val dateStart: Long = 0L,
val dateEnd: Long = 0L,
@ColorRes
val color: Int = 0,
var polygon: List<LatLng>
)<file_sep>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply from: 'dependencies.gradle'
android {
compileSdkVersion 28
defaultConfig {
applicationId "ru.gorshkov.agrotask"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")
}
repositories {
maven { url "http://maven.google.com/" }
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
<file_sep>package ru.gorshkov.agrotask.base.adapter
interface AdapterClickListener<T> {
fun onClick(item : T)
}<file_sep>package ru.gorshkov.agrotask.features.map.interactors
import ru.gorshkov.agrotask.features.map.repositories.FieldsRepository
class FieldsInteractor(private val fieldsRepository: FieldsRepository) {
fun getFields() = fieldsRepository.getFields()
fun searchItems(text: String) = fieldsRepository.onSearchChanged(text)
fun filterItems(year: String?) = fieldsRepository.onFilterSelected(year)
fun getYears() = fieldsRepository.getYears()
}<file_sep>ext {
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//Kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//Android
implementation "androidx.appcompat:appcompat:$appcompat_version"
implementation "com.google.android.material:material:$material_version"
implementation "androidx.core:core-ktx:$appcompat_version"
implementation "androidx.constraintlayout:constraintlayout:$constraint_version"
implementation "androidx.fragment:fragment-ktx:$fragment_version"
//ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
//Logging
implementation "com.github.ajalt:timberkt:$timberkt_version"
//Glide
implementation "com.github.bumptech.glide:glide:$glide_version"
kapt "com.github.bumptech.glide:compiler:$glide_version"
//Google services
implementation "com.google.android.gms:play-services-maps:$map_version"
//Koin
implementation "org.koin:koin-core:$koin_version"
implementation "org.koin:koin-android:$koin_version"
implementation "org.koin:koin-androidx-viewmodel:$koin_version"
//Permissions
implementation "pub.devrel:easypermissions:$permission_version"
}
}<file_sep>package ru.gorshkov.agrotask.features.map.recycler
import android.view.View
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.google.android.gms.maps.model.Polygon
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.base.adapter.BaseAdapter
import ru.gorshkov.agrotask.data.pojo.AgroField
import ru.gorshkov.agrotask.utils.DateUtils
class AgroFieldAdapter(private val dateUtils: DateUtils) :
BaseAdapter<AgroField, AgroFieldHolder>() {
private var selectedPosition = RecyclerView.NO_POSITION
override fun item(itemView: View) = AgroFieldHolder(itemView, dateUtils)
override fun getItemViewType(position: Int) = R.layout.holder_fields
fun update(newItems: List<AgroField>) {
val diffResult = DiffUtil.calculateDiff(AgroFieldCallback(this.items, newItems))
this.items = newItems
diffResult.dispatchUpdatesTo(this)
}
override fun onBindViewHolder(holder: AgroFieldHolder, position: Int) {
super.onBindViewHolder(holder, position)
holder.setSelected(position == selectedPosition)
}
fun getFieldItem(polygon: Polygon): AgroField? {
val code = polygon.points[0]
for (item in items) {
if (code == item.polygon[0])
return item
}
return null
}
fun getPosition(field: AgroField?) = items.indexOf(field)
fun selectItem(field: AgroField?) {
val position = items.indexOf(field)
if (selectedPosition != RecyclerView.NO_POSITION) {
notifyItemChanged(selectedPosition)
}
selectedPosition = position
notifyItemChanged(selectedPosition)
}
}<file_sep>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
kotlin_version = '1.3.61'
appcompat_version = '1.1.0'
material_version = '1.2.0-alpha02'
constraint_version = '2.0.0-beta3'
fragment_version = '1.1.0'
lifecycle_version = '2.1.0'
timberkt_version = '1.5.1'
map_version = '17.0.0'
glide_version = '4.9.0'
koin_version = '2.0.1'
permission_version = '3.0.0'
}
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven { url "http://jitpack.io/" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
<file_sep>package ru.gorshkov.agrotask.features.map
import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.github.ajalt.timberkt.Timber
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE
import com.google.android.gms.maps.MapsInitializer
import kotlinx.android.synthetic.main.fragment_map.*
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import pub.devrel.easypermissions.EasyPermissions
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.base.adapter.AdapterClickListener
import ru.gorshkov.agrotask.base.fragment.BaseFragment
import ru.gorshkov.agrotask.data.pojo.AgroField
import ru.gorshkov.agrotask.features.filter.FilterDialog
import ru.gorshkov.agrotask.features.map.recycler.AgroFieldAdapter
import ru.gorshkov.agrotask.utils.DateUtils
import ru.gorshkov.agrotask.utils.MapUtils
class MapFragment : BaseFragment(), EasyPermissions.PermissionCallbacks {
private var googleMap: GoogleMap? = null
private var adapter: AgroFieldAdapter? = null
private val mapViewModel: MapViewModel by viewModel()
private val dateUtils: DateUtils by inject()
private val mapUtils: MapUtils by inject()
override val layoutRes = R.layout.fragment_map
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mapViewModel.fieldsUpdateLiveData.observe(this, Observer {
googleMap?.clear()
if (it.isNullOrEmpty()) {
fields_recycler.visibility = View.INVISIBLE
return@Observer
}
fields_recycler.visibility = View.VISIBLE
(fields_recycler.adapter as AgroFieldAdapter).update(it)
for (field in it) {
googleMap?.addPolygon(mapUtils.getFieldPolygon(field))
}
mapUtils.moveCamera(googleMap, it[0].polygon, it[0].name)
})
mapViewModel.filterLiveData.observe(this, Observer {
showFilterDialog(it)
})
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
map_view.onCreate(savedInstanceState)
MapsInitializer.initialize(activity)
requestPermissions()
initAdapter()
initRecycler()
search_edit_text.addTextChangedListener {
mapViewModel.onSearchChanged(it.toString())
}
filter_button.setOnClickListener {
mapViewModel.onFilterClicked()
}
}
private fun getMap() {
map_view.getMapAsync { googleMap ->
initMap(googleMap)
mapViewModel.start()
}
}
private fun requestPermissions() {
if (EasyPermissions.hasPermissions(context!!, Manifest.permission.ACCESS_FINE_LOCATION)) {
getMap()
} else {
EasyPermissions.requestPermissions(
this, getString(R.string.message_denied),
100, Manifest.permission.ACCESS_FINE_LOCATION
)
}
}
private fun initRecycler() {
with(fields_recycler) {
layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
(itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
adapter = [email protected]
}
}
private fun initAdapter() {
adapter = AgroFieldAdapter(dateUtils)
adapter?.onClickListener = object : AdapterClickListener<AgroField> {
override fun onClick(item: AgroField) {
mapUtils.moveCamera(googleMap, item.polygon, item.name)
adapter?.selectItem(item)
val position = adapter?.getPosition(item)
if (position != null) {
fields_recycler.scrollToPosition(position)
}
}
}
}
private fun initMap(googleMap: GoogleMap) {
this.googleMap = googleMap
val isMyLocatioEnabled =
EasyPermissions.hasPermissions(context!!, Manifest.permission.ACCESS_FINE_LOCATION)
googleMap.uiSettings.isMyLocationButtonEnabled = isMyLocatioEnabled
googleMap.isMyLocationEnabled = isMyLocatioEnabled
googleMap.setOnPolygonClickListener {
val item = adapter?.getFieldItem(it)
adapter?.selectItem(item)
mapUtils.moveCamera(googleMap, it.points, item?.name)
val position = adapter?.getPosition(item)
if (position != null) {
fields_recycler.scrollToPosition(position)
}
}
googleMap.setOnCameraMoveStartedListener {
if (it == REASON_GESTURE) {
search_edit_text.clearFocus()
search_edit_text?.let { v ->
val imm =
context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(v.windowToken, 0)
}
}
}
moveMyLocationButton()
}
private fun showFilterDialog(years: List<String>) {
if (activity == null || activity?.supportFragmentManager == null) {
Timber.e { "MapFragment::showFilterDialog: activity is null" }
return
}
val filterDialog = FilterDialog()
val args = Bundle()
args.putStringArrayList(FilterDialog.YEARS_BUNDLE, ArrayList(years))
filterDialog.arguments = args
filterDialog.setTargetFragment(this, FilterDialog.REQUEST_CODE)
filterDialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle)
filterDialog.show(activity?.supportFragmentManager!!, filterDialog.javaClass.name)
}
//workaround. No other way how to move my location button
private fun moveMyLocationButton() {
val locationButton =
(map_view.findViewById<View>(Integer.parseInt("1")).parent as View).findViewById<View>(
Integer.parseInt("2")
)
val padding = resources.getDimensionPixelSize(R.dimen.search_edit_text_height) +
resources.getDimensionPixelOffset(R.dimen.padding_16dp)
val rlp = locationButton.layoutParams as (RelativeLayout.LayoutParams)
// position on right top
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0)
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE)
rlp.setMargins(0, padding, 30, 0)
}
override fun onResume() {
super.onResume()
map_view.onResume()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
FilterDialog.REQUEST_CODE ->
mapViewModel.onFilterSelected(data?.getStringExtra(FilterDialog.YEAR_EXTRA))
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
}
override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
Toast.makeText(context, R.string.message_denied, Toast.LENGTH_LONG).show()
getMap()
}
override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
Toast.makeText(context, R.string.message_approved, Toast.LENGTH_LONG).show()
getMap()
}
}<file_sep>package ru.gorshkov.agrotask.base.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
abstract class BaseFragment : Fragment() {
private var rootView: View? = null
protected abstract val layoutRes: Int
override fun onCreateView(
inflater: LayoutInflater, root: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(layoutRes, root, false)
return rootView
}
}<file_sep>package ru.gorshkov.agrotask.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import androidx.core.content.ContextCompat
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.*
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.data.pojo.AgroField
class MapUtils(private val context : Context) {
fun getFieldPolygon(field: AgroField): PolygonOptions {
val color = ContextCompat.getColor(context, field.color)
return PolygonOptions()
.clickable(true)
.addAll(field.polygon)
.strokeColor(color)
.fillColor(color)
}
fun moveCamera(map: GoogleMap?, coordinates: List<LatLng>, title: String?) {
val center = getPolygonCenterPoint(coordinates)
val cameraPosition = CameraPosition.Builder()
.target(center)
.zoom(9f)
.build()
val marker = map?.addMarker(getMarker(center, title))
marker?.showInfoWindow()
map?.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
private fun getMarker(latLng: LatLng, title: String?) : MarkerOptions {
return MarkerOptions()
.position(LatLng(latLng.latitude, latLng.longitude))
.title(title)
.icon(bitmapDescriptorFromVector(R.drawable.ic_empty))
}
private fun getPolygonCenterPoint(polygonPointsList: List<LatLng>): LatLng {
val centerLatLng: LatLng?
val builder: LatLngBounds.Builder = LatLngBounds.Builder()
for (element in polygonPointsList) {
builder.include(element)
}
val bounds: LatLngBounds = builder.build()
centerLatLng = bounds.center
return centerLatLng
}
private fun bitmapDescriptorFromVector(vectorResId: Int): BitmapDescriptor? {
return ContextCompat.getDrawable(context, vectorResId)?.run {
setBounds(0, 0, intrinsicWidth, intrinsicHeight)
val bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888)
draw(Canvas(bitmap))
BitmapDescriptorFactory.fromBitmap(bitmap)
}
}
}<file_sep>package ru.gorshkov.agrotask.features.map.recycler
import android.view.View
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.holder_fields.view.*
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.base.adapter.BaseViewHolder
import ru.gorshkov.agrotask.data.pojo.AgroField
import ru.gorshkov.agrotask.utils.DateUtils
class AgroFieldHolder(
private val view: View,
private val dateUtils: DateUtils
) : BaseViewHolder<AgroField>(view) {
fun setSelected(isSelected: Boolean) {
val color: Int = if (isSelected)
ContextCompat.getColor(itemView.context, R.color.gray)
else
ContextCompat.getColor(itemView.context, R.color.white)
view.holder_root.setCardBackgroundColor(color)
}
override fun bind(item: AgroField) {
view.field_id_text.text = view.resources.getString(R.string.field_name, item.id)
view.field_description_text.text = item.description
view.field_name_text.text = item.name
view.field_size_text.text = view.resources.getString(R.string.field_size, item.size)
view.date_start_text.text = dateUtils.getFieldDate(item.dateStart)
view.date_end_text.text = dateUtils.getFieldDate(item.dateEnd)
}
}<file_sep>package ru.gorshkov.agrotask.features.filter
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.dialog_filter.*
import ru.gorshkov.agrotask.R
import ru.gorshkov.agrotask.base.adapter.AdapterClickListener
import ru.gorshkov.agrotask.base.fragment.BaseDialogFragment
import ru.gorshkov.agrotask.features.filter.recycler.FilterAdapter
class FilterDialog : BaseDialogFragment() {
companion object {
const val REQUEST_CODE = 111
const val YEARS_BUNDLE = "years_bundle"
const val YEAR_EXTRA = "year_extra"
}
private var adapter: FilterAdapter? = null
private val allYears: String by lazy { resources.getString(R.string.all_years) }
override val layoutRes = R.layout.dialog_filter
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val years = arguments?.getStringArrayList(YEARS_BUNDLE)
years?.add(allYears)
adapter = FilterAdapter(years as List<String>)
adapter?.onClickListener = object : AdapterClickListener<String> {
override fun onClick(item: String) {
val intent = Intent()
if (TextUtils.equals(item, allYears)) {
intent.putExtra(YEAR_EXTRA, "")
} else {
intent.putExtra(YEAR_EXTRA, item)
}
targetFragment?.onActivityResult(REQUEST_CODE, Activity.RESULT_OK, intent)
dismiss()
}
}
with(filter_recycler) {
layoutManager = LinearLayoutManager(activity)
adapter = [email protected]
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setTitle(R.string.choose_year)
return dialog
}
}<file_sep>include ':app'
rootProject.name='AgroTask'
<file_sep>package ru.gorshkov.agrotask.features.map
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import ru.gorshkov.agrotask.data.pojo.AgroField
import ru.gorshkov.agrotask.features.map.interactors.FieldsInteractor
class MapViewModel(private val fieldsInteractor: FieldsInteractor) : ViewModel(){
val fieldsUpdateLiveData = MutableLiveData<List<AgroField>>()
val filterLiveData = MutableLiveData<List<String>>()
fun start() {
fieldsUpdateLiveData.postValue(fieldsInteractor.getFields())
}
fun onSearchChanged(text: String) {
fieldsUpdateLiveData.postValue(fieldsInteractor.searchItems(text))
}
fun onFilterClicked() {
filterLiveData.postValue(fieldsInteractor.getYears())
}
fun onFilterSelected(year: String?) {
fieldsUpdateLiveData.postValue(fieldsInteractor.filterItems(year))
}
}<file_sep>package ru.gorshkov.agrotask.utils
import java.text.SimpleDateFormat
import java.util.*
class DateUtils {
fun getFieldDate(timeMills: Long) = getDate("dd.MM.yyyy", timeMills)
fun getYear(timeMills: Long) = getDate("yyyy", timeMills)
private fun getDate(format : String, timeMills: Long): String {
return if(timeMills == 0L)
""
else
SimpleDateFormat(format, Locale.getDefault()).format(timeMills)
}
}<file_sep>package ru.gorshkov.agrotask.features.map.recycler
import androidx.recyclerview.widget.DiffUtil
import ru.gorshkov.agrotask.data.pojo.AgroField
class AgroFieldCallback(
private val oldList: List<AgroField>,
private val newList: List<AgroField>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldPosition: Int, newPosition: Int): Boolean {
return oldList[oldPosition].id == newList[newPosition].id
}
override fun areContentsTheSame(oldPosition: Int, newPosition: Int): Boolean {
return oldList[oldPosition] == newList[newPosition]
}
} | cff6678700e22278cae216cab7a0062bcd74e105 | [
"Kotlin",
"Gradle"
] | 23 | Kotlin | gorshkoov/AgroTask | 42f4f8cb3817adcae47eebcfa519505862b81039 | 626b24bc774983056aefa725d15f8ed65b46d80d | |
refs/heads/master | <file_sep>import numpy
import numpy.random
from multiprocessing import Queue
class State(object):
" Abstract class to define an state. "
def __hash__(self):
raise NotImplementedError("__hash__ function must be implemented.")
@staticmethod
def getfromhash(hash):
raise NotImplementedError("__hash__ function must be implemented.")
def __eq__(self, other):
raise NotImplementedError("__eq__ function must be implemented.")
def next_state(self, state):
raise NotImplementedError("A tuple (new state, reward) must be returned.")
def is_terminal(self):
raise NotImplementedError("Check if the current state is terminal.")
def actions(self):
raise NotImplementedError("List of actions in the state.")
class Sarsa(object):
def __init__(self, start_state, epsilon=0.1, alpha=0.1, gamma=0.8):
self.start_state = start_state
# Keep the estimates for Q(s, a)
self.q_estimates = {}
# Epsilon for the E-greedy policy.
self.epsilon = epsilon
# Alpha/
self.alpha = alpha
# Lambda
self.gamma = gamma
def seed(self, seed):
numpy.random.seed(seed)
def update_q(self, state, action, correction):
q = self.get_q(state, action)
self.q_estimates[(state, action)] = q + self.alpha * correction
def get_q(self, state, action):
if (state, action) not in self.q_estimates:
self.q_estimates[(state, action)] = numpy.random.random()
return self.q_estimates[(state, action)]
def greedy_action(self, state, epsilon=None):
" Compute the E-greedy action. "
if epsilon is None:
epsilon = self.epsilon
# List of actions.
actions = state.actions()
# List of tuples (action, value)
actions_value = [(a, self.get_q(state, a)) for a in actions]
actions_value.sort(key=lambda x: -x[1])
# We now have the state-actions values in order, add the probability.
actions_p = [1 - epsilon + epsilon / len(actions)] + [epsilon / len(actions)]
s = numpy.random.random()
if s < 1 - epsilon:
return actions_value[0][0]
# Choose one between the rest.
s -= 1 - epsilon
s *= (len(actions) - 1) / epsilon
return actions_value[1 + int(s)][0]
def iterate(self):
" Execute a single episode. "
state = self.start_state
action = self.greedy_action(state)
# Save the history.
history = [state]
corrections = []
while not state.is_terminal():
# Take the greedy action.
next_state, r = state.next_state(action)
# Second pair.
next_action = self.greedy_action(next_state)
# Update Q(first_state, first_action)
correction = r + self.gamma * self.get_q(next_state, next_action) - self.get_q(state, action)
self.update_q(state, action, correction)
# Save history.
corrections.append(correction)
history.append(next_state)
# Update state.
state = next_state
action = next_action
return history, corrections
def eval(self, max_iter=100):
""" Just evaluate the current policy."""
# Save the history in different array.
history = [self.start_state]
state = self.start_state
reward = 0
for it in range(max_iter):
# Complete greedy action, no exploration!.
action = self.greedy_action(state=state, epsilon=0)
# Take the greedy action.
state, r = state.next_state(action)
reward += r
# Save the state.
history.append(state)
if state.is_terminal():
break
return history, reward
class SarsaTraces(Sarsa):
def __init__(self, start_state, epsilon=0.1, alpha=0.1, gamma=0.8, Lambda=0.1):
self.start_state = start_state
# Keep the estimates for Q(s, a)
self.q_estimates = {}
# Keep the traces
self.traces = {}
# Epsilon for the E-greedy policy.
self.epsilon = epsilon
# Alpha/
self.alpha = alpha
# Gamma
self.gamma = gamma
# Lambda
self.Lambda = Lambda
self.reset()
def reset(self):
" Reset the state of the machine."
self.history = [self.start_state]
self.corrections = []
# This is not part of the algorithm but I don't see the point in keeping this on
# different episodes, and cleaning this will increase the performance.
self.traces = {}
def update_trace(self, state, action):
# Update and get acts as an sparsed matrix based on key-value.
# Check on:
# http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.dok_matrix.html
self.traces[(state, action)] = self.gamma * self.Lambda * self.get_trace(state, action)
def get_trace(self, state, action):
if (state, action) not in self.traces:
self.traces[(state, action)] = 0
return self.traces[(state, action)]
def update_iter(self, state, action, correction):
self.update_q(state, action, correction)
self.update_trace(state, action)
def iterate(self):
" Execute a single episode. "
self.reset()
state = self.start_state
action = self.greedy_action(state)
while not state.is_terminal():
# Take the greedy action.
next_state, r = state.next_state(action)
# Second pair.
next_action = self.greedy_action(next_state)
# Update Q(first_state, first_action)
correction = r + self.gamma * self.get_q(next_state, next_action) - self.get_q(state, action)
self.traces[(state, action)] = self.get_trace(state, action) + 1
# Update just the states with non-zero trace.
for key, value in self.traces.items():
self.update_q(key[0], key[1], correction * value)
self.update_trace(*key)
self.history.append(next_state)
state = next_state
action = next_action
class SarsaPartition(Sarsa):
"""
Sarsa with partition
====================
I will try to implement a patitioned sarsa based on ideas of the paper:
http://www.ejournal.org.cn/Jweb_cje/EN/article/downloadArticleFile.do?attachType=PDF&id=7638
The basic idea is that we can define a partition in the space state with some nice properties that I will try to express nicely if this works.
I will try to implement a way to split the big problem in little problems adding a method
*part* in the state class which says to which part the state belongs, if we hit a
`next_state` in a different class we are going to need to add a problem starting on
that state to the scheduler, and mark it to update, then any other subproblem that hit
this one will wait for the update mark it again and add a new subproblem starting in the
same point.
We need to add a mark to the Q values, this mark will control that a value of Q in
the boundary of a partition will be used just once by a subsolver.
"""
def __init__(self, *args, **kwargs):
super(SarsaPartition, self).__init__(*args, **kwargs)
# We're going to store the states in this queues.
self.queues = {}
# We need to add the queues of the parts.
for p in kwargs['parts']:
self.queues[p] = Queue()
def iterate(self, part):
" Execute a single episode. "
# Fetch a problem from part
history, corrections, state = self.queue[part].get()
self.reset()
state = self.start_state
action = self.greedy_action(state)
while not state.is_terminal():
# Take the greedy action.
next_state, r = state.next_state(action)
# Second pair.
next_action = self.greedy_action(next_state)
# Update Q(first_state, first_action)
correction = r + self.gamma * self.get_q(next_state, next_action) - self.get_q(state, action)
self.traces[(state, action)] = self.get_trace(state, action) + 1
# Update just the states with non-zero trace.
for key, value in self.traces.items():
self.update_q(key[0], key[1], correction * value)
self.update_trace(*key)
self.history.append(next_state)
state = next_state
action = next_action
<file_sep>import time
from sarsa import State, Sarsa
from itertools import izip_longest
import pylab
class BarnState(State):
"""
State in the Barn
=================
An state in the barn is defined by the position of the rat and the food still in the barn.
:position: must be a 2-tuple of x,y coord.
:food: a list of 2-tuples with the coord of the food.
"""
def __init__(self, position, food, max_size):
self.position = position
self.food = food
self.max_size = max_size
def __hash__(self):
h = "%d:" % self.max_size
h += "%d:%d:" % self.position
h += ":".join("%d:%d" % f for f in self.food)
return hash(h)
def __eq__(self, other):
return (self.position == other.position) and (self.food == other.food) and (self.max_size == other.max_size)
def next_state(self, action):
if action == 'right':
next_position = ((self.position[0] + 1) % self.max_size, self.position[1])
elif action == 'left':
next_position = ((self.position[0] - 1) % self.max_size, self.position[1])
elif action == 'up':
next_position = (self.position[0], (self.position[1] + 1) % self.max_size)
elif action == 'down':
next_position = (self.position[0], (self.position[1] - 1) % self.max_size)
next_food = [f for f in self.food if f != next_position]
reward = -1 if (len(next_food) == len(self.food)) else 1
return BarnState(next_position, next_food, self.max_size), reward
def is_terminal(self):
return (self.food == []) and (self.position == (self.max_size-1, self.max_size-1))
def actions(self):
actions = ["up", "down", "left", "right"]
if self.position[0] == 0:
actions.pop(actions.index("left"))
if self.position[1] == 0:
actions.pop(actions.index("down"))
if self.position[0] == self.max_size - 1:
actions.pop(actions.index("right"))
if self.position[1] == self.max_size - 1:
actions.pop(actions.index("up"))
return actions
def plot_path(path):
pylab.clf()
pylab.xlim(-2, max_size + 1)
pylab.ylim(-2, max_size + 1)
pylab.axis('off')
# Start.
pylab.annotate('start', xy=(0, 0), xytext=(-1, -1), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
pylab.annotate('stop', xy=(max_size-1, max_size-1), xytext=(max_size, max_size), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
# Show the food.
for f in food:
pylab.annotate('food', xy=f, size=5, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), ha='center')
for i in range(len(path) - 1):
pylab.arrow(path[i][0], path[i][1], path[i+1][0] - path[i][0], path[i+1][1] - path[i][1])
# Parameters.
max_size = 20
food = [(0,8), (4,4), (1,1), (8,8), (6,2), (12, 15), (17,2), (4, 12), (17, 17), (12, 1)]
# Start the algorithm.
sarsa = Sarsa(BarnState((0,0), food, max_size), epsilon=0.1, alpha=0.1, gamma=0.2)
sarsa.seed(int(100* time.time()))
plot_in = [10, 100, 200, 400, 600, 1000, 1500, 2000, 4000, 5000, 6000, 8000, 10000, 12000, 15000, 20000]
for i in range(max(plot_in) + 1):
sarsa.iterate()
if i % 10 == 0:
print i
if i in plot_in:
plot_path([s.position for s in sarsa.history])
pylab.savefig('/tmp/simple-path-4-%d.png' % i)
print i
<file_sep>"""
The Barn and the Rat
====================
First we create a squaed Barn with size n x n, and we place m pieces
of food on it.
From the barn we can get the number of possible states of the problem.
Given a barn of size n by n with m pices of food located on it, the number
of states of the system is given by all the possible locations of the rat
in the barn and the foo still in the barn, there are n^2 locations, and
there are 2^m states for the pieces of food, then roughlt speaking there are
n^2 * 2^m states. An state is defined by the location of the rat and the
pieces of food still in the barn, once we choose one location, there are
2 ^ m possibilities for the food. Also, if we choose a possition with food
(there are m of them) we can choose only 2 ^ (m-1), so the real number of states are:
States: (n ^ 2 - m) * 2 ^ m + m * 2 ^ (m - 1) = (2 * n ^ 2 - m ) * 2 ^ (m -1)
Now, a policy is a map from the states to actions, we have at most 4 actions:
left, right, up and down. In some cases just 3 or 2.
We can compute the Value (in terms of the book) of each action given a state,
we estimate that the value is one in any state with no food,
and zero in any state with all the food on it.The Rat will learn to eat the food.
"""
import time
import numpy as np
from random import choice
import matplotlib.pyplot as plt
class Barn(object):
def __init__(self, n, m, alpha=0.1, epsilon=0.1):
# Save the epsilon.
self.epsilon = epsilon
# Save alpha parameter.
self.alpha = alpha
# Save the size and the food.
self.size = n
self.food_size = m
# Locate the food.
self.food = set()
while len(self.food) < self.food_size:
self.food.add(tuple(np.random.random_integers(0, self.size - 1, 2)))
self.food = list(self.food)
# Dynamically save the values.
self._values = {}
# Current state.
self.current = "0:0:" + "1" * self.food_size
# Remember the actions.
self.positions = [(0, 0)]
# def __repr__(self):
# # Create a nice representaiton of the barn.
# # Rat position.
# pos = int(self.current.split(':')[0])
# rat_i = pos / self.food_size
# rat_j = pos % self.food_size
# msg = "+" + "-" * 3 * self.size + "+\n"
# for i in range(self.size):
# msg += "|"
# for j in range(self.size):
# if rat_i == i and rat_j == j:
# msg += " R "
# else:
# msg += " * " if (self.matrix[i, j] == 1) else " "
# msg += "|\n"
# msg += "+" + "-" * 3 * self.size + "+\n"
# msg += " Current State: %s\n" % self.current
# msg += " Number of states: %d\n" % ((2 * self.size ** 2 - self.food_size ) * 2 ** (self.food_size - 1))
# msg += " Actions: %s\n" % (", ".join(self.actions(self.current)))
# for action in self.actions(self.current):
# msg += " %s: next:%s\n" % (action, self.next_state(action))
# return msg
def value(self, id):
" We encode any value as: {i * n + j}:{p0}{p1}{p2}... and so on, then "
if id not in self._values:
if id.endswith(":" + "0" * self.food_size):
# There is no food in the barn.
return 1.0
if id.endswith(":" + "1" * self.food_size):
# There is no food in the barn.
return 0.0
return 0.0
return self._values[id]
def update_value(self, id, correction):
if id not in self._values:
self._values[id] = 0.0
self._values[id] += self.alpha * correction
def actions(self, id):
""" Given some state we compute the possible actions. """
# Possible actions.
actions = set(['left', 'right', 'up', 'down'])
# Rat position.
x, y = map(int, self.current.split(':')[:2])
if x == 0:
actions.remove('left')
if y == 0:
actions.remove('down')
if x == self.size - 1:
actions.remove('right')
if y == self.size - 1:
actions.remove('up')
return actions
def next_state(self, action):
""" Compute the next state given an action. """
x, y, food = self.current.split(':')
x = int(x)
y = int(y)
if action == 'left':
x -= 1
if action == 'right':
x += 1
if action == 'up':
y += 1
if action == 'down':
y -= 1
# Any food in the place.
if (x, y) in self.food:
index = self.food.index((x, y))
food = food[:index] + '0' + food[index + 1:]
return '%d:%d:%s' % (x, y, food)
def choose_action(self):
""" Given the curent state we choose an action. """
values = []
for action in self.actions(self.current):
# Compute the next state.
next_state = self.next_state(action)
# Get the value of this actions.
values.append((action, next_state, self.value(next_state)))
# Greedy guy.
max_value = sorted(values, lambda x, y: int(y[2] - x[2]))[0][2]
# Get the epsilon close states and choose one.
states = [v for v in values if abs(v[2] - max_value) < self.epsilon]
action, next_state = choice(states)[:2]
# Update values.
self.update_value(self.current, self.value(next_state) - self.value(self.current))
self.current = next_state
# Store the action.
self.positions.append(map(int, self.current.split(':')[:2]))
def clear(self):
" Clear the memory for a new run."
# Current state.
self.current = "0:0:" + "1" * self.food_size
self.positions = []
def run(self, maxit=1000):
" Run until the rat finish the food"
for i in range(maxit):
self.choose_action()
if self.current.endswith(":" + "0" * self.food_size):
print "done!"
break
# Return the list of x, y of positions.
x = []
y = []
for pos in self.positions:
x.append(pos[0])
y.append(pos[1])
x = np.array(x)
y = np.array(y)
return x, y
if __name__ == "__main__":
b = Barn(3, 2, epsilon=0.4)
for i in range(100):
x, y = b.run(1000)
b.clear()
x, y = b.run(1000)
plt.figure()
plt.quiver(x[:-1], y[:-1], x[1:]-x[:-1], y[1:]-y[:-1], scale_units='xy', angles='xy', scale=10)
x, y = zip(*b.food)
plt.plot(x, y, 'ro')
plt.show()
<file_sep>import numpy
import numpy.random
from random import randint, choice
from UserDict import UserDict
from multiprocessing import Process, Manager, Pool
from Queue import Queue
import pylab
class StateActionValues(UserDict):
"""
We should handle the blocking in here, if we know that there is not going to be any
problem (interior of the set) we can use the normal dict api, otherwise, the get and set
methods are the one that checks for blocks.
"""
def __getitem__(self, key):
if key not in self.data:
#self.data[key] = numpy.random.random()
self.data[key] = 0
return self.data[key]
class SarsaAgent(Process):
"""
This object will run the iterative process needed in sarsa.
"""
def __init__(self, part, inbox, outbox, max_iter=20, Epsilon=0.8, Alpha=0.1, Gamma=0.8):
Process.__init__(self)
# Save the parameters.
self.Epsilon = Epsilon
self.Alpha = Alpha
self.Gamma = Gamma
# Keep track of all the parts.
self.part = part
# We receive jobs in this queue.
self.inbox = inbox
# We sent stopping states in this box.
self.outbox = outbox
# Max number of iterations.
self.max_iter = max_iter
def run(self):
while True:
# Get a job from the queue.
job = self.inbox.get()
# Stop condition.
if job is None:
break
# Job is just a pair state-action to start.
state, action, own_Q, extra_Q = job
# Recover the Q values.
self.own_Q = StateActionValues(own_Q)
self.extra_Q = StateActionValues(extra_Q)
# Compute greedy action
if action is None:
action = self.greedy_action(state)
# Iterate a bunch of times with this condition.
res = []
for it in range(self.max_iter):
res.append(self.iterate(state, action))
# A message from the agent to the scheduler.
self.outbox.put({'part': self.part, 'extra_Q': self.extra_Q.data, 'own_Q': self.own_Q.data, 'results': res})
def greedy_action(self, state, Epsilon=None):
" Compute the E-greedy action. "
# Get the current epsilon or the stored one (to control the ??greedyness??)
Epsilon = Epsilon or self.Epsilon
# List of actions.
actions = state.actions()
# List of tuples (action, value)
if state.part == self.part:
actions_value = [(a, self.own_Q[(state, a)]) for a in actions]
else:
actions_value = [(a, self.extra_Q[(state, a)]) for a in actions]
actions_value.sort(key=lambda x: -x[1])
# We now have the state-actions values in order, add the probability.
actions_p = [1 - Epsilon + Epsilon / len(actions)] + [Epsilon / len(actions)]
# Check if we're greed in this case.
s = numpy.random.random()
if s < 1 - Epsilon:
return actions_value[0][0]
# Choose one between the rest.
s -= 1 - Epsilon
s *= (len(actions) - 1) / Epsilon
return actions_value[1 + int(s)][0]
def iterate(self, initial_state, initial_action):
state = initial_state
action = initial_action
while (not state.is_terminal()) and (state.part == self.part):
# Take the greedy action.
next_state, reward = state.next_state(action)
# Second action.
next_action = self.greedy_action(next_state)
# If next state is in different part the reward is the estimated value.
# We still use the value in this part, since is job of the scheduler to
# update the value with the possible result in the other part.
if next_state.part != self.part:
reward = self.extra_Q[(next_state, next_action)]
next_q = reward
else:
next_q = self.own_Q[(next_state, next_action)]
# Update Q(first_state, first_action)
correction = reward + self.Gamma * next_q - self.own_Q[(state, action)]
self.own_Q[(state, action)] += self.Alpha * correction
# Update state.
state = next_state
action = next_action
return state, action
class Sarsa(object):
"""
In the state space we can define some nice concept:
- Neighbor of a state x: all the state reacheble from the state after an action.
- Interior of X: the set of states with neigbhors in X.
- Closure of X: the union of neigbhors of the state x for all x in X.
- Boundary of X: Closure of X - Interior of X.
If we let sarsa to act on the interior of a set X we have no problems, we need to check
if an state x in X is in the boundary of X.
A subproblem starts when is fetched from the queue of subproblems, there must be a
master process checking to add more starting problems which is just the starting state.
Once the iterative algorithm hit a state in the boundary we check if next_state is outside
the set, in that case we check if there is a block in the Q(next_state, next_action) and
we wait for it, otherwise we get the value and put a block, in both cases the next step
is to add a subproblem starting in (next_state, next_action).
We need to ensure that the number of starting subproblems is considerable big that the
max of the size of the boundaries.
"""
def __init__(self, manager, initial_state, Epsilon=0.8, Alpha=0.1, Gamma=0.8):
# Save the parameters.
self.Epsilon = Epsilon
self.Alpha = Alpha
self.Gamma = Gamma
# Keep track of all the parts.
self.parts = initial_state.parts
# Create the queues for the passing jobs.
self.outbox = dict((p, manager.Queue()) for p in self.parts)
self.inbox = manager.Queue()
# Keep the global state-action values in here.
self.Q = dict((p, StateActionValues()) for p in self.parts)
# Create the processes for each part.
self.agents = dict((p, SarsaAgent(p, self.outbox[p], self.inbox, Epsilon=Epsilon, Gamma=Gamma, Alpha=Alpha)) for p in self.parts)
# Each part has an unknown set of states in other parts.
self.needed_Q = dict((p, set([])) for p in self.parts)
# Initial states.
self.initial_states = []
# Save the initial state.
self.initial_state = initial_state
# Start all the agents.
[self.agents[a].start() for a in self.agents]
def seed(self, seed):
numpy.random.seed(seed)
def select_jobs(self, n):
" Select n jobs to be scheduled."
return set([choice(self.initial_states) for i in range(n)])
return sorted(self.initial_states, key=lambda x: x[0].part)[:n]
def iterate(self, max_iter=100):
" Execute a single episode. "
# Start the iterations counter, iterations are counted each time we reacheble
# a global stopping state.
it = 0
# Start by sending an initial state.
self.outbox[self.initial_state.part].put((self.initial_state, None, {}, {}))
# Running now
running = 1
while it < max_iter:
if len(self.initial_states) > 0:
# Get the jobs to send
# jobs = set([choice(self.initial_states) for i in range(10 - running)])
jobs = self.select_jobs(max(4 - running, 0))
for job in jobs:
state, action = job
part = state.part
# Get own and extra Q values.
own_Q = self.Q[part].data
extra_Q = dict((k, self.Q[k[0].part][k]) for k in self.needed_Q[part])
# Submit job with Q values.
self.outbox[part].put((state, action, own_Q, extra_Q))
# One more is running.
running += 1
# Read a message.
msg = self.inbox.get()
# One less is running.
running -= 1
# Get part.
part = msg['part']
print part, running
# A message bring results and needed fridges.
self.needed_Q[part] = self.needed_Q[part].union(set(msg['extra_Q'].keys()))
# Update the Q values.
self.Q[part].data.update(msg['own_Q'])
# And we add possible jobs for the future.
for result in msg['results']:
state, action= result
# If final state count iteration, if not save intermidiate job.
if not state.is_terminal():
self.initial_states.append(result)
else:
# Get the Q values from the initial state.
own_Q = self.Q[self.initial_state.part].data
extra_Q = dict((k, self.Q[k[0].part][k]) for k in self.needed_Q[self.initial_state.part])
# Send the job.
self.outbox[self.initial_state.part].put((self.initial_state, None, own_Q, extra_Q))
running += 1
it += 1
print "Iteration: ", it
def greedy_action(self, state, Epsilon=None):
" Compute the E-greedy action. "
# Get the current epsilon or the stored one (to control the ??greedyness??)
Epsilon = Epsilon or self.Epsilon
# List of actions.
actions = state.actions()
# List of tuples (action, value)
actions_value = [(a, self.Q[state.part][(state, a)]) for a in actions]
actions_value.sort(key=lambda x: -x[1])
# We now have the state-actions values in order, add the probability.
actions_p = [1 - Epsilon + Epsilon / len(actions)] + [Epsilon / len(actions)]
# Check if we're greed in this case.
s = numpy.random.random()
if s < 1 - Epsilon:
return actions_value[0][0]
# Choose one between the rest.
s -= 1 - Epsilon
s *= (len(actions) - 1) / Epsilon
return actions_value[1 + int(s)][0]
def eval(self, max_iter=100):
""" Just evaluate the current policy."""
# Save the history in different array.
history = [self.initial_state]
state = self.initial_state
reward = 0
for it in range(max_iter):
part = state.part
# Complete greedy action, no exploration!.
action = self.greedy_action(state=state, Epsilon=0)
# Take the greedy action.
state, r = state.next_state(action)
reward += r
# Save the state.
history.append(state)
if state.is_terminal():
break
return history, reward
class BarnState(object):
"""
State in the Barn
=================
An state in the barn is defined by the position of the rat and the food still in the barn.
:position: must be a 2-tuple of x,y coord.
:food: a list of 2-tuples with the coord of the food.
"""
def __init__(self, position, food, size, amount_food):
self.position = position
self.food = food
self.size = size
self.amount_food = amount_food
self.part = len(food)
self.parts = range(self.amount_food + 1)
def __hash__(self):
h = "%d:" % self.size
h += "%d:%d:" % self.position
h += ":".join("%d:%d" % f for f in self.food)
return hash(h)
def __eq__(self, other):
return (self.position == other.position) and (self.food == other.food) and (self.size == other.size)
def next_state(self, action):
if action == 'right':
next_position = ((self.position[0] + 1) % self.size, self.position[1])
elif action == 'left':
next_position = ((self.position[0] - 1) % self.size, self.position[1])
elif action == 'up':
next_position = (self.position[0], (self.position[1] + 1) % self.size)
elif action == 'down':
next_position = (self.position[0], (self.position[1] - 1) % self.size)
elif action == 'stay':
next_position = (self.position[0], self.position[1])
next_food = [f for f in self.food if f != next_position]
reward = -1 if (len(next_food) == len(self.food)) else 1
if (next_food == []) and (next_position == (self.size-1, self.size-1)):
reward = 10
return BarnState(next_position, next_food, self.size, self.amount_food), reward
def is_terminal(self):
return (self.food == []) and (self.position == (self.size-1, self.size-1))
def actions(self):
actions = ["up", "down", "left", "right", "stay"]
if self.position[0] == 0:
actions.pop(actions.index("left"))
if self.position[1] == 0:
actions.pop(actions.index("down"))
if self.position[0] == self.size - 1:
actions.pop(actions.index("right"))
if self.position[1] == self.size - 1:
actions.pop(actions.index("up"))
return actions
@classmethod
def initial_state(cls, size):
# Randomly locate the food on the ba<rn.
amount_food = randint(size / 2, 2 * size)
food = []
while len(food) < amount_food:
# Add a new piece of food.
food.append((randint(0, size-1), randint(0, size-1)))
# Ensure uniqueness.
food = list(set(food) - set([(0, 0)]))
return cls((0 ,0), food, size, amount_food)
def plot_evaluation(history, title, max_size, food, filename):
" Plot an evaluation. "
pylab.clf()
pylab.xlim(-2, max_size + 1)
pylab.ylim(-2, max_size + 1)
pylab.axis('off')
# Start.
pylab.title(title)
pylab.annotate('start', xy=(0, 0), xytext=(-1, -1), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
pylab.annotate('stop', xy=(max_size-1, max_size-1), xytext=(max_size, max_size), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
# Show the food.
for f in food:
pylab.annotate('food', xy=f, size=5, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), ha='center')
# Create the x and y locations.
x = [s.position[0] for s in history]
y = [s.position[1] for s in history]
pylab.plot(x, y)
# Save the figure
pylab.savefig(filename)
if __name__ == '__main__':
# Create the manager for the multiprprocessing.
manager = Manager()
# Size.
size = 2
# Intial state.
initial_state = BarnState.initial_state(size)
# Create a single sarsa.
sarsa = Sarsa(manager, initial_state, Epsilon=0.8)
# Iterate 1000 times using the pool.
it = 0
per_it = 10
for i in range(100):
sarsa.iterate(per_it)
it += per_it
history, reward = sarsa.eval()
plot_evaluation(history, "Parallel: iteration %d with reward %d" % (it, reward), size, initial_state.food, "parallel-iteration-%d.png" % (it, ))
<file_sep>from UserDict import UserDict
from pybrain.tools.shortcuts import buildNetwork
from pybrain.datasets import SupervisedDataSet
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.structure import TanhLayer, LinearLayer
from random import random
import sys
import argparse
import json
class EligibilityTraces(UserDict):
def __getitem__(self, key):
if key not in self.data:
self.data[key] = 0
return self.data[key]
class StateActionCache(UserDict):
"""
This class will implement the cache described in
section 5.4 in Nissen Thesis [1].
[1] http://leenissen.dk/rl/Steffen_Nissen_Thesis2007_Print.pdf
"""
def __init__(self, input_size, hidden_size=10, cache_size=1000):
self.data = {}
self.cache_size = cache_size
self.fifo = []
# Create the network in here.
self.net = buildNetwork(input_size, hidden_size, 1, outclass=LinearLayer, bias=True)
def __getitem__(self, key):
if key not in self.data:
self.data[key] = (1, self.net.activate(key[0]._to_ann(key[1]))[0])
return self.data[key][1]
def __delitem__(self, key):
# Get current number of appearances,
n, v = self.data.get(key, (0, None))
if n <= 1:
del self.data[key]
else:
self.data[key] = (n - 1, v)
def __setitem__(self, key, value):
if self.filled():
del self[self.fifo.pop(0)]
n = 1
if key in self.data:
n = self.data[key][0] + 1
self.data[key] = (n, value)
self.fifo.append(key)
def filled(self):
return len(self.fifo) > self.cache_size
def train(self):
" Train the network. "
ds = SupervisedDataSet(self.net.indim, self.net.outdim)
n = len(self.fifo)
for k, v in self.data.items():
d = (k[0]._to_ann(k[1]), [v[1]])
for i in range(v[0]):
ds.addSample(*d)
ret = None
if len(ds) != 0:
trainer = BackpropTrainer(self.net, ds)
ret = trainer.train()
# Clean the inner data.
self.data = {}
self.fifo = []
return ret
class QSarsa(object):
def __init__(self, state, cache_size=20000, hidden_size=8, Epsilon=0.8, Alpha=0.1, Gamma=0.8, Tao=0.1, Sigma=0.5, Lambda=0.3):
# Starting state.
self.initial_state = state
# Save the parameters.
self.Epsilon = Epsilon
self.Gamma = Gamma
self.Alpha = Alpha
self.Tao = Tao
self.Sigma = Sigma
self.Lambda = Lambda
# Q Cache.
self.Q = StateActionCache(state._to_ann_size(), cache_size=cache_size, hidden_size=hidden_size)
# Eligibility traces.
self.e = EligibilityTraces()
def select_action(self, state):
" Select an action on the state."
# List of tuples (action, value)
actions = [(a, self.Q[(state, a)]) for a in state.actions]
actions.sort(key=lambda x: -x[1])
# Check if we're greed in this case.
s = random()
if s <= 1 - self.Epsilon:
return actions[0]
# Choose one between the rest.
s -= 1 - self.Epsilon
s *= (len(actions) - 1) / self.Epsilon
return actions[1 + int(s)][0], actions[0][1]
def select_best_action(self, state):
" Select an action on the state."
# List of tuples (action, value)
actions = [(a, self.Q[(state, a)]) for a in state.actions]
actions.sort(key=lambda x: -x[1])
# Check if we're greed in this case.
return actions[0]
def evaluate(self):
" Evaluate the system."
state = self.initial_state
it = 0
history = [state]
reward_total = 0
while not state.is_terminal and it < self.initial_state.size ** 2:
action, best_reward = self.select_best_action(state)
state, reward = state.next_state(action)
reward_total += reward
history.append(state)
it += 1
return reward_total, history
def run(self, it):
" Run a episode."
# Clear the traces.
self.e = EligibilityTraces()
# Starting state.
state = self.initial_state
# Select action.
action, reward = self.select_action(state)
while not state.is_terminal:
# print len(self.Q.fifo), state.position, len(state.food)
# Iterate.
state, action = self.iterate(state, action)
if self.Q.filled():
# Train the neural network,
print json.dumps({'iteration': it, 'train': self.Q.train()})
print json.dumps({'iteration': it, 'train': self.Q.train()})
# self.evaluate()
def iterate(self, state, action):
" Do a single iteration from pair to pair."
# Take the greedy action.
next_state, reward = state.next_state(action)
# Second action.
next_action, max_reward = self.select_action(next_state)
# compute the correction.
delta = reward + self.Gamma *((1 - self.Sigma) * max_reward + self.Sigma * self.Q[(next_state, next_action)]) - self.Q[(state, action)]
# Update eligibility.
self.e[(state, action)] += 1
# # Update the Q and e.
for s, a in self.e.data.keys():
if self.e[(s, a)] < (self.Gamma * self.Lambda) ** 20:
self.e.data.pop((s, a))
else:
self.Q[(s, a)] += self.e[(s, a)] * delta * self.Lambda * self.Alpha
self.e[(s, a)] *= self.Gamma * self.Lambda
# Return the next state and actions.
return next_state, next_action
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Combine Sarsa with Neural Networks.')
parser.add_argument('--size', type=int, dest="size", help='Size of the barn.', default=10)
parser.add_argument('--cache-size', type=int, dest="cache_size", help='Size of the cache.', default=1000)
parser.add_argument('--hidden-size', type=int, dest="hidden_size", help='Size of the hidden layer of neurons.', default=25)
parser.add_argument('--epsilon', type=float, dest="Epsilon", help="Epsilo value, close to one is complete random, 0 is greedy", default=0.6)
parser.add_argument('--alpha', type=float, dest="Alpha", help="Step paramenter, 1 is fast close to zero is slow but secure.", default=0.1)
parser.add_argument('--gamma', type=float, dest="Gamma", help="0 is no memory, 1 is funes.", default=0.2)
parser.add_argument('--lambda', type=float, dest="Lambda", help="Control the eligibility traces.", default=0.2)
parser.add_argument('--iter-step', type=int, dest="iter_step", help="Evaluate and print each number of steps.", default=100)
parser.add_argument('--iter-total', type=int, dest="iter_step", help="Stop at this steps", default=50000)
args = parser.parse_args()
# Intial state.
from state import BarnState
initial_state = BarnState.initial_state(args.size)
# Print to stdout.
print json.dumps(vars(args))
print json.dumps({"initial": {"food": initial_state.food, "position": initial_state.position}})
# Create a single sarsa.
sarsa = QSarsa(initial_state, cache_size=args.cache_size, hidden_size=args.hidden_size, Epsilon=args.Epsilon, Alpha=args.Alpha,
Gamma=args.Gamma, Lambda=args.Lambda, Sigma=1)
for i in range(100000):
sarsa.run(i)
if i % args.iter_step == 0:
reward, history = sarsa.evaluate()
# print reward_total, [(s.position, len(s.food)) for s in history]
print json.dumps({"iteration": i, "eval": {"reward": reward, "history": [(s.position, len(s.food)) for s in history]}})
<file_sep>import time
from sarsa import State, Sarsa
from itertools import izip_longest
from random import randint
from math import log10
import pylab
import sys
import numpy
class BarnState(State):
"""
State in the Barn
=================
An state in the barn is defined by the position of the rat and the food still in the barn.
:position: must be a 2-tuple of x,y coord.
:food: a list of 2-tuples with the coord of the food.
"""
def __init__(self, position, food, max_size):
self.position = position
self.food = food
self.max_size = max_size
def __hash__(self):
h = "%d:" % self.max_size
h += "%d:%d:" % self.position
h += ":".join("%d:%d" % f for f in self.food)
return hash(h)
def __eq__(self, other):
return (self.position == other.position) and (self.food == other.food) and (self.max_size == other.max_size)
def next_state(self, action):
if action == 'right':
next_position = ((self.position[0] + 1) % self.max_size, self.position[1])
elif action == 'left':
next_position = ((self.position[0] - 1) % self.max_size, self.position[1])
elif action == 'up':
next_position = (self.position[0], (self.position[1] + 1) % self.max_size)
elif action == 'down':
next_position = (self.position[0], (self.position[1] - 1) % self.max_size)
next_food = [f for f in self.food if f != next_position]
reward = -1 if (len(next_food) == len(self.food)) else 1
return BarnState(next_position, next_food, self.max_size), reward
def is_terminal(self):
return (self.food == []) and (self.position == (self.max_size-1, self.max_size-1))
def actions(self):
actions = ["up", "down", "left", "right"]
if self.position[0] == 0:
actions.pop(actions.index("left"))
if self.position[1] == 0:
actions.pop(actions.index("down"))
if self.position[0] == self.max_size - 1:
actions.pop(actions.index("right"))
if self.position[1] == self.max_size - 1:
actions.pop(actions.index("up"))
return actions
def plot_evaluation(history, title, max_size, food, filename):
" Plot an evaluation. "
pylab.clf()
pylab.xlim(-2, max_size + 1)
pylab.ylim(-2, max_size + 1)
pylab.axis('off')
# Start.
pylab.title(title)
pylab.annotate('start', xy=(0, 0), xytext=(-1, -1), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
pylab.annotate('stop', xy=(max_size-1, max_size-1), xytext=(max_size, max_size), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
# Show the food.
for f in food:
pylab.annotate('food', xy=f, size=5, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), ha='center')
# Create the x and y locations.
x = [s.position[0] for s in history]
y = [s.position[1] for s in history]
pylab.plot(x, y)
# Save the figure
pylab.savefig(filename)
if __name__ == "__main__":
# We want 5 scenarios.
number_of_scenarios = 5
# Fixed size.
max_size = 10
# Global parameters.
epsilon = 0.1
alpha = 0.1
gamma = 0.2
# Number of iterations.
max_iters = 20000
for n in range(1, number_of_scenarios + 1):
# Randomly locate the food on the barn.
amount_food = randint(max_size / 2, 2 * max_size)
food = []
while len(food) < amount_food:
# Add a new piece of food.
food.append((randint(0, max_size-1), randint(0, max_size-1)))
# Ensure uniqueness.
food = list(set(food))
# Start the algorithm.
sarsa = Sarsa(BarnState((0,0), food, max_size), epsilon=epsilon, alpha=alpha, gamma=gamma)
sarsa.seed(int(100 * time.time()))
# keep track of how much do we move the q.
track = []
for it in range(1, max_iters + 1):
if it % 10 == 0:
print "Scenario %d: %d/%d\r" % (n, it, max_iters) ,
sys.stdout.flush()
history, corrections = sarsa.iterate()
track.append(numpy.sqrt(sum(map(lambda x: x*x, corrections))))
# We're just selecting nice places to evaluate the current policy and create a picture.
if (it % 10 ** int(log10(it)) == 0) and (it / 10 ** int(log10(it)) in [1, 2, 4, 8]):
print " evaluationg current policy at %d ..." % it
history, reward = sarsa.eval(max_size ** 2)
# Plot this.
plot_evaluation(history, "Scenario %d at iteration %d with reward %d" % (n, it, reward), max_size, food, "scenario-%d-iteration-%d.png" % (n, it))
pylab.clf()
pylab.plot(track)
pylab.savefig("scenario-%d-learning.png" % (n, ))
<file_sep>import sys
import numpy
import numpy.random
import random
from UserDict import UserDict
from multiprocessing import Process
from multiprocessing import Manager
import time
from state import BarnState
import matplotlib
matplotlib.use('Agg')
import pylab
class StateActionValues(UserDict):
def __getitem__(self, key):
if key not in self.data:
self.data[key] = 0
return self.data[key]
def update(self, data):
return self.data.update(data)
class SarsaBase(object):
def greedy_action(self, state, Epsilon=None):
" Compute the E-greedy action. "
# Get the current epsilon or the stored one (to control the ??greedyness??)
Epsilon = Epsilon or self.Epsilon
# List of tuples (action, value)
actions = [(a, self.Q[(state, a)]) for a in state.actions]
actions.sort(key=lambda x: -x[1])
# Check if we're greed in this case.
s = numpy.random.random()
if s <= 1 - Epsilon:
return actions[0][0]
# Choose one between the rest.
s -= 1 - Epsilon
s *= (len(actions) - 1) / Epsilon
return actions[1 + int(s)][0]
class SarsaAgent(Process, SarsaBase):
" All the sarsa agents are processes."
def __init__(self, part, inbox, outbox, max_it=500, Epsilon=0.8, Alpha=0.1, Gamma=0.8):
Process.__init__(self)
# Save the parameters.
self.Epsilon = Epsilon
self.Alpha = Alpha
self.Gamma = Gamma
# Keep running flag.
self.keep_running = True
# Inbox to receive the jobs.
self.inbox = inbox
# Outbox.
self.outbox = outbox
# Save the own part.
self.part = part
# State value.
self.Q = StateActionValues()
# Maximum amount of iteration per time.
self.max_it = max_it
self.running_time = 0
def iterate(self, state, action):
# Take the greedy action.
next_state, reward = state.next_state(action)
# Second action.
next_action = self.greedy_action(next_state)
# Next Q(state, action).
next_q = self.Q[(next_state, next_action)]
# If the next state is in another part we use an estimate for the reward.
if next_state.part != self.part:
reward += next_q
# Update Q(first_state, first_action)
correction = reward + self.Gamma * next_q - self.Q[(state, action)]
self.Q[(state, action)] += self.Alpha * correction
return next_state, next_action
def handle_control(self, control):
if control == 'stop':
self.keep_running = False
if 'seed' in control:
numpy.random.seed(control['seed'])
def handle_problem(self, problem):
" Handle the problem. "
# print("Problem received for part: %d %s" % (self.part, problem))
# Get the fringe data.
self.Q.update(problem['Q'])
it = 0
start = time.clock()
jobs = []
while it < self.max_it:
# Get the state-action.
state = problem['state']
action = problem['action']
while state.part == self.part and not state.is_terminal:
# Iterate
state, action = self.iterate(state, action)
it += 1
if not state.is_terminal:
# Send a new job.
jobs.append((state.part, state, action))
else:
# Send a done message.
self.outbox.put({'done': state})
# Send the jobs.
self.send_jobs(jobs)
# Save the running time.
self.running_time += time.clock() - start
def send_jobs(self, jobs):
fringe = {}
for s, a in self.Q.data:
if s.part != self.part:
continue
for sn in s.neighbors():
if sn.part != self.part:
if sn.part not in fringe:
fringe[sn.part] = {}
fringe[sn.part][(s, a)] = self.Q[(s, a)]
# Own Q.
own_Q = dict(((s, a), self.Q[(s, a)]) for s, a in self.Q.data if s.part == self.part)
msg = {
'problem': {
'jobs': jobs,
'fringe': fringe,
'Q': own_Q
}
}
# Send a new job.
print "Running Time %d: %f" % (self.part, self.running_time)
self.outbox.put(msg)
def run(self):
print("Start agent for part: %d" % self.part)
# Start requesting a problem.
self.outbox.put({'request': {'part': self.part}})
while self.keep_running:
# Get a job to process.
job = self.inbox.get()
if 'control' in job:
self.handle_control(job['control'])
continue
if 'problem' in job:
self.handle_problem(job['problem'])
self.outbox.put({'request': {'part': self.part}})
class Sarsa(SarsaBase):
def __init__(self, initial_state, Epsilon=0.7, Alpha=0.2, Gamma=0.5, prefix=None):
# Save the parameters.
self.Epsilon = Epsilon
self.Alpha = Alpha
self.Gamma = Gamma
# Save the initial state.
self.initial_state = initial_state
# Save the parts.
self.parts = self.initial_state.parts
manager = Manager()
# Create the inbox.
self.inbox = manager.Queue()
# Create the boxes.
self.outboxes = dict((p, manager.Queue()) for p in self.parts)
# Create the agents.
self.agents = dict((p, SarsaAgent(p, self.outboxes[p], self.inbox, Epsilon=Epsilon, Gamma=Gamma, Alpha=Alpha)) for p in self.parts)
# Keep running flag.
self.keep_running = True
# Keep track of who is requesting problems.
self.requests = []
# Current jobs.
self.jobs = dict((p, []) for p in self.parts)
# State-Action values in the boundaries.
self.fringe_Q = dict((p, {}) for p in self.parts)
# Own state-action for evaluation.
self.Q = StateActionValues()
# Save prefix for created files.
self.prefix = prefix or str(int(time.time()))
def seed_all(self):
for outbox in self.outboxes.values():
outbox.put({'control': {'seed': int(time.time())}})
def handle_problem(self, problem):
# Save the fringe data.
for p in problem['fringe']:
self.fringe_Q[p].update(problem['fringe'][p])
# Update the local copy of Q.
self.Q.update(problem['Q'])
# Save jobs.
for job in problem['jobs']:
part, state, action = job
self.jobs[part].append({'state': state, 'action': action})
# In case there is someone waiting for this job send it immediately.
if part in self.requests:
self.send_job(part)
def send_job(self, part):
if part in self.requests:
self.requests.pop(self.requests.index(part))
# Select a job randomly. Choose between the last 10
job = random.choice(self.jobs[part][-10:])
# print("Send job to %d" % part)
self.outboxes[part].put({
'problem': {
'action': job['action'],
'state': job['state'],
'Q': self.fringe_Q[part]
}
})
def handle_request(self, request):
part = request['part']
if len(self.jobs[part]) > 0:
self.send_job(part)
else:
self.requests.append(part)
def add_initial_job(self):
self.jobs[self.initial_state.part].append({'state': self.initial_state, 'action': random.choice(self.initial_state.actions)})
def run(self):
start = time.clock()
# Start all the agents.
for agent in self.agents.values():
agent.start()
# Add an initial_state problem.
self.add_initial_job()
# Count the done.
done_counter = 0
while self.keep_running:
# Get a message.
msg = self.inbox.get()
if 'request' in msg:
self.handle_request(msg['request'])
if 'problem' in msg:
self.handle_problem(msg['problem'])
if 'done' in msg:
done_counter += 1
self.add_initial_job()
print done_counter
if done_counter % 10 == 0:
self.eval(done_counter)
def greedy_action(self, state):
" Compute the E-greedy action. "
# List of tuples (action, value)
actions = [(a, self.Q[(state, a)]) for a in state.actions]
actions.sort(key=lambda x: -x[1])
return actions[0][0]
def eval(self, counter, max_it=100):
" Do an evaluation with the current values."
# print "(%d, %d) %s %2.1f" % (k[0].position[0], k[0].position[1], k[1], v)
# print ""
state = self.initial_state
it = 0
history = [state]
reward_total = 0
while not state.is_terminal and it < self.initial_state.size ** 2:
action = self.greedy_action(state)
state, reward = state.next_state(action)
reward_total += reward
history.append(state)
it += 1
print reward_total, [s.position for s in history]
pylab.clf()
pylab.xlim(-2, self.initial_state.size + 1)
pylab.ylim(-2, self.initial_state.size + 1)
pylab.axis('off')
# Start.
pylab.title("Iteration: %d (Size %d with reward %d)" % (counter, self.initial_state.size, reward_total))
pylab.annotate('start', xy=(0, 0), xytext=(-1, -1), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
pylab.annotate('stop', xy=(self.initial_state.size-1, self.initial_state.size-1), xytext=(self.initial_state.size, self.initial_state.size), size=10, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), arrowprops=dict(arrowstyle="->"))
# Show the food.
for f in self.initial_state.food:
pylab.annotate('food', xy=f, size=5, bbox=dict(boxstyle="round4,pad=.5", fc="0.8"), ha='center')
# Create the x and y locations.
x = [s.position[0] for s in history]
y = [s.position[1] for s in history]
pylab.plot(x, y)
# Save the figure
pylab.savefig("%s-%d.png" % (self.prefix, counter))
if __name__ == '__main__':
# Size.
size = int(sys.argv[1])
prefix = sys.argv[2]
# Intial state.
initial_state = BarnState.initial_state(size)
# Create a single sarsa.
sarsa = Sarsa(initial_state, Epsilon=0.6, Alpha=0.1, Gamma=0.8, prefix=prefix)
# Seed all the agents.
sarsa.seed_all()
sarsa.run()
| a41c00ddec3056837a7ff4f01089d180be31b713 | [
"Python"
] | 7 | Python | jorgeecardona/neurothesis | 83e0f5fc718851f08164b8e08d81617f07370627 | 3fb1569da84199795cd8a2906adb9a4b331e149b | |
refs/heads/main | <repo_name>agnakonieczna/recruitment_task<file_sep>/src/App.js
import { useState, useEffect } from 'react';
import GlobalStyle from './styles/GlobalStyles';
import { ThemeProvider } from 'styled-components';
import theme from './styles/theme';
import { Switch, Route } from 'react-router-dom';
import HomePage from './pages/HomePage/HomePage';
import HouseList from './pages/HouseList/HouseList';
import SingleHouse from './pages/SingleHouse/SingleHouse';
import HouseForm from './pages/HouseForm/HouseForm';
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('http://mobile-reality-backend.sadek.usermd.net/houses/all')
.then((res) => {
if (!res.ok) {
throw new Error(res.error);
}
return res.json();
})
.then((data) => setData(data.results))
.catch((err) => console.log(err));
}, []);
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<Switch>
<Route exact path='/'>
<HomePage />
</Route>
<Route path='/house-list'>
<HouseList data={data} setData={setData} />
</Route>
<Route path='/single-house/:id'>
<SingleHouse />
</Route>
<Route path='/house-form'>
<HouseForm houseData={data} setData={setData} />
</Route>
</Switch>
</ThemeProvider>
);
}
export default App;
<file_sep>/src/pages/SingleHouse/SingleHouse.js
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
const SingleHouse = () => {
let { id } = useParams();
const [singleHouse, setSingleHouse] = useState();
useEffect(() => {
fetch(`http://mobile-reality-backend.sadek.usermd.net/houses/${id}`)
.then((res) => res.json())
.then((data) => setSingleHouse(data.result))
.catch((err) => console.log(err));
}, [id]);
return (
singleHouse ? (
<section>
<h2>{singleHouse.address}</h2>
<p>{singleHouse.description}</p>
<p>{singleHouse.floorsNumber}</p>
</section>
) : <p>Nie znaleziono domku</p>
);
};
export default SingleHouse;
<file_sep>/src/pages/HouseList/HouseList.js
import { Link } from 'react-router-dom';
const HouseList = ({ data, setData }) => {
const removeHouse = (id) => {
setData(data.filter((house) => house._id !== id));
fetch(`http://mobile-reality-backend.sadek.usermd.net/houses/${id}`, {
method: 'DELETE'
});
};
return (
<section>
<ul>
{data &&
data.map((house) => {
return (
<li key={house._id}>
<h2>{house.address}</h2>
<p>{house.description}</p>
<p>{house.floorsNumber}</p>
<Link to={`/single-house/${house._id}`}>Zobacz więcej</Link>
<button onClick={() => removeHouse(house._id)}>X</button>
</li>
);
})}
</ul>
<Link to='/house-form'>Dodaj nowy dom</Link>
</section>
);
};
export default HouseList;
| 6ae142f4425336b156bd7269357d1ec72c123ec9 | [
"JavaScript"
] | 3 | JavaScript | agnakonieczna/recruitment_task | 8b81f20c73402274f3e1337afff01b0edbb70201 | ef7b53785a8a03ac866285eb3ceb244e68718b9b | |
refs/heads/master | <repo_name>CrackedBone/CBR_SAXParse<file_sep>/src/MySaxApp.java
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
class CurrencyRate {
String numCode;
String charCode;
int nominal;
String name;
BigDecimal value;
}
public class MySaxApp extends DefaultHandler {
final private static String URL = "http://www.cbr.ru/scripts/XML_daily.asp";
String curElementName = "";
static CurrencyRate current;
static String code;
public static void main(String args[])
throws Exception {
if (args.length > 0){
code = args[0];
//TODO: check the right currency numCode
}
XMLReader xr = XMLReaderFactory.createXMLReader();
MySaxApp handler = new MySaxApp();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
URLConnection con = new URL(URL).openConnection();
if (((HttpURLConnection) con).getResponseCode() == 200)
try
(
InputStream is = con.getInputStream();
) {
xr.parse(new InputSource(is));
}
else
throw new IOException("Connection failed");
}
public MySaxApp() {
super();
}
public void startDocument() {
//System.out.println("Start document");
}
public void endDocument() {
//System.out.println("End document");
}
public void startElement(String uri, String name,
String qName, Attributes atts) throws SAXException {
curElementName = qName;
if (qName.equals("Valute")) {
current = new CurrencyRate();
}
}
public void endElement(String uri, String name, String qName) throws SAXException {
if (qName.equals("Valute")) {
if (current.numCode.equals(code)){
System.out.println(current.nominal + " " + current.name + " " + current.value);
//TODO: throw exception to stop parsing if needed currency found
}
}
curElementName = "";
}
public void characters(char[] ch, int start, int length) throws SAXException {
switch (curElementName){
case "NumCode" :
current.numCode = new String(ch, start, length);
break;
case "CharCode" :
current.charCode = new String(ch, start, length);
break;
case "Nominal" :
current.nominal = new Integer(new String(ch, start, length));
break;
case "Name":
current.name = new String(ch, start, length);
break;
case "Value" :
String value = new String(ch, start, length);
current.value = new BigDecimal(value.replace(",", "."));
break;
default:
break;
}
}
}
| f4864164ed6b5e21930449b9b83a0dc8a9f11127 | [
"Java"
] | 1 | Java | CrackedBone/CBR_SAXParse | 93115e62f4e0e1855e5069fa5c1b64f389bf965e | 68e6d3e7bfe7efe8f8474be4c4fbba5da4703074 | |
refs/heads/master | <file_sep>using System;
using System.IO;
using Logic;
using ZmqConnector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
namespace Application
{
class Program
{
static void Main(string[] args)
{
var logger = LogManager.GetCurrentClassLogger();
try
{
var configuration = BuildConfig();
var servicesProvider = BuildDi(configuration);
using (servicesProvider as IDisposable)
{
var app = servicesProvider.GetRequiredService<Application>();
app.Start();
}
}
catch (Exception e)
{
logger.Error(e, "Error");
throw;
}
finally
{
LogManager.Shutdown();
}
}
private static IConfiguration BuildConfig()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.Build();
}
private static IServiceProvider BuildDi(IConfiguration config)
{
return new ServiceCollection()
.Configure<ApplicationSettings>(config.GetSection("Application"))
.Configure<ConnectionSettings>(config.GetSection("Connection"))
.AddSingleton<Application>()
.AddSingleton<ISender, Sender>()
.AddSingleton<IReceiver, Receiver>()
.AddSingleton<ITextOperations, TextOperations>()
.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
loggingBuilder.AddNLog(config);
})
.BuildServiceProvider();
}
}
}
<file_sep>using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetMQ;
using NetMQ.Sockets;
namespace ZmqConnector
{
public class Receiver : IReceiver
{
private readonly ConnectionSettings _settings;
private readonly ILogger<Receiver> _logger;
public Receiver(IOptions<ConnectionSettings> settings, ILogger<Receiver> logger)
{
_settings = settings.Value;
_logger = logger;
}
public void Run()
{
var subAddress = _settings.SubAddress;
var pullAddress = _settings.PullAddress;
var topic = _settings.SubTopic;
using (var subscriber = new SubscriberSocket())
using (var puller = new PullSocket())
{
subscriber.Connect(subAddress);
subscriber.Subscribe(topic);
_logger.LogInformation($"Sub socket on {subAddress} topic {topic}");
puller.Connect(pullAddress);
_logger.LogInformation($"Pull socket on {pullAddress}");
using (var poller = new NetMQPoller { subscriber, puller })
{
subscriber.ReceiveReady += SubReceiveReady;
puller.ReceiveReady += PullReceiveReady;
poller.Run();
}
}
}
private void SubReceiveReady(object sender, NetMQSocketEventArgs e)
{
var message = e.Socket.ReceiveFrameString();
_logger.LogTrace($"Sub: {message}");
OnSubMessageReceived(new MessageReceivedEventArgs
{
Message = message
});
}
private void PullReceiveReady(object sender, NetMQSocketEventArgs e)
{
var message = e.Socket.ReceiveFrameString();
_logger.LogTrace($"Pull: {message}");
OnPullMessageReceived(new MessageReceivedEventArgs
{
Message = message
});
}
protected virtual void OnSubMessageReceived(MessageReceivedEventArgs e)
{
var handler = SubMessageReceived;
handler?.Invoke(this, e);
}
protected virtual void OnPullMessageReceived(MessageReceivedEventArgs e)
{
var handler = PullMessageReceived;
handler?.Invoke(this, e);
}
public event EventHandler<MessageReceivedEventArgs> SubMessageReceived;
public event EventHandler<MessageReceivedEventArgs> PullMessageReceived;
}
}
<file_sep>using System;
namespace ZmqConnector
{
public class MessageReceivedEventArgs : EventArgs
{
public string Message { get; set; }
}
}
<file_sep>using System.Threading.Tasks;
using Logic;
using ZmqConnector;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Application
{
public class Application
{
private readonly ApplicationSettings _settings;
private readonly ILogger<Application> _logger;
private readonly IReceiver _receiver;
private readonly ISender _sender;
private readonly ITextOperations _operations;
public Application(IOptions<ApplicationSettings> settings, ILogger<Application> logger, IReceiver receiver, ISender sender, ITextOperations operations)
{
_settings = settings.Value;
_logger = logger;
_receiver = receiver;
_sender = sender;
_operations = operations;
_receiver.SubMessageReceived += OnSubMessage;
_receiver.PullMessageReceived += OnPullMessage;
_sender.PushMessageSent += OnPushMessage;
_logger.LogInformation(_settings.Tag);
}
public void Start()
{
var receiveTask = Task.Run(() =>
{
_receiver.Run();
});
_sender.Run();
Task.WaitAll(receiveTask);
}
private void OnSubMessage(object sender, MessageReceivedEventArgs e)
{
// просто получаем длину сообщения
var length = _operations.GetLength(e.Message);
// и отправляем обратно
_sender.SendMessage(length.ToString());
}
private void OnPullMessage(object sender, MessageReceivedEventArgs e)
{
// ...
}
private void OnPushMessage(object sender, MessageSentEventArgs e)
{
// ...
}
}
}
<file_sep>using System;
namespace ZmqConnector
{
public interface IReceiver
{
void Run();
event EventHandler<MessageReceivedEventArgs> SubMessageReceived;
event EventHandler<MessageReceivedEventArgs> PullMessageReceived;
}
}
<file_sep>using System;
namespace ZmqConnector
{
public class MessageSentEventArgs : EventArgs
{
public string Message { get; set; }
}
}
<file_sep>namespace ZmqConnector
{
/// <summary>
/// Настройки ZMQ соединения
/// </summary>
public class ConnectionSettings
{
/// <summary>
/// Протокол
/// </summary>
public string Protocol { get; set; }
/// <summary>
/// Имя хоста
/// </summary>
public string Host { get; set; }
/// <summary>
/// Номер порта Push
/// </summary>
public int PushPort { get; set; }
/// <summary>
/// Номер порта Pull
/// </summary>
public int PullPort { get; set; }
/// <summary>
/// Номер порта Sub
/// </summary>
public int SubPort { get; set; }
/// <summary>
/// Имя топика для подписки
/// </summary>
public string SubTopic { get; set; }
/// <summary>
/// Полный адрес Push сокета
/// </summary>
public string PushAddress => GetAddress(Protocol, Host, PushPort);
/// <summary>
/// Полный адрес Pull сокета
/// </summary>
public string PullAddress => GetAddress(Protocol, Host, PullPort);
/// <summary>
/// Полный адрес Sub сокета
/// </summary>
public string SubAddress => GetAddress(Protocol, Host, SubPort);
private static string GetAddress(string protocol, string host, int port)
{
return $"{protocol}://{host}:{port}";
}
}
}
<file_sep>namespace Logic
{
public interface ITextOperations
{
int GetLength(string message);
}
}
<file_sep>using Microsoft.Extensions.Logging;
namespace Logic
{
public class TextOperations : ITextOperations
{
private readonly ILogger<TextOperations> _logger;
public TextOperations(ILogger<TextOperations> logger)
{
_logger = logger;
}
public int GetLength(string message)
{
var length = message.Length;
_logger.LogTrace($"Message: '{message}', length: {length}");
return length;
}
}
}
<file_sep>namespace Application
{
public class ApplicationSettings
{
public string Tag { get; set; }
}
}
<file_sep>using System;
namespace ZmqConnector
{
public interface ISender
{
void Run();
void SendMessage(string message);
event EventHandler<MessageSentEventArgs> PushMessageSent;
}
}
<file_sep>using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetMQ;
using NetMQ.Sockets;
namespace ZmqConnector
{
public class Sender : ISender
{
private readonly ConnectionSettings _settings;
private readonly ILogger<Sender> _logger;
private PushSocket Socket { get; }
public Sender(IOptions<ConnectionSettings> settings, ILogger<Sender> logger)
{
_settings = settings.Value;
_logger = logger;
Socket = new PushSocket();
}
public void Run()
{
var pushAddress = _settings.PushAddress;
Socket.Connect(pushAddress);
_logger.LogInformation($"Push socket on {pushAddress}");
}
public void SendMessage(string message)
{
_logger.LogTrace($"Push: {message}");
OnPushMessageSent(new MessageSentEventArgs
{
Message = message
});
Socket.SendFrame(message);
}
protected virtual void OnPushMessageSent(MessageSentEventArgs e)
{
var handler = PushMessageSent;
handler?.Invoke(this, e);
}
public event EventHandler<MessageSentEventArgs> PushMessageSent;
}
}
| 19c5b19ff3bf1c625bc527878b9924e23b5751b5 | [
"C#"
] | 12 | C# | in1gma/ZmqExampleApp | d73929699dc7120ea9ad21e6ee6d608078513e2c | 1927efaf375a10d5c0ea9956c44b16b00bdbcfa0 | |
refs/heads/master | <repo_name>cscites/LeadSorter1<file_sep>/src/com/ho8c/Client.java
package com.ho8c;
/**
* Created by chris.scites on 6/12/2017.
*/
public class Client {
private String opportunityName;
private String type;
private String amount;
private String closeDate;
private String fiscalPeriod;
private String accountName;
private String leadSource;
private String billingState;
private String primaryCampaignSource;
private String marketingCampaign;
private String opportunityOwner;
public Client(String opportunityName, String type, String amount, String closeDate, String fiscalPeriod,
String accountName, String leadSource, String billingState, String primaryCampaignSource,
String marketingCampaign, String opportunityOwner){
this.opportunityName = opportunityName;
this.type = type;
this.amount = amount;
this.closeDate = closeDate;
this.fiscalPeriod = fiscalPeriod;
this.accountName = accountName;
this.leadSource = leadSource;
this.billingState = billingState;
this.primaryCampaignSource = primaryCampaignSource;
this.marketingCampaign = marketingCampaign;
this.opportunityOwner = opportunityOwner;
}
public String getOpportunityName(){
return opportunityName;
}
public String getType(){
return type;
}
public String getAmount(){
return amount;
}
public String getCloseDate() {
return closeDate;
}
public String getFiscalPeriod() {
return fiscalPeriod;
}
public String getAccountName() {
return accountName;
}
public String getBillingState() {
return billingState;
}
public String getLeadSource() {
return leadSource;
}
public String getMarketingCampaign() {
return marketingCampaign;
}
public String getPrimaryCampaignSource() {
return primaryCampaignSource;
}
public String getOpportunityOwner() {
return opportunityOwner;
}
}
<file_sep>/src/com/ho8c/CsvParser.java
package com.ho8c;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
/**
* Created by chris on 5/29/17.
*/
public class CsvParser extends ArrayList<String[]> {
private String[] headerArray;
private ArrayList<CSVRecord> variableSets = new ArrayList<>();
public CsvParser(String csvFile) throws IOException {
File csv = new File(csvFile);
Reader in = new FileReader(csv);
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
for(CSVRecord record:records){
variableSets.add(record);
}
int n = variableSets.get(0).size();
headerArray = new String[n];
int a = 0;
while (a < n){
headerArray[a] = variableSets.get(0).get(a);
a++;
}
variableSets.remove(0);
in.close();
}
ArrayList<CSVRecord> getVariableSets(){
return variableSets;
}
String[] getHeaders(){
return headerArray;
}
}
<file_sep>/src/com/ho8c/Lead.java
package com.ho8c;
/**
* Created by chris on 5/21/17.
*/
public class Lead {
private String source;
private String specialty;
private String conference;
private String date;
private String prefix;
private String firstName;
private String middleName;
private String lastName;
private String degree;
private String company;
private String address1;
private String address2;
private String city;
private String state;
private String zip;
private String country;
private String phone;
private String fax;
private String email;
private String notes;
private String geoInt;
private String availability;
private String status;
public Lead(String source, String specialty, String conference, String date, String prefix, String firstName,
String middleName, String lastName, String degree, String company, String address1,
String address2, String city, String state, String zip, String country,
String phone, String fax, String email, String notes, String geoInt,
String availability, String status){
this.source = source;
this.specialty = specialty;
this.conference = conference;
this.date = date;
this.prefix = prefix;
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.degree = degree;
this.company = company;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.state = state;
this.zip = zip;
this.country = country;
this.phone = phone;
this.fax = fax;
this.email = email;
this.notes = notes;
this.geoInt = geoInt;
this.availability = availability;
this.status = status;
}
public String getSource(){
return source;
}
public String getSpecialty(){
return specialty;
}
public String getConference(){
return conference;
}
public String getDate(){
return date;
}
public String getPrefix(){
return prefix;
}
public String getFirstName(){
return firstName;
}
public String getMiddleName(){
return middleName;
}
public String getLastName(){
return lastName;
}
public String getDegree(){
return degree;
}
public String getCompany(){
return company;
}
public String getAddress1(){
return address1;
}
public String getAddress2(){
return address2;
}
public String getCity(){
return city;
}
public String getState(){
return state;
}
public String getZip(){
return zip;
}
public String getCountry(){
return country;
}
public String getPhone(){
return phone;
}
public String getFax(){
return fax;
}
public String getEmail(){
return email;
}
public String getNotes(){
return notes;
}
public String getGeoInt(){
return geoInt;
}
public String getAvailability(){
return availability;
}
public String getStatus(){
return status;
}
}
| a3d081827b5a46fe1112cf3723cf6e83227c2b80 | [
"Java"
] | 3 | Java | cscites/LeadSorter1 | a6d471dd35dfe5fb881ad62ef01083e7a0a5aed4 | 6793d3261dc6153b7bb050a9f9b02a786a1b61bf | |
refs/heads/main | <repo_name>syalciner/Python<file_sep>/serkan_syn_flood.py
#!/usr/bin/python
#İlk Pythonum SERKAN
#Bu Uygulama Tamamen Eğitim Amaçlıdır.
#scapy kütüphanesini çağırdım.
from scapy.all import *
from sys import stdout
# Def ile fonksiyon tanımla ip addresi - destination port- kac tane gönderecen
def SYN_Flood(dstIP,dstPort,say):
#balangıç değeri 1
basla = 1
#for dongusune sokuyoruz girilen say degeri kadar döndürüyoruz
for x in range(1,say):
packet = IP(src=dstIP)/TCP(dport=dstPort,flags="S")
send(packet)
basla += 2
stdout.write("\nToplam Gönderdigimiz Paket Sayısı: %i\n" % basla)
def info():
print ("***********************************************")
print (" *Bu Uygulama Tamamen Eğitim Amaçlıdır. *")
print ("***********************************************")
print ("* İlk Python4 SYN Flood Tool DOS Saldırısı *")
print ("***********************************************")
dstIP = input ("\nHedef IP : ")
dstPort = input ("Hedef Port : ")
return dstIP,int(dstPort)
def main():
dstIP,dstPort = info()
say = input ("Kaç Defa Gönderilsin : ")
SYN_Flood(dstIP,dstPort,int(say))
main()
| 82c4a03ca0bf10047daa6c4a58653c01cc804d8c | [
"Python"
] | 1 | Python | syalciner/Python | a7899408b8916df8b376612c65cb7e705371e060 | c731cfc4623647c50dad62e3d5a529c81917ff9d | |
refs/heads/master | <repo_name>philipf/angularjs101<file_sep>/Angular1MvcBootstrap/App_Start/BundleConfig.cs
using System.Web;
using System.Web.Optimization;
namespace Angular1MvcBootstrap
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new StyleBundle("~/Content/css")
.Include("~/Content/bootstrap.css")
.Include("~/Content/bootstrap-theme.css")
.Include("~/Content/site.css"));
bundles.Add(new ScriptBundle("~/myApp")
.Include("~/Scripts/angular.js")
.Include("~/Scripts/angular-route.js")
.Include("~/angular/app.js")
.Include("~/angular/individual.js")
.Include("~/angular/company.js")
.Include("~/angular/submissionService.js")
);
}
}
}
<file_sep>/Angular1MvcBootstrap/angular/submissionService.js
(function() {
'use strict';
var app = angular.module('myApp');
app.factory('submissionService', ['$http', submissionService]);
function submissionService($http) {
console.log('submissionService created');
return {
getCountries: function(successCallback, errorCallback) {
//return ['USA', 'Singapore', 'South Africa'];
$http.get('/api/submission/Countries').then(successCallback, errorCallback);
}
};
}
})();<file_sep>/Angular1MvcBootstrap/Controllers/SubmissionController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Angular1MvcBootstrap.Controllers
{
public class SubmissionController : ApiController
{
[HttpGet]
public IEnumerable<string> Countries()
{
return new [] { "USA", "South Africa", "Sudan", "Singapore" };
}
// GET: api/Submission/5
public string Get(int id)
{
return "value";
}
// POST: api/Submission
public void Post([FromBody]string value)
{
}
}
}
<file_sep>/Angular1MvcBootstrap/angular/company.js
(function() {
'use strict';
var app = angular.module('myApp');
app.controller('companyController', ['$scope', companyController]);
function companyController($scope) {
console.log('companyController created');
}
})(); | 91a0f9fdeadd24a7c0bd7fd6826c42147618eb7c | [
"JavaScript",
"C#"
] | 4 | C# | philipf/angularjs101 | 2f8f996e771b018698bfe462ea5fb2c0068dc88e | 0926c5be54f3aa8c3f12dec1c595f75fa7cccabc | |
refs/heads/master | <file_sep>$('body').append('<link rel="stylesheet" href="css/motw.css" type="text/css" />');
HTML_TEMPLATE_CACHE = {};
loadTemplate = function(path) {
if ( path in HTML_TEMPLATE_CACHE ) return HTML_TEMPLATE_CACHE[path];
let html = $.get({
url: path,
dataType: 'html',
async: false
}).responseText;
HTML_TEMPLATE_CACHE[path] = html;
return html;
};
sync.render("motw_sheet", function(obj, app, scope) {
let html = loadTemplate("html/motwsheet.html");
let rendered = sync.render("ui_processUI")(obj, app, {display : html});
let activemove = rendered.find(".motw_moves .motw_move_entry:last-child");
activemove.css('display', 'none');
let activeslot = rendered.find('#motw_active_move');
activeslot.html(activemove.html());
activeslot.css('display', 'block');
activeslot.find('.motw_move_description').css('display', 'block');
if (activemove.find('.motw_move_name').length === 0){
activeslot.css('display', 'none');
}
activeslot.find('.motw_movelist_plus').remove();
return rendered;
});
sync.render("motw_monster", function(obj, app, scope) {
let html = loadTemplate("html/motwmonster.html");
let rendered = sync.render("ui_processUI")(obj, app, {display : html});
return rendered;
});
sync.render("motw_move", function(obj, app, scope) {
let html = loadTemplate("html/motw_move.html");
let rendered = sync.render("ui_processUI")(obj, app, {display : html});
return rendered;
});
sync.render("motw_item", function(obj, app, scope) {
let html = loadTemplate("html/motw_item.html");
let rendered = sync.render("ui_processUI")(obj, app, {display : html});
return rendered;
}); | 30c8d7f8d0d9ab7169dffa46bcdf908912169167 | [
"JavaScript"
] | 1 | JavaScript | mesfoliesludiques/GMForge-MotW | cd2c6278b1f7c16741cbdd8624b2e6d6de5f5d3c | 0963183923bf925dae2fcb291b476d6b25ce4686 | |
refs/heads/master | <file_sep>'use strict'
const express = require('express');
var todoList = require('../controllers/todoListController')
const router = express.Router();
router.get('/', todoList.list_all_tasks)
.post('/', todoList.create_a_task);
router.get('/:id', todoList.read_a_task)
.put('/:id', todoList.update_a_task)
.delete('/:id', todoList.delete_a_task);
module.exports = router;
| 2d2d71cee5a03a4c94267e7b4b78c6000b12c747 | [
"JavaScript"
] | 1 | JavaScript | ireolaniyan/todoListAPI | 7e627e64c1a00c098109da5e3a6052c280ae9816 | d3cf83b32182812c7afb8a4f32678cf012bfb0a0 | |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include "common.c"
unsigned char curbyte = 0;
char bitsleft = 0;
char nextbit() {
//returns 0 or 1
//<0 for error
if (bitsleft == 0) {
int in=getchar();
if (in == EOF) return(-1);
curbyte = in;
bitsleft = 8;
}
//printf("curbtye: %hhu\n", curbyte);
char ret = (curbyte&0x80)>0;
curbyte<<=1;
bitsleft--;
return ret;
}
int main() {
char inbits[2] = {0, 0};
while ((inbits[0]=nextbit())>=0 && (inbits[1]=nextbit())>=0) {
//core of the von neumann filter
//printf("inbits: %hhd%hhd\n", inbits[0], inbits[1]);
if (inbits[0] == inbits[1]) continue;
else buildbyte(inbits[0]);
}
return(0);
}
<file_sep>/********************************/
/* <NAME> 2008-2009 */
/* v1.0 */
/* 4/20/2009 */
/********************************/
int baud_rate = 19200;
int adc_pin = 0;
byte partbyte = 0;
byte bitcount = 0;
void setup(){
Serial.begin(baud_rate);
//analogReference(EXTERNAL);
}
void loop(){
int adc_value = analogRead(adc_pin);
// Serial.println(adc_value, DEC);
// return;
boolean bit_in = adc_value % 2;
buildbyte(bit_in);
//delay(10);
}
void buildbyte(boolean bit_in) {
//we don't have to initialize partbyte
partbyte = (partbyte << 1) + bit_in;
bitcount = (bitcount + 1) % 8;
if (bitcount == 0) {
Serial.print(partbyte, BYTE);
}
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
int readblock(long blocksize, char* buf){
//will return 1 when the block has not been filled
//unfilled blocks (the last one, usually) are ignored
//returns 0 on a successfully filled block
int i=0;
int in=0;
for (i=0; i<blocksize; i++) {
in = getchar();
if (in == EOF) return(1);
buf[i] = in;
}
return(0);
}
char partbyte = 0;
char numbits = 0;
void buildbyte(char in_bit) {
//in_bit should be 0 or 1
partbyte = (partbyte << 1) + in_bit;
numbits = (numbits + 1) % 8;
if (numbits == 0){
putchar(partbyte);
}
}
<file_sep>#!/usr/bin/python2
import serial, sys
try:
chunksize = int(sys.argv[1])
except IndexError:
chunksize = 4096
stdout = sys.stdout
s = serial.Serial('/dev/ttyUSB0', 19200)
while 1:
buf = s.read(chunksize)
if not buf:
break
stdout.write(buf)
stdout.flush()
<file_sep>#!/bin/bash
#test each script:
#raw2bin.py
#bin2hist.py -s 2048
#bin2bias.py -s 2048
#hist2pm3d.py
#C scripts as well!
#compare md5sums of good to bad
function checksum {
CHECK=$(md5sum $1 | cut -b-32)
GOOD=$(md5sum $1.good | cut -b-32)
if [[ $CHECK = $GOOD ]]; then
echo "OK: $1"
else
echo "!!! BAD !!!: $1"
fi
}
function status {
echo -ne "$1...\033[0K\r"
}
if [[ $0 != "./test" ]]; then
echo "Run me from my directory!"
exit
fi
echo "Compiling C binaries..."
gcc ../raw2bin.c -o ../raw2bin
gcc ../bin2bias.c -o ../bin2bias
echo "Checking C binaries:"
status raw2bin
cat raw-test.good | ../raw2bin > sample-raw-test
checksum sample-raw-test
status vnf
cat sample-raw-test | ../vnf > sample-raw-test-vnf
checksum sample-raw-test-vnf
status bin2bias
cat sample-raw-test | ../bin2bias 2048 > sample-raw-test.bias
checksum sample-raw-test.bias
echo "Checking python scripts:"
status raw2bin.py
cat raw-test.good | ../raw2bin.py > sample-raw-test
checksum sample-raw-test
status vnf.py
cat sample-raw-test | ../vnf.py > sample-raw-test-vnf
checksum sample-raw-test-vnf
status bin2bias.py
cat sample-raw-test | ../bin2bias.py 2048 > sample-raw-test.bias
checksum sample-raw-test.bias
status bin2hist.py
cat sample-raw-test | ../bin2hist.py 2048 > sample-raw-test.hist
checksum sample-raw-test.hist
status hist2pm3d.py
cat sample-raw-test.hist | ../hist2pm3d.py > sample-raw-test.hist-cov
checksum sample-raw-test.hist-cov
<file_sep>#!/usr/bin/python
import sys
global partbit, numbits
partbit = 0
numbits = 0
def buildbyte(bit_in):
global partbit, numbits
partbit = (partbit << 1) + bit_in
numbits = (numbits + 1) % 8
#print("BIT_IN", bit_in, file=sys.stderr)
if numbits == 0:
#this weird line stops stdout from unicoding the bytes
sys.stdout.write(bytes(chr(partbit), "latin-1"))
partbit = 0
global curbyte, bitsleft
curbyte = 0
bitsleft = 0
def nextbit():
global curbyte, bitsleft
if not bitsleft:
curbyte = sys.stdin.read(1)
if not curbyte: return -1
curbyte = ord(curbyte)
bitsleft = 8
#print(curbyte, file=sys.stderr)
ret = int((curbyte&0x80)>0)
curbyte = (curbyte<<1) & 0xff
bitsleft -= 1
return ret
sys.stdout = sys.stdout.detach()
sys.stdin = sys.stdin.detach()
while 1:
inbits = [nextbit(), nextbit()]
#print(inbits, file=sys.stderr)
if -1 in inbits: break
if inbits[0] != inbits[1]:
buildbyte(inbits[0])
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "common.c"
//for values 0-1023, this should be fine at 5
#define MAXLINELENGTH 10
int readline(char* buf) {
int i=0;
int in=0;
for (i=0; i<MAXLINELENGTH; i++) {
in = getchar();
if (in == EOF) return(1);
if (in == '\n') {
buf[i] = 0;
return(0);
}
buf[i] = in;
}
//if we get to here, we exceeded MAXLINELENGTH
return(2);
}
int main() {
char buf[MAXLINELENGTH];
while (readline(buf) == 0) {
//printf("%s\n", buf);
buildbyte(atoi(buf)%2);
}
return(0);
}
<file_sep>#!/usr/bin/python
import sys, argparse
#parser = argparse.ArgumentParser(description='Analyze bitwise bias of \
#binary data', epilog="Input is binary data for analysis. Output is lines \
#with place in file on vertical axis like this: #0 #1 %0 %1")
#parser.add_argument('-s', default=4096, dest='chunksize', type=int,
# help='size of each chuck to consider separately')
#chunksize = parser.parse_args().chunksize
try:
chunksize = int(sys.argv[1])
except IndexError:
chunksize = 4096
stdin = sys.stdin.detach()
while 1:
chunk = stdin.read(chunksize)
if len(chunk) < chunksize:
break
counts = [0, 0]
for byte in chunk:
# bits = bin(byte)[2:]
# for bit in "0"*(8-len(bits))+bits:
# counts[int(bit)] += 1
for bit in [int(bool(byte & x)) for x in [0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1]]:
counts[int(bit)] += 1
p0 = counts[0]/sum(counts)
p1 = counts[1]/sum(counts)
print('%d %d %f %f' % (counts[0], counts[1], p0, p1))
<file_sep>#!/usr/bin/python
import sys, subprocess
from queue import Queue
from threading import Thread, Lock
from time import sleep
#basically an application-wide buffer size
#this many bytes are handled at a time
#up to this many bytes may be dropped when using tap()
#and directing it to not copy the data (the default)
BLOCKSIZE=128
tostr = lambda byte: str(byte, 'latin-1')
tobytes = lambda string: bytes(string, 'latin-1')
def totype(indata, targettype):
if type(indata) == targettype: return indata
if targettype == str: return tostr(indata)
elif targettype == bytes: return tobytes(indata)
def run(command):
"takes command and arguments in a list"
"returns stdout and stdin file objects"
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
return(p.stdout, p.stdin, p)
class StreamNode():
"A running command which is a piece of the data pipe"
def __init__(self, command, types):
self.stdout, self.stdin, self.p = run(command)
self.outtype, self.intype = types
def stop():
self.p.kill()
class EndNode():
"A file which is only written to and forms the end of a pipe"
def __init__(self, infile, datatype=str):
self.stdout, self.stdin = None, infile
self.outtype, self.intype = None, datatype
self.p = None
def stop():
pass
class SourceNode():
"A file which is only read from and forms the beginning of the pipe"
def __init__(self, outfile, datatype=str):
self.stdout, self.stdin = outfile, None
self.outtype, self.intype = datatype, None
self.p = None
def stop():
pass
class SplitThread(Thread):
"grabs input from an infile and duplicates it across one or more outs"
"can be tapped in both yank and del modes"
"file descriptors used by this class must be in BINARY MODE"
def init(self, infile, outfiles, name=None):
self.setDaemon(True)
self.infile, self.outfiles = infile, outfiles
self.tapreqs = Queue()
self.name = name
self.debug = False
def tap(self, n, copy=False):
"grab n bytes from the running pipe"
"if copy is False, the bytes returned (plus enough to make an even"
"block) will be removed from the pipe and never seen by outfiles"
"returns bytes"
"this method SHOULD be threadsafe"
"name is used for identifying when we error out"
nblocks = n//BLOCKSIZE+1
blocks = []
for bid in range(nblocks):
q = Queue()
self.tapreqs.put([copy, q])
blocks.append(q.get())
return b''.join([totype(b, bytes) for b in blocks])[:n]
def addout(self, out):
"add an out to the splitter using this method"
"argument is in standard format of [fdesc, type]"
"to remove an out, simply close the file descriptor"
self.outfiles.append(out)
def run(self):
while 1:
try:
block = self.infile.read(BLOCKSIZE)
if len(block) < BLOCKSIZE:
raise IOError("Block not filled")
except:
#what do we do now? the command exited, probably
#in any case, we can't go on
#TODO: investigate what happens to downstream stuff
print("SplitThread's infile died (name=%s)" % self.name)
print(sys.exc_info())
for out in self.outfiles:
out[0].close()
break
if self.tapreqs.qsize():
copy, cbq = self.tapreqs.get()
cbq.put(block)
if self.debug:
print("SplitThread %s giving block to tap" % self.name)
if not copy:
continue
if self.debug:
print("SplitThread %s sending block to outfiles" % self.name)
for out in self.outfiles:
try:
out[0].write(totype(block, out[1]))
out[0].flush()
except:
print("Removing outfile from SplitThread (name=%s):" % self.name)
print(sys.exc_info())
self.outfiles.remove(out)
def linknodes(innode, outnodes, name):
infile = innode.stdout
outfiles = []
for node in outnodes:
outfiles.append([node.stdin, node.intype])
splitter = SplitThread()
splitter.init(infile, outfiles, name)
splitter.start()
return splitter
def addnode(splitter, outnode):
splitter.addout([node.stdin, node.intype])
if __name__ == "__main__":
#dumpn = StreamNode(['cat', '/dev/urandom'], [bytes, None])
dumpn = StreamNode(['./dump.py', str(BLOCKSIZE)], [bytes, None])
#dumpn = SourceNode(open('server.py', 'r'))
#hexn = StreamNode(['hexdump', '-C'], [bytes, bytes])
vnfn = StreamNode('./vnf', [bytes, bytes])
#printn = EndNode(sys.stdout)
dumps = linknodes(dumpn, [vnfn], "dump")
dumps.debug = True
vnfs = linknodes(vnfn, [], "vnf")
vnfs.debug = True
#hexs = linknodes(hexn, [printn], "hex > print")
while 1:
sleep(1)
print("dumps", dumps.tap(100, True))
print("vnfs", vnfs.tap(100, True))
#i = dumps.tap(100, False)
#this makes a mess
#print(i)
<file_sep>#!/usr/bin/python
import sys
sys.stdout = sys.stdout.detach()
partbit = 0
numbits = 0
while 1:
line = sys.stdin.readline()
if not line: break
bit_in = int(line) % 2
partbit = (partbit << 1) + bit_in
numbits = (numbits + 1) % 8
if numbits == 0:
#this weird line stops stdout from unicoding the bytes
sys.stdout.write(bytes(chr(partbit), "latin-1"))
partbit = 0
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "common.c"
void checkblock(long blocksize, char* buf) {
int cid=0;
int mask=0;
char comp=1;
long counts[2] = {0, 0};
for (cid=0; cid<blocksize; cid++) {
for (mask=1; mask<=128; mask=mask << 1) {
if ((buf[cid]&mask)>0) { counts[1]++; }
else { counts[0]++; }
}
}
double sum = counts[0] + counts[1];
float p0 = counts[0]/sum;
float p1 = counts[1]/sum;
printf("%ld %ld %f %f\n", counts[0], counts[1], p0, p1);
}
int main(int argc, char *argv[]) {
int i = 0; //currently unused
long blocksize = 4096;
if (argc > 1) {
blocksize = atol(argv[1]);
}
char* buf = malloc(blocksize);
while (readblock(blocksize, buf) == 0) {
checkblock(blocksize, buf);
}
free(buf);
return(0);
}
<file_sep>#!/usr/bin/python
import sys, argparse
#parser = argparse.ArgumentParser(description='Analyze bitwise bias of \
#binary data', epilog="Input is binary data for freq analysis. Output is \
#space-separated lines of waterfall-like quantites with place in file on \
#vertical axis, byte values on horizontal axis, and popularity of each byte \
#as values.")
#parser.add_argument('-s', default=4096, dest='chunksize', type=int,
# help='size of each chuck to consider separately')
#chunksize = parser.parse_args().chunksize
try:
chunksize = int(sys.argv[1])
except IndexError:
chunksize = 4096
stdin = sys.stdin.detach()
while 1:
chunk = stdin.read(chunksize)
if len(chunk) < chunksize:
break
counts = {}
for i in range(256): counts[i] = 0
for byte in chunk:
counts[byte] += 1
for i in range(256):
sys.stdout.write(' %d' % counts[i])
print()
<file_sep>#!/usr/bin/python
import sys
#input should be space-separated lines of
#waterfall-like quantites
#with time on the vertical axis
#types on horizontal axis
#bar heights as values
linecnt = 0
while 1:
line = sys.stdin.readline()
if len(line) == 0:
break
colcnt = 0
for col in line.split():
print('%d %d %d' % (linecnt, colcnt, float(col)))
colcnt += 1
print()
linecnt += 1
| ac8ef1e7e4be72ae5a5be4b64a904657fb7137e4 | [
"C",
"Python",
"C++",
"Shell"
] | 13 | C | comepradz/randuino | 243f5b089d1178c82a2c7bfd14a7ffe7d1dfb4fe | 0ba9b396f113c08ad46c6301209a28972ba0442a | |
refs/heads/master | <file_sep># [yt.filipkin.com](http://yt.filipkin.com)
<file_sep><!doctype html>
<?php include("/var/www/analytics.php"); ?>
<?php ini_set('display_errors', 'Off'); ?>
<?php
function decode($str) {
$dict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765";
$newdict = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~");
$ar = str_split($str);
$out = "";
foreach($ar as &$letter) {
$index = strpos($dict, $letter);
if ($index == false) {
$out.=$letter;
} else {
$out.=$newdict[$index];
}
}
return $out;
}
function nicenumber($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000) return round(($n/1000000000),1).'B';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
$rc = $_GET["rc"];
if ($rc == "") {
$rc = 5;
}
if ($rc > 49) {
$rc = 50;
}
$sc = $_GET["sc"];
if ($sc == "") {
$sc = 5;
}
if ($sc > 49) {
$sc = 50;
}
?>
<html>
<head>
<title>No VPN Youtube</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.search-result-image {
text-align: right !important;
}
.search-result-text {
text-align: left !important;
}
.search-result-text > .link {
color: #282828;
font-weight: bold;
}
.search-result-text > .link-big {
color: #282828;
font-weight: bold;
}
.link > img {
transition: transform 1s ease;
width: 280px;
}
.link:hover > img {
transform: scale(1.1, 1.1);
}
.link-big > img {
transition: transform 1s ease;
width: 320px;
}
.link:hover {
color: #555555;
}
@media screen and (max-width: 48em) {
.search-result-image {
text-align: center !important;
}
.search-result-text {
text-align: center !important;
font-size: 12px;
}
}
#sign-in-or-out-button {
color: #dc3545;
margin-left: 1em;
}
#sign-in-or-out-button:hover {
color: white;
background: #dc3545;
}
</style>
</head>
<body>
<script>function getsc() {return <?php echo $sc; ?>}</script>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#"><img src="logo.svg" height="30" alt=""></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">
<form class="form-inline my-4 my-lg-0" onsubmit="return search();">
<input class="form-control mr-sm-4" style="width: 400px;" type="search" id="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-danger my-4 my-sm-0" type="submit">Search</button>
<a class="btn btn-outline-danger my-4 my-sm-0" id="sign-in-or-out-button">Sign in to get your subscription feed</a>
</form>
</div>
</nav>
<div class="container-fluid" id="body-table">
<h6>Are you having issues or want to leave a suggestion? Email me: <a href="mailto:<EMAIL>?subject=yt.filipkin.com bug/suggestions"><EMAIL></a></h6>
<div class="row">
<div id="subdiv" class="col-xs-12 col-sm-12 col-md-12 col-lg-6 col-xl-6" style="text-align:center;display:none;">
<h2>Subscriptions</h2>
<hr>
<div id="subscriptions">
</div>
<?php
$msc = $sc + 10;
if ($msc > 49) {
$msc = 50;
}
echo '<a href="index.php?sc='.$msc.'&rc='.$rc.'" class="form-control" style="background:#0051BC;color:white;text-align:center;">More Subscription Feed</a>';
?>
</div>
<script src="https://apis.google.com/js/client.js?onload=onLoadCallback" async defer></script>
<script>
var GoogleAuth;
var SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl';
function handleClientLoad() {
// Load the API's client and auth2 modules.
// Call the initClient function after the modules load.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Retrieve the discovery document for version 3 of YouTube Data API.
// In practice, your app can retrieve one or more discovery documents.
var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest';
// Initialize the gapi.client object, which app uses to make API requests.
// Get API key and client ID from API Console.
// 'scope' field specifies space-delimited list of access scopes.
gapi.client.init({
'discoveryDocs': [discoveryUrl],
'clientId': '1088047505782-gnfl6110hvq4o942hpl1hirginuoj2d2.apps.googleusercontent.com',
'scope': SCOPE
}).then(function () {
GoogleAuth = gapi.auth2.getAuthInstance();
// Listen for sign-in state changes.
GoogleAuth.isSignedIn.listen(updateSigninStatus);
// Handle initial sign-in state. (Determine if user is already signed in.)
var user = GoogleAuth.currentUser.get();
setSigninStatus();
// Call handleAuthClick function when user clicks on
// "Sign In/Authorize" button.
$('#sign-in-or-out-button').click(function() {
handleAuthClick();
});
});
}
function handleAuthClick() {
if (GoogleAuth.isSignedIn.get()) {
// User is authorized and has clicked 'Sign out' button.
GoogleAuth.signOut();
} else {
// User is not signed in. Start Google auth flow.
GoogleAuth.signIn();
}
}
function revokeAccess() {
GoogleAuth.disconnect();
}
function setSigninStatus(isSignedIn) {
var user = GoogleAuth.currentUser.get();
var isAuthorized = user.hasGrantedScopes(SCOPE);
if (isAuthorized) {
$('#sign-in-or-out-button').html('Sign out');
var element = document.getElementById('subdiv');
element.style.display = "block";
$('#trending').addClass("col-xs-0");
$('#trending').addClass("col-sm-0");
$('#trending').addClass("col-md-0");
$('#trending').addClass("col-lg-6");
$('#trending').addClass("col-xl-6");
$('#trending').removeClass("col-xs-12");
$('#trending').removeClass("col-sm-12");
$('#trending').removeClass("col-md-12");
$('#trending').removeClass("col-lg-12");
$('#trending').removeClass("col-xl-12");
$('.search-result-image').find('.link-big').addClass('link');
$('.search-result-image').find('.link-big').removeClass('link-big');
var request = gapi.client.request({
'method': 'GET',
'path': '/youtube/v3/subscriptions',
'params': {'part': 'snippet', 'mine': 'true', 'maxResults': '50'}
});
// Execute the API request.
var numberOfSubsProcessed=0;
var subs = [];
request.execute(function(response) {
var videos = [];
var items = response.items;
items.forEach(function(obj){
var id = obj.snippet.resourceId.channelId;
subs.push(id);
});
var sc = getsc();
var multiple=0;
for (i=0; i*subs.length<sc; i++) {
multiple++;
}
subs.forEach(function(sub){
var request = gapi.client.request({
'method': 'GET',
'path': '/youtube/v3/search',
'params': {'part': 'snippet', 'channelId': sub, 'maxResults': multiple+1, 'order':'date'}
});
request.execute(function(response) {
numberOfSubsProcessed++;
var items = response.items;
items.forEach(function(obj) {
videos.push(obj)
});
if (numberOfSubsProcessed == subs.length) {
var releaseTimestamps = [];
var newvideos = [];
videos.forEach(function(obj) {
var newobj = {"timestamp": obj.snippet.publishedAt, "id": obj.id.videoId, "channel": obj.snippet.channelTitle, "title": obj.snippet.title, "thumbnail": obj.snippet.thumbnails.medium.url};
newvideos.push(newobj);
});
newvideos.sort(function(a, b) {
var at = Date.parse(a.timestamp);
var bt = Date.parse(b.timestamp);
return bt-at;
})
newvideos = newvideos.slice(0, sc)
console.log(newvideos);
var out = [];
var x = 0;
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
newvideos.forEach(function(obj, i) {
httpGet("data.php?id="+obj.id, function(data) {
var data = JSON.parse(data)
var views = data.views;
var datetime = new Date(Date.parse(obj.timestamp));
var date = months[datetime.getMonth()]+" "+datetime.getDate()+" "+datetime.getFullYear();
var length = data.length;
var link = '<a href="watch.php?id='+obj.id+'" class="link">';
out[i] = '<div class="row">';
out[i] += '<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 search-result-image">'+link+'<img src="'+obj.thumbnail+'"></a></div>';
out[i] += '<div class="col-xs-0 col-sm-0 col-md-5 col-md-offset-1 col-lg-6 col-xl-6 search-result-text">'+link+obj.title+'</a>';
out[i] += '<br>By: '+obj.channel;
out[i] += '<br>Views: '+views;
out[i] += '<br>Length: '+length;
out[i] += '<br>Published: '+date+'</div></div>';
document.getElementById("subscriptions").innerHTML=out.join("<hr>")+"<hr>";
});
})
}
});
});
});
} else {
$('#sign-in-or-out-button').html('Sign in to get your subscription feed');
var element = document.getElementById('subdiv');
element.style.display = "none";
$('#trending').removeClass("col-xs-0");
$('#trending').removeClass("col-sm-0");
$('#trending').removeClass("col-md-0");
$('#trending').removeClass("col-lg-6");
$('#trending').removeClass("col-xl-6");
$('#trending').addClass("col-xs-12");
$('#trending').addClass("col-sm-12");
$('#trending').addClass("col-md-12");
$('#trending').addClass("col-lg-12");
$('#trending').addClass("col-xl-12");
$('.search-result-image').find('.link').addClass('link-big');
$('.search-result-image').find('.link').removeClass('link');
}
}
function updateSigninStatus(isSignedIn) {
setSigninStatus();
}
function httpGet(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<div id="trending" class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12" style="text-align:center;">
<h2>Trending</h2>
<hr>
<?php
$result = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=snippet&chart=mostPopular&maxResults=".$rc."&key=<KEY>"));
foreach($result->items as &$obj) {
$url = "watch.php?id=".$obj->id;
$link = '<a class="link-big" href="'.$url.'">';
$content = file_get_contents("https://youtube.com/get_video_info?video_id=".$obj->id);
parse_str($content, $ytarr);
$title = $ytarr['title'];
$views = $ytarr['view_count'];
$length = $ytarr['length_seconds'];
$hours = floor($length / 3600);
$mins = floor($length / 60 % 60);
$secs = floor($length % 60);
echo '<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 search-result-image">'.$link.'<img src="'.$obj->snippet->thumbnails->medium->url.'"></a></div>
<div class="col-xs-0 col-sm-0 col-md-5 col-lg-6 col-xl-6 search-result-text">'.$link.$obj->snippet->title.'</a>
<br>By: '.$obj->snippet->channelTitle.'
<br>Views: '.nicenumber($views).'
<br>Length: '.sprintf('%02d:%02d:%02d', $hours, $mins, $secs).'</div></div><hr>';
}
$mrc = $rc + 10;
if ($mrc > 49) {
$mrc = 50;
}
echo '<a href="index.php?sc='.$sc.'&rc='.$mrc.'" class="form-control" style="background:#0051BC;color:white;text-align:center;">More Trending</a>';
?>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script>
function encode(str) {
var dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var newdict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var ar = str.split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return encodeURIComponent(out.join(''))
}
function decode(str) {
var dict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var newdict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var ar = decodeURIComponent(str).split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return out.join('')
}
function search() {
var url = "http://yt.filipkin.com/search.php?q="+encode(document.getElementById("q").value)
window.location = url;
return false;
}
</script>
</body>
</html>
<file_sep><?php
function nicenumber($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000) return round(($n/1000000000),1).'B';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
$id = $_GET["id"];
$content = file_get_contents("https://youtube.com/get_video_info?video_id=".$id);
parse_str($content, $ytarr);
$views = $ytarr['view_count'];
$length = $ytarr['length_seconds'];
$hours = floor($length / 3600);
$mins = floor($length / 60 % 60);
$secs = floor($length % 60);
echo '{"views": "'.nicenumber($views).'", "length": "'.sprintf('%02d:%02d:%02d', $hours, $mins, $secs).'", "debug": '.json_encode($ytarr).'}';
?>
<file_sep><!doctype html>
<?php include("/var/www/analytics.php"); ?>
<?php ini_set('display_errors', 'Off'); ?>
<?php
function decode($str) {
$dict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765";
$newdict = str_split("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~");
$ar = str_split($str);
$out = "";
foreach($ar as &$letter) {
$index = strpos($dict, $letter);
if ($index == false) {
$out.=$letter;
} else {
$out.=$newdict[$index];
}
}
return $out;
}
function nicenumber($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000) return round(($n/1000000000),1).'B';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
$rc = $_GET["rc"];
if ($rc == "") {
$rc = 5;
}
if ($rc > 49) {
$rc = 50;
}
?>
<html>
<head>
<title>No VPN Youtube</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.search-result-image {
text-align: right !important;
}
.search-result-text {
text-align: left !important;
}
.link > img {
transition: transform 1s ease;
width: 320px;
}
.link:hover > img {
transform: scale(1.1, 1.1);
}
.link {
color: #282828;
transition: color 0.5s ease;
font-weight: bold;
}
.link:hover {
color: #555555;
}
@media screen and (max-width: 48em) {
.search-result-image {
text-align: center !important;
}
.search-result-text {
text-align: center !important;
font-size: 12px;
}
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.php"><img src="logo.svg" height="30" alt=""></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">
<form class="form-inline my-4 my-lg-0" onsubmit="return search();">
<input class="form-control mr-sm-4" style="width: 400px;" type="search" id="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-danger my-4 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="container-fluid" id="body-table">
<hr>
<?php
$q = decode($_GET['q']);
$result = json_decode(file_get_contents("https://www.googleapis.com/youtube/v3/search?type=video&maxResults=".$rc."&key=<KEY>&part=snippet&q=".urlencode($q)));
foreach($result->items as &$obj) {
$url = "watch.php?id=".$obj->id->videoId;
$link = '<a class="link" href="'.$url.'">';
$content = file_get_contents("https://youtube.com/get_video_info?video_id=".$obj->id->videoId);
parse_str($content, $ytarr);
$title = $ytarr['title'];
$views = $ytarr['view_count'];
$length = $ytarr['length_seconds'];
$hours = floor($length / 3600);
$mins = floor($length / 60 % 60);
$secs = floor($length % 60);
echo '<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 search-result-image">'.$link.'<img src="'.$obj->snippet->thumbnails->medium->url.'"></a></div>
<div class="col-xs-0 col-sm-0 col-md-5 col-lg-6 col-xl-6 search-result-text">'.$link.$obj->snippet->title.'</a>
<br>By: '.$obj->snippet->channelTitle.'
<br>Views: '.nicenumber($views).'
<br>Length: '.sprintf('%02d:%02d:%02d', $hours, $mins, $secs).'</div></div><hr>';
}
$mrc = $rc + 10;
if ($mrc > 49) {
$mrc = 50;
}
echo '<a href="search.php?q='.urlencode($_GET["q"]).'&rc='.$mrc.'" class="form-control" style="background:#0051BC;color:white;text-align:center;">More Results</a>';
echo '<script>document.getElementById("q").value="'.$q.'"</script>';
?>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script>
function encode(str) {
var dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var newdict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var ar = str.split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return encodeURIComponent(out.join(''))
}
function decode(str) {
var dict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var newdict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var ar = decodeURIComponent(str).split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return out.join('')
}
function search() {
var url = "http://yt.filipkin.com/search.php?q="+encode(document.getElementById("q").value)
window.location = url;
return false;
}
</script>
</body>
</html>
<file_sep>//Hey look here!
homePage = "http://filipkin.com";
adminEmail = "<EMAIL>";
function buttonize() {
if (document.getElementById("homepage") !== null){
document.getElementById("homepage").href = homePage;
}
if (document.getElementById("problem") !== null) {
document.getElementById("problem").href = "mailto:" + adminEmail;
}
}
function ErrorPage(container, pageType, templateName) {
this.$container = $(container);
this.$contentContainer = this.$container.find(templateName == 'sign' ? '.sign-container' : '.content-container');
this.pageType = pageType;
this.templateName = templateName;
}
ErrorPage.prototype.centerContent = function () {
var containerHeight = this.$container.outerHeight()
, contentContainerHeight = this.$contentContainer.outerHeight()
, top = (containerHeight - contentContainerHeight) / 2
, offset = this.templateName == 'sign' ? -100 : 0;
this.$contentContainer.css('top', top + offset);
};
ErrorPage.prototype.initialize = function () {
var self = this;
this.centerContent();
this.$container.on('resize', function (e) {
e.preventDefault();
e.stopPropagation();
self.centerContent();
});
// fades in content on the plain template
if (this.templateName == 'plain') {
window.setTimeout(function () {
self.$contentContainer.addClass('in');
}, 500);
}
// swings sign in on the sign template
if (this.templateName == 'sign') {
$('.sign-container').animate({textIndent : 0}, {
step : function (now) {
$(this).css({
transform : 'rotate(' + now + 'deg)',
'transform-origin' : 'top center'
});
},
duration : 1000,
easing : 'easeOutBounce'
});
}
};
ErrorPage.prototype.createTimeRangeTag = function(start, end) {
return (
'<time utime=' + start + ' simple_format="MMM DD, YYYY HH:mm">' + start + '</time> - <time utime=' + end + ' simple_format="MMM DD, YYYY HH:mm">' + end + '</time>.'
)
};
ErrorPage.prototype.handleStatusFetchSuccess = function (pageType, data) {
if (pageType == '503') {
$('#replace-with-fetched-data').html(data.status.description);
} else {
if (!!data.scheduled_maintenances.length) {
var maint = data.scheduled_maintenances[0];
$('#replace-with-fetched-data').html(this.createTimeRangeTag(maint.scheduled_for, maint.scheduled_until));
$.fn.localizeTime();
}
else {
$('#replace-with-fetched-data').html('<em>(there are no active scheduled maintenances)</em>');
}
}
};
ErrorPage.prototype.handleStatusFetchFail = function (pageType) {
$('#replace-with-fetched-data').html('<em>(enter a valid Statuspage url)</em>');
};
ErrorPage.prototype.fetchStatus = function (pageUrl, pageType) {
//console.log('in app.js fetch');
if (!pageUrl || !pageType || pageType == '404') return;
var url = ''
, self = this;
if (pageType == '503') {
url = pageUrl + '/api/v2/status.json';
}
else {
url = pageUrl + '/api/v2/scheduled-maintenances/active.json';
}
$.ajax({
type : "GET",
url : url,
}).success(function (data, status) {
//console.log('success');
self.handleStatusFetchSuccess(pageType, data);
}).fail(function (xhr, msg) {
//console.log('fail');
self.handleStatusFetchFail(pageType);
});
};
// hack to make sure content stays centered >_<
$(window).on('resize', function() {
$('body').trigger('resize')
});
<file_sep><!doctype html>
<?php include("/var/www/analytics.php"); ?>
<?php ini_set('display_errors', 'Off'); ?>
<?php
$id = $_GET["id"];
$content = file_get_contents("https://youtube.com/get_video_info?video_id=".$id);
parse_str($content, $ytarr);
$title = $ytarr['title'];
$views = $ytarr['view_count'];
$channel = $ytarr['author'];
$length = $ytarr['length_seconds'];
function nicenumber($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000) return round(($n/1000000000),1).'B';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
?>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<style>
.related-link {
font-weight: bold;
color: #282828;
transition: color 1s ease;
font-size:18px;
}
.related-channel {
color: #333333;
transition: color 1s ease;
}
.related-link:hover {
font-weight: bold;
color: #444444;
}
.related-channel:hover {
color: #666666;
}
.related-link > img {
transition: transform 1s ease;
}
.related-link:hover > img {
transform: scale(1.1, 1.1);
}
</style>
<title><?php echo $title; ?></title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="index.php"><img src="logo.svg" height="30" alt=""></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">
<form class="form-inline my-4 my-lg-0" onsubmit="return search();">
<input class="form-control mr-sm-4" style="width: 400px;" type="search" id="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-danger my-4 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="container-fluid" id="body-table">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-7">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-zero embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="http://www.youtubeeducation.com/embed/<?php echo $id; ?>?autoplay=1" frameborder=0 allowfullscreen="allowfullscreen"></iframe>
</div>
<h1><?php echo $title; ?></h1>
Channel: <?php echo $channel; ?>
<br>Views: <?php echo nicenumber($views); ?>
</div>
<div class="col-xs-0 col-sm-0 col-md-0 col-lg-5">
<h4>Related Videos</h4><table id="related"></table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script>
function httpGet(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
httpGet("https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=10&relatedToVideoId=<?php echo $id; ?>&type=video&key=AIzaSyAiH7HiJnrV6AERNET7ISmcONbisaJvkOA", function(data) {
var rt = document.getElementById("related");
var videos = JSON.parse(data).items;
videos.forEach(function(obj) {
var row = rt.insertRow(rt.rows.length);
httpGet("data.php?id="+obj.id.videoId, function(data) {
var data = JSON.parse(data)
var views = data.views;
var length = data.length;
row.insertCell(0).innerHTML = '<a class="related-link" href="watch.php?id='+obj.id.videoId+'"><img src="'+obj.snippet.thumbnails.medium.url+'"></a>';
var data = '<a class="related-link" href="watch.php?id='+obj.id.videoId+'">'+obj.snippet.title+'</a>';
data += '<br><a class="related-channel" href="#">'+obj.snippet.channelTitle+'</a>';
data += '<br>Views: '+views+'<br>Length: '+length;
row.insertCell(1).innerHTML = data
});
});
});
</script>
<script>
function encode(str) {
var dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var newdict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var ar = str.split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return encodeURIComponent(out.join(''))
}
function decode(str) {
var dict = "FEDCBAPONMLKJIHGZYXWVUTSRQjihgfedcbatsrqponmlk4321zyxwvu~_-.098765".split('')
var newdict = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.-_~".split('')
var ar = decodeURIComponent(str).split('')
var out = []
ar.forEach(function(letter) {
var index = dict.indexOf(letter);
if (index == -1) {
out.push(letter)
} else {
out.push(newdict[index])
}
})
return out.join('')
}
function search() {
var url = "http://yt.filipkin.com/search.php?q="+encode(document.getElementById("q").value)
window.location = url;
return false;
}
</script>
</body>
</html>
| 03213bc7f42e4f524ac0e6649549a73c8bc77985 | [
"Markdown",
"JavaScript",
"PHP"
] | 6 | Markdown | Filip-Kin/yt.filipkin.com | e49c423d339a8fb3f935362fd1422cf961587076 | 097168dbdc1d2e996fed038feb22868b0c3dd18e | |
refs/heads/master | <file_sep>package ru.ovrays.example
import ru.ovrays.bukkitcooldowns.Cooldowns
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.event.player.PlayerChangedWorldEvent
import org.bukkit.plugin.java.JavaPlugin
class ExamplePlugin : JavaPlugin(), Listener {
override fun onEnable() {
this.server.pluginManager.registerEvents(this, this)
}
@EventHandler
fun onWorldChange(e: PlayerChangedWorldEvent) {
Cooldowns.setCooldown(e.player, "Protect", 5000) // Time in ms
}
@EventHandler
fun onEntityDamage(e: EntityDamageEvent) {
if(e.entity !is Player) return
val player = e.entity as Player
if (Cooldowns.tryCooldown(player, "Protect")) {
// This code will be executed if cooldown does not exist or expired
} else {
e.isCancelled = true
player.sendMessage("You are protected from being damaged! (${(Cooldowns.getCooldown(player, "ProtectCooldown") as Long / 1000)} seconds left)")
}
}
}
<file_sep># BukkitCooldowns
Cooldown system for Bukkit/Spigot 1.12.2+
<file_sep>package ru.ovrays.bukkitcooldowns
import com.google.common.collect.HashBasedTable
import org.bukkit.entity.Player
object Cooldowns {
private val cooldowns = HashBasedTable.create<Any, Any, Any>()
/**
* Update a cooldown for the specified player.
* @param player - the player.
* @param key - cooldown to update.
* @param delay - number of milliseconds until the cooldown will expire again.
* @return The previous number of milliseconds until expiration.
*/
fun setCooldown(player: Player, key: String, delay: Long): Long {
return calculateRemainder(
cooldowns.put(player.name, key, System.currentTimeMillis() + delay) as Long?
)
}
/**
* Retrieve the number of milliseconds left until a given cooldown expires.
*
*
* Check for a negative value to determine if a given cooldown has expired. <br></br>
* Cooldowns that have never been defined will return [Long.MIN_VALUE].
* @param player - the player.
* @param key - cooldown to locate.
* @return Number of milliseconds until the cooldown expires.
*/
fun getCooldown(player: Player, key: String): Long? {
return calculateRemainder(cooldowns.get(player.name, key) as Long? ?: return null)
}
/**
* Determine if a given cooldown has expired. If it has, refresh the cooldown. If not, do nothing.
* @param player - the player.
* @param key - cooldown to update.
* @return TRUE if the cooldown was expired/unset, FALSE otherwise.
*/
fun tryCooldown(player: Player, key: String): Boolean {
val cooldown = getCooldown(player, key)
return if(cooldown != null)
cooldown <= 0
else
true
}
private fun calculateRemainder(expireTime: Long?): Long {
return if (expireTime != null) expireTime - System.currentTimeMillis() else java.lang.Long.MIN_VALUE
}
}
| 3d87a394a6b8581716556c111ebc8fc70ea4a2fc | [
"Markdown",
"Kotlin"
] | 3 | Kotlin | ovrays/BukkitCooldowns | bd7fe4b29090a26c9a59bc7d32d186c5b824e06f | e5e6809848a11815c4021d27ebfe5eb17407126e | |
refs/heads/main | <file_sep>import turtle
import random
color_list = [(139, 168, 195), (206, 154, 121), (192, 140, 150), (25, 36, 55), (58, 105, 140), (145, 178, 162), (151, 68, 58),
(137, 68, 76), (229, 212, 107), (47, 36, 41), (145, 29, 36), (28, 53, 47), (55, 108, 89), (228, 167, 173),
(189, 99, 107), (139, 33, 28), (194, 92, 79), (49, 40, 36), (228, 173, 166), (20, 92, 69), (177, 189, 212),
(29, 62, 107), (113, 123, 155), (172, 202, 190), (51, 149, 193), (166, 200, 213)]
timy = turtle.Turtle()
turtle.colormode(255)
timy.hideturtle()
timy.speed(0)
timy.penup()
def dot_line():
for column in range(10):
for dot in range(10):
timy.dot(20, random.choice(color_list))
timy.penup()
timy.forward(50)
timy.setx(0)
timy.penup()
timy.left(90)
timy.forward(50)
timy.right(90)
dot_line()
screen = turtle.Screen()
screen.exitonclick()
| 3549183309e279f198bedd8063f1c189b407c219 | [
"Python"
] | 1 | Python | Soare95/Hirst-Picture | 466219d83558ca01f028431cdc2652cb5ae9d053 | c31573085056bbebf1b9c1ab8cc5f2a716dd2bca | |
refs/heads/master | <file_sep>{{#if_eq build "standalone"}}
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
{{/if_eq}}
import Vue from 'vue'
import App from './App'
{{#router}}
import router from './router'
{{/router}}
{{#http}}
import http from './plugins/http'
{{/http}}
{{#adaptive}}
import Adaptive from 'vue-adaptive'
import {adaptive as adaptiveConf} from '../config/app.config'
{{/adaptive}}
{{#vuex}}
import Vuex from 'vuex'
import Store from './store'
{{/vuex}}
{{#adaptive}}
// Setting adaptive plugin
Vue.use(Adaptive, adaptiveConf)
{{/adaptive}}
{{#http}}
// Setting http plugin
Vue.use(http)
{{/http}}
{{#vuex}}
// Setting store
Vue.use(Vuex)
const store = new Vuex.Store(Store)
{{/vuex}}
Vue.config.productionTip = false
export default new Vue({
el: '#app',
{{#router}}
router,
{{/router}}
{{#vuex}}
store,
{{/vuex}}
{{#if_eq build "runtime"}}
render: h => h(App)
{{/if_eq}}
{{#if_eq build "standalone"}}
components: { App },
template: '<App/>'
{{/if_eq}}
})
<file_sep>// Here you can store configs for all components and plugins
module.exports.styleImports = {
/*
* You can use string or array of string.
* String can starts with @ - that means that path is relative to src folder (vue root).
* You always can write path relative to build directory instead.
* !Warning: It is better to use arrays instead of one file with imports 'cause imports will slow down build.
* Imported files must contain ONLY preprocessor info (variables, mixins, e.t.c.)
********************************************************************************************
* stylus: [],
* less: '@assets/less/style.less',
* sass: '../src/assets/sass/style.sass',
* scss: '@assets/scss/style.scss'
*/
}
{{#adaptive}}
module.exports.adaptive = {
'desktop:wide': {
rem: 10,
from: {
width: 1352
}
},
'desktop:thin': {
k: .75,
from: {
width: 1008
},
base: {
width: 1008
},
to: {
width: 1351
},
},
'tablet': {
rem: 10,
from: {
width: 752
},
to: {
width: 1008
}
},
'mobile': {
rem: 10,
from: {
width: 305
},
to: {
width: 751
}
}
}
{{/adaptive}}
{{#http}}
module.exports.http = {
credentials : 'same-origin',
url : 'https://api.stackexchange.com/2.2/search',
method : 'GET',
mode : 'no-cors',
dataType : 'form'
}
{{/http}}
<file_sep>import {http as defaultConfig} from '../../config/app.config'
import _ from 'lodash'
import base64 from 'base-64'
export default {
instance (config) {
config = _.defaults(config, defaultConfig)
let fetchConfig = {
method: config.hasOwnProperty('method') ? config.method : 'GET',
credentials: config.hasOwnProperty('credentials') ? config.credentials : 'same-origin',
mode: config.hasOwnProperty('mode') ? config.mode : 'no-cors',
headers: new Headers()
}
if (config.hasOwnProperty('authorization')) {
const login = config.authorization.login
const password = config.authorization.password
fetchConfig.headers.append('Authorization', `basic ${base64.encode(`${login}:${password}`)}`)
}
if (config.hasOwnProperty('data')) {
if (fetchConfig.method === 'GET') {
let attrList = []
for (let attr in config.data) {
if (config.data.hasOwnProperty(attr)) attrList.push(encodeURIComponent(attr) + '=' + encodeURIComponent(config.data[attr]))
}
config.url += `?${attrList.join('&')}`
console.log(config.url)
// If we'll send JSON
} else if (config.dataType === 'json') {
fetchConfig.headers.append('Content-Type', 'application/json')
fetchConfig.body = JSON.stringify(config.data)
// If we'll send formData
} else {
let payload = new FormData()
for (let chunk in config.data) {
if (config.data.hasOwnProperty(chunk)) payload.append(chunk, config.data[chunk])
}
fetchConfig.body = payload
}
}
return fetch(config.url, fetchConfig).then(response => response.json())
},
install (Vue) {
Vue.prototype.$http = this.instance
}
}
| b00b9a4eaa2dd62a4d0cde5427ccb2042bb411e0 | [
"JavaScript"
] | 3 | JavaScript | zmey3301/webpack | e42d4e6f561c5de5eb5fb162430c81fa8b883df2 | 634456dcfd4a24b91c6b7d7608c357eb85c692ec | |
refs/heads/master | <file_sep>using Plugin.TextToSpeech;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App12
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void ClickedButton(object Sender, EventArgs args)
{
var text = Enter.Text;
CrossTextToSpeech.Current.Speak(text);
}
}
}
| 3588b79c730066002c9c9e9385d68cf45571a854 | [
"C#"
] | 1 | C# | Samirgc/Slac2018SecA | 8e8eb9fea318273b8418d992f80c90cd18c5d7f2 | 80f7285e78b75c6e261b8a7b5f15744dc73fd8cd | |
refs/heads/master | <repo_name>fcccode/bkdrv<file_sep>/main.c
#include "utils.h"
#include "pe.h"
void DriverUnload(PDRIVER_OBJECT pDriverObject)
{
UNREFERENCED_PARAMETER(pDriverObject);
DbgPrint("Driver Unload Success !");
}
NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegsiterPath)
{
const uint8_t *new_module, *old_module;
new_module = pe_load_file(L"\\??\\C:\\WINDOWS\\system32\\ntkrnlpa.exe");
if (new_module == NULL)
{
return STATUS_NOT_SUPPORTED;
}
old_module = get_module_base(pDriverObject, L"\\??\\C:\\WINDOWS\\system32\\ntkrnlpa.exe");
if (old_module == NULL) {
return STATUS_NOT_SUPPORTED;
}
fix_reloc_table(new_module, old_module);
pDriverObject->DriverUnload = DriverUnload;
return STATUS_SUCCESS;
}<file_sep>/utils.h
#pragma once
#include <ntddk.h>
#include <ntimage.h>
KIRQL unset_wp();
VOID set_wp(KIRQL Irql);<file_sep>/struct.h
#pragma once
#include <fltkernel.h>
typedef unsigned char BYTE;
typedef unsigned int UINT;
typedef int BOOL;
// TODO This is rather ugly, but does the job for now.
#define DWORD UINT
#pragma warning( push )
#pragma warning( disable : 4200 ) // warning C4200: nonstandard extension used : zero-sized array in struct/union
#pragma warning( disable : 4201 ) // warning C4201: nonstandard extension used : nameless struct/union
typedef enum _SECTION_INFORMATION_CLASS {
SectionBasicInformation,
SectionImageInformation
} SECTION_INFORMATION_CLASS, *PSECTION_INFORMATION_CLASS;
typedef struct _SYSTEM_MODULE {
PVOID reserved[2];
PVOID Base;
ULONG Size;
ULONG Flags;
USHORT Index;
USHORT Unknown;
USHORT LoadCount;
USHORT ModuleNameOffset;
CHAR ImageName[256];
} SYSTEM_MODULE, *PSYSTEM_MODULE;
typedef struct _SYSTEM_MODULE_INFORMATION {
ULONG ModulesCount;
SYSTEM_MODULE Modules[];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;
typedef enum _SYSDBG_COMMAND {
SysDbgQueryModuleInformation = 1,
SysDbgQueryTraceInformation,
SysDbgSetTracepoint,
SysDbgSetSpecialCall,
SysDbgClearSpecialCalls,
SysDbgQuerySpecialCalls
} SYSDBG_COMMAND, *PSYSDBG_COMMAND;
typedef struct _RTL_USER_PROCESS_PARAMETERS {
UCHAR Reserved1[16];
PVOID Reserved2[10];
UNICODE_STRING ImagePathName;
UNICODE_STRING CommandLine;
} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
typedef struct _PS_ATTRIBUTE {
ULONG_PTR Attribute;
SIZE_T Size;
union {
ULONG_PTR Value;
PVOID ValuePtr;
};
PSIZE_T ReturnLength;
} PS_ATTRIBUTE, *PPS_ATTRIBUTE;
typedef struct _PS_ATTRIBUTE_LIST {
SIZE_T TotalLength;
PS_ATTRIBUTE Attributes[1];
} PS_ATTRIBUTE_LIST, *PPS_ATTRIBUTE_LIST;
typedef struct _INITIAL_TEB {
PVOID StackBase;
PVOID StackLimit;
PVOID StackCommit;
PVOID StackCommitMax;
PVOID StackReserved;
} INITIAL_TEB, *PINITIAL_TEB;
typedef struct _SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER Reserved[3];
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE ProcessId;
HANDLE InheritedFromProcessId;
ULONG HandleCount;
ULONG Reserved2[2];
ULONG PrivatePageCount;
VM_COUNTERS VirtualMemoryCounters;
IO_COUNTERS IoCounters;
PVOID Threads[0];
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemBasicInformation,
SystemProcessorInformation,
SystemPerformanceInformation,
SystemTimeOfDayInformation,
SystemPathInformation,
SystemProcessInformation,
SystemCallCountInformation,
SystemDeviceInformation,
SystemProcessorPerformanceInformation,
SystemFlagsInformation,
SystemCallTimeInformation,
SystemModuleInformation,
SystemLocksInformation,
SystemStackTraceInformation,
SystemPagedPoolInformation,
SystemNonPagedPoolInformation,
SystemHandleInformation,
SystemObjectInformation,
SystemPageFileInformation,
SystemVdmInstemulInformation,
SystemVdmBopInformation,
SystemFileCacheInformation,
SystemPoolTagInformation,
SystemInterruptInformation,
SystemDpcBehaviorInformation,
SystemFullMemoryInformation,
SystemLoadGdiDriverInformation,
SystemUnloadGdiDriverInformation,
SystemTimeAdjustmentInformation,
SystemSummaryMemoryInformation,
SystemNextEventIdInformation,
SystemEventIdsInformation,
SystemCrashDumpInformation,
SystemExceptionInformation,
SystemCrashDumpStateInformation,
SystemKernelDebuggerInformation,
SystemContextSwitchInformation,
SystemRegistryQuotaInformation,
SystemExtendServiceTableInformation,
SystemPrioritySeperation,
SystemPlugPlayBusInformation,
SystemDockInformation,
SystemWhatTheFuckInformation,
SystemProcessorSpeedInformation,
SystemCurrentTimeZoneInformation,
SystemLookasideInformation
} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS;
typedef struct _SECTION_IMAGE_INFORMATION {
PVOID EntryPoint;
ULONG unknown[14];
} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION;
typedef struct _THREAD_BASIC_INFORMATION {
NTSTATUS ExitStatus;
PVOID TebBaseAddress;
CLIENT_ID ClientId;
ULONG AffinityMask;
ULONG Priority;
ULONG BasePriority;
} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
typedef struct _KSERVICE_TABLE_DESCRIPTOR {
LONG *Base;
ULONG *ServiceCounterTableBase;
ULONG NumberOfServices;
UCHAR *ParamTableBase;
} KSERVICE_TABLE_DESCRIPTOR, *PKSERVICE_TABLE_DESCRIPTOR;
typedef struct _MEMORY_BASIC_INFORMATION {
PVOID BaseAddress;
PVOID AllocationBase;
ULONG AllocationProtect;
SIZE_T RegionSize;
ULONG State;
ULONG Protect;
ULONG Type;
} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;
typedef enum _MEMORY_INFORMATION_CLASS {
MemoryBasicInformation
} MEMORY_INFORMATION_CLASS;
NTSYSAPI NTSTATUS NTAPI ZwQuerySection(
HANDLE SectionHandle, SECTION_INFORMATION_CLASS InformationClass,
PVOID InformationBuffer, SIZE_T InformationBufferSize,
PSIZE_T ResultLength
);
NTSYSAPI NTSTATUS NTAPI ZwQuerySystemInformation(
SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation,
SIZE_T SystemInformationLength, PSIZE_T ReturnLength
);
NTSYSAPI NTSTATUS NTAPI ZwQueryInformationProcess(
HANDLE ProcessHandle, PROCESSINFOCLASS ProcessInformationClass,
PVOID ProcessInformation, ULONG ProcessInformationLength,
PULONG ReturnLength
);
NTSYSAPI NTSTATUS NTAPI ZwQueryInformationThread(
HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass,
PVOID ThreadInformation, SIZE_T ThreadInformationLength,
PSIZE_T ReturnLength
);
NTSYSAPI NTSTATUS NTAPI ZwQueryVirtualMemory(
HANDLE ProcessHandle, PVOID BaseAddress,
MEMORY_INFORMATION_CLASS MemoryInformationClass, PVOID MemoryInformation,
SIZE_T MemoryInformationLength, PSIZE_T ReturnLength
);
typedef struct tagGETCLIPBDATA {
UINT uFmtRet;
BOOL fGlobalHandle;
union {
HANDLE hLocale;
HANDLE hPalette;
};
} GETCLIPBDATA, *PGETCLIPBDATA;
typedef struct tagSETCLIPBDATA {
BOOL fGlobalHandle;
BOOL fIncSerialNumber;
} SETCLIPBDATA, *PSETCLIPBDATA;
#include "pshpack4.h"
#define WOW64_SIZE_OF_80387_REGISTERS 80
#define WOW64_MAXIMUM_SUPPORTED_EXTENSION 512
typedef struct _WOW64_FLOATING_SAVE_AREA {
DWORD ControlWord;
DWORD StatusWord;
DWORD TagWord;
DWORD ErrorOffset;
DWORD ErrorSelector;
DWORD DataOffset;
DWORD DataSelector;
BYTE RegisterArea[WOW64_SIZE_OF_80387_REGISTERS];
DWORD Cr0NpxState;
} WOW64_FLOATING_SAVE_AREA;
typedef struct _WOW64_CONTEXT {
DWORD ContextFlags;
DWORD Dr0;
DWORD Dr1;
DWORD Dr2;
DWORD Dr3;
DWORD Dr6;
DWORD Dr7;
WOW64_FLOATING_SAVE_AREA FloatSave;
DWORD SegGs;
DWORD SegFs;
DWORD SegEs;
DWORD SegDs;
DWORD Edi;
DWORD Esi;
DWORD Ebx;
DWORD Edx;
DWORD Ecx;
DWORD Eax;
DWORD Ebp;
DWORD Eip;
DWORD SegCs; // MUST BE SANITIZED
DWORD EFlags; // MUST BE SANITIZED
DWORD Esp;
DWORD SegSs;
BYTE ExtendedRegisters[WOW64_MAXIMUM_SUPPORTED_EXTENSION];
} WOW64_CONTEXT;
typedef WOW64_CONTEXT *PWOW64_CONTEXT;
#include "poppack.h"
typedef struct _PEB_LDR_DATA {
ULONG Length;
BOOLEAN Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _LDR_MODULE {
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID BaseAddress;
PVOID EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
SHORT LoadCount;
SHORT TlsIndex;
LIST_ENTRY HashTableEntry;
ULONG TimeDateStamp;
} LDR_MODULE, *PLDR_MODULE;
typedef struct _PEB {
BOOLEAN InheritedAddressSpace;
BOOLEAN ReadImageFileExecOptions;
BOOLEAN BeingDebugged;
BOOLEAN Spare;
HANDLE Mutant;
PVOID ImageBaseAddress;
PPEB_LDR_DATA LoaderData;
PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
PVOID SubSystemData;
PVOID ProcessHeap;
PVOID FastPebLock;
void *FastPebLockRoutine;
void *FastPebUnlockRoutine;
ULONG EnvironmentUpdateCount;
PVOID KernelCallbackTable;
PVOID EventLogSection;
PVOID EventLog;
void *FreeList;
ULONG TlsExpansionCounter;
PVOID TlsBitmap;
ULONG TlsBitmapBits[0x2];
PVOID ReadOnlySharedMemoryBase;
PVOID ReadOnlySharedMemoryHeap;
PVOID ReadOnlyStaticServerData;
PVOID AnsiCodePageData;
PVOID OemCodePageData;
PVOID UnicodeCaseTableData;
ULONG NumberOfProcessors;
ULONG NtGlobalFlag;
BYTE Spare2[0x4];
LARGE_INTEGER CriticalSectionTimeout;
ULONG HeapSegmentReserve;
ULONG HeapSegmentCommit;
ULONG HeapDeCommitTotalFreeThreshold;
ULONG HeapDeCommitFreeBlockThreshold;
ULONG NumberOfHeaps;
ULONG MaximumNumberOfHeaps;
PVOID *ProcessHeaps;
PVOID GdiSharedHandleTable;
PVOID ProcessStarterHelper;
PVOID GdiDCAttributeList;
PVOID LoaderLock;
ULONG OSMajorVersion;
ULONG OSMinorVersion;
ULONG OSBuildNumber;
ULONG OSPlatformId;
ULONG ImageSubSystem;
ULONG ImageSubSystemMajorVersion;
ULONG ImageSubSystemMinorVersion;
ULONG GdiHandleBuffer[0x22];
ULONG PostProcessInitRoutine;
ULONG TlsExpansionBitmap;
BYTE TlsExpansionBitmapBits[0x80];
ULONG SessionId;
} PEB, *PPEB;
extern PDEVICE_OBJECT g_device_object;
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004
#define PROC_THREAD_ATTRIBUTE_NUMBER 0x0000FFFF
#define PROC_THREAD_ATTRIBUTE_THREAD 0x00010000 // Attribute may be used with thread creation
#define PROC_THREAD_ATTRIBUTE_INPUT 0x00020000 // Attribute is input only
#define PROC_THREAD_ATTRIBUTE_ADDITIVE 0x00040000 // Attribute may be "accumulated," e.g. bitmasks, counters, etc.
typedef enum _PROC_THREAD_ATTRIBUTE_NUM {
ProcThreadAttributeParentProcess = 0,
ProcThreadAttributeExtendedFlags,
ProcThreadAttributeHandleList,
ProcThreadAttributeGroupAffinity,
ProcThreadAttributePreferredNode,
ProcThreadAttributeIdealProcessor,
ProcThreadAttributeUmsThread,
ProcThreadAttributeMitigationPolicy,
ProcThreadAttributeMax
} PROC_THREAD_ATTRIBUTE_NUM;
#define ProcThreadAttributeValue(Number, Thread, Input, Additive) \
(((Number) & PROC_THREAD_ATTRIBUTE_NUMBER) | \
((Thread != FALSE) ? PROC_THREAD_ATTRIBUTE_THREAD : 0) | \
((Input != FALSE) ? PROC_THREAD_ATTRIBUTE_INPUT : 0) | \
((Additive != FALSE) ? PROC_THREAD_ATTRIBUTE_ADDITIVE : 0))
#define PROC_THREAD_ATTRIBUTE_PARENT_PROCESS \
ProcThreadAttributeValue (ProcThreadAttributeParentProcess, FALSE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS \
ProcThreadAttributeValue (ProcThreadAttributeExtendedFlags, FALSE, TRUE, TRUE)
#define PROC_THREAD_ATTRIBUTE_HANDLE_LIST \
ProcThreadAttributeValue (ProcThreadAttributeHandleList, FALSE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY \
ProcThreadAttributeValue (ProcThreadAttributeGroupAffinity, TRUE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_PREFERRED_NODE \
ProcThreadAttributeValue (ProcThreadAttributePreferredNode, FALSE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR \
ProcThreadAttributeValue (ProcThreadAttributeIdealProcessor, TRUE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_UMS_THREAD \
ProcThreadAttributeValue (ProcThreadAttributeUmsThread, TRUE, TRUE, FALSE)
#define PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY \
ProcThreadAttributeValue (ProcThreadAttributeMitigationPolicy, FALSE, TRUE, FALSE)
typedef HANDLE ALPC_HANDLE, *PALPC_HANDLE;
typedef struct _PORT_MESSAGE {
union {
struct {
CSHORT DataLength;
CSHORT TotalLength;
} s1;
ULONG Length;
} u1;
union {
struct {
CSHORT Type;
CSHORT DataInfoOffset;
} s2;
ULONG ZeroInit;
} u2;
union {
CLIENT_ID ClientId;
QUAD DoNotUseThisField;
};
ULONG MessageId;
union {
SIZE_T ClientViewSize;
ULONG CallbackId;
} u3;
} PORT_MESSAGE, *PPORT_MESSAGE;
typedef struct _ALPC_MESSAGE_ATTRIBUTES {
ULONG AllocatedAttributes;
ULONG ValidAttributes;
} ALPC_MESSAGE_ATTRIBUTES, *PALPC_MESSAGE_ATTRIBUTES;
typedef struct _ALPC_PORT_ATTRIBUTES {
ULONG Flags;
SECURITY_QUALITY_OF_SERVICE SecurityQos;
SIZE_T MaxMessageLength;
SIZE_T MemoryBandwidth;
SIZE_T MaxPoolUsage;
SIZE_T MaxSectionSize;
SIZE_T MaxViewSize;
SIZE_T MaxTotalSectionSize;
ULONG DupObjectTypes;
#ifdef _WIN64
ULONG Reserved;
#endif
} ALPC_PORT_ATTRIBUTES, *PALPC_PORT_ATTRIBUTES;
typedef enum _ALPC_MESSAGE_INFORMATION_CLASS {
AlpcMessageSidInformation, // q: out SID
AlpcMessageTokenModifiedIdInformation, // q: out LUID
AlpcMessageDirectStatusInformation,
AlpcMessageHandleInformation, // ALPC_MESSAGE_HANDLE_INFORMATION
MaxAlpcMessageInfoClass
} ALPC_MESSAGE_INFORMATION_CLASS, *PALPC_MESSAGE_INFORMATION_CLASS;
typedef enum _ALPC_PORT_INFORMATION_CLASS {
AlpcBasicInformation, // q: out ALPC_BASIC_INFORMATION
AlpcPortInformation, // s: in ALPC_PORT_ATTRIBUTES
AlpcAssociateCompletionPortInformation, // s: in ALPC_PORT_ASSOCIATE_COMPLETION_PORT
AlpcConnectedSIDInformation, // q: in SID
AlpcServerInformation, // q: inout ALPC_SERVER_INFORMATION
AlpcMessageZoneInformation, // s: in ALPC_PORT_MESSAGE_ZONE_INFORMATION
AlpcRegisterCompletionListInformation, // s: in ALPC_PORT_COMPLETION_LIST_INFORMATION
AlpcUnregisterCompletionListInformation, // s: VOID
AlpcAdjustCompletionListConcurrencyCountInformation, // s: in ULONG
AlpcRegisterCallbackInformation, // kernel-mode only
AlpcCompletionListRundownInformation, // s: VOID
AlpcWaitForPortReferences
} ALPC_PORT_INFORMATION_CLASS;
typedef struct _LPC_MESSAGE {
USHORT DataLength;
USHORT Length;
USHORT MessageType;
USHORT DataInfoOffset;
CLIENT_ID ClientId;
ULONG MessageId;
ULONG CallbackId;
} LPC_MESSAGE, *PLPC_MESSAGE;
typedef struct _LDR_DATA_TABLE_ENTRY
{
LIST_ENTRY InLoadOrderLinks;
LIST_ENTRY InMemoryOrderLinks;
LIST_ENTRY InInitializationOrderLinks;
PVOID DllBase;
PVOID EntryPoint;
DWORD SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
DWORD Flags;
USHORT LoadCount;
USHORT TlsIndex;
LIST_ENTRY HashLinks;
PVOID SectionPointer;
DWORD CheckSum;
DWORD TimeDateStamp;
PVOID LoadedImports;
PVOID EntryPointActivationContext;
PVOID PatchInformation;
}LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
#pragma warning( pop )<file_sep>/pe.h
#pragma once
#include "types.h"
const uint8_t *pe_export_addr(
const uint8_t *module, uintptr_t filesize, const char *funcname
);
const uint8_t *pe_section_bounds(
const uint8_t *module, uintptr_t *size, uint8_t *ptr
);
const uint8_t *pe_load_file(
const wchar_t * filepath
);
void fix_reloc_table(
const uint8_t * module, const uint8_t * ori_img_base
);
uint8_t * get_module_base(
const PDRIVER_OBJECT drv_obj, const wchar_t *name
);<file_sep>/utils.c
#include <ntifs.h>
#include <wdm.h>
#include "utils.h"
KIRQL unset_wp()
{
KIRQL Irql = KeRaiseIrqlToDpcLevel();
UINT_PTR cr0 = __readcr0();
cr0 &= ~0x10000;
__writecr0(cr0);
_disable();
return Irql;
}
VOID set_wp(KIRQL Irql)
{
UINT_PTR cr0 = __readcr0();
cr0 |= 0x10000;
_enable();
__writecr0(cr0);
KeLowerIrql(Irql);
}<file_sep>/types.h
#pragma once
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
<file_sep>/file.c
#include <ntddk.h>
#include "file.h"
typedef struct _AUX_ACCESS_DATA {
PPRIVILEGE_SET PrivilegesUsed;
GENERIC_MAPPING GenericMapping;
ACCESS_MASK AccessesToAudit;
ACCESS_MASK MaximumAuditMask;
ULONG Unknown[256];
} AUX_ACCESS_DATA, *PAUX_ACCESS_DATA;
typedef struct _QUERY_DIRECTORY {
ULONG Length;
PUNICODE_STRING FileName;
FILE_INFORMATION_CLASS FileInformationClass;
ULONG FileIndex;
} QUERY_DIRECTORY, *PQUERY_DIRECTORY;
NTSTATUS ObCreateObject(KPROCESSOR_MODE ProbeMode, POBJECT_TYPE ObjectType, POBJECT_ATTRIBUTES ObjectAttributes, KPROCESSOR_MODE OwnershipMode, PVOID ParseContext, ULONG ObjectBodySize, ULONG PagedPoolCharge, ULONG NonPagedPoolCharge, PVOID *Object);
NTSTATUS SeCreateAccessState(PACCESS_STATE AccessState, PVOID AuxData, ACCESS_MASK DesiredAccess, PGENERIC_MAPPING GenericMapping);
NTSTATUS IoCompletionRoutine(
IN PDEVICE_OBJECT device_object,
IN PIRP irp,
IN PVOID context
){
*irp->UserIosb = irp->IoStatus;
if(irp->UserEvent)
KeSetEvent(irp->UserEvent, IO_NO_INCREMENT, 0);
if(irp->MdlAddress){
IoFreeMdl(irp->MdlAddress);
irp->MdlAddress = NULL;
}
IoFreeIrp(irp);
return STATUS_MORE_PROCESSING_REQUIRED;
}
NTSTATUS IrpCreateFile(
IN PUNICODE_STRING FileName,
IN ACCESS_MASK DesiredAccess,
OUT PIO_STATUS_BLOCK io_status,
IN ULONG FileAttributes,
IN ULONG ShareAccess,
IN ULONG CreateDisposition,
IN ULONG CreateOptions,
IN PDEVICE_OBJECT DeviceObject,
IN PDEVICE_OBJECT RealDevice,
OUT PVOID *Object
){
NTSTATUS status;
KEVENT event;
PIRP irp;
PIO_STACK_LOCATION irp_sp;
IO_SECURITY_CONTEXT security_context;
ACCESS_STATE access_state;
OBJECT_ATTRIBUTES object_attributes;
PFILE_OBJECT file_object;
AUX_ACCESS_DATA aux_data;
RtlZeroMemory(&aux_data, sizeof(AUX_ACCESS_DATA));
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoAllocateIrp(DeviceObject->StackSize, FALSE);
if(irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
InitializeObjectAttributes(&object_attributes, NULL, OBJ_CASE_INSENSITIVE, 0, NULL);
status = ObCreateObject(KernelMode,
*IoFileObjectType,
&object_attributes,
KernelMode,
NULL,
sizeof(FILE_OBJECT),
0,
0,
(PVOID *)&file_object);
if(!NT_SUCCESS(status)){
IoFreeIrp(irp);
return status;
}
RtlZeroMemory(file_object, sizeof(FILE_OBJECT));
file_object->Size = sizeof(FILE_OBJECT);
file_object->Type = IO_TYPE_FILE;
file_object->DeviceObject = RealDevice;
if(CreateOptions & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)){
file_object->Flags = FO_SYNCHRONOUS_IO;
if(CreateOptions & FILE_SYNCHRONOUS_IO_ALERT)
file_object->Flags |= FO_ALERTABLE_IO;
}
if(CreateOptions & FILE_NO_INTERMEDIATE_BUFFERING)
file_object->Flags |= FO_NO_INTERMEDIATE_BUFFERING;
file_object->FileName.MaximumLength = FileName->MaximumLength;
file_object->FileName.Buffer = ExAllocatePool(NonPagedPool, FileName->MaximumLength);
if (file_object->FileName.Buffer == NULL){
IoFreeIrp(irp);
ObDereferenceObject(file_object);
return STATUS_INSUFFICIENT_RESOURCES;
}
RtlCopyUnicodeString(&file_object->FileName, FileName);
KeInitializeEvent(&file_object->Lock, SynchronizationEvent, FALSE);
KeInitializeEvent(&file_object->Event, NotificationEvent, FALSE);
irp->MdlAddress = NULL;
irp->Flags |= IRP_CREATE_OPERATION | IRP_SYNCHRONOUS_API;
irp->RequestorMode = KernelMode;
irp->UserIosb = io_status;
irp->UserEvent = &event;
irp->PendingReturned = FALSE;
irp->Cancel = FALSE;
irp->CancelRoutine = NULL;
irp->Tail.Overlay.Thread = (PETHREAD)KeGetCurrentThread();
irp->Tail.Overlay.AuxiliaryBuffer = NULL;
irp->Tail.Overlay.OriginalFileObject = file_object;
status = SeCreateAccessState(&access_state,
&aux_data,
DesiredAccess,
IoGetFileObjectGenericMapping());
if(!NT_SUCCESS(status)){
IoFreeIrp(irp);
ExFreePool(file_object->FileName.Buffer);
ObDereferenceObject(file_object);
return status;
}
security_context.SecurityQos = NULL;
security_context.AccessState = &access_state;
security_context.DesiredAccess = DesiredAccess;
security_context.FullCreateOptions = 0;
irp_sp= IoGetNextIrpStackLocation(irp);
irp_sp->MajorFunction = IRP_MJ_CREATE;
irp_sp->DeviceObject = DeviceObject;
irp_sp->FileObject =file_object;
irp_sp->Parameters.Create.SecurityContext = &security_context;
irp_sp->Parameters.Create.Options = (CreateDisposition << 24) | CreateOptions;
irp_sp->Parameters.Create.FileAttributes = (USHORT)FileAttributes;
irp_sp->Parameters.Create.ShareAccess = (USHORT)ShareAccess;
irp_sp->Parameters.Create.EaLength = 0;
IoSetCompletionRoutine(irp, IoCompletionRoutine, NULL, TRUE, TRUE, TRUE);
status = IoCallDriver(DeviceObject, irp);
if (status == STATUS_PENDING)
KeWaitForSingleObject(&event, Executive, KernelMode, TRUE, NULL);
status = io_status->Status;
if (!NT_SUCCESS(status)){
ExFreePool(file_object->FileName.Buffer);
file_object->FileName.Length = 0;
file_object->DeviceObject = NULL;
ObDereferenceObject(file_object);
}else{
InterlockedIncrement(&file_object->DeviceObject->ReferenceCount);
if (file_object->Vpb)
InterlockedIncrement(&file_object->Vpb->ReferenceCount);
*Object = file_object;
}
return status;
}
NTSTATUS IrpCloseFile(
IN PDEVICE_OBJECT DeviceObject,
IN PFILE_OBJECT FileObject
){
NTSTATUS status;
KEVENT event;
PIRP irp;
PVPB vpb;
IO_STATUS_BLOCK ioStatusBlock;
PIO_STACK_LOCATION irpSp;
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoAllocateIrp(DeviceObject->StackSize, FALSE);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
irp->Tail.Overlay.OriginalFileObject = FileObject;
irp->Tail.Overlay.Thread = PsGetCurrentThread();
irp->RequestorMode = KernelMode;
irp->UserEvent = &event;
irp->UserIosb = &irp->IoStatus;
irp->Overlay.AsynchronousParameters.UserApcRoutine = (PIO_APC_ROUTINE)NULL;
irp->Flags = IRP_SYNCHRONOUS_API | IRP_CLOSE_OPERATION;
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_CLEANUP;
irpSp->FileObject = FileObject;
status = IoCallDriver(DeviceObject, irp);
if (status == STATUS_PENDING)
KeWaitForSingleObject(&event,UserRequest,KernelMode,FALSE,NULL);
IoReuseIrp(irp , STATUS_SUCCESS);
KeClearEvent(&event);
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_CLOSE;
irpSp->FileObject = FileObject;
irp->UserIosb = &ioStatusBlock;
irp->UserEvent = &event;
irp->Tail.Overlay.OriginalFileObject = FileObject;
irp->Tail.Overlay.Thread = PsGetCurrentThread();
irp->AssociatedIrp.SystemBuffer = (PVOID)NULL;
irp->Flags = IRP_CLOSE_OPERATION | IRP_SYNCHRONOUS_API;
vpb = FileObject->Vpb;
if (vpb && !(FileObject->Flags & FO_DIRECT_DEVICE_OPEN)){
InterlockedDecrement(&vpb->ReferenceCount);
FileObject->Flags |= FO_FILE_OPEN_CANCELLED;
}
status = IoCallDriver(DeviceObject, irp);
if (status == STATUS_PENDING)
KeWaitForSingleObject(&event,UserRequest,KernelMode,FALSE,NULL);
IoFreeIrp(irp);
return status;
}
NTSTATUS IrpReadFile(
IN PFILE_OBJECT FileObject,
IN PLARGE_INTEGER ByteOffset OPTIONAL,
IN ULONG Length,
OUT PVOID Buffer,
OUT PIO_STATUS_BLOCK IoStatusBlock
){
NTSTATUS status;
KEVENT event;
PIRP irp;
PIO_STACK_LOCATION irpSp;
PDEVICE_OBJECT deviceObject;
if (ByteOffset == NULL){
if (!(FileObject->Flags & FO_SYNCHRONOUS_IO))
return STATUS_INVALID_PARAMETER;
ByteOffset = &FileObject->CurrentByteOffset;
}
if (FileObject->Vpb == 0 || FileObject->Vpb->RealDevice == NULL)
return STATUS_UNSUCCESSFUL;
deviceObject = FileObject->Vpb->DeviceObject;
irp = IoAllocateIrp(deviceObject->StackSize, FALSE);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
irp->MdlAddress = IoAllocateMdl(Buffer, Length, FALSE, TRUE, NULL);
if (irp->MdlAddress == NULL){
IoFreeIrp(irp);
return STATUS_INSUFFICIENT_RESOURCES;
}
MmBuildMdlForNonPagedPool(irp->MdlAddress);
irp->Flags = IRP_READ_OPERATION;
irp->RequestorMode = KernelMode;
irp->UserIosb = IoStatusBlock;
irp->UserEvent = &event;
irp->Tail.Overlay.Thread = (PETHREAD)KeGetCurrentThread();
irp->Tail.Overlay.OriginalFileObject = FileObject;
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_READ;
irpSp->MinorFunction = IRP_MN_NORMAL;
irpSp->DeviceObject = deviceObject;
irpSp->FileObject = FileObject;
irpSp->Parameters.Read.Length = Length;
irpSp->Parameters.Read.ByteOffset = *ByteOffset;
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
IoSetCompletionRoutine(irp, IoCompletionRoutine, NULL, TRUE, TRUE, TRUE);
status = IoCallDriver(deviceObject, irp);
if (status == STATUS_PENDING)
status = KeWaitForSingleObject(&event, Executive, KernelMode, TRUE, NULL);
return status;
}
NTSTATUS IrpFileWrite(
IN PFILE_OBJECT FileObject,
IN PLARGE_INTEGER ByteOffset OPTIONAL,
IN ULONG Length,
IN PVOID Buffer,
OUT PIO_STATUS_BLOCK IoStatusBlock
){
NTSTATUS status;
KEVENT event;
PIRP irp;
PIO_STACK_LOCATION irpSp;
PDEVICE_OBJECT deviceObject;
if (ByteOffset == NULL)
{
if (!(FileObject->Flags & FO_SYNCHRONOUS_IO))
return STATUS_INVALID_PARAMETER;
ByteOffset = &FileObject->CurrentByteOffset;
}
if (FileObject->Vpb == 0 || FileObject->Vpb->RealDevice == NULL)
return STATUS_UNSUCCESSFUL;
deviceObject = FileObject->Vpb->DeviceObject;
irp = IoAllocateIrp(deviceObject->StackSize, FALSE);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
irp->MdlAddress = IoAllocateMdl(Buffer, Length, FALSE, TRUE, NULL);
if (irp->MdlAddress == NULL)
{
IoFreeIrp(irp);
return STATUS_INSUFFICIENT_RESOURCES;
}
MmBuildMdlForNonPagedPool(irp->MdlAddress);
irp->Flags = IRP_WRITE_OPERATION;
irp->RequestorMode = KernelMode;
irp->UserIosb = IoStatusBlock;
irp->UserEvent = &event;
irp->Tail.Overlay.Thread = (PETHREAD)KeGetCurrentThread();
irp->Tail.Overlay.OriginalFileObject = FileObject;
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_WRITE;
irpSp->MinorFunction = IRP_MN_NORMAL;
irpSp->DeviceObject = deviceObject;
irpSp->FileObject = FileObject;
irpSp->Parameters.Write.Length = Length;
irpSp->Parameters.Write.ByteOffset = *ByteOffset;
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
IoSetCompletionRoutine(irp, IoCompletionRoutine, NULL, TRUE, TRUE, TRUE);
status = IoCallDriver(deviceObject, irp);
if (status == STATUS_PENDING)
status = KeWaitForSingleObject(&event, Executive, KernelMode, TRUE, NULL);
return status;
}
NTSTATUS IrpFileQuery(
IN PFILE_OBJECT FileObject,
OUT PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass
){
NTSTATUS status;
KEVENT event;
PIRP irp;
IO_STATUS_BLOCK ioStatus;
PIO_STACK_LOCATION irpSp;
PDEVICE_OBJECT deviceObject;
if (FileObject->Vpb == 0 || FileObject->Vpb->RealDevice == NULL)
return STATUS_UNSUCCESSFUL;
deviceObject = FileObject->Vpb->DeviceObject;
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoAllocateIrp(deviceObject->StackSize, FALSE);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
irp->Flags = IRP_BUFFERED_IO;
irp->AssociatedIrp.SystemBuffer = FileInformation;
irp->RequestorMode = KernelMode;
irp->Overlay.AsynchronousParameters.UserApcRoutine = (PIO_APC_ROUTINE)NULL;
irp->UserEvent = &event;
irp->UserIosb = &ioStatus;
irp->Tail.Overlay.Thread = (PETHREAD)KeGetCurrentThread();
irp->Tail.Overlay.OriginalFileObject = FileObject;
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_QUERY_INFORMATION;
irpSp->DeviceObject = deviceObject;
irpSp->FileObject = FileObject;
irpSp->Parameters.QueryFile.Length = Length;
irpSp->Parameters.QueryFile.FileInformationClass = FileInformationClass;
IoSetCompletionRoutine(irp, IoCompletionRoutine, NULL, TRUE, TRUE, TRUE);
status = IoCallDriver(deviceObject, irp);
if (status == STATUS_PENDING)
KeWaitForSingleObject(&event, Executive, KernelMode, TRUE, NULL);
return ioStatus.Status;
}
NTSTATUS IrpDirectoryQuery(
IN PFILE_OBJECT FileObject,
IN FILE_INFORMATION_CLASS FileInformationClass,
OUT PVOID Buffer,
IN ULONG Length
){
NTSTATUS status;
KEVENT event;
PIRP irp;
IO_STATUS_BLOCK ioStatus;
PIO_STACK_LOCATION irpSp;
PDEVICE_OBJECT deviceObject;
PQUERY_DIRECTORY queryDirectory;
if (FileObject->Vpb == 0 || FileObject->Vpb->RealDevice == NULL)
return STATUS_UNSUCCESSFUL;
deviceObject = FileObject->Vpb->DeviceObject;
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoAllocateIrp(deviceObject->StackSize, FALSE);
if (irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
irp->Flags = IRP_INPUT_OPERATION | IRP_BUFFERED_IO;
irp->RequestorMode = KernelMode;
irp->UserEvent = &event;
irp->UserIosb = &ioStatus;
irp->UserBuffer = Buffer;
irp->Tail.Overlay.Thread = (PETHREAD)KeGetCurrentThread();
irp->Tail.Overlay.OriginalFileObject = FileObject;
irp->Overlay.AsynchronousParameters.UserApcRoutine = (PIO_APC_ROUTINE)NULL;
//irp->Pointer = FileObject;
irpSp = IoGetNextIrpStackLocation(irp);
irpSp->MajorFunction = IRP_MJ_DIRECTORY_CONTROL;
irpSp->MinorFunction = IRP_MN_QUERY_DIRECTORY;
irpSp->DeviceObject = deviceObject;
irpSp->FileObject = FileObject;
queryDirectory = (PQUERY_DIRECTORY)&irpSp->Parameters;
queryDirectory->Length = Length;
queryDirectory->FileName = NULL;
queryDirectory->FileInformationClass = FileInformationClass;
queryDirectory->FileIndex = 0;
IoSetCompletionRoutine(irp, IoCompletionRoutine, NULL, TRUE, TRUE, TRUE);
status = IoCallDriver(deviceObject, irp);
if (status == STATUS_PENDING)
{
KeWaitForSingleObject(&event, Executive, KernelMode, TRUE, NULL);
status = ioStatus.Status;
}
return status;
}
NTSTATUS
IrpSetInformationFile(
IN PFILE_OBJECT FileObject,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN PVOID FileInformation,
IN ULONG Length,
IN FILE_INFORMATION_CLASS FileInformationClass,
IN BOOLEAN ReplaceIfExists)
{
NTSTATUS ntStatus;
PIRP Irp;
KEVENT kEvent;
PIO_STACK_LOCATION IrpSp;
if (FileObject->Vpb == 0 || FileObject->Vpb->DeviceObject == NULL)
return STATUS_UNSUCCESSFUL;
Irp = IoAllocateIrp(FileObject->Vpb->DeviceObject->StackSize, FALSE);
if(Irp == NULL)
return STATUS_INSUFFICIENT_RESOURCES;
KeInitializeEvent(&kEvent, SynchronizationEvent, FALSE);
Irp->AssociatedIrp.SystemBuffer = FileInformation;
Irp->UserEvent = &kEvent;
Irp->UserIosb = IoStatusBlock;
Irp->RequestorMode = KernelMode;
Irp->Tail.Overlay.Thread = PsGetCurrentThread();
Irp->Tail.Overlay.OriginalFileObject = FileObject;
IrpSp = IoGetNextIrpStackLocation(Irp);
IrpSp->MajorFunction = IRP_MJ_SET_INFORMATION;
IrpSp->DeviceObject = FileObject->Vpb->DeviceObject;
IrpSp->FileObject = FileObject;
IrpSp->Parameters.SetFile.ReplaceIfExists = ReplaceIfExists;
IrpSp->Parameters.SetFile.FileObject = FileObject;
IrpSp->Parameters.SetFile.AdvanceOnly = FALSE;
IrpSp->Parameters.SetFile.Length = Length;
IrpSp->Parameters.SetFile.FileInformationClass = FileInformationClass;
IoSetCompletionRoutine(Irp, IoCompletionRoutine, 0, TRUE, TRUE, TRUE);
ntStatus = IoCallDriver(FileObject->Vpb->DeviceObject, Irp);
if (ntStatus == STATUS_PENDING)
KeWaitForSingleObject(&kEvent, Executive, KernelMode, TRUE, 0);
return IoStatusBlock->Status;
}
BOOLEAN GetDriveObject(
IN ULONG DriveNumber,
OUT PDEVICE_OBJECT *DeviceObject,
OUT PDEVICE_OBJECT *ReadDevice
){
WCHAR driveName[] = L"//DosDevices//A://";
UNICODE_STRING deviceName;
HANDLE deviceHandle;
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK ioStatus;
PFILE_OBJECT fileObject;
NTSTATUS status;
if (DriveNumber >= 'A' && DriveNumber <= 'Z')
{
driveName[12] = (CHAR)DriveNumber;
}
else if (DriveNumber >= 'a' && DriveNumber <= 'z')
{
driveName[12] = (CHAR)DriveNumber - 'a' + 'A';
}
else
{
return FALSE;
}
RtlInitUnicodeString(&deviceName, driveName);
InitializeObjectAttributes(&objectAttributes,
&deviceName,
OBJ_CASE_INSENSITIVE,
NULL,
NULL);
status = IoCreateFile(&deviceHandle,
SYNCHRONIZE | FILE_ANY_ACCESS,
&objectAttributes,
&ioStatus,
NULL,
0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_DIRECTORY_FILE,
NULL,
0,
CreateFileTypeNone,
NULL,
0x100);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not open drive %c: %x/n", DriveNumber, status);
return FALSE;
}
status = ObReferenceObjectByHandle(deviceHandle,
FILE_READ_DATA,
*IoFileObjectType,
KernelMode,
&fileObject,
NULL);
if (!NT_SUCCESS(status))
{
DbgPrint("Could not get fileobject from handle: %c/n", DriveNumber);
ZwClose(deviceHandle);
return FALSE;
}
if (fileObject->Vpb == 0 || fileObject->Vpb->RealDevice == NULL)
{
ObDereferenceObject(fileObject);
ZwClose(deviceHandle);
return FALSE;
}
*DeviceObject = fileObject->Vpb->DeviceObject;
*ReadDevice = fileObject->Vpb->RealDevice;
ObDereferenceObject(fileObject);
ZwClose(deviceHandle);
return TRUE;
}
NTSTATUS ForceDeleteFile(UNICODE_STRING ustrFileName)
{
NTSTATUS status = STATUS_SUCCESS;
PFILE_OBJECT pFileObject = NULL;
IO_STATUS_BLOCK iosb = { 0 };
FILE_BASIC_INFORMATION fileBaseInfo = { 0 };
FILE_DISPOSITION_INFORMATION fileDispositionInfo = { 0 };
PVOID pImageSectionObject = NULL;
PVOID pDataSectionObject = NULL;
PVOID pSharedCacheMap = NULL;
status = IrpCreateFile(&ustrFileName, GENERIC_READ | GENERIC_WRITE,
&iosb, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0, &pFileObject);
if (!NT_SUCCESS(status))
{
DbgPrint("IrpCreateFile Error[0x%X]\n", status);
return FALSE;
}
RtlZeroMemory(&fileBaseInfo, sizeof(fileBaseInfo));
fileBaseInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
status = IrpSetInformationFile(pFileObject, &iosb, &fileBaseInfo, sizeof(fileBaseInfo), FileBasicInformation, FALSE);
if (!NT_SUCCESS(status))
{
DbgPrint("IrpSetInformationFile[SetInformation] Error[0x%X]\n", status);
return status;
}
if (pFileObject->SectionObjectPointer)
{
pImageSectionObject = pFileObject->SectionObjectPointer->ImageSectionObject;
pDataSectionObject = pFileObject->SectionObjectPointer->DataSectionObject;
pSharedCacheMap = pFileObject->SectionObjectPointer->SharedCacheMap;
pFileObject->SectionObjectPointer->ImageSectionObject = NULL;
pFileObject->SectionObjectPointer->DataSectionObject = NULL;
pFileObject->SectionObjectPointer->SharedCacheMap = NULL;
}
RtlZeroMemory(&fileDispositionInfo, sizeof(fileDispositionInfo));
fileDispositionInfo.DeleteFile = TRUE;
status = IrpSetInformationFile(pFileObject, &iosb, &fileDispositionInfo, sizeof(fileDispositionInfo), FileDispositionInformation, FALSE);
if (!NT_SUCCESS(status))
{
DbgPrint("IrpSetInformationFile[DeleteFile] Error[0x%X]\n", status);
return status;
}
if (pFileObject->SectionObjectPointer)
{
pFileObject->SectionObjectPointer->ImageSectionObject = pImageSectionObject;
pFileObject->SectionObjectPointer->DataSectionObject = pDataSectionObject;
pFileObject->SectionObjectPointer->SharedCacheMap = pSharedCacheMap;
}
ObDereferenceObject(pFileObject);
return status;
}<file_sep>/file.h
#pragma once
NTSTATUS ForceDeleteFile(UNICODE_STRING ustrFileName);<file_sep>/pe.c
#include <fltkernel.h>
#include <ntimage.h>
#include "struct.h"
#include "pe.h"
static const uint8_t *rva_to_ptr(
IMAGE_NT_HEADERS *image_nt_headers, uintptr_t rva,
const uint8_t *module, uintptr_t filesize
) {
IMAGE_SECTION_HEADER *image_section_header =
IMAGE_FIRST_SECTION(image_nt_headers);
uint32_t idx, section_count =
image_nt_headers->FileHeader.NumberOfSections;
for (idx = 0; idx < section_count; idx++, image_section_header++) {
uintptr_t va = image_section_header->VirtualAddress;
if (rva >= va && rva < va + image_section_header->Misc.VirtualSize) {
rva += image_section_header->PointerToRawData - va;
return rva < filesize ? module + rva : NULL;
}
}
return NULL;
}
static int32_t rva_to_section(
IMAGE_NT_HEADERS *image_nt_headers, uintptr_t rva
) {
IMAGE_SECTION_HEADER *image_section_header =
IMAGE_FIRST_SECTION(image_nt_headers);
uint32_t idx, section_count =
image_nt_headers->FileHeader.NumberOfSections;
for (idx = 0; idx < section_count; idx++, image_section_header++) {
uintptr_t va = image_section_header->VirtualAddress;
if (rva >= va && rva < va + image_section_header->Misc.VirtualSize) {
return idx;
}
}
return -1;
}
const uint8_t *pe_export_addr(
const uint8_t *module, uintptr_t filesize, const char *funcname
) {
IMAGE_DOS_HEADER *image_dos_header; IMAGE_NT_HEADERS *image_nt_headers;
IMAGE_DATA_DIRECTORY *image_data_directory;
IMAGE_EXPORT_DIRECTORY *image_export_directory;
uintptr_t export_rva, export_size; uint16_t *addr_ordinals;
uint32_t *addr_functions, *addr_names, idx, func_rva;
const char *name;
image_dos_header = (IMAGE_DOS_HEADER *)module;
if (image_dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
return NULL;
}
image_nt_headers =
(IMAGE_NT_HEADERS *)(module + image_dos_header->e_lfanew);
if (image_nt_headers->Signature != IMAGE_NT_SIGNATURE) {
return NULL;
}
image_data_directory = image_nt_headers->OptionalHeader.DataDirectory;
export_rva =
image_data_directory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
export_size =
image_data_directory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
image_export_directory = (IMAGE_EXPORT_DIRECTORY *)
rva_to_ptr(image_nt_headers, export_rva, module, filesize);
if (image_export_directory == NULL) {
return NULL;
}
addr_functions = (uint32_t *)rva_to_ptr(
image_nt_headers, image_export_directory->AddressOfFunctions,
module, filesize
);
addr_ordinals = (uint16_t *)rva_to_ptr(
image_nt_headers, image_export_directory->AddressOfNameOrdinals,
module, filesize
);
addr_names = (uint32_t *)rva_to_ptr(
image_nt_headers, image_export_directory->AddressOfNames,
module, filesize
);
if (addr_functions == NULL || addr_ordinals == NULL || addr_names == NULL) {
return NULL;
}
for (idx = 0; idx < image_export_directory->NumberOfNames; idx++) {
name = (const char *)rva_to_ptr(
image_nt_headers, addr_names[idx], module, filesize
);
if (name == NULL) {
continue;
}
// Ignore forwarded exports.
func_rva = addr_functions[addr_ordinals[idx]];
if (func_rva >= export_rva && func_rva < export_rva + export_size) {
continue;
}
if (strcmp(name, funcname) == 0) {
return rva_to_ptr(image_nt_headers, func_rva, module, filesize);
}
}
return NULL;
}
const uint8_t *pe_section_bounds(
const uint8_t *module, uintptr_t *size, uint8_t *ptr
) {
IMAGE_DOS_HEADER *image_dos_header; IMAGE_NT_HEADERS *image_nt_headers;
IMAGE_SECTION_HEADER *image_section_header; int32_t section;
if (ptr < module) {
return NULL;
}
image_dos_header = (IMAGE_DOS_HEADER *)module;
if (image_dos_header->e_magic != IMAGE_DOS_SIGNATURE) {
return NULL;
}
image_nt_headers = (IMAGE_NT_HEADERS *)(
(uint8_t *)module + image_dos_header->e_lfanew
);
if (image_nt_headers->Signature != IMAGE_NT_SIGNATURE) {
return NULL;
}
section = rva_to_section(image_nt_headers, ptr - module);
if (section < 0) {
return NULL;
}
image_section_header = IMAGE_FIRST_SECTION(image_nt_headers);
*size = image_section_header[section].SizeOfRawData;
return module + image_section_header[section].VirtualAddress;
}
uint8_t * get_module_base(
const PDRIVER_OBJECT drv_obj, const wchar_t *name
) {
PLDR_DATA_TABLE_ENTRY data_table_entry_ptr, tmp_data_table_entry_ptr;
PLIST_ENTRY plist;
UNICODE_STRING module_name;
RtlInitUnicodeString(&module_name, name);
data_table_entry_ptr = (LDR_DATA_TABLE_ENTRY*)drv_obj->DriverSection;
if (data_table_entry_ptr == NULL)
return NULL;
plist = data_table_entry_ptr->InLoadOrderLinks.Flink;
while (plist != &data_table_entry_ptr->InLoadOrderLinks) {
tmp_data_table_entry_ptr = (LDR_DATA_TABLE_ENTRY *)plist;
if (0 == RtlCompareUnicodeString(&tmp_data_table_entry_ptr->BaseDllName, &module_name, FALSE))
return tmp_data_table_entry_ptr->DllBase;
plist = plist->Flink;
}
return NULL;
}
void fix_reloc_table(
const uint8_t * new_module, const uint8_t * old_module
) {
PIMAGE_DOS_HEADER img_dos_header_ptr;
PIMAGE_NT_HEADERS img_nt_header_ptr;
IMAGE_DATA_DIRECTORY img_data_entry;
PIMAGE_BASE_RELOCATION img_base_relocation_ptr;
PUSHORT type_offset_ptr;
uintptr_t img_base;
ULONG reloc_table_size;
ULONG index, type, *reloc_addr;
img_dos_header_ptr = (PIMAGE_DOS_HEADER)new_module;
img_nt_header_ptr = (PIMAGE_NT_HEADERS)(new_module + img_dos_header_ptr->e_lfanew);
img_base = img_nt_header_ptr->OptionalHeader.ImageBase;
img_data_entry = img_nt_header_ptr->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
img_base_relocation_ptr = (PIMAGE_BASE_RELOCATION)(new_module + img_data_entry.VirtualAddress);
if (img_base_relocation_ptr == NULL) {
return;
}
while (img_base_relocation_ptr->SizeOfBlock) {
reloc_table_size = (img_base_relocation_ptr->SizeOfBlock - 8) / 2;
type_offset_ptr = (PUSHORT)((uintptr_t)img_base_relocation_ptr + sizeof(IMAGE_BASE_RELOCATION));
for (index = 0; index < reloc_table_size; index++) {
type = type_offset_ptr[index] >> 12;
if (type == IMAGE_REL_BASED_HIGHLOW) {
reloc_addr = (ULONG*)((uintptr_t)(type_offset_ptr[index] & 0x0FFF) + img_base_relocation_ptr->VirtualAddress + new_module);
if (!MmIsAddressValid(reloc_addr)) continue;
*reloc_addr += (ULONG)((uintptr_t)old_module - img_base);
}
}
img_base_relocation_ptr = (PIMAGE_BASE_RELOCATION)((uintptr_t)img_base_relocation_ptr + img_base_relocation_ptr->SizeOfBlock);
}
}
const uint8_t *pe_load_file(
const wchar_t * filepath
) {
NTSTATUS status;
UNICODE_STRING file_path;
HANDLE handle;
OBJECT_ATTRIBUTES obj_attrs;
IO_STATUS_BLOCK io_status_block;
LARGE_INTEGER file_offset;
ULONG index;
ULONG section_va, section_size;
IMAGE_DOS_HEADER img_dos_header;
IMAGE_NT_HEADERS img_nt_header;
PIMAGE_SECTION_HEADER img_section_header_ptr;
PVOID module;
InitializeObjectAttributes(&obj_attrs, &file_path, OBJ_CASE_INSENSITIVE, NULL, NULL);
RtlInitUnicodeString(&file_path, filepath);
status = ZwCreateFile(&handle, FILE_ALL_ACCESS, &obj_attrs, &io_status_block, 0,
FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE, NULL, 0);
if (!NT_SUCCESS(status)) {
return NULL;
}
file_offset.QuadPart = 0;
status = ZwReadFile(handle, NULL, NULL, NULL, &io_status_block, &img_dos_header, sizeof(IMAGE_DOS_HEADER), &file_offset, NULL);
if (!NT_SUCCESS(status)) {
ZwClose(handle);
return NULL;
}
file_offset.QuadPart = img_dos_header.e_lfanew;
status = ZwReadFile(handle, NULL, NULL, NULL, &io_status_block, &img_nt_header, sizeof(IMAGE_NT_HEADERS), &file_offset, NULL);
if (!NT_SUCCESS(status)) {
ZwClose(handle);
return NULL;
}
img_section_header_ptr = (PIMAGE_SECTION_HEADER)ExAllocatePoolWithTag(NonPagedPool, sizeof(IMAGE_SECTION_HEADER) * img_nt_header.FileHeader.NumberOfSections, 'epaw');
if (img_section_header_ptr == NULL) {
ZwClose(handle);
return NULL;
}
file_offset.QuadPart += sizeof(IMAGE_NT_HEADERS);
status = ZwReadFile(handle, NULL, NULL, NULL, &io_status_block, img_section_header_ptr, sizeof(IMAGE_SECTION_HEADER) * img_nt_header.FileHeader.NumberOfSections, &file_offset, NULL);
if (!NT_SUCCESS(status)) {
ExFreePoolWithTag(img_section_header_ptr, 'epaw');
ZwClose(handle);
return NULL;
}
module = ExAllocatePoolWithTag(NonPagedPool, img_nt_header.OptionalHeader.SizeOfImage, 'epaw');
if (module == NULL) {
ExFreePoolWithTag(img_section_header_ptr, 'epaw');
ZwClose(handle);
return NULL;
}
memset(module, 0, img_nt_header.OptionalHeader.SizeOfImage);
RtlCopyMemory(module, &img_dos_header, sizeof(IMAGE_DOS_HEADER));
RtlCopyMemory(module, &img_nt_header, sizeof(IMAGE_NT_HEADERS));
RtlCopyMemory(module, img_section_header_ptr, sizeof(IMAGE_SECTION_HEADER) * img_nt_header.FileHeader.NumberOfSections);
for (index = 0; index < img_nt_header.FileHeader.NumberOfSections; index++) {
section_va = img_section_header_ptr[index].VirtualAddress;
section_size = max(img_section_header_ptr[index].Misc.VirtualSize, img_section_header_ptr[index].SizeOfRawData);
file_offset.QuadPart = img_section_header_ptr[index].PointerToRawData;
status = ZwReadFile(handle, NULL, NULL, NULL, &io_status_block, (PVOID)((uintptr_t)module + section_va), section_size, &file_offset, NULL);
if (!NT_SUCCESS(status)) {
ExFreePoolWithTag(img_section_header_ptr, 'epaw');
ExFreePoolWithTag(module, 'epaw');
ZwClose(handle);
return NULL;
}
}
ExFreePoolWithTag(img_section_header_ptr, 'epaw');
ZwClose(handle);
return module;
} | 79a85ada636893dad81cc2bf420cdebf77ee8813 | [
"C"
] | 9 | C | fcccode/bkdrv | dc980fe8f76ccdd38b64affb9c49c68aa1e997d6 | 133ea01ec6681ce2ef3dd086d5aa1f3a98e7b414 | |
refs/heads/main | <repo_name>blocks-dao/blocks-xdai-module<file_sep>/readme.md
# BLOCKS xDAI Module
This application interacts with the xDAI OmbiBridge to port BLOCKS between networks. You can migrate BLOCKS from ETH to xDAI and back again.
# Use Cases for BLOCKS on xDAI
- Fast and extremely low-cost BLOCKS transactions for P2P
- BLOCKS compatibility with DeFi applications on xDAI
## Project Notes:
- Project interacts with Ethereum mainnet and xDAI mainnet
- Metamask is used as the provider to sign transactions
- Bridging back to ETH from xDAI requires a manual execution on the [ABM Live Monitoring Tool](https://docs.tokenbridge.net/about-tokenbridge/components/amb-live-monitoring-application)
## Live Demo
[BLOCKS Bridge Web App](https://blocks-bridge.web.app/home)
## Running Locally
The app is built with ReactJs and Ionic Framework
```
npm install -g @ionic/cli
```
[Install the Ionic CLI](https://ionicframework.com/docs/cli/)
Clone the repo and run:
```
npm install
```
Start the app using:
```
ionic serve
```
## Have Fun
Have fun moving BLOCKS between networks!
## License
Copyright © 2021 <BLOCKS DAO, LLC>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.<file_sep>/src/blocksDetails.ts
const blocksData = {
blocksAddress: "0x8a6d4c8735371ebaf8874fbd518b56edd66024eb",
blocksXdaiAddress: "0x1a4ea432e58bff38873af87bf68c525eb402aa1d",
ethToXdaiBridge: "0x88ad09518695c6c3712AC10a214bE5109a655671",
xDaiToEthBridge: "0xf6A78083ca3e2a662D6dd1703c939c8aCE2e268d",
blocksAbi: [
{
"inputs":[
{
"internalType":"string",
"name":"name",
"type":"string"
},
{
"internalType":"string",
"name":"symbol",
"type":"string"
},
{
"internalType":"address[]",
"name":"defaultOperators",
"type":"address[]"
},
{
"internalType":"uint256",
"name":"initialSupply",
"type":"uint256"
},
{
"internalType":"address",
"name":"treasury",
"type":"address"
}
],
"stateMutability":"nonpayable",
"type":"constructor"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"owner",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"spender",
"type":"address"
},
{
"indexed":false,
"internalType":"uint256",
"name":"value",
"type":"uint256"
}
],
"name":"Approval",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"tokenHolder",
"type":"address"
}
],
"name":"AuthorizedOperator",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"from",
"type":"address"
},
{
"indexed":false,
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"indexed":false,
"internalType":"bytes",
"name":"data",
"type":"bytes"
},
{
"indexed":false,
"internalType":"bytes",
"name":"operatorData",
"type":"bytes"
}
],
"name":"Burned",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"to",
"type":"address"
},
{
"indexed":false,
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"indexed":false,
"internalType":"bytes",
"name":"data",
"type":"bytes"
},
{
"indexed":false,
"internalType":"bytes",
"name":"operatorData",
"type":"bytes"
}
],
"name":"Minted",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"previousOwner",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"newOwner",
"type":"address"
}
],
"name":"OwnershipTransferred",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"tokenHolder",
"type":"address"
}
],
"name":"RevokedOperator",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"from",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"to",
"type":"address"
},
{
"indexed":false,
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"indexed":false,
"internalType":"bytes",
"name":"data",
"type":"bytes"
},
{
"indexed":false,
"internalType":"bytes",
"name":"operatorData",
"type":"bytes"
}
],
"name":"Sent",
"type":"event"
},
{
"anonymous":false,
"inputs":[
{
"indexed":true,
"internalType":"address",
"name":"from",
"type":"address"
},
{
"indexed":true,
"internalType":"address",
"name":"to",
"type":"address"
},
{
"indexed":false,
"internalType":"uint256",
"name":"value",
"type":"uint256"
}
],
"name":"Transfer",
"type":"event"
},
{
"inputs":[
{
"internalType":"address",
"name":"holder",
"type":"address"
},
{
"internalType":"address",
"name":"spender",
"type":"address"
}
],
"name":"allowance",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"spender",
"type":"address"
},
{
"internalType":"uint256",
"name":"value",
"type":"uint256"
}
],
"name":"approve",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"operator",
"type":"address"
}
],
"name":"authorizeOperator",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"tokenHolder",
"type":"address"
}
],
"name":"balanceOf",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"internalType":"bytes",
"name":"data",
"type":"bytes"
}
],
"name":"burn",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"decimals",
"outputs":[
{
"internalType":"uint8",
"name":"",
"type":"uint8"
}
],
"stateMutability":"pure",
"type":"function"
},
{
"inputs":[
],
"name":"defaultOperators",
"outputs":[
{
"internalType":"address[]",
"name":"",
"type":"address[]"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
],
"name":"granularity",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"operator",
"type":"address"
},
{
"internalType":"address",
"name":"tokenHolder",
"type":"address"
}
],
"name":"isOperatorFor",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
],
"name":"name",
"outputs":[
{
"internalType":"string",
"name":"",
"type":"string"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"account",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"internalType":"bytes",
"name":"data",
"type":"bytes"
},
{
"internalType":"bytes",
"name":"operatorData",
"type":"bytes"
}
],
"name":"operatorBurn",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"sender",
"type":"address"
},
{
"internalType":"address",
"name":"recipient",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"internalType":"bytes",
"name":"data",
"type":"bytes"
},
{
"internalType":"bytes",
"name":"operatorData",
"type":"bytes"
}
],
"name":"operatorSend",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"owner",
"outputs":[
{
"internalType":"address",
"name":"",
"type":"address"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address payable",
"name":"to",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
}
],
"name":"release",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"renounceOwnership",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"operator",
"type":"address"
}
],
"name":"revokeOperator",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"recipient",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
},
{
"internalType":"bytes",
"name":"data",
"type":"bytes"
}
],
"name":"send",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"symbol",
"outputs":[
{
"internalType":"string",
"name":"",
"type":"string"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
],
"name":"totalSupply",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"recipient",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
}
],
"name":"transfer",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"holder",
"type":"address"
},
{
"internalType":"address",
"name":"recipient",
"type":"address"
},
{
"internalType":"uint256",
"name":"amount",
"type":"uint256"
}
],
"name":"transferFrom",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"newOwner",
"type":"address"
}
],
"name":"transferOwnership",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
}
],
blocksOnXdaiAbi: [
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"mintingFinished",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"string",
"name":""
}
],
"name":"name",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"approve",
"inputs":[
{
"type":"address",
"name":"_spender"
},
{
"type":"uint256",
"name":"_value"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"setBridgeContract",
"inputs":[
{
"type":"address",
"name":"_bridgeContract"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint256",
"name":""
}
],
"name":"totalSupply",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"transferFrom",
"inputs":[
{
"type":"address",
"name":"_sender"
},
{
"type":"address",
"name":"_recipient"
},
{
"type":"uint256",
"name":"_amount"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"bytes32",
"name":""
}
],
"name":"PERMIT_TYPEHASH",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint8",
"name":""
}
],
"name":"decimals",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"bytes32",
"name":""
}
],
"name":"DOMAIN_SEPARATOR",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"increaseAllowance",
"inputs":[
{
"type":"address",
"name":"spender"
},
{
"type":"uint256",
"name":"addedValue"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"transferAndCall",
"inputs":[
{
"type":"address",
"name":"_to"
},
{
"type":"uint256",
"name":"_value"
},
{
"type":"bytes",
"name":"_data"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"mint",
"inputs":[
{
"type":"address",
"name":"_to"
},
{
"type":"uint256",
"name":"_amount"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"burn",
"inputs":[
{
"type":"uint256",
"name":"_value"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"string",
"name":""
}
],
"name":"version",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"decreaseApproval",
"inputs":[
{
"type":"address",
"name":"_spender"
},
{
"type":"uint256",
"name":"_subtractedValue"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"claimTokens",
"inputs":[
{
"type":"address",
"name":"_token"
},
{
"type":"address",
"name":"_to"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint256",
"name":""
}
],
"name":"balanceOf",
"inputs":[
{
"type":"address",
"name":"_owner"
}
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"renounceOwnership",
"inputs":[
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"isBridge",
"inputs":[
{
"type":"address",
"name":"_address"
}
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"finishMinting",
"inputs":[
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint256",
"name":""
}
],
"name":"nonces",
"inputs":[
{
"type":"address",
"name":""
}
],
"constant":true
},
{
"type":"function",
"stateMutability":"pure",
"payable":false,
"outputs":[
{
"type":"uint64",
"name":"major"
},
{
"type":"uint64",
"name":"minor"
},
{
"type":"uint64",
"name":"patch"
}
],
"name":"getTokenInterfacesVersion",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"address",
"name":""
}
],
"name":"owner",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"permit",
"inputs":[
{
"type":"address",
"name":"_holder"
},
{
"type":"address",
"name":"_spender"
},
{
"type":"uint256",
"name":"_nonce"
},
{
"type":"uint256",
"name":"_expiry"
},
{
"type":"bool",
"name":"_allowed"
},
{
"type":"uint8",
"name":"_v"
},
{
"type":"bytes32",
"name":"_r"
},
{
"type":"bytes32",
"name":"_s"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"string",
"name":""
}
],
"name":"symbol",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"decreaseAllowance",
"inputs":[
{
"type":"address",
"name":"spender"
},
{
"type":"uint256",
"name":"subtractedValue"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"transfer",
"inputs":[
{
"type":"address",
"name":"_to"
},
{
"type":"uint256",
"name":"_value"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"push",
"inputs":[
{
"type":"address",
"name":"_to"
},
{
"type":"uint256",
"name":"_amount"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"move",
"inputs":[
{
"type":"address",
"name":"_from"
},
{
"type":"address",
"name":"_to"
},
{
"type":"uint256",
"name":"_amount"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"address",
"name":""
}
],
"name":"bridgeContract",
"inputs":[
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
{
"type":"bool",
"name":""
}
],
"name":"increaseApproval",
"inputs":[
{
"type":"address",
"name":"_spender"
},
{
"type":"uint256",
"name":"_addedValue"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint256",
"name":""
}
],
"name":"allowance",
"inputs":[
{
"type":"address",
"name":"_owner"
},
{
"type":"address",
"name":"_spender"
}
],
"constant":true
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"pull",
"inputs":[
{
"type":"address",
"name":"_from"
},
{
"type":"uint256",
"name":"_amount"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"nonpayable",
"payable":false,
"outputs":[
],
"name":"transferOwnership",
"inputs":[
{
"type":"address",
"name":"_newOwner"
}
],
"constant":false
},
{
"type":"function",
"stateMutability":"view",
"payable":false,
"outputs":[
{
"type":"uint256",
"name":""
}
],
"name":"expirations",
"inputs":[
{
"type":"address",
"name":""
},
{
"type":"address",
"name":""
}
],
"constant":true
},
{
"type":"constructor",
"stateMutability":"nonpayable",
"payable":false,
"inputs":[
{
"type":"string",
"name":"_name"
},
{
"type":"string",
"name":"_symbol"
},
{
"type":"uint8",
"name":"_decimals"
},
{
"type":"uint256",
"name":"_chainId"
}
]
},
{
"type":"event",
"name":"ContractFallbackCallFailed",
"inputs":[
{
"type":"address",
"name":"from",
"indexed":false
},
{
"type":"address",
"name":"to",
"indexed":false
},
{
"type":"uint256",
"name":"value",
"indexed":false
}
],
"anonymous":false
},
{
"type":"event",
"name":"Mint",
"inputs":[
{
"type":"address",
"name":"to",
"indexed":true
},
{
"type":"uint256",
"name":"amount",
"indexed":false
}
],
"anonymous":false
},
{
"type":"event",
"name":"MintFinished",
"inputs":[
],
"anonymous":false
},
{
"type":"event",
"name":"OwnershipRenounced",
"inputs":[
{
"type":"address",
"name":"previousOwner",
"indexed":true
}
],
"anonymous":false
},
{
"type":"event",
"name":"OwnershipTransferred",
"inputs":[
{
"type":"address",
"name":"previousOwner",
"indexed":true
},
{
"type":"address",
"name":"newOwner",
"indexed":true
}
],
"anonymous":false
},
{
"type":"event",
"name":"Burn",
"inputs":[
{
"type":"address",
"name":"burner",
"indexed":true
},
{
"type":"uint256",
"name":"value",
"indexed":false
}
],
"anonymous":false
},
{
"type":"event",
"name":"Transfer",
"inputs":[
{
"type":"address",
"name":"from",
"indexed":true
},
{
"type":"address",
"name":"to",
"indexed":true
},
{
"type":"uint256",
"name":"value",
"indexed":false
},
{
"type":"bytes",
"name":"data",
"indexed":false
}
],
"anonymous":false
},
{
"type":"event",
"name":"Approval",
"inputs":[
{
"type":"address",
"name":"owner",
"indexed":true
},
{
"type":"address",
"name":"spender",
"indexed":true
},
{
"type":"uint256",
"name":"value",
"indexed":false
}
],
"anonymous":false
},
{
"type":"event",
"name":"Transfer",
"inputs":[
{
"type":"address",
"name":"from",
"indexed":true
},
{
"type":"address",
"name":"to",
"indexed":true
},
{
"type":"uint256",
"name":"value",
"indexed":false
}
],
"anonymous":false
}
],
omniBridgeAbi:[
{
"inputs":[
{
"internalType":"contract IERC677",
"name":"token",
"type":"address"
},
{
"internalType":"address",
"name":"_receiver",
"type":"address"
},
{
"internalType":"uint256",
"name":"_value",
"type":"uint256"
}
],
"name":"relayTokens",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"contract IERC677",
"name":"token",
"type":"address"
},
{
"internalType":"address",
"name":"_receiver",
"type":"address"
},
{
"internalType":"uint256",
"name":"_value",
"type":"uint256"
},
{
"internalType":"bytes",
"name":"_data",
"type":"bytes"
}
],
"name":"relayTokensAndCall",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"bytes32",
"name":"_messageId",
"type":"bytes32"
}
],
"name":"requestFailedMessageFix",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"requestGasLimit",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_bridgeContract",
"type":"address"
}
],
"name":"setBridgeContract",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_nativeToken",
"type":"address"
},
{
"internalType":"address",
"name":"_bridgedToken",
"type":"address"
}
],
"name":"setCustomTokenAddressPair",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_dailyLimit",
"type":"uint256"
}
],
"name":"setDailyLimit",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_dailyLimit",
"type":"uint256"
}
],
"name":"setExecutionDailyLimit",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_maxPerTx",
"type":"uint256"
}
],
"name":"setExecutionMaxPerTx",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_maxPerTx",
"type":"uint256"
}
],
"name":"setMaxPerTx",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_mediatorContract",
"type":"address"
}
],
"name":"setMediatorContractOnOtherSide",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_minCashThreshold",
"type":"uint256"
}
],
"name":"setMinCashThreshold",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_minPerTx",
"type":"uint256"
}
],
"name":"setMinPerTx",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"uint256",
"name":"_gasLimit",
"type":"uint256"
}
],
"name":"setRequestGasLimit",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_tokenFactory",
"type":"address"
}
],
"name":"setTokenFactory",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
],
"name":"tokenFactory",
"outputs":[
{
"internalType":"contract TokenFactory",
"name":"",
"type":"address"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_day",
"type":"uint256"
}
],
"name":"totalExecutedPerDay",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_day",
"type":"uint256"
}
],
"name":"totalSpentPerDay",
"outputs":[
{
"internalType":"uint256",
"name":"",
"type":"uint256"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"newOwner",
"type":"address"
}
],
"name":"transferOwnership",
"outputs":[
],
"stateMutability":"nonpayable",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_amount",
"type":"uint256"
}
],
"name":"withinExecutionLimit",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"view",
"type":"function"
},
{
"inputs":[
{
"internalType":"address",
"name":"_token",
"type":"address"
},
{
"internalType":"uint256",
"name":"_amount",
"type":"uint256"
}
],
"name":"withinLimit",
"outputs":[
{
"internalType":"bool",
"name":"",
"type":"bool"
}
],
"stateMutability":"view",
"type":"function"
}
]
};
export default blocksData; | 0a574038c8813ebb067c60812a0cd3f20a42fe38 | [
"Markdown",
"TypeScript"
] | 2 | Markdown | blocks-dao/blocks-xdai-module | c9d5cbcee32c8144286870a865e550902be3d6e5 | 4d4d9148120c98cf2902654bdacd8a7f8e00249d | |
refs/heads/master | <file_sep>#!/bin/bash
##
## Move EC2 RAID array from a given instance to a given instance
##
## <NAME> <<EMAIL>>
##
##
##
## The MIT License (MIT)
## Copyright (c) 2012-2013 <NAME>
##
## Permission is hereby granted, free of charge, to any person obtaining a
## copy of this software and associated documentation files (the "Software"),
## to deal in the Software without restriction, including without limitation
## the rights to use, copy, modify, merge, publish, distribute, sublicense,
## and/or sell copies of the Software, and to permit persons to whom the
## Software is furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included
## in all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
## DEALINGS IN THE SOFTWARE.
#
# Confirmation Prompt
#
confirm () {
read -r -p "${1:-Continue? [y/N]} " response
case $response in
[yY][eE][sS]|[yY]) true
;;
*) false
;;
esac
}
# Print Usage
#
usage() {
echo -e "\n*** This script will migrate a RAID array from one instance to another instance in the same availability zone. A safer way to do this is to build a new array on the destination instance and rsync everything over.\n"
echo -e "\nUsage: $0 -f <from instance> -t <to instance> -d <drive letter> (-h for help)"
}
# Process Command Line Args
while getopts ":f:t:d:h" optname
do
case ${optname} in
h|H) usage
echo -e "\n\tRequired Arguments:\n"
echo -e "\t-f <from instance> - the instance id the array is currently attached to"
echo -e "\t-t <to instance> - the instance id to copy the array to"
echo -e "\t-d <drive> - the drive identifier (last letter), ie 'h' for /dev/xvdh*"
echo -e "\n"
exit 0
;;
f|F) FROMINSTANCE=${OPTARG}
;;
t|T) TOINSTANCE=${OPTARG}
;;
d|D) DRIVEID=${OPTARG}
;;
*) echo "No such option ${optname}."
usage
exit 1
;;
esac
done
# Do we have values for required arguments?
[[ $FROMINSTANCE && ${FROMINSTANCE-x} ]] || { echo "No From instance given"; usage; exit 1; }
[[ $TOINSTANCE && ${TOINSTANCE-x} ]] || { echo "No To instance given"; usage; exit 1; }
[[ $DRIVEID && ${DRIVEID-x} ]] || { echo "No Drive Letter given"; usage; exit 1; }
# Do we have a valid DRIVEID
driveidletters=`echo -n $DRIVEID | wc -c`
[[ $driveidletters -gt 1 ]] && { echo -e "Only specify one drive letter d-z."; exit 1; }
driveidcheck=`echo $DRIVEID | grep [d-z] | wc -c`
[[ $driveidcheck -gt 0 ]] || { echo -e "Drive Letter ${DRIVEID} is invalid. Please specify d-z."; exit 1; }
# Check to make sure instances are in the same availability zone
echo -n "Checking Availability Zone..."
FROMAZ=`ec2-describe-instances -v $FROMINSTANCE | grep "<availabilityZone>" | awk -F'<availabilityZone>' '{print$2}' | awk -F'<' '{print$1}'`
echo -n "$FROMINSTANCE is in $FROMAZ..."
TOAZ=`ec2-describe-instances -v $TOINSTANCE | grep "<availabilityZone>" | awk -F'<availabilityZone>' '{print$2}' | awk -F'<' '{print$1}'`
echo "$TOINSTANCE is in $TOAZ."
[[ $FROMAZ != $TOAZ ]] && { echo "Instances $FROMINSTANCE and $TOINSTANCE are not in the same availability zone."; exit 1; }
# Get Array Info
echo -n "Getting array info..."
SAVEIFS=$IFS
IFS=$'\n'
DRIVEARRAY=(`ec2-describe-volumes | grep $FROMINSTANCE | grep "/dev/sd${DRIVEID}"`)
IFS=$SAVEIFS
ARRAYSIZE=${#DRIVEARRAY[@]}
# Check to make sure given drive letter exists on given from instance
[[ $ARRAYSIZE -gt 2 ]] || { echo -e "No array found as ${DRIVEID} on ${FROMINSTANCE}"; exit 1; }
echo -e "Moving an array of $ARRAYSIZE disks from $FROMINSTANCE to $TOINSTANCE in $FROMAZ.\n"
echo "Found $ARRAYSIZE volumes:"
for volume in "${DRIVEARRAY[@]}"
do
VOL=`echo $volume | awk '{print$2}'`
DEV=`echo $volume | awk '{print$4}'`
echo "$VOL as $DEV"
echo "$VOL:$DEV" >> /tmp/ec2raid-safetyfile.dat
done
echo ""
confirm && {
echo "Moving EBS volumes...";
for volume in "${DRIVEARRAY[@]}";
do
VOL=`echo $volume | awk '{print$2}'`;
DEV=`echo $volume | awk '{print$4}'`;
echo -en "\nDetaching $VOL from ${FROMINSTANCE}...";
ec2-detach-volume ${VOL};
sleep 8;
echo -en "\nAttaching ${VOL} to ${TOINSTANCE} as ${DEV}...";
ec2-attach-volume ${VOL} -i ${TOINSTANCE} -d ${DEV};
done;
echo "Done. There is a backup file of the mapping in /tmp/ec2raid-safetyfile.dat.";
}
<file_sep>#!/bin/bash
########
##
## Build RAID 10 array in Amazon EC2
## -----------------------------------
##
## <NAME> <<EMAIL>>
##
## Creates EBS volumes in Amazon EC2 and associates them with an EC2 instance for use as a RAID array
#
## Requirements
## --------------
##
## ec2-api-tools - http://aws.amazon.com/developertools/351
##
## !!!!!!!! !!!!!!!!
## !!!!!!!! NOTICE !!!!!!!! BEFORE CALLING THIS SCRIPT:
## !!!!!!!! !!!!!!!!
##
## ec2-api-tools must be working and your environment variables set up:
##
## AWS_ACCESS_KEY
## AWS_SECRET_KEY
#
## Usage
## -------
##
## buildec2raid.sh -s <size> -z <zone> -i <instance> [-d drive letter] [-n number of disks] [-o iops] [-v]
##
## size - the usable size of the raid array (in GB)
## zone - the availability zone
## instance - the ec2 instance id to attach to
## drive letter (optional) - the drive letter to use in association with the instance (defaults to h)
## number of disks (optional) - the number of disks to create for the array (defaults to 8, minimum 4)
## iops (optional) - the requested number of I/O operations per second that the volume can support
## -v to specify HVM instance (uses a different drive assignment scheme)
##
## Examples
## ----------
##
## ./buildec2raid.sh -s 1024 -z us-east-1a -i i-9i8u7y7y
##
## - this would create a 1TB array in us-east-1a attached to i-918u7y7y
##
## ./buildec2raid.sh -s 128 -z us-east-1d -i i-715e8e8v -o 100
##
## - this would create a 128GB array in us-east-1d attached to i-715e8e8v with 100 IOPS per second provisioned for each volume in the array.
#
##
## The MIT License (MIT)
## Copyright (c) 2012-2014 <NAME>
##
## Permission is hereby granted, free of charge, to any person obtaining a
## copy of this software and associated documentation files (the "Software"),
## to deal in the Software without restriction, including without limitation
## the rights to use, copy, modify, merge, publish, distribute, sublicense,
## and/or sell copies of the Software, and to permit persons to whom the
## Software is furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included
## in all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
## DEALINGS IN THE SOFTWARE.
#
##
## VARIABLES
#
# Default Number of Disks for the array
DISKS=4
# Default Drive ID
DRIVEID="h"
# Is HVM
HVM=1
# IOPS
PROVIOPS=0
##
## END VARIABILE DEFINITIONS
#
##
## FUNCTIONS
#
# Confirmation Prompt
#
confirm () {
read -r -p "${1:-Continue? [y/N]} " response
case $response in
[yY][eE][sS]|[yY]) true
;;
*) false
;;
esac
}
# Print Usage
#
usage() {
echo -e "\nUsage: $0 -s <size> -z <availability zone> -i <instance> [-d <drive letter>] [-n <disks>] [-o <iops>] (-h for help)"
}
# Check for AWS Environment Vars as we can't do much without them
[[ $AWS_ACCESS_KEY && ${AWS_ACCESS_KEY-x} ]] || { echo "AWS_ACCESS_KEY not defined. Please set up your AWS credentials. See http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?SettingUp_CommandLine.html for more information."; exit 1; }
[[ $AWS_SECRET_KEY && ${AWS_SECRET_KEY-x} ]] || { echo "AWS_SECRET_KEY not defined. Please set up your AWS credentials. See http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?SettingUp_CommandLine.html for more information."; exit 1; }
# Process Command Line Args
while getopts ":d:s:z:i:n:o:h:v" optname
do
case ${optname} in
h|H) usage
echo -e "\n\tRequired Arguments:\n"
echo -e "\t-s <size> - the usable size of the raid array (in GB)"
echo -e "\t-z <region> - the AWS region"
echo -e "\t-i <instance> - the EC2 instance id to attach to"
echo -e "\n\tOptional Arguments:\n"
echo -e "\t-d <drive> - the drive identifier to use (defaults to h)"
echo -e "\t-n <number of disks> - the number of disks to create in the array (defaults to 4)"
echo -e "\t-o <iops> - the requested number of I/O operations per second that the volume can support"
echo -e "\t-v specify PV instance (Defaults to HVM without this flag)"
echo -e "\n"
exit 0
;;
s|S) TOTALSIZE=${OPTARG}
;;
z|Z) AWSZONE=${OPTARG}
;;
i|I) EC2INSTANCE=${OPTARG}
;;
n|N) DISKS=${OPTARG}
;;
o|O) IOPS=${OPTARG}
PROVIOPS=1
;;
d|D) DRIVEID=${OPTARG}
;;
v|V) HVM=0
;;
* ) echo "No such option ${optname}."
usage
exit 1
;;
esac
done
# Do we have values for required arguments?
[[ $TOTALSIZE && ${TOTALSIZE-x} ]] || { echo "No size given"; usage; exit 1; }
[[ $AWSZONE && ${AWSZONE-x} ]] || { echo "No AWS Zone given"; usage; exit 1; }
[[ $EC2INSTANCE && ${EC2INSTANCE-x} ]] || { echo "No EC2 Instance given"; usage; exit 1; }
# Get list of AWS regions
AWSZONES=$(ec2-describe-availability-zones | awk '{printf("%s ", $2)}')
# Check given AWS region for validity
[[ "${AWSZONES}" =~ "${AWSZONE}" ]] || { echo -e "$AWSZONE is not a valid AWS zone.\n\nValid Zones: $AWSZONES\n"; exit 1; }
# Do we have a valid DRIVEID
driveidletters=$(echo -n $DRIVEID | wc -c)
[[ $driveidletters -gt 1 ]] && { echo -e "Only specify one drive letter d-z."; exit 1; }
driveidcheck=$(echo $DRIVEID | grep [d-z] | wc -c)
[[ $driveidcheck -gt 0 ]] || { echo -e "Drive Letter ${DRIVEID} is invalid. Please specify d-z."; exit 1; }
# Do we have the minimum number of disks for RAID 10
[[ $DISKS -gt 3 ]] || { echo -e "You need at least 4 disks for RAID10."; exit 1; }
# Make sure the instance is in the same zone
echo -n "Checking for instance $EC2INSTANCE in region ${AWSZONE}..."
# Get AWS endpoint for region
AWSURL=$(ec2-describe-regions | grep us-west-2 | awk '{print$3}')
AWSINSTANCECHECK=$(ec2-describe-instances | grep INSTANCE | grep $EC2INSTANCE | wc -c)
[[ $AWSINSTANCECHECK -gt 3 ]] || { echo -e "Instance ID: $EC2INSTANCE not found in ${AWSZONE}. Check your credentials, the instance id, and availability zone for the instance.\n\n"; exit 1; }
echo "found."
echo -n "Creating a $TOTALSIZE GB array in $AWSZONE for instance $EC2INSTANCE"
[[ $PROVIOPS -eq 1 ]] && { echo -n " with $IOPS I/O operations per second"; IOPSARGS="--type io1 --iops ${IOPS}"; }
echo "."
# Do the Math: 2X total capacity, each disk 2*(capacity)/(number of disks)
CAPACITY=$(expr $TOTALSIZE \* 2)
EACHDISK=$(expr $CAPACITY / $DISKS)
echo -e "This means a total of $CAPACITY GB in $DISKS EBS volumes of $EACHDISK GB each will be added to the instance.\n"
# Error check: IOPS volumes must be at least 10GB in size
[[ $PROVIOPS -eq 1 ]] && [[ $EACHDISK -lt 10 ]] && { echo -e "** EBS volumes with IOPS must be at least 10GB in size. Increase the array size or reduce the number of disks (-n <disks>)\n\n"; exit 1; }
confirm && {
HVMDISKARRAY=$DRIVEID
PVDISKARRAY="1"
echo "Creating EBS Volumes...";
for (( disk=1; disk<=$DISKS; disk++));
do
echo -en "\tCreating volume $disk of $DISKS...";
# Create Volumes
createvolume=$(ec2-create-volume --size ${EACHDISK} --availability-zone ${AWSZONE} ${IOPSARGS})
# exit if it didn't work
[[ $createvolume && ${createvolume-x} ]] || { echo "Volume Creation Unsuccessful. Exiting." exit 1; }
# pause to allow amazon's api to catch up
sleep 4
# Associate with Instance, exit if unsuccessful
echo -en "Associating with instance...\n\t";
volume=$(echo $createvolume | awk '{print$2}');
if [[ $HVM -eq 0 ]]
then
ec2-attach-volume $volume -i ${EC2INSTANCE} -d /dev/sd${DRIVEID}${disk} || { echo "Association of volume $volume to instance ${EC2INSTANCE} as /dev/sd${DRIVEID}${disk} failed! Exiting..."; exit 1; };
else
ec2-attach-volume $volume -i ${EC2INSTANCE} -d /dev/sd${DRIVEID} || { echo "Association of volume $volume to instance ${EC2INSTANCE} as /dev/sd/${DRIVEID} failed! Exiting..."; exit 1; };
LASTDRIVEID=$DRIVEID
newdriveletter=$(echo $DRIVEID | perl -nle 'print ++$_')
DRIVEID=${newdriveletter}
fi
done;
echo -en "EC2 volumes creation is complete. You can now log into the instance and create the raid array:\n\tmdadm --create -l10 -n$DISKS /dev/md0 ";
if [[ $HVM -eq 1 ]]
then
echo "/dev/xvd[$HVMDISKARRAY-$LASTDRIVEID]"
else
echo "/dev/sd$DRIVEID[$PVDISKARRAY-$DISKS]"
fi
}
<file_sep># Build RAID 10 array in Amazon EC2
Creates EBS volumes in Amazon EC2 and associates them with an EC2 instance for use as a RAID array
## Requirements
### ec2-api-tools - http://aws.amazon.com/developertools/351
ec2-api-tools must be working and your environment variables set up:
* AWS_ACCESS_KEY
* AWS_SECRET_KEY
## Usage
$ buildec2raid.sh -s <size> -z <zone> -i <instance> [-d drive letter] [-n number of disks] [-o iops] -v
* size - the usable size of the raid array (in GB)
* zone - the availability zone
* instance - the ec2 instance id to attach to
* drive letter (optional) - the drive letter to use in association with the instance (defaults to h)
* number of disks (optional) - the number of disks to create for the array (defaults to 4)
* iops (optional) - the requested number of I/O operations per second that the volume can support
* -v to specify PV instances (HVM instances use a different drive assignment scheme than PV)
## Example
$ ./buildec2raid.sh -s 1024 -z us-east-1a -i i-9i8u7y7y
This would create a 1TB array in us-east-1a attached to i-918u7y7y
$ ./buildec2raid.sh -s 1024 -z us-east-1a -i i-9i8u7y7y -n 6 -o 100 -d j
This would create a 1TB array in us-east-1a attached to i-9i8u7y7y using 6 drives provisioned with 100 IOPS per second and using j as the drive letter
(/dev/sdj and /dev/xvdj)
## More information
After completing the creation of the EBS volumes using this script, you can log into the instance and initialize the raid array. For example:
$ mdadm --create -l10 -n8 /dev/md0 /dev/xvdh*
This creates a RAID 10 volume from 8 EBS disks. For more information on software raid, see https://raid.wiki.kernel.org/index.php/Linux_Raid
## License
This script is distributed under the MIT License (see LICENSE)
## Migrating a RAID array to another instance
Typically if you want to migrate data between hosts within the same availability zone, you would create a new array on the destination instance and copy or rsync the data over.
However the <strong>moveec2raid.sh</strong> script in this repository will migrate a RAID array to another instance.
The syntax is:
$ ./moveec2raid.sh -f <from instance> -t <to instance> -d <drive letter>
All three fields are required. The drive letter is the drive identifier of the origin instance. ie. /dev/xvdh*.
<em>The script assumes that all volumes mounted with that drive letter are part of your RAID array and they will be migrated in place.</em> If you used the <strong>buildec2raid.sh</strong> script, that is how the array is set up.
Make note of your <em>/etc/mdadm.conf</em> file as it contains the identification information for your array.
[](https://github.com/igrigorik/ga-beacon)
| 65d3d09d4d75e2ed789dcf9bfddbeea5d5e5e04b | [
"Markdown",
"Shell"
] | 3 | Shell | bparsons/buildec2raid | b90e13472b41db8df6c80cd3d93240bb49d04fd0 | 3531adfd4ee074e39e667ef05d81324a051750de | |
refs/heads/master | <file_sep>-- {{{ Required libraries
gears = require("gears")
awful = require("awful")
awful.rules = require("awful.rules")
require("awful.autofocus")
wibox = require("wibox")
beautiful = require("beautiful")
naughty = require("naughty")
lain = require("lain")
menubar = require("menubar")
require("eminent")
-- }}}
-- {{{ Error handling
if awesome.startup_errors then
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors })
end
do
local in_error = false
awesome.connect_signal("debug::error", function (err)
if in_error then return end
in_error = true
naughty.notify({ preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = err })
in_error = false
end)
end
-- }}}
-- {{{ Autostart applications
function run_once(cmd)
findme = cmd
firstspace = cmd:find(" ")
if firstspace then
findme = cmd:sub(0, firstspace-1)
end
awful.util.spawn_with_shell("pgrep -u $USER -x " .. findme .. " > /dev/null || (" .. cmd .. ")")
end
--run_once("urxvtd")
run_once("unclutter")
-- }}}
-- {{{ Variable definitions
-- localization
os.setlocale(os.getenv("LANG"))
-- beautiful init
beautiful.init(os.getenv("HOME") .. "/.config/awesome/theme/theme.lua")
-- common
modkey = "Mod4"
altkey = "Mod1"
terminal = "urxvt" or "xterm"
editor = os.getenv("EDITOR") or "nano" or "vi"
editor_cmd = terminal .. " -e " .. editor
-- user defined
browser = "google-chrome-stable"
browser2 = "firefox"
gui_editor = "gvim"
graphics = "gimp"
mail = terminal .. " -e mutt "
iptraf = terminal .. " -g 180x54-20+34 -e sudo iptraf-ng -i all "
musicplr = terminal .. " -g 130x34-320+16 -e ncmpcpp "
layouts =
{
lain.layout.uselesstile,
lain.layout.uselesstile.left,
lain.layout.uselesstile.bottom,
lain.layout.uselesstile.top,
lain.layout.uselessfair,
lain.layout.uselessfair.horizontal,
lain.layout.uselesspiral,
lain.layout.uselesspiral.dwindle
}
-- }}}
-- {{{ Tags
tags = {
names = { "1", "2", "3", "4", "5"},
layout = { layouts[1], layouts[2], layouts[3], layouts[1], layouts[4] }
}
for s = 1, screen.count() do
tags[s] = awful.tag(tags.names, s, tags.layout)
end
-- }}}
-- {{{ Wallpaper
if beautiful.wallpaper then
for s = 1, screen.count() do
gears.wallpaper.maximized(beautiful.wallpaper[s], s, true)
end
end
-- }}}
dofile(awful.util.getdir("config") .. "/bindings.lua")
dofile(awful.util.getdir("config") .. "/widgets.lua")
dofile(awful.util.getdir("config") .. "/signals.lua")
dofile(awful.util.getdir("config") .. "/rules.lua")
<file_sep>-- {{{ Rules
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
keys = clientkeys,
buttons = clientbuttons,
size_hints_honor = false } },
{ rule = { class = "MPlayer" },
properties = { floating = true } },
{ rule = { class = "Dwb" },
properties = { tag = tags[1][1] } },
{ rule = { class = "Iron" },
properties = { tag = tags[1][1] } },
{ rule = { instance = "plugin-container" },
properties = { tag = tags[1][1] } },
{ rule = { class = "kshutdown" },
properties = { floating = true } },
}
-- }}}
| 4178e02045c2c9ff83bd096af1e289b352757814 | [
"Lua"
] | 2 | Lua | Expi1/dotfiles | ccccd16ceceaced1998297932715ed00bcd1188a | 3ed4433c983fabc0557e494cf2ae669d42306ed1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.