branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>HybridRbt/Programing-with-CSharp<file_sep>/ConsoleApplicationHomeWork3/ConsoleApplicationHomeWork3/Program.cs
using System;
namespace ConsoleApplicationHomeWork3
{
class Program
{
static void Main(string[] args)
{
// just a illustration of the exception handling.
try
{
GetStudentInfo();
}
catch (FormatException formatEx)
{
Console.WriteLine("The format of you last input is incorrect!");
}
catch (ArgumentOutOfRangeException arguEx)
{
Console.WriteLine("Your last input is out of range!");
}
GetCourseInfo();
GetTeacherInfo();
GetProgramInfo();
GetDegreeInfo();
Console.ReadLine();
//ValidateStudentBirthday();
}
/*
private static void ValidateStudentBirthday()
{
throw new NotImplementedException();
}
*/
static void GetStudentInfo()
{
Console.WriteLine("Enter the student's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the student's birth year: ");
int birthYear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the student's birth month: ");
int birthMonth = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the student's birth date: ");
int birthDate = Convert.ToInt32(Console.ReadLine());
DateTime birthday = new DateTime(birthYear, birthMonth, birthDate);
PrintStudentDetails(firstName, lastName, birthday.ToShortDateString());
}
static void PrintStudentDetails(string first, string last, string birthday)
{
Console.WriteLine("{0} {1} was born on: {2}.", first, last, birthday);
}
static void GetCourseInfo()
{
Console.WriteLine("Enter course name: ");
string courseName = Console.ReadLine();
Console.WriteLine("Enter the course code: ");
string courseCode = Console.ReadLine();
Console.WriteLine("Enter the semester of the course: ");
string semester = Console.ReadLine();
PrintCourseDetails(courseName, courseCode, semester);
}
static void PrintCourseDetails(string name, string code, string semester)
{
Console.WriteLine("This course: {0}: {1} will be held in {2}.", code, name, semester);
}
static void GetTeacherInfo()
{
Console.WriteLine("Enter the teacher's first name: ");
string firstName = Console.ReadLine();
Console.WriteLine("Enter the teacher's last name: ");
string lastName = Console.ReadLine();
Console.WriteLine("Enter the teacher's department: ");
string department = Console.ReadLine();
PrintTeacherDetails(firstName, lastName, department);
}
static void PrintTeacherDetails(string first, string last, string department)
{
Console.WriteLine("{0} {1} is a teacher in {2}", first, last, department);
}
static void GetProgramInfo()
{
Console.WriteLine("Enter name of the program: ");
string programName = Console.ReadLine();
Console.WriteLine("Enter department that offers this program: ");
string departmentName = Console.ReadLine();
Console.WriteLine("Enter the name of the department head: ");
string departmentHeadName = Console.ReadLine();
PrintProgramDetails(programName, departmentName, departmentHeadName);
}
static void PrintProgramDetails(string name, string dep, string depHead)
{
Console.WriteLine("{0} is a program offered by {1}. This department is led by {2}.", name, dep, depHead);
}
static void GetDegreeInfo()
{
Console.WriteLine("Enter name of the degree: ");
string name = Console.ReadLine();
Console.WriteLine("Enter length of the degree: ");
string length = Console.ReadLine();
Console.WriteLine("Enter required credit to complete the degree: ");
string credit = Console.ReadLine();
PrintDegreeDetails(name, length, credit);
}
static void PrintDegreeDetails(string name, string length, string credit)
{
Console.WriteLine("This degree {0} will last {1}, and require {2} credits to complete.", name, length, credit);
}
}
}
<file_sep>/ConsoleAppHomework1/ConsoleAppHomework1/Program.cs
using System;
namespace ConsoleApplicationModule1
{
class Program
{
static void Main(string[] args)
{
//**** student information ***//
string firstName = "John";
string lastName = "Down";
DateTime birthDate = new DateTime(85, 1, 20);
string addressLine1 = "9900 Independent Pkwy";
string addressLine2 = "Room 335";
string city = "Irving";
string stateOrProvince = "TX";
string zipOrPostal = "70605";
string country = "U.S.A";
//**** professor information ***//
string professorName = "<NAME>";
string professorMajor = "Computer Science";
//**** degree info ***//
string degreeName = "Bachelor of Science in Information Technology";
int degreeCreditsReq = 30;
//**** university program ***//
string programName = "Computer Science";
string degreesOffered = "Bachelor";
string departmentHead = "Root Grooves";
//**** course info ***//
string courseName = "Programming with C#";
string courseIntro = "This course aims to teach the basics of C# all the way through the advanced features of the language. " +
"This course is not a beginner course on C#, although beginners can still learn a lot from the material." +
" It is intended to provide an introduction to the C# language and the world of .NET programming for" +
" existing programmers who need or want to learn more about C# and managed code development.";
Console.WriteLine("First Name: " + firstName);
Console.WriteLine("Last Name: " + lastName);
Console.WriteLine("Birth Day: " + birthDate);
Console.WriteLine("Address Line 1: " + addressLine1);
Console.WriteLine("Address Line 2: " + addressLine2);
Console.WriteLine("City: " + city);
Console.WriteLine("State: " + stateOrProvince);
Console.WriteLine("Zip: " + zipOrPostal);
Console.WriteLine("Country: " + country);
Console.WriteLine("My profesor is: " + professorName);
Console.WriteLine("And his major is: " + professorMajor);
Console.WriteLine("My degree is: " + degreeName + ", which requires " + degreeCreditsReq + " credits to complete.");
Console.WriteLine("My program is: " + programName + ", with " + departmentHead
+ " as the department head. And they offer " + degreesOffered + " in the program.");
Console.WriteLine("My current course is: " + courseName + ". " + courseIntro);
Console.ReadLine();
}
}
}
<file_sep>/Module2/ConsoleApplicationHomeWork2/ConsoleApplicationHomeWork2/Program.cs
using System;
namespace ConsoleApplicationHomeWork2
{
class Program
{
static void Main(string[] args)
{
int rowNumber = 8;
int colNumber = 8;
string currentPattern;
for (int i = 0; i < rowNumber; i++)
{
if (i % 2 == 0) //rowNumber is even, starts with "X"
{
currentPattern = "X";
}
else
{
currentPattern = "O";
}
for (int j = 0; j < colNumber; j++)
{
Console.Write(currentPattern);
if (currentPattern == "X")
{
currentPattern = "O";
}
else
{
currentPattern = "X";
}
}
Console.Write("\n"); // next line
}
Console.ReadLine();
}
}
}
<file_sep>/ConsoleApplicationHomeWork4/ConsoleApplicationHomeWork4/Program.cs
using System;
namespace ConsoleApplicationHomeWork4
{
class Program
{
public struct Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDay { get; set; }
}
public struct Teacher
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
}
public struct DegreeProgram
{
public string Name { get; set; }
public string Length { get; set; }
public string Credit { get; set; }
}
public struct Course
{
public string Name { get; set; }
public string Code { get; set; }
public string Semester { get; set; }
}
static void Main(string[] args)
{
Student[] studentsArray = new Student[5];
string firstName = "John";
string lastName = "Reese";
DateTime birthday = new DateTime(1983, 3, 15);
AssignStudentDetails(ref studentsArray[0], firstName, lastName, birthday);
AssignStudentDetails(ref studentsArray[1], "Kyle", "Finch", new DateTime(1973, 5, 21));
Console.WriteLine("Details about the first student:");
PrintStudentDetails(studentsArray[0]);
Console.WriteLine("\nDetails about the second student:");
PrintStudentDetails(studentsArray[1]);
Console.ReadLine();
}
private static void AssignStudentDetails(ref Student aStudent, string firstName, string lastName, DateTime birthday)
{
// A better way to do this is to ask user for input
// interactively like we did in last homework, but
// here since it's not required I will just assign
// them directly.
aStudent.FirstName = firstName;
aStudent.LastName = lastName;
aStudent.BirthDay = birthday;
}
private static void PrintStudentDetails(Student aStudent)
{
Console.WriteLine("Name: " + aStudent.FirstName + " " + aStudent.LastName);
Console.WriteLine("Birthday: " + aStudent.BirthDay.ToShortDateString());
}
}
}
| f4dd05ab307ae25af857a968b657ea9abe2c7369 | [
"C#"
] | 4 | C# | HybridRbt/Programing-with-CSharp | 5860ab76bb22ee3463b0102a7485de3fd5e6e86a | 9e875995bbae544e5bb84536806f46dd76b7fdf1 |
refs/heads/master | <file_sep>extern crate eva_lib;
use eva_lib::mat;
use eva_lib::mat::Mat;
use mat::pixel_description::PixelDescription;
use rand::Rng;
use std::time::{Duration, Instant};
use std::thread::sleep;
fn main() {
let tree_left = mat::Mat::load_png("examples/test_left.png");
let tree_right = mat::Mat::load_png("examples/test_right.png");
let tree_left_gray = tree_left.to_gray();
let tree_right_gray = tree_right.to_gray();
let mut match_points = Vec::<(PixelDescription, PixelDescription)>::new();
let groups = tree_left_gray.rows/200;
let mut masks = Vec::<((u16, u16, u16, u16), (u16, u16, u16, u16))>::with_capacity(groups as usize);
for i in 0..groups {
let left_x = tree_left_gray.cols - 200 -1;
let right_x = 0u16;
let y = i * 200;
let w = 200;
let h = 200;
masks.push(((left_x, y, w, h), (right_x, y, w, h)));
}
let total_begin = Instant::now();
for i in 0..groups {
let now = Instant::now();
let tree_left_descriptions = tree_left_gray.fast_search_features(10, &masks[i as usize].0, mat::pixel_description::Direction::Horizontal);
let tree_right_descriptions = tree_right_gray.fast_search_features(10, &masks[i as usize].1, mat::pixel_description::Direction::Horizontal);
println!("Spend ms on SEARCH:{}", now.elapsed().as_millis());
println!("{:?}", "111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
let now = Instant::now();
let points = &PixelDescription::match_points(&tree_left_descriptions, &tree_right_descriptions, 900);
match_points.extend_from_slice(points);
println!("Spend ms on MATCH:{}", now.elapsed().as_millis());
println!("{:?}", "222222222222222222222222222222222222222222222222222222222222222222222222222222222222");
}
println!("Spend ms on TOTAL:{}", total_begin.elapsed().as_millis());
println!("{:?}", "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
let mut combined_image = Mat::new(tree_left.cols + tree_right.cols, 3500, None);
let tree_left_cols = tree_left.cols;
let left_tree_cols = tree_right.cols;
combined_image = combined_image.merge(tree_left, 0, 0);
combined_image = combined_image.merge(tree_right, left_tree_cols - 1, 0);
println!("Pairs: {:?}", match_points.len());
for point_pair in &match_points {
let point_a_xy = point_pair.0.coordinate;
let point_b_xy = point_pair.1.coordinate;
let mut rng = rand::thread_rng();
let r: u8 = rng.gen();
let g: u8 = rng.gen();
let b: u8 = rng.gen();
let mut color = vec![r, g, b, 255u8];
combined_image.draw_line((point_a_xy.0 as usize, point_a_xy.1 as usize), ((point_b_xy.0 + tree_left_cols) as usize, point_b_xy.1 as usize), &mut color);
}
combined_image.save_as_png("combined_image.png");
let tree_left = mat::Mat::load_png("examples/test_left.png");
let tree_right = mat::Mat::load_png("examples/test_right.png");
let move_vector = Mat::avg_mapping_vector(&match_points);
let mut dist = Mat::new(tree_left.cols + tree_right.cols, tree_left.rows, Some(255u8));
Mat::move_mat(&mut dist, &tree_left, (0., 0.));
Mat::move_mat(&mut dist, &tree_right, move_vector);
dist.save_as_png("merged_image.png");
}<file_sep>#[derive(Debug)]
pub struct Kernel {
pub data: Vec<Vec<f32>>,
}
impl Kernel {
pub fn load(data: Vec<Vec<f32>>)
-> Kernel
{
let kernel = Kernel { data: data };
kernel
}
pub fn laplation_8() -> Kernel {
Kernel::load(vec![
vec![1.0, 1.0, 1.0],
vec![1.0, -8.0, 1.0],
vec![1.0, 1.0, 1.0]
])
}
pub fn laplation_4() -> Kernel {
Kernel::load(vec![
vec![0.0, 1.0, 0.0],
vec![1.0, -4.0, 1.0],
vec![0.0, 1.0, 0.0]
])
}
pub fn laplation_12() -> Kernel {
Kernel::load(vec![
vec![1.0, 1.0, 1.0, 1.0],
vec![1.0, -3.0, -3.0, 1.0],
vec![1.0, -3.0, -3.0, 1.0],
vec![1.0, 1.0, 1.0, 1.0]
])
}
pub fn size(&self) -> usize {
self.data.len()
}
pub fn flatten(&self)
-> Vec<f32>
{
let mut vec = Vec::with_capacity(self.elements());
for row in self.data.to_vec() {
for value in row {
vec.push(value);
}
}
vec
}
pub fn elements(&self)
-> usize
{
self.data.len()*self.data.len()
}
pub fn indexes(&self, index: usize, chrunk_size: usize, total_elements: usize)
-> (bool, Vec<usize>)
{
let mut indexes = Vec::with_capacity(self.size()*self.size());
let offset = index%chrunk_size;
if (offset + self.size()) > chrunk_size {
return (false, vec![]);
}
for row in 0..self.size() {
for col in 0..self.size() {
let id = row * chrunk_size + col + index;
if id >= total_elements {
return (false, vec![]);
}
indexes.push(id);
}
}
return (true, indexes);
}
}<file_sep>extern crate eva_lib;
extern crate serde_json;
use eva_lib::mat::Mat;
use std::fs::File;
use std::io::Read;
fn main() {
let dir = std::env::args().nth(1).expect("no pattern given");
let mut file = File::open(format!("{}/merged_fragments.json", dir)).unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let result: Vec<Vec<usize>> = serde_json::from_str(&data).unwrap();
let image = Mat::load_png(&format!("{}/result.png", dir));
for (i, ffp) in result.iter().enumerate() {
let mut fragment_image = image.crop(ffp[0], ffp[1], ffp[2] - ffp[0], ffp[3] - ffp[1]);
// fragment_image = fragment_image.add_padding(20);
fragment_image.save_as_png(&format!("{}/fragment_{}.png", dir, i));
}
// let ffp = result[35].clone();
// let fragment_image = image.crop(ffp[0], ffp[1], ffp[2] - ffp[0], ffp[3] - ffp[1]);
// fragment_image.save_as_png(&format!("{}/fragment_{}.png", dir, 35));
}<file_sep>extern crate eva_lib;
use eva_lib::mat;
use eva_lib::mat::Mat;
use mat::pixel_description::PixelDescription;
use mat::pixel_description::Direction;
use rand::Rng;
fn main() {
// let mat = mat::Mat::load_jpeg("examples/tests/chips.jpg");
// mat.save_as_bmp("large.bmp");
// let mat_png = mat::Mat::load_png("examples/rust.png");
// mat.save_as_png("large.png");
// let mat_gray_png = mat.to_gray();
// mat_gray_png.save_as_png("large_gray.png");
// mat_gray_png.to_gray().save_as_png("gray_to_gray.png");
// let new_mat = mat.crop(1, 1, 800, 800);
// new_mat.save_as_png("croped_large.png");
// let resized_mat = mat.resize(200, 100);
// let beauty = mat::Mat::load_jpeg("examples/beauty.jpeg");
// let mut unfocus = mat::Mat::load_jpeg("examples/tests/chips.jpg");
// let laplation_result = beauty.convolute(mat::kernels::Kernel::laplation_4());
// let unfocus_laplation_result = unfocus.to_gray().convolute(mat::kernels::Kernel::laplation_8());
// unfocus_laplation_result.save_as_png("laplation_result.png");
// Stitching two pictures
// END stitching two pictures
// resized_mat.save_as_png("resized_large.png");
let mat_ma = mat::Mat::load_jpeg("examples/tests/top.jpg");
mat_ma.fast_search_features(10, &(0, 0, mat_ma.cols, mat_ma.rows), Direction::Horizontal);
// let mut mat_mb = mat::Mat::load_jpeg("examples/tests/large.jpg");
// mat_ma.merge(mat_mb, 100, 100);
// let new_mat = mat::Mat::load_from_vec(vec![105u8; 40000], 100, 100, 4);
// mat_ma.save_as_png("new_mat.png");
// let mat_merged_result_channel_0 = mat.get_channel(0);
// mat_merged_result_channel_0.save_as_png("merge_result_c0.jpg");
// let mat_merged_result_channel_1 = mat.get_channel(1);
// mat_merged_result_channel_1.save_as_png("merge_result_c1.jpg");
}
<file_sep>pub mod mat;
pub mod cl;
use cl::CL;
use mat::Mat;
use mat::pixel_description::{PixelDescription, Direction};
use std::time::Instant;
#[macro_use]
extern crate lazy_static;
pub fn stitch_left_right(left: &Mat, right: &Mat)
-> (Mat, f32, f32)
{
let total_begin = Instant::now();
let left_gray = left.to_gray();
let right_gray = right.to_gray();
// 433ms
fn gen_masks(src: &Mat, width: usize, height: usize)
-> Vec<((usize, usize, usize, usize), (usize, usize, usize, usize))>
{
let groups = src.rows/height;
let mut masks = Vec::<((usize, usize, usize, usize), (usize, usize, usize, usize))>::with_capacity(groups as usize);
for i in 0..groups {
let left_x = src.cols - width -1;
let right_x = 0usize;
let y = i * height;
let w = width;
let h = height;
masks.push(((left_x, y, w, h), (right_x, y, w, h)));
}
masks
}
let mut match_points = Vec::<(PixelDescription, PixelDescription)>::new();
let mask_pairs = gen_masks(&left_gray, 150, 150);
for mask_pair in mask_pairs {
let left_descriptions = left_gray.fast_search_features(10, &mask_pair.0, Direction::Horizontal);
let right_descriptions = right_gray.fast_search_features(10, &mask_pair.1, Direction::Horizontal);
let points = &PixelDescription::match_points(&left_descriptions, &right_descriptions, 900);
match_points.extend_from_slice(points);
}
println!("Pairs: {:?}", match_points.len());
// 922ms
let mut move_vector = Mat::avg_mapping_vector(&match_points);
if move_vector.0.is_nan() || move_vector.1.is_nan() || match_points.len() < 3 {
move_vector = ((left.cols as f32) - 235.0f32, 0f32);
}
let mut dist = Mat::new(left.cols + right.cols - (left.cols - move_vector.0 as usize), left.rows, Some(255u8));
// Mat::move_mat(&mut dist, &left, (0., 0.));
let shared_section = transition_section(&left, move_vector);
println!("{:?}", move_vector);
dist.merge(left, 0, 0);
println!("{:?}", shared_section);
println!("===================================================================================================");
let left_shared_mat = dist.crop(shared_section.0, shared_section.1, shared_section.2, shared_section.3);
Mat::move_mat(&mut dist, &right, move_vector);
// Mat::move_mat_by_multi_points(&mut dist, &right, &match_points, move_vector);
let right_shared_mat = dist.crop(shared_section.0, shared_section.1, shared_section.2, shared_section.3);
let shared_mat = fuse(&left_shared_mat, &right_shared_mat, Direction::Horizontal);
let total_begin = total_begin.elapsed().as_millis();
// shared_mat.save_as_png("shared_mat_1.png");
println!("Spend ms on STITCHING:{}", total_begin);
dist.merge(&shared_mat, shared_section.0 as usize, shared_section.1 as usize);
(dist, move_vector.0, move_vector.1)
}
pub fn stitch_top_bottom(top: &Mat, bottom: &Mat)
-> (Mat, f32, f32)
{
let total_begin = Instant::now();
let top_gray = top.to_gray();
let bottom_gray = bottom.to_gray();
fn gen_masks(src: &Mat, width: usize, height: usize)
-> Vec<((usize, usize, usize, usize), (usize, usize, usize, usize))>
{
let groups = src.cols/width;
let mut masks = Vec::<((usize, usize, usize, usize), (usize, usize, usize, usize))>::with_capacity(groups as usize);
for i in 0..groups {
let x = i*width;
let top_y = src.rows- height -1;
let bottom_y = 0;
let w = width;
let h = height;
masks.push(((x, top_y, w, h), (x, bottom_y, w, h)));
}
masks
}
let mut match_points = Vec::<(PixelDescription, PixelDescription)>::new();
let mask_pairs = gen_masks(&top_gray, 400, 162);
let total_begin = total_begin.elapsed().as_millis();
for mask_pair in mask_pairs {
println!("Mask X: {:?}", (mask_pair.0).0);
let top_descriptions = top_gray.fast_search_features(10, &mask_pair.0, Direction::Vertical);
let bottom_descriptions = bottom_gray.fast_search_features(10, &mask_pair.1, Direction::Vertical);
let points = &PixelDescription::match_points(&top_descriptions, &bottom_descriptions, 900);
println!("Pairs: {:?}", points.len());
println!("Mask: ====================================================");
match_points.extend_from_slice(points);
}
let mut move_vector = Mat::avg_mapping_vector(&match_points);
let mut multi_points = true;
if move_vector.0.is_nan() || move_vector.1.is_nan() {
println!("强行来个位置");
move_vector = (0f32, (top.rows - 156) as f32);
multi_points = false;
}
let mut dist = Mat::new(top.cols, top.rows + bottom.rows - (top.rows - move_vector.1 as usize), Some(255u8));
let shared_section = transition_section(&top, move_vector);
Mat::move_mat(&mut dist, &top, (0., 0.));
println!("{:?}", shared_section);
println!("===================================================================================================");
let top_shared_mat = dist.crop(shared_section.0, shared_section.1, shared_section.2, shared_section.3);
// if multi_points {
// Mat::move_mat_by_multi_points(&mut dist, &bottom, move_vector, &match_points);
// } else {
Mat::move_mat(&mut dist, &bottom, move_vector);
let bottom_shared_mat = dist.crop(shared_section.0, shared_section.1, shared_section.2, shared_section.3);
let shared_mat = fuse(&top_shared_mat, &bottom_shared_mat, Direction::Vertical);
dist.merge(&shared_mat, shared_section.0 as usize, shared_section.1 as usize);
// }
// Mat::move_mat(&mut dist, &bottom, move_vector);
// shared_mat.save_as_png("shared_mat_2.png");
println!("Spend ms on STITCHING:{}", total_begin);
// for pair in match_points {
// // println!("{:?}, ", pair.0.coordinate.0);
// dist.draw_point(pair.0.coordinate, vec!(255u8, 0u8, 0u8));
// }
(dist, move_vector.0, move_vector.1)
}
fn fuse(a_image: &Mat, b_image: &Mat, direction: Direction) -> Mat {
let mut new_section = Mat::new(a_image.cols, a_image.rows, Some(255u8));
for y in 0..(a_image.rows as usize) {
for x in 0..(a_image.cols as usize) {
let mut new_vec = Vec::<u8>::new();
for i in 0..a_image.bytes_per_pixel {
let factor = match direction {
Direction::Horizontal => {
1.0 - x as f32/a_image.cols as f32
},
Direction::Vertical => {
1.0 - y as f32/a_image.rows as f32
}
};
let mut value = (a_image.get_pixel_by_xy(x, y)[i] as f32 * factor).round() + (b_image.get_pixel_by_xy(x, y)[i] as f32 * (1.0-factor)).round();
if value > 255.0 {
value = 255.0;
}
new_vec.push(value as u8);
}
new_section.set_pixel_by_xy(x, y, new_vec);
}
}
new_section
}
fn transition_section(a_image: &Mat, move_vector: (f32, f32))
-> (usize, usize, usize, usize)
{
let x = match move_vector.0 < 0.0 {
true => 0usize,
false => move_vector.0 as usize
};
let y = match move_vector.1 < 0.0 {
true => 0usize,
false => move_vector.1 as usize
};
let width = match a_image.cols as f32 - move_vector.0 < 0.0 {
true => 0usize,
false => {
if move_vector.0 < 0.0f32 {
a_image.cols as usize
} else {
(a_image.cols as f32 - move_vector.0) as usize
}
}
};
let height = match a_image.rows as f32 - move_vector.1 < 0.0 {
true => 0usize,
false => {
if move_vector.1 < 0.0f32 {
a_image.rows as usize
} else {
(a_image.rows as f32 - move_vector.1) as usize
}
}
};
(x, y, width, height)
}<file_sep>[package]
name = "eva_lib"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
jpeg-decoder = "*"
bmp = "*"
png = "0.14.1"
rand = "0.7.0"
ocl = "0.19"
heapsize = "0.4.2"
lazy_static = "1.3.0"
serde_json = "1.0"<file_sep>extern crate ocl;
use std::ffi::CString;
use ocl::builders::ContextProperties;
use ocl::{core, flags};
use ocl::enums::ArgVal;
use std::time::Instant;
use crate::mat::kernels::Kernel;
#[derive(Debug, Clone)]
pub struct CL {
context: ocl::core::Context,
program: ocl::core::Program,
queue: ocl::core::CommandQueue
}
impl CL {
pub fn new() -> CL {
let src = r#"
__kernel void crop(__global uchar* result, __global uchar* data, int x, int y, int width, int height, int channels, int data_width) {
int new_x = get_global_id(0);
int new_y = get_global_id(1);
int new_index = new_y * width * channels + new_x * channels;
int old_x = new_x + x;
int old_y = new_y + y;
int old_index = old_x * channels + old_y * data_width * channels;
result[new_index] = data[old_index];
for (int i=0;i<channels;i++) {
result[new_index+i] = data[old_index+i];
}
}
__kernel void convolute(__global float* result, __global float* data, __global float* kernel_array, int width, int height, int kernel_width) {
int result_x = get_global_id(0);
int result_y = get_global_id(1);
int result_width = width - kernel_width + 1;
int result_index = result_y * result_width + result_x;
float result_value = 0.0;
for (int ky=0;ky<kernel_width;ky++) {
for (int kx=0;kx<kernel_width;kx++) {
int data_x = result_x + kx;
int data_y = result_y + ky;
int data_index = data_y * width + data_x;
int k_index = kx + ky * kernel_width;
float k_value = kernel_array[k_index];
float data_value = data[data_index];
result_value = result_value + k_value * data_value;
}
}
result[result_index] = result_value;
}
__kernel void to_gray(__global uchar* result, __global uchar* data, int channels) {
int base_index = get_global_id(0);
uchar r = (float) data[base_index * channels];
uchar g = (float) data[base_index * channels + 1];
uchar b = (float) data[base_index * channels + 2];
uchar gray = (r*0.299 + g*0.587 + b*0.114);
result[base_index] = gray;
}
__kernel void normalize_u8(__global float* result, __global uchar* data, float max) {
int index = get_global_id(0);
float value = (float) data[index];
float v = value/max;
result[index] = v;
}
__kernel void recover_u8(__global uchar* result, __global float* data, float max) {
int index = get_global_id(0);
float raw_value = data[index];
if (raw_value < 0.0) {
raw_value = -raw_value;
}
uchar value = (uchar) (raw_value / 8.0 * max);
result[index] = value;
}
__kernel void calculate_pair(
__global uchar* result,
__global uchar* src,
__global uchar* a_cols,
__global uchar* a_rows,
__global uchar* b_cols,
__global uchar* b_rows,
int x,
int y,
int width,
int height
) {
int index = get_global_id(0);
int a_src_x = x+a_cols[index];
int a_src_y = y+a_rows[index];
int a_src_index = a_src_y*width + a_src_x;
int b_src_x = x+b_cols[index];
int b_src_y = y+b_rows[index];
int b_src_index = b_src_y*width + b_src_x;
if (a_src_x < width && a_src_y < height && b_src_x < width && b_src_y < height) {
uchar a_value = src[a_src_index];
uchar b_value = src[b_src_index];
if (a_value > b_value) {
result[index] = 1;
} else {
result[index] = 0;
}
}
}
"#;
// (1) Define which platform and device(s) to use. Create a context,
// queue, and program then define some dims..
let platform_id = core::default_platform().unwrap();
let device_ids = core::get_device_ids(&platform_id, None, None).unwrap();
let device_id = device_ids[0];
let context_properties = ContextProperties::new().platform(platform_id);
let context = core::create_context(Some(&context_properties),
&[device_id], None, None).unwrap();
let src_cstring = CString::new(src).unwrap();
let program = core::create_program_with_source(&context, &[src_cstring]).unwrap();
core::build_program(&program, Some(&[device_id]), &CString::new("").unwrap(),
None, None).unwrap();
let queue = core::create_command_queue(&context, &device_id, None).unwrap();
CL {context, program, queue}
}
pub fn cl_crop(&self, data: &[u8], raw_width: i32, x: i32, y: i32, width: i32, height: i32, channels: i32)
-> ocl::Result<Vec<u8>>
{
let dims = [width as usize, height as usize, 1];
let size: usize = width as usize * height as usize * channels as usize;
let mut vec = vec![0u8; size];
let buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, size, Some(&vec))?
};
let raw_data = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, data.len(), Some(&data))?
};
// (3) Create a kernel with arguments matching those in the source above:
let kernel = core::create_kernel(&self.program, "crop")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&raw_data))?;
core::set_kernel_arg(&kernel, 2, ArgVal::scalar(&x))?;
core::set_kernel_arg(&kernel, 3, ArgVal::scalar(&y))?;
core::set_kernel_arg(&kernel, 4, ArgVal::scalar(&width))?;
core::set_kernel_arg(&kernel, 5, ArgVal::scalar(&height))?;
core::set_kernel_arg(&kernel, 6, ArgVal::scalar(&(channels as i32)))?;
core::set_kernel_arg(&kernel, 7, ArgVal::scalar(&(raw_width as i32)))?;
// (4) Run the kernel:
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 2, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// (5) Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
Ok(vec)
}
pub fn cl_to_gray(
&self,
data: &[u8],
channels: usize
) -> ocl::Result<Vec<u8>> {
let size: usize = data.len()/channels as usize;
let dims = [size, 1, 1];
let mut vec = vec![0u8; size];
let buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, size, Some(&vec))?
};
let raw_data = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, data.len(), Some(&data))?
};
// (3) Create a kernel with arguments matching those in the source above:
let kernel = core::create_kernel(&self.program, "to_gray")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&raw_data))?;
core::set_kernel_arg(&kernel, 2, ArgVal::scalar(&(channels as i32)))?;
// (4) Run the kernel:
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 2, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// (5) Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
Ok(vec)
}
pub fn cl_normalize(&self, data: &[u8], max: f32) -> ocl::Result<Vec<f32>> {
let mut vec = vec![0f32; data.len()];
let dims = [data.len(), 1, 1];
let result_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, data.len(), Some(&vec))?
};
let data_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, data.len(), Some(data))?
};
let kernel = core::create_kernel(&self.program, "normalize_u8")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&result_buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&data_buffer))?;
core::set_kernel_arg(&kernel, 2, ArgVal::scalar(&max))?;
// Run the kernel:
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 1, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &result_buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
Ok(vec)
}
pub fn cl_recover(&self, data: &[f32], max: f32) -> ocl::Result<Vec<u8>> {
let mut vec = vec![0u8; data.len()];
let dims = [data.len(), 1, 1];
let result_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, data.len(), Some(&vec))?
};
let data_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, data.len(), Some(data))?
};
let kernel = core::create_kernel(&self.program, "recover_u8")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&result_buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&data_buffer))?;
core::set_kernel_arg(&kernel, 2, ArgVal::scalar(&max))?;
// Run the kernel:
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 1, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &result_buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
Ok(vec)
}
pub fn cl_convolute(
&self,
src: &[f32],
width: usize,
height: usize,
convolution_kernel: &Kernel
) -> ocl::Result<Vec<f32>> {
let result_width = width - convolution_kernel.size() + 1;
let result_height = height - convolution_kernel.size() + 1;
let dims = [result_width, result_height, 1];
let mut vec = vec![0.0; result_width*result_height];
let result_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, result_width*result_height, Some(&vec))?
};
let data_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, src.len(), Some(&src))?
};
let kernel_array = convolution_kernel.flatten();
let kernel_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, convolution_kernel.elements(), Some(&kernel_array))?
};
// (3) Create a kernel with arguments matching those in the source above:
let kernel = core::create_kernel(&self.program, "convolute")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&result_buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&data_buffer))?;
core::set_kernel_arg(&kernel, 2, ArgVal::mem(&kernel_buffer))?;
core::set_kernel_arg(&kernel, 3, ArgVal::scalar(&(width as i32)))?;
core::set_kernel_arg(&kernel, 4, ArgVal::scalar(&(height as i32)))?;
core::set_kernel_arg(&kernel, 5, ArgVal::scalar(&(convolution_kernel.size() as i32)))?;
// (4) Run the kernel:
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 2, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// (5) Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &result_buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
Ok(vec)
}
pub fn cl_laplation(
&self,
src: &[u8],
width: usize,
height: usize,
convolution_kernel: &Kernel,
channels: usize
) -> ocl::Result<(usize, usize, f32, Vec<u8>)> {
let gray_data = self.cl_to_gray(src, channels)?;
let normalized_data = self.cl_normalize(&gray_data, 255.0)?;
let laplation_data = self.cl_convolute(&normalized_data, width, height, convolution_kernel)?;
let recovered_data = self.cl_recover(&laplation_data, 255.0)?;
let length = recovered_data.len();
let mut total = 0f64;
for pixel in &recovered_data {
total += *pixel as f64;
}
let avg = total/length as f64;
let mut variance = 0f64;
for pixel in &recovered_data {
variance += (*pixel as f64 - avg).powi(2);
}
let standard_deviation = (variance/length as f64).sqrt() as f32;
let result_width = width - convolution_kernel.size() + 1;
let result_height = height - convolution_kernel.size() + 1;
Ok((result_width, result_height, standard_deviation, recovered_data))
}
pub fn cl_resize() {}
pub fn cl_calculate_pair(
&self,
src: &[u8],
x: i32,
y: i32,
width: i32,
height: i32,
ax: Vec<i32>,
ay: Vec<i32>,
bx: Vec<i32>,
by: Vec<i32>
)
-> ocl::Result<Vec<i32>>
{
let mut vec = vec![2i32; 1024];
let dims = [1024, 1, 1];
let result_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_WRITE | flags::MEM_COPY_HOST_PTR, 1024, Some(&vec))?
};
let src_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, src.len(), Some(src))?
};
let ax_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, 1024, Some(&ax))?
};
let ay_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, 1024, Some(&ay))?
};
let bx_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, 1024, Some(&bx))?
};
let by_buffer = unsafe {
core::create_buffer(&self.context, flags::MEM_READ_ONLY | flags::MEM_COPY_HOST_PTR, 1024, Some(&by))?
};
let kernel = core::create_kernel(&self.program, "calculate_pair")?;
core::set_kernel_arg(&kernel, 0, ArgVal::mem(&result_buffer))?;
core::set_kernel_arg(&kernel, 1, ArgVal::mem(&src_buffer))?;
core::set_kernel_arg(&kernel, 2, ArgVal::mem(&ax_buffer))?;
core::set_kernel_arg(&kernel, 3, ArgVal::mem(&ay_buffer))?;
core::set_kernel_arg(&kernel, 4, ArgVal::mem(&bx_buffer))?;
core::set_kernel_arg(&kernel, 5, ArgVal::mem(&by_buffer))?;
core::set_kernel_arg(&kernel, 6, ArgVal::scalar(&x))?;
core::set_kernel_arg(&kernel, 7, ArgVal::scalar(&y))?;
core::set_kernel_arg(&kernel, 8, ArgVal::scalar(&width))?;
core::set_kernel_arg(&kernel, 9, ArgVal::scalar(&height))?;
// Run the kernel:
let now = Instant::now();
unsafe {
core::enqueue_kernel(&self.queue, &kernel, 1, None, &dims,
None, None::<core::Event>, None::<&mut core::Event>)?;
}
// Read results from the device into a vector:
unsafe {
core::enqueue_read_buffer(&self.queue, &result_buffer, true, 0, &mut vec,
None::<core::Event>, None::<&mut core::Event>)?;
}
println!("Calculate Pair: {:?}", now.elapsed().as_millis());
Ok(vec)
}
}<file_sep>extern crate eva_lib;
use eva_lib::mat::Mat;
use eva_lib::mat::pixel_description::Direction;
fn main() {
let mut mat = Mat::load_jpeg("examples/unfocus.jpg");
let mask = (0, 0, mat.cols, mat.rows);
let descriptions = mat.fast_search_features(30, &mask, Direction::Horizontal);
for desc in descriptions {
mat.draw_point(desc.coordinate, &mut vec![0u8, 255u8, 0u8, 255u8]);
}
mat.save_as_png("feature_points.png");
}
<file_sep>use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::io::BufWriter;
extern crate bmp;
extern crate png;
use jpeg_decoder::Decoder;
use jpeg_decoder::PixelFormat;
use std::time::{Instant};
use super::CL;
pub mod kernels;
pub mod pixel_description;
pub mod transform;
use pixel_description::PixelDescription;
use pixel_description::Direction;
lazy_static! {
static ref CL_INSTANCE: CL = CL::new();
}
#[derive(Debug, Clone)]
pub struct Mat {
pub cols: usize,
pub rows: usize,
pub bytes_per_pixel: usize,
// pub data: Vec<Vec<Vec<u8>>>,
pub pixels: Vec<u8>,
pub size: usize,
}
impl Mat {
pub fn new(w: usize, h: usize, color: Option<u8>)
-> Mat
{
let color = color.unwrap_or_else(
|| 0u8
);
let mut data = Vec::<u8>::with_capacity(w*h*3);
data.resize((w as usize) * (h as usize) * 3, color);
Mat::load_from_vec(data, w, h, 3)
}
pub fn create(w: usize, h: usize, color: Vec<u8>)
-> Mat
{
let mut data = Vec::<u8>::with_capacity(w*h*3);
for i in 0..(w*h) {
for chn in &color {
data.push(*chn);
}
}
Mat::load_from_vec(data, w, h, 3)
}
pub fn load_jpeg(path: &str)
-> Mat
{
let file = File::open(path).expect("failed to open file");
let mut decoder = Decoder::new(BufReader::new(file));
let raw_pixels = decoder.decode().expect("failed to decode image");
let metadata = decoder.info().unwrap();
let bytes_per_pixel = match metadata.pixel_format {
PixelFormat::L8 => 2,
PixelFormat::RGB24 => 3,
PixelFormat::CMYK32 => 4
};
Mat::load_from_vec(raw_pixels, metadata.width as usize, metadata.height as usize, bytes_per_pixel as usize)
}
pub fn save_as_bmp(&self, path: &str)
{
let mut bmp_image = bmp::Image::new(self.cols as u32, self.rows as u32);
for y in 0..(self.rows) {
for x in 0..(self.cols) {
let pixel = self.get_pixel_by_xy(x, y);
if self.bytes_per_pixel == 1 {
bmp_image.set_pixel(x as u32, y as u32, bmp::Pixel::new(pixel[0], pixel[0], pixel[0]));
} else if self.bytes_per_pixel == 3 {
bmp_image.set_pixel(x as u32, y as u32, bmp::Pixel::new(pixel[0], pixel[1], pixel[2]));
} else {
panic!("Image channels should be 1 or 3");
}
}
}
let _ = bmp_image.save(path).unwrap_or_else(|e| {
panic!("Failed to save: {}", e)
});
}
pub fn load_png(path: &str)
-> Mat
{
let decoder = png::Decoder::new(File::open(path).unwrap());
let (output_info, mut reader) = decoder.read_info().unwrap();
println!("{:?}", output_info.color_type);
let bytes = reader.info().bytes_per_pixel();
let mut buf = vec![0; output_info.buffer_size()];
let (width, height) = reader.info().size();
reader.next_frame(&mut buf).unwrap();
Mat::load_from_vec(buf, width as usize, height as usize, bytes)
}
pub fn save_as_png(&self, path: &str)
{
use png::HasParameters;
let path = Path::new(path);
let file = File::create(path).unwrap();
let ref mut w = BufWriter::new(file);
let mut encoder = png::Encoder::new(w, self.cols as u32, self.rows as u32); // Width is 2 pixels and height is 1.
if self.bytes_per_pixel == 1 {
// Save as grayscale picture
encoder.set(png::ColorType::Grayscale).set(png::BitDepth::Eight);
} else if self.bytes_per_pixel == 2 {
// Save as grayscale picture
encoder.set(png::ColorType::GrayscaleAlpha).set(png::BitDepth::Eight);
} else if self.bytes_per_pixel == 3 {
// Save as RGB picture
encoder.set(png::ColorType::RGB).set(png::BitDepth::Eight);
} else {
// Save as RGBA picture
encoder.set(png::ColorType::RGBA).set(png::BitDepth::Eight);
}
let mut writer = encoder.write_header().unwrap();
// An array containing a sequence.
writer.write_image_data(&self.pixels).unwrap(); // Save
}
pub fn load_from_vec(raw: Vec<u8>, width: usize, height: usize, bytes_per_pixel: usize)
-> Mat
{
let mut new_bytes_per_pixel = bytes_per_pixel;
let mut new_data = raw;
// println!("{:?}", new_bytes_per_pixel);
if bytes_per_pixel == 4usize || bytes_per_pixel == 2usize {
let mut vec = Vec::<u8>::with_capacity(width*height*(bytes_per_pixel-1));
for i in 0..width*height {
for p in 0..(bytes_per_pixel-1) {
vec.push(new_data[i*bytes_per_pixel+p]);
}
}
new_data = vec;
new_bytes_per_pixel = bytes_per_pixel - 1;
}
Mat {cols: width, rows: height, bytes_per_pixel: new_bytes_per_pixel, pixels: new_data, size: width*height}
}
pub fn crop(&self, x: usize, y: usize, width: usize, height: usize) -> Mat {
let new_data = CL_INSTANCE.cl_crop(&self.pixels, self.cols as i32, x as i32, y as i32, width as i32, height as i32, self.bytes_per_pixel as i32).unwrap();
Mat::load_from_vec(new_data, width, height, self.bytes_per_pixel)
}
// pub fn resize(&self, width: usize, height: usize)
// -> Mat
// {
// let scale_x = (self.cols as f32)/(width as f32);
// let scale_y = (self.rows as f32)/(height as f32);
// let mut new_data = vec![vec![vec![0u8; 4]; width]; height];
// let src_data = &self.data;
// for y in 0..height {
// for x in 0..width {
// let src_x = ((x as f32)*scale_x).round() as usize;
// let src_y = ((y as f32)*scale_y).round() as usize;
// if src_x < self.cols as usize && src_y < self.rows as usize {
// new_data[y][x] = src_data[src_y][src_x].to_vec();
// }
// }
// }
// let mat = Mat {cols: width as usize, rows: height as usize, bytes_per_pixel: self.bytes_per_pixel, data: new_data, size: height*width};
// mat
// }
pub fn merge(&mut self, other: &Mat, x: usize, y: usize) {
for row in 0..other.rows {
for col in 0..other.cols {
let pixel = other.get_pixel_by_xy(col, row);
// println!("{:?}", pixel);
self.set_pixel_by_xy(col+x, row+y, pixel);
}
}
}
pub fn rectangle(&self) {
}
// TODO
pub fn change_each_pixel(&mut self, closure: &Fn(usize, usize, Vec<u8>) -> Vec<u8>) {
for y in 0..(self.rows as usize) {
for x in 0..(self.cols as usize) {
let index = self.find_index(x, y);
let pixel = self.get_pixel(index);
let new_pixel = closure(x, y, pixel);
self.set_pixel(index, new_pixel);
}
}
}
pub fn find_index(&self, x: usize, y: usize) -> usize {
let result = y*self.cols + x;
// if result > 33177600 {
// println!("错的时候 Y: {}, Cols: {}", y, self.cols);
// }
result
}
pub fn get_pixel(&self, index: usize) -> Vec<u8> {
if index >= self.size {
return vec![0u8; self.bytes_per_pixel];
}
self.pixels.get(index*self.bytes_per_pixel..(index*self.bytes_per_pixel+self.bytes_per_pixel)).unwrap().to_vec()
}
pub fn set_pixel(&mut self, index: usize, pixel: Vec<u8>) {
if self.bytes_per_pixel != pixel.len() {
panic!(format!("The pixel should contain {} U8, but there are only {}", self.bytes_per_pixel, pixel.len()))
}
for i in 0..pixel.len() {
self.pixels[index*self.bytes_per_pixel+i] = pixel[i];
}
}
pub fn each_pixel(&self, closure: &Fn(usize, usize, Vec<u8>)) {
for y in 0..(self.rows as usize) {
for x in 0..(self.cols as usize) {
let index = self.find_index(x, y);
let pixel = self.get_pixel(index);
closure(x, y, pixel);
}
}
}
pub fn get_channel(&self, channel_number: usize)
-> Mat
{
let mut channel = self.clone();
channel.bytes_per_pixel = 1;
channel.change_each_pixel(
&|_, _, pixel| {
let mut new_vec = vec![0u8];
new_vec[0] = pixel[channel_number];
new_vec
}
);
channel
}
pub fn to_gray(&self)
-> Mat
{
let new_data = CL_INSTANCE.cl_to_gray(&self.pixels, self.bytes_per_pixel).unwrap();
Mat::load_from_vec(new_data, self.cols, self.rows, 1)
}
pub fn convolute(&self, kernel: kernels::Kernel)
// -> Vec<u8>
-> Mat
{
let new_cols = self.cols as usize - kernel.size() + 1;
let new_rows = self.rows as usize - kernel.size() + 1;
let result_size = new_cols * new_rows;
let mut result_pixels = Vec::<u8>::with_capacity(result_size);
let all_pixels = self.to_gray().get_channel(0);
let kernel_values = kernel.flatten();
let pixels = &all_pixels.pixels;
let mut unified_pixels = Vec::<f32>::with_capacity(pixels.len());
for pixel in pixels {
unified_pixels.push(*pixel as f32/255.0);
}
for i in 0..unified_pixels.len() {
let indexes_result = kernel.indexes(i, self.cols as usize, unified_pixels.len());
if indexes_result.0 {
let mut point_result = 0f32;
for i in 0..(kernel.elements()) {
let pixel_index = indexes_result.1[i];
point_result = unified_pixels[pixel_index] * kernel_values[i] + point_result;
}
let pixel = ((point_result/4.0)*255.0).abs();
result_pixels.push(pixel as u8);
}
}
Mat::load_from_vec(result_pixels, new_cols as usize, new_rows as usize, 1)
}
pub fn fast_search_features(&self, threshold: usize, mask: &(usize, usize, usize, usize), direction: Direction)
-> Vec<PixelDescription>
{
let mut descriptions = Vec::<PixelDescription>::new();
let now = Instant::now();
for y in (mask.1)..(mask.1+mask.3) {
for x in (mask.0)..(mask.0+mask.2) {
let (result, mut description) = PixelDescription::load_as_fast((x, y), self, threshold, &direction);
if result {
descriptions.push(description);
}
}
}
println!("");
println!("Spend ms on generate descriptions: {:?}", now.elapsed().as_millis());
let before_nms = Instant::now();
descriptions = self.nms(&mut descriptions);
println!("Spend ms on NMS:{}", before_nms.elapsed().as_millis());
let len = descriptions.len();
let before_calculate_pair = Instant::now();
for i in 0..descriptions.len() {
descriptions[i].calculate_pair(self, &direction);
}
println!("Spend ms on calculate pairs:{}", before_calculate_pair.elapsed().as_millis());
println!("Feature points:{:?}", len);
descriptions
}
// non maximum suppression(NMS)
fn nms(&self, descriptions: &mut Vec<PixelDescription>)
-> Vec<PixelDescription>
{
let window_size = 5;
let r = window_size/2;
println!("R = {:?}", r);
let mut current_descriptions = Vec::<PixelDescription>::new();
let len = descriptions.len();
println!("Total descriptions {:?}", len);
for desc_i in 0..len {
for other_i in 0..len {
if descriptions[other_i].coordinate != descriptions[desc_i].coordinate {
let xr = ((descriptions[desc_i].coordinate.0 as i32 - descriptions[other_i].coordinate.0 as i32)).abs();
let yr = ((descriptions[desc_i].coordinate.1 as i32 - descriptions[other_i].coordinate.1 as i32)).abs();
if (xr <= r) && (yr <= r) {
if descriptions[desc_i].maximum_value() >= descriptions[other_i].maximum_value() {
descriptions[other_i].remove();
}
}
}
}
}
for desc in descriptions {
// println!("{:?}", desc.removed);
if !(desc.removed) {
current_descriptions.push(desc.clone());
}
}
println!("Effective descriptions {:?}", current_descriptions.len());
current_descriptions
}
pub fn draw_point(&mut self, coordinate: (usize, usize), color: Vec<u8>) {
let mark = vec![(-3, 0),(-2, 0),(-1, 0),(3, 0),(2, 0),(1, 0),(0, -3),(0, -2),(0, -1),(0, 3),(0, 2),(0, 1)];
for xy in mark {
let y = coordinate.1 as i32 + xy.1;
let x = coordinate.0 as i32 + xy.0;
if x >= 0 || y >= 0 || x < self.cols as i32 || y < self.rows as i32 {
self.set_pixel_by_xy(x as usize, y as usize, color.to_vec());
}
}
}
pub fn draw_line(&mut self, end1: (usize, usize), end2: (usize, usize), color:&mut Vec<u8>) {
let distance = ((end1.0 as f32 - end2.0 as f32).powi(2) + (end1.1 as f32 - end2.1 as f32).powi(2)).sqrt().round() as f32;
let sin = (end2.1 as f32-end1.1 as f32)/distance;
let cos = (end2.0 as f32-end1.0 as f32)/distance;
for d in 0..(distance as usize) {
let x = (d as f32*cos).round() as usize;
let y = (d as f32*sin).round() as usize;
self.set_pixel_by_xy(x, y, color.to_vec());
}
}
pub fn set_pixel_by_xy(&mut self, x: usize, y: usize, pixel: Vec<u8>) {
if x < self.cols && y < self.rows {
let index = self.find_index(x, y);
self.set_pixel(index, pixel);
}
}
pub fn polarize(&self) -> Mat {
let mut new_image = self.clone();
new_image.change_each_pixel(&|_, _, vec| {
if vec[0] > 10u8 {
let mut new_value = vec[0] as u32 * 8;
if new_value > 255 { new_value = 255; }
return vec![new_value as u8, 255u8];
} else {
return vec![0u8, 255u8];
}
});
new_image
}
// pub fn rotate(&self, degree: f32)
// -> Mat
// {
// }
pub fn avg_mapping_vector(pairs: &Vec<(PixelDescription, PixelDescription)>) -> (f32, f32) {
let mut x_move_total = 0.0;
let mut y_move_total = 0.0;
for pair in pairs {
let x_move = pair.0.coordinate.0 as f32 - pair.1.coordinate.0 as f32;
let y_move = pair.0.coordinate.1 as f32 - pair.1.coordinate.1 as f32;
x_move_total += x_move;
y_move_total += y_move;
}
(x_move_total/pairs.len() as f32, y_move_total/pairs.len() as f32)
}
pub fn move_mat(dist: &mut Mat, src: &Mat, vec: (f32, f32)) {
for y in 0..src.rows {
for x in 0..src.cols {
let dist_x = (x as f32 + vec.0).round() as usize;
let dist_y = (y as f32 + vec.1).round() as usize;
if dist_x < dist.cols as usize && dist_y < dist.rows as usize {
// dist.data[dist_y][dist_x] = src.data[y as usize][x as usize].to_vec();
dist.set_pixel_by_xy(dist_x, dist_y, src.get_pixel_by_xy(x, y));
}
}
}
}
pub fn get_vector(desc_a: &PixelDescription, desc_b: &PixelDescription) -> (f32, f32) {
(desc_b.coordinate.0 as f32 - desc_a.coordinate.0 as f32, desc_b.coordinate.1 as f32 - desc_a.coordinate.1 as f32)
}
pub fn add_padding(&self, width: usize) -> Mat {
let mut colors = Vec::<Vec<u8>>::new();
for x in (0..self.cols) {
colors.push(self.get_pixel_by_xy(x, 0));
colors.push(self.get_pixel_by_xy(x, self.rows));
}
let mut avg_color = vec![0usize; self.bytes_per_pixel];
for color in &colors {
for (i, chn) in color.iter().enumerate() {
avg_color[i] += *chn as usize;
}
}
let mut new_color = vec![0u8; self.bytes_per_pixel];
for (i, sum_chn) in avg_color.iter().enumerate() {
new_color[i] = (avg_color[i]/colors.len()) as u8;
}
let mut new_image = Mat::create(self.cols + width*2, self.rows + width*2, new_color);
new_image.merge(self, width, width);
new_image
}
pub fn region_vector(x: usize, y: usize, pairs: &Vec<(PixelDescription, PixelDescription)>, direction: Direction) -> (f32, f32) {
let mut left_pair: Option<&(PixelDescription, PixelDescription)> = None;
for pair in pairs {
if (left_pair.is_none() || (pair.0.coordinate.0 > left_pair.unwrap().0.coordinate.0)) && pair.0.coordinate.0 <= x {
left_pair = Some(pair);
}
}
let mut right_pair: Option<&(PixelDescription, PixelDescription)> = None;
for pair in pairs {
if (right_pair.is_none() || (pair.0.coordinate.0 < right_pair.unwrap().0.coordinate.0)) && pair.0.coordinate.0 > x {
right_pair = Some(pair);
}
}
if left_pair.is_none() {
let pair = right_pair.unwrap();
return Mat::get_vector(&pair.0, &pair.1);
}
if right_pair.is_none() {
let pair = left_pair.unwrap();
return Mat::get_vector(&pair.0, &pair.1);
}
let left_pair = left_pair.unwrap();
let right_pair = right_pair.unwrap();
let left_right_distance = right_pair.0.coordinate.0 - left_pair.0.coordinate.0;
let left_distance = x - left_pair.0.coordinate.0;
let right_distance = right_pair.0.coordinate.0 - x;
let right_weight = left_distance as f32/left_right_distance as f32;
let left_weight = right_distance as f32/left_right_distance as f32;
let left_vector = Mat::get_vector(&left_pair.0, &left_pair.1);
let right_vector = Mat::get_vector(&right_pair.0, &right_pair.1);
return (left_vector.0*left_weight + right_vector.0*right_weight, left_vector.1*left_weight + right_vector.1*right_weight);
}
pub fn move_mat_by_multi_points(dist: &mut Mat, src: &Mat, avg_vector: (f32, f32), points: &Vec<(PixelDescription, PixelDescription)>) {
for y in 0..src.rows {
// println!("{:?}", y);
for x in 0..src.cols {
let dist_x = x as f32 + avg_vector.0;
let dist_y = y as f32 + avg_vector.1;
if dist_x >= 0.0f32 && dist_x < dist.cols as f32 && dist_y >= 0.0f32 && dist_y < dist.rows as f32 {
let dist_x = dist_x.round() as usize;
let dist_y = dist_y.round() as usize;
let vec = Mat::region_vector(dist_x, dist_y, points, Direction::Vertical);
// println!("{:?}", vec);
let src_x = (dist_x as f32 + vec.0).round() as i32;
let src_y = (dist_y as f32 + vec.1).round() as i32;
if src_x >= 0 && src_y >= 0 {
dist.set_pixel_by_xy(dist_x, dist_y, src.get_pixel_by_xy(src_x as usize, src_y as usize));
}
}
}
}
}
pub fn get_pixel_by_xy(&self, x: usize, y: usize) -> Vec<u8> {
let index = self.find_index(x, y);
self.get_pixel(index)
}
pub fn elements(&self) -> u32 {
self.rows as u32 * self.cols as u32
}
}
pub trait VecOperators<T> {
fn add(&self, other: T) -> T;
fn times(&self, factor: f32) -> T;
}
impl VecOperators<Vec<u8>> for Vec<u8> {
fn add(&self, other: Vec<u8>) -> Vec<u8> {
let mut new_vec = Vec::with_capacity(self.len());
for i in 0..self.len() {
new_vec.push(((self[i] as f32 + other[i] as f32)/2.0).round() as u8);
}
new_vec
}
fn times(&self, factor: f32) -> Vec<u8> {
let mut new_vec = Vec::with_capacity(self.len());
for i in 0..self.len() {
new_vec.push((self[i] as f32 * factor).round() as u8);
}
new_vec
}
}<file_sep>extern crate eva_lib;
use eva_lib::mat;
use eva_lib::mat::Mat;
use mat::pixel_description::PixelDescription;
use rand::Rng;
use std::mem;
fn main() {
let left = mat::Mat::load_png("examples/tests/6pics/1.png");
let right = mat::Mat::load_png("examples/tests/6pics/0.png");
let (result, x, y) = eva_lib::stitch_left_right(&left, &right);
result.save_as_png("examples/tests/6pics/final_result.png");
// let top = mat::Mat::load_jpeg("examples/tests/top.jpg");
// let bottom = mat::Mat::load_jpeg("examples/tests/bottom.jpg");
// let result = eva_lib::stitch_top_bottom(top, bottom);
// result.save_as_png("lib_example_top_bottom.png");
}
// fn get_img() -> Vec<u8> {
// let left = mat::Mat::load_jpeg("examples/tests/4k.jpg");
// std::thread::sleep_ms(20000);
// println!("==========================================");
// left.flatten()
// }
| ae86083d8cb3c5dae8c7d2ba53753e1a01f6d3e5 | [
"TOML",
"Rust"
] | 10 | Rust | ZackYang/EVA_LIB | 94ec098b6a26b3c5a72b4164e3fa047a96f90253 | 4120dc4ecf08ed01e11919b21e09693ed276fcfa |
refs/heads/master | <repo_name>iury123/BluetoothDaggerApp<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/utils/Utils.java
package com.example.iurymiguel.daggerapp.utils;
import android.content.Context;
import android.widget.Toast;
public class Utils {
private static Toast sToast;
public static void showToast(Context context, String message, int duration) {
if (sToast != null) {
sToast.cancel();
}
sToast = Toast.makeText(context, message, duration);
sToast.show();
}
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/dagger/modules/ActivityModule.java
package com.example.iurymiguel.daggerapp.dagger.modules;
import com.example.iurymiguel.daggerapp.views.activities.MainActivity;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
@Module
public abstract class ActivityModule {
@ContributesAndroidInjector(modules = MainActivityFragmentsModule.class)
abstract MainActivity mainActivity();
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/broadcastReceivers/BluetoothStateListener.java
package com.example.iurymiguel.daggerapp.broadcastReceivers;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BluetoothStateListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
Intent i = new Intent("onBluetoothStateChanged");
i.putExtra("state", intent
.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1));
context.sendBroadcast(i);
}
}
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/dagger/components/AppComponent.java
package com.example.iurymiguel.daggerapp.dagger.components;
import android.app.Application;
import com.example.iurymiguel.daggerapp.application.MyApplication;
import com.example.iurymiguel.daggerapp.dagger.modules.ActivityModule;
import com.example.iurymiguel.daggerapp.dagger.modules.ViewModelModule;
import javax.inject.Singleton;
import dagger.BindsInstance;
import dagger.Component;
import dagger.android.AndroidInjector;
import dagger.android.support.AndroidSupportInjectionModule;
@Component(modules =
{
ViewModelModule.class,
ActivityModule.class,
AndroidSupportInjectionModule.class
})
@Singleton
public interface AppComponent extends AndroidInjector<MyApplication> {
@Component.Builder
interface Builder {
@BindsInstance
AppComponent.Builder application(Application application);
AppComponent build();
}
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/application/MyApplication.java
package com.example.iurymiguel.daggerapp.application;
import com.example.iurymiguel.daggerapp.dagger.components.DaggerAppComponent;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
public class MyApplication extends DaggerApplication {
@Override
public void onCreate() {
super.onCreate();
}
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent
.builder()
.application(this)
.build();
}
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/views/activities/MainActivity.java
package com.example.iurymiguel.daggerapp.views.activities;
import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.example.iurymiguel.daggerapp.R;
import com.example.iurymiguel.daggerapp.databinding.ActivityMainBinding;
import com.example.iurymiguel.daggerapp.factories.ViewModelFactory;
import com.example.iurymiguel.daggerapp.utils.TimeoutHandler;
import com.example.iurymiguel.daggerapp.utils.Utils;
import com.example.iurymiguel.daggerapp.viewModels.MainViewModel;
import com.example.iurymiguel.daggerapp.views.fragments.DeviceDetailsFragment;
import com.example.iurymiguel.daggerapp.views.fragments.DevicesListFragment;
import javax.inject.Inject;
import dagger.Lazy;
import dagger.android.support.DaggerAppCompatActivity;
public class MainActivity extends DaggerAppCompatActivity {
@Inject
ViewModelFactory mViewModelFactory;
@Inject
Lazy<TimeoutHandler> mTimeoutHandler;
private ActivityMainBinding mBinding;
private MainViewModel mMainViewModel;
private BluetoothAdapter mBluetoothAdapter;
private final int REQUEST_ENABLE_BT = 1;
private final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
private final BroadcastReceiver mOnBluetoothStateChangeListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case BluetoothAdapter.STATE_TURNING_ON:
Utils.showToast(context, "Bluetooth ligando.",
Toast.LENGTH_SHORT);
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Utils.showToast(context, "Bluetooth desligando.",
Toast.LENGTH_SHORT);
break;
case BluetoothAdapter.STATE_ON:
Utils.showToast(context, "Bluetooth ligado.",
Toast.LENGTH_SHORT);
break;
case BluetoothAdapter.STATE_OFF:
Utils.showToast(context, "Bluetooth desligado.",
Toast.LENGTH_SHORT);
break;
default:
}
}
};
private final BroadcastReceiver mOnDeviceFoundListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i("DDD", device.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mMainViewModel = ViewModelProviders.of(this, mViewModelFactory)
.get(MainViewModel.class);
registerBroadcasts();
checkIfHasLocationPermission();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Utils.showToast(this, "Bluetooth ativado.",
Toast.LENGTH_SHORT);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterBroadcasts();
}
private void initializeBluetooth() {
if (!isThereBluetooth()) {
Utils.showToast(this, "O dispositivo não possui Bluetooth.",
Toast.LENGTH_SHORT);
} else if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
private boolean isThereBluetooth() {
mBluetoothAdapter = mMainViewModel.getMyBluetoothManager()
.getBluetoothAdapter();
return (mBluetoothAdapter != null);
}
private void registerBroadcasts() {
registerReceiver(mOnBluetoothStateChangeListener,
new IntentFilter("onBluetoothStateChanged"));
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mOnDeviceFoundListener, filter);
}
private void unregisterBroadcasts() {
unregisterReceiver(mOnBluetoothStateChangeListener);
unregisterReceiver(mOnDeviceFoundListener);
}
private void checkIfHasLocationPermission() {
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Utils.showToast(this, "É necessário habilitar a permissão" +
" de localização para o correto funcionamento do app", Toast.LENGTH_LONG);
mTimeoutHandler.get().startTimer(this::requestPermissions, 4000);
} else {
requestPermissions();
}
} else {
initializeBluetooth();
}
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
initializeBluetooth();
}
break;
}
}
}
}
<file_sep>/app/src/main/java/com/example/iurymiguel/daggerapp/views/fragments/DeviceDetailsFragment.java
package com.example.iurymiguel.daggerapp.views.fragments;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.iurymiguel.daggerapp.R;
import com.example.iurymiguel.daggerapp.bluetooth.MyBluetoothManager;
import com.example.iurymiguel.daggerapp.factories.ViewModelFactory;
import com.example.iurymiguel.daggerapp.viewModels.MainViewModel;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
public class DeviceDetailsFragment extends DaggerFragment {
@Inject ViewModelFactory mViewModelFactory;
private MainViewModel mMainViewModel;
public DeviceDetailsFragment() {
// Required empty public constructor
}
public static DeviceDetailsFragment newInstance() {
DeviceDetailsFragment fragment = new DeviceDetailsFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMainViewModel = ViewModelProviders.of(getActivity(), mViewModelFactory).get(MainViewModel.class);
Log.i("AAA2", mMainViewModel.toString());
Log.i("AAA3", mMainViewModel.getMyBluetoothManager().toString());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_device_details, container, false);
}
}
| a742d5dfbe9ac1e23e1c4ef4a563cd954e0a3642 | [
"Java"
] | 7 | Java | iury123/BluetoothDaggerApp | 9fc434943230efff353c8e7981218d4364580c1e | 68c3795553d10c9ae4b6dbca1cd02d2da9b67880 |
refs/heads/master | <file_sep>import React from 'react'
import './index.css'
function Header() {
return(
<div>
<header className="header-section">
<img className="image-section" src="http://www.pngall.com/wp-content/uploads/2016/05/Trollface.png" alt="Problem" />
<h3>Meme Generator</h3>
</header>
</div>
)
}
export default Header | 4d83ee1730684530bdee956ec033a867c4683cc1 | [
"JavaScript"
] | 1 | JavaScript | Joseph-Maninang/react-meme-generator | 71505c05f49df22511781b44cece681076f798d6 | f525c8f69c202fd63f69394dcf0eb1f4f8c3741d |
refs/heads/main | <repo_name>MarkCirineo/word-guess<file_sep>/assets/js/script.js
var startButton = $(".start-button");
var timerCounter = $(".timer-count");
var wordBlanks = $(".word-blanks");
var wins = $(".win");
var losses = $(".lose");
var resetButton = $(".reset-button");
var secondsLeft = 10;
var randomWord = "";
var randomWordArr = [];
var underscore = [];
var numOfBlanks = 0;
var win = false;
var timer;
var winCount = 0;
var lossCount = 0;
function startTimer() {
timer = setInterval(() => {
secondsLeft--;
timerCounter.text(secondsLeft)
if (secondsLeft > 0) {
if(win && secondsLeft > 0) {
clearInterval(timer)
// console.log("win")
gameWin();
}
}
if (secondsLeft === 0) {
clearInterval(timer);
gameLoss();
}
}, 1000);
}
var words = ["blue", "green", "purple", "orange", "red", "yellow", "brown"];
function startGame() {
win = false;
secondsLeft = 10;
startTimer();
randomWord = words[Math.floor(Math.random() * words.length)];
randomWordArr = randomWord.split("");
numOfBlanks = randomWordArr.length;
underscore = []
console.log(randomWordArr)
for (let i = 0; i < numOfBlanks; i++) {
underscore.push("_");
}
wordBlanks.text(underscore.join(" "))
}
function checkLetter(letter) {
var letterInWord = false;
for (var i = 0; i < numOfBlanks; i++) {
if (randomWord[i] === letter) {
letterInWord = true;
}
}
if (letterInWord) {
for (var j = 0; j < numOfBlanks; j++) {
if (randomWord[j] === letter) {
underscore[j] = letter;
}
}
wordBlanks.text(underscore.join(" "))
}
}
document.addEventListener("keydown", function (e) {
if (secondsLeft === 0) {
return;
}
var key = e.key.toLowerCase();
var alphabet = "abcdefghijklmnopqrstuvwxyz ".split("");
if (alphabet.includes(key)) {
var letterGuessed = e.key;
checkLetter(letterGuessed);
if (randomWord === underscore.join("")) {
win = true;
// console.log(win);
}
}
})
startButton.on("click", startGame);
function gameWin() {
wordBlanks.text("YOU WIN!")
winCount++;
// console.log(winCount)
wins.text(winCount);
localStorage.setItem("wins", winCount);
}
function gameLoss() {
wordBlanks.text("YOU LOSE!")
lossCount++;
losses.text(lossCount);
localStorage.setItem("losses", lossCount);
}
function getWins() {
var storedWins = localStorage.getItem("wins")
if (storedWins === null) {
winCount = 0;
} else {
winCount = storedWins;
}
wins.text(winCount);
}
function getLosses() {
var storedLosses = localStorage.getItem("losses");
if (storedLosses === null) {
lossCount = 0;
} else {
lossCount = storedLosses;
}
losses.text(lossCount);
}
function init() {
getWins();
getLosses();
}
init();
function resetScore() {
winCount = 0;
lossCount = 0;
wins.text(winCount);
losses.text(lossCount);
localStorage.setItem("wins", winCount);
localStorage.setItem("losses", lossCount);
}
resetButton.on("click", resetScore); | 17388141bbdd05b3dcbd3233a8eebedc34e72d5b | [
"JavaScript"
] | 1 | JavaScript | MarkCirineo/word-guess | 4757dca53b082df35168f696528645ff751e4206 | 881189d2dbe8bcb2e6f9079aa946c988730419fb |
refs/heads/master | <file_sep>import React from 'react';
import './Game.scss';
import Board from '../Board';
class Game extends React.Component {
constructor(props) {
super(props);
this.placeToken = this.placeToken.bind(this);
this.endTurn = this.endTurn.bind(this);
this.checkWin = this.checkWin.bind(this);
let playerColors;
if (props.playerOneColor === 'red') {
playerColors = ['red', 'black'];
} else {
playerColors = ['black', 'red'];
}
this.state = {
currentPlayer: 0,
playerColors: playerColors,
maxTurnsRemaining: 41,
gameData: [
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null],
[null, null, null, null, null, null]
],
}
}
placeToken(col, row, value) {
this.setState(prevState => {
let updatedGameData = prevState.gameData;
updatedGameData[col][row] = value;
return {
gameData: updatedGameData,
maxTurnsRemaining: prevState.maxTurnsRemaining - 1,
};
}, () => {
const { end } = this.props;
const result = this.checkWin(col, row);
if (result) {
end(result);
} else {
this.endTurn();
}
});
}
endTurn() {
this.setState(prevState => {
if (prevState.currentPlayer === 0) {
return {
currentPlayer: 1
};
} else {
return {
currentPlayer: 0
};
}
});
}
checkWin(col, row) {
const {
maxTurnsRemaining,
currentPlayer,
playerColors,
} = this.state;
if (maxTurnsRemaining <= 0) {
return 'Tie Game';
} else {
let horizontalSum = 0, // -
verticalSum = 0, // |
rtlSum = 0, // /
ltrSum = 0; // \
for (let i = -3; i <= 3; i++) {
// Check Horizontal Win Condition
horizontalSum = this.computeSum(col + i, row, playerColors[currentPlayer], horizontalSum);
if (horizontalSum >= 4) {
return `Player ${currentPlayer + 1} wins!`;
}
// Check Vertical Win Condition
verticalSum = this.computeSum(col, row + i, playerColors[currentPlayer], verticalSum);
if (verticalSum >= 4) {
return `Player ${currentPlayer + 1} wins!`;
}
// Check Right to Left Diagonal Win Condition
rtlSum = this.computeSum(col + i, row + i, playerColors[currentPlayer], rtlSum);
if (rtlSum >= 4) {
return `Player ${currentPlayer + 1} wins!`;
}
// Check Left to Right Diagonal Win Condition
ltrSum = this.computeSum(col + i, row - i, playerColors[currentPlayer], ltrSum);
if (ltrSum >= 4) {
return `Player ${currentPlayer + 1} wins!`;
}
}
}
return false;
}
computeSum(col, row, val, sum) {
const { gameData } = this.state;
if ((col >= 0 && col <= 6) && (row >= 0 && row <= 5)) {
if (gameData[col][row] === val) {
return sum + 1;
}
else {
return 0;
}
}
return sum;
}
render() {
const {
currentPlayer,
playerColors,
gameData,
} = this.state;
return (
<div className="game">
<div className="game__controls">
<h1 className={`game__controls__current-player ${playerColors[currentPlayer]}`}>Player {currentPlayer + 1}</h1>
<p className="game__controls__label">place a token.</p>
</div>
<Board
gameData={gameData}
playerColors={playerColors}
currentPlayer={currentPlayer}
placeToken={this.placeToken}
/>
</div>
);
}
}
export default Game;
<file_sep>import React from 'react';
import './Space.scss';
function Space(props) {
return (
<div className="space">
<div className ={`space__icon ${props.value ? props.value : ''}`} />
</div>
);
}
export default Space;
<file_sep>import React from 'react';
import './Board.scss';
import Column from '../Column';
function Board(props) {
const {
currentPlayer,
playerColors,
gameData,
placeToken,
} = props;
return (
<div className="board">
{gameData.map((col, i) => (
<Column
key={i}
index={i}
currentPlayer={currentPlayer}
playerColors={playerColors}
columnData={col}
placeToken={placeToken}
/>
))}
</div>
);
}
export default Board;
<file_sep>import React from 'react';
import './Column.scss';
import Space from '../Space';
class Column extends React.Component {
constructor(props) {
super(props);
this.selectColumn = this.selectColumn.bind(this);
this.state = {
tokenCount: 0,
}
}
selectColumn() {
const {
index,
currentPlayer,
playerColors,
placeToken,
} = this.props;
const { tokenCount } = this.state;
if (tokenCount < 6 ) {
placeToken(index, tokenCount, playerColors[currentPlayer]);
this.setState(prevState => ({
tokenCount: prevState.tokenCount + 1,
}));
}
}
render() {
const {
columnData,
} = this.props;
return (
<div onClick={this.selectColumn} className="column">
{columnData.slice(0).reverse().map((val, i) => (
<Space
key={i}
value={val}
/>
))}
</div>
);
}
}
export default Column;
| ca16f086cdbf360654758f95f2007d3eca28206f | [
"JavaScript"
] | 4 | JavaScript | Gtallant/Connect-Four | a3d93cc26b4e813554d55baf6a0aad0aaccc474a | 80821074fd6e26ae1642d843d8ebf79c9f52fa4a |
refs/heads/master | <repo_name>ramp-cyb/LAY.js<file_sep>/src/method/level.js
(function() {
"use strict";
LAY.level = function ( path ) {
return LAY.$pathName2level[ path ];
};
})();
<file_sep>/src/helper/findRenderCall.js
(function(){
"use strict";
LAY.$findRenderCall = function( prop, level ) {
var
renderCall,
multipleTypePropMatchDetails;
if ( level.isHelper ) {
return "";
} else if ( !LAY.$checkIsValidUtils.propAttr( prop ) ||
( [ "centerX", "right", "centerY", "bottom" ] ).indexOf( prop ) !== -1 ||
LAY.$shorthandPropsUtils.checkIsDecentralizedShorthandProp( prop ) ) {
return undefined;
} else {
multipleTypePropMatchDetails = LAY.$findMultipleTypePropMatchDetails(
prop );
if ( multipleTypePropMatchDetails ) {
return multipleTypePropMatchDetails[ 1 ];
}
renderCall =
LAY.$shorthandPropsUtils.getShorthandPropCenteralized(
prop );
if ( renderCall !== undefined ) {
if ( level.isGpu &&
( renderCall === "x" ||
renderCall === "y" ||
renderCall === "transform" ) ) {
return "positionAndTransform";
} else {
return renderCall;
}
} else {
if ( prop.startsWith("text") &&
( !level.part || level.part.type === "none" ) ) {
return undefined;
}
}
return prop;
}
};
})();
<file_sep>/LAY.js
/*
* Copyright 2015 <NAME>
* @license: MIT
* @author: <NAME> <<EMAIL>>
*/
(function () {
"use strict";
window.LAY = {
/* version is a method in order
to maintain the consistency of
only method accesses from the user
During build (gulp) the version will be set
so leave the string "0.8.14" just as is. */
version: function(){ return "0.8.14"; },
$pathName2level: {},
$newlyInstalledStateLevelS: [],
$newlyUninstalledStateLevelS: [],
$newLevelS: [],
$recalculateDirtyAttrValS: [],
$renderDirtyPartS: [],
$prevFrameTime: 0,
$newManyS: [],
$isRendering: false,
$isGpuAccelerated: undefined,
$isBelowIE9: undefined,
$numClog: 0,
$isSolving: false,
$isSolveRequiredOnRenderFinish: false,
$isOkayToEstimateWhitespaceHeight: true,
// The below refer to dimension
// dirty parts whereby the dimensions
// depend upon the child parts
$naturalHeightDirtyPartS: [],
$naturalWidthDirtyPartS: [],
$relayoutDirtyManyS: [],
$isDataTravellingShock: false,
$isDataTravelling: false,
$dataTravelDelta: 0.0,
$dataTravellingLevel: undefined,
$dataTravellingAttrInitialVal: undefined,
$dataTravellingAttrVal: undefined
};
})();
// Polyfill for Array.indexOf must be implemented
// before the LAY library executes
//
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.io/#x15.4.4.14
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var k;
// 1. Let O be the result of calling ToObject passing
// the this value as the argument.
if (this === null) {
throw new TypeError('"" is null or not defined');
}
var O = Object(this);
// 2. Let lenValue be the result of calling the Get
// internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If len is 0, return -1.
if (len === 0) {
return -1;
}
// 5. If argument fromIndex was passed let n be
// ToInteger(fromIndex); else let n be 0.
var n = +fromIndex || 0;
if (Math.abs(n) === Infinity) {
n = 0;
}
// 6. If n >= len, return -1.
if (n >= len) {
return -1;
}
// 7. If n >= 0, then Let k be n.
// 8. Else, n<0, Let k be len - abs(n).
// If k is less than 0, then let k be 0.
k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
// 9. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the
// HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
// i. Let elementK be the result of calling the Get
// internal method of O with the argument ToString(k).
// ii. Let same be the result of applying the
// Strict Equality Comparison Algorithm to
// searchElement and elementK.
// iii. If same is true, return k.
if (k in O && O[k] === searchElement) {
return k;
}
k++;
}
return -1;
};
}
( function () {
"use strict";
// The naming convention:
// attr -> string attr name
// attrVal -> class AttrVal
LAY.AttrVal = function ( attr, level ) {
// undefined initializations:
// (1) performance (http://jsperf.com/objects-with-undefined-initialized-properties/2)
// (2) readability
this.level = level;
this.val = undefined;
this.prevVal = undefined;
this.isTakeValReady = undefined;
this.attr = attr;
this.isRecalculateRequired = true;
this.calcVal = undefined;
this.transCalcVal = undefined;
this.startCalcVal = undefined;
this.transition = undefined;
this.isTransitionable = false;
this.isForceRecalculate = false;
// if the attr is of "<state>.onlyif"
// the below will store the state name <state>
this.onlyIfStateName = getStateNameOfOnlyIf( attr );
this.isStateProjectedAttr = checkIsStateProjectedAttr( attr );
this.isEventReadonlyAttr =
LAY.$eventReadonlyUtils.checkIsEventReadonlyAttr( attr );
this.renderCall =
level && ( level.isPart ) &&
( LAY.$findRenderCall( attr, level ) );
this.takerAttrValS = [];
this.eventReadonlyEventType2boundFnHandler = {};
}
/*
* For attrs which are of type state ( i.e state.<name> )
* Return the name component.
* Else return the empty string.
*/
function getStateNameOfOnlyIf ( attr ) {
if ( attr.lastIndexOf( ".onlyif" ) !== -1 &&
!attr.startsWith("data.") &&
!attr.startsWith("row.") ) {
return attr.slice(0, attr.indexOf(".") );
} else {
return "";
}
}
/*
* For attrs which are of type "when"
* ( i.e when.<eventType>.<eventNum> )
* Return the event type component.
* Else return the empty string.
*/
function getWhenEventTypeOfAttrWhen ( attr ) {
return attr.startsWith( "when." ) ?
attr.slice( 5, attr.length - 2 ) : "";
}
/*
* For attrs which are of type "transition"
* ( i.e transition.<prop>.<>.<> )
* Return the event type component.
* Else return the empty string.
*/
function getTransitionPropOfAttrTransition( attr ) {
return attr.startsWith( "transition." ) ?
attr.slice( 11, attr.indexOf(".", 11 ) ) : "";
}
function checkIsStateProjectedAttr( attr ) {
var i = attr.indexOf( "." );
if ( LAY.$checkIsValidUtils.propAttr( attr ) &&
[ "centerX", "right",
"centerY", "bottom" ].indexOf( attr ) === -1 ) {
return true;
} else if (
[ "formation", "filter", "sort" ].indexOf ( attr ) !== -1 ) {
return true;
} else {
var prefix = attr.slice( 0, i );
return ( ( [ "when", "transition", "fargs", "sort", "$$num", "$$max" ] ).indexOf(
prefix ) !== -1 );
}
}
/* TODO: update this doc below along with its slash-asterisk
formatting
Returns true if the value is different,
false otherwise */
LAY.AttrVal.prototype.update = function ( val ) {
this.val = val;
if ( !LAY.identical( val, this.prevVal ) ) {
if ( this.prevVal instanceof LAY.Take ) {
this.takeNot( this.prevVal );
}
this.isTakeValReady = false;
this.requestRecalculation();
return true;
}
};
/*
* Request the level corresponding to the given AttrVal
* to recalculate this AttrVal.
*/
LAY.AttrVal.prototype.requestRecalculation = function () {
this.isRecalculateRequired = true;
if ( this.level ) { // check for empty level
LAY.$arrayUtils.pushUnique(
LAY.$recalculateDirtyAttrValS, this );
// this.level.addRecalculateDirtyAttrVal( this );
}
};
/*
* Force the level corresponding to the given AttrVal
* to recalculate this AttrVal.
*/
LAY.AttrVal.prototype.forceRecalculation = function () {
this.isForceRecalculate = true;
this.requestRecalculation();
};
LAY.AttrVal.prototype.checkIsTransitionable = function () {
return this.renderCall &&
( this.startCalcVal !== this.calcVal ) &&
(
(
( typeof this.startCalcVal === "number" )
&&
( typeof this.calcVal === "number" )
)
||
(
( this.startCalcVal instanceof LAY.Color )
&&
( this.calcVal instanceof LAY.Color )
)
) &&
this.attr !== "zIndex";
};
/*
*
* Recalculate the value of the attr value.
* Propagate the change across the LOM (LAY object model)
* if the change in value produces a change.
* For constraint (take) based attributes, recalculate the
* value, for non constraint based use the `value` parameter
* as the change.
* Return true if calculation successful, false if
* a circular reference rendered it unsuccessful
*/
LAY.AttrVal.prototype.recalculate = function () {
var
isDirty = false,
recalcVal,
level = this.level,
part = level.part,
many = level.manyObj,
attr = this.attr,
i, len;
if ( attr.charAt( 0 ) === "$" ) {
if ( LAY.$checkIfImmidiateReadonly( attr ) ) {
this.val = part.getImmidiateReadonlyVal( attr );
}
}
if ( this.val instanceof LAY.Take ) { // is LAY.Take
if ( !this.isTakeValReady ) {
this.isTakeValReady = this.take();
// if the attrval has not been taken
// as yet then there is chance that
// the giver attrval has not been
// initialized as yet. Thus we
// skip a round of solving to
// let the other attrvals complete calculation
return false;
}
recalcVal = this.val.execute( this.level );
if ( attr.startsWith("data.") ||
attr.startsWith("row.") ) {
recalcVal = LAY.$clone( recalcVal );
}
if ( !LAY.identical( recalcVal, this.calcVal ) ) {
isDirty = true;
this.calcVal = recalcVal;
}
} else {
if ( attr.startsWith("data.") ||
attr.startsWith("row.") ) {
this.val = LAY.$clone( this.val );
}
if ( !LAY.identical( this.val, this.calcVal ) ) {
isDirty = true;
this.calcVal = this.val;
}
}
if ( this.isForceRecalculate ) {
isDirty = true;
}
/*
switch ( attr ) {
case "scrollX":
// TODO: investigate the below code block's
// redundancy
this.transCalcVal =
this.level.part.node.scrollLeft;
if ( level.attr2attrVal.$scrolledX ) {
level.$changeAttrVal( "$scrolledX",
this.calcVal );
}
isDirty = true;
break;
case "scrollY":
// TODO: investigate the below code block's
// redundancy
this.transCalcVal =
this.level.part.node.scrollTop;
if ( level.attr2attrVal.$scrolledY ) {
level.$changeAttrVal( "$scrolledY",
this.calcVal );
}
isDirty = true;
break;
}
*/
// rows is always dirty when recalculated
// as changes made to rows would have rows
// retain the same pointer to the array
if ( attr === "rows" ) {
isDirty = true;
level.attr2attrVal.filter.forceRecalculation();
}
if ( isDirty ) {
var
stateName = this.onlyIfStateName,
whenEventType = getWhenEventTypeOfAttrWhen( attr ),
transitionProp = getTransitionPropOfAttrTransition( attr );
this.prevVal = this.val;
for ( i = 0, len = this.takerAttrValS.length; i < len; i++ ) {
this.takerAttrValS[ i ].requestRecalculation();
}
if ( LAY.$isDataTravellingShock ) {
part.addTravelRenderDirtyAttrVal( this );
}
if ( this.renderCall ) {
this.startCalcVal = this.transCalcVal;
this.isTransitionable = this.checkIsTransitionable();
if ( !LAY.$isDataTravellingShock ) {
part.addNormalRenderDirtyAttrVal( this );
}
switch ( attr ) {
case "display":
var parentLevel = this.level.parentLevel;
if ( parentLevel ) {
parentLevel.part.updateNaturalWidth();
parentLevel.part.updateNaturalHeight();
}
if ( this.calcVal === false ) {
recursivelySwitchOffDoingEvents( level );
}
break;
case "input":
if ( part.inputType === "multiple" ||
part.inputType === "select" ) {
level.attr2attrVal.$input.requestRecalculation();
}
break;
case "width":
if ( part.isText ) {
var textWrapAttrVal = level.attr2attrVal.textWrap;
if ( textWrapAttrVal &&
!textWrapAttrVal.isRecalculateRequired &&
textWrapAttrVal.calcVal !== "nowrap" ) {
part.updateNaturalHeight();
}
} else if ( part.type === "image" ) {
part.updateNaturalHeight();
}
break;
case "height":
if ( part.type === "image" ) {
part.updateNaturalWidth();
}
break;
case "imageUrl":
part.isImageLoaded = false;
break;
case "audioController":
part.updateNaturalHeight();
part.updateNaturalHeight();
break;
default:
var checkIfAttrAffectsTextDimesion =
function ( attr ) {
return attr.startsWith("text") &&
!attr.startsWith("textShadows") &&
([ "textColor",
"textDecoration",
"textSmoothing",
"textShadows"
]).indexOf( attr ) === -1;
};
if ( part.isText ) {
if ( checkIfAttrAffectsTextDimesion( attr ) ) {
part.updateNaturalWidth();
part.updateNaturalHeight();
} else if ( ( attr === "borderTopWidth" ) ||
( attr === "borderBottomWidth" ) ) {
part.updateNaturalHeight();
} else if ( ( attr === "borderLeftWidth" ) ||
( attr === "borderRightWidth" ) ) {
part.updateNaturalWidth();
part.updateNaturalHeight();
}
}
}
// In case there exists a transition
// for the given prop then update it
part.updateTransitionProp( attr );
} else if ( stateName !== "" ) {
if ( this.calcVal ) { // state
if ( LAY.$arrayUtils.pushUnique( level.stateS, stateName ) ) {
level.$updateStates();
// remove from the list of uninstalled states (which may/may not be present within)
LAY.$arrayUtils.remove( level.newlyUninstalledStateS, stateName );
// add state to the list of newly installed states
LAY.$arrayUtils.pushUnique( level.newlyInstalledStateS, stateName );
// add level to the list of levels which have newly installed states
LAY.$arrayUtils.pushUnique( LAY.$newlyInstalledStateLevelS, level );
}
} else { // remove state
if ( LAY.$arrayUtils.remove( level.stateS, stateName ) ) {
level.$updateStates();
// remove from the list of installed states (which may/may not be present within)
LAY.$arrayUtils.remove( level.newlyInstalledStateS, stateName );
// add state to the list of newly uninstalled states
LAY.$arrayUtils.pushUnique( level.newlyUninstalledStateS, stateName );
// add level to the list of levels which have newly uninstalled states
LAY.$arrayUtils.pushUnique( LAY.$newlyUninstalledStateLevelS, level );
}
}
} else if ( whenEventType !== "" ) {
part.updateWhenEventType( whenEventType );
} else if ( transitionProp !== "" ) {
part.updateTransitionProp( transitionProp );
} else if ( many ) {
if ( attr === "rows" ) {
many.updateRows();
} else if ( attr === "filter" ) {
if ( !many.updateFilter() ) {
return false;
}
many.updateLayout()
} else if ( attr.startsWith("sort.") ) {
many.updateRows();
} else if ( attr.startsWith("fargs.") ||
attr === "formation" ) {
many.updateLayout();
}
} else {
switch( attr ) {
case "exist":
level.$updateExistence();
break;
case "right":
if ( level.parentLevel !== undefined ) {
level.parentLevel.part.
updateNaturalWidth();
}
break;
case "bottom":
if ( level.parentLevel !== undefined ) {
level.parentLevel.part.
updateNaturalHeight();
}
break;
case "$naturalWidth":
if ( this.level.attr2attrVal.scrollX ) {
var self = this;
setTimeout(function(){
self.level.attr2attrVal.scrollX.
requestRecalculation();
LAY.$solve();
});
}
break;
case "$naturalHeight":
if ( this.level.attr2attrVal.scrollY ) {
var self = this;
setTimeout(function(){
self.level.attr2attrVal.scrollY.
requestRecalculation();
LAY.$solve();
});
}
break;
case "$input":
part.updateNaturalWidth();
if ( part.inputType !== "line" ||
!part.isInitiallyRendered ) {
part.updateNaturalHeight();
}
break;
}
}
}
this.isForceRecalculate = false;
this.isRecalculateRequired = false;
return true;
};
/*
* Doing events: clicking, hovering
*/
function recursivelySwitchOffDoingEvents( level ) {
var
hoveringAttrVal = level.attr2attrVal.$hovering,
clickingAttrVal = level.attr2attrVal.$clicking,
childLevel,
childLevelS = level.childLevelS;
if ( hoveringAttrVal ) {
hoveringAttrVal.update( false );
}
if ( clickingAttrVal ) {
clickingAttrVal.update( false );
}
if ( childLevelS.length ) {
for ( var i = 0, len = childLevelS.length;
i < len; i++ ) {
childLevel = childLevelS[ i ];
if ( childLevel.part ) {
recursivelySwitchOffDoingEvents( childLevel );
}
}
}
}
LAY.AttrVal.prototype.checkIfDeferenced = function () {
return this.takerAttrValS.length === 0;
};
LAY.AttrVal.prototype.give = function ( attrVal ) {
if ( LAY.$arrayUtils.pushUnique( this.takerAttrValS, attrVal ) &&
this.takerAttrValS.length === 1 ) {
if ( this.isEventReadonlyAttr ) {
// Given that a reference exists, add event listeners
var
eventType2fnHandler = LAY.$eventReadonlyUtils.getEventType2fnHandler( this.attr ),
eventType,
fnBoundHandler, node;
node = this.level.part.node;
for ( eventType in eventType2fnHandler ) {
if ( LAY.$checkIsWindowEvent( eventType ) &&
this.level.pathName === "/" ) {
node = window;
}
fnBoundHandler =
eventType2fnHandler[ eventType ].bind( this.level );
LAY.$eventUtils.add( node, eventType, fnBoundHandler );
this.eventReadonlyEventType2boundFnHandler[ eventType ] =
fnBoundHandler;
}
}
}
};
LAY.AttrVal.prototype.giveNot = function ( attrVal ) {
if ( LAY.$arrayUtils.remove( this.takerAttrValS, attrVal ) &&
this.takerAttrValS.length === 0 ) {
if ( this.isEventReadonlyAttr ) {
// Given that no reference exists, remove event listeners
var
eventType2fnHandler =
LAY.$eventReadonlyUtils.getEventType2fnHandler( this.attr ),
eventType,
fnBoundHandler, node;
node = this.level.part.node;
for ( eventType in eventType2fnHandler ) {
if ( LAY.$checkIsWindowEvent( eventType ) &&
this.level.pathName === "/" ) {
node = window;
}
fnBoundHandler = this.eventReadonlyEventType2boundFnHandler[ eventType ];
LAY.$eventUtils.remove( node, eventType, fnBoundHandler );
this.eventReadonlyEventType2boundFnHandler[ eventType ] =
undefined;
}
}
}
};
LAY.AttrVal.prototype.take = function () {
if ( this.val instanceof LAY.Take ) {
var _relPath00attr_S, relPath, level, attr,
i, len;
// value is of type `LAY.Take`
_relPath00attr_S = this.val._relPath00attr_S;
for ( i = 0, len = _relPath00attr_S.length; i < len; i++ ) {
relPath = _relPath00attr_S[ i ][ 0 ];
attr = _relPath00attr_S[ i ][ 1 ];
level = relPath.resolve( this.level );
if ( level === undefined ) {
return false;
}
if ( ( level.attr2attrVal[ attr ] === undefined ) ) {
level.$createLazyAttr( attr );
// return false to let the lazily created attribute
// to calculate itself first (in the case of no
// created attrval lazily then returing false
// is the only option)
return false;
}
if ( level.attr2attrVal[ attr ].isRecalculateRequired ) {
return false;
}
}
for ( i = 0; i < len; i++ ) {
relPath = _relPath00attr_S[ i ][ 0 ];
attr = _relPath00attr_S[ i ][ 1 ];
relPath.resolve( this.level ).$getAttrVal( attr ).give( this );
}
}
return true;
};
LAY.AttrVal.prototype.takeNot = function ( val ) {
if ( val instanceof LAY.Take ) {
var _relPath00attr_S, relPath, level, attr;
_relPath00attr_S = val._relPath00attr_S;
for ( var i = 0, len = _relPath00attr_S.length; i < len; i++ ) {
relPath = _relPath00attr_S[ i ][ 0 ];
attr = _relPath00attr_S[ i ][ 1 ];
level = relPath.resolve( this.level );
if ( ( level !== undefined ) && ( level.$getAttrVal( attr ) !== undefined ) ) {
level.$getAttrVal( attr ).giveNot( this );
}
}
}
};
LAY.AttrVal.prototype.remove = function () {
this.takeNot( this.val );
}
})();
(function() {
"use strict";
// Check for CSS3 color support within the browser
// source inspired from:
// http://lea.verou.me/2009/03/check-whether-the-browser-supports-rgba-and-other-css3-values/
var isCss3ColorSupported = (function () {
var prevColor = document.body.style.color;
try {
document.body.style.color = "rgba(0,0,0,0)";
} catch (e) {}
var result = document.body.style.color !== prevColor;
document.body.style.color = prevColor;
return result;
})();
// inspiration from: sass (https://github.com/sass/sass/)
LAY.Color = function ( format, key2value, alpha ) {
this.format = format;
this.r = key2value.r;
this.g = key2value.g;
this.b = key2value.b;
this.h = key2value.h;
this.s = key2value.s;
this.l = key2value.l;
this.a = alpha;
};
LAY.Color.prototype.getFormat = function () {
return this.format;
};
LAY.Color.prototype.getRed = function () {
return this.r;
};
LAY.Color.prototype.getGreen = function () {
return this.g;
};
LAY.Color.prototype.getBlue = function () {
return this.b;
};
LAY.Color.prototype.getHue = function () {
return this.h;
};
LAY.Color.prototype.getSaturation = function () {
return this.s;
};
LAY.Color.prototype.getLightness = function () {
return this.l;
};
LAY.Color.prototype.getAlpha = function () {
return this.a;
};
LAY.Color.prototype.stringify = function () {
var rgb, hsl;
if ( isCss3ColorSupported ) {
if ( this.format === "hsl" ) {
hsl = this.getHsl();
if ( this.a === 1 ) {
return "hsl(" + Math.round(hsl.h) + "," + Math.round(hsl.s) + "%," + Math.round(hsl.l) + "%)";
} else {
return "hsla(" + Math.round(hsl.h) + "," + Math.round(hsl.s) + "%," + Math.round(hsl.l) + "%," + this.a + ")";
}
} else {
rgb = this.getRgb();
if ( this.a === 1 ) {
return "rgb(" + Math.round(rgb.r) + "," + Math.round(rgb.g) + "," + Math.round(rgb.b) + ")";
} else {
return "rgba(" + Math.round(rgb.r) + "," + Math.round(rgb.g) + "," + Math.round(rgb.b) + "," + this.a + ")";
}
}
} else {
// for IE8 and legacy browsers
// where rgb is the sole color
// mode available
if ( this.a < 0.1 ) {
return "transparent";
} else {
rgb = this.getRgb();
return "rgb(" + rgb.r + "," + rgb.g + "," + rgb.b + ")";
}
}
};
LAY.Color.prototype.copy = function () {
return this.format === "rgb" ?
new LAY.Color( "rgb", { r: this.r, g: this.g, b: this.b } , this.a ) :
new LAY.Color( "hsl", { h: this.h, s: this.s, l: this.l } , this.a );
};
LAY.Color.prototype.equals = function ( otherColor ) {
return ( this.format === otherColor.format ) &&
( this.a === otherColor.a ) &&
(
(
this.format === "rgb" &&
this.r === otherColor.r &&
this.g === otherColor.g &&
this.b === otherColor.b
)
||
(
this.format === "hsl" &&
this.h === otherColor.h &&
this.s === otherColor.s &&
this.l === otherColor.l
)
);
};
LAY.Color.prototype.getRgb = function () {
if ( this.format === "rgb" ) {
return { r: this.r, g: this.g, b: this.b };
} else {
return convertHslToRgb( this.r, this.g, this.b );
}
};
LAY.Color.prototype.getHsl = function () {
if ( this.format === "hsl" ) {
return { h: this.h, s: this.s, l: this.l };
} else {
return convertRgbToHsl( this.r, this.g, this.b );
}
};
LAY.Color.prototype.getRgba = function () {
var rgb = this.getRgb();
rgb.a = this.a;
return rgb;
};
LAY.Color.prototype.getHsla = function () {
var hsl = this.getHsl();
hsl.a = this.a;
return hsl;
};
// mix, invert, saturate, desaturate
LAY.Color.prototype.red = function ( val ) {
if ( this.format === "rgb" ) {
this.r = val;
} else {
var rgb = this.getRgb();
var hsl = convertRgbToHsl( val, rgb.g, rgb.b );
this.h = hsl.h;
this.s = hsl.s;
this.l = hsl.l;
}
return this;
};
LAY.Color.prototype.green = function ( val ) {
if ( this.format === "rgb" ) {
this.g = val;
} else {
var rgb = this.getRgb();
var hsl = convertRgbToHsl( rgb.r, val, rgb.b );
this.h = hsl.h;
this.s = hsl.s;
this.l = hsl.l;
}
return this;
};
LAY.Color.prototype.blue = function ( val ) {
if ( this.format === "rgb" ) {
this.b = val;
} else {
var rgb = this.getRgb();
var hsl = convertRgbToHsl( rgb.r, rgb.g, val );
this.h = hsl.h;
this.s = hsl.s;
this.l = hsl.l;
}
return this;
};
LAY.Color.prototype.hue = function ( val ) {
if ( this.format === "hsl" ) {
this.h = val;
} else {
var hsl = this.getHsl();
var rgb = convertHslToRgb( val, hsl.s, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.saturation = function ( val ) {
if ( this.format === "hsl" ) {
this.s = val;
} else {
var hsl = this.getHsl();
var rgb = convertHslToRgb( hsl.h, val, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.lightness = function ( val ) {
if ( this.format === "hsl" ) {
this.l = val;
} else {
var hsl = this.getHsl();
var rgb = convertHslToRgb( hsl.h, hsl.s, val );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
/* Sets alpha */
LAY.Color.prototype.alpha = function ( alpha ) {
this.a = alpha;
return this;
};
LAY.Color.prototype.darken = function ( fraction ) {
var hsl = this.getHsl();
hsl.l = hsl.l - ( hsl.l * fraction );
if ( this.format === "hsl" ) {
this.l = hsl.l;
} else {
var rgb = convertHslToRgb( hsl.h, hsl.s, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.lighten = function ( fraction ) {
var hsl = this.getHsl();
hsl.l = hsl.l + ( hsl.l * fraction );
if ( this.format === "hsl" ) {
this.l = hsl.l;
} else {
var rgb = convertHslToRgb( hsl.h, hsl.s, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.saturate = function ( fraction ) {
var hsl = this.getHsl();
hsl.s = hsl.s + ( hsl.s * fraction );
if ( this.format === "hsl" ) {
this.s = hsl.s;
} else {
var rgb = convertHslToRgb( hsl.h, hsl.s, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.desaturate = function ( fraction ) {
var hsl = this.getHsl();
hsl.s = hsl.s - ( hsl.s * fraction );
if ( this.format === "hsl" ) {
this.s = hsl.s;
} else {
var rgb = convertHslToRgb( hsl.h, hsl.s, hsl.l );
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
}
return this;
};
LAY.Color.prototype.invert = function ( ) {
var rgb = this.getRgb();
rgb.r = 255 - rgb.r;
rgb.g = 255 - rgb.g;
rgb.b = 255 - rgb.b;
if ( this.format === "rgb" ) {
this.r = rgb.r;
this.g = rgb.g;
this.b = rgb.b;
} else {
var hsl = convertRgbToHsl( rgb.r, rgb.g, rgb.b );
this.h = hsl.h;
this.s = hsl.s;
this.l = hsl.l;
}
return this;
};
function convertHslToRgb( h, s, l ) {
// calculate
// source: http://stackoverflow.com/a/9493060
var r, g, b;
if(s === 0){
r = g = b = l; // achromatic
}else{
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = convertHueToRgb(p, q, h + 1/3);
g = convertHueToRgb(p, q, h);
b = convertHueToRgb(p, q, h - 1/3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
function convertRgbToHsl( r, g, b ) {
// calculate
// source: http://stackoverflow.com/a/9493060
r = r / 255; g = g / 255; b = b / 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
function convertHueToRgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
})();
( function () {
"use strict";
LAY.Level = function ( path, lson, parent, isHelper, derivedMany, rowDict, id ) {
this.pathName = path;
this.lson = lson;
// if level is many, partLson contains the non-many part of the lson
this.partLson = undefined;
this.isGpu = undefined;
this.isInitialized = false;
this.parentLevel = parent; // parent Level
this.attr2attrVal = {};
// True if the Level is a Part Level,
// false if the Level is a Many Level.
this.isPart = undefined;
// If the level name begins with "_",
// the level is considered a helper (non-renderable)
this.isHelper = isHelper;
this.isExist = true;
// If the Level is a Many (i.e this.isPart is false)
// then this.many will hold a reference to the corresponding
// Many object.
this.part = undefined;
// If the Level is a Many (i.e this.isPart is false)
// then this.many will hold a reference to the corresponding
// Many object.
this.manyObj = undefined;
// If the Level is derived from a Many
// then this.derivedMany will hold
// a reference to the Many
this.derivedMany = derivedMany;
// If the Level is derived from a Many Level
// this will be the id by which it is referenced
this.id = id;
// If the Level is derived from a Many Level
// this will contain the row information will
// be contained within below
this.rowDict = rowDict;
this.isInherited = false;
this.childLevelS = [];
this.stateS = [ "root" ];
this.stringHashedStates2_cachedAttr2val_ = {};
this.newlyInstalledStateS = [];
this.newlyUninstalledStateS = [];
};
LAY.Level.prototype.$init = function () {
LAY.$pathName2level[ this.pathName ] = this;
LAY.$newLevelS.push( this );
if ( this.parentLevel ) {
this.parentLevel.childLevelS.push( this );
}
};
LAY.Level.prototype.level = function ( relativePath ) {
return ( new LAY.RelPath( relativePath ) ).resolve( this );
};
LAY.Level.prototype.parent = function () {
return this.parentLevel;
};
LAY.Level.prototype.children = function () {
return this.childLevelS;
};
LAY.Level.prototype.path = function () {
return this.pathName;
};
LAY.Level.prototype.node = function () {
return this.isPart && this.part.node;
};
LAY.Level.prototype.attr = function ( attr ) {
if ( this.attr2attrVal[ attr ] ) {
return this.attr2attrVal[ attr ].calcVal;
} else {
// Check if it is a doing event
if ( attr.charAt( 0 ) === "$" ) {
if ( LAY.$checkIfDoingReadonly( attr ) ) {
console.error("LAY Error: " + attr + " must be placed in $obdurate");
return undefined;
} else if ( LAY.$checkIfImmidiateReadonly( attr ) ) {
return this.part.getImmidiateReadonlyVal( attr );
}
}
if ( this.$createLazyAttr( attr, true ) ) {
var attrVal = this.attr2attrVal[ attr ];
attrVal.give( LAY.$emptyAttrVal );
LAY.$solve();
return attrVal.calcVal;
} else {
return undefined;
}
}
};
LAY.Level.prototype.data = function ( dataKey, value ) {
this.$changeAttrVal( "data." + dataKey, value );
LAY.$solve();
};
LAY.Level.prototype.row = function ( rowKey, value ) {
if ( this.derivedMany ) {
this.derivedMany.id2row[ this.id ][ rowKey ] = value;
this.derivedMany.level.attr2attrVal.rows.requestRecalculation();
LAY.$solve();
}
};
LAY.Level.prototype.changeNativeInput = function ( value ) {
this.part.node.value = value;
};
LAY.Level.prototype.changeNativeScrollX = function ( value ) {
this.part.node.scrollLeft = value;
};
LAY.Level.prototype.changeNativeScrollY = function ( value ) {
this.part.node.scrollTop = value;
};
LAY.Level.prototype.many = function () {
return this.derivedMany && this.derivedMany.level;
};
LAY.Level.prototype.levels = function () {
return this.manyObj && this.manyObj.allLevelS;
};
LAY.Level.prototype.rowsCommit = function ( newRowS ) {
if ( !this.isPart ) {
this.manyObj.rowsCommit( newRowS );
}
};
LAY.Level.prototype.rowsMore = function ( newRowS ) {
if ( !this.isPart ) {
this.manyObj.rowsMore( newRowS );
}
};
LAY.Level.prototype.rowAdd = function ( newRow ) {
this.rowsMore( [ newRow ] );
};
LAY.Level.prototype.rowDeleteByID = function ( id ) {
if ( !this.isPart ) {
this.manyObj.rowDeleteByID( id );
}
};
LAY.Level.prototype.rowsUpdate = function ( key, val, queryRowS ) {
if ( !this.isPart ) {
if ( queryRowS instanceof LAY.Query ) {
queryRowS = queryRowS.rowS;
}
this.manyObj.rowsUpdate( key, val, queryRowS );
}
};
LAY.Level.prototype.rowsDelete = function ( queryRowS ) {
if ( !this.isPart ) {
if ( queryRowS instanceof LAY.Query ) {
queryRowS = queryRowS.rowS;
}
this.manyObj.rowsDelete( queryRowS );
}
};
LAY.Level.prototype.dataTravelBegin = function ( dataKey, finalVal ) {
var attrVal;
if ( LAY.$isDataTravelling ) {
console.error("LAY Warning: Existence of another unfinished data travel");
} else {
attrVal = this.attr2attrVal[ "data." + dataKey ];
if ( attrVal === undefined ) {
console.error ("LAY Warning: Inexistence of data key for data travel");
}
LAY.$isDataTravelling = true;
LAY.level("/").attr2attrVal.$dataTravelling.update( true );
LAY.$dataTravellingLevel = this;
LAY.level("/").attr2attrVal.$dataTravelLevel.update( this );
LAY.$dataTravellingAttrInitialVal = attrVal.val;
LAY.$dataTravellingAttrVal = attrVal;
LAY.$isDataTravellingShock = true;
attrVal.update( finalVal );
LAY.$solve();
LAY.$isDataTravellingShock = false;
}
};
LAY.Level.prototype.dataTravelContinue = function ( delta ) {
if ( !LAY.$isDataTravelling ) {
console.error( "LAY Warning: Inexistence of a data travel" );
} else if ( this !== LAY.$dataTravellingLevel ){
console.error( "LAY Warning: Inexistence of a data travel for this Level" );
} else {
if ( LAY.$dataTravelDelta !== delta ) {
LAY.$dataTravelDelta = delta;
LAY.level("/").attr2attrVal.$dataTravelDelta.update( delta );
LAY.$render();
}
}
};
LAY.Level.prototype.dataTravelArrive = function ( isArrived ) {
if ( !LAY.$isDataTravelling ) {
console.error( "LAY Warning: Inexistence of a data travel" );
} else {
LAY.$isDataTravelling = false;
LAY.level("/").attr2attrVal.$dataTravelling.update( false );
LAY.$dataTravellingLevel = undefined;
LAY.level("/").attr2attrVal.$dataTravelLevel.update( null );
LAY.$dataTravelDelta = 0.0;
LAY.level("/").attr2attrVal.$dataTravelDelta.update( 0.0 );
// clear out attrvalues which are data travelling
LAY.$clearDataTravellingAttrVals();
if ( !isArrived ) {
LAY.$dataTravellingAttrVal.update(
LAY.$dataTravellingAttrInitialVal );
LAY.$solve();
} else {
}
LAY.$render();
}
};
LAY.Level.prototype.queryRows = function () {
if ( !this.isPart ) {
return this.manyObj.queryRows();
}
};
LAY.Level.prototype.queryFilter = function () {
if ( !this.isPart ) {
return this.manyObj.queryFilter();
}
};
LAY.Level.prototype.addChildren = function ( name2lson ) {
for ( var name in name2lson ) {
var lson = name2lson[ lson ];
this.lson.children[ name ] = lson;
this.$addChild( name, name2lson );
}
};
LAY.Level.prototype.remove = function () {
if ( this.pathName === "/" ) {
console.error("LAY Error: Attempt to remove root level '/' prohibited");
} else {
if ( this.derivedMany ) {
this.derivedMany.rowDeleteByID( this.id );
} else {
this.$remove();
LAY.$solve();
}
}
};
LAY.Level.prototype.$remove = function () {
var
childLevelS = this.childLevelS,
attr2attrVal = this.attr2attrVal;
LAY.$pathName2level[ this.pathName ] = undefined;
LAY.$arrayUtils.remove( this.parentLevel.childLevelS, this );
if ( this.isPart ) {
this.part && this.part.remove();
}
for ( var attr in attr2attrVal ) {
attr2attrVal[ attr ].remove();
}
this.$removeDescendants();
};
LAY.Level.prototype.$removeDescendants = function () {
var descendantLevelS = this.isPart ?
this.childLevelS : this.manyObj.allLevelS;
for ( var i=0, len=descendantLevelS.length; i<len; i++ ) {
descendantLevelS[ i ] &&
descendantLevelS[ i ].$remove();
}
};
LAY.Level.prototype.$addChildren = function ( name2lson ) {
if ( name2lson !== undefined ) {
for ( var name in name2lson ) {
this.$addChild( name, name2lson[ name ] );
}
}
};
LAY.Level.prototype.$addChild = function ( name, lson ) {
var childPath, childLevel;
if ( !LAY.$checkIsValidUtils.levelName( name ) ) {
throw ( "LAY Error: Invalid Level Name: " + name );
}
childPath = this.pathName +
( this.pathName === "/" ? "" : "/" ) + name;
if ( LAY.$pathName2level[ childPath ] !== undefined ) {
throw ( "LAY Error: Level already exists with path: " +
childPath + " within Level: " + this.pathName );
}
childLevel = new LAY.Level( childPath,
lson, this, name.charAt(0) === "_" );
childLevel.$init();
};
/*
* Return false if the level could not be inherited (due
* to another level not being present or started as yet)
*/
LAY.Level.prototype.$normalizeAndInherit = function () {
var lson, refS, i, len, ref, level, inheritedAndNormalizedLson;
LAY.$normalize( this.lson, this.isHelper );
// check if it contains anything to inherit from
if ( this.lson.$inherit !== undefined ) {
lson = {};
refS = this.lson.$inherit;
for ( i = 0, len = refS.length; i < len; i++ ) {
ref = refS[ i ];
if ( typeof ref === "string" ) { // pathname reference
if ( ref === this.pathName ) {
return false;
}
level = ( new LAY.RelPath( ref ) ).resolve( this );
if ( ( level === undefined ) || !level.isInherited ) {
return false;
}
}
}
for ( i = 0; i < len; i++ ) {
ref = refS[ i ];
if ( typeof ref === "string" ) { // pathname reference
level = ( new LAY.RelPath( ref ) ).resolve( this );
inheritedAndNormalizedLson = level.lson;
} else { // object reference
LAY.$normalize( ref, true );
inheritedAndNormalizedLson = ref;
}
LAY.$inherit( lson, inheritedAndNormalizedLson );
}
LAY.$inherit( lson, this.lson );
this.lson = lson;
}
this.isInherited = true;
return true;
};
LAY.Level.prototype.$reproduce = function () {
if ( this.isPart ) {
this.part = new LAY.Part( this );
this.part.init();
if ( this.lson.children !== undefined ) {
this.$addChildren( this.lson.children );
}
} else {
this.manyObj = new LAY.Many( this, this.partLson );
this.manyObj.init();
}
};
LAY.Level.prototype.$identify = function () {
this.isPart = this.lson.many === undefined ||
this.derivedMany;
if ( this.pathName === "/" ) {
this.isGpu = this.lson.$gpu === undefined ?
true :
this.lson.$gpu;
} else {
this.isGpu = this.lson.$gpu === undefined ?
this.parentLevel.isGpu :
this.lson.$gpu;
}
this.isGpu = this.isGpu && LAY.$isGpuAccelerated;
if ( this.isPart ) {
if ( !this.derivedMany ) {
LAY.$defaultizePartLson( this.lson,
this.parentLevel );
}
} else {
if ( this.pathName === "/" ) {
throw "LAY Error: 'many' prohibited for root level /";
}
this.partLson = this.lson;
this.lson = this.lson.many;
LAY.$defaultizeManyLson( this.lson );
}
};
function initAttrsObj( attrPrefix, key2val,
attr2val, isNoUndefinedAllowed ) {
var key, val;
for ( key in key2val ) {
if ( ( key2val[ key ] !== undefined ) ||
!isNoUndefinedAllowed ) {
attr2val[ attrPrefix + key ] = key2val[ key ];
}
}
}
function initAttrsArray( attrPrefix, elementS, attr2val ) {
var i, len;
for ( i = 0, len = elementS.length ; i < len; i++ ) {
attr2val[ attrPrefix + "." + ( i + 1 ) ] = elementS[ i ];
}
}
/* Flatten the slson to attr2val dict */
function convertSLSONtoAttr2Val( slson, attr2val, isPart ) {
var
prop,
transitionProp, transitionDirective,
transitionPropPrefix,
eventType, fnCallbackS,
prop2val = slson.props,
when = slson.when,
transition = slson.transition,
fargs = slson.fargs,
i, len;
if ( isPart ){
initAttrsObj( "", slson.props, attr2val, true );
for ( transitionProp in transition ) {
transitionDirective = transition[ transitionProp ];
transitionPropPrefix = "transition." + transitionProp + ".";
if ( transitionDirective.type !== undefined ) {
attr2val[ transitionPropPrefix + "type" ] =
transitionDirective.type;
}
if ( transitionDirective.duration !== undefined ) {
attr2val[ transitionPropPrefix + "duration" ] =
transitionDirective.duration;
}
if ( transitionDirective.delay !== undefined ) {
attr2val[ transitionPropPrefix + "delay" ] =
transitionDirective.delay;
}
if ( transitionDirective.done !== undefined ) {
attr2val[ transitionPropPrefix + "done" ] =
transitionDirective.done;
}
if ( transitionDirective.args !== undefined ) {
initAttrsObj( transitionPropPrefix + "args.",
transitionDirective.args, attr2val, false );
}
}
for ( eventType in when ) {
fnCallbackS = when[ eventType ];
initAttrsArray( "when." + eventType, fnCallbackS, attr2val );
}
if ( slson.$$num !== undefined ) {
initAttrsObj( "$$num.", slson.$$num, attr2val, false );
}
if ( slson.$$max !== undefined ) {
initAttrsObj( "$$max.", slson.$$max, attr2val, false );
}
} else {
attr2val.formation = slson.formation;
attr2val.filter = slson.filter;
if ( fargs ) {
for ( var formationFarg in fargs ) {
initAttrsObj( "fargs." + formationFarg + ".",
fargs[ formationFarg ], attr2val, false );
}
}
attr2val[ "$$num.sort" ] = slson.sort.length;
for ( i = 0, len = slson.sort.length; i < len; i++ ) {
initAttrsObj( "sort." + ( i + 1 ) + ".", slson.sort[ i ],
attr2val, false );
}
}
}
LAY.Level.prototype.$updateExistence = function () {
var isExist = this.attr2attrVal.exist.calcVal;
if ( isExist ) {
this.$appear();
} else {
this.$disappear();
}
};
/*
LAY.Level.prototype.$checkIfParentExists = function () {
if ( this.pathName === "/" ) {
return this.isExist;
} else {
return this.isExist ? this.parentLevel.$checkIfParentExists() : false;
}
};*/
LAY.Level.prototype.$appear = function () {
this.isExist = true;
this.$reproduce();
this.$initAllAttrs();
if ( this.isPart ) {
this.part.add();
}
};
LAY.Level.prototype.$disappear = function () {
console.log(this.pathName);
this.isExist = false;
var attr2attrVal = this.attr2attrVal;
for ( var attr in attr2attrVal ) {
if ( attr !== "exist" ) {
attr2attrVal[ attr ].remove();
}
}
this.$removeDescendants();
if ( this.isPart ) {
this.part && this.part.remove();
}
};
LAY.Level.prototype.$decideExistence = function () {
if ( !this.isHelper ) {
this.$createAttrVal( "exist", this.lson.exist ===
undefined ? true : this.lson.exist );
}
};
LAY.Level.prototype.$initAllAttrs = function () {
var
obdurateReadonlyS = this.lson.$obdurate ?
this.lson.$obdurate : [],
obdurateReadonly, i, len;
this.isInitialized = true;
if ( this.isPart ) {
if ( this.lson.states.root.props.scrollX ) {
obdurateReadonlyS.push( "$naturalWidth" );
}
if ( this.lson.states.root.props.scrollY ) {
obdurateReadonlyS.push( "$naturalHeight" );
}
if ( this.part.type === "input" &&
this.part.inputType !== "line" ) {
// $input will be required to compute
// the natural height if it exists
// TODO: optimize
obdurateReadonlyS.push( "$input" );
}
}
if ( obdurateReadonlyS.length ) {
for ( i = 0, len = obdurateReadonlyS.length; i < len; i++ ) {
obdurateReadonly = obdurateReadonlyS[ i ];
if ( !this.$createLazyAttr( obdurateReadonly ) ) {
throw "LAY Error: Unobervable Attr: '" +
obdurateReadonly + "'";
}
this.attr2attrVal[ obdurateReadonly ].give(
LAY.$emptyAttrVal );
}
}
this.$initNonStateProjectedAttrs();
this.$updateStates();
};
LAY.Level.prototype.$initNonStateProjectedAttrs = function () {
var
key, val, stateName, state,
states = this.lson.states,
lson = this.lson,
attr2val = {};
initAttrsObj( "data.", lson.data, attr2val, false );
for ( stateName in states ) {
state = states[ stateName ];
if ( stateName !== "root" ) {
attr2val[ stateName + "." + "onlyif" ] = state.onlyif;
if ( state.install ) {
attr2val[ stateName + "." + "install" ] = state.install;
}
if ( state.uninstall ) {
attr2val[ stateName + "." + "uninstall" ] = state.uninstall;
}
}
}
if ( this.isPart ) {
attr2val.right = LAY.$essentialPosAttr2take.right;
attr2val.bottom = LAY.$essentialPosAttr2take.bottom;
if ( this.pathName === "/" ) {
attr2val.$dataTravelling = false;
attr2val.$dataTravelDelta = 0.0;
attr2val.$dataTravelLevel = undefined;
attr2val.$absoluteLeft = 0;
attr2val.$absoluteTop = 0;
attr2val.$windowWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
attr2val.$windowHeight = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
} else if ( this.derivedMany ) {
initAttrsObj( "row.", this.rowDict, attr2val, false );
attr2val.$i = 0;
attr2val.$f = 0;
}
} else { // Many
attr2val.rows = lson.rows;
attr2val.$id = lson.$id;
attr2val.$$layout = null;
}
this.$commitAttr2Val( attr2val );
};
LAY.Level.prototype.$commitAttr2Val = function ( attr2val ) {
var attr, val, attrVal;
for ( attr in attr2val ) {
val = attr2val[ attr ];
attrVal = this.attr2attrVal[ attr ];
if ( ( attrVal === undefined ) ) {
attrVal = this.attr2attrVal[ attr ] = new LAY.AttrVal( attr, this );
}
attrVal.update( val );
}
};
LAY.Level.prototype.$createAttrVal = function ( attr, val ) {
( this.attr2attrVal[ attr ] =
new LAY.AttrVal( attr, this ) ).update( val );
};
/*
* Return true if attr was created as it exists (in lazy form),
* false otherwise (it is not present at all to be created)
*/
LAY.Level.prototype.$createLazyAttr = function ( attr, isNoImmidiateReadonly ) {
var
splitAttrLsonComponentS, attrLsonComponentObj, i, len,
firstAttrLsonComponent;
if ( LAY.$miscPosAttr2take[ attr ] ) {
this.$createAttrVal( attr,
LAY.$miscPosAttr2take[ attr ] );
} else if ( attr.charAt( 0 ) === "$" ) { //readonly
if ( [ "$type", "$load", "$id", "$inherit", "$obdurate" ].indexOf(
attr ) !== -1 ) {
this.$createAttrVal( attr, this.lson[ attr ] );
} else if ( attr === "$path" ) {
this.$createAttrVal( "$path", this.pathName );
} else {
if ( !isNoImmidiateReadonly &&
LAY.$checkIfImmidiateReadonly( attr ) ) {
this.$createAttrVal( attr, null );
} else if ( LAY.$checkIfDoingReadonly( attr ) ) {
this.$createAttrVal( attr, false );
} else {
console.error("LAY Error: Incorrectly named readonly: " + attr );
return false;
}
}
} else {
if ( attr.indexOf( "." ) === -1 ) {
var lazyVal = LAY.$getLazyPropVal( attr,
this.parentLevel === undefined );
if ( lazyVal !== undefined ) {
this.$createAttrVal( attr, lazyVal );
} else {
return false;
}
} else {
if ( attr.startsWith( "data." ||
attr.startsWith("row.") ) ) {
return false;
} else {
splitAttrLsonComponentS = attr.split( "." );
if ( this.lson.states === undefined ) {
return false;
} else {
firstAttrLsonComponent = splitAttrLsonComponentS[ 0 ];
// Get down to state level
if ( LAY.$checkIsValidUtils.stateName(
firstAttrLsonComponent ) ) {
attrLsonComponentObj = this.lson.states[ firstAttrLsonComponent ];
} else {
return false;
}
splitAttrLsonComponentS.shift();
// remove the state part of the attr components
if ( splitAttrLsonComponentS[ 0 ] === "when" ) {
splitAttrLsonComponentS[ splitAttrLsonComponentS.length - 1 ] =
parseInt( splitAttrLsonComponentS[
splitAttrLsonComponentS.length -1 ] ) - 1;
} else if ( ["fargs", "sort",
"formation", "filter", "rows"].indexOf(
splitAttrLsonComponentS[ 0 ]) !== -1 ) {
} else if ( splitAttrLsonComponentS[ 0 ] !== "transition" ) {
// props
if ( attrLsonComponentObj.props !== undefined ) {
attrLsonComponentObj = attrLsonComponentObj.props;
} else {
return false;
}
}
for ( i = 0, len = splitAttrLsonComponentS.length; i < len; i++ ) {
attrLsonComponentObj =
attrLsonComponentObj[ splitAttrLsonComponentS[ i ] ];
if ( attrLsonComponentObj === undefined ) {
break;
}
}
// Not present within states
if ( attrLsonComponentObj === undefined ) {
return false;
} else {
this.$createAttrVal( attr ,
attrLsonComponentObj );
}
}
}
}
}
return true;
};
/*
Undefine all current attributes which are influencable
by states: props, transition, when, $$num, $$max
*/
LAY.Level.prototype.$undefineStateProjectedAttrs = function() {
var attr;
for ( attr in this.attr2attrVal ) {
if ( this.attr2attrVal[ attr ].isStateProjectedAttr ) {
this.attr2attrVal[ attr ].update( undefined );
}
}
};
/* Return the attr2value generated
by the current states */
LAY.Level.prototype.$getStateAttr2val = function () {
var
attr2val = {},
stringHashedStates2_cachedAttr2val_ = this.derivedMany ?
this.derivedMany.levelStringHashedStates2_cachedAttr2val_ :
this.stringHashedStates2_cachedAttr2val_;
this.$sortStates();
var stringHashedStates = this.stateS.join( "&" );
if ( stringHashedStates2_cachedAttr2val_[
stringHashedStates ] === undefined ) {
convertSLSONtoAttr2Val( this.$generateSLSON(), attr2val, this.isPart);
stringHashedStates2_cachedAttr2val_[ stringHashedStates ] =
attr2val;
}
return stringHashedStates2_cachedAttr2val_[ stringHashedStates ];
};
/*
* TODO: fill in details of priority
*/
LAY.Level.prototype.$sortStates = function ( stateS ) {
var
sortedStateS = this.stateS.sort(),
i, len, sortedState;
// Push the "root" state to the start for least priority
LAY.$arrayUtils.remove( sortedStateS, "root" );
sortedStateS.unshift("root");
// Push the "formationDisplayNone" state to the end of the
// list of states for maximum priority.
if ( sortedStateS.indexOf( "formationDisplayNone" ) !== -1 ) {
LAY.$arrayUtils.remove( sortedStateS, "formationDisplayNone" );
sortedStateS.push( "formationDisplayNone" );
}
};
/*
* From the current states generate the
* correspinding SLSON (state projected lson)
* Requirement: the order of states must be sorted
*/
LAY.Level.prototype.$generateSLSON = function () {
this.$sortStates();
var slson = {}, attr2val;
for ( var i = 0, len = this.stateS.length; i < len; i++ ) {
LAY.$inherit( slson, this.lson.states[ this.stateS[ i ] ],
true, !this.isPart, true );
}
return slson;
};
LAY.Level.prototype.$updateStates = function () {
var attr2attrVal = this.attr2attrVal;
this.$undefineStateProjectedAttrs();
this.$commitAttr2Val( this.$getStateAttr2val() );
if ( this.derivedMany &&
!this.derivedMany.level.attr2attrVal.filter.isRecalculateRequired &&
attr2attrVal.$f.calcVal !== 1 ) {
this.$setFormationXY( this.part.formationX,
this.part.formationY );
}
};
LAY.Level.prototype.$getAttrVal = function ( attr ) {
return this.attr2attrVal[ attr ];
};
/* Manually change attr value */
LAY.Level.prototype.$changeAttrVal = function ( attr, val ) {
if ( this.attr2attrVal[ attr ] ) {
this.attr2attrVal[ attr ].update( val );
LAY.$solve();
}
};
LAY.Level.prototype.$requestRecalculation = function ( attr ) {
if ( this.attr2attrVal[ attr ] ) {
this.attr2attrVal[ attr ].requestRecalculation();
LAY.$solve();
}
};
LAY.Level.prototype.$setFormationXY = function ( x, y ) {
this.part.formationX = x;
this.part.formationY = y;
if ( this.part ) { //level might not initialized as yet
var
topAttrVal = this.attr2attrVal.top,
leftAttrVal = this.attr2attrVal.left;
if ( x === undefined ) {
leftAttrVal.update( this.derivedMany.defaultFormationX );
} else {
leftAttrVal.update( x );
}
if ( y === undefined ) {
topAttrVal.update( this.derivedMany.defaultFormationY );
} else {
topAttrVal.update( y );
}
topAttrVal.requestRecalculation();
leftAttrVal.requestRecalculation();
}
};
})();
(function() {
"use strict";
LAY.Many = function ( level, partLson ) {
this.level = level;
this.partLson = partLson;
this.allLevelS = [];
this.filteredLevelS = [];
// "stringHashedStates2_cachedAttr2val_"
// for levels derived from the many
// Keeping this cache ensures thats
// each derived level (which could potentially
// large arbitrary number n) calculates
// only once.
this.levelStringHashedStates2_cachedAttr2val_ = {};
this.id = level.lson.$id || "id";
this.id2level = {};
this.id2row = {};
this.isLoaded = false;
this.isAutoId = false;
this.defaultFormationX = undefined;
this.defaultFormationY = undefined;
};
LAY.Many.prototype.init = function () {
var
states = this.partLson.states ||
( this.partLson.states = {} );
states.formationDisplayNone =
LAY.$formationDisplayNoneState;
LAY.$defaultizePartLson( this.partLson,
this.level.parentLevel );
LAY.$newManyS.push( this );
this.defaultFormationX = this.partLson.states.root.props.left;
this.defaultFormationY = this.partLson.states.root.props.top;
};
LAY.Many.prototype.queryRows = function () {
return new LAY.Query(
LAY.$arrayUtils.cloneSingleLevel(
this.level.attr2attrVal.rows.calcVal ) );
};
LAY.Many.prototype.queryFilter = function () {
return new LAY.Query(
LAY.$arrayUtils.cloneSingleLevel(
this.level.attr2attrVal.filter.calcVal ) );
};
LAY.Many.prototype.rowsCommit = function ( newRowS ) {
var rowsAttrVal = this.level.attr2attrVal.rows;
rowsAttrVal.val = newRowS;
rowsAttrVal.requestRecalculation();
LAY.$solve();
};
LAY.Many.prototype.rowsMore = function ( newRowS ) {
var
rowsAttrVal = this.level.attr2attrVal.rows,
curRowS = rowsAttrVal.calcVal;
if ( checkIfRowsIsNotObjectified( newRowS ) ) {
newRowS = objectifyRows( newRowS );
}
for ( var i = 0; i < newRowS.length; i++ ) {
curRowS.push( newRowS[ i ] );
}
rowsAttrVal.val = rowsAttrVal.calcVal;
rowsAttrVal.requestRecalculation();
LAY.$solve();
};
LAY.Many.prototype.rowDeleteByID = function ( id ) {
var
rowsAttrVal = this.level.attr2attrVal.rows,
curRowS = rowsAttrVal.calcVal,
row = this.id2row [ id ];
if ( row ) {
LAY.$arrayUtils.remove(
curRowS, row );
rowsAttrVal.val = rowsAttrVal.calcVal;
rowsAttrVal.requestRecalculation();
LAY.$solve();
}
};
LAY.Many.prototype.rowsUpdate = function ( key, val, queryRowS ) {
var rowsAttrVal = this.level.attr2attrVal.rows;
// If no queriedRowS parameter is supplied then
// update all the rows
queryRowS = queryRowS ||
rowsAttrVal.calcVal || [];
for ( var i = 0, len = queryRowS.length; i < len; i++ ) {
var fetchedRow = this.id2row[ queryRowS[ i ][ this.id ] ];
if ( fetchedRow ) {
fetchedRow[ key ] = val;
}
}
rowsAttrVal.val = rowsAttrVal.calcVal;
rowsAttrVal.requestRecalculation();
LAY.$solve();
};
LAY.Many.prototype.rowsDelete = function ( queryRowS ) {
var
rowsAttrVal = this.level.attr2attrVal.rows,
curRowS = rowsAttrVal.calcVal;
// If no queriedRowS parameter is supplied then
// delete all the rows
queryRowS = queryRowS ||
rowsAttrVal.calcVal || [];
for ( var i = 0, len = queryRowS.length; i < len; i++ ) {
var fetchedRow = this.id2row[ queryRowS[ i ][ this.id ] ];
LAY.$arrayUtils.remove( curRowS, fetchedRow );
}
rowsAttrVal.val = rowsAttrVal.calcVal;
rowsAttrVal.requestRecalculation();
LAY.$solve();
};
function checkIfRowsIsNotObjectified ( rowS ) {
return rowS.length &&
( typeof rowS[ 0 ] !== "object" );
}
function objectifyRows ( rowS, idKey ) {
var objectifiedRowS = [];
for ( var i = 0, len = rowS.length; i < len; i++ ) {
var objectifiedRow = { content: rowS[ i ]};
objectifiedRow[ idKey ] = i+1;
objectifiedRowS.push( objectifiedRow );
}
return objectifiedRowS;
}
function checkIfRowsHaveNoId( rowS, idKey ) {
var totalIds = 0;
for ( var i=0, len=rowS.length; i<len; i++ ) {
if ( rowS[ i ][ idKey ] !== undefined ) {
totalIds++;
}
}
if ( totalIds > 0 ) {
if ( totalIds !== rowS.length ) {
throw "LAY Error: Inconsistent id provision to rows of " +
this.level.pathName;
}
} else if ( rowS.length ) {
return true;
}
return false;
}
function idifyRows ( rowS, idKey ) {
for ( var i=0, len=rowS.length; i<len; i++ ) {
rowS[ i ][ idKey ] = i+1;
}
// check for duplicates
// complexity of solution is O(n)
var hasDuplicates = false;
for ( var i=0, len=rowS.length; i<len; i++ ) {
if ( rowS[ i ][ idKey ] !== i+1 ) {
hasDuplicates = true;
break;
}
}
if ( hasDuplicates ) {
for ( var i=0, len=rowS.length; i<len; i++ ) {
rowS[ i ] = LAY.$clone( rowS[ i ] );
rowS[ i ][ idKey ] = i+1;
}
}
return rowS;
}
/*
* Update the rows by:
* (1) Creating new levels in accordance to new rows
* (2) Updating existing levels in accordance to changes in changed rows
*/
LAY.Many.prototype.updateRows = function () {
var
rowS = this.level.attr2attrVal.rows.calcVal,
row,
id,
level,
parentLevel = this.level.parentLevel,
updatedAllLevelS = [],
newLevelS = [],
id2level = this.id2level,
id2row = this.id2row,
rowKey, rowVal, rowAttr,
rowAttrVal,
i, len;
// incase rows is explicity set to undefined
// (most likely through a Take)
if ( !rowS ) {
rowS = [];
}
if ( checkIfRowsIsNotObjectified ( rowS ) ) {
rowS = objectifyRows( rowS, this.id );
var rowsAttrVal = this.level.attr2attrVal.rows;
rowsAttrVal.calcVal = rowS;
} else if ( this.isAutoId ||
checkIfRowsHaveNoId( rowS, this.id ) ) {
this.isAutoId = true;
rowS = idifyRows( rowS, this.id );
var rowsAttrVal = this.level.attr2attrVal.rows;
rowsAttrVal.calcVal = rowS;
}
this.sort( rowS );
for ( i = 0, len = rowS.length; i < len; i++ ) {
row = rowS[ i ];
id = row[ this.id ];
id2row[ id ] = row;
level = this.id2level[ id ];
if ( !level ) {
// create new level with row
level = new LAY.Level(
this.level.pathName + ":" + id,
this.partLson, this.level.parentLevel, false,
this, row, id );
level.$init();
id2level[ id ] = level;
id2row[ id ] = row;
newLevelS.push( level );
} else if ( level.isInitialized ) {
for ( rowKey in row ) {
rowVal = row[ rowKey ];
rowAttr = "row." + rowKey;
rowAttrVal = level.attr2attrVal[ rowAttr ];
if ( !rowAttrVal ) {
level.$createAttrVal( rowAttr, rowVal );
} else {
rowAttrVal.update( rowVal );
}
}
}
updatedAllLevelS.push( level );
}
for ( id in id2level ) {
level = id2level[ id ];
if ( level &&
updatedAllLevelS.indexOf( level ) === -1 ) {
level.$remove();
this.id2row[ id ] = undefined;
this.id2level[ id ] = undefined;
}
}
this.allLevelS = updatedAllLevelS;
};
/* Return false if not all levels have been
* initialized, else return true
*/
LAY.Many.prototype.updateFilter = function () {
var
allLevelS = this.allLevelS,
filteredRowS =
this.level.attr2attrVal.filter.calcVal || [],
filteredLevelS = [],
filteredLevel, f = 1,
level;
for (
var i = 0, len = allLevelS.length;
i < len; i++ ) {
level = allLevelS[ i ];
// has not been initialized as yet
if ( !level.isInitialized ) {
return false;
}
level.attr2attrVal.$i.update( i + 1 );
level.attr2attrVal.$f.update( -1 );
}
var idKey = this.id;
for (
var i = 0, len = filteredRowS.length;
i < len; i++ ) {
filteredLevel = this.id2level[ filteredRowS[ i ][ idKey ] ];
if ( filteredLevel ) {
filteredLevelS.push( filteredLevel );
filteredLevel.attr2attrVal.$f.update( f++ );
}
}
this.filteredLevelS = filteredLevelS;
return true;
};
LAY.Many.prototype.updateLayout = function () {
LAY.$arrayUtils.pushUnique(
LAY.$relayoutDirtyManyS, this);
};
LAY.Many.prototype.relayout = function () {
var
filteredLevelS = this.filteredLevelS,
firstFilteredLevel = filteredLevelS[ 0 ],
attr2attrVal = this.level.attr2attrVal,
formation = attr2attrVal.formation.calcVal,
defaultFargs = LAY.$formation2fargs[ formation ],
fargs = {},
fargAttrVal;
for ( var farg in defaultFargs ) {
fargAttrVal = attr2attrVal[ "fargs." +
formation + "." + farg ];
fargs[ farg ] = fargAttrVal ?
fargAttrVal.calcVal : defaultFargs[ farg ];
}
var formationFn = LAY.$formation2fn[ formation ];
if ( firstFilteredLevel ) {
firstFilteredLevel.$setFormationXY(
undefined, undefined );
}
for (
var f = 1, len = filteredLevelS.length, filteredLevel, xy;
f < len;
f++
) {
filteredLevel = filteredLevelS[ f ];
/*// if the level is not initialized then
// discontinue the filtered positioning
if ( !filteredLevel.part ) {
return;
}*/
xy = formationFn( f + 1, filteredLevel,
filteredLevelS, fargs );
filteredLevel.$setFormationXY(
xy[ 0 ],
xy[ 1 ]
);
}
};
LAY.Many.prototype.sort = function ( rowS ) {
var sortAttrPrefix,
attr2attrVal = this.level.attr2attrVal,
numSorts = attr2attrVal["$$num.sort"] ?
attr2attrVal["$$num.sort"].calcVal : 0,
sortDictS = [];
if ( numSorts > 0 ) {
for ( var i=0; i<numSorts; i++ ) {
sortAttrPrefix = "sort." + ( i + 1 ) + ".";
sortDictS.push(
{ key:attr2attrVal[ sortAttrPrefix + "key" ].calcVal,
ascending:
attr2attrVal[ sortAttrPrefix + "ascending" ].calcVal });
}
rowS.sort( dynamicSortMultiple( sortDictS ) );
}
};
LAY.Many.prototype.remove = function () {
var allLevelS = this.allLevelS;
for ( var i=0, len=allLevelS.length; i<len; i++ ) {
allLevelS[ i ].remove()
}
};
/*! below code is taken from one of the responses
to the stackoverflow question:
http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript
@source: http://stackoverflow.com/a/4760279 */
function dynamicSort( sortDict ) {
var key = sortDict.key,
sortOrder = sortDict.ascending ? 1 : -1;
return function (a,b) {
var result = (a[key] < b[key]) ? -1 : (a[key] > b[key]) ? 1 : 0;
return result * sortOrder;
}
}
function dynamicSortMultiple( sortDictS ) {
return function (obj1, obj2) {
var i = 0, result = 0,
numberOfProperties = sortDictS.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(sortDictS[i])(obj1, obj2);
i++;
}
return result;
}
}
})();
( function () {
"use strict";
var cssPrefix, allStyles,
defaultCss, defaultTextCss,
textDimensionCalculateNodeCss,
inputType2tag, nonInputType2tag,
textSizeMeasureNode,
imageSizeMeasureNode,
supportedInputTypeS,
audioWidth, audioHeight;
// source: http://davidwalsh.name/vendor-prefix
if ( window.getComputedStyle ) {
cssPrefix = (Array.prototype.slice
.call(window.getComputedStyle(document.body, null))
.join('')
.match(/(-moz-|-webkit-|-ms-)/)
)[1];
} else {
cssPrefix = "-ms-";
}
// source: xicooc (http://stackoverflow.com/a/29837441)
LAY.$isBelowIE9 = (/MSIE\s/.test(navigator.userAgent) &&
parseFloat(navigator.appVersion.split("MSIE")[1]) < 10);
allStyles = document.body.style;
// check for matrix 3d support
// source: https://gist.github.com/webinista/3626934
// http://tiffanybbrown.com/2012/09/04/testing-for-css-3d-transforms-support/
allStyles[ (cssPrefix + "transform" ) ] =
'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)';
if ( window.getComputedStyle ) {
LAY.$isGpuAccelerated =
Boolean(
window.getComputedStyle(
document.body, null ).getPropertyValue(
( cssPrefix + "transform" ) ) ) &&
!LAY.$isBelowIE9;
} else {
LAY.$isGpuAccelerated = false;
}
allStyles = undefined;
defaultCss = "position:absolute;display:block;visibility:inherit;" +
"margin:0;padding:0;" +
"backface-visibility: hidden;" +
"-webkit-backface-visibility: hidden;" +
"box-sizing:border-box;-moz-box-sizing:border-box;" +
"transform-style:preserve-3d;-webkit-transform-style:preserve-3d;" +
"-webkit-overflow-scrolling:touch;" +
// "user-drag:none;" +
"white-space:nowrap;" +
"outline:none;border:none;";
// Most CSS text(/font) properties
// match the defaults of LAY, however
// for ones which do not match the
// below list contains their default css
defaultTextCss = defaultCss +
"font-size:15px;" +
"font-family:sans-serif;color:black;" +
"text-decoration:none;" +
"text-align:left;direction:ltr;line-height:1.3em;" +
"white-space:nowrap;" +
"-webkit-font-smoothing:antialiased;";
textDimensionCalculateNodeCss =
defaultTextCss +
"visibility:hidden;height:auto;" +
"border:0px solid transparent;";
inputType2tag = {
multiline: "textarea",
select: "select",
multiple: "select"
};
nonInputType2tag = {
none: "div",
text: "div",
html: "div",
iframe: "iframe",
canvas: "canvas",
image: "img",
video: "video",
audio: "audio",
link: "a"
};
supportedInputTypeS = [
"line", "multiline", "password", "select",
"multiple" ];
var audioElement = document.createElement("audio");
audioElement.controls = true;
document.body.appendChild(audioElement);
audioWidth = audioElement.offsetWidth;
audioHeight = audioElement.offsetHeight;
document.body.removeChild(audioElement);
audioElement = undefined;
function stringifyPlusPx ( val ) {
return val + "px";
}
function setText ( node, text ) {
if ( LAY.$isBelowIE9 ) {
node.innerText = text;
} else {
node.textContent = text;
}
}
function generateSelectOptionsHTML( optionS ) {
var option, html = "";
for ( var i=0, len=optionS.length; i<len; i++ ) {
option = optionS[ i ];
html += "<option value='" + option.value + "'" +
( option.selected ? " selected='true'" : "" ) +
( option.disabled ? " disabled='true'" : "" ) +
">" + option.content + "</option>";
}
return html;
}
textSizeMeasureNode = document.createElement("div");
textSizeMeasureNode.style.cssText =
textDimensionCalculateNodeCss;
document.body.appendChild( textSizeMeasureNode );
imageSizeMeasureNode = document.createElement("img");
imageSizeMeasureNode.style.cssText = defaultCss +
"visibility:hidden;"
document.body.appendChild( imageSizeMeasureNode );
LAY.Part = function ( level ) {
this.level = level;
this.node = undefined;
this.type = undefined;
this.inputType = undefined;
this.isText = undefined;
this.isInitiallyRendered = false;
this.normalRenderDirtyAttrValS = [];
this.travelRenderDirtyAttrValS = [];
this.whenEventType2fnMainHandler = {};
this.isImageLoaded = false;
// for many derived levels
this.formationX = undefined;
this.formationY = undefined;
};
function getInputType ( type ) {
return type.startsWith( "input:" ) &&
type.slice( "input:".length );
}
LAY.Part.prototype.init = function () {
var inputTag, parentNode, inputType;
inputType = this.inputType = getInputType(
this.level.lson.$type );
this.type = this.inputType ? "input" :
this.level.lson.$type;
if ( inputType && supportedInputTypeS.indexOf(
inputType ) === -1 ) {
throw "LAY Error: Unsupported $type: input:" +
inputType;
}
if ( this.level.pathName === "/" ) {
this.node = document.body;
} else if ( this.inputType ) {
inputTag = inputType2tag[ this.inputType ];
if ( inputTag ) {
this.node = document.createElement( inputTag );
if ( inputType === "multiple" ) {
this.node.multiple = true;
}
} else {
this.node = document.createElement( "input" );
this.node.type = this.inputType === "line" ?
"text" : this.inputType;
if ( inputType === "password" ) {
// we wil treat password as a line
// for logic purposes, as we we will
// not alter the input[type] during
// runtime
this.inputType = "line";
}
}
} else {
this.node = document.createElement(
nonInputType2tag[ this.type]);
}
this.isText = this.type === "input" ||
this.type === "text" || this.type === "link" ||
this.type === "html";
if ( this.isText ) {
this.node.style.cssText = defaultTextCss;
} else {
this.node.style.cssText = defaultCss;
}
if ( this.type === "input" && this.inputType === "multiline" ) {
this.node.style.resize = "none";
}
if ( this.type === "image" ) {
var part = this;
LAY.$eventUtils.add( this.node, "load", function() {
part.isImageLoaded = true;
part.updateNaturalWidth();
part.updateNaturalHeight();
LAY.$solve();
});
}
};
// Precondition: not called on "/" level
LAY.Part.prototype.remove = function () {
if ( this.level.pathName !== "/" ) {
var parentPart = this.level.parentLevel.part;
parentPart.updateNaturalWidth();
parentPart.updateNaturalHeight();
// If the level is inexistent from the start
// then the node will not have been attached
if ( this.node.parentNode === parentPart.node ) {
parentPart.node.removeChild( this.node );
}
}
};
LAY.Part.prototype.add = function () {
if ( this.level.pathName !== "/" ) {
var parentPart = this.level.parentLevel.part;
parentPart.updateNaturalWidth();
parentPart.updateNaturalHeight();
this.level.parentLevel.part.node.appendChild( this.node );
}
};
function checkIfLevelIsDisplayed ( level ) {
var attrValDisplay = level.attr2attrVal.display;
return !attrValDisplay || attrValDisplay.calcVal;
}
/*
* Additional constraint of not being dependent upon
* parent for the attr
*/
LAY.Part.prototype.findChildMaxOfAttr =
function ( attr ) {
var
curMaxVal = 0,
childLevel, childLevelAttrVal;
for ( var i = 0,
childLevelS = this.level.childLevelS,
len = childLevelS.length;
i < len; i++ ) {
childLevel = childLevelS[ i ];
if ( childLevel.isPart && !childLevel.isHelper &&
childLevel.isExist ) {
if ( checkIfLevelIsDisplayed( childLevel ) ) {
childLevelAttrVal = childLevel.attr2attrVal[ attr ];
if (
( childLevelAttrVal !== undefined ) &&
( childLevelAttrVal.calcVal )
) {
if ( childLevelAttrVal.calcVal > curMaxVal ) {
curMaxVal = childLevelAttrVal.calcVal;
}
}
}
}
}
return curMaxVal;
};
LAY.Part.prototype.getImmidiateReadonlyVal = function ( attr ) {
switch ( attr ) {
case "$naturalWidth":
return this.calculateNaturalWidth();
case "$naturalHeight":
return this.calculateNaturalHeight();
case "$scrolledX":
return this.node.scrollLeft;
case "$scrolledY":
return this.node.scrollTop;
case "$focused":
return node === document.activeElement;
case "$input":
if ( this.inputType === "multiple" ||
this.inputType === "select" ) {
var optionS =
this.isInitiallyRendered ?
this.node.options :
( // input might not be calculated
// as yet, thus OR with the empty array
this.level.attr2attrVal.input.calcVal || [] );
var valS = [];
for ( var i = 0, len = optionS.length;
i < len; i++ ) {
if ( optionS[ i ].selected ) {
valS.push( optionS[ i ].value )
}
}
// Select the first option if none is selected
// as that will be the default
if ( optionS.length && !valS.length &&
this.inputType === "select" ) {
valS.push(optionS[ 0 ].value );
}
return this.inputType === "select" ?
valS[ 0 ] : valS ;
} else {
return this.node.value;
}
}
};
LAY.Part.prototype.updateNaturalWidth = function () {
var naturalWidthAttrVal =
this.level.$getAttrVal("$naturalWidth");
if ( naturalWidthAttrVal ) {
LAY.$arrayUtils.pushUnique(
LAY.$naturalWidthDirtyPartS,
this );
}
};
LAY.Part.prototype.updateNaturalHeight = function () {
var naturalHeightAttrVal =
this.level.$getAttrVal("$naturalHeight");
if ( naturalHeightAttrVal ) {
LAY.$arrayUtils.pushUnique(
LAY.$naturalHeightDirtyPartS,
this );
}
};
LAY.Part.prototype.calculateNaturalWidth = function () {
var attr2attrVal = this.level.attr2attrVal;
if ( this.isText ) {
return this.calculateTextNaturalDimesion( true );
} else if ( this.type === "image" ) {
return this.calculateImageNaturalDimesion( true );
} else if ( this.type === "audio" ) {
return this.calculateTextNaturalDimesion( true );
} else {
return this.findChildMaxOfAttr( "right" );
}
};
LAY.Part.prototype.calculateNaturalHeight = function () {
var attr2attrVal = this.level.attr2attrVal;
if ( this.isText ) {
return this.calculateTextNaturalDimesion( false );
} else if ( this.type === "image" ) {
return this.calculateImageNaturalDimesion( false );
} else if ( this.type === "audio" ) {
return this.calculateTextNaturalDimesion( false );
} else {
return this.findChildMaxOfAttr( "bottom" );
}
};
LAY.Part.prototype.calculateImageNaturalDimesion = function ( isWidth ) {
if ( !this.isImageLoaded ) {
return 0;
} else {
imageSizeMeasureNode.src =
this.level.attr2attrVal.imageUrl.calcVal;
var otherDim = isWidth ? "height" : "width",
otherDimAttrVal = this.level.attr2attrVal[
otherDim ],
otherDimVal = otherDimAttrVal ?
( otherDimAttrVal.calcVal !== undefined ?
otherDimAttrVal.calcVal + "px" : "auto" ) : "auto";
if ( isWidth ) {
imageSizeMeasureNode.style.height = otherDimVal;
imageSizeMeasureNode.style.width = "auto";
return imageSizeMeasureNode.offsetWidth;
} else {
imageSizeMeasureNode.style.width = otherDimVal;
imageSizeMeasureNode.style.height = "auto";
return imageSizeMeasureNode.offsetHeight;
}
}
};
LAY.Part.prototype.calculateAudioNaturalDimesion = function ( isWidth ) {
var isAudioController =
this.level.attr2attrVal.audioController &&
this.level.attr2attrVal.audioController.calcVal;
if ( isWidth ) {
return isAudioController ? audioWidth : 0;
} else {
return isAudioController ? audioHeight : 0;
}
};
/*
* ( Height occupied naturally by text can be estimated
* without creating a DOM node and checking ".offsetHeight"
* if the text does not wrap, or it does wrap however with
* extremely high probability does not span more than 1 line )
* If the height can be estimated without using a DOM node
* then return the estimated height, else return -1;
*/
LAY.Part.prototype.estimateTextNaturalHeight = function ( text ) {
if ( this.type === "html" &&
checkIfTextMayHaveHTML ( text ) ) {
return -1;
} else {
var heightAttr2default = {
"textSize": 15,
"textWrap": "nowrap",
"textPaddingTop": 0,
"textPaddingBottom": 0,
"borderTopWidth": 0,
"borderBottomWidth": 0,
"textLineHeight": 1.3,
"textLetterSpacing": 1,
"textWordSpacing": 1,
"width": null
};
var heightAttr2val = {};
for ( var heightAttr in heightAttr2default ) {
var attrVal = this.level.attr2attrVal[ heightAttr ];
heightAttr2val[ heightAttr ] = ( attrVal === undefined ||
attrVal.calcVal === undefined ) ?
heightAttr2default[ heightAttr ] : attrVal.calcVal;
}
// Do not turn the below statement into a ternary as
// it will end up being unreadable
var isEstimatePossible = false;
if ( heightAttr2val.textWrap === "nowrap" ) {
isEstimatePossible = true;
} else if (
LAY.$isOkayToEstimateWhitespaceHeight &&
( heightAttr2val.textWrap === "normal" ||
text.indexOf( "\\" ) === -1 ) && //escape characters can
// contain whitespace characters such as line breaks and/or tabs
heightAttr2val.textLetterSpacing === 1 &&
heightAttr2val.textWordSpacing === 1 &&
heightAttr2val.width !== null ) {
if ( text.length < ( 0.7 *
( heightAttr2val.width / heightAttr2val.textSize ) ) ) {
isEstimatePossible = true;
}
}
if ( isEstimatePossible ) {
return ( heightAttr2val.textSize * heightAttr2val.textLineHeight ) +
heightAttr2val.textPaddingTop +
heightAttr2val.textPaddingBottom +
heightAttr2val.borderTopWidth +
heightAttr2val.borderBottomWidth;
} else {
return -1;
}
}
};
function checkIfTextMayHaveHTML( text ) {
return text.indexOf( "<" ) !== -1 && text.indexOf( ">" ) !== -1;
};
LAY.Part.prototype.calculateTextNaturalDimesion = function ( isWidth ) {
var dimensionAlteringAttr2fnStyle = {
textSize: stringifyPxOrString,
textFamily: null,
textWeight: null,
textAlign: null,
textStyle: null,
textDirection: null,
textTransform: null,
textVariant: null,
textLetterSpacing: stringifyPxOrStringOrNormal,
textWordSpacing: stringifyPxOrStringOrNormal,
textLineHeight: stringifyEmOrString,
textOverflow: null,
textIndent: stringifyPlusPx,
textWrap: null,
textWordBreak: null,
textWordWrap: null,
textRendering: null,
textPaddingTop: stringifyPlusPx,
textPaddingRight: stringifyPlusPx,
textPaddingBottom: stringifyPlusPx,
textPaddingLeft: stringifyPlusPx,
borderTopWidth: stringifyPlusPx,
borderRightWidth: stringifyPlusPx,
borderBottomWidth: stringifyPlusPx,
borderLeftWidth: stringifyPlusPx
};
var dimensionAlteringAttr2cssProp = {
textSize: "font-size",
textFamily: "font-family",
textWeight: "font-weight",
textAlign: "text-align",
textStyle: "font-style",
textDirection: "direction",
textTransform: "text-transform",
textVariant: "font-variant",
textLetterSpacing: "letter-spacing",
textWordSpacing: "word-spacing",
textLineHeight: "line-height",
textOverflow: "text-overflow",
textIndent: "text-indent",
textWrap: "white-space",
textWordBreak: "word-break",
textWordWrap: "word-wrap",
textRendering: "text-rendering",
textPaddingTop: "padding-top",
textPaddingRight: "padding-right",
textPaddingBottom: "padding-bottom",
textPaddingLeft: "padding-left",
borderTopWidth: "border-top-width",
borderRightWidth: "border-right-width",
borderBottomWidth: "border-bottom-width",
borderLeftWidth: "border-left-width"
};
var
attr2attrVal = this.level.attr2attrVal,
dimensionAlteringAttr, fnStyle,
textRelatedAttrVal,
content, ret,
cssText = textDimensionCalculateNodeCss;
if ( this.type === "input" ) {
if ( this.inputType === "select" ||
this.inputType === "multiple" ) {
if ( attr2attrVal.input.isRecalculateRequired ) {
return 0
}
content = "<select" +
( this.inputType === "multiple" ?
" multiple='true' " : "" ) + ">" +
generateSelectOptionsHTML(
attr2attrVal.input.calcVal
) + "</select>";
} else {
content = attr2attrVal.$input ?
attr2attrVal.$input.calcVal : "a";
}
} else {
if ( attr2attrVal.text.isRecalculateRequired ) {
return 0;
}
content = attr2attrVal.text.calcVal;
}
if ( typeof content !== "string" ) {
content = content.toString();
}
if ( !isWidth ) {
var estimatedHeight = this.estimateTextNaturalHeight( content );
if ( estimatedHeight !== -1 ) {
return estimatedHeight;
}
}
for ( dimensionAlteringAttr in
dimensionAlteringAttr2fnStyle ) {
textRelatedAttrVal = attr2attrVal[
dimensionAlteringAttr ];
if ( textRelatedAttrVal &&
textRelatedAttrVal.calcVal !== undefined ) {
fnStyle = dimensionAlteringAttr2fnStyle[
dimensionAlteringAttr ];
cssText +=
dimensionAlteringAttr2cssProp[
dimensionAlteringAttr ] + ":" +
( (fnStyle === null) ?
textRelatedAttrVal.calcVal :
fnStyle( textRelatedAttrVal.calcVal ) ) + ";";
}
}
if ( isWidth ) {
cssText += "display:inline;width:auto;";
textSizeMeasureNode.style.cssText = cssText;
if ( this.type === "html" ) {
textSizeMeasureNode.innerHTML = content;
} else {
setText( textSizeMeasureNode, content );
}
ret = textSizeMeasureNode.offsetWidth;
} else {
cssText += "width:" +
( attr2attrVal.width.calcVal || 0 ) + "px;";
textSizeMeasureNode.style.cssText = cssText;
// If empty we will subsitute with the character "a"
// as we wouldn't want the height to resolve to 0
if ( this.type === "html" ) {
textSizeMeasureNode.innerHTML = content || "a";
} else {
setText( textSizeMeasureNode, content || "a" );
}
ret = textSizeMeasureNode.offsetHeight;
}
return ret;
};
LAY.Part.prototype.addNormalRenderDirtyAttrVal = function ( attrVal ) {
LAY.$arrayUtils.remove( this.travelRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( this.normalRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( LAY.$renderDirtyPartS, this );
};
LAY.Part.prototype.addTravelRenderDirtyAttrVal = function ( attrVal ) {
LAY.$arrayUtils.remove( this.normalRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( this.travelRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( LAY.$renderDirtyPartS, this );
};
LAY.Part.prototype.updateWhenEventType = function ( eventType ) {
var
numFnHandlersForEventType =
this.level.attr2attrVal[ "$$num.when." + eventType ].val,
fnMainHandler,
thisLevel = this.level,
node = this.node;
if ( LAY.$checkIsWindowEvent( eventType ) &&
this.level.pathName === "/" ) {
node = window;
}
if ( this.whenEventType2fnMainHandler[ eventType ] !== undefined ) {
LAY.$eventUtils.remove(
node, eventType,
this.whenEventType2fnMainHandler[ eventType ] );
}
if ( numFnHandlersForEventType !== 0 ) {
fnMainHandler = function ( e ) {
var i, len, attrValForFnHandler;
for ( i = 0; i < numFnHandlersForEventType; i++ ) {
attrValForFnHandler =
thisLevel.attr2attrVal[ "when." + eventType + "." + ( i + 1 ) ];
if ( attrValForFnHandler !== undefined ) {
attrValForFnHandler.calcVal.call( thisLevel, e );
}
}
};
LAY.$eventUtils.add( node, eventType, fnMainHandler );
this.whenEventType2fnMainHandler[ eventType ] = fnMainHandler;
} else {
this.whenEventType2fnMainHandler[ eventType ] = undefined;
}
};
LAY.Part.prototype.checkIsPropInTransition = function ( prop ) {
return ( this.level.attr2attrVal[ "transition." + prop + ".type" ] !==
undefined ) ||
( this.level.attr2attrVal[ "transition." + prop + ".delay" ] !==
undefined );
};
LAY.Part.prototype.updateTransitionProp = function ( transitionProp ) {
if ( this.isInitiallyRendered ) {
var
attr2attrVal = this.level.attr2attrVal,
attr, attrVal,
transitionPrefix,
transitionType, transitionDuration, transitionDelay, transitionDone,
transitionArgS, transitionArg2val = {},
transitionObj,
i, len,
allAffectedProp, // (eg: when `top` changes but transition
//is provided by `positional`)
affectedPropAttrVal;
// TODO: change the below to a helper function
if ( ( [ "centerX", "right", "centerY", "bottom" ] ).indexOf(
transitionProp ) !== -1 ) {
return;
}
if ( !this.checkIsPropInTransition( transitionProp ) ) {
if ( this.checkIsPropInTransition( "all" ) ) {
allAffectedProp = transitionProp;
transitionProp = "all";
} else {
return;
}
}
transitionPrefix = "transition." + transitionProp + ".";
transitionType =
attr2attrVal[ transitionPrefix + "type" ] ?
attr2attrVal[ transitionPrefix + "type" ].calcVal :
"linear";
transitionDuration =
( attr2attrVal[ transitionPrefix + "duration" ] ?
attr2attrVal[ transitionPrefix + "duration" ].calcVal :
0 );
transitionDelay =
( attr2attrVal[ transitionPrefix + "delay" ] ?
attr2attrVal[ transitionPrefix + "delay" ].calcVal :
0 );
transitionDone =
( attr2attrVal[ transitionPrefix + "done" ] ?
attr2attrVal[ transitionPrefix + "done" ].calcVal :
undefined );
transitionArgS = LAY.$transitionType2args[ transitionType ] ?
LAY.$transitionType2args[ transitionType ] : [];
for ( i = 0, len = transitionArgS.length; i < len; i++ ) {
transitionArg2val[ transitionArgS[ i ] ] = (
attr2attrVal[ transitionPrefix + "args." +
transitionArgS[ i ] ] ?
attr2attrVal[ transitionPrefix + "args." +
transitionArgS[ i ] ].calcVal : undefined );
}
if ( !allAffectedProp && ( transitionProp === "all" ) ) {
for ( attr in attr2attrVal ) {
attrVal = attr2attrVal[ attr ];
// Only invoke a transition if:
// (1) The prop is renderable (i.e has a render call)
// (2) The prop doesn't have a transition of its
// own. For instance if "left" already has
// a transition then we will not want to override
// its transition with the lower priority "all" transition
if ( attrVal.renderCall &&
!this.checkIsPropInTransition( attrVal.attr ) ) {
this.updateTransitionAttrVal(
attrVal,
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone
);
}
}
} else {
this.updateTransitionAttrVal(
attr2attrVal[ allAffectedProp || transitionProp ],
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone
);
}
}
};
LAY.Part.prototype.updateTransitionAttrVal = function ( attrVal,
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone ) {
// First check if the transition information is complete
if (
transitionType &&
( transitionDuration !== undefined ) &&
( transitionDelay !== undefined ) &&
( attrVal !== undefined ) &&
( attrVal.isTransitionable )
) {
attrVal.startCalcVal = attrVal.transCalcVal;
attrVal.transition = new LAY.Transition (
transitionType,
transitionDelay,
transitionDuration, transitionArg2val,
transitionDone );
} else if ( attrVal !== undefined ) { // else delete the transition
attrVal.transition = undefined;
}
}
function stringifyPxOrString( val, defaultVal ) {
return ( val === undefined ) ?
defaultVal : ( typeof val === "number" ?
( val + "px" ) : val );
}
function stringifyPxOrStringOrNormal( val, defaultVal ) {
if ( val === 0 ) {
return "normal";
} else {
return stringifyPlusPx( val, defaultVal );
}
}
function stringifyEmOrString( val, defaultVal ) {
return ( val === undefined ) ?
defaultVal : ( typeof val === "number" ?
( val + "em" ) : val );
}
function computePxOrString( attrVal, defaultVal ) {
return stringifyPxOrString(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computePxOrStringOrNormal( attrVal, defaultVal ) {
return stringifyPxOrStringOrNormal(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computeEmOrString( attrVal, defaultVal ) {
return stringifyEmOrString(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computeColorOrString( attrVal, defaultVal ) {
var transCalcVal =
attrVal && attrVal.transCalcVal;
return ( transCalcVal === undefined ) ?
defaultVal : ( transCalcVal instanceof LAY.Color ?
transCalcVal.stringify() : transCalcVal );
}
LAY.Part.prototype.render = function ( renderCall ) {
var attr2attrVal = this.level.attr2attrVal;
switch ( renderCall ) {
case "x":
this.node.style.left =
( attr2attrVal.left.transCalcVal +
( attr2attrVal.shiftX !== undefined ?
attr2attrVal.shiftX.transCalcVal : 0 ) ) +
"px";
break;
case "y":
this.node.style.top =
( attr2attrVal.top.transCalcVal +
( attr2attrVal.shiftY !== undefined ?
attr2attrVal.shiftY.transCalcVal : 0 ) ) +
"px";
break;
case "positionAndTransform":
cssPrefix = cssPrefix === "-moz-" ? "" : cssPrefix;
this.node.style[ cssPrefix + "transform" ] =
"translate(" +
( ( attr2attrVal.left.transCalcVal +
( attr2attrVal.shiftX !== undefined ?
attr2attrVal.shiftX.transCalcVal : 0 ) ) + "px, " ) +
( ( attr2attrVal.top.transCalcVal +
( attr2attrVal.shiftY !== undefined ?
attr2attrVal.shiftY.transCalcVal : 0 ) ) + "px) " ) +
( attr2attrVal.z !== undefined ?
"translateZ(" + attr2attrVal.z.transCalcVal + "px) " : "" ) +
( attr2attrVal.scaleX !== undefined ?
"scaleX(" + attr2attrVal.scaleX.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleY !== undefined ?
"scaleY(" + attr2attrVal.scaleY.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleZ !== undefined ?
"scaleZ(" + attr2attrVal.scaleZ.transCalcVal + ") " : "" ) +
( attr2attrVal.skewX !== undefined ?
"skewX(" + attr2attrVal.skewX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.skewY !== undefined ?
"skewY(" + attr2attrVal.skewY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateX !== undefined ?
"rotateX(" + attr2attrVal.rotateX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateY !== undefined ?
"rotateY(" + attr2attrVal.rotateY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateZ !== undefined ?
"rotateZ(" + attr2attrVal.rotateZ.transCalcVal + "deg)" : "" );
break;
case "transform":
cssPrefix = cssPrefix === "-moz-" ? "" : cssPrefix;
this.node.style[ cssPrefix + "transform" ] =
( attr2attrVal.scaleX !== undefined ?
"scaleX(" + attr2attrVal.scaleX.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleY !== undefined ?
"scaleY(" + attr2attrVal.scaleY.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleZ !== undefined ?
"scaleZ(" + attr2attrVal.scaleZ.transCalcVal + ") " : "" ) +
( attr2attrVal.skewX !== undefined ?
"skewX(" + attr2attrVal.skewX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.skewY !== undefined ?
"skewY(" + attr2attrVal.skewY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateX !== undefined ?
"rotateX(" + attr2attrVal.rotateX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateY !== undefined ?
"rotateY(" + attr2attrVal.rotateY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateZ !== undefined ?
"rotateZ(" + attr2attrVal.rotateZ.transCalcVal + "deg)" : "" );
break;
case "width":
this.node.style.width =
attr2attrVal.width.transCalcVal + "px";
if ( [ "canvas", "video", "image","iframe" ].indexOf(
this.type ) !== -1 ) {
this.node.width =
attr2attrVal.width.transCalcVal;
}
break;
case "height":
this.node.style.height =
attr2attrVal.height.transCalcVal + "px";
if ( [ "canvas", "video", "image","iframe" ].indexOf(
this.type ) !== -1 ) {
this.node.height =
attr2attrVal.height.transCalcVal;
}
break;
case "origin":
this.node.style[ cssPrefix + "transform-origin" ] =
( ( attr2attrVal.originX !== undefined ?
attr2attrVal.originX.transCalcVal : 0.5 ) * 100 ) + "% " +
( ( attr2attrVal.originY !== undefined ?
attr2attrVal.originY.transCalcVal : 0.5 ) * 100 ) + "% " +
( attr2attrVal.originZ !== undefined ?
attr2attrVal.originZ.transCalcVal : 0 ) + "px";
break;
case "perspective":
this.node.style[ cssPrefix + "perspective" ] =
attr2attrVal.perspective.transCalcVal + "px";
break;
case "perspectiveOrigin":
this.node.style[ cssPrefix + "perspective-origin" ] =
( attr2attrVal.perspectiveOriginX ?
( attr2attrVal.perspectiveOriginX.transCalcVal * 100 )
: 0 ) + "% " +
( attr2attrVal.perspectiveOriginY ?
( attr2attrVal.perspectiveOriginY.transCalcVal * 100 )
: 0 ) + "%";
break;
case "backfaceVisibility":
this.node.style[ cssPrefix + "backface-visibility" ] =
attr2attrVal.backfaceVisibility.transCalcVal;
break;
case "opacity":
this.node.style.opacity = attr2attrVal.opacity.transCalcVal;
break;
case "display":
this.node.style.display =
attr2attrVal.display.transCalcVal ?
"block" : "none";
break;
case "visible":
this.node.style.visibility =
attr2attrVal.visible.transCalcVal ?
"inherit" : "hidden";
break;
case "zIndex":
this.node.style.zIndex =
attr2attrVal.zIndex.transCalcVal || "auto";
break;
case "focus":
if ( attr2attrVal.focus.transCalcVal ) {
this.node.focus();
} else if ( document.activeElement === this.node ) {
document.body.focus();
}
break;
case "scrollX":
this.node.scrollLeft =
attr2attrVal.scrollX.transCalcVal;
break;
case "scrollY":
this.node.scrollTop =
attr2attrVal.scrollY.transCalcVal;
break;
case "scrollElastic":
this.node["-webkit-overflow-scrolling"] =
attr2attrVal.scrollElastic.transCalcVal ?
"touch" : "auto";
break;
case "overflowX":
this.node.style.overflowX =
attr2attrVal.overflowX.transCalcVal;
break;
case "overflowY":
this.node.style.overflowY =
attr2attrVal.overflowY.transCalcVal;
break;
case "cursor":
this.node.style.cursor = attr2attrVal.
cursor.transCalcVal;
break;
case "userSelect":
if ( this.type !== "input" ) {
this.node.style[ cssPrefix + "user-select" ] =
attr2attrVal.userSelect.transCalcVal;
}
break;
case "title":
this.node.title =
attr2attrVal.title.transCalcVal;
break;
case "tabindex":
this.node.tabindex =
attr2attrVal.
tabindex.transCalcVal;
break;
case "backgroundColor":
this.node.style.backgroundColor =
attr2attrVal.
backgroundColor.transCalcVal.stringify();
break;
case "backgroundAttachment":
this.node.style.backgroundAttachment =
attr2attrVal.backgroundAttachment.transCalcVal;
break;
case "backgroundRepeat":
this.node.style.backgroundRepeat =
attr2attrVal.backgroundRepeat.transCalcVal;
break;
case "backgroundSize":
this.node.style.backgroundSize =
computePxOrString(
attr2attrVal.backgroundSizeX, "auto" ) +
" " +
computePxOrString(
attr2attrVal.backgroundSizeY, "auto" );
break;
case "backgroundPosition":
this.node.style.backgroundPosition =
computePxOrString(
attr2attrVal.backgroundPositionX, "0px" ) +
" " +
computePxOrString(
attr2attrVal.backgroundPositionX, "0px" );
break;
case "boxShadows":
if ( !LAY.$isBelowIE9 ) {
var s = "";
for ( var i = 1, len = attr2attrVal[ "$$max.boxShadows" ].calcVal;
i <= len; i++ ) {
s +=
( ( attr2attrVal["boxShadows" + i + "Inset" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Inset" ].transCalcVal :
false ) ? "inset " : "" ) +
( attr2attrVal["boxShadows" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["boxShadows" + i + "Y" ].transCalcVal + "px " ) +
( ( attr2attrVal["boxShadows" + i + "Blur" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Blur" ].transCalcVal : 0 )
+ "px " ) +
( ( attr2attrVal["boxShadows" + i + "Spread" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Spread" ].transCalcVal : 0 )
+ "px " ) +
( attr2attrVal["boxShadows" + i + "Color" ].
transCalcVal.stringify() );
if ( i !== len ) {
s += ",";
}
}
this.node.style.boxShadow = s;
}
break;
case "filters":
var s = "", filterType;
for ( var i = 1, len = attr2attrVal[ "$$max.filters" ].calcVal;
i <= len; i++ ) {
filterType = attr2attrVal[ "filters" + i + "Type" ].calcVal;
switch ( filterType ) {
case "dropShadow":
s += "drop-shadow(" +
( attr2attrVal["filters" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["filters" + i + "Y" ].transCalcVal + "px " ) +
( attr2attrVal["filters" + i + "Blur" ].transCalcVal + "px " ) +
// ( ( attr2attrVal["filters" + i + "Spread" ] !== undefined ?
// attr2attrVal[ "filters" + i + "Spread" ].transCalcVal : 0 ) + "px " ) +
( attr2attrVal["filters" + i + "Color" ].
transCalcVal.stringify() ) +
") ";
break;
case "blur":
s += "blur(" + attr2attrVal[ "filters" + i + "Blur" ] + ") ";
break;
case "hueRotate":
s += "hue-rotate(" + attr2attrVal[ "filters" + i +
"HueRotate" ] + "deg) ";
break;
case "url":
s += "url(" + attr2attrVal[ "filters" + i + "Url" ] + ") ";
break;
default:
s += filterType + "(" + ( attr2attrVal[ "filters" + i +
LAY.$capitalize( filterType ) ] * 100 ) + "%) ";
}
}
this.node.style[ cssPrefix + "filter" ] = s;
break;
case "cornerRadiusTopLeft":
this.node.style.borderTopLeftRadius =
attr2attrVal.cornerRadiusTopLeft.transCalcVal + "px";
break;
case "cornerRadiusTopRight":
this.node.style.borderTopRightRadius =
attr2attrVal.cornerRadiusTopRight.transCalcVal + "px";
break;
case "cornerRadiusBottomRight":
this.node.style.borderBottomRightRadius =
attr2attrVal.cornerRadiusBottomRight.transCalcVal + "px";
break;
case "cornerRadiusBottomLeft":
this.node.style.borderBottomLeftRadius =
attr2attrVal.cornerRadiusBottomLeft.transCalcVal + "px";
break;
case "borderTopStyle":
this.node.style.borderTopStyle =
attr2attrVal.borderTopStyle.transCalcVal;
break;
case "borderRightStyle":
this.node.style.borderRightStyle =
attr2attrVal.borderRightStyle.transCalcVal;
break;
case "borderBottomStyle":
this.node.style.borderBottomStyle =
attr2attrVal.borderBottomStyle.transCalcVal;
break;
case "borderLeftStyle":
this.node.style.borderLeftStyle =
attr2attrVal.borderLeftStyle.transCalcVal;
break;
case "borderTopColor":
this.node.style.borderTopColor =
attr2attrVal.borderTopColor.transCalcVal.stringify();
break;
case "borderRightColor":
this.node.style.borderRightColor =
attr2attrVal.borderRightColor.transCalcVal.stringify();
break;
case "borderBottomColor":
this.node.style.borderBottomColor =
attr2attrVal.borderBottomColor.transCalcVal.stringify();
break;
case "borderLeftColor":
this.node.style.borderLeftColor =
attr2attrVal.borderLeftColor.transCalcVal.stringify();
break;
case "borderTopWidth":
this.node.style.borderTopWidth =
attr2attrVal.borderTopWidth.transCalcVal + "px";
break;
case "borderRightWidth":
this.node.style.borderRightWidth =
attr2attrVal.borderRightWidth.transCalcVal + "px";
break;
case "borderBottomWidth":
this.node.style.borderBottomWidth =
attr2attrVal.borderBottomWidth.transCalcVal + "px";
break;
case "borderLeftWidth":
this.node.style.borderLeftWidth =
attr2attrVal.borderLeftWidth.transCalcVal + "px";
break;
case "text":
var text = attr2attrVal.text.transCalcVal;
if ( this.type === "html" ) {
this.node.innerHTML = text;
} else { //else is type "html"
setText( this.node, text );
}
break;
case "textSize":
this.node.style.fontSize =
computePxOrString( attr2attrVal.textSize );
break;
case "textFamily":
this.node.style.fontFamily =
attr2attrVal.textFamily.transCalcVal;
break;
case "textWeight":
this.node.style.fontWeight =
attr2attrVal.textWeight.transCalcVal;
break;
case "textColor":
this.node.style.color =
computeColorOrString(
attr2attrVal.textColor );
break;
case "textVariant":
this.node.style.fontVariant =
attr2attrVal.textVariant.transCalcVal;
break;
case "textTransform":
this.node.style.textTransform =
attr2attrVal.textTransform.transCalcVal;
break;
case "textStyle":
this.node.style.fontStyle =
attr2attrVal.textStyle.transCalcVal;
break;
case "textDecoration":
this.node.style.textDecoration =
attr2attrVal.textDecoration.transCalcVal;
break;
case "textLetterSpacing":
this.node.style.letterSpacing = computePxOrStringOrNormal(
attr2attrVal.textLetterSpacing );
break;
case "textWordSpacing":
this.node.style.wordSpacing = computePxOrStringOrNormal(
attr2attrVal.textWordSpacing );
break;
case "textAlign":
this.node.style.textAlign = attr2attrVal.textAlign.transCalcVal;
break;
case "textDirection":
this.node.style.direction = attr2attrVal.textDirection.transCalcVal;
break;
case "textLineHeight":
this.node.style.lineHeight = computeEmOrString(
attr2attrVal.textLineHeight );
break;
case "textOverflow":
this.node.style.textOverflow =
attr2attrVal.textOverflow.transCalcVal;
break;
case "textIndent":
this.node.style.textIndent =
attr2attrVal.textIndent.transCalcVal + "px";
break;
case "textWrap":
this.node.style.whiteSpace = attr2attrVal.textWrap.transCalcVal;
break;
case "textWordBreak":
this.node.style.wordBreak = attr2attrVal.textWordBreak.transCalcVal;
break;
case "textWordWrap":
this.node.style.wordWrap = attr2attrVal.textWordWrap.transCalcVal;
break;
case "textSmoothing":
this.node.style[ cssPrefix + "font-smoothing" ] =
attr2attrVal.textSmoothing.transCalcVal;
break;
case "textRendering":
this.node.style.textRendering = attr2attrVal.textRendering.transCalcVal;
break;
case "textPaddingTop":
this.node.style.paddingTop =
attr2attrVal.textPaddingTop.transCalcVal + "px";
break;
case "textPaddingRight":
this.node.style.paddingRight =
attr2attrVal.textPaddingRight.transCalcVal + "px";
break;
case "textPaddingBottom":
this.node.style.paddingBottom =
attr2attrVal.textPaddingBottom.transCalcVal + "px";
break;
case "textPaddingLeft":
this.node.style.paddingLeft =
attr2attrVal.textPaddingLeft.transCalcVal + "px";
break;
case "textShadows":
var s = "";
for ( var i = 1, len = attr2attrVal[ "$$max.textShadows" ].calcVal;
i <= len; i++ ) {
s +=
( attr2attrVal["textShadows" + i + "Color" ].
transCalcVal.stringify() ) + " " +
( attr2attrVal["textShadows" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["textShadows" + i + "Y" ].transCalcVal + "px " ) +
( attr2attrVal["textShadows" + i + "Blur" ].transCalcVal + "px" );
if ( i !== len ) {
s += ",";
}
}
this.node.style.textShadow = s;
break;
case "input":
var inputVal = attr2attrVal.input.transCalcVal;
if ( this.inputType === "select" || this.inputType === "multiple" ) {
this.node.innerHTML = generateSelectOptionsHTML( inputVal );
} else {
this.node.value = inputVal;
}
break;
case "inputLabel":
this.node.label = attr2attrVal.inputLabel.transCalcVal;
break;
case "inputPlaceholder":
this.node.placeholder = attr2attrVal.inputPlaceholder.transCalcVal;
break;
case "inputAutocomplete":
this.node.autocomplete = attr2attrVal.inputAutocomplete.transCalcVal;
break;
case "inputAutocorrect":
this.node.autocorrect = attr2attrVal.inputAutocorrect.transCalcVal;
break;
case "inputDisabled":
this.node.disabled = attr2attrVal.inputDisabled.transCalcVal;
break;
case "linkHref":
this.node.href = attr2attrVal.linkHref.transCalcVal;
break;
case "linkRel":
this.node.rel = attr2attrVal.linkRel.transCalcVal;
break;
case "linkDownload":
this.node.download = attr2attrVal.linkDownload.transCalcVal;
break;
case "linkTarget":
this.node.target = attr2attrVal.linkTarget.transCalcVal;
break;
case "imageUrl":
this.node.src = attr2attrVal.imageUrl.transCalcVal;
break;
case "imageAlt":
this.node.alt = attr2attrVal.imageAlt.transCalcVal;
break;
case "audioSrc":
this.node.src = attr2attrVal.audioSrc.transCalcVal;
break;
case "audioSources":
var
documentFragment = document.createDocumentFragment(),
childNodes = this.node.childNodes,
childNode;
// first remove the current audio sources
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[ i ];
if ( childNode.tagName === "SOURCE" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.audioSources" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "source" );
childNode.type =
attr2attrVal[ "audioSources" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "audioSources" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
this.node.appendChild( documentFragment );
break;
case "audioTracks":
var
documentFragment = document.createDocumentFragment(),
childNodes = this.node.childNodes,
childNode;
// first remove the current audio tracks
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[ i ];
if ( childNode.tagName === "TRACK" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.audioTracks" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "track" );
childNode.type =
attr2attrVal[ "audioTracks" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "audioTracks" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
this.node.appendChild( documentFragment );
break;
case "audioVolume":
this.node.volume = attr2attrVal.audioVolume.transCalcVal;
break;
case "audioController":
this.node.controls = attr2attrVal.audioController.transCalcVal;
break;
case "audioLoop":
this.node.loop = attr2attrVal.audioLoop.transCalcVal;
break;
case "audioMuted":
this.node.muted = attr2attrVal.audioMuted.transCalcVal;
break;
case "audioPreload":
this.node.preload = attr2attrVal.audioPreload.transCalcVal;
break;
case "videoSrc":
this.node.src = attr2attrVal.videoSrc.transCalcVal;
break;
case "videoSources":
var
documentFragment = document.createDocumentFragment(),
childNodes = this.node.childNodes,
childNode;
// first remove the current video sources
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[ i ];
if ( childNode.tagName === "SOURCE" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.videoSources" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "source" );
childNode.type =
attr2attrVal[ "videoSources" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "videoSources" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
this.node.appendChild( documentFragment );
break;
case "videoTracks":
var
documentFragment = document.createDocumentFragment(),
childNodes = this.node.childNodes,
childNode;
// first remove the current video tracks
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[ i ];
if ( childNode.tagName === "TRACK" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.videoTracks" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "track" );
childNode.type =
attr2attrVal[ "videoTracks" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "videoTracks" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
this.node.appendChild( documentFragment );
break;
case "videoAutoplay":
this.node.autoplay = attr2attrVal.videoAutoplay.transCalcVal;
break;
case "videoController":
this.node.controls = attr2attrVal.videoController.transCalcVal;
break;
case "videoCrossorigin":
this.node.crossorigin = attr2attrVal.videoCrossorigin.transCalcVal;
break;
case "videoLoop":
this.node.loop = attr2attrVal.videoLoop.transCalcVal;
break;
case "videoMuted":
this.node.muted = attr2attrVal.videoMuted.transCalcVal;
break;
case "videoPreload":
this.node.preload = attr2attrVal.videoPreload.transCalcVal;
break;
case "videoPoster":
this.node.poster = attr2attrVal.videoPoster.transCalcVal;
break;
case "iframeSrc":
this.node.src = attr2attrVal.iframeSrc.transCalcVal;
break;
default:
throw "LAY Error: Inexistent prop: '" + renderCall + "'";
}
};
})();
( function () {
"use strict";
LAY.Query = function ( rowS ) {
this.rowS = rowS;
};
LAY.Query.prototype.filterEq = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.eq(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterNeq = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.neq(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterGt = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.gt(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterGte = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.gte(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterLt = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.lt(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterLte = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.lte(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterRegex = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.regex(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterContains = function ( key, val ) {
return new LAY.Query( LAY.$filterUtils.contains(
this.rowS, key, val ) );
};
LAY.Query.prototype.filterWithin = function ( key, val ) {
return new LAY.Query(
LAY.$filterUtils.within( this.rowS, key, val ) );
};
LAY.Query.prototype.filterFn = function ( fnFilter ) {
return new LAY.Query( LAY.$filterUtils.fn(
this.rowS, fnFilter ) );
};
LAY.Query.prototype.foldMin = function ( key ) {
return LAY.$foldUtils.min( this.rowS, key, val );
};
LAY.Query.prototype.foldMax = function ( key ) {
return LAY.$foldUtils.max( this.rowS, key, val );
};
LAY.Query.prototype.foldSum = function ( key ) {
return LAY.$foldUtils.sum( this.rowS, key, val );
};
LAY.Query.prototype.foldFn = function ( fnFold, acc ) {
return LAY.$foldUtils.fn( this.rowS, fnFold, acc );
};
LAY.Query.prototype.index = function ( i ) {
return this.rowS[ i ];
};
LAY.Query.prototype.length = function () {
return this.rowS.length;
};
LAY.Query.prototype.finish = function () {
return this.rowS;
};
})();
(function () {
"use strict";
LAY.RelPath = function ( relativePath ) {
this.isMe = false;
this.isMany = false;
this.path = "";
this.isAbsolute = false;
this.traverseArray = [];
if ( relativePath === "" ) {
this.isMe = true;
} else {
if ( relativePath.charAt(0) === "/" ) {
this.isAbsolute = true;
this.path = relativePath;
} else {
var i=0;
while ( relativePath.charAt( i ) === "." ) {
if ( relativePath.slice(i, i+3) === "../" ) {
this.traverseArray.push(0);
i +=3;
} else if ( relativePath.slice(i, i+4) === ".../" ) {
this.traverseArray.push(1);
i += 4;
} else {
throw "LAY Error: Error in Take path: " + relativePath;
}
}
// strip off the "../"s
// eg: "../../Body" should become "Body"
this.path = relativePath.slice( i );
}
if ( this.path.length !== 0 &&
this.path.indexOf("*") === this.path.length - 1 ) {
this.isMany = true;
if ( this.path.length === 1 ) {
this.path = "";
} else {
this.path = this.path.slice(0, this.path.length-2);
}
}
}
};
LAY.RelPath.prototype.resolve = function ( referenceLevel ) {
if ( this.isMe ) {
return referenceLevel;
} else {
var level;
if ( this.isAbsolute ) {
level = LAY.$pathName2level[ this.path ];
} else {
level = referenceLevel;
var traverseArray = this.traverseArray;
for ( var i=0, len=traverseArray.length; i<len; i++ ) {
if ( traverseArray[ i ] === 0 ) { //parent traversal
level = level.parentLevel;
} else { //closest row traversal
do {
level = level.parentLevel;
} while ( !level.derivedMany )
}
}
level = ( this.path === "" ) ? level :
LAY.$pathName2level[ level.pathName +
( ( level.pathName === "/" ) ? "" : "/" )+
this.path ];
}
if ( this.isMany ) {
return level.derivedMany.level;
} else {
return level;
}
}
};
})();
( function () {
"use strict";
LAY.Take = function ( relativePath, attr ) {
var _relPath00attr_S;
if ( attr !== undefined ) {
var path = new LAY.RelPath( relativePath );
_relPath00attr_S = [ [ path, attr ] ];
this.executable = function () {
return path.resolve( this ).$getAttrVal( attr ).calcVal;
};
} else { // direct value provided
_relPath00attr_S = [];
// note that 'relativePath' is misleading name
// here in this second overloaded case
var directValue = relativePath;
if ( directValue instanceof LAY.Take ) {
this.executable = directValue.executable;
_relPath00attr_S = directValue._relPath00attr_S;
} else {
this.executable = function () {
return directValue;
};
}
}
this._relPath00attr_S = _relPath00attr_S;
};
LAY.Take.prototype.execute = function ( contextPart ) {
// pass in context part for relative path lookups
return this.executable.call( contextPart );
};
LAY.Take.prototype.$mergePathAndAttrs = function ( take ) {
var _relPath00attr_S = take._relPath00attr_S;
for ( var i = 0, len = _relPath00attr_S.length; i < len; i++ ) {
this._relPath00attr_S.push( _relPath00attr_S[ i ] );
}
};
LAY.Take.prototype.add = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) + val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) + val;
};
}
return this;
};
LAY.Take.prototype.plus = LAY.Take.prototype.add;
LAY.Take.prototype.subtract = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) - val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) - val;
};
}
return this;
};
LAY.Take.prototype.minus = LAY.Take.prototype.subtract;
LAY.Take.prototype.divide = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) / val.execute( this );
};
} else {
if ( val === 2 ) {
return this.half();
}
this.executable = function () {
return oldExecutable.call( this ) / val;
};
}
return this;
};
LAY.Take.prototype.multiply = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) * val.execute( this );
};
} else {
if ( val === 2 ) {
return this.double();
}
this.executable = function () {
return oldExecutable.call( this ) * val;
};
}
return this;
};
LAY.Take.prototype.remainder = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) % val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) % val;
};
}
return this;
};
LAY.Take.prototype.half = function ( ) {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ) / 2;
};
return this;
};
LAY.Take.prototype.double = function ( ) {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ) * 2;
};
return this;
};
LAY.Take.prototype.contains = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).indexOf( val.execute( this ) ) !== -1;
};
} else {
this.executable = function () {
return oldExecutable.call( this ).indexOf( val ) !== -1;
};
}
return this;
};
LAY.Take.prototype.identical = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.identical( oldExecutable.call( this ),
val.execute( this ) );
};
} else {
this.executable = function () {
return LAY.identical( oldExecutable.call( this ), val );
};
}
return this;
};
LAY.Take.prototype.eq = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) === val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) === val;
};
}
return this;
};
LAY.Take.prototype.neq = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) !== val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) !== val;
};
}
return this;
};
LAY.Take.prototype.gt = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) > val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) > val;
};
}
return this;
};
LAY.Take.prototype.gte = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) >= val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) >= val;
};
}
return this;
};
LAY.Take.prototype.lt = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) < val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) < val;
};
}
return this;
};
LAY.Take.prototype.lte = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) <= val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) <= val;
};
}
return this;
};
LAY.Take.prototype.or = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) || val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) || val;
};
}
return this;
};
LAY.Take.prototype.and = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ) && val.execute( this );
};
} else {
this.executable = function () {
return oldExecutable.call( this ) && val;
};
}
return this;
};
LAY.Take.prototype.not = function () {
var oldExecutable = this.executable;
this.executable = function () {
return !oldExecutable.call( this );
};
return this;
};
LAY.Take.prototype.negative = function () {
var oldExecutable = this.executable;
this.executable = function () {
return -oldExecutable.call( this );
};
return this;
};
LAY.Take.prototype.number = function () {
var oldExecutable = this.executable;
this.executable = function () {
return parseInt( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.key = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this )[ val.execute( this ) ];
};
} else {
this.executable = function () {
return oldExecutable.call( this )[ val ];
};
}
return this;
};
LAY.Take.prototype.index = LAY.Take.prototype.key;
LAY.Take.prototype.length = function ( val ) {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ).length;
};
return this;
};
LAY.Take.prototype.slice = function ( start, end ) {
var oldExecutable = this.executable;
if ( start instanceof LAY.Take ) {
this.$mergePathAndAttrs( start );
if ( end instanceof LAY.Take ) {
this.$mergePathAndAttrs( end );
this.executable = function () {
return oldExecutable.call( this ).slice(
start.execute( this ), end.execute( this ) );
}
} else {
this.executable = function () {
return oldExecutable.call( this ).slice(
start.execute( this ), end );
}
}
} else if ( end instanceof LAY.Take ) {
this.$mergePathAndAttrs( end );
this.executable = function () {
return oldExecutable.call( this ).slice(
start, end.execute( this ) );
}
} else {
this.executable = function () {
return oldExecutable.call( this ).slice(
start, end );
}
}
return this;
};
LAY.Take.prototype.min = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return Math.min( oldExecutable.call( this ), val.execute( this ) );
};
} else {
this.executable = function () {
return Math.min( oldExecutable.call( this ), val );
};
}
return this;
};
LAY.Take.prototype.max = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return Math.max( oldExecutable.call( this ), val.execute( this ) );
};
} else {
this.executable = function () {
return Math.max( oldExecutable.call( this ), val );
};
}
return this;
};
LAY.Take.prototype.ceil = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.ceil( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.floor = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.floor( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.round = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.round( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.sin = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.sin( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.cos = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.cos( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.tan = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.tan( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.abs = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.abs( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.pow = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return Math.pow( oldExecutable.call( this ), val.execute( this ) );
};
} else {
this.executable = function () {
return Math.pow( oldExecutable.call( this ), val );
};
}
return this;
};
LAY.Take.prototype.log = function () {
var oldExecutable = this.executable;
this.executable = function () {
return Math.log( oldExecutable.call( this ) );
};
return this;
};
LAY.Take.prototype.match = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).match( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).match( val );
};
}
return this;
};
LAY.Take.prototype.test = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).test( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).test( val );
};
}
return this;
};
LAY.Take.prototype.concat = LAY.Take.prototype.add;
LAY.Take.prototype.lowercase = function () {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ).toLowerCase();
};
return this;
};
LAY.Take.prototype.uppercase = function () {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ).toUpperCase();
};
return this;
};
LAY.Take.prototype.capitalize = function () {
var oldExecutable = this.executable;
this.executable = function () {
var val = oldExecutable.call( this );
return val.charAt( 0 ).toUpperCase() +
val.slice( 1 );
};
return this;
};
LAY.Take.prototype.format = function () {
var argS = Array.prototype.slice.call( arguments ),
takeFormat = new LAY.Take( LAY.$format );
argS.unshift( this );
return takeFormat.fn.apply( takeFormat, argS );
};
LAY.Take.prototype.i18nFormat = function () {
function fnWrapperI18nFormat () {
var argS = Array.prototype.slice.call( arguments );
argS[ 0 ] = ( argS[ 0 ] )[ LAY.level( '/' ).attr( 'data.lang' ) ];
if ( argS[ 0 ] === undefined ) {
throw "LAY Error: No language defined for i18nFormat";
}
return LAY.$format.apply( undefined, argS );
}
this._relPath00attr_S.push( [ new LAY.RelPath( '/' ), 'data.lang' ] );
var argS = Array.prototype.slice.call(arguments),
takeFormat = new LAY.Take( fnWrapperI18nFormat );
argS.unshift( this );
return takeFormat.fn.apply( takeFormat, argS);
};
LAY.Take.prototype.colorEquals = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).equals( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).equals( val );
};
}
return this;
};
LAY.Take.prototype.colorLighten = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().lighten( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().lighten( val );
};
}
return this;
};
LAY.Take.prototype.colorDarken = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().darken( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().darken( val );
};
}
return this;
};
LAY.Take.prototype.colorStringify = function ( ) {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ).copy().stringify( );
};
return this;
};
LAY.Take.prototype.colorInvert = function ( ) {
var oldExecutable = this.executable;
this.executable = function () {
return oldExecutable.call( this ).copy().invert();
};
return this;
};
LAY.Take.prototype.colorSaturate = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().saturate( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().saturate( val );
};
}
return this;
};
LAY.Take.prototype.colorDesaturate = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().desaturate( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().desaturate( val );
};
}
return this;
};
LAY.Take.prototype.colorAlpha = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().alpha( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().alpha( val );
};
}
return this;
};
LAY.Take.prototype.colorRed = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().red( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().red( val );
};
}
return this;
};
LAY.Take.prototype.colorGreen = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().green( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().green( val );
};
}
return this;
};
LAY.Take.prototype.colorBlue = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().blue( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().blue( val );
};
}
return this;
};
LAY.Take.prototype.colorHue = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().hue( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().hue( val );
};
}
return this;
};
LAY.Take.prototype.colorSaturation = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().saturation( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().saturation( val );
};
}
return this;
};
LAY.Take.prototype.colorLightness = function ( val ) {
var oldExecutable = this.executable;
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return oldExecutable.call( this ).copy().lightness( val.execute( this ) );
};
} else {
this.executable = function () {
return oldExecutable.call( this ).copy().lightness( val );
};
}
return this;
};
LAY.Take.prototype.filterEq = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.eq(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.eq(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.eq(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.eq(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterNeq = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.neq(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.neq(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.neq(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.neq(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterGt = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.gt(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.gt(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.gt(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.gt(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterGte = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.gte(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.gte(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.gte(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.gte(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterLt = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.lt(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.lt(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.lt(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.lt(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterLte = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.lte(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.lte(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.lte(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.lte(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterRegex = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.regex(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.regex(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.regex(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.regex(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterContains = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.contains(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.contains(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.contains(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.contains(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterWithin = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.within(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.within(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.within(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.within(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.filterFn = function ( attr, val ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.fn(
oldExecutable.call( this ),
attr.execute( this ),
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.fn(
oldExecutable.call( this ),
attr.execute( this ),
val
);
}
}
} else if ( val instanceof LAY.Take ) {
this.$mergePathAndAttrs( val );
this.executable = function () {
return LAY.$filterUtils.fn(
oldExecutable.call( this ),
attr,
val.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$filterUtils.fn(
oldExecutable.call( this ),
attr,
val
);
}
}
return this;
};
LAY.Take.prototype.foldMin = function ( attr ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
this.executable = function () {
return LAY.$foldUtils.min(
oldExecutable.call( this ),
attr.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$foldUtils.min(
oldExecutable.call( this ),
attr
);
}
}
return this;
};
LAY.Take.prototype.foldMax = function ( attr ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
this.executable = function () {
return LAY.$foldUtils.max(
oldExecutable.call( this ),
attr.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$foldUtils.max(
oldExecutable.call( this ),
attr
);
}
}
return this;
};
LAY.Take.prototype.foldSum = function ( attr ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
this.executable = function () {
return LAY.$foldUtils.sum(
oldExecutable.call( this ),
attr.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$foldUtils.sum(
oldExecutable.call( this ),
attr
);
}
}
return this;
};
LAY.Take.prototype.foldFn = function ( attr, acc ) {
var oldExecutable = this.executable;
if ( attr instanceof LAY.Take ) {
this.$mergePathAndAttrs( attr );
if ( acc instanceof LAY.Take ) {
this.$mergePathAndAttrs( acc );
this.executable = function () {
return LAY.$foldUtils.fn(
oldExecutable.call( this ),
attr.execute( this ),
acc.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$foldUtils.fn(
oldExecutable.call( this ),
attr.execute( this ),
acc
);
}
}
} else if ( acc instanceof LAY.Take ) {
this.$mergePathAndAttrs( acc );
this.executable = function () {
return LAY.$foldUtils.fn(
oldExecutable.call( this ),
attr,
acc.execute( this )
);
}
} else {
this.executable = function () {
return LAY.$foldUtils.fn(
oldExecutable.call( this ),
attr,
ac
);
}
}
return this;
};
/*
* Call custom function with arguments, where arguments
* can be LAY.Take objects.
*/
LAY.Take.prototype.fn = function () {
var fnExecutable = this.executable;
//console.log(fnExecutable.call(this));
//console.log(fnExecutable, arguments, arguments.length);
if ( arguments.length === 0 ) {
this.executable = function () {
return fnExecutable.call( this ).call( this );
};
} else if ( arguments.length === 1 ) {
var arg = arguments[ 0 ];
if ( arg instanceof LAY.Take ) {
this.$mergePathAndAttrs( arg );
this.executable = function () {
return fnExecutable.call( this ).call( this, arg.execute( this ) );
};
} else {
this.executable = function () {
return fnExecutable.call( this ).call( this, arg );
};
}
} else if ( arguments.length === 2 ) {
var arg1 = arguments[ 0 ];
var arg2 = arguments[ 1 ];
if ( arg1 instanceof LAY.Take ) {
this.$mergePathAndAttrs( arg1 );
if ( arg2 instanceof LAY.Take ) {
this.$mergePathAndAttrs( arg2 );
this.executable = function () {
return fnExecutable.call( this ).call( this, arg1.execute( this ), arg2.execute( this ) );
};
} else {
this.executable = function () {
return fnExecutable.call( this ).call( this, arg1.execute( this ), arg2 );
};
}
} else if ( arg2 instanceof LAY.Take ) {
this.$mergePathAndAttrs( arg2 );
this.executable = function () {
return fnExecutable.call( this ).call( this, arg1, arg2.execute( this ) );
};
} else {
this.executable = function () {
return fnExecutable.call( this ).call( this, arg1, arg2 );
};
}
} else {
var argSlength = arguments.length;
var argS = Array.prototype.slice.call( arguments );
for ( var i = 0, curArg; i < argSlength; i++ ) {
curArg = arguments[ i ];
if ( curArg instanceof LAY.Take ) {
this.$mergePathAndAttrs( curArg );
}
}
this.executable = function () {
var executedArgS = new Array( argSlength );
for ( var i = 0, arg; i < argSlength; i++ ) {
arg = argS[ i ];
executedArgS[ i ] = arg instanceof LAY.Take ? arg.execute( this ) : arg;
}
return fnExecutable.call( this ).apply( this, executedArgS );
};
}
return this;
};
}());
( function () {
"use strict";
var transitionType2fn,
epsilon = 1e-6;
LAY.Transition = function ( type, delay, duration, args, done ) {
this.done = done;
this.delay = delay;
this.transition = ( transitionType2fn[ type ] )( duration, args );
};
LAY.Transition.prototype.generateNext = function ( delta ) {
return this.transition.generateNext( delta );
};
LAY.Transition.prototype.checkIsComplete = function () {
return this.transition.checkIsComplete();
};
function LinearTransition ( duration, args ) {
this.curTime = 0;
this.duration = duration;
}
LinearTransition.prototype.generateNext = function ( delta ) {
return ( ( this.curTime += delta ) / this.duration );
};
LinearTransition.prototype.checkIsComplete = function () {
return this.curTime >= this.duration;
};
function CubicBezierTransition ( duration, args ) {
this.curTime = 0;
this.duration = duration;
this.cx = 3.0 * args.a;
this.bx = 3.0 * (args.c - args.a) - this.cx
this.ax = 1.0 - this.cx - this.bx
this.cy = 3.0 * args.b;
this.by = 3.0 * (args.d - args.b) - this.cy
this.ay = 1.0 - this.cy - this.by
}
// source of cubic bezier code below:
// facebook pop framework & framer.js
CubicBezierTransition.prototype.generateNext = function ( delta ) {
return this.sampleCurveY( this.solveCurveX(
(this.curTime += delta) / this.duration
) );
}
CubicBezierTransition.prototype.checkIsComplete = function () {
return this.curTime >= this.duration;
};
CubicBezierTransition.prototype.sampleCurveX = function ( t ) {
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
return ((this.ax * t + this.bx) * t + this.cx) * t;
};
CubicBezierTransition.prototype.sampleCurveY = function ( t ) {
return ((this.ay * t + this.by) * t + this.cy) * t;
};
CubicBezierTransition.prototype.sampleCurveDerivativeX = function( t ) {
return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;
};
CubicBezierTransition.prototype.solveCurveX = function( x ) {
var t0, t1, t2, x2, d2, i;
// First try a few iterations of Newton's method -- normally very fast.
for ( t2 = x, i = 0; i < 8; i++ ) {
x2 = this.sampleCurveX( t2 ) - x;
if ( Math.abs( x2 ) < epsilon )
return t2;
d2 = this.sampleCurveDerivativeX( t2 );
if ( Math.abs( d2 ) < 1e-6 )
break;
t2 = t2 - x2 / d2;
}
// Fall back to the bisection method for reliability.
t0 = 0.0;
t1 = 1.0;
t2 = x;
if ( t2 < t0 )
return t0;
if ( t2 > t1 )
return t1;
while ( t0 < t1 ) {
x2 = this.sampleCurveX( t2 );
if ( Math.abs( x2 - x ) < epsilon )
return t2;
if ( x > x2 )
t0 = t2;
else
t1 = t2;
t2 = ( t1 - t0 ) * .5 + t0;
}
// Failure.
return t2;
};
transitionType2fn = {
linear: function ( duration, args ) {
return new LinearTransition( duration, args );
},
"spring": function ( duration, args ) {
return new LAY.$springTransition( duration, args );
},
"cubic-bezier": function ( duration, args ) {
return new CubicBezierTransition( duration, args );
},
ease: function ( duration, args ) {
return new CubicBezierTransition( duration, {
a: 0.25, b: 0.1, c: 0.25, d: 1
});
},
"ease-in": function ( duration, args ) {
return new CubicBezierTransition( duration, {
a: 0.42, b: 0, c: 1, d: 1
});
},
"ease-out": function ( duration, args ) {
return new CubicBezierTransition( duration, {
a: 0, b: 0, c: 0.58, d: 1
});
},
"ease-in-out": function ( duration, args ) {
return new CubicBezierTransition( duration, {
a: 0.42, b: 0, c: 0.58, d: 1
});
}
/*
ease: function ( startCalcVal, duration, delay, done, args ) {
return new CubicBezierTransition( startCalcVal, duration, delay, done, {
a: 0.25, b: 0.1, c: 0.25, d: 1
});
},
"ease-in": function ( startCalcVal, duration, delay, done, args ) {
return new CubicBezierTransition( startCalcVal, duration, delay, done, {
a: 0.42, b: 0, c: 1, d: 1
});
},
"ease-out": function ( startCalcVal, duration, delay, done, args ) {
return new CubicBezierTransition( startCalcVal, duration, delay, done, {
a: 0, b: 0, c: 0.58, d: 1
});
},
"ease-in-out": function ( startCalcVal, duration, delay, done, args ) {
return new CubicBezierTransition( startCalcVal, duration, delay, done, {
a: 0.42, b: 0, c: 0.58, d: 1
});
}*/
};
})();
( function () {
"use strict";
LAY.clog = function () {
LAY.$numClog++;
};
})();
( function() {
"use strict";
function takeColor ( color ) {
return LAY.color( color );
}
var numRegex = /(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,?\s*((\d+\.\d+)|(\d+))?/;
LAY.color = function ( colorName ) {
if ( colorName instanceof LAY.Take ) {
return new LAY.Take( takeColor ).fn( colorName );
} else {
colorName = colorName.toLowerCase();
var colorValue = colorName2colorValue[ colorName ];
if ( colorValue !== undefined ) {
return new LAY.Color( 'rgb', colorValue, 1 );
} else {
if ( colorName.match(/(rgb)|(hsl)/) ) {
var match = colorName.match( numRegex );
if ( match ) {
var
arg1 = parseInt(match[1]),
arg2 = parseInt(match[2]),
arg3 = parseInt(match[3]),
argAlpha = match[4] === undefined ?
1 : parseFloat(match[4]);
if ( colorName.indexOf("rgb") !== -1 ) {
return LAY.rgba( arg1,arg2,arg3, argAlpha );
} else {
return LAY.hsla( arg1,arg2,arg3, argAlpha );
}
}
}
}
}
throw ("LAY Error: Color name: " + colorName + " not found." );
};
// source page: http://www.w3.org/TR/css3-color/
// source code: for ( var i=2, len=tbody.childNodes.length; i < len; i++) { var m = tbody.childNodes[i].childNodes[5].innerText.match(/(\d+),(\d+),(\d+)/); d[tbody.childNodes[i].childNodes[3].childNodes[0].innerText] = {r:m[1], g:m[2], b:m[3]}}
var colorName2colorValue = {
aliceblue : { r: 240 , g: 248 , b: 255 },
antiquewhite : { r: 250 , g: 235 , b: 215 },
aqua : { r: 0 , g: 255 , b: 255 },
aquamarine : { r: 127 , g: 255 , b: 212 },
azure : { r: 240 , g: 255 , b: 255 },
beige : { r: 245 , g: 245 , b: 220 },
bisque : { r: 255 , g: 228 , b: 196 },
black : { r: 0 , g: 0 , b: 0 },
blanchedalmond : { r: 255 , g: 235 , b: 205 },
blue : { r: 0 , g: 0 , b: 255 },
blueviolet : { r: 138 , g: 43 , b: 226 },
brown : { r: 165 , g: 42 , b: 42 },
burlywood : { r: 222 , g: 184 , b: 135 },
cadetblue : { r: 95 , g: 158 , b: 160 },
chartreuse : { r: 127 , g: 255 , b: 0 },
chocolate : { r: 210 , g: 105 , b: 30 },
coral : { r: 255 , g: 127 , b: 80 },
cornflowerblue : { r: 100 , g: 149 , b: 237 },
cornsilk : { r: 255 , g: 248 , b: 220 },
crimson : { r: 220 , g: 20 , b: 60 },
cyan : { r: 0 , g: 255 , b: 255 },
darkblue : { r: 0 , g: 0 , b: 139 },
darkcyan : { r: 0 , g: 139 , b: 139 },
darkgoldenrod : { r: 184 , g: 134 , b: 11 },
darkgray : { r: 169 , g: 169 , b: 169 },
darkgreen : { r: 0 , g: 100 , b: 0 },
darkgrey : { r: 169 , g: 169 , b: 169 },
darkkhaki : { r: 189 , g: 183 , b: 107 },
darkmagenta : { r: 139 , g: 0 , b: 139 },
darkolivegreen : { r: 85 , g: 107 , b: 47 },
darkorange : { r: 255 , g: 140 , b: 0 },
darkorchid : { r: 153 , g: 50 , b: 204 },
darkred : { r: 139 , g: 0 , b: 0 },
darksalmon : { r: 233 , g: 150 , b: 122 },
darkseagreen : { r: 143 , g: 188 , b: 143 },
darkslateblue : { r: 72 , g: 61 , b: 139 },
darkslategray : { r: 47 , g: 79 , b: 79 },
darkslategrey : { r: 47 , g: 79 , b: 79 },
darkturquoise : { r: 0 , g: 206 , b: 209 },
darkviolet : { r: 148 , g: 0 , b: 211 },
deeppink : { r: 255 , g: 20 , b: 147 },
deepskyblue : { r: 0 , g: 191 , b: 255 },
dimgray : { r: 105 , g: 105 , b: 105 },
dimgrey : { r: 105 , g: 105 , b: 105 },
dodgerblue : { r: 30 , g: 144 , b: 255 },
firebrick : { r: 178 , g: 34 , b: 34 },
floralwhite : { r: 255 , g: 250 , b: 240 },
forestgreen : { r: 34 , g: 139 , b: 34 },
fuchsia : { r: 255 , g: 0 , b: 255 },
gainsboro : { r: 220 , g: 220 , b: 220 },
ghostwhite : { r: 248 , g: 248 , b: 255 },
gold : { r: 255 , g: 215 , b: 0 },
goldenrod : { r: 218 , g: 165 , b: 32 },
gray : { r: 128 , g: 128 , b: 128 },
green : { r: 0 , g: 128 , b: 0 },
greenyellow : { r: 173 , g: 255 , b: 47 },
grey : { r: 128 , g: 128 , b: 128 },
honeydew : { r: 240 , g: 255 , b: 240 },
hotpink : { r: 255 , g: 105 , b: 180 },
indianred : { r: 205 , g: 92 , b: 92 },
indigo : { r: 75 , g: 0 , b: 130 },
ivory : { r: 255 , g: 255 , b: 240 },
khaki : { r: 240 , g: 230 , b: 140 },
lavender : { r: 230 , g: 230 , b: 250 },
lavenderblush : { r: 255 , g: 240 , b: 245 },
lawngreen : { r: 124 , g: 252 , b: 0 },
lemonchiffon : { r: 255 , g: 250 , b: 205 },
lightblue : { r: 173 , g: 216 , b: 230 },
lightcoral : { r: 240 , g: 128 , b: 128 },
lightcyan : { r: 224 , g: 255 , b: 255 },
lightgoldenrodyellow : { r: 250 , g: 250 , b: 210 },
lightgray : { r: 211 , g: 211 , b: 211 },
lightgreen : { r: 144 , g: 238 , b: 144 },
lightgrey : { r: 211 , g: 211 , b: 211 },
lightpink : { r: 255 , g: 182 , b: 193 },
lightsalmon : { r: 255 , g: 160 , b: 122 },
lightseagreen : { r: 32 , g: 178 , b: 170 },
lightskyblue : { r: 135 , g: 206 , b: 250 },
lightslategray : { r: 119 , g: 136 , b: 153 },
lightslategrey : { r: 119 , g: 136 , b: 153 },
lightsteelblue : { r: 176 , g: 196 , b: 222 },
lightyellow : { r: 255 , g: 255 , b: 224 },
lime : { r: 0 , g: 255 , b: 0 },
limegreen : { r: 50 , g: 205 , b: 50 },
linen : { r: 250 , g: 240 , b: 230 },
magenta : { r: 255 , g: 0 , b: 255 },
maroon : { r: 128 , g: 0 , b: 0 },
mediumaquamarine : { r: 102 , g: 205 , b: 170 },
mediumblue : { r: 0 , g: 0 , b: 205 },
mediumorchid : { r: 186 , g: 85 , b: 211 },
mediumpurple : { r: 147 , g: 112 , b: 219 },
mediumseagreen : { r: 60 , g: 179 , b: 113 },
mediumslateblue : { r: 123 , g: 104 , b: 238 },
mediumspringgreen : { r: 0 , g: 250 , b: 154 },
mediumturquoise : { r: 72 , g: 209 , b: 204 },
mediumvioletred : { r: 199 , g: 21 , b: 133 },
midnightblue : { r: 25 , g: 25 , b: 112 },
mintcream : { r: 245 , g: 255 , b: 250 },
mistyrose : { r: 255 , g: 228 , b: 225 },
moccasin : { r: 255 , g: 228 , b: 181 },
navajowhite : { r: 255 , g: 222 , b: 173 },
navy : { r: 0 , g: 0 , b: 128 },
oldlace : { r: 253 , g: 245 , b: 230 },
olive : { r: 128 , g: 128 , b: 0 },
olivedrab : { r: 107 , g: 142 , b: 35 },
orange : { r: 255 , g: 165 , b: 0 },
orangered : { r: 255 , g: 69 , b: 0 },
orchid : { r: 218 , g: 112 , b: 214 },
palegoldenrod : { r: 238 , g: 232 , b: 170 },
palegreen : { r: 152 , g: 251 , b: 152 },
paleturquoise : { r: 175 , g: 238 , b: 238 },
palevioletred : { r: 219 , g: 112 , b: 147 },
papayawhip : { r: 255 , g: 239 , b: 213 },
peachpuff : { r: 255 , g: 218 , b: 185 },
peru : { r: 205 , g: 133 , b: 63 },
pink : { r: 255 , g: 192 , b: 203 },
plum : { r: 221 , g: 160 , b: 221 },
powderblue : { r: 176 , g: 224 , b: 230 },
purple : { r: 128 , g: 0 , b: 128 },
red : { r: 255 , g: 0 , b: 0 },
rosybrown : { r: 188 , g: 143 , b: 143 },
royalblue : { r: 65 , g: 105 , b: 225 },
saddlebrown : { r: 139 , g: 69 , b: 19 },
salmon : { r: 250 , g: 128 , b: 114 },
sandybrown : { r: 244 , g: 164 , b: 96 },
seagreen : { r: 46 , g: 139 , b: 87 },
seashell : { r: 255 , g: 245 , b: 238 },
sienna : { r: 160 , g: 82 , b: 45 },
silver : { r: 192 , g: 192 , b: 192 },
skyblue : { r: 135 , g: 206 , b: 235 },
slateblue : { r: 106 , g: 90 , b: 205 },
slategray : { r: 112 , g: 128 , b: 144 },
slategrey : { r: 112 , g: 128 , b: 144 },
snow : { r: 255 , g: 250 , b: 250 },
springgreen : { r: 0 , g: 255 , b: 127 },
steelblue : { r: 70 , g: 130 , b: 180 },
tan : { r: 210 , g: 180 , b: 140 },
teal : { r: 0 , g: 128 , b: 128 },
thistle : { r: 216 , g: 191 , b: 216 },
tomato : { r: 255 , g: 99 , b: 71 },
turquoise : { r: 64 , g: 224 , b: 208 },
violet : { r: 238 , g: 130 , b: 238 },
wheat : { r: 245 , g: 222 , b: 179 },
white : { r: 255 , g: 255 , b: 255 },
whitesmoke : { r: 245 , g: 245 , b: 245 },
yellow : { r: 255 , g: 255 , b: 0 },
yellowgreen : { r: 154 , g: 205 , b: 50 }
};
})();
( function () {
"use strict";
LAY.formation = function ( name, fargs, fn ) {
LAY.$formation2fargs[ name ] = fargs;
LAY.$formation2fn[ name ] = fn;
};
})();
( function() {
"use strict";
function takeHex ( hex ) {
return LAY.hex( hex );
}
LAY.hex = function ( hexVal ) {
if ( hexVal instanceof LAY.Take ) {
return new LAY.Take( takeHex ).fn( hexVal );
} else {
return new LAY.Color( 'rgb', hexToRgb(hexVal), 1 );
}
};
// source: http://stackoverflow.com/users/1047797/david
// http://stackoverflow.com/a/11508164
function hexToRgb(hex) {
return {
r: (hex >> 16) & 255,
g: (hex >> 8) & 255,
b: hex & 255
};
}
})();
(function() {
"use strict";
LAY.hsl = function ( h, s, l ) {
return LAY.hsla( h, s, l, 1 );
};
})();
(function() {
"use strict";
function takeHSLA ( h, s, l, a ) {
var color = new LAY.Color( "hsl", { h: h, s: s, l: l }, a );
}
LAY.hsla = function ( h, s, l, a ) {
if ( h instanceof LAY.Take ||
s instanceof LAY.Take ||
l instanceof LAY.Take ||
a instanceof LAY.Take ) {
return new LAY.Take( takeHSLA ).fn( h, s, l, a );
} else {
return new LAY.Color( "hsl", { h: h, s: s, l: l }, a );
}
};
})();
( function () {
"use strict";
/*!
* source: chai.js (https://github.com/chaijs/deep-eql)
* deep-eql
* Copyright(c) 2013 <NAME> <<EMAIL>>
* MIT Licensed
*/
LAY.identical = function ( a, b ) {
return deepEqual( a, b, undefined );
};
function type (x) {
return LAY.$type(x);
}
function deepEqual(a,b,m) {
var
typeA = type( a ),
typeB = type( b );
if ( sameValue( a, b ) ) {
return true;
} else if ( 'color' === typeA ) {
return colorEqual(a, b);
} else if ( 'level' === typeA ) {
return levelEqual(a, b);
} else if ( 'take' === typeA || 'take' === typeB ) {
return false;
} else if ('date' === typeA ) {
return dateEqual(a, b);
} else if ('regexp' === typeA) {
return regexpEqual(a, b);
} else if ('arguments' === typeA) {
return argumentsEqual(a, b, m);
} else if (('object' !== typeA && 'object' !== typeB)
&& ('array' !== typeA && 'array' !== typeB)) {
return sameValue(a, b);
} else {
return objectEqual(a, b, m);
}
}
/*
* Strict (egal) equality test. Ensures that NaN always
* equals NaN and `-0` does not equal `+0`.
*
* @param {Mixed} a
* @param {Mixed} b
* @return {Boolean} equal match
*/
function sameValue(a, b) {
if (a === b) return a !== 0 || 1 / a === 1 / b;
return a !== a && b !== b;
}
/*
* Compare two Date objects by asserting that
* the time values are equal using `saveValue`.
*
* @param {Date} a
* @param {Date} b
* @return {Boolean} result
*/
function dateEqual(a, b) {
if ('date' !== type(b)) return false;
return sameValue(a.getTime(), b.getTime());
}
function colorEqual (a, b) {
return type(b) === "color" && a.equals(b);
}
function levelEqual (a, b) {
return type(b) === "level" && ( a.pathName === b.pathName );
}
/*
* Compare two regular expressions by converting them
* to string and checking for `sameValue`.
*
* @param {RegExp} a
* @param {RegExp} b
* @return {Boolean} result
*/
function regexpEqual(a, b) {
if ('regexp' !== type(b)) return false;
return sameValue(a.toString(), b.toString());
}
/*
* Assert deep equality of two `arguments` objects.
* Unfortunately, these must be sliced to arrays
* prior to test to ensure no bad behavior.
*
* @param {Arguments} a
* @param {Arguments} b
* @param {Array} memoize (optional)
* @return {Boolean} result
*/
function argumentsEqual(a, b, m) {
if ('arguments' !== type(b)) return false;
a = [].slice.call(a);
b = [].slice.call(b);
return deepEqual(a, b, m);
}
/*
* Get enumerable properties of a given object.
*
* @param {Object} a
* @return {Array} property names
*/
function enumerable(a) {
var res = [];
for (var key in a) res.push(key);
return res;
}
/*
* Simple equality for flat iterable objects
* such as Arrays or Node.js buffers.
*
* @param {Iterable} a
* @param {Iterable} b
* @return {Boolean} result
*/
function iterableEqual(a, b) {
if (a.length !== b.length) return false;
var i = 0;
var match = true;
for (; i < a.length; i++) {
if (a[i] !== b[i]) {
match = false;
break;
}
}
return match;
}
/*
* Extension to `iterableEqual` specifically
* for Node.js Buffers.
*
* @param {Buffer} a
* @param {Mixed} b
* @return {Boolean} result
*/
function bufferEqual(a, b) {
if (!Buffer.isBuffer(b)) return false;
return iterableEqual(a, b);
}
/*
* Block for `objectEqual` ensuring non-existing
* values don't get in.
*
* @param {Mixed} object
* @return {Boolean} result
*/
function isValue(a) {
return a !== null && a !== undefined;
}
/*
* Recursively check the equality of two objects.
* Once basic sameness has been established it will
* defer to `deepEqual` for each enumerable key
* in the object.
*
* @param {Mixed} a
* @param {Mixed} b
* @return {Boolean} result
*/
function objectEqual(a, b, m) {
if (!isValue(a) || !isValue(b)) {
return false;
}
if (a.prototype !== b.prototype) {
return false;
}
var i;
if (m) {
for (i = 0; i < m.length; i++) {
if ((m[i][0] === a && m[i][1] === b)
|| (m[i][0] === b && m[i][1] === a)) {
return true;
}
}
} else {
m = [];
}
try {
var ka = enumerable(a);
var kb = enumerable(b);
} catch (ex) {
return false;
}
ka.sort();
kb.sort();
if (!iterableEqual(ka, kb)) {
return false;
}
m.push([ a, b ]);
var key;
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!deepEqual(a[key], b[key], m)) {
return false;
}
}
return true;
}
})();
(function() {
"use strict";
LAY.level = function ( path ) {
return LAY.$pathName2level[ path ];
};
})();
(function() {
"use strict";
LAY.rgb = function ( r, g, b ) {
return LAY.rgba( r, g, b, 1 );
};
})();
(function() {
"use strict";
function takeRGBA ( r, g, b, a ) {
return new LAY.Color( "rgb", { r: r, g: g, b: b }, a );
}
LAY.rgba = function ( r, g, b, a ) {
if ( r instanceof LAY.Take ||
g instanceof LAY.Take ||
b instanceof LAY.Take ||
a instanceof LAY.Take ) {
return new LAY.Take( takeRGBA ).fn( r, g, b, a );
} else {
return new LAY.Color( "rgb", { r: r, g: g, b: b }, a );
}
};
})();
(function() {
"use strict";
LAY.run = function ( rootLson ) {
setRuntimeGlobals();
( new LAY.Level( "/", rootLson, undefined ) ).$init();
LAY.$solve();
window.onresize = updateSize;
};
function setRuntimeGlobals () {
var
takeMidpointX = LAY.take("", "width").half(),
takeMidpointY = LAY.take("", "height").half();
LAY.$miscPosAttr2take = {
centerX: LAY.take("","left").add( takeMidpointX ),
centerY: LAY.take("","top").add( takeMidpointY ),
$midpointX: takeMidpointX,
$midpointY: takeMidpointY,
$absoluteLeft: LAY.take("../", "$absoluteLeft").add(
LAY.take("", "left") ),
$absoluteTop: LAY.take("../", "$absoluteTop").add(
LAY.take("", "top") )
};
LAY.$essentialPosAttr2take = {
right: LAY.take("","left").add( LAY.take("", "width") ),
bottom: LAY.take("","top").add( LAY.take("", "height") )
};
LAY.$emptyAttrVal = new LAY.AttrVal( "", undefined );
LAY.$formationDisplayNoneState = {
onlyif: LAY.take("","$f").eq(-1),
props: {
display:false
}
};
}
function updateSize () {
var rootLevel = LAY.$pathName2level[ "/" ];
rootLevel.$changeAttrVal( "$windowWidth", window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth );
rootLevel.$changeAttrVal( "$windowHeight", window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight );
}
})();
(function() {
"use strict";
LAY.take = function ( relativePath, prop ) {
if ( ( prop !== undefined ) &&
( LAY.$checkIsValidUtils.checkIsAttrExpandable( prop ) ) ) {
throw ( "LAY Error: takes using expander props such as '" + relativePath + "' are not permitted." );
} else {
return new LAY.Take( relativePath, prop );
}
};
})();
( function() {
"use strict";
LAY.transparent = function ( ) {
return new LAY.Color( 'rgb', { r: 0, g: 0, b: 0 }, 0 );
};
})();
(function() {
"use strict";
LAY.unclog = function () {
if ( --LAY.$numClog === 0 ) {
LAY.$solve();
}
};
})();
( function () {
"use strict";
LAY.$arrayUtils = {
/*
* Add to array if element does not exist already
* Return true the element was added (as it did not exist previously)
*/
pushUnique: function ( elementS, element ) {
if ( elementS.indexOf( element ) === -1 ) {
elementS.push( element );
return true;
}
return false;
},
/* Prepend element, if preset already then remove and prepend */
prependUnique: function ( elementS, element ) {
LAY.$arrayUtils.remove( elementS, element );
elementS.unshift( element );
},
/*
* Remove from array if element exists in it
* Return true the element was remove (as it did exist previously)
*/
remove: function ( elementS, element ) {
var ind = elementS.indexOf( element );
if ( ind !== -1 ) {
elementS.splice( ind, 1 );
return true;
}
return false;
},
/*
* Remove element at index i
*/
removeAtIndex: function ( elementS, ind ) {
elementS.splice( ind, 1 );
},
/* Clone array at a single level */
cloneSingleLevel: function ( elementS ) {
return elementS.slice( 0 );
},
/*Swap element at index a with index b */
swap: function ( elementS, a, b ) {
var tmp = elementS[ a ];
elementS[ a ] = elementS[ b ];
elementS[ b ] = tmp;
}
};
})();
(function(){
"use strict";
LAY.$capitalize = function( string ) {
return string.charAt( 0 ).toUpperCase() + string.slice( 1 );
};
})();
(function () {
"use strict";
var doingReadonlyS = [
"$hovering", "$clicking"
];
LAY.$checkIfDoingReadonly = function ( attr ) {
return doingReadonlyS.indexOf( attr ) !== -1;
};
})();
( function () {
"use strict";
var immidiateReadonlyS = [
"$naturalWidth", "$naturalHeight",
"$scrolledX", "$scrolledY",
"$focused",
"$input"
];
LAY.$checkIfImmidiateReadonly = function ( attr ) {
return immidiateReadonlyS.indexOf( attr ) !== -1;
};
})();
(function(){
"use strict";
var reservedNameS = [
"root", "transition", "data", "when", "onlyif",
"states", "exist",
"",
"many", "formation", "formationDisplayNone",
"sort", "fargs",
"rows", "row", "filter", "args", "all"
];
function stripStateAttrPrefix( attr ) {
var nonStateAttrPrefixS = [ "data", "when", "transition" ];
var i = attr.indexOf(".");
if ( i === -1 ) {
return attr;
} else {
var prefix = attr.slice( 0, i );
if ( nonStateAttrPrefixS.indexOf( prefix ) !== -1 ) {
return attr;
} else {
return attr.slice( i + 1 );
}
}
}
/*
* Must not contain ".", "/" or ":"
*/
function checkIfNoIllegalCharacters ( name ) {
return ( name.indexOf(".") === -1 ) &&
( name.indexOf("/") === -1 ) &&
( name.indexOf(":") === -1) &&
( name.indexOf("*") === -1 );
}
LAY.$checkIsValidUtils = {
levelName: function ( levelName ) {
return checkIfNoIllegalCharacters( levelName ) &&
( reservedNameS.indexOf( levelName ) === -1 );
},
/*
* Rules of a state name:
* (1) Must not contain any illegal characters
l * (2) Must not be a reserved name with the exception of "root"
* as "root" state name has already been checked at the
* start of normalizing
*/
stateName: function ( stateName ) {
return checkIfNoIllegalCharacters( stateName ) &&
( ( reservedNameS.indexOf( stateName ) === -1 ) ||
( stateName === "root" ) );
},
checkIsAttrExpandable: function ( attr ) {
return this.checkIsNonPropAttrExpandable( attr ) ||
this.checkIsPropAttrExpandable( attr );
},
checkIsNonPropAttrExpandable: function ( attr ) {
var expanderAttrS = [
"data", "when", "transition", "states", "fargs", "sort"
];
var regexExpanderAttrs = /(^sort\.\d+$)|(^fargs\.[a-zA-Z]+$)|(^transition\.[a-zA-Z]+$)|(^transition\.[a-zA-Z]+\.args$)|(^when\.[a-zA-Z]+$)/;
var strippedStateAttr = stripStateAttrPrefix( attr );
return ( ( expanderAttrS.indexOf( strippedStateAttr ) !== -1 ) ||
( regexExpanderAttrs.test( strippedStateAttr ) )
);
},
checkIsPropAttrExpandable: function ( attr ) {
var expanderPropS = [
"border", "background", "boxShadows", "textShadows",
"videoSources", "audioSources", "videoTracks", "audioTracks",
"filters","borderTop", "borderRight", "borderBottom", "borderLeft",
];
var regexExpanderProps = /(^boxShadows\d+$)|(^textShadows\d+$)|(^videoSources\d+$)|(^audioSources\d+$)|(^videoTracks\d+$)|(^audioTracks\d+$)|(^filters\d+$)|(^filters\d+DropShadow$)/;
var strippedStateAttr = stripStateAttrPrefix( attr );
return ( ( expanderPropS.indexOf( strippedStateAttr ) !== -1 ) ||
( regexExpanderProps.test( strippedStateAttr ) )
);
},
propAttr: function ( attr ) {
return ( ( attr.indexOf( "." ) === -1 ) &&
( attr.charAt(0) !== "$") &&
( reservedNameS.indexOf( attr ) === -1 )
);
},
// source: underscore.js
nan: function ( num ) {
return ( typeof val === "number" ) &&
( val !== +val );
}
};
})();
(function(){
"use strict";
LAY.$checkIsWindowEvent = function ( eventName ) {
return [
"beforeunload",
"blur",
"error",
"focus",
"focusin",
"focusout",
"hashchange",
"load",
"message",
"offline",
"online",
"orientationchange",
"pagehide",
"pageshow",
"popstate",
"resize",
"scroll",
"storage",
"unload",
"webkitmouseforcechanged",
"webkitmouseforcedown",
"webkitmouseforceup",
"webkitmouseforcewillbegin",
"webkitwillrevealbottom",
"webkitwillrevealleft",
"webkitwillrevealright",
"webkitwillrevealtop",
].indexOf( eventName ) !== -1;
};
})();
( function () {
"use strict";
LAY.$clearDataTravellingAttrVals = function () {
var
x, y,
yLen,
renderDirtyPartS = LAY.$renderDirtyPartS,
renderDirtyPart,
travelRenderDirtyAttrValS,
travelRenderDirtyAttrVal;
for ( x = 0; x < renderDirtyPartS.length; x++ ) {
renderDirtyPart = renderDirtyPartS[ x ];
travelRenderDirtyAttrValS = renderDirtyPart.travelRenderDirtyAttrValS;
for ( y = 0, yLen = travelRenderDirtyAttrValS.length; y < yLen; y++ ) {
travelRenderDirtyAttrVal = travelRenderDirtyAttrValS[ 0 ];
if ( travelRenderDirtyAttrVal.renderCall ) {
travelRenderDirtyAttrVal.startCalcVal =
travelRenderDirtyAttrVal.transCalcVal;
// Adding to the "normal" render list automatically
// removes the attrval from the "travel" render list
renderDirtyPart.addNormalRenderDirtyAttrVal(
travelRenderDirtyAttrVal
);
} else {
LAY.$arrayUtils.remove( travelRenderDirtyAttrValS,
travelRenderDirtyAttrVal
);
}
}
}
};
})();
(function () {
"use strict";
/* @source: https://github.com/pvorb/node-clone/blob/master/clone.js
*/
function objectToString(o) {
return Object.prototype.toString.call(o);
}
var util = {
isArray: function (ar) {
return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]');
},
isDate: function (d) {
return typeof d === 'object' && objectToString(d) === '[object Date]';
},
isRegExp: function (re) {
return typeof re === 'object' && objectToString(re) === '[object RegExp]';
},
getRegExpFlags: function (re) {
var flags = '';
re.global && (flags += 'g');
re.ignoreCase && (flags += 'i');
re.multiline && (flags += 'm');
return flags;
}
};
/**
* Clones (copies) an Object using deep copying.
*
* This function supports circular references by default, but if you are certain
* there are no circular references in your object, you can save some CPU time
* by calling clone(obj, false).
*
* Caution: if `circular` is false and `parent` contains circular references,
* your program may enter an infinite loop and crash.
*
* @param `parent` - the object to be cloned
*/
LAY.$clone = function (parent) {
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
if ( typeof parent !== "object" ||
parent instanceof LAY.Level ||
parent instanceof LAY.Take ) {
return parent;
}
var allParents = [];
var allChildren = [];
var circular = true;
var depth = Infinity;
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null)
return null;
if (depth === 0)
return parent;
var child;
var proto;
if (typeof parent != 'object' ||
parent instanceof LAY.Level ||
parent instanceof LAY.Take ) {
return parent;
}
if ( parent instanceof LAY.Color ) {
return parent.copy();
}
if (util.isArray(parent)) {
child = [];
} else if (util.isRegExp(parent)) {
child = new RegExp(parent.source, util.getRegExpFlags(parent));
if (parent.lastIndex) child.lastIndex = parent.lastIndex;
} else if (util.isDate(parent)) {
child = new Date(parent.getTime());
} else {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
}
if (circular) {
var index = allParents.indexOf(parent);
if (index != -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
for (var i in parent) {
var attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, i);
}
if (attrs && attrs.set === null) {
continue;
}
child[i] = _clone(parent[i], depth - 1);
}
return child;
}
return _clone(parent, depth);
};
})();
( function () {
"use strict";
var
essentialProp2defaultValue,
formation2defaultArgs;
LAY.$defaultizeManyLson = function ( lson ) {
var
essentialProp,
rootState = lson.states.root;
lson.rows = lson.rows || [];
/* Filling in the defaults here for root lson */
for ( essentialProp in essentialProp2defaultValue ) {
if ( rootState[ essentialProp ] === undefined ) {
rootState[ essentialProp ] =
essentialProp2defaultValue[ essentialProp ];
}
}
// TODO: defaultize fargs here?
};
essentialProp2defaultValue = {
filter: new LAY.Take( "", "rows" ),
sort: [{key:"id", ascending:true}],
formation: "onebelow",
fargs: {}
};
})();
( function () {
"use strict";
var
nonRootEssentialProp2defaultValue,
rootEssentialProp2defaultValue,
lazyProp2defaultValue;
LAY.$defaultizePartLson = function ( lson, parentLevel ) {
var
essentialProp,
rootState = lson.states.root,
rootStateProps = rootState.props,
rootStateWhen = rootState.when,
rootStateTransition = rootState.transition,
props,
states = lson.states,
stateName, state,
prop,
when, transition, metaMax, maxProp,
eventType, transitionProp,
isRootLevel = parentLevel === undefined,
lazyVal,
parentLevelRootProps,
takeWindowWidth = LAY.take("", "$windowWidth"),
takeWindowHeight = LAY.take("", "$windowHeight"),
takeNaturalWidth = LAY.take("", "$naturalWidth"),
takeNaturalHeight = LAY.take("", "$naturalHeight"),
takeParentWidth = LAY.take("../", "width");
for ( stateName in states ) {
state = states[ stateName ];
props = state.props;
when = state.when;
transition = state.transition;
metaMax = state.$$max;
for ( prop in props ) {
if ( isRootLevel ) {
if ( props.top || props.left || props.width || props.height ) {
throw "LAY ERROR: Cannot set top/left/width/height of root Level";
}
}
if (rootStateProps[ prop ] === undefined ) {
lazyVal = LAY.$getLazyPropVal( prop,
isRootLevel );
if ( lazyVal !== undefined ) {
rootStateProps[ prop ] = lazyVal;
}
}
}
}
for ( maxProp in metaMax ) {
lson.$$max = lson.$$max || {};
if ( !lson.$$max[ maxProp ] ) {
lson.$$max[ metaMax ] = metaMax[ maxProp ];
}
}
for ( eventType in when ) {
if ( !rootStateWhen[ eventType ] ) {
rootStateWhen[ eventType ] = [];
}
}
for ( transitionProp in rootStateTransition ) {
if ( !rootStateTransition[ transitionProp ] ) {
rootStateTransition[ transitionProp ] = {};
}
}
if ( !isRootLevel ) {
// If the parent has an inheritable prop
// then create a prop within the root of
// the child's root props which can inherit
// in the case that the prop hasn't already
// been declared within the (child's root) props
parentLevelRootProps = parentLevel.lson.states.root.props;
for ( prop in parentLevelRootProps ) {
if ( rootStateProps[ prop ] === undefined &&
LAY.$inheritablePropS.indexOf( prop ) !== -1 ) {
rootStateProps[ prop ] = LAY.$getLazyPropVal( prop );
}
}
}
if ( rootStateProps.text !== undefined &&
( lson.$type === undefined || lson.$type === "none" ) ) {
lson.$type = "text";
} else if ( lson.$type === undefined ) {
lson.$type = "none";
}
/* Filling in the defaults here for root state lson */
if ( rootStateProps.left === undefined ) {
rootStateProps.left = 0;
}
if ( rootStateProps.top === undefined ) {
rootStateProps.top = 0;
}
if ( isRootLevel ) {
rootStateProps.width = takeWindowWidth;
rootStateProps.height = takeWindowHeight;
} else {
if ( rootStateProps.width === undefined ) {
/* if ( [
"text",
"html",
"input:select",
"input:multiple",
"image",
"link"
].indexOf( lson.$type ) !== -1 ) {
rootStateProps.width = takeNaturalWidth;
} else {
rootStateProps.width = takeParentWidth;
}*/
rootStateProps.width = takeNaturalWidth;
}
if ( rootStateProps.height === undefined ) {
rootStateProps.height = takeNaturalHeight;
}
}
};
})();
( function(){
"use strict";
var eventReadonly2_eventType2fnHandler_ = {
$hovering: {
mouseover: function () {
this.$changeAttrVal( "$hovering", true );
},
mouseout: function () {
this.$changeAttrVal( "$hovering", false );
}
},
$clicking: {
mousedown: function () {
this.$changeAttrVal( "$clicking", true );
},
touchdown: function () {
this.$changeAttrVal( "$clicking", true );
},
mouseup: function () {
this.$changeAttrVal( "$clicking", false );
},
mouseleave: function () {
this.$changeAttrVal( "$clicking", false );
},
touchup: function () {
this.$changeAttrVal( "$clicking", false );
}
},
$focused: {
focus: function () {
this.$requestRecalculation( "$focused" );
},
blur: function () {
this.$requestRecalculation( "$focused" );
}
},
$scrolledX: {
scroll: function () {
this.$requestRecalculation( "$scrolledX" );
}
},
$scrolledY: {
scroll: function () {
this.$requestRecalculation( "$scrolledY" );
}
},
$cursorX: {
mousemove: function (e) {
this.$changeAttrVal( "$cursorX", e.clientX );
}
},
$cursorY: {
mousemove: function (e) {
this.$changeAttrVal( "$cursorY", e.clientY );
}
},
$input: {
click: function () {
if ( this.part.inputType === "multiline" ||
this.part.inputType === "line" ) {
this.$requestRecalculation( "$input" );
}
},
change: function () {
this.$requestRecalculation( "$input" );
},
keyup: function () {
if ( this.part.inputType === "multiline" ||
this.part.inputType === "line" ) {
this.$requestRecalculation( "$input" );
}
}
}
};
LAY.$eventReadonlyUtils = {
checkIsEventReadonlyAttr: function ( attr ) {
return eventReadonly2_eventType2fnHandler_[ attr ] !==
undefined;
},
getEventType2fnHandler: function ( attr ) {
return eventReadonly2_eventType2fnHandler_[ attr ];
}
};
})();
( function () {
"use strict";
// Modified Source of: <NAME>, 2005
// with input from <NAME>, <NAME>, <NAME>
// Original Source: http://dean.edwards.name/weblog/2005/10/add-event/
LAY.$eventUtils = {
add: function ( element, type, handler ) {
if ( element.addEventListener ) {
element.addEventListener(type, handler, false);
} else {
// create a hash table of event types for the element
if (!element.events) element.events = {};
// create a hash table of event handlers for each element/event pair
var handlers = element.events[type];
if (!handlers) {
handlers = element.events[type] = [];
// store the existing event handler (if there is one)
if (element["on" + type]) {
handlers.push( element["on" + type] );
}
}
// add the event handler to the list of handlers
handlers.push( handler );
// assign a global event handler to do all the work
element["on" + type] = handle;
}
},
remove: function ( element, type, handler ) {
if ( element.removeEventListener ) {
element.removeEventListener(type, handler, false);
} else {
// delete the event handler from the hash table
if (element.events && element.events[type]) {
var handlers = element.events[type];
LAY.$arrayUtils.remove(handlers, handler);
}
}
}
};
function handle( event ) {
var returnValue = true;
// grab the event object (IE uses a global event object)
event = event || fix(((this.ownerDocument || this.document || this).parentWindow || window).event);
// get a reference to the hash table of event handlers
var handlers = this.events[event.type];
// execute each event handler
for ( var i=0, len=handlers.length; i<len; i++ ) {
this.$$handleEvent = handlers[i];
if (this.$$handleEvent(event) === false) {
returnValue = false;
}
}
return returnValue;
}
function fix(event) {
// add W3C standard event methods
event.preventDefault = fix_preventDefault;
event.stopPropagation = fix_stopPropagation;
return event;
}
function fix_preventDefault() {
this.returnValue = false;
}
function fix_stopPropagation() {
this.cancelBubble = true;
}
})();
( function () {
"use strict";
LAY.$filterUtils = {
eq: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] === val;
}, rowS );
},
neq: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] !== val;
}, rowS );
},
gt: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] > val;
}, rowS );
},
gte: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] >= val;
}, rowS );
},
lt: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] < val;
}, rowS );
},
lte: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ] <= val;
}, rowS );
},
regex: function ( rowS, key, val ) {
return filter( function ( row ) {
return val.test( row[ key ] );
}, rowS );
},
contains: function ( rowS, key, val ) {
return filter( function ( row ) {
return row[ key ].indexOf( val ) !== -1;
}, rowS );
},
within: function ( rowS, key, val ) {
return filter( function ( row ) {
return val.indexOf( row[ key ] ) !== -1;
}, rowS );
},
fn: function ( rowS, fnFilter ) {
return filter( fnFilter , rowS );
}
};
function filter ( fnFilter, rowS ) {
var filteredRowS = [];
for ( var i = 0, len = rowS.length, row; i < len; i++ ) {
row = rowS[ i ];
if ( fnFilter( row ) ) {
filteredRowS.push( row );
}
}
return filteredRowS;
}
})();
( function () {
"use strict";
var regexDetails = /^([a-zA-Z]+)(\d+)/;
LAY.$findMultipleTypePropMatchDetails = function ( prop ) {
return prop.match( regexDetails );
};
})();
(function(){
"use strict";
LAY.$findRenderCall = function( prop, level ) {
var
renderCall,
multipleTypePropMatchDetails;
if ( level.isHelper ) {
return "";
} else if ( !LAY.$checkIsValidUtils.propAttr( prop ) ||
( [ "centerX", "right", "centerY", "bottom" ] ).indexOf( prop ) !== -1 ||
LAY.$shorthandPropsUtils.checkIsDecentralizedShorthandProp( prop ) ) {
return undefined;
} else {
multipleTypePropMatchDetails = LAY.$findMultipleTypePropMatchDetails(
prop );
if ( multipleTypePropMatchDetails ) {
return multipleTypePropMatchDetails[ 1 ];
}
renderCall =
LAY.$shorthandPropsUtils.getShorthandPropCenteralized(
prop );
if ( renderCall !== undefined ) {
if ( level.isGpu &&
( renderCall === "x" ||
renderCall === "y" ||
renderCall === "transform" ) ) {
return "positionAndTransform";
} else {
return renderCall;
}
} else {
if ( prop.startsWith("text") &&
( !level.part || level.part.type === "none" ) ) {
return undefined;
}
}
return prop;
}
};
})();
( function () {
"use strict";
LAY.$foldlUtils = {
min: function ( rowS, key ) {
return fold( function ( row, acc ) {
var val = row[ key ];
if ( ( acc === undefined ) || ( val < acc ) ) {
return val;
} else {
return acc;
}
}, undefined, rowS );
},
max: function ( rowS, key ) {
return fold( function ( row, acc ) {
var val = row[ key ];
if ( ( acc === undefined ) || ( val > acc ) ) {
return val;
} else {
return acc;
}
}, undefined, rowS );
},
sum: function ( rowS, key ) {
return fold( function ( row, acc ) {
return acc + row[ key ];
}, 0, rowS );
},
fn: function ( rowS, fnFold, acc ) {
return fold( fnFold, acc, rowS );
}
};
function fold ( fnFold, acc, rowS ) {
for ( var i = 0, len = rowS.length; i < len; i++ ) {
acc = fnFold( rowS[ i ], acc );
}
return acc;
}
})();
// LAY has taken the below source from 'tmaeda1981jp'
// source: https://github.com/tmaeda1981jp/string-format-js/blob/master/format.js
(function() {
"use strict";
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var Formatter = (function() {
var Constr = function(identifier) {
var array = function(len){ return new Array(len); };
switch(true) {
case /^#\{(\w+)\}*$/.test(identifier):
this.formatter = function(line, param) {
return line.replace('#{' + RegExp.$1 + '}', param[RegExp.$1]);
};
break;
case /^([ds])$/.test(identifier):
this.formatter = function(line, param) {
if (RegExp.$1 === 'd' && !isNumber(param)) {
throw new TypeError();
}
return line.replace("%" + identifier, param);
};
break;
// Octet
case /^(o)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
return line.replace(
"%" + identifier,
parseInt(param).toString(8));
};
break;
// Binary
case /^(b)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
return line.replace(
"%" + identifier,
parseInt(param).toString(2));
};
break;
// Hex
case /^([xX])$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
var hex = parseInt(param).toString(16);
if (identifier === 'X') { hex = hex.toUpperCase(); }
return line.replace("%" + identifier, hex);
};
break;
case /^(c)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
return line.replace("%" + identifier, String.fromCharCode(param));
};
break;
case /^(u)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
return line.replace("%" + identifier, parseInt(param, 10) >>> 0);
};
break;
case /^(-?)(\d*).?(\d?)(e)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
var lpad = RegExp.$1 === '-',
width = RegExp.$2,
decimal = RegExp.$3 !== '' ? RegExp.$3: undefined,
val = param.toExponential(decimal),
mantissa, exponent, padLength
;
if (width !== '') {
if (decimal !== undefined) {
padLength = width - val.length;
if (padLength >= 0){
val = lpad ?
val + array(padLength + 1).join(" "):
array(padLength + 1).join(" ") + val;
}
else {
// TODO throw ?
}
}
else {
mantissa = val.split('e')[0];
exponent = 'e' + val.split('e')[1];
padLength = width - (mantissa.length + exponent.length);
val = padLength >= 0 ?
mantissa + (array(padLength + 1)).join("0") + exponent :
mantissa.slice(0, padLength) + exponent;
}
}
return line.replace("%" + identifier, val);
};
break;
case /^(-?)(\d*).?(\d?)(f)$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
var lpad = RegExp.$1 === '-',
width = RegExp.$2,
decimal = RegExp.$3,
DOT_LENGTH = '.'.length,
integralPart = param > 0 ? Math.floor(param) : Math.ceil(param),
val = parseFloat(param).toFixed(decimal !== '' ? decimal : 6),
numberPartWidth, spaceWidth;
if (width !== '') {
if (decimal !== '') {
numberPartWidth =
integralPart.toString().length + DOT_LENGTH + parseInt(decimal, 10);
spaceWidth = width - numberPartWidth;
val = lpad ?
parseFloat(param).toFixed(decimal) + (array(spaceWidth + 1).join(" ")) :
(array(spaceWidth + 1).join(" ")) + parseFloat(param).toFixed(decimal);
}
else {
val = parseFloat(param).toFixed(
width - (integralPart.toString().length + DOT_LENGTH));
}
}
return line.replace("%" + identifier, val);
};
break;
// Decimal
case /^([0\-]?)(\d+)d$/.test(identifier):
this.formatter = function(line, param) {
if (!isNumber(param)) { throw new TypeError(); }
var len = RegExp.$2 - param.toString().length,
replaceString = '',
result;
if (len < 0) { len = 0; }
switch(RegExp.$1) {
case "": // rpad
replaceString = (array(len + 1).join(" ") + param).slice(-RegExp.$2);
break;
case "-": // lpad
replaceString = (param + array(len + 1).join(" ")).slice(-RegExp.$2);
break;
case "0": // 0pad
replaceString = (array(len + 1).join("0") + param).slice(-RegExp.$2);
break;
}
return line.replace("%" + identifier, replaceString);
};
break;
// String
case /^(-?)(\d)s$/.test(identifier):
this.formatter = function(line, param) {
var len = RegExp.$2 - param.toString().length,
replaceString = '',
result;
if (len < 0) { len = 0; }
switch(RegExp.$1) {
case "": // rpad
replaceString = (array(len + 1).join(" ") + param).slice(-RegExp.$2);
break;
case "-": // lpad
replaceString = (param + array(len + 1).join(" ")).slice(-RegExp.$2);
break;
default:
// TODO throw ?
}
return line.replace("%" + identifier, replaceString);
};
break;
// String with max length
case /^(-?\d?)\.(\d)s$/.test(identifier):
this.formatter = function(line, param) {
var replaceString = '',
max, spacelen;
// %.4s
if (RegExp.$1 === '') {
replaceString = param.slice(0, RegExp.$2);
}
// %5.4s %-5.4s
else {
param = param.slice(0, RegExp.$2);
max = Math.abs(RegExp.$1);
spacelen = max - param.toString().length;
replaceString = RegExp.$1.indexOf('-') !== -1 ?
(param + array(spacelen + 1).join(" ")).slice(-max): // lpad
(array(spacelen + 1).join(" ") + param).slice(-max); // rpad
}
return line.replace("%" + identifier, replaceString);
};
break;
default:
this.formatter = function(line, param) {
return line;
};
}
};
Constr.prototype = {
format: function(line, param) {
return this.formatter.call(this, line, param);
}
};
return Constr;
}());
LAY.$format = function() {
var i,
result,
argSLength = arguments.length,
argS = Array.prototype.slice.call(arguments),
arg;
try {
// result contians the formattable string
result = argS[ 0 ];
for ( i = 1; i < argSLength; i++ ) {
arg = argS[ i ];
if (result.match(/%([.#0-9\-]*[bcdefosuxX])/)) {
arg = arg instanceof LAY.Color ? arg.stringify() : arg;
result = new Formatter(RegExp.$1).format(result, arg );
}
}
return result;
} catch (err) {
return "";
}
};
}());
( function() {
"use strict";
LAY.$formation2fargs = {
"onebelow": {
gap: 0
},
"totheright": {
gap: 0
},
"grid": {
columns: null,
hgap: 0,
vgap: 0
},
"none": {
},
"circular": {
radius: null
}
};
})();
( function () {
"use strict";
LAY.$formation2fn = {
none: function ( f , filteredLevel, filteredLevelS, fargs ) {
return [ undefined, undefined ];
},
onebelow: function ( f, filteredLevel, filteredLevelS, fargs ) {
return [
undefined,
fargs.gap === 0 ?
LAY.take(filteredLevelS[ f - 2 ].path(), "bottom") :
LAY.take(filteredLevelS[ f - 2 ].path(), "bottom").add(
fargs.gap)
];
},
totheright: function ( f, filteredLevel, filteredLevelS, fargs ) {
return [
fargs.gap === 0 ?
LAY.take(filteredLevelS[ f - 2 ].path(), "right") :
LAY.take(filteredLevelS[ f - 2 ].path(), "right").add(
fargs.gap),
undefined
];
},
grid: function ( f, filteredLevel, filteredLevelS, fargs ) {
var numCols = fargs.columns;
var vgap = fargs.vgap;
var hgap = fargs.hgap;
var x,y;
if ( f > numCols && ( ( f % numCols === 1 ) || numCols === 1 ) ) {
x = LAY.take( filteredLevelS[ 0 ].path(), "left" );
} else {
x = LAY.take( filteredLevelS[ f - 2 ].path(), "right" ).add(hgap);
}
if ( f <= numCols ) {
y = undefined;
} else {
y = LAY.take( filteredLevelS[ f - numCols - 1 ].path(),
"bottom" ).add(vgap);
}
return [ x, y ];
},
circular: function ( f, filteredLevel, filteredLevelS, fargs) {
var angle = ( (f-1) * ( 360 / filteredLevelS.length ) ) - 90;
var firstLevelPathName = filteredLevelS[ 0 ].path();
var originX = LAY.take(firstLevelPathName, "centerX");
var originY = LAY.take(firstLevelPathName, "centerY").add(
fargs.radius );
var degreesToRadian = Math.PI / 180;
var paramX = fargs.radius * Math.cos(angle*degreesToRadian);
var paramY = fargs.radius * Math.sin(angle*degreesToRadian);
return [originX.add(paramX).minus(
LAY.take("", "width").half()),
originY.add(paramY).minus(LAY.take("", "height").half())];
}
};
})();
( function () {
"use strict";
LAY.$generateColorMix = function ( startColor, endColor, fraction ) {
var
startColorRgbaDict = startColor.getRgba(),
endColorRgbaDict = endColor.getRgba(),
midColor;
return new LAY.Color( "rgb", {
r: Math.round( startColorRgbaDict.r +
fraction * ( endColorRgbaDict.r - startColorRgbaDict.r )
),
g: Math.round( startColorRgbaDict.g +
fraction * ( endColorRgbaDict.g - startColorRgbaDict.g )
),
b: Math.round( startColorRgbaDict.b +
fraction * ( endColorRgbaDict.b - startColorRgbaDict.b )
)
}, ( startColorRgbaDict.a +
fraction * ( endColorRgbaDict.a - startColorRgbaDict.a )
) );
};
})();
( function() {
"use strict";
var
rootLazyProp2defaultVal = {
userSelect: "auto",
cursor: "auto",
textSize: 15,
textFamily: "sans-serif",
textWeight: "normal",
textColor: LAY.color("black"),
textVariant: "normal",
textTransform: "none",
textStyle: "normal",
textLetterSpacing: 0,
textWordSpacing: 0,
textAlign: "left",
textDirection: "ltr",
textLineHeight: 1.3,
textIndent: 0,
textWrap: "nowrap",
textWordBreak: "normal",
textWordWrap: "normal",
textSmoothing: "antialiased",
textRendering: "auto"
},
nonRootLazyProp2defaultVal = {
userSelect: LAY.take("../", "userSelect"),
cursor: LAY.take("../", "cursor"),
textSize: LAY.take("../", "textSize"),
textFamily: LAY.take("../", "textFamily"),
textWeight: LAY.take("../", "textWeight"),
textColor: LAY.take("../", "textColor"),
textVariant: LAY.take("../", "textVariant"),
textTransform: LAY.take("../", "textTransform"),
textStyle: LAY.take("../", "textStyle"),
textLetterSpacing: LAY.take("../", "textLetterSpacing"),
textWordSpacing: LAY.take("../", "textWordSpacing"),
textAlign: LAY.take("../", "textAlign"),
textDirection: LAY.take("../", "textDirection"),
textLineHeight: LAY.take("../", "textLineHeight"),
textIndent: LAY.take("../", "textIndent"),
textWrap: LAY.take("../", "textWrap"),
textWordBreak: LAY.take("../", "textWordBreak"),
textWordWrap: LAY.take("../", "textWordWrap"),
textSmoothing: LAY.take("../", "textSmoothing"),
textRendering: LAY.take("../", "textRendering")
},
commonLazyProp2defaultVal = {
display: true,
visible: true,
z: 0,
shiftX: 0,
shiftY: 0,
rotateX: 0,
rotateY: 0,
rotateZ: 0,
scaleX: 1,
scaleY: 1,
scaleZ:1,
skewX: 0,
skewY: 0,
originX: 0.5,
originY: 0.5,
originZ: 0,
perspective:0,
perspectiveOriginX: 0.5,
perspectiveOriginY: 0.5,
backfaceVisibility: false,
opacity:1.0,
zIndex: "auto",
scrollX: 0,
scrollY: 0,
focus: false,
scrollElastic: true,
title: null,
backgroundColor: LAY.transparent(),
backgroundImage: "none",
backgroundAttachment: "scroll",
backgroundRepeat: "repeat",
backgroundPositionX: 0,
backgroundPositionY: 0,
backgroundSizeX: "auto",
backgroundSizeY: "auto",
cornerRadiusTopLeft: 0,
cornerRadiusTopRight: 0,
cornerRadiusBottomLeft: 0,
cornerRadiusBottomRight: 0,
borderTopStyle: "solid",
borderBottomStyle: "solid",
borderRightStyle: "solid",
borderLeftStyle: "solid",
borderTopWidth: 0,
borderBottomWidth: 0,
borderRightWidth: 0,
borderLeftWidth: 0,
borderTopColor: LAY.transparent(),
borderBottomColor: LAY.transparent(),
borderRightColor: LAY.transparent(),
borderLeftColor: LAY.transparent(),
text: "",
textOverflow: "clip",
textDecoration: "none",
textPaddingTop: 0,
textPaddingRight: 0,
textPaddingBottom: 0,
textPaddingLeft: 0,
input: "",
inputLabel: "",
inputPlaceholder: "",
inputAutocomplete: false,
inputAutocorrect: true,
inputDisabled: false,
imageUrl:null,
imageAlt: null,
videoAutoplay: false,
videoControls: true,
videoCrossorigin: "anonymous",
videoLoop: false,
videoMuted: false,
videoPreload: "auto",
videoPoster: null,
audioControls: true,
audioLoop: false,
audioMuted: false,
audioPreload: "auto",
audioVolume: 1.0
};
LAY.$getLazyPropVal = function ( prop, isRootLevel ) {
var commonLazyVal = commonLazyProp2defaultVal[ prop ];
return commonLazyVal !== undefined ?
commonLazyVal :
( isRootLevel ?
rootLazyProp2defaultVal[ prop ] :
nonRootLazyProp2defaultVal[ prop ] );
}
})();
(function () {
"use strict";
// Inheritance allows modifications to the
// `intoLson` object, but disallows modifications
// to `fromLson`
/*
* Inherit the root, state, or many LSON from `from` into `into`.
*/
LAY.$inherit = function ( into, from, isStateInheritance, isMany, isMainLson ) {
if ( !isStateInheritance ) {
for ( var key in from ) {
if ( from[ key ] ) {
if ( key2fnInherit[ key ] ) {
key2fnInherit[ key ]( into, from, isMany );
} else {
into[ key ] = from[ key ];
}
}
}
} else {
if ( !isMainLson ) {
into.onlyif = from.onlyif || into.onlyif;
into.install = from.install || into.install;
into.uninstall = from.uninstall || into.uninstall;
}
if ( isMany ) {
into.formation = from.formation || into.formation;
into.filter = from.filter || into.filter;
key2fnInherit.fargs( into, from );
into.sort = from.sort || into.sort;
} else {
if ( from.props !== undefined ) {
key2fnInherit.props( into, from );
}
if ( from.when !== undefined ) {
key2fnInherit.when( into, from );
}
if ( from.transition !== undefined ) {
key2fnInherit.transition( into, from );
}
if ( from.$$max !== undefined ) {
key2fnInherit.$$max( into, from );
}
}
}
};
function inheritTransitionProp ( intoTransition, fromTransition,
intoTransitionProp, fromTransitionProp ) {
var
fromTransitionDirective = fromTransition[ fromTransitionProp ],
intoTransitionDirective = intoTransition[ intoTransitionProp ],
fromTransitionArgKey2val, intoTransitionArgKey2val,
fromTransitionArgKey;
if ( fromTransitionDirective !== undefined ) {
if ( intoTransitionDirective === undefined ) {
intoTransitionDirective =
intoTransition[ intoTransitionProp ] = {};
}
intoTransitionDirective.type = fromTransitionDirective.type ||
intoTransitionDirective.type;
intoTransitionDirective.duration = fromTransitionDirective.duration ||
intoTransitionDirective.duration;
intoTransitionDirective.delay = fromTransitionDirective.delay ||
intoTransitionDirective.delay;
intoTransitionDirective.done = fromTransitionDirective.done ||
intoTransitionDirective.done;
fromTransitionArgKey2val = fromTransitionDirective.args;
intoTransitionArgKey2val = intoTransitionDirective.args;
if ( fromTransitionArgKey2val !== undefined ) {
if ( intoTransitionArgKey2val === undefined ) {
intoTransitionArgKey2val =
intoTransitionDirective.args = {};
}
for ( fromTransitionArgKey in fromTransitionArgKey2val ) {
intoTransitionArgKey2val[ fromTransitionArgKey ] =
fromTransitionArgKey2val[ fromTransitionArgKey ];
}
}
}
}
function checkIsMutable ( val ) {
return ( typeof val === "object" );
}
function inheritSingleLevelObject( intoObject, fromObject, key, isDuplicateOn ) {
var fromKey2value, intoKey2value, fromKey, fromKeyValue;
fromKey2value = fromObject[ key ];
intoKey2value = intoObject[ key ];
if ( intoKey2value === undefined ) {
intoKey2value = intoObject[ key ] = {};
}
for ( fromKey in fromKey2value ) {
fromKeyValue = fromKey2value[ fromKey ];
intoKey2value[ fromKey ] = ( isDuplicateOn &&
checkIsMutable( fromKeyValue ) ) ?
LAY.$clone( fromKeyValue ) :
fromKeyValue;
}
}
// Precondition: `into<Scope>.key (eg: intoLAY.key)` is already defined
var key2fnInherit = {
data: function( intoLson, fromLson ) {
inheritSingleLevelObject( intoLson, fromLson, "data" );
},
props: function( intoLson, fromLson ) {
inheritSingleLevelObject( intoLson, fromLson, "props" );
},
transition: function ( intoLson, fromLson ) {
var
fromTransition = fromLson.transition,
intoTransition = intoLson.transition,
fromTransitionProp,
intoTransitionProp,
i, len,
tmpTransition = {};
if ( ( intoTransition === undefined ) ) {
intoTransition = intoLson.transition = {};
}
// "all" prop overwrite stage
//
// Eg: "rotateX" partially/completely overwritten
// by "all" where "rotateX" is present
// within "into"LSON and "all" is present
// within "from"LSON
if ( fromTransition.all ) {
for ( intoTransitionProp in intoTransition ) {
if ( intoTransition !== "all" ) {
inheritTransitionProp( intoTransition, fromTransition,
intoTransitionProp, "all" );
}
}
}
// General inheritance of props of exact
// names across from and into LSON
for ( fromTransitionProp in fromTransition ) {
inheritTransitionProp( intoTransition, fromTransition,
fromTransitionProp, fromTransitionProp );
}
// flatten stage
//
// This is akin to a self-inheritance stafe whereby
// prop transition directives are stacked
// below the "all" transition direction
//
// Eg: a shorthand property such as "rotateX"
// would inherit values from "all"
//
if ( intoTransition.all ) {
for ( intoTransitionProp in intoTransition ) {
if ( intoTransitionProp !== "all" ) {
tmpTransition[ intoTransitionProp ] = {};
inheritTransitionProp(
tmpTransition, intoTransition,
intoTransitionProp, "all" );
inheritTransitionProp(
tmpTransition, intoTransition,
intoTransitionProp, intoTransitionProp );
intoTransition[ intoTransitionProp ] =
tmpTransition[ intoTransitionProp ];
}
}
}
},
many: function( intoLson, fromLson ) {
if ( intoLson.many === undefined ) {
intoLson.many = {};
}
LAY.$inherit( intoLson.many, fromLson.many,
false, true, false );
},
rows: function( intoLson, fromLson ) {
var
intoLsonRowS = intoLson.rows,
fromLsonRowS = fromLson.rows,
fromLsonRow;
if ( fromLsonRowS ) {
if ( fromLsonRowS instanceof LAY.Take ) {
intoLson.rows = fromLsonRowS;
} else {
intoLson.rows = new Array( fromLsonRowS.length );
intoLsonRowS = intoLson.rows;
for ( var i = 0, len = fromLsonRowS.length; i < len; i++ ) {
fromLsonRow = fromLsonRowS[ i ];
intoLsonRowS[ i ] = checkIsMutable( fromLsonRow ) ?
LAY.$clone( fromLsonRow ) : fromLsonRow;
}
}
}
},
fargs: function ( intoLson, fromLson ) {
var
formationFarg,
intoFargs = intoLson.fargs,
fromFargs = fromLson.fargs;
if ( fromFargs ) {
if ( !intoFargs ) {
intoFargs = intoLson.fargs = {};
}
for ( formationFarg in fromFargs ) {
if ( !intoFargs[ formationFarg ] ) {
intoFargs[ formationFarg ] = {};
}
inheritSingleLevelObject(
intoFargs, fromFargs, formationFarg );
}
}
},
children: function( intoLson, fromLson ) {
var fromChildName2lson, intoChildName2lson;
fromChildName2lson = fromLson.children;
intoChildName2lson = intoLson.children;
if ( intoChildName2lson === undefined ) {
intoChildName2lson = intoLson.children = {};
}
for ( var name in fromChildName2lson ) {
if ( intoChildName2lson[ name ] === undefined ) { // inexistent child
intoChildName2lson[ name ] = {};
}
LAY.$inherit( intoChildName2lson[ name ], fromChildName2lson[ name ],
false, false, false );
}
},
states: function( intoLson, fromLson, isMany ) {
var
fromStateName2state = fromLson.states,
intoStateName2state = intoLson.states,
inheritFromState, inheritIntoState;
if ( intoStateName2state === undefined ) {
intoStateName2state = intoLson.states = {};
}
for ( var name in fromStateName2state ) {
if ( !intoStateName2state[ name ] ) { //inexistent state
intoStateName2state[ name ] = {};
}
LAY.$inherit( intoStateName2state[ name ],
fromStateName2state[ name ], true, isMany, false );
}
},
when: function( intoLson, fromLson ) {
var
fromEventType2_fnEventHandlerS_ = fromLson.when,
intoEventType2_fnEventHandlerS_ = intoLson.when,
fnFromEventHandlerS, fnIntoEventHandlerS, fromEventType;
if ( intoEventType2_fnEventHandlerS_ === undefined ) {
intoEventType2_fnEventHandlerS_ = intoLson.when = {};
}
for ( fromEventType in fromEventType2_fnEventHandlerS_ ) {
fnFromEventHandlerS = fromEventType2_fnEventHandlerS_[ fromEventType ];
fnIntoEventHandlerS = intoEventType2_fnEventHandlerS_[ fromEventType ];
if ( fnIntoEventHandlerS === undefined ) {
intoEventType2_fnEventHandlerS_[ fromEventType ] = LAY.$arrayUtils.cloneSingleLevel( fnFromEventHandlerS );
} else {
intoEventType2_fnEventHandlerS_[ fromEventType ] = fnIntoEventHandlerS.concat( fnFromEventHandlerS );
}
LAY.$meta.set( intoLson, "num", "when." + fromEventType,
( intoEventType2_fnEventHandlerS_[ fromEventType ] ).length );
}
},
$$max: function ( intoLson, fromLson ) {
LAY.$meta.inherit.$$max( intoLson, fromLson );
}
};
})();
(function () {
"use strict";
LAY.$inheritablePropS = [
"textSize",
"textFamily",
"textWeight",
"textColor",
"textVariant",
"textTransform",
"textStyle",
"textLetterSpacing",
"textWordSpacing",
"textAlign",
"textDirection",
"textLineHeight",
"textIndent",
"textWrap",
"textWordBreak",
"textWordWrap",
"textSmoothing",
"textRendering",
"cursor",
"userSelect"
];
})();
(function() {
"use strict";
LAY.$meta = {
set: function ( lson, metaDomain, attr, val ) {
var fullMetaDomain = "$$" + metaDomain;
if ( lson[ fullMetaDomain ] === undefined ) {
lson[ fullMetaDomain ] = {};
}
lson[ fullMetaDomain ][ attr ] = val;
},
get: function ( lson, metaDomain, attr ) {
var fullMetaDomain = "$$" + metaDomain;
if ( lson[ fullMetaDomain ] === undefined ) {
return undefined;
} else {
return lson[ fullMetaDomain ][ attr ];
}
},
inherit: {
$$max: function ( intoLson, fromLson ) {
var
fromAttr2max = fromLson.$$max,
intoAttr2max = intoLson.$$max,
fromAttr;
if ( intoAttr2max === undefined ) {
intoAttr2max = intoLson.$$max = {};
}
for ( fromAttr in fromAttr2max ) {
if ( intoAttr2max[ fromAttr ] === undefined ) {
intoAttr2max[ fromAttr ] =
fromAttr2max[ fromAttr ];
} else {
intoAttr2max[ fromAttr ] = Math.max(
intoAttr2max[ fromAttr ],
fromAttr2max[ fromAttr ]
);
}
}
}
}
};
})();
(function () {
"use strict";
var
normalizedExternalLsonS = [],
fnCenterToPos,
fnOppEdgeToPos,
takeWidth,
takeHeight,
takeParentWidth,
takeParentHeight,
takeZeroCenterX,
takeZeroCenterY,
key2fnNormalize;
fnCenterToPos = function( center, dim, parentDim ) {
return ( parentDim / 2 ) + ( center - ( dim / 2 ) );
};
fnOppEdgeToPos = function( edge, dim, parentDim ) {
return parentDim - ( edge + dim );
};
takeWidth = new LAY.Take( "", "width" );
takeHeight = new LAY.Take( "", "height" );
takeParentWidth = new LAY.take( "../", "width");
takeParentHeight = new LAY.take( "../", "height");
takeZeroCenterX = ( new LAY.take("../", "width")).half().minus(
( new LAY.take("", "width") ).half() );
takeZeroCenterY = ( new LAY.take("../", "height")).half().minus(
( new LAY.take("", "height") ).half() );
LAY.$normalize = function( lson, isExternal ) {
if ( isExternal ) {
// If we haven't previously normalized it, only then proceed
if ( normalizedExternalLsonS.indexOf( lson ) === -1 ) {
normalize( lson, true );
normalizedExternalLsonS.push( lson );
}
} else {
normalize( lson, false );
}
};
function normalize( lson, isRecursive ) {
var
lsonKey,
rootLson = lson;
if ( !lson.$$normalized ) {
if ( !lson.states ) {
lson.states = {};
}
if ( lson.states.root ) {
throw "LAY Error: State name 'root' is reserved.";
}
checkForInconsistentReadonlyKeys( lson );
normalizeLazyChildren( lson );
lson.states.root = {
props: lson.props,
when: lson.when,
transition: lson.transition
};
for ( lsonKey in lson ) {
if ( lsonKey !== "children" || isRecursive ) {
if ( lson[ lsonKey ] && lsonKey !== "$$max" ) {
if ( !key2fnNormalize[ lsonKey ] ) {
throw "LAY Error: LSON key: '" + lsonKey + "' not found";
}
key2fnNormalize[ lsonKey ]( lson );
}
}
}
lson.props = undefined;
lson.when = undefined;
lson.transition = undefined;
lson.$$normalized = true;
}
}
/*
* Checks for common naming mistakes with
* readonly keys (i.e beginning with "$")
*/
function checkForInconsistentReadonlyKeys( lson ) {
var errorReadonly = "";
if ( lson.inherits || lson.$inherits ) {
throw "LAY Error: Did you mean '$inherit'?";
} else if ( lson.load ) {
errorReadonly = "load";
} else if ( lson.inherit ) {
errorReadonly = "inherit";
} else if ( lson.gpu ) {
errorReadonly = "gpu";
} else if ( lson.obdurate ) {
errorReadonly = "obdurate";
} else if ( lson.type ) {
errorReadonly = "type"
}
if ( errorReadonly ) {
throw "LAY Error: prefix readonly '" +
errorReadonly + "' with '$'";
}
}
function normalizeLazyChildren( lson ) {
lson.children = lson.children || {};
for ( var key in lson ) {
if ( !key2fnNormalize[ key ]) {
lson.children[ key ] = lson[ key ];
lson[ key ] = undefined;
}
}
}
function checkAndThrowErrorAttrAsTake ( name, val ) {
if ( val instanceof LAY.Take ) {
throw ( "LAY Error: takes for special/expander props such as '" + name + "' are not permitted." );
}
}
/*
* Recursively flatten the prop if object or array typed
*/
function flattenProp( props, obj, key, prefix ) {
var val, type, flattenedProp;
val = obj[ key ];
type = LAY.$type( val );
if ( type === "array" && key !== "input" ) {
for ( var i = 0, len = val.length; i < len; i++ ) {
flattenedProp = prefix + ( i + 1 );
flattenProp( props, val, i, flattenedProp );
}
obj[ key ] = undefined;
} else if ( type === "object" ) {
for ( var subKey in val ) {
flattenedProp = prefix + LAY.$capitalize( subKey );
flattenProp( props, val, subKey, flattenedProp );
obj[ key ] = undefined;
}
} else {
if ( LAY.$checkIsValidUtils.checkIsPropAttrExpandable( prefix ) ) {
checkAndThrowErrorAttrAsTake( prefix, val );
}
props[ prefix ] = val;
}
}
key2fnNormalize = {
/*type: function ( lson ) {
checkAndThrowErrorAttrAsTake( "type", lson.type );
if ( lson.type === undefined ) {
// check if text type
var isTextType = false;
if ( lson.props.text !== undefined ) {
isTextType = true;
}
lson.type = isTextType ? "text" : "none";
}
var type = lson.type;
if ( ( type === "text" ) && ( lson.children !== undefined ) ) {
throw( "LAY Error: Text type Level with child Levels found" );
}
if ( type.startsWith( "input" ) ) {
lson.type = "input";
lson.inputType = type.slice( ( "input:" ).length );
}
},*/
$type: function ( lson ) {
checkAndThrowErrorAttrAsTake( "$type", lson.$type );
},
$inherit: function ( lson ) {
if ( !( lson.$inherit instanceof Array ) ) {
lson.$inherit = [ lson.$inherit ];
}
checkAndThrowErrorAttrAsTake( "$inherit", lson.$inherit );
if ( ( lson.$inherit !== undefined ) &&
LAY.$type( lson.$inherit ) !== "array" ) {
lson.$inherit = [ lson.$inherit ];
}
},
$obdurate: function ( lson ) {
checkAndThrowErrorAttrAsTake( "$obdurate", lson.$obdurate );
},
$load: function ( lson ) {
checkAndThrowErrorAttrAsTake( "$load", lson.$load );
},
$gpu: function ( lson ) {
checkAndThrowErrorAttrAsTake( "$gpu", lson.$gpu );
},
data: function ( lson ) {
checkAndThrowErrorAttrAsTake( "data", lson.data );
},
exist: function ( lson ) {
},
/*
* normalize the `lson`
*/
props: function( lson ) {
var
prop2val = lson.props,
prop, val,
longhandPropS, longhandProp, shorthandVal,
multipleTypePropMatchDetails,curMultipleMax,
i, len;
if ( lson.props === undefined ) {
prop2val = lson.props = {};
}
checkAndThrowErrorAttrAsTake( "props", lson.props );
if ( prop2val.centerX !== undefined ) {
if ( prop2val.centerX === 0 ) { //optimization
prop2val.left = takeZeroCenterX;
} else {
prop2val.left = ( new LAY.Take( fnCenterToPos ) ).fn(
prop2val.centerX, takeWidth, takeParentWidth );
}
prop2val.centerX = undefined;
}
if ( prop2val.right !== undefined ) {
prop2val.left = ( new LAY.Take( fnOppEdgeToPos ) ).fn(
prop2val.right, takeWidth, takeParentWidth );
prop2val.right = undefined;
}
if ( prop2val.centerY !== undefined ) {
if ( prop2val.centerY === 0 ) { //optimization
prop2val.top = takeZeroCenterY;
} else {
prop2val.top = ( new LAY.Take( fnCenterToPos ) ).fn(
prop2val.centerY, takeHeight, takeParentHeight );
}
prop2val.centerY = undefined;
}
if ( prop2val.bottom !== undefined ) {
prop2val.top = ( new LAY.Take( fnOppEdgeToPos ) ).fn(
prop2val.bottom, takeHeight, takeParentHeight );
prop2val.bottom = undefined;
}
for ( prop in prop2val ) {
flattenProp( prop2val, prop2val, prop, prop );
}
for ( prop in prop2val ) {
longhandPropS = LAY.$shorthandPropsUtils.getLonghandPropsDecenteralized( prop );
if ( longhandPropS !== undefined ) {
shorthandVal = prop2val[ prop ];
for ( i = 0, len = longhandPropS.length; i < len; i++ ) {
longhandProp = longhandPropS[ i ];
prop2val[ longhandProp ] = prop2val[ longhandProp ] ||
shorthandVal;
}
}
}
for ( prop in prop2val ) {
if ( prop.lastIndexOf("Color") !== -1 ) {
if ( typeof prop2val[ prop ] === "string" ) {
throw "LAY Error: '" + prop + "' must be LAY.color()/LAY.rgb()/LAY.rgba()/LAY.hsl()/LAY.hsla()";
}
}
multipleTypePropMatchDetails =
LAY.$findMultipleTypePropMatchDetails( prop );
if ( multipleTypePropMatchDetails !== null ) {
curMultipleMax =
LAY.$meta.get( lson, "max", multipleTypePropMatchDetails[ 1 ] );
if ( ( curMultipleMax === undefined ) ||
( curMultipleMax < parseInt( multipleTypePropMatchDetails[ 2 ] ) ) ) {
LAY.$meta.set( lson, "max", multipleTypePropMatchDetails[ 1 ],
parseInt( multipleTypePropMatchDetails[ 2 ] ) );
}
}
}
},
when: function ( lson ) {
if ( lson.when === undefined ) {
lson.when = {};
} else {
checkAndThrowErrorAttrAsTake( "when", lson.when );
var eventType2_fnCallbackS_ = lson.when,
eventType, fnCallbackS, i, len;
for ( eventType in eventType2_fnCallbackS_ ) {
fnCallbackS = eventType2_fnCallbackS_[ eventType ];
//console.log(eventType2_fnCallbackS_[ eventType ]);
if ( ! ( fnCallbackS instanceof Array ) ) {
fnCallbackS =
eventType2_fnCallbackS_[ eventType ] =
[ fnCallbackS ];
}
checkAndThrowErrorAttrAsTake( "when." + eventType,
fnCallbackS );
//LAY.$meta.set( lson, "num", "when." + eventType, fnCallbackS.length );
}
}
},
transition: function( lson ) {
if ( lson.transition === undefined ) {
lson.transition = {};
} else {
var transitionProp, transitionDirective,
transitionArgKey2val, transitionArgKey, transitionArgKeyS,
transition = lson.transition,
defaulterProp, defaultedPropS, defaultedProp, i, len;
if ( transition !== undefined ) {
checkAndThrowErrorAttrAsTake( "transition", lson.transition );
if ( transition.centerX !== undefined ) {
transition.left = transition.centerX;
}
if ( transition.right !== undefined ) {
transition.left = transition.right;
}
if ( transition.centerY !== undefined ) {
transition.top = transition.centerY;
}
if ( transition.bottom !== undefined ) {
transition.top = transition.bottom;
}
for ( transitionProp in transition ) {
if ( LAY.$checkIsValidUtils.checkIsPropAttrExpandable( transitionProp ) ) {
throw ( "LAY Error: transitions for special/expander props such as '" + name + "' are not permitted." );
}
transitionDirective = transition[ transitionProp ];
checkAndThrowErrorAttrAsTake( "transition." + transitionProp,
transitionDirective );
transitionArgKey2val = transitionDirective.args;
if ( transitionArgKey2val !== undefined ) {
checkAndThrowErrorAttrAsTake( "transition." + transitionProp + ".args",
transitionArgKey2val );
}
}
}
}
},
states: function( lson, isMany ) {
if ( lson.states !== undefined ) {
var stateName2state = lson.states, state;
checkAndThrowErrorAttrAsTake( "states", stateName2state );
for ( var stateName in stateName2state ) {
if ( !LAY.$checkIsValidUtils.stateName( stateName ) ) {
throw ( "LAY Error: Invalid state name: " + stateName );
}
state = stateName2state[ stateName ];
checkAndThrowErrorAttrAsTake( "states." + stateName, state );
if ( !isMany ) {
key2fnNormalize.props( state );
key2fnNormalize.when( state );
key2fnNormalize.transition( state );
} else {
key2fnNormalize.fargs( state );
key2fnNormalize.sort( state );
}
}
}
},
children: function( lson ) {
if ( lson.children !== undefined ) {
var childName2childLson = lson.children;
checkAndThrowErrorAttrAsTake( "children", childName2childLson );
for ( var childName in childName2childLson ) {
normalize( childName2childLson[ childName ], true );
}
}
},
many: function ( lson ) {
if ( lson.many !== undefined ) {
var many = lson.many;
checkAndThrowErrorAttrAsTake( "many", many );
if ( !many.states ) {
many.states = {};
}
many.states.root = {
formation: many.formation,
sort: many.sort,
filter: many.filter,
fargs: many.fargs
};
many.formation = undefined;
many.sort = undefined;
many.filter = undefined;
many.fargs = undefined;
key2fnNormalize.states( many, true );
}
},
// formation args (Many)
fargs: function ( lson ) {
if ( lson.fargs ) {
var
fargs = lson.fargs,
formationArg;
checkAndThrowErrorAttrAsTake( "fargs", fargs );
for ( formationArg in fargs ) {
checkAndThrowErrorAttrAsTake( "fargs." + formationArg,
fargs[ formationArg ] );
}
}
},
sort: function ( lson ) {
if ( lson.sort ) {
var
sortS = lson.sort,
i, len;
checkAndThrowErrorAttrAsTake( "sort", sortS );
for ( i = 0, len = sortS.length; i < len; i++ ) {
checkAndThrowErrorAttrAsTake( "sort." + i,
sortS[ i ] );
if ( sortS[ i ].ascending === undefined ) {
sortS[ i ].ascending = true;
}
}
}
}
};
}());
( function () {
"use strict";
// source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
if ( Function.prototype.bind === undefined ) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis ?
this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
})();
(function () {
"use strict";
// Non console API compliant browsers will not throw an error
if ( window.console === undefined ) {
window.console = { error: function () {}, log: function () {}, info: function () {} };
}
})();
(function(){
"use strict";
/* Modified source of: <NAME>'s https://gist.github.com/paulirish/5438650
And https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
*/
if ( window.performance === undefined ) {
window.performance = {};
}
if ( window.performance.now === undefined ) {
if ( Date.now === undefined ) {
Date.now = function now() {
return new Date().getTime();
};
}
var nowOffset = Date.now();
if ( performance.timing !== undefined && performance.timing.navigationStart !== undefined ) {
nowOffset = performance.timing.navigationStart;
}
window.performance.now = function now() {
return Date.now() - nowOffset;
};
}
})();
/*
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
requestAnimationFrame polyfill by <NAME>. fixes from <NAME> and <NAME>
MIT license*/
(function() {
"use strict";
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] ||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
(function () {
"use strict";
if ( String.prototype.startWith === undefined ) {
String.prototype.startsWith = function ( prefix ) {
return this.indexOf(prefix) === 0;
}
}
})();
( function () {
"use strict";
/*
* Optional argument of `timeNow`
* which represent the previous time frame
*/
LAY.$render = function ( timeNow ) {
if ( ( ( LAY.$renderDirtyPartS.length !== 0 ) ||
LAY.isDataTravelling
) ) {
if ( timeNow ) {
LAY.$prevTimeFrame = timeNow;
window.requestAnimationFrame( render );
} else {
LAY.$prevTimeFrame = performance.now() - 16.7;
render();
}
}
}
function render() {
var
curTimeFrame = performance.now(),
timeFrameDiff = curTimeFrame - LAY.$prevTimeFrame,
parentNode,
x, y,
i, len,
isDataTravelling = LAY.$isDataTravelling,
dataTravellingDelta = LAY.$dataTravelDelta,
renderDirtyPartS = LAY.$renderDirtyPartS,
renderDirtyPart,
travelRenderDirtyAttrValS,
travelRenderDirtyAttrVal,
normalRenderDirtyAttrValS,
normalRenderDirtyAttrVal,
renderDirtyTransition,
renderCallS, isNormalAttrValTransitionComplete,
renderNewLevelS = [],
renderNewLevel,
fnLoad,
isAllNormalTransitionComplete = true;
LAY.$isRendering = true;
for ( x = 0; x < renderDirtyPartS.length; x++ ) {
renderDirtyPart = renderDirtyPartS[ x ];
travelRenderDirtyAttrValS = renderDirtyPart.travelRenderDirtyAttrValS;
normalRenderDirtyAttrValS = renderDirtyPart.normalRenderDirtyAttrValS;
renderCallS = [];
for ( y = 0; y < travelRenderDirtyAttrValS.length; y++ ) {
travelRenderDirtyAttrVal = travelRenderDirtyAttrValS[ y ];
if ( travelRenderDirtyAttrVal.isTransitionable ) {
transitionAttrVal( travelRenderDirtyAttrVal, dataTravellingDelta );
LAY.$arrayUtils.pushUnique(
renderCallS, travelRenderDirtyAttrVal.renderCall );
}
}
for ( y = 0; y < normalRenderDirtyAttrValS.length; y++ ) {
normalRenderDirtyAttrVal = normalRenderDirtyAttrValS[ y ];
isNormalAttrValTransitionComplete = true;
if ( normalRenderDirtyAttrVal.calcVal !== undefined ) {
LAY.$arrayUtils.pushUnique( renderCallS,
normalRenderDirtyAttrVal.renderCall );
}
renderDirtyTransition = normalRenderDirtyAttrVal.transition;
if ( renderDirtyTransition !== undefined ) { // if transitioning
if ( renderDirtyTransition.delay &&
renderDirtyTransition.delay > 0 ) {
renderDirtyTransition.delay -= timeFrameDiff;
isNormalAttrValTransitionComplete = false;
} else {
if ( !renderDirtyTransition.checkIsComplete() ) {
isAllNormalTransitionComplete = false;
isNormalAttrValTransitionComplete = false;
transitionAttrVal( normalRenderDirtyAttrVal,
renderDirtyTransition.generateNext( timeFrameDiff ) );
} else {
if ( renderDirtyTransition.done !== undefined ) {
renderDirtyTransition.done.call( renderDirtyPart.level );
}
normalRenderDirtyAttrVal.transition = undefined;
}
}
}
if ( isNormalAttrValTransitionComplete ) {
normalRenderDirtyAttrVal.transCalcVal =
normalRenderDirtyAttrVal.calcVal;
LAY.$arrayUtils.removeAtIndex( normalRenderDirtyAttrValS, y );
y--;
}
}
// scroll positions must be affected last
// as a dimensional update would require
// scroll to be updated after
if ( LAY.$arrayUtils.remove( renderCallS, "scrollX" ) ) {
renderCallS.push( "scrollX" );
}
if ( LAY.$arrayUtils.remove( renderCallS, "scrollY" ) ) {
renderCallS.push( "scrollY" );
}
for ( i = 0, len = renderCallS.length; i < len; i++ ) {
renderDirtyPart.render( renderCallS[ i ] );
}
if (
( normalRenderDirtyAttrValS.length === 0 ) &&
( travelRenderDirtyAttrValS.length === 0 ) ) {
LAY.$arrayUtils.removeAtIndex( LAY.$renderDirtyPartS, x );
x--;
}
if ( !renderDirtyPart.isInitiallyRendered &&
LAY.$renderDirtyPartS.indexOf( renderDirtyPart ) === -1 ) {
LAY.$arrayUtils.pushUnique( renderNewLevelS,
renderDirtyPart.level );
}
}
for ( i = 0, len = renderNewLevelS.length; i < len; i++ ) {
renderNewLevel = renderNewLevelS[ i ];
renderNewLevel.part.isInitiallyRendered = true;
fnLoad = renderNewLevel.lson.$load;
if ( fnLoad ) {
fnLoad.call( renderNewLevel );
}
}
LAY.$isRendering = false;
if ( LAY.$isSolveRequiredOnRenderFinish ) {
LAY.$isSolveRequiredOnRenderFinish = false;
LAY.$solve();
} else if ( !isAllNormalTransitionComplete ) {
LAY.$render( curTimeFrame );
}
}
function transitionAttrVal( normalRenderDirtyAttrVal, delta ) {
if ( normalRenderDirtyAttrVal.calcVal instanceof LAY.Color ) {
normalRenderDirtyAttrVal.transCalcVal =
LAY.$generateColorMix( normalRenderDirtyAttrVal.startCalcVal,
normalRenderDirtyAttrVal.calcVal,
delta );
} else {
normalRenderDirtyAttrVal.transCalcVal =
normalRenderDirtyAttrVal.startCalcVal +
( delta *
( normalRenderDirtyAttrVal.calcVal -
normalRenderDirtyAttrVal.startCalcVal )
);
}
}
})();
( function () {
"use strict";
var
shorthandProp2_longhandPropS_,
longhandPropS,
centeralizedShorthandPropS;
shorthandProp2_longhandPropS_ = {
transform:[
"z",
"scaleX", "scaleY", "scaleZ",
"rotateX", "rotateY", "rotateZ",
"skewX", "skewY"
],
x: [ "left", "shiftX"],
y: [ "top", "shiftY"],
origin: ["originX", "originY", "originZ" ],
overflow: [
"overflowX", "overflowY" ],
backgroundPosition: [
"backgroundPositionX", "backgroundPositionY" ],
backgroundSize: [
"backgroundSizeX", "backgroundSizeY" ],
borderWidth: [
"borderTopWidth", "borderRightWidth",
"borderBottomWidth", "borderLeftWidth" ],
borderColor: [
"borderTopColor", "borderRightColor",
"borderBottomColor", "borderLeftColor" ],
borderStyle: [
"borderTopStyle", "borderRightStyle",
"borderBottomStyle", "borderLeftStyle" ],
textPadding: [
"textPaddingTop", "textPaddingRight",
"textPaddingBottom", "textPaddingLeft" ],
cornerRadius: [
"cornerRadiusTopLeft", "cornerRadiusTopRight",
"cornerRadiusBottomRight", "cornerRadiusBottomLeft" ]
};
// Centralized shorthand props are those props which
// have same render calls (almost akin to css properties)
// for each shorthand property
centeralizedShorthandPropS = [
"transform", "x", "y", "origin",
"backgroundPosition", "backgroundSize"
];
longhandPropS = ( function () {
var
longhandPropS = [],
shorthandProp,
i, len;
for ( shorthandProp in shorthandProp2_longhandPropS_ ) {
longhandPropS = longhandPropS.concat( shorthandProp2_longhandPropS_[ shorthandProp ] );
}
return longhandPropS;
})();
LAY.$shorthandPropsUtils = {
getLonghandProps: function ( shorthandProp ) {
return shorthandProp2_longhandPropS_[ shorthandProp ];
},
getLonghandPropsDecenteralized: function ( shorthandProp ) {
if ( centeralizedShorthandPropS.indexOf( shorthandProp ) === -1 ) {
return shorthandProp2_longhandPropS_[ shorthandProp ];
} else {
return undefined;
}
},
getShorthandProp: function ( longhandProp ) {
var shorthandProp;
if ( longhandPropS.indexOf( longhandProp ) !== -1 ) {
for ( shorthandProp in shorthandProp2_longhandPropS_ ) {
if ( shorthandProp2_longhandPropS_[ shorthandProp ].indexOf( longhandProp ) !== -1 ) {
return shorthandProp;
}
}
}
return undefined;
},
getShorthandPropCenteralized: function ( longhandProp ) {
var shorthandProp = LAY.$shorthandPropsUtils.getShorthandProp( longhandProp );
if ( shorthandProp !== undefined && centeralizedShorthandPropS.indexOf( shorthandProp ) !== -1 ) {
return shorthandProp;
} else {
return undefined;
}
},
checkIsDecentralizedShorthandProp: function ( shorthandProp ) {
return shorthandProp2_longhandPropS_[ shorthandProp ] !== undefined &&
centeralizedShorthandPropS.indexOf( shorthandProp ) === -1;
}
};
})();
( function () {
"use strict";
LAY.$solve = function () {
if ( LAY.$isRendering ) {
LAY.$isSolveRequiredOnRenderFinish = true;
} else if ( !LAY.$isSolving && LAY.$numClog === 0 ) {
var
ret,
isSolveNewComplete,
isSolveRecalculationComplete,
isSolveProgressed,
isSolveHaltedForOneLoop = false;
LAY.$isSolving = true;
do {
isSolveProgressed = false;
isSolveNewComplete = false;
isSolveRecalculationComplete = false;
ret = LAY.$solveForNew();
if ( ret < 2 ) {
isSolveProgressed = true;
}
ret = LAY.$solveForRecalculation();
if ( ret < 2 ) {
isSolveProgressed = true;
}
// The reason we cannot use `ret` to confirm
// completion and not `ret` is because during solving
// for recalculation new levels could have been
// added ((from many.rows), and during execution
// of state installation new recalculations or
// levels could have been created
isSolveRecalculationComplete =
LAY.$recalculateDirtyAttrValS.length === 0;
isSolveNewComplete =
LAY.$newLevelS.length === 0;
if ( !isSolveProgressed ) {
if ( isSolveHaltedForOneLoop ) {
break;
} else {
isSolveHaltedForOneLoop = true;
}
} else {
isSolveHaltedForOneLoop = false;
}
} while ( !( isSolveNewComplete && isSolveRecalculationComplete ) );
if ( !( isSolveNewComplete && isSolveRecalculationComplete ) ) {
var msg = "LAY Error: Circular/Undefined Reference Encountered [";
if ( !isSolveNewComplete ) {
msg += "Uninheritable Level: " + LAY.$newLevelS[ 0 ].pathName;
} else {
var circularAttrVal = LAY.$recalculateDirtyAttrValS[ 0 ];
msg += "Uninstantiable Attr: " +
circularAttrVal.attr +
" (Level: " + circularAttrVal.level.pathName + ")";
}
msg += "]";
throw msg;
}
relayout();
recalculateNaturalDimensions();
executeManyLoads();
executeStateInstallation();
// If the load/install functions of
// many or level demands a recalculation
// then we will solve, otherwise we shall
// render
LAY.$isSolving = false;
if ( LAY.$recalculateDirtyAttrValS.length ) {
LAY.$solve();
} else {
LAY.$render();
}
}
};
function relayout() {
var relayoutDirtyManyS = LAY.$relayoutDirtyManyS;
for ( var i=0, len=relayoutDirtyManyS.length; i<len; i++ ) {
relayoutDirtyManyS[ i ].relayout();
}
LAY.$relayoutDirtyManyS = [];
};
function recalculateNaturalDimensions () {
var
naturalWidthDirtyPartS =
LAY.$naturalWidthDirtyPartS,
naturalHeightDirtyPartS =
LAY.$naturalHeightDirtyPartS,
i, len, attrVal;
// calculate natural width first
// as knowing natural width is useful
// while calculating natural height
for ( i=naturalWidthDirtyPartS.length - 1;
i >= 0; i-- ) {
attrVal =
naturalWidthDirtyPartS[ i ].level.attr2attrVal.$naturalWidth;
if ( attrVal ) {
attrVal.requestRecalculation();
}
}
for ( i=naturalHeightDirtyPartS.length - 1;
i >= 0; i-- ) {
attrVal =
naturalHeightDirtyPartS[ i ].level.attr2attrVal.$naturalHeight;
if ( attrVal ) {
attrVal.requestRecalculation();
}
}
LAY.$naturalWidthDirtyPartS = [];
LAY.$naturalHeightDirtyPartS = [];
}
function executeManyLoads () {
var newManyS = LAY.$newManyS, newMany, fnLoad;
for ( var i = 0, len = newManyS.length; i < len; i++ ) {
newMany = newManyS[ i ];
newMany.isLoaded = true;
fnLoad = newMany.level.lson.$load;
if ( fnLoad ) {
fnLoad.call( newMany.level );
}
}
LAY.$newManyS = [];
}
function executeStateInstallation () {
var
i, j, len, jLen,
newlyInstalledStateLevelS = LAY.$newlyInstalledStateLevelS,
newlyInstalledStateLevel,
newlyInstalledStateS,
attrValNewlyInstalledStateInstall,
newlyUninstalledStateLevelS = LAY.$newlyUninstalledStateLevelS,
newlyUninstalledStateLevel,
newlyUninstalledStateS,
attrValNewlyUninstalledStateUninstall;
for ( i = 0, len = newlyInstalledStateLevelS.length; i < len; i++ ) {
newlyInstalledStateLevel = newlyInstalledStateLevelS[ i ];
newlyInstalledStateS = newlyInstalledStateLevel.newlyInstalledStateS;
for ( j = 0, jLen = newlyInstalledStateS.length; j < jLen; j++ ) {
attrValNewlyInstalledStateInstall =
newlyInstalledStateLevel.attr2attrVal[ newlyInstalledStateS[ j ] +
".install" ];
attrValNewlyInstalledStateInstall &&
( LAY.$type(attrValNewlyInstalledStateInstall.calcVal ) ===
"function") &&
attrValNewlyInstalledStateInstall.calcVal.call(
newlyInstalledStateLevel );
}
// empty the list
newlyInstalledStateLevel.newlyInstalledStateS = [];
}
LAY.$newlyInstalledStateLevelS = [];
for ( i = 0, len = newlyUninstalledStateLevelS.length; i < len; i++ ) {
newlyUninstalledStateLevel = newlyUninstalledStateLevelS[ i ];
newlyUninstalledStateS = newlyUninstalledStateLevel.newlyUninstalledStateS;
for ( j = 0, jLen = newlyUninstalledStateS.length; j < jLen; j++ ) {
attrValNewlyUninstalledStateUninstall =
newlyUninstalledStateLevel.attr2attrVal[ newlyUninstalledStateS[ j ] +
".uninstall" ];
attrValNewlyUninstalledStateUninstall &&
( LAY.$type( attrValNewlyUninstalledStateUninstall.calcVal) ===
"function") &&
attrValNewlyUninstalledStateUninstall.calcVal.call(
newlyUninstalledStateLevel );
}
// empty the list
newlyUninstalledStateLevel.newlyUninstalledStateS = [];
}
LAY.$newlyUninstalledStateLevelS = [];
}
})();
( function () {
"use strict";
LAY.$solveForNew = function () {
var
i, len,
isSolveProgressed,
isSolveProgressedOnce = false,
newLevelS = LAY.$newLevelS,
newLevel,
solvedLevelS = [];
if ( !newLevelS.length ) {
return 3;
}
do {
isSolveProgressed = false;
for ( i = 0; i < newLevelS.length; i++ ) {
newLevel = newLevelS[ i ];
if ( newLevel.$normalizeAndInherit() ) {
newLevel.$identify();
isSolveProgressed = true;
isSolveProgressedOnce = true;
solvedLevelS.push( newLevel );
LAY.$arrayUtils.removeAtIndex( newLevelS, i );
i--;
}
}
} while ( ( newLevelS.length !== 0 ) && isSolveProgressed );
for ( i = 0, len = solvedLevelS.length; i < len; i++ ) {
solvedLevelS[ i ].$decideExistence();
}
return newLevelS.length === 0 ? 0 :
isSolveProgressedOnce ? 1 : 2;
}
})();
( function () {
"use strict";
LAY.$solveForRecalculation = function () {
var
i,
isSolveProgressed,
isSolveProgressedOnce = false,
ret,
recalculateDirtyAttrValS = LAY.$recalculateDirtyAttrValS;
if ( !recalculateDirtyAttrValS.length ) {
return 3;
}
do {
isSolveProgressed = false;
for ( i = 0; i < recalculateDirtyAttrValS.length; i++ ) {
ret =
recalculateDirtyAttrValS[ i ].recalculate();
if ( ret ) {
isSolveProgressed = true;
isSolveProgressedOnce = true;
LAY.$arrayUtils.removeAtIndex( recalculateDirtyAttrValS, i );
i--;
}
}
} while ( ( recalculateDirtyAttrValS.length !== 0 ) && isSolveProgressed );
return recalculateDirtyAttrValS.length === 0 ? 0 :
isSolveProgressedOnce ? 1 : 2;
};
})();
// source of spring code insprired from below:
// facebook pop framework & framer.js
( function() {
"use strict";
LAY.$springTransition = function( duration, args ) {
this.curTime = 0;
this.value = 0;
this.friction = parseFloat( args.friction );
this.tension = parseFloat( args.tension );
this.velocity = parseFloat( args.velocity || 0 );
this.threshold = parseFloat( args.threshold || ( 1 / 1000 ) );
this.isComplete = false;
};
LAY.$springTransition.prototype.generateNext = function ( delta ) {
var
finalVelocity, net1DVelocity, netFloat,
netValueIsLow, netVelocityIsLow, stateAfter, stateBefore;
delta = delta / 1000;
this.curTime += delta;
stateBefore = {};
stateAfter = {};
stateBefore.x = this.value - 1;
stateBefore.v = this.velocity;
stateBefore.tension = this.tension;
stateBefore.friction = this.friction;
stateAfter = springIntegrateState( stateBefore, delta );
this.value = 1 + stateAfter.x;
finalVelocity = stateAfter.v;
netFloat = stateAfter.x;
net1DVelocity = stateAfter.v;
netValueIsLow = Math.abs( netFloat ) < this.threshold;
netVelocityIsLow = Math.abs( net1DVelocity ) < this.threshold;
this.isComplete = netValueIsLow && netVelocityIsLow;
this.velocity = finalVelocity;
return this.value;
};
LAY.$springTransition.prototype.checkIsComplete = function() {
return this.isComplete;
};
function springAccelerationForState ( state ) {
return ( - state.tension * state.x ) - ( state.friction * state.v );
};
function springEvaluateState ( initialState ) {
var output;
output = {};
output.dx = initialState.v;
output.dv = springAccelerationForState( initialState );
return output;
};
function springEvaluateStateWithDerivative( initialState, dt, derivative ) {
var output, state;
state = {};
state.x = initialState.x + derivative.dx * dt;
state.v = initialState.v + derivative.dv * dt;
state.tension = initialState.tension;
state.friction = initialState.friction;
output = {};
output.dx = state.v;
output.dv = springAccelerationForState(state);
return output;
};
function springIntegrateState ( state, speed ) {
var a, b, c, d, dvdt, dxdt;
a = springEvaluateState(state);
b = springEvaluateStateWithDerivative(state, speed * 0.5, a);
c = springEvaluateStateWithDerivative(state, speed * 0.5, b);
d = springEvaluateStateWithDerivative(state, speed, c);
dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx);
dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
state.x = state.x + dxdt * speed;
state.v = state.v + dvdt * speed;
return state;
}
})();
( function () {
"use strict";
LAY.$transitionType2args = {
"linear": [],
"cubic-bezier": [ "a", "b", "c", "d" ],
"spring": [ "velocity", "tension", "friction", "threshold" ]
};
})();
(function () {
"use strict";
// source: jquery-2.1.1.js (line 302, 529)
var typeIdentifier2_type_ = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object',
'[object Error]': 'error'
};
LAY.$type = function( obj ) {
if ( obj === null ) {
return obj + "";
} else if ( obj instanceof LAY.Color ) {
return "color";
} else if ( obj instanceof LAY.Take ) {
return "take";
} else if ( obj instanceof LAY.Level ) {
return "level";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
typeIdentifier2_type_[ Object.prototype.toString.call(obj) ] || "object" :
typeof obj;
};
})();
<file_sep>/progress.markdown
Current:
- todo recursive remove level
- sort problem when update .row()
- change "*" to many
- width default complete (with spec update)
- formationX/Y undefined then skip setting it? new thing = null?
- $id attrVal undefined
- video height auto
- invesitagte width (recalc) undefined in switch-case
- defaultize many lson fargs which are mentioned in states but not otherwise
- what is "$hovering" or any of the event binding events
is called from attr() after having themselves deferenced
then what happens?
- < state >.bottom/right/centerX/centerY
- function to get all partLevelS from many?
- checkIsValidUtils.isExpanderAttr() <- make similar to prevent takes of "$type", "$inherit", "$observe"
- checkAndThrowErrorAttrAsTake
- LAY.Many.remove()
- transition multiple props comma separated, eg: "textColor, left, opacity"
- website
spec:
- Many.rowsUpdate()
- many.rows can take array of non-objects
- Add "$i" index for Many to spec
- formation spec (include part for creating formations)
- add LAY.level.changeNativeInput/ScrollX/Y() to spec
- update spec to have quotes around state names
- filter.finish() ?
- queryAll, queryFiltered
Future:
- investigate "-text-size-adjust"
- grid formation fill vertically, vgrid?
- LAY.Take.percent()
- input:file
- fix bug of rows containing duplicate objects
- objectEqual(a, b, m) [remove 3rd arg m]
- check for illegal characters id row.id val
- take.colorRed -> take.colorSetRed? or take.colorGetRed? (clarify)
- video controls $readonly (eg: $videoMuted)
- IE ms-filter
- IE7 text width issue
- optimize by putting "right" and "bottom" at end (or atleast after left, top, width, and height) of recalculate attr list
- < img > srcset
- LAY.transparent() -> LAY.transparent ?
- selective inheritance where part of lson is inherited
eg: ($inherit: [{level:"../Button", keys: ["props", "when"]}] )
- CSS pointer-events optimization
- CSS will-change optimization
- HTML5 aria
- natural width and height dependent upon the rotation of Z axis of children.
- move `eventReadonlyEventType2boundFnHandler` outside of AttrVal (move to Level) to save space
- Add $time as a read only property of root '/'
- $numberOfChildren, $numberOfDisplayedChildren
- Add support for other HTML5 input types
- 'when' for formation, it should include function handler for insertion of new item into the formation alongwith deletion.
- LAY.Color mix
Complain:
- poor scrolling GPU performance: http://indiegamr.com/ios-html5-performance-issues-with-overflow-scrolling-touch-and-hardware-acceleration/
- "-moz-user-select" unactivated from JS
<file_sep>/src/helper/polyfillStartsWith.js
(function () {
"use strict";
if ( String.prototype.startWith === undefined ) {
String.prototype.startsWith = function ( prefix ) {
return this.indexOf(prefix) === 0;
}
}
})();
<file_sep>/src/obj/Level.js
( function () {
"use strict";
LAY.Level = function ( path, lson, parent, isHelper, derivedMany, rowDict, id ) {
this.pathName = path;
this.lson = lson;
// if level is many, partLson contains the non-many part of the lson
this.partLson = undefined;
this.isGpu = undefined;
this.isInitialized = false;
this.parentLevel = parent; // parent Level
this.attr2attrVal = {};
// True if the Level is a Part Level,
// false if the Level is a Many Level.
this.isPart = undefined;
// If the level name begins with "_",
// the level is considered a helper (non-renderable)
this.isHelper = isHelper;
this.isExist = true;
// If the Level is a Many (i.e this.isPart is false)
// then this.many will hold a reference to the corresponding
// Many object.
this.part = undefined;
// If the Level is a Many (i.e this.isPart is false)
// then this.many will hold a reference to the corresponding
// Many object.
this.manyObj = undefined;
// If the Level is derived from a Many
// then this.derivedMany will hold
// a reference to the Many
this.derivedMany = derivedMany;
// If the Level is derived from a Many Level
// this will be the id by which it is referenced
this.id = id;
// If the Level is derived from a Many Level
// this will contain the row information will
// be contained within below
this.rowDict = rowDict;
this.isInherited = false;
this.childLevelS = [];
this.stateS = [ "root" ];
this.stringHashedStates2_cachedAttr2val_ = {};
this.newlyInstalledStateS = [];
this.newlyUninstalledStateS = [];
};
LAY.Level.prototype.$init = function () {
LAY.$pathName2level[ this.pathName ] = this;
LAY.$newLevelS.push( this );
if ( this.parentLevel ) {
this.parentLevel.childLevelS.push( this );
}
};
LAY.Level.prototype.level = function ( relativePath ) {
return ( new LAY.RelPath( relativePath ) ).resolve( this );
};
LAY.Level.prototype.parent = function () {
return this.parentLevel;
};
LAY.Level.prototype.children = function () {
return this.childLevelS;
};
LAY.Level.prototype.path = function () {
return this.pathName;
};
LAY.Level.prototype.node = function () {
return this.isPart && this.part.node;
};
LAY.Level.prototype.attr = function ( attr ) {
if ( this.attr2attrVal[ attr ] ) {
return this.attr2attrVal[ attr ].calcVal;
} else {
// Check if it is a doing event
if ( attr.charAt( 0 ) === "$" ) {
if ( LAY.$checkIfDoingReadonly( attr ) ) {
console.error("LAY Error: " + attr + " must be placed in $obdurate");
return undefined;
} else if ( LAY.$checkIfImmidiateReadonly( attr ) ) {
return this.part.getImmidiateReadonlyVal( attr );
}
}
if ( this.$createLazyAttr( attr, true ) ) {
var attrVal = this.attr2attrVal[ attr ];
attrVal.give( LAY.$emptyAttrVal );
LAY.$solve();
return attrVal.calcVal;
} else {
return undefined;
}
}
};
LAY.Level.prototype.data = function ( dataKey, value ) {
this.$changeAttrVal( "data." + dataKey, value );
LAY.$solve();
};
LAY.Level.prototype.row = function ( rowKey, value ) {
if ( this.derivedMany ) {
this.derivedMany.id2row[ this.id ][ rowKey ] = value;
this.derivedMany.level.attr2attrVal.rows.requestRecalculation();
LAY.$solve();
}
};
LAY.Level.prototype.changeNativeInput = function ( value ) {
this.part.node.value = value;
};
LAY.Level.prototype.changeNativeScrollX = function ( value ) {
this.part.node.scrollLeft = value;
};
LAY.Level.prototype.changeNativeScrollY = function ( value ) {
this.part.node.scrollTop = value;
};
LAY.Level.prototype.many = function () {
return this.derivedMany && this.derivedMany.level;
};
LAY.Level.prototype.levels = function () {
return this.manyObj && this.manyObj.allLevelS;
};
LAY.Level.prototype.rowsCommit = function ( newRowS ) {
if ( !this.isPart ) {
this.manyObj.rowsCommit( newRowS );
}
};
LAY.Level.prototype.rowsMore = function ( newRowS ) {
if ( !this.isPart ) {
this.manyObj.rowsMore( newRowS );
}
};
LAY.Level.prototype.rowAdd = function ( newRow ) {
this.rowsMore( [ newRow ] );
};
LAY.Level.prototype.rowDeleteByID = function ( id ) {
if ( !this.isPart ) {
this.manyObj.rowDeleteByID( id );
}
};
LAY.Level.prototype.rowsUpdate = function ( key, val, queryRowS ) {
if ( !this.isPart ) {
if ( queryRowS instanceof LAY.Query ) {
queryRowS = queryRowS.rowS;
}
this.manyObj.rowsUpdate( key, val, queryRowS );
}
};
LAY.Level.prototype.rowsDelete = function ( queryRowS ) {
if ( !this.isPart ) {
if ( queryRowS instanceof LAY.Query ) {
queryRowS = queryRowS.rowS;
}
this.manyObj.rowsDelete( queryRowS );
}
};
LAY.Level.prototype.dataTravelBegin = function ( dataKey, finalVal ) {
var attrVal;
if ( LAY.$isDataTravelling ) {
console.error("LAY Warning: Existence of another unfinished data travel");
} else {
attrVal = this.attr2attrVal[ "data." + dataKey ];
if ( attrVal === undefined ) {
console.error ("LAY Warning: Inexistence of data key for data travel");
}
LAY.$isDataTravelling = true;
LAY.level("/").attr2attrVal.$dataTravelling.update( true );
LAY.$dataTravellingLevel = this;
LAY.level("/").attr2attrVal.$dataTravelLevel.update( this );
LAY.$dataTravellingAttrInitialVal = attrVal.val;
LAY.$dataTravellingAttrVal = attrVal;
LAY.$isDataTravellingShock = true;
attrVal.update( finalVal );
LAY.$solve();
LAY.$isDataTravellingShock = false;
}
};
LAY.Level.prototype.dataTravelContinue = function ( delta ) {
if ( !LAY.$isDataTravelling ) {
console.error( "LAY Warning: Inexistence of a data travel" );
} else if ( this !== LAY.$dataTravellingLevel ){
console.error( "LAY Warning: Inexistence of a data travel for this Level" );
} else {
if ( LAY.$dataTravelDelta !== delta ) {
LAY.$dataTravelDelta = delta;
LAY.level("/").attr2attrVal.$dataTravelDelta.update( delta );
LAY.$render();
}
}
};
LAY.Level.prototype.dataTravelArrive = function ( isArrived ) {
if ( !LAY.$isDataTravelling ) {
console.error( "LAY Warning: Inexistence of a data travel" );
} else {
LAY.$isDataTravelling = false;
LAY.level("/").attr2attrVal.$dataTravelling.update( false );
LAY.$dataTravellingLevel = undefined;
LAY.level("/").attr2attrVal.$dataTravelLevel.update( null );
LAY.$dataTravelDelta = 0.0;
LAY.level("/").attr2attrVal.$dataTravelDelta.update( 0.0 );
// clear out attrvalues which are data travelling
LAY.$clearDataTravellingAttrVals();
if ( !isArrived ) {
LAY.$dataTravellingAttrVal.update(
LAY.$dataTravellingAttrInitialVal );
LAY.$solve();
} else {
}
LAY.$render();
}
};
LAY.Level.prototype.queryRows = function () {
if ( !this.isPart ) {
return this.manyObj.queryRows();
}
};
LAY.Level.prototype.queryFilter = function () {
if ( !this.isPart ) {
return this.manyObj.queryFilter();
}
};
LAY.Level.prototype.addChildren = function ( name2lson ) {
for ( var name in name2lson ) {
var lson = name2lson[ lson ];
this.lson.children[ name ] = lson;
this.$addChild( name, name2lson );
}
};
LAY.Level.prototype.remove = function () {
if ( this.pathName === "/" ) {
console.error("LAY Error: Attempt to remove root level '/' prohibited");
} else {
if ( this.derivedMany ) {
this.derivedMany.rowDeleteByID( this.id );
} else {
this.$remove();
LAY.$solve();
}
}
};
LAY.Level.prototype.$remove = function () {
var
childLevelS = this.childLevelS,
attr2attrVal = this.attr2attrVal;
LAY.$pathName2level[ this.pathName ] = undefined;
LAY.$arrayUtils.remove( this.parentLevel.childLevelS, this );
if ( this.isPart ) {
this.part && this.part.remove();
}
for ( var attr in attr2attrVal ) {
attr2attrVal[ attr ].remove();
}
this.$removeDescendants();
};
LAY.Level.prototype.$removeDescendants = function () {
var descendantLevelS = this.isPart ?
this.childLevelS : this.manyObj.allLevelS;
for ( var i=0, len=descendantLevelS.length; i<len; i++ ) {
descendantLevelS[ i ] &&
descendantLevelS[ i ].$remove();
}
};
LAY.Level.prototype.$addChildren = function ( name2lson ) {
if ( name2lson !== undefined ) {
for ( var name in name2lson ) {
this.$addChild( name, name2lson[ name ] );
}
}
};
LAY.Level.prototype.$addChild = function ( name, lson ) {
var childPath, childLevel;
if ( !LAY.$checkIsValidUtils.levelName( name ) ) {
throw ( "LAY Error: Invalid Level Name: " + name );
}
childPath = this.pathName +
( this.pathName === "/" ? "" : "/" ) + name;
if ( LAY.$pathName2level[ childPath ] !== undefined ) {
throw ( "LAY Error: Level already exists with path: " +
childPath + " within Level: " + this.pathName );
}
childLevel = new LAY.Level( childPath,
lson, this, name.charAt(0) === "_" );
childLevel.$init();
};
/*
* Return false if the level could not be inherited (due
* to another level not being present or started as yet)
*/
LAY.Level.prototype.$normalizeAndInherit = function () {
var lson, refS, i, len, ref, level, inheritedAndNormalizedLson;
LAY.$normalize( this.lson, this.isHelper );
// check if it contains anything to inherit from
if ( this.lson.$inherit !== undefined ) {
lson = {};
refS = this.lson.$inherit;
for ( i = 0, len = refS.length; i < len; i++ ) {
ref = refS[ i ];
if ( typeof ref === "string" ) { // pathname reference
if ( ref === this.pathName ) {
return false;
}
level = ( new LAY.RelPath( ref ) ).resolve( this );
if ( ( level === undefined ) || !level.isInherited ) {
return false;
}
}
}
for ( i = 0; i < len; i++ ) {
ref = refS[ i ];
if ( typeof ref === "string" ) { // pathname reference
level = ( new LAY.RelPath( ref ) ).resolve( this );
inheritedAndNormalizedLson = level.lson;
} else { // object reference
LAY.$normalize( ref, true );
inheritedAndNormalizedLson = ref;
}
LAY.$inherit( lson, inheritedAndNormalizedLson );
}
LAY.$inherit( lson, this.lson );
this.lson = lson;
}
this.isInherited = true;
return true;
};
LAY.Level.prototype.$reproduce = function () {
if ( this.isPart ) {
this.part = new LAY.Part( this );
this.part.init();
if ( this.lson.children !== undefined ) {
this.$addChildren( this.lson.children );
}
} else {
this.manyObj = new LAY.Many( this, this.partLson );
this.manyObj.init();
}
};
LAY.Level.prototype.$identify = function () {
this.isPart = this.lson.many === undefined ||
this.derivedMany;
if ( this.pathName === "/" ) {
this.isGpu = this.lson.$gpu === undefined ?
true :
this.lson.$gpu;
} else {
this.isGpu = this.lson.$gpu === undefined ?
this.parentLevel.isGpu :
this.lson.$gpu;
}
this.isGpu = this.isGpu && LAY.$isGpuAccelerated;
if ( this.isPart ) {
if ( !this.derivedMany ) {
LAY.$defaultizePartLson( this.lson,
this.parentLevel );
}
} else {
if ( this.pathName === "/" ) {
throw "LAY Error: 'many' prohibited for root level /";
}
this.partLson = this.lson;
this.lson = this.lson.many;
LAY.$defaultizeManyLson( this.lson );
}
};
function initAttrsObj( attrPrefix, key2val,
attr2val, isNoUndefinedAllowed ) {
var key, val;
for ( key in key2val ) {
if ( ( key2val[ key ] !== undefined ) ||
!isNoUndefinedAllowed ) {
attr2val[ attrPrefix + key ] = key2val[ key ];
}
}
}
function initAttrsArray( attrPrefix, elementS, attr2val ) {
var i, len;
for ( i = 0, len = elementS.length ; i < len; i++ ) {
attr2val[ attrPrefix + "." + ( i + 1 ) ] = elementS[ i ];
}
}
/* Flatten the slson to attr2val dict */
function convertSLSONtoAttr2Val( slson, attr2val, isPart ) {
var
prop,
transitionProp, transitionDirective,
transitionPropPrefix,
eventType, fnCallbackS,
prop2val = slson.props,
when = slson.when,
transition = slson.transition,
fargs = slson.fargs,
i, len;
if ( isPart ){
initAttrsObj( "", slson.props, attr2val, true );
for ( transitionProp in transition ) {
transitionDirective = transition[ transitionProp ];
transitionPropPrefix = "transition." + transitionProp + ".";
if ( transitionDirective.type !== undefined ) {
attr2val[ transitionPropPrefix + "type" ] =
transitionDirective.type;
}
if ( transitionDirective.duration !== undefined ) {
attr2val[ transitionPropPrefix + "duration" ] =
transitionDirective.duration;
}
if ( transitionDirective.delay !== undefined ) {
attr2val[ transitionPropPrefix + "delay" ] =
transitionDirective.delay;
}
if ( transitionDirective.done !== undefined ) {
attr2val[ transitionPropPrefix + "done" ] =
transitionDirective.done;
}
if ( transitionDirective.args !== undefined ) {
initAttrsObj( transitionPropPrefix + "args.",
transitionDirective.args, attr2val, false );
}
}
for ( eventType in when ) {
fnCallbackS = when[ eventType ];
initAttrsArray( "when." + eventType, fnCallbackS, attr2val );
}
if ( slson.$$num !== undefined ) {
initAttrsObj( "$$num.", slson.$$num, attr2val, false );
}
if ( slson.$$max !== undefined ) {
initAttrsObj( "$$max.", slson.$$max, attr2val, false );
}
} else {
attr2val.formation = slson.formation;
attr2val.filter = slson.filter;
if ( fargs ) {
for ( var formationFarg in fargs ) {
initAttrsObj( "fargs." + formationFarg + ".",
fargs[ formationFarg ], attr2val, false );
}
}
attr2val[ "$$num.sort" ] = slson.sort.length;
for ( i = 0, len = slson.sort.length; i < len; i++ ) {
initAttrsObj( "sort." + ( i + 1 ) + ".", slson.sort[ i ],
attr2val, false );
}
}
}
LAY.Level.prototype.$updateExistence = function () {
var isExist = this.attr2attrVal.exist.calcVal;
if ( isExist ) {
this.$appear();
} else {
this.$disappear();
}
};
/*
LAY.Level.prototype.$checkIfParentExists = function () {
if ( this.pathName === "/" ) {
return this.isExist;
} else {
return this.isExist ? this.parentLevel.$checkIfParentExists() : false;
}
};*/
LAY.Level.prototype.$appear = function () {
this.isExist = true;
this.$reproduce();
this.$initAllAttrs();
if ( this.isPart ) {
this.part.add();
}
};
LAY.Level.prototype.$disappear = function () {
console.log(this.pathName);
this.isExist = false;
var attr2attrVal = this.attr2attrVal;
for ( var attr in attr2attrVal ) {
if ( attr !== "exist" ) {
attr2attrVal[ attr ].remove();
}
}
this.$removeDescendants();
if ( this.isPart ) {
this.part && this.part.remove();
}
};
LAY.Level.prototype.$decideExistence = function () {
if ( !this.isHelper ) {
this.$createAttrVal( "exist", this.lson.exist ===
undefined ? true : this.lson.exist );
}
};
LAY.Level.prototype.$initAllAttrs = function () {
var
obdurateReadonlyS = this.lson.$obdurate ?
this.lson.$obdurate : [],
obdurateReadonly, i, len;
this.isInitialized = true;
if ( this.isPart ) {
if ( this.lson.states.root.props.scrollX ) {
obdurateReadonlyS.push( "$naturalWidth" );
}
if ( this.lson.states.root.props.scrollY ) {
obdurateReadonlyS.push( "$naturalHeight" );
}
if ( this.part.type === "input" &&
this.part.inputType !== "line" ) {
// $input will be required to compute
// the natural height if it exists
// TODO: optimize
obdurateReadonlyS.push( "$input" );
}
}
if ( obdurateReadonlyS.length ) {
for ( i = 0, len = obdurateReadonlyS.length; i < len; i++ ) {
obdurateReadonly = obdurateReadonlyS[ i ];
if ( !this.$createLazyAttr( obdurateReadonly ) ) {
throw "LAY Error: Unobervable Attr: '" +
obdurateReadonly + "'";
}
this.attr2attrVal[ obdurateReadonly ].give(
LAY.$emptyAttrVal );
}
}
this.$initNonStateProjectedAttrs();
this.$updateStates();
};
LAY.Level.prototype.$initNonStateProjectedAttrs = function () {
var
key, val, stateName, state,
states = this.lson.states,
lson = this.lson,
attr2val = {};
initAttrsObj( "data.", lson.data, attr2val, false );
for ( stateName in states ) {
state = states[ stateName ];
if ( stateName !== "root" ) {
attr2val[ stateName + "." + "onlyif" ] = state.onlyif;
if ( state.install ) {
attr2val[ stateName + "." + "install" ] = state.install;
}
if ( state.uninstall ) {
attr2val[ stateName + "." + "uninstall" ] = state.uninstall;
}
}
}
if ( this.isPart ) {
attr2val.right = LAY.$essentialPosAttr2take.right;
attr2val.bottom = LAY.$essentialPosAttr2take.bottom;
if ( this.pathName === "/" ) {
attr2val.$dataTravelling = false;
attr2val.$dataTravelDelta = 0.0;
attr2val.$dataTravelLevel = undefined;
attr2val.$absoluteLeft = 0;
attr2val.$absoluteTop = 0;
attr2val.$windowWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
attr2val.$windowHeight = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
} else if ( this.derivedMany ) {
initAttrsObj( "row.", this.rowDict, attr2val, false );
attr2val.$i = 0;
attr2val.$f = 0;
}
} else { // Many
attr2val.rows = lson.rows;
attr2val.$id = lson.$id;
attr2val.$$layout = null;
}
this.$commitAttr2Val( attr2val );
};
LAY.Level.prototype.$commitAttr2Val = function ( attr2val ) {
var attr, val, attrVal;
for ( attr in attr2val ) {
val = attr2val[ attr ];
attrVal = this.attr2attrVal[ attr ];
if ( ( attrVal === undefined ) ) {
attrVal = this.attr2attrVal[ attr ] = new LAY.AttrVal( attr, this );
}
attrVal.update( val );
}
};
LAY.Level.prototype.$createAttrVal = function ( attr, val ) {
( this.attr2attrVal[ attr ] =
new LAY.AttrVal( attr, this ) ).update( val );
};
/*
* Return true if attr was created as it exists (in lazy form),
* false otherwise (it is not present at all to be created)
*/
LAY.Level.prototype.$createLazyAttr = function ( attr, isNoImmidiateReadonly ) {
var
splitAttrLsonComponentS, attrLsonComponentObj, i, len,
firstAttrLsonComponent;
if ( LAY.$miscPosAttr2take[ attr ] ) {
this.$createAttrVal( attr,
LAY.$miscPosAttr2take[ attr ] );
} else if ( attr.charAt( 0 ) === "$" ) { //readonly
if ( [ "$type", "$load", "$id", "$inherit", "$obdurate" ].indexOf(
attr ) !== -1 ) {
this.$createAttrVal( attr, this.lson[ attr ] );
} else if ( attr === "$path" ) {
this.$createAttrVal( "$path", this.pathName );
} else {
if ( !isNoImmidiateReadonly &&
LAY.$checkIfImmidiateReadonly( attr ) ) {
this.$createAttrVal( attr, null );
} else if ( LAY.$checkIfDoingReadonly( attr ) ) {
this.$createAttrVal( attr, false );
} else {
console.error("LAY Error: Incorrectly named readonly: " + attr );
return false;
}
}
} else {
if ( attr.indexOf( "." ) === -1 ) {
var lazyVal = LAY.$getLazyPropVal( attr,
this.parentLevel === undefined );
if ( lazyVal !== undefined ) {
this.$createAttrVal( attr, lazyVal );
} else {
return false;
}
} else {
if ( attr.startsWith( "data." ||
attr.startsWith("row.") ) ) {
return false;
} else {
splitAttrLsonComponentS = attr.split( "." );
if ( this.lson.states === undefined ) {
return false;
} else {
firstAttrLsonComponent = splitAttrLsonComponentS[ 0 ];
// Get down to state level
if ( LAY.$checkIsValidUtils.stateName(
firstAttrLsonComponent ) ) {
attrLsonComponentObj = this.lson.states[ firstAttrLsonComponent ];
} else {
return false;
}
splitAttrLsonComponentS.shift();
// remove the state part of the attr components
if ( splitAttrLsonComponentS[ 0 ] === "when" ) {
splitAttrLsonComponentS[ splitAttrLsonComponentS.length - 1 ] =
parseInt( splitAttrLsonComponentS[
splitAttrLsonComponentS.length -1 ] ) - 1;
} else if ( ["fargs", "sort",
"formation", "filter", "rows"].indexOf(
splitAttrLsonComponentS[ 0 ]) !== -1 ) {
} else if ( splitAttrLsonComponentS[ 0 ] !== "transition" ) {
// props
if ( attrLsonComponentObj.props !== undefined ) {
attrLsonComponentObj = attrLsonComponentObj.props;
} else {
return false;
}
}
for ( i = 0, len = splitAttrLsonComponentS.length; i < len; i++ ) {
attrLsonComponentObj =
attrLsonComponentObj[ splitAttrLsonComponentS[ i ] ];
if ( attrLsonComponentObj === undefined ) {
break;
}
}
// Not present within states
if ( attrLsonComponentObj === undefined ) {
return false;
} else {
this.$createAttrVal( attr ,
attrLsonComponentObj );
}
}
}
}
}
return true;
};
/*
Undefine all current attributes which are influencable
by states: props, transition, when, $$num, $$max
*/
LAY.Level.prototype.$undefineStateProjectedAttrs = function() {
var attr;
for ( attr in this.attr2attrVal ) {
if ( this.attr2attrVal[ attr ].isStateProjectedAttr ) {
this.attr2attrVal[ attr ].update( undefined );
}
}
};
/* Return the attr2value generated
by the current states */
LAY.Level.prototype.$getStateAttr2val = function () {
var
attr2val = {},
stringHashedStates2_cachedAttr2val_ = this.derivedMany ?
this.derivedMany.levelStringHashedStates2_cachedAttr2val_ :
this.stringHashedStates2_cachedAttr2val_;
this.$sortStates();
var stringHashedStates = this.stateS.join( "&" );
if ( stringHashedStates2_cachedAttr2val_[
stringHashedStates ] === undefined ) {
convertSLSONtoAttr2Val( this.$generateSLSON(), attr2val, this.isPart);
stringHashedStates2_cachedAttr2val_[ stringHashedStates ] =
attr2val;
}
return stringHashedStates2_cachedAttr2val_[ stringHashedStates ];
};
/*
* TODO: fill in details of priority
*/
LAY.Level.prototype.$sortStates = function ( stateS ) {
var
sortedStateS = this.stateS.sort(),
i, len, sortedState;
// Push the "root" state to the start for least priority
LAY.$arrayUtils.remove( sortedStateS, "root" );
sortedStateS.unshift("root");
// Push the "formationDisplayNone" state to the end of the
// list of states for maximum priority.
if ( sortedStateS.indexOf( "formationDisplayNone" ) !== -1 ) {
LAY.$arrayUtils.remove( sortedStateS, "formationDisplayNone" );
sortedStateS.push( "formationDisplayNone" );
}
};
/*
* From the current states generate the
* correspinding SLSON (state projected lson)
* Requirement: the order of states must be sorted
*/
LAY.Level.prototype.$generateSLSON = function () {
this.$sortStates();
var slson = {}, attr2val;
for ( var i = 0, len = this.stateS.length; i < len; i++ ) {
LAY.$inherit( slson, this.lson.states[ this.stateS[ i ] ],
true, !this.isPart, true );
}
return slson;
};
LAY.Level.prototype.$updateStates = function () {
var attr2attrVal = this.attr2attrVal;
this.$undefineStateProjectedAttrs();
this.$commitAttr2Val( this.$getStateAttr2val() );
if ( this.derivedMany &&
!this.derivedMany.level.attr2attrVal.filter.isRecalculateRequired &&
attr2attrVal.$f.calcVal !== 1 ) {
this.$setFormationXY( this.part.formationX,
this.part.formationY );
}
};
LAY.Level.prototype.$getAttrVal = function ( attr ) {
return this.attr2attrVal[ attr ];
};
/* Manually change attr value */
LAY.Level.prototype.$changeAttrVal = function ( attr, val ) {
if ( this.attr2attrVal[ attr ] ) {
this.attr2attrVal[ attr ].update( val );
LAY.$solve();
}
};
LAY.Level.prototype.$requestRecalculation = function ( attr ) {
if ( this.attr2attrVal[ attr ] ) {
this.attr2attrVal[ attr ].requestRecalculation();
LAY.$solve();
}
};
LAY.Level.prototype.$setFormationXY = function ( x, y ) {
this.part.formationX = x;
this.part.formationY = y;
if ( this.part ) { //level might not initialized as yet
var
topAttrVal = this.attr2attrVal.top,
leftAttrVal = this.attr2attrVal.left;
if ( x === undefined ) {
leftAttrVal.update( this.derivedMany.defaultFormationX );
} else {
leftAttrVal.update( x );
}
if ( y === undefined ) {
topAttrVal.update( this.derivedMany.defaultFormationY );
} else {
topAttrVal.update( y );
}
topAttrVal.requestRecalculation();
leftAttrVal.requestRecalculation();
}
};
})();<file_sep>/readme.markdown
Refer to specification.markdown
**Demos**
- Clock: [http://codepen.io/relfor/pen/eJZQab?editors=001](http://codepen.io/relfor/pen/eJZQab?editors=001)
- TodoMVC: [http://codepen.io/relfor/full/VeaVNe/](http://codepen.io/relfor/full/VeaVNe/)
- Hello World: [http://codepen.io/relfor/pen/bEpONL?editors=001](http://codepen.io/relfor/pen/bEpONL?editors=001)
- Drawer Menu: [http://codepen.io/relfor/full/BjKvNm/](http://codepen.io/relfor/full/BjKvNm/)
**Basic API**
LAY.run({
"<ChildName>": {
$type: string,
$gpu: boolean,
$inherit: string | object | [ string | object, ... ],
$obdurate: [ string, ... ],
$load: function,
exist: boolean (take),
data: object,
props: object,
when: object,
transition: object,
many: {
$load: function,
$id: string,
data: object,
formation: string (take),
sort: [sortDict, ...],
filter: take,
rows: array | take,
fargs: {
<formationName>: args
},
states: {
< name >: {
onlyif: take,
formation: string (take),
sort: [sortDict, ...],
filter: LAY.take,
fargs: obj,
install: function
uninstall: function
}
}
},
states: {
< name >: {
onlyif: boolean (take),
props: object,
when: object,
transition: transitionObj,
install: function,
uninstall: function
}
}
}
}
});<file_sep>/test/nondisplay/runner.js
var
qunit = require('node-qunit-phantomjs'),
testDomainS,
i, len,
exec = require('child_process').exec;
exec('ls test*.html', function (error, stdout, stderr) {
testDomainS = stdout.trim().split("\n");
for ( i = 0, len = testDomainS.length; i < len; i++ ) {
qunit( "./" + testDomainS[ i ], { "verbose": false } );
}
});
<file_sep>/src/helper/render.js
( function () {
"use strict";
/*
* Optional argument of `timeNow`
* which represent the previous time frame
*/
LAY.$render = function ( timeNow ) {
if ( ( ( LAY.$renderDirtyPartS.length !== 0 ) ||
LAY.isDataTravelling
) ) {
if ( timeNow ) {
LAY.$prevTimeFrame = timeNow;
window.requestAnimationFrame( render );
} else {
LAY.$prevTimeFrame = performance.now() - 16.7;
render();
}
}
}
function render() {
var
curTimeFrame = performance.now(),
timeFrameDiff = curTimeFrame - LAY.$prevTimeFrame,
parentNode,
x, y,
i, len,
isDataTravelling = LAY.$isDataTravelling,
dataTravellingDelta = LAY.$dataTravelDelta,
renderDirtyPartS = LAY.$renderDirtyPartS,
renderDirtyPart,
travelRenderDirtyAttrValS,
travelRenderDirtyAttrVal,
normalRenderDirtyAttrValS,
normalRenderDirtyAttrVal,
renderDirtyTransition,
renderCallS, isNormalAttrValTransitionComplete,
renderNewLevelS = [],
renderNewLevel,
fnLoad,
isAllNormalTransitionComplete = true;
LAY.$isRendering = true;
for ( x = 0; x < renderDirtyPartS.length; x++ ) {
renderDirtyPart = renderDirtyPartS[ x ];
travelRenderDirtyAttrValS = renderDirtyPart.travelRenderDirtyAttrValS;
normalRenderDirtyAttrValS = renderDirtyPart.normalRenderDirtyAttrValS;
renderCallS = [];
for ( y = 0; y < travelRenderDirtyAttrValS.length; y++ ) {
travelRenderDirtyAttrVal = travelRenderDirtyAttrValS[ y ];
if ( travelRenderDirtyAttrVal.isTransitionable ) {
transitionAttrVal( travelRenderDirtyAttrVal, dataTravellingDelta );
LAY.$arrayUtils.pushUnique(
renderCallS, travelRenderDirtyAttrVal.renderCall );
}
}
for ( y = 0; y < normalRenderDirtyAttrValS.length; y++ ) {
normalRenderDirtyAttrVal = normalRenderDirtyAttrValS[ y ];
isNormalAttrValTransitionComplete = true;
if ( normalRenderDirtyAttrVal.calcVal !== undefined ) {
LAY.$arrayUtils.pushUnique( renderCallS,
normalRenderDirtyAttrVal.renderCall );
}
renderDirtyTransition = normalRenderDirtyAttrVal.transition;
if ( renderDirtyTransition !== undefined ) { // if transitioning
if ( renderDirtyTransition.delay &&
renderDirtyTransition.delay > 0 ) {
renderDirtyTransition.delay -= timeFrameDiff;
isNormalAttrValTransitionComplete = false;
} else {
if ( !renderDirtyTransition.checkIsComplete() ) {
isAllNormalTransitionComplete = false;
isNormalAttrValTransitionComplete = false;
transitionAttrVal( normalRenderDirtyAttrVal,
renderDirtyTransition.generateNext( timeFrameDiff ) );
} else {
if ( renderDirtyTransition.done !== undefined ) {
renderDirtyTransition.done.call( renderDirtyPart.level );
}
normalRenderDirtyAttrVal.transition = undefined;
}
}
}
if ( isNormalAttrValTransitionComplete ) {
normalRenderDirtyAttrVal.transCalcVal =
normalRenderDirtyAttrVal.calcVal;
LAY.$arrayUtils.removeAtIndex( normalRenderDirtyAttrValS, y );
y--;
}
}
// scroll positions must be affected last
// as a dimensional update would require
// scroll to be updated after
if ( LAY.$arrayUtils.remove( renderCallS, "scrollX" ) ) {
renderCallS.push( "scrollX" );
}
if ( LAY.$arrayUtils.remove( renderCallS, "scrollY" ) ) {
renderCallS.push( "scrollY" );
}
for ( i = 0, len = renderCallS.length; i < len; i++ ) {
renderDirtyPart.render( renderCallS[ i ] );
}
if (
( normalRenderDirtyAttrValS.length === 0 ) &&
( travelRenderDirtyAttrValS.length === 0 ) ) {
LAY.$arrayUtils.removeAtIndex( LAY.$renderDirtyPartS, x );
x--;
}
if ( !renderDirtyPart.isInitiallyRendered &&
LAY.$renderDirtyPartS.indexOf( renderDirtyPart ) === -1 ) {
LAY.$arrayUtils.pushUnique( renderNewLevelS,
renderDirtyPart.level );
}
}
for ( i = 0, len = renderNewLevelS.length; i < len; i++ ) {
renderNewLevel = renderNewLevelS[ i ];
renderNewLevel.part.isInitiallyRendered = true;
fnLoad = renderNewLevel.lson.$load;
if ( fnLoad ) {
fnLoad.call( renderNewLevel );
}
}
LAY.$isRendering = false;
if ( LAY.$isSolveRequiredOnRenderFinish ) {
LAY.$isSolveRequiredOnRenderFinish = false;
LAY.$solve();
} else if ( !isAllNormalTransitionComplete ) {
LAY.$render( curTimeFrame );
}
}
function transitionAttrVal( normalRenderDirtyAttrVal, delta ) {
if ( normalRenderDirtyAttrVal.calcVal instanceof LAY.Color ) {
normalRenderDirtyAttrVal.transCalcVal =
LAY.$generateColorMix( normalRenderDirtyAttrVal.startCalcVal,
normalRenderDirtyAttrVal.calcVal,
delta );
} else {
normalRenderDirtyAttrVal.transCalcVal =
normalRenderDirtyAttrVal.startCalcVal +
( delta *
( normalRenderDirtyAttrVal.calcVal -
normalRenderDirtyAttrVal.startCalcVal )
);
}
}
})();
<file_sep>/version.js
var
arg = process.argv[2],
msg = process.argv[3],
semver = require("semver"),
util = require("util"),
fs = require('fs'),
curVersion = fs.readFileSync("version.txt").toString().trim(),
newVersion;
if ( arg === undefined ) {
console.error("ERROR: Enter Arg (major|minor|patch|<version>)");
return 1;
} else if ( !semver.valid(curVersion) ) {
console.error("ERROR: Current git version is not valid: " + curVersion );
return 1;
} else if ( msg === undefined ) {
console.error("ERROR: No message provided");
return 1;
}
var
major = semver(curVersion).major,
minor = semver(curVersion).minor,
patch = semver(curVersion).patch,
semverFormatString = "%d.%d.%d";
switch (arg) {
case "major":
newVersion = util.format(semverFormatString, major+1, 0, 0);
break;
case "minor":
newVersion = util.format(semverFormatString, major, minor+1, 0);
break;
case "patch":
newVersion = util.format(semverFormatString, major, minor, patch+1);
break;
default:
if (!semver.valid(arg)) {
console.error("ERROR: invalid semver version: " + arg );
return 1;
} else if ( !semver.gt(arg, curVersion )) {
console.error("ERROR: version " + arg + " is not greater than current version " + curVersion );
return 1;
} else {
newVersion = arg;
}
}
fs.writeFileSync("version.txt", newVersion);
require("child_process").execSync("gulp concat");
require("child_process").execSync("git commit -a -m " + '"' + msg + '"');
require("child_process").execSync("git tag -a v" + newVersion + " -m " + '"' + msg + '"');
<file_sep>/src/obj/RelPath.js
(function () {
"use strict";
LAY.RelPath = function ( relativePath ) {
this.isMe = false;
this.isMany = false;
this.path = "";
this.isAbsolute = false;
this.traverseArray = [];
if ( relativePath === "" ) {
this.isMe = true;
} else {
if ( relativePath.charAt(0) === "/" ) {
this.isAbsolute = true;
this.path = relativePath;
} else {
var i=0;
while ( relativePath.charAt( i ) === "." ) {
if ( relativePath.slice(i, i+3) === "../" ) {
this.traverseArray.push(0);
i +=3;
} else if ( relativePath.slice(i, i+4) === ".../" ) {
this.traverseArray.push(1);
i += 4;
} else {
throw "LAY Error: Error in Take path: " + relativePath;
}
}
// strip off the "../"s
// eg: "../../Body" should become "Body"
this.path = relativePath.slice( i );
}
if ( this.path.length !== 0 &&
this.path.indexOf("*") === this.path.length - 1 ) {
this.isMany = true;
if ( this.path.length === 1 ) {
this.path = "";
} else {
this.path = this.path.slice(0, this.path.length-2);
}
}
}
};
LAY.RelPath.prototype.resolve = function ( referenceLevel ) {
if ( this.isMe ) {
return referenceLevel;
} else {
var level;
if ( this.isAbsolute ) {
level = LAY.$pathName2level[ this.path ];
} else {
level = referenceLevel;
var traverseArray = this.traverseArray;
for ( var i=0, len=traverseArray.length; i<len; i++ ) {
if ( traverseArray[ i ] === 0 ) { //parent traversal
level = level.parentLevel;
} else { //closest row traversal
do {
level = level.parentLevel;
} while ( !level.derivedMany )
}
}
level = ( this.path === "" ) ? level :
LAY.$pathName2level[ level.pathName +
( ( level.pathName === "/" ) ? "" : "/" )+
this.path ];
}
if ( this.isMany ) {
return level.derivedMany.level;
} else {
return level;
}
}
};
})();
<file_sep>/src/helper/foldUtils.js
( function () {
"use strict";
LAY.$foldlUtils = {
min: function ( rowS, key ) {
return fold( function ( row, acc ) {
var val = row[ key ];
if ( ( acc === undefined ) || ( val < acc ) ) {
return val;
} else {
return acc;
}
}, undefined, rowS );
},
max: function ( rowS, key ) {
return fold( function ( row, acc ) {
var val = row[ key ];
if ( ( acc === undefined ) || ( val > acc ) ) {
return val;
} else {
return acc;
}
}, undefined, rowS );
},
sum: function ( rowS, key ) {
return fold( function ( row, acc ) {
return acc + row[ key ];
}, 0, rowS );
},
fn: function ( rowS, fnFold, acc ) {
return fold( fnFold, acc, rowS );
}
};
function fold ( fnFold, acc, rowS ) {
for ( var i = 0, len = rowS.length; i < len; i++ ) {
acc = fnFold( rowS[ i ], acc );
}
return acc;
}
})();
| fc48cd3b08f7ef00cbfffa586d6d2d7675dff418 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | ramp-cyb/LAY.js | d1be4344ecaf794c229619ba6684b02c75ed6896 | f223c303f72d6966e5f34d1891e87843c7bbf86b |
refs/heads/master | <repo_name>elizhang227/Week2Exercises<file_sep>/game-of-thrones/game-of-thrones.py
from characters import characters
from houses import houses
# print(len(characters))
# jon_snow = {"url":"https://anapioficeandfire.com/api/characters/583","name":"<NAME>","gender":"Male","culture":"Northmen","born":"In 283 AC","died":"","titles":["Lord Commander of the Night's Watch"],"aliases":["Lord Snow","Ned Stark's Bastard","The Snow of Winterfell","The Crow-Come-Over","The 998th Lord Commander of the Night's Watch","The Bastard of Winterfell","The Black Bastard of the Wall","Lord Crow"],"father":"","mother":"","spouse":"","allegiances":["https://anapioficeandfire.com/api/houses/362"],"books":["https://anapioficeandfire.com/api/books/5"],"povBooks":["https://anapioficeandfire.com/api/books/1","https://anapioficeandfire.com/api/books/2","https://anapioficeandfire.com/api/books/3","https://anapioficeandfire.com/api/books/8"],"tvSeries":["Season 1","Season 2","Season 3","Season 4","Season 5","Season 6"],"playedBy":["<NAME>"]}
# # print out the key names individually
# # for k in jon_snow:
# # print(k)
# # print out just the values
# # for k in jon_snow:
# # print(jon_snow[k])
# print both the key and the value
# for k in jon_snow:
# print("%s: %s" % (k, jon_snow[k]))
# Characters names start with A
# count = 0
# list_of_characters = []
# for characters in characters:
# if characters['name'][0] == 'A':
# list_of_characters.append(characters['name'])
# count += 1
# print(count) # OR
# print(len(list_of_characters))
# print(list_of_characters) # prints all names with A
# Characters names start with Z
# count = 0
# for characters in characters:
# if characters['name'][0] == 'Z':
# count += 1
# print(count)
# How many character are dead?
# count = 0
# for characters in characters:
# if characters['died'] != "":
# count += 1
# print(count)
##### Who has the most titles?
# for characters in characters:
# print(len(characters['titles']))
# How many are Valyrian?
# count = 0
# for characters in characters:
# if characters['culture'] == 'Valyrian':
# count += 1
# print(count)
# What actors plays "Hot Pie" (and don't use IMDB)?
# for characters in characters:
# if characters['name'] == "<NAME>":
# print(characters['playedBy'])
###### How many characters are *not* in the tv show?
# count = 0
# for characters in characters:
# if characters['playedBy'] == "":
# count += 1
# print(count)
# List of characters with last name Targaryen
# list = []
# for characters in characters:
# if "Targaryen" in characters['name']:
# list.append(characters['name'])
# length = len(list)
# print(list)
# print('There are %s people with the last name Targaryen' % length)
# Histogram of the houses
# def letter_counter(str):
# dict = {}
# for i in str:
# if i in dict.keys():
# dict[i] += 1
# elif i not in dict.keys():
# dict[i] = 1
# return dict
dict = {}
for char in characters:
if characters["allegiances"] in dict.keys():
dict[char] += 1
elif characters['allegiances'] not in dict.keys():
dict[characters] = 1
print(dict)
| 7c246197af6b9e39907c4c9be50440c7a9b5588a | [
"Python"
] | 1 | Python | elizhang227/Week2Exercises | 28e00a3eb0157a00ef6141b0ca1b64fa70d6b2ad | 45b9934497abfa381745d68db32ddb8d7f909267 |
refs/heads/master | <repo_name>AnandKumarRamasamy/TwitterDLRESBot<file_sep>/TwitterDLRESBot/Services/APIIntegration.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace TwitterDLRESBot.Services
{
public static class APIIntegration
{
public static string GetReplyFromBot(string userMessage, string directLineSecret, bool startConversation, string userID)
{
model obj = new model();
FromUser user = new FromUser();
user.id = userID;
obj.from = user;
obj.text = userMessage;
obj.type = "message";
string conversationID = string.Empty;
conversationID = GetResponse(directLineSecret, "content locker", "https://directline.botframework.com/v3/directline/conversations", string.Empty);
Trace.TraceError("conversationID : " + conversationID);
string id = GetResponseCopy(directLineSecret, "content locker", "https://directline.botframework.com/v3/directline/conversations/" + conversationID + "/activities", obj);
Trace.TraceError("ID : " + id);
string reply = GetActivitiesCopy("https://directline.botframework.com/v3/directline/conversations/" + conversationID + "/activities", directLineSecret, id);
return reply;
}
private static string GetResponse(string token, string userMessage, string url, string data)
{
string URL = url;
string DATA = data;
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(URL);
//byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token + "");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(URL, content).Result;
string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
var jsonData = JsonConvert.DeserializeObject<Conversation>(result);
description = jsonData.conversationId;
}
return description;
}
private static string GetResponseCopy(string token, string userMessage, string url, model obj)
{
string jsonOrder = JsonConvert.SerializeObject(obj);
var DATA = Encoding.UTF8.GetBytes(jsonOrder);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(url);
//byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token + "");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(jsonOrder, UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(url, content).Result;
string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
var jsonData = JsonConvert.DeserializeObject<ActivityConversation>(result);
description = jsonData.id;
}
return description;
}
private static string GetActivitiesCopy(string url, string token, string id)
{
string reply = string.Empty;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
//string message = request.Method + url + request.ContentType + unixdate;
request.Headers["Authorization"] = "Bearer " + token + "";
//request.Headers["Content-Type"] = "application/json";
//post data
//get response
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
if (((HttpWebResponse)response).StatusDescription == "OK")
{
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string description = reader.ReadToEnd();
ActivitiesList jsonData = JsonConvert.DeserializeObject<ActivitiesList>(description);
foreach (Activities obj in jsonData.activities)
{
if (obj.replyToId == id)
{
reply = obj.text;
}
}
}
}
return reply;
}
public class model
{
public string type { get; set; }
public FromUser from { get; set; }
public string text { get; set; }
}
public class FromUser
{
public string id { get; set; }
}
public class Conversation
{
public string conversationId { get; set; }
public string token { get; set; }
}
public class ActivityConversation
{
public string id { get; set; }
}
public class ActivitiesList
{
public List<Activities> activities { get; set; }
}
public class Activities
{
public string type { get; set; }
public string id { get; set; }
public string timestamp { get; set; }
public string channelId { get; set; }
public string text { get; set; }
public string replyToId { get; set; }
public FromUser from { get; set; }
public ActivityConversation conversation { get; set; }
}
}
}<file_sep>/TwitterDLRESBot/Models/DirectlineRequest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TwitterDLRESBot.Models
{
public class DirectlineRequest
{
public string userMessage { get; set; }
public string directLineSecret { get; set; }
public bool startConversation { get; set; }
public string userID { get; set; }
}
}<file_sep>/TwitterDLRESBot/Controllers/ValuesController.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TwitterDLRESBot.Models;
using TwitterDLRESBot.Services;
namespace TwitterDLRESBot.Controllers
{
public class ValuesController : ApiController
{
public static string directLineSecret = ConfigurationManager.AppSettings["directLineSecret"];
public static string directLineWrapperUrl = ConfigurationManager.AppSettings["directLineWrapperUrl"];
public static SqlConnection GetSqlConnection()
{
//Dev
string ADOConnectionstring = "Server=tcp:dlbotdbs1.database.windows.net,1433;Initial Catalog=DLBotDB;Persist Security Info=False;User ID=DlBotdbs1;Password=<PASSWORD>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
//PROD
//string ADOConnectionstring = "Server=tcp:dlbotdbs1.database.windows.net,1433;Initial Catalog=Lpsmldb;Persist Security Info=False;User ID=DlBotdbs1;Password=<PASSWORD>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
var connection = new SqlConnection(ADOConnectionstring);
connection.Open();
return connection;
}
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public Response Get(string id)
{
Response responseobj = new Response();
responseobj.speech = "Test response from API";
responseobj.displayText = "Test response from API";
responseobj.data = null;
responseobj.contextOut = null;
responseobj.source = "directline";
responseobj.followupEvent = null;
return responseobj;
}
// POST api/values
public Response Post()
{
Response responseobj = new Response();
DirectlineRequest requestobj = new DirectlineRequest();
string userID = string.Empty;
string userMessage = string.Empty;
string reply = string.Empty;
try
{
string content = Request.Content.ReadAsStringAsync().Result;
//var requestData = (JObject)JsonConvert.DeserializeObject(content);
JObject requestData = JObject.Parse(content);
JToken objJToken;
if(requestData.TryGetValue("originalRequest", out objJToken))
userID =(string)requestData["originalRequest"]["data"]["user"]["id_str"];
userMessage = (string)requestData["result"]["resolvedQuery"];
Trace.TraceInformation("API.AI Params : " + content);
//Reset response table
//DeleteResponseContextForBot(userID);
//call directline API wrapper
requestobj.userID = userID;
requestobj.userMessage = userMessage;
requestobj.startConversation = true;
requestobj.directLineSecret = directLineSecret;
//reply= DirectlineAPIWrapper.GetResponseFromDirectlineAPI(requestobj, directLineWrapperUrl);
reply = APIIntegration.GetReplyFromBot(userMessage, directLineSecret, true, userID);
responseobj.speech = reply;
responseobj.displayText = "DisplayText";
responseobj.data = null;
responseobj.contextOut = null;
responseobj.source = "twitter";
responseobj.followupEvent = null;
Trace.TraceInformation("Reply from bot : " + reply);
}
catch (Exception ex)
{
Trace.TraceInformation("Exception : " + ex.Message);
}
return responseobj;
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
public static void DeleteResponseContextForBot(string userId)
{
try
{
using (var connection = GetSqlConnection())
{
SqlCommand cmd = new SqlCommand("DeleteResponseContextForBot", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = userId;
using (SqlDataReader reader = cmd.ExecuteReader())
connection.Close();
}
}
catch (Exception e)
{
Trace.TraceError("Error:" + e + " Method: ConnectionManager ");
throw (e);
}
}
}
}
<file_sep>/TwitterDLRESBot/Services/DirectlineAPIWrapper.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using TwitterDLRESBot.Models;
namespace TwitterDLRESBot.Services
{
public class DirectlineAPIWrapper
{
public static string GetResponseFromDirectlineAPI(DirectlineRequest requestObj,string url)
{
string result = string.Empty;
string jsonOrder = JsonConvert.SerializeObject(requestObj);
var DATA = Encoding.UTF8.GetBytes(jsonOrder);
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(url);
//byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(jsonOrder, UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(url, content).Result;
string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
result = messge.Content.ReadAsStringAsync().Result;
//var jsonData = JsonConvert.DeserializeObject<ActivityConversation>(result);
//description = jsonData.id;
}
return result;
}
}
}<file_sep>/TwitterDLRESBot/Models/Response.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TwitterDLRESBot.Models
{
public class Response
{
public string speech { get; set; }
public string displayText { get; set; }
public data data { get; set; }
public string source { get; set; }
public List<context> contextOut { get; set; }
public followupEvent followupEvent { get; set; }
}
public class context
{
public string name { get; set; }
public string lifespan { get; set; }
}
public class followupEvent
{
public string name { get; set; }
public data data { get; set; }
}
}<file_sep>/TwitterDLRESBot/Models/Request.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TwitterDLRESBot.Models
{
public class Request
{
public string id { get; set; }
public string timestamp { get; set; }
public string lang { get; set; }
public string sessionId { get; set; }
public result result { get; set; }
public originalRequest originalRequest { get; set; }
}
public class result
{
public string source { get; set; }
public string resolvedQuery { get; set; }
public string action { get; set; }
public List<context> contextList { get; set; }
public bool actionIncomplete { get; set; }
}
public class originalRequest
{
public data data { get; set; }
}
public class data
{
public user user { get; set; }
}
public class user
{
public string id_str { get; set; }
public string screen_name { get; set; }
}
public class input
{
public string intent { get; set; }
}
public class conversation
{
public string conversation_id { get; set; }
public int type { get; set; }
public string conversation_token { get; set; }
}
} | bd84c759a4e754e9a6e5484d83d3a896c7d9b290 | [
"C#"
] | 6 | C# | AnandKumarRamasamy/TwitterDLRESBot | 6e1dc865c034f7da1cd7b5515b64118062ae4a66 | 433f8e10b4791e292b86b2dae0a93671bb2c396c |
refs/heads/master | <repo_name>ephraimd/lfc-followup-utility<file_sep>/util/Db.js
const fs = require('fs');
//TODO: Add periodic db json file backup via email
let db = [],
categories = [
{ title: 'First Timers', tag: 'first-timers' },
{ title: 'Outreach Contacts', tag: 'outreach-contacts' },
{ title: 'Established', tag: 'established' },
{ title: 'New Converts', tag: 'new-converts' },
];
let dataDetails = [];
const DB_PATH = 'db/database.json';
let init = () => {
return new Promise((resolve, reject) => {
try {
resolve(JSON.parse(fs.readFileSync(DB_PATH)));
} catch (err) {
reject(err);
}
});
};
if (fs.existsSync(DB_PATH)) {
init()
.then(rdb => {
db = rdb.db;
categories = rdb.categories;
dataDetails = rdb.dataDetails;
module.exports.db = db;
module.exports.categories = categories;
module.exports.dataDetails = dataDetails;
})
.catch(err => console.log(err));
} else {
module.exports.db = db;
module.exports.categories = categories;
module.exports.dataDetails = dataDetails;
}
module.exports.saveDB = () => {
fs.writeFile(DB_PATH, JSON.stringify({
db, categories, dataDetails
}), 'utf8', (err) => console.log(err));
};
<file_sep>/README.md
# lfc-followup-utility
Follow up utility app for Living Faith Church, FUTA, Akure<file_sep>/app.js
let express = require('express');
let path = require('path');
let logger = require('morgan');
let cors = require('cors');
const Response = require('./util/Response');
const app = express();
app.use(cors());
app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
//app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
//res.sendStatus(resp.headers.status);
res.json(Response.error('Invalid Resource'));
});
let routeV1 = require('./routes/v1/index');
app.use('/v1', routeV1);
module.exports = app;
<file_sep>/routes/v1/index.js
let express = require('express');
let bodyParser = require('body-parser');
const Response = require('../../util/Response');
let DB = require('../../util/Db');
const app = express();
app.use(bodyParser());
app.use(express.json());
app.get('/get_categories', (req, res) => {
res.json(Response.success(DB.categories));
});
app.get('/get_category_data', (req, res) => {
const category = req.param('category', undefined);
if (!category) {
const resp = Response.error(`No Category value sent`);
res.status(resp.status).json(resp); //should exit
return;
}
const data = DB.db.filter(d => d.category === category);
if (!data) {
const resp = Response.error(`Category '${category}' not found`);
res.status(resp.status).json(resp); //should exit
} else {
//sort by the once that have been not been called recently
//better way: a.date_last_called - b.date_last_called
//lets just leave it like that
data.sort((a, b) => {
if (a.date_last_called > b.date_last_called) return 1;
else if (b.date_last_called > a.date_last_called) return -1;
else return 0;
});
res.json(Response.success(data));
}
});
app.get('/get_table_column_titles', (req, res) => {
res.json(Response.success(['Phone', 'Name', 'Last called']));
});
app.get('/get_data_detail', (req, res) => {
const id = req.param('id', undefined);
if (!id) {
const resp = Response.error(`Invalid Info ID value sent`);
res.status(resp.status).json(resp); //should exit
return;
}
const index = DB.db.findIndex((d) => d.id === parseInt(id));
if (index === -1) {
const resp = Response.error(`Data ID '${id}' was not found in the database`);
res.status(resp.status).json(resp); //should exit
} else {
let detail = {};
res.json(Response.success(Object.assign(detail, DB.dataDetails[index], DB.db[index])));
}
});
app.get('/search_phone', (req, res) => {
const phone = req.param('phone', undefined);
if (!phone) {
const resp = Response.error(`API needs a valid phone number to search`);
res.status(resp.status).json(resp); //should exit
return;
}
const result = DB.db.filter((d) => d.phone.match(phone) !== null);
result.sort((a, b) => {
if (a.date_last_called > b.date_last_called) return 1;
else if (b.date_last_called > a.date_last_called) return -1;
else return 0;
});
res.json(Response.success(result));
});
app.get('/search_date_period', (req, res) => {
const from = req.param('from', undefined);
const to = req.param('to', undefined);
const category = req.param('category', undefined);
if (!from || !to || !category) {
const resp = Response.error(`Date period from, to and category must be properly passed`);
res.status(resp.status).json(resp); //should exit
return;
}
const result = DB.db.filter((d) => d.category === category && d.date_created >= parseInt(from) && d.date_created <= parseInt(to));
result.sort((a, b) => {
if (a.date_last_called > b.date_last_called) return 1;
else if (b.date_last_called > a.date_last_called) return -1;
else return 0;
});
res.json(Response.success(result));
});
app.get('/move_category_data', (req, res) => {
const category = req.param('category', undefined);
const id = req.param('id', undefined);
if (!category || !id) {
const resp = Response.error(`Invalid Category or ID value sent`);
res.status(resp.status).json(resp); //should exit
return;
}
const index = DB.db.findIndex((d) => d.id === parseInt(id));
if (index === -1) {
const resp = Response.error(`category '${category}' not found`);
res.status(resp.status).json(resp); //should exit
} else {
DB.db[index].category = category;
res.json(Response.success('ok'));
DB.saveDB();
}
});
app.post('/edit_data_detail', (req, res) => {
const newComment = req.body.new_comment;
const prayer = req.body.prayer;
const date_last_called = req.body.date_last_called;
const id = req.body.id;
if (newComment === undefined || id === undefined || prayer === undefined || date_last_called === undefined) {
const resp = Response.error("'new_comment', 'date_last_called', 'prayer' and 'id' parameters must all be sent");
res.status(resp.status).json(resp); //should exit
return;
}
const index = DB.db.findIndex((d) => d.id === parseInt(id));
if (index === -1) {
const resp = Response.error(`Row with ID '${id}' was not found`);
res.status(resp.status).json(resp); //should exit
} else {
DB.db[index].date_last_called = date_last_called;
DB.dataDetails[index].date_last_called = date_last_called;
DB.dataDetails[index].comments = newComment;
DB.dataDetails[index].prayer = prayer;
res.json(Response.success('ok'));
DB.saveDB();
}
});
app.get('/delete_data', (req, res) => {
const id = req.param('id', undefined);
if (!id) {
const resp = Response.error(`Invalid Info ID value sent`);
res.status(resp.status).json(resp); //should exit
return;
}
const index = DB.db.findIndex((d) => d.id === parseInt(id));
if (index === -1) {
const resp = Response.error(`Data ID '${id}' was not found in the database`);
res.status(resp.status).json(resp); //should exit
} else {
const id_ = DB.db[index].id;
DB.dataDetails.splice(index, 1);
DB.db.splice(index, 1);
res.json(Response.success({ id: id_ }));
DB.saveDB();
}
});
app.post('/add_data', (req, res) => {
const body = req.body;
//probably don't need error checking here
const phone = body.phone;
const name = body.name;
const category = body.category;
//comment, prayer and address are optional
if (!phone || !name || !category) {
const resp = Response.error('phone, name and category parameters are all required!');
res.status(resp.status).json(resp); //should exit
return;
}
const index = DB.db.findIndex((d) => d.phone === phone);
if (index !== -1) {
const resp = Response.error(`Record with phone number '${phone}' already exists in the database under category ${DB.db[index].category}!`);
res.status(resp.status).json(resp); //should exit
} else {
let data = {};
data.name = name;
data.phone = phone;
data.category = category;
data.id = DB.db.length + 1;
let detail = {};
detail.id = data.id;
detail.comments = body.comment || "";
detail.address = body.address || "";
detail.prayer = body.prayer || "";
detail.date_created = new Date().getTime();
detail.date_last_called = body.been_called === true ? detail.date_created : 0;
//duplicate in first table
data.date_created = detail.date_created;
data.date_last_called = detail.date_last_called;
DB.db.push(data);
DB.dataDetails.push(detail);
res.json(Response.success(data));
DB.saveDB();
}
});
module.exports = app; | bd419ecf0d7f48ea0fa3e0b90e5c95b4ed8ca096 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | ephraimd/lfc-followup-utility | 728fbea9631ad32b1b1feb9d38c587531074e252 | 01f47b6a495f5c556d369dd024699280961c9369 |
refs/heads/main | <repo_name>Jyotika999/IIT2019036-Bit-By-Bit<file_sep>/density_of_each_attr.py
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
import numpy
import seaborn as sns; sns.set()
import tkinter
import base64
import warnings
warnings.filterwarnings("ignore")
import streamlit.components.v1 as components
from PIL import Image
def app():
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
# bootstrap 4 collapse example
df = pd.read_csv("Dataset/hepatitis.csv")
fig = plt.figure(figsize=(12, 18))
for i in range(len(df.columns)):
fig.add_subplot(9, 4, i + 1)
sns.distplot(df.iloc[:, i].dropna(), rug=True, hist=True, label='UW', kde_kws={'bw': 0.1})
plt.xlabel(df.columns[i])
plt.tight_layout()
plt.show()
components.html(
"""
<h1 style='text-align: center; color: #7b113a; font-size: 3rem'> Density of each attribute </h1>
"""
)
img = Image.open("images/hepatitis1.jpg")
st.image(img, width=700, caption='hepatitis')
st.pyplot(fig)
st.subheader("**Living and death concentrations over some important attributes**")
numerical_class = ['age', 'bilirubin', 'protime', 'albumin', 'alk_phosphate', 'sgot', 'class']
pp = sns.pairplot(df[numerical_class], hue="class", palette='winter')
st.pyplot(pp)
col1, col2, col3 = st.beta_columns(3)
with col1:
st.image('images/bacteria.png', width=220)
with col2:
st.image('images/virus (2).png', width=220)
with col3:
st.image('images/bacteria.png', width=220)
# main_bg = "back.png"
# main_bg_ext = "back.png"
st.markdown(
"""
<style>
.reportview-container {
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}
.sidebar .sidebar-content {
}
</style>
""",
unsafe_allow_html=True
)<file_sep>/about_this_project.py
# homepage.py
import streamlit as st
import base64
def app():
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
main_bg = "back.png"
main_bg_ext = "back.png"
side_bg = "back.png"
side_bg_ext = "back.png"
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)
st.markdown("""
<style>
.sidebar .sidebar-content {
color: #35b7aa;
background-color: #35b7aa;
}
</style>
""", unsafe_allow_html=True)
st.markdown("<h1 style='text-align: center; color: #7b113a;'>ABOUT US</h1>",
unsafe_allow_html=True)
st.write('\n\nThis application is a collaboration work of the below mentioned team from IIIT Allahabad.\n\n'
'It is developed as our **Software Engineering** project. This project deals with the visualisation and '
'analysis on hepatitis data set. For further information on this application visit the home page '
'\n\n\n\n**HAVE A NICE DAY :)**\n\n\n\n** Thanks For Visiting** ')
st.subheader('**TEAM MEMBERS**')
col1, col2, col3, col4 = st.beta_columns(4)
col1.image('https://avatars.githubusercontent.com/u/54600270?v=4', width=160)
col1.write('Jyotika')
col1.write('[Github](https://github.com/Jyotika999)')
col2.image('https://avatars.githubusercontent.com/u/58432166?v=4', width=160)
col2.write('Vidushi')
col2.write('[Github](https://github.com/vidushi1012)')
col3.image('https://avatars.githubusercontent.com/u/58389098?v=4', width=160)
col3.write('Aarushi')
col3.write('[Github](https://github.com/shee35)')
col4.image('https://avatars.githubusercontent.com/u/58399279?v=4', width=160)
col4.write('Medha')
col4.write('[Github](https://github.com/medhabalani)')
<file_sep>/app2.py
import pandas as pd
import numpy as np
import sweetviz
def app():
train = pd.read_csv("Dataset/hepatitis.csv")
train.head()
train.tail()
analysisofphosphate = sweetviz.analyze([train, "Train"], target_feat='alk_phosphate')
# In[21]:
analysisofphosphate.show_html('ReportEDAofalk_phosphate.html')
# In[17]:
# analysis of age
analysisofage = sweetviz.analyze([train, "Train"], target_feat='age')
# In[18]:
analysisofage.show_html('ReportEDAofage.html')
# In[ ]:
# In[ ]:
<file_sep>/README.md
# Software Engineering Project
## Hepatitis Data Analysis and Visualisation
--------------------------------------------------------------------------------------------------------------------------------------------------
## Features of software
* A Graphical user interface which takes Hepatitis Disease dataset as input.
* Splitting the data in multiple chunks, analyse and visualize each data chunk as a pattern.
* Identification of the changes in data patterns and invoke some pop-up msg at the time when there is a change.
* Building a Correlation matrix from the attributes of the given data.
* Computation of Metrics while processing each data attribute
* Prediction of Person surviving or dying acoording to the user input values of different attributes
* Visualisation of each attribute according to their density curve
* Exploratory DataAnalysis of each attribute on the Dataset
-------------------------------------------------------------------------------------------------------------------------------------------------
## Demo
* [Frontend Workflow](https://drive.google.com/file/d/1wiHDJ_9zvLFE8opaE6Ig1aaaMI-a4AJT/view)
* [Backend Workflow](https://drive.google.com/file/d/1C5DEeCgHXYnc9KxZND1D09qwZo8jq25f/view)
-------------------------------------------------------------------------------------------------------------------------------------------------
## Flow of our Software

--------------------------------------------------------------------------------------------------------------------------------------------------
## About Hepatitis Dataset
The Dataset have the following attribute information
```
Attribute information:
1. Class: DIE, LIVE
2. AGE: 10, 20, 30, 40, 50, 60, 70, 80
3. SEX: male, female
4. STEROID: no, yes
5. ANTIVIRALS: no, yes
6. FATIGUE: no, yes
7. MALAISE: no, yes
8. ANOREXIA: no, yes
9. LIVER BIG: no, yes
10. LIVER FIRM: no, yes
11. SPLEEN PALPABLE: no, yes
12. SPIDERS: no, yes
13. ASCITES: no, yes
14. VARICES: no, yes
15. BILIRUBIN: 0.39, 0.80, 1.20, 2.00, 3.00, 4.00
16. ALK PHOSPHATE: 33, 80, 120, 160, 200, 250
17. SGOT: 13, 100, 200, 300, 400, 500,
18. ALBUMIN: 2.1, 3.0, 3.8, 4.5, 5.0, 6.0
19. PROTIME: 10, 20, 30, 40, 50, 60, 70, 80, 90
20. HISTOLOGY: no, yes
```
--------------------------------------------------------------------------------------------------------------------------------------------------
## Diagrams
<table>
<tr>
<td align="center"><img src="Diagrams/DFD diagram (1).jpg" width="500px;" alt=""/><br /><sub><b>DFD DIAGRAM</b></sub></a><br /></td>
<td align="center"><img src="Diagrams/SOE_Activity_diagram.jpeg" width="500px;" alt=""/><br /><sub><b>ACTIVITY DIAGRAM</b></sub></a><br /></td>
</tr>
</table>
--------------------------------------------------------------------------------------------------------------------------------------------------
<!--## About each component page
* app.py =
* app1.py =
* app2.py
* homepage.py
* html_profiling.py
* info_About_models.py
* density_of_each_attr.py
* predict.py
* -->
-------------------------------------------------------------------------------------------------------------------------------------------------
## Technology used
* Python 3.8 Version
* Embedded HTML
* Embedded CSS
--------------------------------------------------------------------------------------------------------------------------------------------------
## Requirements
Install the modules in ```Requirements.txt```
```
streamlit==0.79.0
pandas==1.2.3
matplotlib==3.4.1
numpy==1.20.2
pandas_profiling==2.11.0
plotly==4.14.3
seaborn==0.11.1
streamlit-pandas-profiling==0.1.1
sweetviz==2.1.0
altair==4.1.0
joblib==1.0.1
lime==0.2.0.1
```
--------------------------------------------------------------------------------------------------------------------------------------------------
## Installation Guide Locally
* fork the repo
* git clone [REPO-URL]
* Setup the project in IDE with installed requirements
* Run ``` streamlit run app.py```
--------------------------------------------------------------------------------------------------------------------------------------------------
## Team:
<table>
<tr>
<td align="center"><a href="https://github.com/medhabalani"><img src="https://avatars3.githubusercontent.com/u/58399279?s=400&v=4" width="300px;" alt=""/><br /><sub><b>Medha - IIT2019021</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/vidushi1012"><img src="https://avatars3.githubusercontent.com/u/58432166?s=400&u=7e05b92ffe0ef8c4d5dc3c2c314ab1edebf9a431&v=4" width="300px;" alt=""/><br /><sub><b>Vidushi - IIT2019027</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/xxx32"><img src="https://avatars1.githubusercontent.com/u/58389098?s=400&u=f3f311649ce839abd0ea3fd57674a818030b5549&v=4" width="300px;" alt=""/><br /><sub><b>Aarushi - IIT2019032</b></sub></a><br /></td>
<td align="center"><a href="https://github.com/Jyotika999"><img src="https://avatars0.githubusercontent.com/u/54600270?v=4" width="300px;" alt=""/><br /><sub><b>Jyotika - IIT2019036</b></sub></a><br /></td>
</tr>
</table>
<!--# Models used for prediction:
1. [Decision Tree Model](https://webfocusinfocenter.informationbuilders.com/wfappent/TLs/TL_rstat/source/DecisionTree47.htm)
2. [KNN MODEL](https://towardsdatascience.com/machine-learning-basics-with-the-k-nearest-neighbors-algorithm-6a6e71d01761)
3. [Logistic Regression](https://towardsdatascience.com/introduction-to-logistic-regression-66248243c148) -->
<file_sep>/homepage.py
# homepage.py
import streamlit as st
import base64
def app():
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
# def set_png_as_page_bg(png_file):
# bin_str = get_base64_of_bin_file(png_file)
# page_bg_img = '''
# <style>
# body {
# background-image: url("data:image/png;base64,%s");
# background-size: cover;
# }
# </style>
# ''' % bin_str
#
# st.markdown(page_bg_img, unsafe_allow_html=True)
# return
#
# set_png_as_page_bg('imag1.png')
main_bg = "images/back.png"
main_bg_ext = "images/back.png"
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)
st.markdown("<h1 style='text-align: center; color: #7b113a;'>HEPATITIS DATASET ANALYSIS AND VISUALISATION </h1>", unsafe_allow_html=True)
st.subheader('**ABOUT HEPATITIS**')
st.write(
'Viral hepatitis is liver inflammation due to a viral infection.It may present in acute form '
'as a recent infection with relatively rapid onset, or in chronic form.'
'Hepatitis viruses are the most common cause of hepatitis in the world but other infections, toxic '
'substances (e.g. alcohol, certain drugs), and autoimmune diseases can also cause hepatitis.')
col1, mid, col2 = st.beta_columns([10, 8, 20])
with col1:
st.image('images/bacteria.png', width=320)
with col2:
st.write('There are 5 main hepatitis viruses, referred to as types A, B, C, D and E. These 5 types are of '
'greatest concern because of the burden of illness and death they cause and the potential for '
'outbreaks and epidemic spread. In particular, types B and C lead to chronic disease in hundreds'
'of millions of people and, together, are the most common cause of liver cirrhosis and cancer.')
st.write(
'Viral hepatitis is liver inflammation due to a viral infection.It may present in acute form '
'as a recent infection with relatively rapid onset, or in chronic form.'
'Hepatitis viruses are the most common cause of hepatitis in the world but other infections, toxic '
'substances (e.g. alcohol, certain drugs), and autoimmune diseases can also cause hepatitis.')
col1, mid, col2 = st.beta_columns([20, 1, 20])
with col2:
st.image('images/virus.png', width=320)
with col1:
st.write('There are 5 main hepatitis viruses, referred to as types A, B, C, D and E. These 5 types are of '
'greatest concern because of the burden of illness and death they cause and the potential for '
'outbreaks and epidemic spread. In particular, types B and C lead to chronic disease in hundreds'
'of millions of people and, together, are the most common cause of liver cirrhosis and cancer.')
st.subheader('**ABOUT THIS APP**')
st.write('This applications aims at analysing the various trends in hepatitis viruses along with their analysis '
'and visualisation and EDA analysis. You can also check the possibilities of survival and death of a '
'patient by inputing various values of some necessary fields. This application intends to help in '
'prediction and plotting correlation matrix along with graphical analysis of data over the past trends, '
'in hepatitis patients. It also detects drastic changes in the changing trends of the models.\n\n\n'
'Our software is made for the sole purpose of contributing to the medical field. It provides analysis '
'and visualization of the previous trends of hepatitis disease seen in patients of different age, gender '
'and various other attributes like intake of antivirals, steroid etc. It detects changes and gives pop up '
'notifications in the previous trends. It also displays correlation matrix for various attributes.')
<file_sep>/info_About_models.py
# homepage.py
import streamlit as st
import base64
import warnings
warnings.filterwarnings("ignore")
from PIL import Image
def app():
#st.markdown("")[image]
# uploaded_file = st.file_uploader("safety.jpg", type="jpg")
#
# if uploaded_file is not None:
# # Convert the file to an opencv image.
# file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
# opencv_image = cv2.imdecode(file_bytes, 1)
#
# # Now do something with the image! For example, let's display it:
# st.image(opencv_image, channels="BGR")
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
# def set_png_as_page_bg(png_file):
# bin_str = get_base64_of_bin_file(png_file)
# page_bg_img = '''
# <style>
# body {
# background-image: url("data:image/png;base64,%s");
# background-size: cover;
# }
# </style>
# ''' % bin_str
#
# st.markdown(page_bg_img, unsafe_allow_html=True)
# return
#
# set_png_as_page_bg('imag1.png')
main_bg = "images/back.png"
main_bg_ext = "images/back.png"
side_bg = "images/back.png"
side_bg_ext = "images/back.png"
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
.sidebar .sidebar-content {{
background: url(data:image/{side_bg_ext};base64,{base64.b64encode(open(side_bg, "rb").read()).decode()})
}}
</style>
""",
unsafe_allow_html=True
)
st.markdown("""
<style>
.sidebar .sidebar-content {
color: #35b7aa;
background-color: #35b7aa;
}
</style>
""", unsafe_allow_html=True)
st.markdown("<h1 style='text-align: center; color: #7b113a;'>Models Used</h1>",
unsafe_allow_html=True)
st.markdown("""
<style>
.big-font {
font-size:20px !important;
}
</style>
""", unsafe_allow_html=True)
# st.title('Models used:')
# st.write('add info about three models we have used for prediction')
st.subheader('**KNN Model:** ')
img = Image.open("images/knn.png")
st.image(img, width=700, caption='Hepatitis Virus')
st.markdown('<p class="big-font">The k-nearest neighbors (KNN) algorithm is a simple, easy-to-implement supervised machine learning algorithm that can be used to solve both classification and regression problems. Steps involed are:</p>', unsafe_allow_html=True)
st.write('\n')
st.markdown('<p class = "big-font">Load the data, Initialize K to your chosen number of neighbors, For each example in the data, Calculate the distance between the query example and the current example from the data, Add the distance and the index of the example to an ordered collection, Sort the ordered collection of distances and indices from smallest to largest (in ascending order) by the distances, Pick the first K entries from the sorted collection, Get the labels of the selected K entries, If regression, return the mean of the K labels, If classification, return the mode of the K labels.</p>', unsafe_allow_html=True)
st.write('\n')
st.subheader('**SVM Model:** ')
img = Image.open("images/SVM.png")
st.image(img, width=700, caption='SVM')
st.markdown('<p class="big-font">Support Vector Machine” (SVM) is a supervised machine learning algorithm which can be used for both classification or regression challenges. However, it is mostly used in classification problems. In the SVM algorithm, we plot each data item as a point in n-dimensional space (where n is number of features you have) with the value of each feature being the value of a particular coordinate. Then, we perform classification by finding the hyper-plane that differentiates the two classes very well.</p>', unsafe_allow_html=True)
st.write('\n')
st.subheader('**Naive Bayes Model:** ')
img = Image.open("images/NB.jpg")
st.image(img, width=700, caption='Naive bayes')
st.markdown('<p class="big-font">It is a classification technique based on Bayes’ Theorem with an assumption of independence among predictors. In simple terms, a Naive Bayes classifier assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature.Naive Bayes model is easy to build and particularly useful for very large data sets. Along with simplicity, Naive Bayes is known to outperform even highly sophisticated classification methods</p>', unsafe_allow_html=True)<file_sep>/change_Detection.py
# change detection and pop up
import numpy as np
import pandas as pd
import streamlit as st
import seaborn as sns
import base64
import altair as alt
def app():
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
menu1 = ["age", "sex", "steroid", "antivirals", "fatigue", "malaise", "anorexia", "liver_big", "liver_firm",
"spleen_palable", "spiders", "ascites", "varices", "bilirubin", "alk_phosphate", "sgot", "albumin",
"protime", "histology"]
menu2 = ["sex","age", "steroid", "antivirals", "fatigue", "malaise", "anorexia", "liver_big", "liver_firm", "spleen_palable", "spiders", "ascites","varices","bilirubin","alk_phosphate","sgot","albumin","protime","histology"]
choice1 = st.sidebar.selectbox("Attribute 1", menu1)
choice2 = st.sidebar.selectbox("Attribute 2", menu2)
st.markdown("<h1 style='text-align: center; color: #7b113a;'>Change in Trends and Values</h1>",
unsafe_allow_html=True)
st.subheader('**INTRODUCTION**')
st.write('Changes in attribute corresponding to the other attributes and corresponding to the live and '
'death percentages. Select the attribute among which the changes are required to be seen from '
'the side menu 1st attribute refers to attribute corresponding to the X-axis, and similarly '
'2nd attribute refers to the attribute corresponding to the Y-axis ')
dx = pd.read_csv('Dataset/hepatitis.csv')
df = pd.DataFrame(
dx,
columns=[choice1, choice2, 'class']
)
c = alt.Chart(df).mark_circle().encode(
x=choice1, y=choice2, size='class', color='class', tooltip=[choice1, choice2, 'class'])
st.altair_chart(c, use_container_width=True)
st.title("Hepatitis Dataset Correlation Matrix")
st.write(sns.heatmap(dx.corr()))
st.pyplot()
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)<file_sep>/app.py
# app.py
# app.py
import app1
import app2
import homepage
import predict
import change_Detection
import about_this_project
import info_About_models
import correlation_matrix
import density_of_each_attr
import html_profiling
# import EDUsingPandasProfiling
import streamlit as st
import time
# Spinner
with st.spinner("Waiting .."):
time.sleep(5)
PAGES = {
"Home": homepage,
"Data Visualisation ": app1,
#"EDA analysis": app2,
"Change Detection on attributes": change_Detection,
#"Correlation matrix": correlation_matrix,
"Density of attributes": density_of_each_attr,
"Profiling of Dataset": html_profiling,
"Mortality Prediction": predict,
"Models used": info_About_models,
"About Team: Bit By Bit": about_this_project,
}
st.markdown(
"""
<style>
.sidebar .sidebar-content {
background-color: #008B8B;
color: white;
}
</style>
""",
unsafe_allow_html=True,
)
st.sidebar.image('images/liver-care.png', width=210)
st.sidebar.title('Hepatitis Analysis ')
selection = st.sidebar.radio("CONTENTS: ", list(PAGES.keys()))
page = PAGES[selection]
page.app()
<file_sep>/correlation_matrix.py
# prac.py
# import streamlit as st
# def app():
# st.title('APP1')
# st.write('Welcome to app1')
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
import numpy as np
import seaborn as sns
import tkinter
import base64
import plotly.figure_factory as ff
import warnings
warnings.filterwarnings("ignore")
def app():
# Add histogram data
df = pd.read_csv("Dataset/hepatitis.csv")
#x1 = df["class"].tolist()
#x2 = df["age"].tolist()
#x3 = df["sex"].tolist()
# Group data together
#hist_data = [x1, x2, x3]
#group_labels = ['percentage', 'age', 'sex']
# Create distplot with custom bin_size
# fig = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])
# Plot!
#st.plotly_chart(fig, use_container_width=True)
# st.set_option('deprecation.showPlotGlobalUse', False)
st.title("Hepatitis Dataset Correlation Matrix")
st.write(sns.heatmap(df.corr()))
st.pyplot()
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)<file_sep>/predict.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
import streamlit as st
import seaborn as sns
import joblib
import os
import lime
import lime.lime_tabular
def app():
feature_names_best = ['age', 'sex', 'steroid', 'antivirals', 'fatigue', 'spiders', 'ascites', 'varices',
'bilirubin', 'alk_phosphate', 'sgot', 'albumin', 'protime', 'histology']
gender_dict = {"male": 1, "female": 2}
feature_dict = {"No": 1, "Yes": 2}
def get_value(val, my_dict):
for key, value in my_dict.items():
if val == key:
return value
def get_key(val, my_dict):
for key, value in my_dict.items():
if val == key:
return key
def get_fvalue(val):
feature_dict = {"No": 1, "Yes": 2}
for key, value in feature_dict.items():
if val == key:
return value
# Load ML Models
def load_model(model_file):
loaded_model = joblib.load(open(os.path.join(model_file), "rb"))
return loaded_model
st.title("Mortality Prediction")
st.subheader("Predictive Analysis")
age = st.number_input("Age", 7, 80)
sex = st.radio("Sex", tuple(gender_dict.keys()))
steroid = st.radio("Do You Take Steroids?", tuple(feature_dict.keys()))
antivirals = st.radio("Do You Take Antivirals?", tuple(feature_dict.keys()))
fatigue = st.radio("Do You Have Fatigue", tuple(feature_dict.keys()))
spiders = st.radio("Presence of Spider Naevi", tuple(feature_dict.keys()))
ascites = st.selectbox("Ascitis", tuple(feature_dict.keys()))
varices = st.selectbox("Presence of Varices", tuple(feature_dict.keys()))
bilirubin = st.number_input("bilirubin Content", 0.0, 8.0)
alk_phosphate = st.number_input("Alkaline Phosphate Content", 0.0, 296.0)
sgot = st.number_input("Sgot", 0.0, 648.0)
albumin = st.number_input("Albumin", 0.0, 6.4)
protime = st.number_input("Prothrombin Time", 0.0, 100.0)
histology = st.selectbox("Histology", tuple(feature_dict.keys()))
feature_list = [age, get_value(sex, gender_dict), get_fvalue(steroid), get_fvalue(antivirals), get_fvalue(fatigue),
get_fvalue(spiders), get_fvalue(ascites), get_fvalue(varices), bilirubin, alk_phosphate, sgot,
albumin, int(protime), get_fvalue(histology)]
st.write(len(feature_list))
result = {"age": age, "sex": sex, "steroid": steroid, "antivirals": antivirals, "fatigue": fatigue,
"spiders": spiders, "ascites": ascites, "varices": varices, "bilirubin": bilirubin,
"alk_phosphate": alk_phosphate, "sgot": sgot, "albumin": albumin, "protime": protime,
"histolog": histology}
st.json(result)
single_sample = np.array(feature_list).reshape(1, -1)
#model_choice = st.selectbox("Select Model", ["LR", "KNN", "DecisionTree"])
model_choice = "KNN"
if st.button("Predict"):
loaded_model = load_model("model/logistic_regression_hepB_model.pkl")
prediction = loaded_model.predict(single_sample)
pred_prob = loaded_model.predict_proba(single_sample)
# st.write(prediction)
# prediction_label = {"Die":1,"Live":2}
# final_result = get_key(prediction.prediction_label)
if prediction == 1:
st.warning("Patient Dies")
pred_probability_score = {"Die": pred_prob[0][0] * 100, "Live": pred_prob[0][1] * 100}
st.subheader("Prediction Probability Score using {}".format(model_choice))
st.json(pred_probability_score)
st.subheader("Prescriptive Analytics")
else:
st.success("Patient Lives")
pred_probability_score = {"Die": pred_prob[0][0] * 100, "Live": pred_prob[0][1] * 100}
st.subheader("Prediction Probability Score using {}".format(model_choice))
st.json(pred_probability_score)
if st.checkbox("Interpret"):
loaded_model = load_model("model/logistic_regression_hepB_model.pkl")
# loaded_model = load_model("models/logistic_regression_model.pkl")
# 1 Die and 2 Live
df = pd.read_csv("Dataset/hepatitis.csv")
x = df[['age', 'sex', 'steroid', 'antivirals', 'fatigue', 'spiders', 'ascites', 'varices', 'bilirubin',
'alk_phosphate', 'sgot', 'albumin', 'protime', 'histology']]
feature_names = ['age', 'sex', 'steroid', 'antivirals', 'fatigue', 'spiders', 'ascites', 'varices',
'bilirubin', 'alk_phosphate', 'sgot', 'albumin', 'protime', 'histology']
class_names = ['Die(1)', 'Live(2)']
explainer = lime.lime_tabular.LimeTabularExplainer(x.values, feature_names=feature_names,
class_names=class_names, discretize_continuous=True)
# The Explainer Instance
exp = explainer.explain_instance(np.array(feature_list), loaded_model.predict_proba, num_features=13,
top_labels=1)
exp.show_in_notebook(show_table=True, show_all=False)
# exp.save_to_file('lime_oi.html')
st.write(exp.as_list())
new_exp = exp.as_list()
label_limits = [i[0] for i in new_exp]
# st.write(label_limits)
label_scores = [i[1] for i in new_exp]
plt.barh(label_limits, label_scores)
st.pyplot()
plt.figure(figsize=(20, 10))
fig = exp.as_pyplot_figure()
st.pyplot()
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)<file_sep>/requirements.txt
streamlit==0.79.0
pandas==1.2.3
matplotlib==3.4.1
numpy==1.20.2
pandas_profiling==2.11.0
plotly==4.14.3
seaborn==0.11.1
streamlit-pandas-profiling==0.1.1
sweetviz==2.1.0
altair==4.1.0
joblib==1.0.1
lime==0.2.0.1<file_sep>/app1.py
import matplotlib.pyplot as plt
import pandas as pd
import streamlit as st
import numpy as np
import statistics as stat
import seaborn as sns
import tkinter
import base64
import streamlit.components.v1 as components
import warnings
warnings.filterwarnings("ignore")
def app():
@st.cache(allow_output_mutation=True)
def get_base64_of_bin_file(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
df = pd.read_csv("Dataset/hepatitis.csv")
attribute_name = st.sidebar.selectbox("SELECT ATTRIBUTE", (
"age", "sex", "steroid", "antivirals", "fatigue", "malaise", "anorexia", "liver_big", "liver_firm",
"spleen_palable", "spiders", "ascites", "varices", "bilirubin", "alk_phosphate", "sgot", "albumin", "protime",
"histology"))
st.title("Histogram Plot for " + attribute_name);
st.write("the entire data set is divided into chunks of 30 rows and they ar analysed and visualised here "
"individually as well as compared to the other parts of the chunks and the overall data set. Choose the"
"attributes from the side bar drop down menu and the plots for mean variance and standard deviation are "
"generated and their individual distribution over the data set can be visualised.")
n = 30
stdev = []
varn = []
meanx = []
final = [df[i * n:(i + 1) * n] for i in range((len(df) + n - 1) // n)]
st.subheader("**ENTIRE DATA SET**")
fig, ax = plt.subplots()
df.hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#86bf91",
zorder=1,
rwidth=0.7,
ax=ax,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean: **" + str(stat.mean(df[attribute_name])))
col2.write(" **Variance: **" + str(stat.variance(df[attribute_name])))
col1.write("** Standard Deviation:** " + str(stat.stdev(df[attribute_name])))
stdev.append(stat.stdev(df[attribute_name]))
varn.append(stat.variance(df[attribute_name]))
meanx.append(stat.mean(df[attribute_name]))
st.subheader("**FOR CHUNKS**")
st.write("From here onwards the divided data set is being taken into account and their individual analysis is "
"being done the attribute selection criteria is same in all the cases for all the generated graphs.")
fig1, ax1 = plt.subplots()
final[0].hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#576675",
zorder=1,
rwidth=0.7,
ax=ax1,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig1)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean:** " + str(stat.mean(final[0][attribute_name])))
col2.write(" **Variance:** " + str(stat.variance(final[0][attribute_name])))
col1.write(" **Standard Deviation: **" + str(stat.stdev(final[0][attribute_name])))
stdev.append(stat.stdev(final[0][attribute_name]))
varn.append(stat.variance(final[0][attribute_name]))
meanx.append(stat.mean(final[0][attribute_name]))
fig2, ax2 = plt.subplots()
final[1].hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#ff9636",
zorder=1,
rwidth=0.7,
ax=ax2,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig2)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean: **" + str(stat.mean(final[1][attribute_name])))
col2.write(" **Variance:** " + str(stat.variance(final[1][attribute_name])))
col1.write(" **Standard Deviation:** " + str(stat.stdev(final[1][attribute_name])))
stdev.append(stat.stdev(final[1][attribute_name]))
varn.append(stat.variance(final[1][attribute_name]))
meanx.append(stat.mean(final[1][attribute_name]))
fig3, ax3 = plt.subplots()
final[2].hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#687bbe",
zorder=1,
rwidth=0.7,
ax=ax3,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig3)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean:** " + str(stat.mean(final[2][attribute_name])))
col2.write(" **Variance:** " + str(stat.variance(final[2][attribute_name])))
col1.write(" **Standard Deviation:** " + str(stat.stdev(final[2][attribute_name])))
stdev.append(stat.stdev(final[2][attribute_name]))
varn.append(stat.variance(final[2][attribute_name]))
meanx.append(stat.mean(final[2][attribute_name]))
fig4, ax4 = plt.subplots()
final[3].hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#daa520",
zorder=1,
rwidth=0.7,
ax=ax4,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig4)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean: **" + str(stat.mean(final[3][attribute_name])))
col2.write(" **Variance:** " + str(stat.variance(final[3][attribute_name])))
col1.write(" **Standard Deviation:** " + str(stat.stdev(final[3][attribute_name])))
stdev.append(stat.stdev(final[3][attribute_name]))
varn.append(stat.variance(final[3][attribute_name]))
meanx.append(stat.mean(final[3][attribute_name]))
fig5, ax5 = plt.subplots()
final[4].hist(
bins=8,
column=attribute_name,
grid=False,
figsize=(8, 8),
color="#800080",
yrot=2,
zorder=1,
rwidth=0.7,
ax=ax5,
)
plt.xlabel(attribute_name)
plt.ylabel("number of people")
st.write(fig5)
col1, col2 = st.beta_columns(2)
# st.write("X-axis: " + attribute_name + "Y-axis: number of people")
col1.write("**Mean: **" + str(stat.mean(final[4][attribute_name])))
col2.write(" **Variance:** " + str(stat.variance(final[4][attribute_name])))
col1.write(" **Standard Deviation:** " + str(stat.stdev(final[4][attribute_name])))
stdev.append(stat.stdev(final[4][attribute_name]))
varn.append(stat.variance(final[4][attribute_name]))
meanx.append(stat.mean(final[4][attribute_name]))
st.subheader("**Standard Deviation And Mean Plot**")
st.write("Here we analyse the mean and standard deviation of chunks corresponding to the entire data set.")
arri = np.array([0, 1, 2, 3, 4, 5])
fig6 = plt.figure()
plt.plot(arri, stdev, label="SD")
plt.plot(arri, meanx, label="Mean")
leg = plt.legend()
plt.xlabel("Chunks Number")
plt.ylabel("Y-axis")
plt.show()
st.write(fig6)
st.subheader("**Variance Plot**")
st.write("Here we analyse the Variance of chunks corresponding to the entire data set.")
fig7 = plt.figure()
plt.plot(arri, varn, label="Variance")
leg = plt.legend()
plt.xlabel("Chunks Number")
plt.ylabel("Y-axis")
plt.show()
st.write(fig7)
# changing background color
st.markdown(
f"""
<style>
.reportview-container {{
background: #E55D87; /* fallback for old browsers */
background: -webkit-linear-gradient(to right, #5FC3E4, #E55D87); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to right, #5FC3E4, #E55D87); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}}
</style>
""",
unsafe_allow_html=True
)
| 3f7d0127f43a51984ffc502c790ad5d00fdb57cb | [
"Markdown",
"Python",
"Text"
] | 12 | Python | Jyotika999/IIT2019036-Bit-By-Bit | 831c5674a3d4e130b3847555f125340089f81326 | b3ee1cab1046a0d6e52e5b00ce266fead909e47b |
refs/heads/master | <repo_name>christinavalore/data-aqu-mgmt-607<file_sep>/Data 607-Assignment 12.Rmd
---
title: 'Data 607: Week 12 assignment'
author: "<NAME>"
date: "4/24/2019"
output:
word_document:
toc: yes
html_document:
number_sections: no
theme: readable
toc: yes
---
For this assignment, you should take information from a relational database and migrate it to a NoSQL database of your own choosing. For the relational database, you might use the flights database, the tb database, the “data skills” database your team created for Project 3, or another database of your own choosing or creation. For the NoSQL database, you may use MongoDB (which we introduced in week 7), Neo4j, or another NoSQL database of your choosing.
Your migration process needs to be reproducible. R code is encouraged, but not required. You should also briefly describe the advantages and disadvantages of storing the data in a relational database vs. your NoSQL database.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
##Step 1: Load Packages
I decided on migrating the flights database, specifically the flights and airports tables, from SQL to Neo4j. We first have to load the necessary packages to connect the databases to R. To get the RNeo4j package, I downloaded it from Neo4j Github here: https://github.com/nicolewhite/RNeo4j
```{r load packages}
#load mySQL packages to connect to SQL db
library(RMySQL)
library(DBI)
#download and load the RNeo4j package from GitHub
devtools::install_github("nicolewhite/RNeo4j")
library(RNeo4j)
```
##Step 2: SQL data export
After connecting to the SQL database, I then used a select statement to pull out the ALL data for the airports and flights tables and added them to data frames inside R. I also did a data dimension to check to ensure the data prior to import matched the exported version in R.
```{r SQL}
#connect to SQL database
flights_db <- dbConnect(MySQL(), user='root', password='<PASSWORD>', dbname='flights', host='127.0.0.1')
#count number of rows/columns in airport/flights tables (airport: 4x3, flights: 24x7)
air_rcount<-dbGetQuery(flights_db,"SELECT COUNT(*) FROM airports")
air_rcount
air_ccount<-dbGetQuery(flights_db,"SELECT COUNT(*)FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'airports'")
air_ccount
flight_rcount<-dbGetQuery(flights_db,"SELECT COUNT(*) FROM flights")
flight_rcount
flight_ccount<-dbGetQuery(flights_db,"SELECT COUNT(*)FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'flights'")
flight_ccount
#import all data from the airports and flights tables
airports <- dbGetQuery(flights_db, "SELECT * FROM airports")
flights <- dbGetQuery(flights_db, "SELECT * FROM flights")
#view the imported data
View(airports)
View(flights)
#check airports/flights data frame dimensions to see if they match the SQL tables (they match!)
dim(airports)
dim(flights)
```
##Step 3: Neo4j data import
After connecting to the Neo4j database, I cleared any exisiting graphs, created queries on both the airports/flights to create nodes and then created relationships by matching the aiport lables to the departure/arrival airports in flights. Once completed, we see that 24 flight nodes and 4 airport nodes with 48 relationships were created which makes sense because each flight (24) has a departue and arrival (24 X 2 = 48).
```{r Neo4j}
#create the connection from Neo4J to R
graph <- startGraph("http://localhost:7474/db/data/", username = "data607", password = "<PASSWORD>")
#clear exisiting graphs
clear(graph, input = FALSE)
#create the Neo4j query, first creating the airport nodes
queryA <- "MERGE (a1:Airport {label:{label}, city:{city}, state:{state}})"
#creat the transaction in Neo4j
trA <- newTransaction(graph)
#loop through airports, adding in the node names for label, city and state
for (i in 1:nrow(airports)){
appendCypher(trA,
queryA,
label = airports[i,]$label,
city = airports[i,]$city,
state = airports[i,]$state)
}
commit(trA)
#create flight nodes, then match the flight depart/arrive nodes w/ airport labels and create the relationship w/ airport departure (a) and matching flight (n) to arrival aiport (c)
queryF <- "MERGE (n:Flight {flight:{flight}, airline:{airline}, capacity:{capacity}})
WITH n MATCH (a:Airport {label:{depart}}), (c:Airport {label:{arrive}}) CREATE (a) -[de:DEPART {takeoff:{takeoff}}]-> (n) -[ar:ARRIVE {landing:{landing}}]-> (c)
"
trF <- newTransaction(graph)
for (i in 1:nrow(flights)){
appendCypher(trF,
queryF,
flight = flights[i,]$flight,
airline = flights[i,]$airline,
capacity = flights[i,]$capacity,
takeoff = flights[i,]$takeoff,
landing = flights[i,]$landing,
depart = flights[i,]$depart ,
arrive = flights[i,]$arrive)
}
commit(trF)
#view the relationship by using the summary function
summary(graph)
#Open the graph in the browser the use code to view: match (n) return n
browse(graph, viewer = FALSE)
```
<center>

</center>
##Analysis:
We can see that the least amount of flights are between the PIT and ATL aiports, with only 2 flight nodes in between them. There an equal amount of flights between DTW-PIT, DTW-BOS, BOS-PIT and ATL-DTW, with 6 flight nodes. DTW looks to be the busiest airports as it is connected to 18 flight nodes and ATL is the least busiest with only 12 flight nodes.
##Pros/Cons
SQL Pros:
- highly suitable for relational databases
- has a predefined schema
- fast in retrieving database records
- single standardized language across different RDBMS
SQL Cons:
- interfacing is complex
- SQL is an object that occupies space
- big data scaling requires increased hardware which is costly
NoSQL Pros:
- handles big data well
- high level of flexibility with data models
- low-cost database
- Easier and low-cost scalability
NoSQL Cons:
- less community support
- Lacks standardization, which can create issues during migration
- relaxed ACID properties which can effect the consistency in data
<file_sep>/Data607Assignment9.Rmd
---
title: 'Data 607: Assignment 9'
author: "<NAME>"
date: "3/31/2019"
output:
html_document:
toc: true
toc_float: true
---
##Web APIs
The New York Times web site provides a rich set of APIs, as described here: http://developer.nytimes.com/docs You’ll need to start by signing up for an API key. Your task is to choose one of the New York Times APIs, construct an interface in R to read in the JSON data, and transform it to an R dataframe.
```{r packages}
library(jsonlite)
library(tidyr)
suppressMessages(library(dplyr))
suppressMessages(library(RCurl))
library(httr)
suppressWarnings(library(kableExtra))
```
##Step 1
First we called the URL using our API key to see the most viewed articles on the NYT site for the past seven days. Then we place the data into a dataframe:
```{r dataframe}
url <- "https://api.nytimes.com/svc/mostpopular/v2/viewed/1.json?api-key=<KEY>"
resp <- GET(url, accept_json())
json <- fromJSON(content(resp, as="text"))
df <- data.frame(json)
```
##Step 2
Next, we subsetted the data pulling out important columns such as title, author, URL and Abstract and placed those into a nww smaller dataframe.
```{r clean}
head(df)
tidied_df<-subset(df, select=c(results.views,results.title,results.byline,results.url,results.section,results.abstract))
names(tidied_df) <- c("Top ","Article Title ", "Author(s) ", "URL ", "Section ", "Abstract ")
tidied_df %>%
kable() %>%
kable_styling()
```
##Conclusion
We can see some of the most viewed headlines over the past week, the most viewed article for this week is titled "Fossil Site Reveals Day That Meteor Hit Earth and, Maybe, Wiped Out Dinosaurs". The most viewed articles mostly came from the US section in the NYT, 5/20 of the articles to be precise.
<file_sep>/Final Project-607.Rmd
---
title: 'Data 607: Final Project'
author: "<NAME>, <NAME>, <NAME>"
date: "5/10/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Project Overview
## Business Question
<<<<<<< HEAD
Is the time of the year predicitive of the NYC subway on-time perfromance (OTP)?
## Obtain the Data
Source: MTA
```{r MTA}
# load data
data<- read.csv("https://raw.githubusercontent.com/ChristinaValore/stats-prob-606/master/Performance_NYCT.csv", header=TRUE, check.names = FALSE)
# subsetting the data to only pull out the OTP (ON TIME %) for individual subway lines
otp <-data[ which(data$PARENT_SEQ=='391690'), ]
# separate the indicator and name column to have the subway names listed individually
library(tidyr)
otp<-separate(otp,INDICATOR_NAME,into=c( "INDICATOR" , "NAME" ),sep="-")
otp$NAME<-as.factor(otp$NAME)
# remove columns that are not needed for this analysis
otp<- otp[c(-1:-4)]
```
Source: https://www.weather.gov/media/okx/Climate/CentralPark/monthlyannualtemp.pdf
```{r weather}
## @David - please add in the weather data
```
```{r population}
## @Anthony - please add in the population data
```
## Cleansing
```{r}
## Once we have all the data - we can attempt to combine all a do a futher cleansing process as needed.
```
## Exploration
```{r ggplot}
library(ggplot2)
summary(otp$MONTHLY_ACTUAL)
summary(otp$MONTHLY_TARGET)
# qualitative value - no need for a summary
summary(otp$PERIOD_MONTH)
#aggregating the monthly on-time values by subway line
month_mean<-aggregate(otp$MONTHLY_ACTUAL, by = list(otp$NAME), FUN=mean)
names(month_mean)<- c("LINE","AVG")
#Plotting the aggregate values to have a quick view of which subways have the best/worst time overall monthly
ggplot(month_mean,aes(x=reorder(LINE,-AVG), y= AVG)) + geom_bar(stat="identity") + theme (axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
```
## Modeling
## Interpreration
=======
Is weather a predictor of the NYC subway's on time percentage (OTP)?
## Obtain the Data
## Cleansing
## Exploration
## Modeling
## Interpreting
## Conclusion
<file_sep>/README.md
# Data Acquisition and Management
In this course students will learn about core concepts of contemporary data collection and its management. Topics will include systems for collecting data
(real time, sensors, open data sets, etc.) and implications for practice; types of data (textual, quantitative, qualitative, GIS, etc.) and sources; an
overview of the use of data, including what and how much should be collected and the distinction between data, information, and knowledge from a data-centric
point of view; provenance; managing data with and without databases; computer and data security; data cleaning, fusing, and processing techniques; combining
data from different sources; storage techniques including very large data sets; and storing data keeping in mind privacy and security issues.
Students will be required to create a working system for a large volume of data using publically available data sets.
<file_sep>/movierating.sql
CREATE TABLE movies
(title varchar(100) not null,
movieyear int not null,
id int,
primary key (id)
);
CREATE TABLE critics
(firstname varchar(40) not null,
lastname varchar(40) not null,
id int,
primary key (id)
);
CREATE TABLE ratings
(critic_rating int,
movie int,
critic int,
id int,
primary key (critic, movie),
foreign key (critic) references critics(id),
foreign key (movie) references movies(id)
);
Insert into movies values ('Glass', 2019, 1);
Insert into movies values ('The Upside', 2019, 2);
Insert into movies values ('<NAME>', 2019, 3);
Insert into movies values ('Aquaman', 2019, 4);
Insert into movies values ('Spider-Man: Into the Spider', 2019, 5);
Insert into movies values ('Green Book', 2019, 6);
insert into critics values ('Donna','Valore',1);
insert into critics values ('Anthony','Valore',2);
insert into critics values ('<NAME>.','Valore',3);
insert into critics values ('Samantha','Grande',4);
insert into critics values ('Melanie','Grande',5);
/*Insert ratings for the first movie Glass */
insert into ratings values (5,1,1,1);
insert into ratings values (4,1,2,2);
insert into ratings values (5,1,3,3);
insert into ratings values (3,1,4,4);
insert into ratings values (5,1,5,5);
/*Insert ratings for the second movie The Upside */
insert into ratings values (2,2,1,1);
insert into ratings values (5,2,2,2);
insert into ratings values (5,2,3,3);
insert into ratings values (3,2,4,4);
insert into ratings values (4,2,5,5);
/*Insert ratings for the third movie M<NAME>ala */
insert into ratings values (2,3,1,1);
insert into ratings values (4,3,2,2);
insert into ratings values (4,3,3,3);
insert into ratings values (5,3,4,4);
insert into ratings values (3,3,5,5);
/*Insert ratings for the fourth movie Aquaman */
insert into ratings values (4,4,1,1);
insert into ratings values (5,4,2,2);
insert into ratings values (2,4,3,3);
insert into ratings values (1,4,4,4);
insert into ratings values (5,4,5,5);
/*Insert ratings for the fifth movie Spiderman */
insert into ratings values (3,5,1,1);
insert into ratings values (2,5,2,2);
insert into ratings values (1,5,3,3);
insert into ratings values (4,5,4,4);
insert into ratings values (3,5,5,5);
/*Insert ratings for the sixth movie Green Book */
insert into ratings values (5,6,1,1);
insert into ratings values (5,6,2,2);
insert into ratings values (3,6,3,3);
insert into ratings values (4,6,4,4);
insert into ratings values (1,6,5,5);
<file_sep>/Assignment 1_Christina Valore_607.Rmd
---
title: "Assignment 1_607"
author: "<NAME>"
date: "2/2/2019"
output:
html_document: default
pdf_document: default
---
##Assignment – Loading Data into a Data Frame
Your task is to study the dataset and the associated description of the data (i.e. “data dictionary”). You may need to look around a bit, but it’s there! You should take the data, and create a data frame with a subset of the columns in the dataset. You should include the column that indicates edible or poisonous and three or four other columns. You should also add meaningful column names and replace the abbreviations used in the data—for example, in the appropriate column, “e” might become “edible.” Your deliverable is the R code to perform these transformation tasks.
## Loading the data from a URL and adding column names
```{r mushroom data}
mushroom<-read.csv("https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.data", header=FALSE, stringsAsFactors=FALSE)
colnames(mushroom) <- c("Class","Cap-Shape","Cap-Surface","Cap-Color","Bruises?","Odor","Gill-Attachment","Gill-Spacing","Gill-Size","Gill-Color","Stalk-Shape","Stalk-Root","Stalk-Surface-Above-Ring","Stalk-Surface-Below-Ring","Stalk-Color-Above-Ring","Stalk-Color-Below-Ring","Veil-Type","Veil-Color","Ring-Number","Ring-Type","Spore-Print-Color","Population","Habitat")
head(mushroom)
```
## Creating a subset of the original dataframe
```{r mushroom subset}
mushroom_subset <- subset(mushroom, select=c("Class","Gill-Size","Stalk-Shape", "Population","Habitat"))
head(mushroom_subset)
```
## Changing the abbreviations to full words
```{r abbreviation}
mushroom_subset$Class[mushroom_subset$Class == "e"] <- "Edible"
mushroom_subset$Class[mushroom_subset$Class == "p"] <- "Poisonous"
mushroom_subset$`Gill-Size`[mushroom_subset$`Gill-Size` == "b"] <- "Broad"
mushroom_subset$`Gill-Size`[mushroom_subset$`Gill-Size` == "n"] <- "Narrow"
mushroom_subset$`Stalk-Shape`[mushroom_subset$`Stalk-Shape` == "e"] <- "Enlarging"
mushroom_subset$`Stalk-Shape`[mushroom_subset$`Stalk-Shape` == "t"] <- "Tapering"
mushroom_subset$Population[mushroom_subset$Population == "a"] <- "Abundant"
mushroom_subset$Population[mushroom_subset$Population == "c"] <- "Clustered"
mushroom_subset$Population[mushroom_subset$Population == "n"] <- "Numerous"
mushroom_subset$Population[mushroom_subset$Population == "s"] <- "Scattered"
mushroom_subset$Population[mushroom_subset$Population == "v"] <- "Several"
mushroom_subset$Population[mushroom_subset$Population == "y"] <- "Solitary"
mushroom_subset$Habitat[mushroom_subset$Habitat == "g"] <- "Grasses"
mushroom_subset$Habitat[mushroom_subset$Habitat == "l"] <- "Leaves"
mushroom_subset$Habitat[mushroom_subset$Habitat == "m"] <- "Meadows"
mushroom_subset$Habitat[mushroom_subset$Habitat == "p"] <- "Paths"
mushroom_subset$Habitat[mushroom_subset$Habitat == "u"] <- "Urban"
mushroom_subset$Habitat[mushroom_subset$Habitat == "w"] <- "Waste"
mushroom_subset$Habitat[mushroom_subset$Habitat == "d"] <- "Woods"
head(mushroom_subset)
```
<file_sep>/Data 607- Project 3-final.Rmd
---
title: "Project 3 - Data Science Skills"
author: "<NAME>, <NAME>, <NAME>, <NAME>."
date: "3/24/2019"
output:
flexdashboard::flex_dashboard:
orientation: rows
source_code: embed
---
Row {.tabset .tabset-fade}
-------------------------------------
### Overview
Data was brough in two ways: via scraping and manual collection. The manual collection was taken from LinkedIn profiles, where we collected 40 data scientists information including: education, school, location,and skills. For the scraping, we used the kdnuggets website to look at tools currently used by data scientist's and trends from 2017 - 2018.
The LinkedIn data was then added to a relational database and tidied inside of R. The scraped data was brought directly into R. After the data was in their respective dataframes, we then graphed, created wordclouds and used a map to analyze the data. For the graphing, we made use of the ggplot library and for the map we used ggmap package.
### Data Load
Several of the top data scientist's information was stored in in a CSV file and was tidy up using dplyr libraries.
```{r data load}
library(tidyr)
library(wordcloud)
library(tm)
library(SnowballC)
library(RColorBrewer)
library(magrittr)
library(DBI)
library(dplyr)
library(rvest)
library(stringr)
library(ggplot2)
library(RColorBrewer)
# Data Files
ds <- read.csv("https://raw.githubusercontent.com/omarp120/DATA607Week8/master/DataScientists.csv", header=TRUE, stringsAsFactors = FALSE)
tidyDS <- gather(ds, "Number", "Skill", Skill1:Skill50) #makes data tall
finalDS <- tidyDS[tidyDS$Skill != "",] #removes rows with empty skill values
counts <- as.data.frame(table(finalDS$Skill)) #creates a data frame with skill frequencies
```
### SQL Creation and Insertion
DBI was used to create tables on the fly with an Azure SQL DB for MySQL. The databases were created from R and all insert statements were completed from R. The following tables were created:
Skills Table
Person Table
The tables were created with a Many to Many relationship.
```{r SQL dataload}
# Create Skill Table
skilltable <- unique(finalDS$Skill)
skilltable <- as.data.frame(skilltable, stringsAsFactors = FALSE)
skillids <- 1:nrow(skilltable)
skilltable <- cbind.data.frame(skilltable,skillids)
names(skilltable) <- c("SkillName", "SkillID")
# Run SQL statements to create tables
con <- dbConnect(RMariaDB::MariaDB(), user='<EMAIL>', password="<PASSWORD>", dbname='datascientists' ,host='cunyspsmysql.mysql.database.azure.com')
rs<- dbSendStatement(con, "drop table if exists person_skills;")
dbClearResult(rs)
rs<-dbSendStatement(con, "drop table if exists person;")
dbClearResult(rs)
rs<-dbSendStatement(con, "drop table if exists skills;")
dbClearResult(rs)
rs <- dbSendStatement(con, "CREATE TABLE person (
personid int NOT NULL auto_increment primary key,
title nchar(50),
name nchar(50) NOT NULL,
education nchar(50),
degree nchar(50),
location nchar(50),
company nchar(50));")
dbClearResult(rs)
rs<- dbSendStatement(con, "CREATE TABLE skills (
skillid int NOT NULL auto_increment primary key,
skillname nchar(50) NOT NULL);")
dbClearResult(rs)
rs<- dbSendStatement(con, "CREATE TABLE person_skills (
personid int NOT NULL references person(personid),
skillid int NOT NULL references skills(skillid),
CONSTRAINT person_skill primary key(personid, skillid));")
dbClearResult(rs)
dbDisconnect(con)
# Create SQL Connection
con <- dbConnect(RMariaDB::MariaDB(), user='<EMAIL>', password="<PASSWORD>", dbname='datascientists' ,host='cunyspsmysql.mysql.database.azure.com')
#mysql_datascientists <- dbGetQuery(con, 'select * from skills')
for(i in 1:nrow(skilltable))
{
# print(paste0("Inserting Skill: ", skilltable[i,]$SkillName, ", SkillID: ", skilltable[i,]$SkillID) )
sql <- sprintf("insert into skills
(skillname, skillid)
values ('%s', %d);",
skilltable[i,]$SkillName, skilltable[i,]$SkillID)
rs <- dbSendQuery(con, sql)
dbClearResult(rs)
}
mysql_dataskills <- dbGetQuery(con, 'select * from skills
limit 10')
mysql_dataskills
dbDisconnect(con)
```
Below is a list of the people being pulled from a database.
mysql_datascientists <- dbGetQuery(con, 'select name,education,degree,title,company,location from person
limit 10;')
We limit the results to only 10 rows.
```{r insert peope}
# Get Unique People to Insert
con <- dbConnect(RMariaDB::MariaDB(), user='<EMAIL>', password="<PASSWORD>", dbname='datascientists' ,host='cunyspsmysql.mysql.database.azure.com')
people_table <- finalDS %>% select(ID,Person, Title, School, HighestLevel, Location, Company) %>% unique()
for(i in 1:nrow(people_table))
{
# print(paste0("Inserting Person: ",
# people_table[i,]$Person, ", Title: ",
# people_table[i,]$Title, "School: ",
# people_table[i,]$School, ", Degree: ",
# people_table[i,]$HighestLevel, ", Location: ",
# people_table[i,]$Location, ", Company: ",
# people_table[i,]$Company))
sql <- sprintf("insert into person
(name, title, education, degree, location, company)
values ('%s', '%s', '%s','%s', '%s', '%s');",
people_table[i,]$Person,
people_table[i,]$Title,
people_table[i,]$School,
people_table[i,]$HighestLevel,
people_table[i,]$Location,
people_table[i,]$Company)
rs <- dbSendQuery(con, sql)
dbClearResult(rs)
}
mysql_datascientists <- dbGetQuery(con, 'select name,education,degree,title,company,location from person
limit 10;')
mysql_datascientists
dbDisconnect(con)
# Create Many to Many Relationship
linkdb<- tidyDS %>% select(ID, Skill)
returnIndex <- function(n)
{
for(i in 1:nrow(n))
{
return (skilltable$SkillID[skilltable$SkillName == n[i,]$Skill])
}
}
# Remove duplicate rows
person_skill <- finalDS %>% select(ID, Person, Skill) %>% distinct()
#returnIndex(linkdb[478,])
# Create Link Table
con <- dbConnect(RMariaDB::MariaDB(), user='<EMAIL>', password="<PASSWORD>", dbname='datascientists' ,host='cunyspsmysql.mysql.database.azure.com')
for(i in 1:nrow(person_skill))
{
if(length(returnIndex(person_skill[i,])) != 0)
{
# print(paste0("Inserting (PersonID: ", person_skill[i,]$ID, " SkillID: ", returnIndex(person_skill[i,]),")") )
sql <- sprintf("insert into person_skills
(personid, skillid)
values (%d, %d);",
person_skill[i,]$ID, returnIndex(person_skill[i,]))
rs <- dbSendQuery(con, sql)
dbClearResult(rs)
}else
{
print("Empty Skill Value, skipping link")
}
}
dbDisconnect(con)
```
### Web Scraping Information
On this section we did web scraping on the KDnuggets website where we gather some information about a Software poll about what’s tools in percent the software developer and data Scientist have share and use more. we can look at the major analytics tools, language programing and others tools and also the increasing and decreasing of those tools between years 2017-2018.
```{r}
data <- read_html("https://www.kdnuggets.com/2018/05/poll-tools-analytics-data-science-machine-learning-results.html")
table1 <- data %>% html_nodes("table") %>% .[1] %>% html_table(fill = T) %>% as.data.frame() %>% lapply( gsub, pattern='%', replacement='' ) %>% as.data.frame() %>% droplevels()
colnames(table1) <- c("Software", "2018 % share","% change 2018 vs 2017")
#as.numeric(as.character(table1$`2018 % share`))
table2 <- data %>% html_nodes("table") %>% .[2] %>% html_table(fill = T) %>% as.data.frame() %>% lapply( gsub, pattern='%', replacement='') %>% as.data.frame()
colnames(table2) <- c("Tool", "% change","2018 % share","2017 % share")
table3 <- data %>% html_nodes("table") %>% .[3] %>% html_table(fill = T) %>% as.data.frame() %>% lapply( gsub, pattern='%', replacement='') %>% as.data.frame()
colnames(table3) <- c("Tool", "% change","2018 % share","2017 % share")
table4 <- data %>% html_nodes("table") %>% .[4] %>% html_table(fill = T) %>% as.data.frame() %>% lapply( gsub, pattern='%', replacement='') %>% as.data.frame()
colnames(table4) <- c("Tool", "% change","2018 % share","2017 % share")
```
### Web Scraping analysis
```{r web scrape analysis}
#Table 1: Top software
ggplot(table1,aes(x=Software, y=`% change 2018 vs 2017`,fill= Software)) + geom_bar(stat="identity") + scale_fill_brewer(palette="Set3") + xlab("Software") + ylab("Percent Change") + ggtitle("Top Analytics Software in 2018") + theme(legend.position = "none",
axis.text.x = element_text(angle = 25, hjust = 1))
#Table 2: Top software with increase in usage
ggplot(table2,aes(x=Tool, y=`% change`, fill = Tool)) + geom_bar(stat="identity")+ scale_fill_brewer(palette="Paired") + xlab("Software") + ylab("Percent Change") + ggtitle("Major Analytics Tools with largest increase from 2017 - 2018") + theme(legend.position = "none", axis.text.x = element_text(angle = 25, hjust = 1))
#Table 3: Top software with decline in usage
#n is large so we must increase the palatte size
colorCount = length(unique(table3$Tool))
getPalette = colorRampPalette(brewer.pal(9, "Set1"))
ggplot(table3,aes(x=Tool, y=`% change`, fill = Tool)) + geom_bar(stat="identity", fill=getPalette(colorCount)) + xlab("Software") + ylab("Percent Change") + ggtitle("Major Analytics Tools with largest decline from 2017 - 2018") + theme(legend.position = "none", axis.text.x = element_text(angle = 25, hjust = 1))
#Table 4: Big data tools decline
ggplot(table4,aes(x=Tool, y=`% change`, fill = Tool)) + geom_bar(stat="identity")+ scale_fill_brewer(palette="Set2") + xlab("Software") + ylab("Percent Change") + ggtitle("Decline in Big Data Tools Usage from 2017 - 2018") + theme(legend.position = "none", axis.text.x = element_text(angle = 25, hjust = 1))
```
### Word Cloud
Using a word cloud graph, we can visually see that the most common skills amoung the top data scientists are Machine Learning, Data Mining, Python, Data Analysis, and Algoritms.
```{r data vis}
colnames(counts) <- c("Skill", "Freq")
wordcloud(counts$Skill, counts$Freq, random.order = FALSE, scale = c(2, 0.10), colors=brewer.pal(8, "Dark2"))
```
### Data Scientists Common Locations
```{r goecode}
#code adapted from http://www.storybench.org/geocode-csv-addresses-r/
#library(ggmap)
#register_google(key = "xxx") #removed personal API key
# Initialize the data frame
#getOption("ggmap")
# Loop through the addresses to get the latitude and longitude of each address and add it to the
# origAddress data frame in new columns lat and lon
#for(i in 1:nrow(ds))
#{
# Print("Working...")
# result <- geocode(ds$Location[i], output = "latlon", source = "google")
# ds$lon[i] <- as.numeric(result[1])
# ds$lat[i] <- as.numeric(result[2])
#}
# Write a CSV file containing origAddress to the working directory
#write.csv(ds, "geocoded.csv", row.names=FALSE)
```
```{r map}
library(leaflet)
cities <- read.csv("https://raw.githubusercontent.com/omarp120/DATA607Week8/master/geocoded.csv")
cities %>%
leaflet() %>%
addTiles() %>%
addMarkers(clusterOption=markerClusterOptions())
```
### Top Skills Analysis
```{r skill graph}
# grouped by skill and summarized into new data frame
skill_df<-finalDS %>%
group_by(Skill) %>%
summarize(n())
skill_df_top<-arrange(skill_df,desc(`n()`))
top10<- head(skill_df_top,10)
ggplot(top10,aes(x=Skill, y=`n()`,fill= top10$Skill)) + geom_bar(stat="identity") + scale_fill_brewer(palette="Spectral") + xlab("Skill") + ylab("Count") + ggtitle("Top 10 Data Scientist Skills ") + theme(legend.position = "none",
axis.text.x = element_text(angle = 25, hjust = 1))
```
### Conclusion
For the top data scientist skills, we can see machine learning followed by data mining and Python are at the top of the list. This could be due to the increased demand of predicitive analytics. In terms of datat science software, there is a decrease in the use of R, while there is a signifigant increase in RapidMiner from 2017 to 2018. Other tools with increased adoption from 2017 - 2018 are Keras and PyTorch, while Caffe and Machine Learning Server saw over a 50% decline in usage.
### References
1-) Web Scrapping website,data retrieved 3/21/2019
https://www.kdnuggets.com/2018/05/poll-tools-analytics-data-science-machine-learning-results.html<file_sep>/Data 607 - Assignment 7.Rmd
---
title: "Data 607 - Assignment 7"
author: "<NAME>"
date: "3/17/2019"
output: html_document
---
Pick three of your favorite books on one of your favorite subjects. At least one of the books should have more
than one author. For each book, include the title, authors, and two or three other attributes that you find
interesting.
Take the information that you’ve selected about these three books, and separately create three files which
store the book’s information in HTML (using an html table), XML, and JSON formats (e.g. “books.html”,
“books.xml”, and “books.json”).
To help you better understand the different file structures, I’d prefer that you
create each of these files “by hand” unless you’re already very comfortable with the file formats.
Write R code, using your packages of choice, to load the information from each of the three sources into
separate R data frames. Are the three data frames identical?
#HTML
```{r HTML}
library(RCurl)
library(XML)
#first we get the HTML data from the git URL
html<- getURL("https://raw.githubusercontent.com/ChristinaValore/data-aqu-mgmt-607/master/books.html")
#read the data into a variable in R
books.html <- readHTMLTable(html, header = TRUE)
books.html
#load html into a dataframe
html_df <- data.frame(books.html$`Fiction Books`)
html_df
```
## JSON
```{r json}
library(jsonlite)
json <- getURL("https://raw.githubusercontent.com/ChristinaValore/data-aqu-mgmt-607/master/books.json")
books.json <- fromJSON(json)
books.json
#load html into a dataframe
json_df <- data.frame(books.json$`Fiction Books`)
```
## Including Plots
You can also embed plots, for example:
```{r pressure, echo=FALSE}
xml<- getURL("https://raw.githubusercontent.com/ChristinaValore/data-aqu-mgmt-607/master/books.xml")
books.xml <- xmlParse(xml)
root <- xmlRoot(books.xml)
xmlName(root)
#resulting matrix was transposed and put into a dataframe
xml_df <- data.frame(t(xmlSApply(root, function(x) xmlSApply(x, xmlValue))), row.names = NULL)
```
Conclusion:
The three dataframes generates are similar but not identical.
The data frames derived from the XML and HTML table files are closet with the exception of the column name Author, as the XMl has two author columns to separate the book with the two authors, while the HTML has only one, where the two authors are separated by a ','.
The JSON dataframe also has a different author structure for the book with two authors as I chose to use an array to store the two names. This resulted in the author values being parsed as a list.
<file_sep>/Project 1-607.Rmd
---
title: "Data607 Assignment"
author: "<NAME>, <NAME>, <NAME>"
date: "2/14/2019"
output:
html_document:
toc: true
toc_float: true
---
# Overview
Team: Anthony, Christina, David
Our team decided to use the following libraries to clean and select the data:
stringr
magrtitr
dplyer
DT
# Data Cleansing
In this section, we used the built-in R csv loader using "|" as a separator. This still left a lot of information to clean. Regular expressions were used to remove dashes and NAs rows.
```{r}
suppressWarnings(library(stringr))
suppressWarnings(library(dplyr))
library(ggplot2)
library(DT)
#Reading the Tournament file and separing by | and omiting the NAs
data = read.csv(file = "https://raw.githubusercontent.com/ChristinaValore/data-aqu-mgmt-607/master/tournament.txt", header = FALSE, sep = "|",na.strings = c(" ", ""),stringsAsFactors = FALSE)[1:10] %>% na.omit()
#Spliting the Players and merging rows
data.new <- cbind(data[seq(1, nrow(data), by = 2 ), ],
data[seq(2, nrow(data), by = 2), 1:2 ])[-1,]
#Naming the column
colnames(data.new) <- c("num","Name","Points","round_1","round_2","round_3","round_4","round_5","round_6","round_7","State","Rating")
#Extracting the pre rating
data.new$Rating <- as.numeric(as.character(str_remove_all(str_extract_all(data.new$Rating,"R: \\s?([\\d]{3,4})"),"R: \\s?")))
#Removing the letters W D L
data.new <- data.frame(lapply(data.new, gsub, pattern = "([W D L])[ ]{2,3}(\\d+)", replacement = "\\2"), stringsAsFactors = FALSE)
data.new$Points <- as.numeric(data.new$Points )
#Calculating the opponent average
data.new$Average <- apply(data.new[,4:10], MARGIN=1,function(x) {
suppressWarnings(round(mean(as.numeric(as.character(data.new$Rating[as.numeric(x)])),na.rm =TRUE)))
})
```
# DataTable
```{r DataTable}
#creating the DataTable with preferenced column
datatable(data.new[ c(2,3,11,12,13)])
#creating the CSV file
write.csv(data.new[ c(2,3,11,12,13)], file = "Data.csv")
```
# Data Selection and Visualization
```{r Data Graph}
#looking at the graph its seem fairly normal distrubution.
ggplot(data=data.new) + geom_histogram (aes(x=Points),color="Blue", fill="white", bins = 6) + labs(title="Points Frequency plot",x="Points", y = "Point Frequency ")
```<file_sep>/Data 607- Assignment 5.Rmd
---
title: 'Data 607: Assignment 5'
author: "<NAME>"
date: "3/2/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results="hide")
library(tidyr)
library(dplyr)
library(ggplot2)
library(plotly)
```
## Overview
For this assignment, we were to create an airlines .CSV file and perform R functions to clean and transform the data using the packages tidyr and dplyr. We were then asked to compare the flight delays for both airlines. This was done via a bar graph.
```{r read in data,results= "markup"}
#read in data from GitHub
airlines<-read.csv("https://raw.githubusercontent.com/ChristinaValore/data-aqu-mgmt-607/master/Airlines.csv",header=TRUE,sep=",")
#view the data
airlines
```
```{r data cleaning,results="markup"}
# Remove NA values and rename columns while placing data into new data frame
airlines_data<-airlines %>%
filter(!is.na(Seattle)) %>%
rename("Airline"=X,"Arrival Status"=X.1,"Los Angeles"=Los.Angeles,"San Diego"=San.Diego,"San Francisco"=San.Francisco)
# Add the missing airline names
airlines_data$Airline<-as.character(airlines_data$Airline)
airlines_data$Airline[2]<-c("Alaska")
airlines_data$Airline[4]<-c("AM West")
#view the data
airlines_data
```
```{r sort data by region,results="markup"}
# Gather the city columns into rows
tidy_data<-airlines_data %>%
gather(key=City,value="Amount",3:7)
# Order the data by Airline then by Arrival Status (high to low) and finally by City
tidy_data<-arrange(tidy_data,Airline,desc(`Arrival Status`), City)
#view the data
tidy_data
```
```{r total amt flights and total amt delayed/on time,results="markup"}
#See the total amount of flights by airline
tidy_data %>%
group_by(Airline) %>%
summarize(`Total Flights`=sum(Amount))
#See the total amount of delayed and on time flights by airline
tidy_data %>%
group_by(Airline,`Arrival Status`) %>%
summarize(`Total Amount`=sum(Amount))
```
```{r add new columns,results="markup"}
# Spread the arrival status and amount rows into columns and add new columns for total amount, on time ration and delayed ration
spread_data<-tidy_data %>%
spread(`Arrival Status`,Amount) %>%
mutate(Total = delayed+`on time`,`On time ratio`=`on time`/Total,`Delayed Ratio`=delayed/Total)
# View data
spread_data
```
```{r delayed flights graph,results="markup"}
#Create a graph for the delayed flights
ggplotly(ggplot(spread_data,aes(x=City,y=`Delayed Ratio`))+geom_bar(aes(fill=Airline),stat="identity",position="dodge")+xlab("US City")+ylab("Delayed Flights Ratio")+ggtitle("Flights Delayed by City"))
```
From this graph we can see the comparison of delayed flights between airlines. The highest ratio of delayed flights come from AM West Airlines. Specifically, AM West flights to San Francisco are delayed approximately 28.73% of the time. While the lowest ratio of delayed flights come from Alaska Airlines, with flights to Phoenix delayed approximately 5% of the time. Overall flights to San Francisco have higher ratios of being delayed when compared to other US cities.
```{r on time flights graph,results="markup"}
#Create a graph for on time flights
ggplotly(ggplot(spread_data,aes(x=City,y=`On time ratio`))+geom_bar(aes(fill=Airline),stat="identity",position="dodge")+xlab("US City")+ylab("On Time Flights Ratio")+ggtitle("On Time Flights by City"))
```
As we saw in the last graph, delayed flights overall had the lowest ratios of being delayed when flying to Phoenix and so, here we can see that Phoenix has the highest on time flight ratios, with Alaska at approximately 94.84% and AM West at 92.1%.
So if you are planning to fly to Phoenix you can probably expect the flight to be on time, while flying to San Francisco has a higher chance of being delayed. <file_sep>/Data 607_Assignment 3.Rmd
---
title: "Data 607_Assignment 3"
author: "<NAME>"
date: "2/17/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Assignment 3
Copy the introductory example. The vector name stores the extracted names.
```{r intro example}
library(stringr)
raw.data <- "555-1239Moe Szyslak(636) 555-0113Burns, C. Montgomery555-6542Rev. Timothy Lovejoy555 8904Ned Flanders636-555-3226Simpson, Homer5553642Dr. <NAME>"
Name <- unlist(str_extract_all(raw.data, "[[:alpha:]., ]{2,}"))
Name
```
###Question 3
(a) Use the tools of this chapter to rearrange the vector so that all elements conform to the standard first_name last_name.
```{r rearrange first last}
#change order in Burns and Simpson
Name <- str_replace_all(Name, "(.+)(, .+)$", "\\2 \\1")
Name
```
```{r comma removal}
#remove commas from Burns and Simpson
Name <- str_replace_all(Name, ", ", "")
Name
```
(b) Construct a logical vector indicating whether a character has a title (i.e., Rev. and Dr.).
```{r logical vector}
library(knitr)
logical <- data.frame(Name)
logical$Title <- str_detect(string = Name, pattern = "\\w{2,3}\\.")
logical
```
(c) Construct a logical vector indicating whether a character has a second name.
```{r second name}
logical$Second_Name <- str_detect(string = Name, pattern = "[A-Z]{1}\\.")
logical
```
###Question 4
Describe the types of strings that conform to the following regular expressions and construct an example that is matched by the regular expression.
(1) [0-9]+\\$
```{r one}
test<- c("Christina456$Toby", "7150$", "123$789", "cdcse", "$", "98765$123")
test<- unlist(str_extract_all(test, pattern = "[0-9]+\\$" ))
test
```
We see that this espression looks for any combination of numbers 0-9 followed by a $ as the pattern to extract.
(2) \\b[a-z]{1,4}\\b
```{r two}
test <- c("CHRISTINA", "chri", "CHRI Val", "56787652", "c6v53b8w764hd", "val", "dan")
test <- str_extract_all(test, pattern = "\\b[a-z]{1,4}\\b" )
test
```
We see that this expression takes a 3 character single word that is all lowercase.
(3) .*?\\.txt$
```{r three}
test <- c("christina.txt", "VALORE.TXT", ".txt", "TXT", "txt", ".txt Christina", "help .txt", "help. txt")
test <- str_extract_all(test, pattern = ".*?\\.txt$" )
test
```
We see that this expression takes any string ending in .txt that is lowercase. The .txt can be alone but there can be no space between the period and the 'txt' phrase.
(4) \\d{2}/\\d{2}/\\d{4}
```{r four}
test <- c("02/17/2019", "2/1/19", "christina", "CHRISTINA", "2019/02/17", "12 12 4567", "03/17/20195456")
test <- str_extract_all(test, pattern = "\\d{2}/\\d{2}/\\d{4}")
test
```
We see that this expression takes 2 digits separated by a / then 2 more digits separated by a/ and finally four digits. After the four digits, if there are more digits, the function only exytracts the first four.
(5) <(.+?)>.+?</\\1>
```{r five}
test<- c("<Christina>Toby</Valore>", "<christina>", "<1233christina>, <Christina> TOBY</Christina>","<Christina> TOBY</CHRISTINA>")
test<- str_extract_all(test, pattern = "<(.+?)>.+?</\\1>")
test
```
We see that this expression looks to match the strings between the opening <> and the closing </>. The words between the arrows are case sensitive. This looks as if the pattern is looking for HTML tags.
### Question 9
The following code hides a secret message. Crack it with R and regular expressions. Hint: Some of the characters are more revealing than others! The code snippet is also available in the materials at www.r-datacollection.com.
```{r code cracking lower}
code <- "<KEY>"
#first lets try the lower case letters
lower_code = unlist(str_extract_all(code, "[[:lower:].!]"))
print (lower_code)
#Remove "" for easier reading
lower_code_new = paste(lower_code, collapse="")
print (lower_code_new)
```
We don't see anything from just the lower case alone, lets try upper.
```{r code cracking upper}
#upper case letters
upper_code = unlist(str_extract_all(code, "[[:upper:].!]"))
print (upper_code)
#Remove "" for easier reading
upper_code_new = paste(upper_code, collapse="")
print (upper_code_new)
#Remove the periods
cracked = str_replace_all(upper_code_new, "[\\.]", " ")
print(cracked)
```
Code is: CONGRATULATIONS YOU ARE A SUPERNERD!<file_sep>/Data 607- Discussion 11.Rmd
---
title: 'Data 607: Sephora Recommender System'
author: "<NAME>"
date: "4/10/2019"
output:
html_document:
theme: readable
toc: true
number_sections: false
---
### Scenario Design analysis
1. Who are your target users?
Our target users are creative individuals who want to feel beautiful physically and enjoy creating makeup looks to enhance their natural beauty.
2. What are their key goals?
Their goals are to be in control of how they look physically through makeup art. They want to look beautiful on the outside as it makes them feel good on the inside.
3. How can you help them accomplish those goals?
By offering them personalized makeup suggestions as makeup is very versatile, however, certain color palettes are not for everyone. We want to be able to suggest only makeup items we think will enhance the user's beauty.
### Reverse Engineering
Suggestions seem to be based off the context of several items such as:
- Previous purchases: using what this customer has bought previously, we can potentially see things like the foundation shades, which is a good indicator of the color of skin the user has. From this we can recommend items that compliment that specific shade, i.e. fairer skin foundation -> suggest light brown eyeliner as black may be too harsh
- Top performing products: we always want our customers to know about the best rated products we carry, so by suggesting top performing products as they relate to the user. Makeup lovers are usually always keen to try the top performing products as optimal beauty if always the goal.
- Website browsing: as users spend time on our site, we can analyze the time they spend browsing specific sections. If a user exits a section without buying an item after spending 10+ minutes browsing, the recommender system can show the user options they may have not seen but think s/he will like based on their activity.
- Search box: using terms placed in the search box on the site, we can analyze the phrases used to better understand what our users are mostly looking for. If a user searches mostly for eyeshadow then the recommender system should immediately begin to suggest eyeshadows and other products related to the eyes, i.e. mascara, eyeliner, brow products
### Recommendations
Health purposes:
It would be useful to have a way to filter out item's users may be potentially allergic to. From experience, I have purchased face makeup that I was slightly allergic to and although nothing serious occurred, it was still an unpleasant feeling to have an itchy face for several hours. This could be an additional data field in the online account that could account for potential allergens in products.
Ethical treatment of animals:
I would also recommend taking into account those who are vegans. Most vegans will not use products that were tested on animals or have any animal products in them. Looking at the website right now, I am being recommended several products that are tested on animals that I would never purchase.
Variation:
Currently the recommender system only shows about 12 products and 7 of those products are pretty much the same things. I would ask for more variation in products being suggested. I even clicked through the site a few times, going to different sections and still I am shown the same recommendations.
<file_sep>/Assignment 2 - 607.Rmd
---
title: "Assignment 2 - 607"
author: "<NAME>"
date: "2/10/2019"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## SQL and R
Choose six recent popular movies. Ask at least five people that you know (friends, family, classmates, imaginary friends) to rate each of these movie that they have seen on a scale of 1 to 5. Take the results (observations) and store them in a SQL database. Load the information into an R dataframe.
```{r mysql connection}
install.packages("RMySQL")
install.packages("DBI")
library(RMySQL)
library (DBI)
movie_rating_db <- dbConnect(MySQL(), user='root', password='<PASSWORD>', dbname='movieratings', host='127.0.0.1')
```
```{r sql to dataframe}
movie_df <- dbGetQuery(movie_rating_db,"Select title, firstname, lastname,critic_rating from movies m, critics c, ratings r where m.id = r.movie and c.id =r.critic;")
movie_df
colnames(movie_df)<-c("Movie", "First Name", "Last Name", "Movie Rating")
movie_df
```
| 69d77b7eaaafbad33e3bf0cd4fc8df2a7eb0aaf2 | [
"Markdown",
"SQL",
"RMarkdown"
] | 13 | RMarkdown | christinavalore/data-aqu-mgmt-607 | 586bab4f37bbb510805d2fbdc0b4113bfd3e234f | 5dbe940c168729c7b613e711a14303b7c93c51f0 |
refs/heads/master | <file_sep>package ukmutilizer.project.com.ukm_utilizer.model.EditProfile;
public class SubmitEditProfileRequest {
private String user_id;
private String category;
private String name;
private String dateofbirth;
private String gender;
private String nik_number;
private String photo_ktp;
private String email;
private String phone_number;
private String address;
private int province;
private int city;
private int district;
private int sub_district;
private int postcode;
public SubmitEditProfileRequest(String user_id, String category, String name, String dateofbirth, String gender, String nik_number, String photo_ktp, String email, String phone_number, String address, int province, int city, int district, int sub_district, int postcode) {
this.user_id = user_id;
this.category = category;
this.name = name;
this.dateofbirth = dateofbirth;
this.gender = gender;
this.nik_number = nik_number;
this.photo_ktp = photo_ktp;
this.email = email;
this.phone_number = phone_number;
this.address = address;
this.province = province;
this.city = city;
this.district = district;
this.sub_district = sub_district;
this.postcode = postcode;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDateofbirth() {
return dateofbirth;
}
public void setDateofbirth(String dateofbirth) {
this.dateofbirth = dateofbirth;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNik_number() {
return nik_number;
}
public void setNik_number(String nik_number) {
this.nik_number = nik_number;
}
public String getPhoto_ktp() {
return photo_ktp;
}
public void setPhoto_ktp(String photo_ktp) {
this.photo_ktp = photo_ktp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public int getCity() {
return city;
}
public void setCity(int city) {
this.city = city;
}
public int getDistrict() {
return district;
}
public void setDistrict(int district) {
this.district = district;
}
public int getSub_district() {
return sub_district;
}
public void setSub_district(int sub_district) {
this.sub_district = sub_district;
}
public int getPostcode() {
return postcode;
}
public void setPostcode(int postcode) {
this.postcode = postcode;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.GetUserProfile;
public class GetUserProfileRequest {
private String email;
public GetUserProfileRequest(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.investor.InvestorAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment.UkmDashboardOfferingDetail;
import ukmutilizer.project.com.ukm_utilizer.model.InvestorOffering.ViewInvestorOfferingResponseData;
public class InvestorOfferingDataAdapter extends BaseAdapter {
private Context context;
private ArrayList<ViewInvestorOfferingResponseData> investorOfferingResponseData;
@Override
public int getCount() {
return investorOfferingResponseData.size();
}
@Override
public Object getItem(int position) {
return investorOfferingResponseData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public InvestorOfferingDataAdapter(Context context, ArrayList<ViewInvestorOfferingResponseData> investorOfferingResponseData) {
this.context = context;
this.investorOfferingResponseData = investorOfferingResponseData;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.fragment_dashboard_inv_offering_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
holder.ukmName.setText(investorOfferingResponseData.get(position).getName());
holder.amount.setText(investorOfferingResponseData.get(position).getFunds().toString());
holder.offeringId = investorOfferingResponseData.get(position).getOfferingId();
return convertView;
}
public class ViewHolder{
TextView ukmName, amount;
String offeringId;
public ViewHolder(View view){
ukmName = view.findViewById(R.id.offeringUkmName);
amount = view.findViewById(R.id.offeringUkmAmount);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UkmDashboardOfferingDetail.class);
String offering_id = offeringId;
intent.putExtra("viewDetailOfferingId", offeringId);
v.getContext().startActivity(intent);
}
});
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.SubmitSurvey;
public class AdminSubmitSurveyRequest {
private String offering_id;
private String due_date;
private int status;
private String comment;
public AdminSubmitSurveyRequest(String offering_id, String due_date, int status, String comment) {
this.offering_id = offering_id;
this.due_date = due_date;
this.status = status;
this.comment = comment;
}
public String getOffering_id() {
return offering_id;
}
public void setOffering_id(String offering_id) {
this.offering_id = offering_id;
}
public String getDue_date() {
return due_date;
}
public void setDue_date(String due_date) {
this.due_date = due_date;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter.UkmMainDataAdapter;
import ukmutilizer.project.com.ukm_utilizer.model.Dashboard.DashboardRequest;
import ukmutilizer.project.com.ukm_utilizer.model.Dashboard.DashboardResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Dashboard.DashboardResponseData;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class MainDashboardFragment extends Fragment {
@BindView(R.id.dashboardChartRecycle)
RecyclerView dashboardChartRecycle;
@BindView(R.id.dashboardTitle)
TextView dashboardTitle;
private ArrayList<DashboardResponseData> dataList;
private UkmMainDataAdapter ukmMainDataAdapter;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private OnFragmentInteractionListener mListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_dashboard, container, false);
ButterKnife.bind(this, view);
String addId = getArguments().getString("viewUkmId");
String userName = getArguments().getString("viewUserName");
dashboardTitle.setText("UKM Dashboard");
getHomeScreen(addId);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onStart() {
super.onStart();
try {
mListener = (MainDashboardFragment.OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void getHomeScreen(String ukmId){
final DashboardRequest dashboardRequest = new DashboardRequest(ukmId);
Call<DashboardResponse> call = apiService.getUkmHomescreen(dashboardRequest);
call.enqueue(new Callback<DashboardResponse>() {
@Override
public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
if(response.body().getData() != null){
ArrayList<DashboardResponseData> dashboardResponseData = response.body().getData();
dataList = response.body().getData();
ukmMainDataAdapter = new UkmMainDataAdapter(dataList);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getContext());
dashboardChartRecycle.setLayoutManager(eLayoutManager);
dashboardChartRecycle.setAdapter(ukmMainDataAdapter);
}else{
Toast.makeText(getContext(), "TIDAK ADA DATA", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<DashboardResponse> call, Throwable t) {
Toast.makeText(getContext(), "Failed Get Dashboard Data", Toast.LENGTH_SHORT).show();
Log.e("Error Get Chart : ", String.valueOf(t));
}
});
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.constant_var;
public class ConstantVar {
public static String investorId = "";
public static String ukmId = "";
public static String category = "";
public static String userId = "";
//temp var
public static String imagePath = "";
public static String ktpImagePath = "";
public static String tokoImagePath = "";
public static String ukmType="";
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.registration;
import android.content.Intent;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import ivb.com.materialstepper.progressMobileStepper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.CheckEmailPage;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.CompleteRegistrationPage;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.InvestorAlamatStep;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.InvestorDataStep;
import ukmutilizer.project.com.ukm_utilizer.interfaces.OnInvestorFragmentPassing;
import ukmutilizer.project.com.ukm_utilizer.model.Registration.InvestorRegistrationRequest;
import ukmutilizer.project.com.ukm_utilizer.model.Registration.InvestorRegistrationResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class InvestorRegistrationForm extends progressMobileStepper implements OnInvestorFragmentPassing {
List<Class> stepperFragmentList = new ArrayList<>();
private String mName, mDateofBirth, mGender, mNikNumber, mPhotoEktp, mEmail, mPhoneNumber, mAddress, mProvince, mCity, mDistrict, mSubDistrict, mPostCode,
mOccupation, mCompanyName, mCompanyAddress, mCompanyProvince, mCompanyCity, mCompanyDistrict, mCompanySubDistrict, mCompanyPostcode;
public List<Class> init(){
stepperFragmentList.add(InvestorDataStep.class);
stepperFragmentList.add(InvestorAlamatStep.class);
stepperFragmentList.add(CompleteRegistrationPage.class);
return stepperFragmentList;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
@Override
public void sendInvPersonalName(String investorPersonalName) {
mName = investorPersonalName;
}
@Override
public void sendInvDob(String investorDob) {
mDateofBirth = investorDob;
}
@Override
public void sendInvGender(String investorGender) {
mGender = investorGender;
}
@Override
public void sendInvNikNumber(String investorNikNumber) {
mNikNumber = investorNikNumber;
}
@Override
public void sendInvPhotoKtp(String investorPhotoKtp) {
mPhoneNumber = investorPhotoKtp;
}
/*@Override
public void sendInvEmail(String investorEmail) {
mEmail = investorEmail;
}*/
@Override
public void sendInvPhone(String investorPhone) {
mPhoneNumber = investorPhone;
}
@Override
public void sendInvAddress(String investorAddress) {
mAddress = investorAddress;
}
@Override
public void sendInvProvince(String investorProvince) {
mProvince = investorProvince;
}
@Override
public void sendInvCity(String investorCity) {
mCity = investorCity;
}
@Override
public void sendInvDistrict(String investorDistrict) {
mDistrict = investorDistrict;
}
@Override
public void sendInvSubDistrict(String investorSubDistrict) {
mSubDistrict = investorSubDistrict;
}
@Override
public void sendInvPostCode(String investorPostCode) {
mPostCode = investorPostCode;
}
@Override
public void sendInvOccupation(String investorOccupation) {
mOccupation = investorOccupation;
}
/*@Override
public void sendInvCompanyName(String investorCompanyName) {
mCompanyName = investorCompanyName;
}*/
@Override
public void sendInvCompanyAddress(String investorCompanyAddress) {
mCompanyAddress = investorCompanyAddress;
}
@Override
public void sendInvCompanyProvince(String investorCompanyProvince) {
mCompanyProvince = investorCompanyProvince;
}
@Override
public void sendInvCompanyCity(String investorCompanyCity) {
mCompanyCity = investorCompanyCity;
}
@Override
public void sendInvCompanyDistrict(String investorCompanyDistrict) {
mCompanyDistrict = investorCompanyDistrict;
}
@Override
public void sendInvCompanySubDistrict(String investorCompanySubDistrict) {
mCompanySubDistrict = investorCompanySubDistrict;
}
@Override
public void sendInvCompanyPostCode(String investorCompanyPostCode) {
mCompanyPostcode = investorCompanyPostCode;
}
@Override
public void onStepperCompleted() {
showCompletedDialog();
}
protected void showCompletedDialog(){
String category = "2";
String email = getIntent().getStringExtra("emailInvestorRegistration");
String photo = ConstantVar.imagePath;
String getPhoto = "";
if(!photo.equals("")){
getPhoto = photo;
}else{
getPhoto = "https://s3.us-east-2.amazonaws.com/ukm-document-storage/07cc3c56-bcb9-41f8-938f-6e2e7273da9b";
}
InvestorRegistrationRequest investorRegistrationRequest = new InvestorRegistrationRequest(category, mName, mDateofBirth, mGender, mNikNumber,
getPhoto, email, mPhoneNumber, mAddress, mProvince, mCity, mDistrict, mSubDistrict, mPostCode, mOccupation, mCompanyName, mCompanyAddress,
mCompanyProvince, mCompanyCity, mCompanyDistrict, mCompanySubDistrict, mCompanyPostcode);
Call<InvestorRegistrationResponse> call = apiService.investorRegistration(investorRegistrationRequest);
call.enqueue(new Callback<InvestorRegistrationResponse>() {
@Override
public void onResponse(Call<InvestorRegistrationResponse> call, Response<InvestorRegistrationResponse> response) {
if(response.body().getCode()==1000){
Toast.makeText(InvestorRegistrationForm.this, "Successfully Register!", Toast.LENGTH_SHORT).show();
redirectCheckEmail();
}else{
Toast.makeText(InvestorRegistrationForm.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<InvestorRegistrationResponse> call, Throwable t) {
Toast.makeText(InvestorRegistrationForm.this, "Failed Register", Toast.LENGTH_SHORT).show();
}
});
}
private void redirectCheckEmail(){
Intent intent = new Intent(this, CheckEmailPage.class);
startActivity(intent);
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.model.ChooseCategory.ChooseCategoryResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.OfferingProgress.ViewOfferingProgressResponse;
import ukmutilizer.project.com.ukm_utilizer.model.OfferingProgress.ViewOfferingProgressResponseData;
import ukmutilizer.project.com.ukm_utilizer.registration.InvestorRegistrationForm;
import ukmutilizer.project.com.ukm_utilizer.registration.UkmRegistrationForm;
public class UkmOfferingProgressDataAdapter extends RecyclerView.Adapter<UkmOfferingProgressDataAdapter.ViewHolder> {
private List<ViewOfferingProgressResponseData> viewOfferingProgressResponseData;
public UkmOfferingProgressDataAdapter(List<ViewOfferingProgressResponseData> viewOfferingProgressResponseData) {
this.viewOfferingProgressResponseData = viewOfferingProgressResponseData;
}
@NonNull
@Override
public UkmOfferingProgressDataAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = null;
if(viewOfferingProgressResponseData!=null){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_view_offering_progress_list, parent, false);
}
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull UkmOfferingProgressDataAdapter.ViewHolder holder, int position) {
ViewOfferingProgressResponseData responseData = viewOfferingProgressResponseData.get(position);
if(responseData.getStatus().equals(1)){
holder.offeringProgressStatus.setText("On Progress");
holder.offeringProgressStatus.setTextColor(Color.parseColor("#bdbdbd"));
}else if(responseData.getStatus().equals(2)){
holder.offeringProgressStatus.setText("Approved");
holder.offeringProgressStatus.setTextColor(Color.parseColor("#31f288"));
}else if(responseData.getStatus().equals(3)){
holder.offeringProgressStatus.setText("Rejected");
holder.offeringProgressStatus.setTextColor(Color.parseColor("#e56567"));
}else if(responseData.getStatus().equals(4)){
holder.offeringProgressStatus.setText("Need More Survey");
holder.offeringProgressStatus.setTextColor(Color.parseColor("#d4e168"));
}
holder.offeringProgressComment.setText(responseData.getComment());
holder.offeringProgressDueDate.setText(responseData.getDueDate());
//holder.color = color;
//holder.offeringProgressStatus.setText(responseData.getStatus().toString());
holder.offeringProgressComment.setText(responseData.getComment());
holder.offeringProgressDueDate.setText(responseData.getDueDate());
holder.offeringNumber.setText(String.valueOf(position+1));
}
@Override
public int getItemCount() {
return viewOfferingProgressResponseData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView offeringProgressStatus, offeringProgressComment, offeringProgressDueDate, offeringNumber;
//String color;
public ViewHolder(View itemView) {
super(itemView);
//CategoryDataAdapter categoryDataAdapter = new
offeringProgressStatus = itemView.findViewById(R.id.offeringProgressStatus);
offeringProgressComment = itemView.findViewById(R.id.offeringProgressComment);
offeringProgressDueDate = itemView.findViewById(R.id.offeringProgressDueDate);
offeringNumber = itemView.findViewById(R.id.offeringNumber);
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.admin;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.model.ManageParamUkmType.ManageCategRequest;
import ukmutilizer.project.com.ukm_utilizer.model.ManageParamUkmType.ManageJobTypeRequest;
import ukmutilizer.project.com.ukm_utilizer.model.ManageParamUkmType.ManageParamResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class UpdateCateg extends AppCompatActivity {
@BindView(R.id.updParamCategory)
EditText updParamCategory;
@BindView(R.id.updParamCategoryDesc)
EditText updParamCategoryDesc;
@BindView(R.id.submitUpdateCateg)
Button submitUpdateCateg;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private android.support.v4.app.Fragment fragment;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_manageparam_update_categ);
ButterKnife.bind(this);
final int getCategId = getIntent().getIntExtra("manageCategId", 0);
String getCategTitle = getIntent().getStringExtra("manageCategTitle");
String getCategDesc = getIntent().getStringExtra("manageCategDesc");
updParamCategory.setText(getCategTitle);
updParamCategoryDesc.setText(getCategDesc);
submitUpdateCateg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setSubmitUpdateCateg(getCategId);
}
});
}
public void setSubmitUpdateCateg(int getCategId){
String updatedTitle = updParamCategory.getText().toString();
String updatedDesc = updParamCategoryDesc.getText().toString();
ManageCategRequest manageCategRequest = new ManageCategRequest(getCategId, updatedTitle, updatedDesc);
Call<ManageParamResponse> call = apiService.updateCateg(manageCategRequest);
call.enqueue(new Callback<ManageParamResponse>() {
@Override
public void onResponse(Call<ManageParamResponse> call, Response<ManageParamResponse> response) {
Toast.makeText(UpdateCateg.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onFailure(Call<ManageParamResponse> call, Throwable t) {
Toast.makeText(UpdateCateg.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.admin.AdminAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.admin.CreateSurveySchedule;
import ukmutilizer.project.com.ukm_utilizer.model.AdminDashboard.AdminHomeResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Report.ViewReportResponseData;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter.UkmViewDataAdapter;
public class AdminMainAdapter extends BaseAdapter {
private Context context;
private ArrayList<AdminHomeResponseData> adminHomeResponseData;
@Override
public int getCount() {
return adminHomeResponseData.size();
}
@Override
public Object getItem(int position) {
return adminHomeResponseData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public AdminMainAdapter(ArrayList<AdminHomeResponseData> adminHomeResponseData, Context context) {
this.adminHomeResponseData = adminHomeResponseData;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_admin_dashboard_list, parent, false);
holder = new AdminMainAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (AdminMainAdapter.ViewHolder)convertView.getTag();
}
holder.admUkmName.setText(adminHomeResponseData.get(position).getUkmName());
holder.admUkmOwner.setText(adminHomeResponseData.get(position).getOwnerUkmName());
holder.admInvName.setText("Investment from " + adminHomeResponseData.get(position).getInvestorName());
holder.offeringId = adminHomeResponseData.get(position).getId();
holder.ukmName = adminHomeResponseData.get(position).getUkmName();
holder.invName = adminHomeResponseData.get(position).getInvestorName();
holder.amount = adminHomeResponseData.get(position).getFunds();
holder.installment = adminHomeResponseData.get(position).getInstallment();
return convertView;
}
public class ViewHolder {
public TextView admUkmName;
public TextView admUkmOwner;
public TextView admInvName;
public String offeringId, invName, ukmName;
public int amount, installment;
public ViewHolder(View view){
admUkmName = view.findViewById(R.id.admDashboardUkmName);
admUkmOwner = view.findViewById(R.id.admDashboardUkmOwner);
admInvName = view.findViewById(R.id.admDashboardInvName);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CreateSurveySchedule.class);
String mOfferingId = offeringId;
String mInvName = invName;
String mUkmName = ukmName;
int mAmount = amount;
int mInstallment = installment;
intent.putExtra("surveyOffId", mOfferingId);
intent.putExtra("surveyInvName", mInvName);
intent.putExtra("surveyUkmName", mUkmName);
intent.putExtra("surveyAmount", mAmount);
intent.putExtra("surveyInstallment", mInstallment);
v.getContext().startActivity(intent);
}
});
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.registration;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import ivb.com.materialstepper.progressMobileStepper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.CheckEmailPage;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.CompleteRegistrationPage;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.PersonalDataStep;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.TokoAlamatStep;
import ukmutilizer.project.com.ukm_utilizer.registration.fragment.TokoDataStep;
import ukmutilizer.project.com.ukm_utilizer.interfaces.OnFragmentPassing;
import ukmutilizer.project.com.ukm_utilizer.model.Registration.UkmRegistrationRequest;
import ukmutilizer.project.com.ukm_utilizer.model.Registration.UkmRegistrationResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
/**
* Created by rafi.farabi on 3/14/2018.
*/
public class UkmRegistrationForm extends progressMobileStepper implements OnFragmentPassing {
@BindView(R.id.txtNamaRegist)
EditText txtNamaRegist;
List<Class> stepperFragmentList = new ArrayList<>();
private String mPersonalName, mPersonalDob, mPersonalGender, mPersonalPhone, mPersonalNik,
mUkmName, mUkmType, mUkmAddress, mUkmProvince, mUkmCity, mUkmSubDistrict, mUkmDistrict, mUkmPostalCode,
mPersonalAddress, mPersonalProvince, mPersonalCity, mPersonalDistrict, mPersonalSubDistrict, mPersonalPostalCode;
public List<Class> init(){
stepperFragmentList.add(PersonalDataStep.class);
stepperFragmentList.add(TokoAlamatStep.class);
stepperFragmentList.add(TokoDataStep.class);
stepperFragmentList.add(CompleteRegistrationPage.class);
return stepperFragmentList;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
@Override
public void sendPersonalName(String personalName) {
mPersonalName = personalName;
}
@Override
public void sendDob(String dob) {
mPersonalDob = dob;
}
@Override
public void sendGender(String gender) {
mPersonalGender = gender;
}
@Override
public void sendNikData(String nik) {
mPersonalNik = nik;
}
@Override
public void sendPhone(String phoneNumber) {
mPersonalPhone = phoneNumber;
}
@Override
public void sendAddress(String address) {
mPersonalAddress = address;
}
@Override
public void sendAddressProvince(String province) {
mPersonalProvince = province;
}
@Override
public void sendAddressCity(String city) {
mPersonalCity = city;
}
@Override
public void sendAddressDistrict(String district) {
mPersonalDistrict = district;
}
@Override
public void sendAddressSubDistrict(String subDistrict) {
mPersonalSubDistrict = subDistrict;
}
@Override
public void sendAddressPostalCode(String postalCode) {
mPersonalPostalCode = postalCode;
}
@Override
public void sendUkmType(String ukmType) {
mUkmType = ukmType;
}
@Override
public void sendUkmAddress(String ukmAddress) {
mUkmAddress = ukmAddress;
}
@Override
public void sendUkmAddressProvince(String ukmProvince) {
mUkmProvince = ukmProvince;
}
@Override
public void sendUkmAddressCity(String ukmCity) {
mUkmCity = ukmCity;
}
@Override
public void sendUkmAddressDistrict(String ukmDistrict) {
mUkmDistrict = ukmDistrict;
}
@Override
public void sendUkmAddressSubDistrict(String ukmSubDistrict) {
mUkmSubDistrict = ukmSubDistrict;
}
@Override
public void sendUkmPostalCode(String ukmPostalCode) {
mUkmPostalCode = ukmPostalCode;
}
@Override
public void sendUkmName(String ukmName) {
mUkmName = ukmName;
}
@Override
public void onStepperCompleted() {
showCompletedDialog();
}
protected void showCompletedDialog(){
//Toast.makeText(this, "nama "+ mPersonalName + mNamaToko, Toast.LENGTH_SHORT).show();
String category = "1";
String photoKtp = ConstantVar.ktpImagePath;
String photoToko = ConstantVar.tokoImagePath;
String email = getIntent().getStringExtra("emailUkmRegistration");
String ukmType = ConstantVar.ukmType;
String getPhoto = "";
if(!photoKtp.equals("")){
getPhoto = photoKtp;
}else{
getPhoto = "https://s3.us-east-2.amazonaws.com/ukm-document-storage/07cc3c56-bcb9-41f8-938f-6e2e7273da9b";
}
String getTokoPhoto = "";
if(!photoToko.equals("")){
getTokoPhoto = photoToko;
}else{
getTokoPhoto = "https://s3.us-east-2.amazonaws.com/ukm-document-storage/07cc3c56-bcb9-41f8-938f-6e2e7273da9b";
}
UkmRegistrationRequest ukmRegistrationRequest = new UkmRegistrationRequest(category, mPersonalName, mPersonalDob, mPersonalGender, mPersonalNik,
getPhoto, email, mPersonalPhone, mPersonalAddress, mPersonalProvince, mPersonalCity, mPersonalDistrict, mPersonalSubDistrict,
mPersonalPostalCode, mUkmName, ukmType, getTokoPhoto, mUkmAddress, mUkmProvince, mUkmCity, mUkmDistrict, mUkmSubDistrict, mUkmPostalCode);
Call<UkmRegistrationResponse> call = apiService.ukmRegistrationResponse(ukmRegistrationRequest);
call.enqueue(new Callback<UkmRegistrationResponse>() {
@Override
public void onResponse(Call<UkmRegistrationResponse> call, Response<UkmRegistrationResponse> response) {
if(response.body().getCode()==1000){
String status = response.body().getData().getStatus();
Toast.makeText(UkmRegistrationForm.this, "status : "+ status, Toast.LENGTH_SHORT).show();
redirectCheckEmail();
}else{
Toast.makeText(UkmRegistrationForm.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UkmRegistrationResponse> call, Throwable t) {
Toast.makeText(UkmRegistrationForm.this, "Failed Registration !", Toast.LENGTH_SHORT).show();
}
});
}
private void redirectCheckEmail(){
Intent intent = new Intent(this, CheckEmailPage.class);
startActivity(intent);
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.model.UkmOfferingAccept.UkmAcceptOfferingRequest;
import ukmutilizer.project.com.ukm_utilizer.model.UkmOfferingAccept.UkmAcceptOfferingResponse;
import ukmutilizer.project.com.ukm_utilizer.model.UkmOfferingDetail.UkmOfferingDetailRequest;
import ukmutilizer.project.com.ukm_utilizer.model.UkmOfferingDetail.UkmOfferingDetailResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
import ukmutilizer.project.com.ukm_utilizer.ukm.ViewOfferingProgress;
public class UkmDashboardOfferingDetail extends AppCompatActivity {
@BindView(R.id.txtOfferInvName)
EditText txtOfferInvName;
@BindView(R.id.txtOfferInvProf)
EditText txtOfferInvProf;
@BindView(R.id.txtOfferInvAddr)
EditText txtOfferInvAddr;
@BindView(R.id.txtOfferInvOfferedFund)
EditText txtOfferInvOfferedFund;
@BindView(R.id.txtOfferInvInstallment)
EditText txtOfferInvInstallment;
@BindView(R.id.txtOfferInvInterest)
EditText txtOfferInvInterest;
@BindView(R.id.txtOfferInvStatus)
TextView txtOfferInvStatus;
@BindView(R.id.textViewInterested)
TextView textViewInterested;
@BindView(R.id.btnOfferInvSubmit)
Button btnOfferInvSubmit;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
String offeringId;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_dashboard_offering_detail);
ButterKnife.bind(this);
if(ConstantVar.category.equals("2")){
btnOfferInvSubmit.setVisibility(View.INVISIBLE);
textViewInterested.setVisibility(View.INVISIBLE);
}
offeringId = getIntent().getExtras().getString("viewDetailOfferingId");
getDetailOfferingId(offeringId);
txtOfferInvStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(UkmDashboardOfferingDetail.this, "test", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), ViewOfferingProgress.class);
intent.putExtra("viewOfferingId", offeringId);
v.getContext().startActivity(intent);
}
});
}
public void getDetailOfferingId(String offering_id){
UkmOfferingDetailRequest ukmOfferingDetailRequest = new UkmOfferingDetailRequest(offering_id);
Call<UkmOfferingDetailResponse> call = apiService.viewOfferingDetail(ukmOfferingDetailRequest);
call.enqueue(new Callback<UkmOfferingDetailResponse>() {
@Override
public void onResponse(Call<UkmOfferingDetailResponse> call, Response<UkmOfferingDetailResponse> response) {
if(response.body().getCode().equals(1000)){
txtOfferInvName.setText(response.body().getData().getInvestorName());
txtOfferInvAddr.setText(response.body().getData().getInvestorAddress());
txtOfferInvOfferedFund.setText(response.body().getData().getAmount().toString());
txtOfferInvInstallment.setText(response.body().getData().getInstallment().toString());
txtOfferInvInterest.setText(response.body().getData().getInterest());
if(response.body().getData().getStatus().equals(1)){
txtOfferInvStatus.setText("Not Initiated");
}else if(response.body().getData().getStatus().equals(2)){
txtOfferInvStatus.setText("Waiting for Admin");
}else if(response.body().getData().getStatus().equals(3)){
txtOfferInvStatus.setText("On Progress");
}else if(response.body().getData().getStatus().equals(4)){
txtOfferInvStatus.setText("Approved");
}else if(response.body().getData().getStatus().equals(5)) {
txtOfferInvStatus.setText("Rejected");
}else if(response.body().getData().getStatus().equals(6)) {
txtOfferInvStatus.setText("Re-Survey");
}
//txtOfferInvStatus.setText(response.body().getData().getStatus().toString());
}else{
Toast.makeText(UkmDashboardOfferingDetail.this, "Failed Get Offering Detail", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UkmOfferingDetailResponse> call, Throwable t) {
Toast.makeText(UkmDashboardOfferingDetail.this, "Error Get Data", Toast.LENGTH_SHORT).show();
}
});
}
@OnClick(R.id.btnOfferInvSubmit)
public void submitOffer(){
LayoutInflater inflater = LayoutInflater.from(UkmDashboardOfferingDetail.this);
View view = inflater.inflate(R.layout.fragment_dashboard_offering_confirmation, null, false);
final EditText txtAcceptOfferingComment = view.findViewById(R.id.txtAcceptOfferingComment);
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(UkmDashboardOfferingDetail.this);
builder.setView(view)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int which) {
String comment = txtAcceptOfferingComment.getText().toString();
UkmAcceptOfferingRequest ukmAcceptOfferingRequest = new UkmAcceptOfferingRequest(offeringId, comment);
Call<UkmAcceptOfferingResponse> call = apiService.ukmAcceptOffering(ukmAcceptOfferingRequest);
call.enqueue(new Callback<UkmAcceptOfferingResponse>() {
@Override
public void onResponse(Call<UkmAcceptOfferingResponse> call, Response<UkmAcceptOfferingResponse> response) {
if(response.body().getCode().equals(1000)){
dialog.dismiss();
acceptingLayout();
}else{
Toast.makeText(UkmDashboardOfferingDetail.this, "Failed Accepting Offering", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
@Override
public void onFailure(Call<UkmAcceptOfferingResponse> call, Throwable t) {
Toast.makeText(UkmDashboardOfferingDetail.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
public void acceptingLayout(){
LayoutInflater inflater = LayoutInflater.from(UkmDashboardOfferingDetail.this);
View view = inflater.inflate(R.layout.fragment_dashboard_offering_accept, null, false);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(UkmDashboardOfferingDetail.this);
alertDialog.setView(view);
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
alertDialog.show();
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.Report;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ViewReportResponseData {
@SerializedName("ukm_id")
@Expose
private String ukmId;
@SerializedName("id")
@Expose
private String id;
@SerializedName("start_date")
@Expose
private String startDate;
@SerializedName("end_date")
@Expose
private String endDate;
@SerializedName("amount")
@Expose
private Integer amount;
public ViewReportResponseData(String ukmId, String id, String startDate, String endDate, Integer amount) {
this.ukmId = ukmId;
this.id = id;
this.startDate = startDate;
this.endDate = endDate;
this.amount = amount;
}
public String getUkmId() {
return ukmId;
}
public void setUkmId(String ukmId) {
this.ukmId = ukmId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.AdminViewSurvey;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class AdminViewSurveyResponse {
@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private ArrayList<AdminViewSurveyResponseData> data;
public AdminViewSurveyResponse(Integer code, String message, ArrayList<AdminViewSurveyResponseData> data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ArrayList<AdminViewSurveyResponseData> getData() {
return data;
}
public void setData(ArrayList<AdminViewSurveyResponseData> data) {
this.data = data;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.model.SendOtp.SendOtpRequest;
import ukmutilizer.project.com.ukm_utilizer.model.VerifyOtp.VerifyOtpRequest;
import ukmutilizer.project.com.ukm_utilizer.model.VerifyOtp.VerifyOtpResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class InsertOtpPage extends AppCompatActivity {
@BindView(R.id.txt_otp1)
EditText otp1;
@BindView(R.id.txt_otp2)
EditText otp2;
@BindView(R.id.txt_otp3)
EditText otp3;
@BindView(R.id.txt_otp4)
EditText otp4;
@BindView(R.id.veriyOtpCode)
Button verifyOtpCode;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_layout);
Toast.makeText(this, "test", Toast.LENGTH_SHORT).show();
ButterKnife.bind(this);
/*if(!otp1.getText().equals("") || !otp2.getText().equals("") || !otp3.getText().equals("") || !otp4.getText().equals("")){
}*/
//VerifyOtpRequest verifyOtpRequest = new VerifyOtpRequest(txtOtp, email);
}
@OnClick(R.id.veriyOtpCode)
void verifyOtpCode(){
final String getUserStatus = getIntent().getStringExtra("statusCode");
String txtOtp = otp1.getText().toString() + otp2.getText().toString() + otp3.getText().toString() + otp4.getText().toString();
String email = getIntent().getStringExtra("email");
//Toast.makeText(this, getUserStatus, Toast.LENGTH_SHORT).show();
VerifyOtpRequest verifyOtpRequest = new VerifyOtpRequest(email, txtOtp);
Call<VerifyOtpResponse> call = apiService.verifyOtp(verifyOtpRequest);
call.enqueue(new Callback<VerifyOtpResponse>() {
@Override
public void onResponse(Call<VerifyOtpResponse> call, Response<VerifyOtpResponse> response) {
if(response.body().getMessage().equals("OK")){
if(getUserStatus.equals("1")){
Toast.makeText(InsertOtpPage.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
redirectCreatePassword();
}else if(getUserStatus.equals("3")){
Toast.makeText(InsertOtpPage.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
redirectPreRegistration();
}else{
Toast.makeText(InsertOtpPage.this, response.body().getData(), Toast.LENGTH_SHORT).show();
}
clearOtpText();
}else{
Toast.makeText(InsertOtpPage.this, response.body().getMessage() + " - " + response.body().getData(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<VerifyOtpResponse> call, Throwable t) {
Log.e("Error Insert OTP : ", String.valueOf(t));
Toast.makeText(InsertOtpPage.this, "Failed Send OTP", Toast.LENGTH_SHORT).show();
}
});
}
public void clearOtpText(){
otp1.getText().clear();
otp2.getText().clear();
otp3.getText().clear();
otp4.getText().clear();
}
public void redirectCreatePassword(){
Intent intent = new Intent(this, CreatePassword.class);
String email = getIntent().getStringExtra("email");
intent.putExtra("emailCreatePassword", email);
startActivity(intent);
}
public void redirectPreRegistration(){
Intent intent = new Intent(this, ChooseCategory.class);
String email = getIntent().getStringExtra("email");
intent.putExtra("emailPreRegistration", email);
startActivity(intent);
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId "ukmutilizer.project.com.ukm_utilizer"
minSdkVersion 24
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
res.srcDirs =
[
'src/main/res/layouts/layout_ukm',
'src/main/res/layouts',
'src/main/res'
]
}
}
buildToolsVersion '27.0.3'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:support-v4:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.android.support:design:27.1.1'
compile 'com.android.support:support-annotations:+'
//butterknive
compile 'com.jakewharton:butterknife:8.6.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
//retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'
//gson
//retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
//http logging interceptor
compile 'com.squareup.okhttp3:logging-interceptor:3.9.1'
//material steppers
compile 'com.stepstone.stepper:material-stepper:4.3.1'
compile 'ivb.com.materialstepper:material-stepper:0.0.2'
// RecyclerView
compile 'com.android.support:recyclerview-v7:27.1.1'
// CardView
compile 'com.android.support:cardview-v7:27.1.1'
//BottomSheet
compile 'com.cocosw:bottomsheet:1.+@aar'
//Editspinner
compile 'com.reginald:editspinner:1.0.0'
//picasso
implementation 'com.squareup.picasso:picasso:2.71828'
//diagram
implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'
//edittextMaasking
implementation 'com.github.santalu:mask-edittext:1.0.2'
//carousel
compile 'com.synnapps:carouselview:0.1.4'
//vertical stepper
compile 'com.ernestoyaquello.stepperform:vertical-stepper-form:0.9.9'
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.AdminReport;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AdminReportInvestmentResponseData {
@SerializedName("survey_id")
@Expose
private String surveyId;
@SerializedName("offering_id")
@Expose
private String offeringId;
@SerializedName("ukm_name")
@Expose
private String ukmName;
@SerializedName("ukm_owner")
@Expose
private String ukmOwner;
@SerializedName("investor_name")
@Expose
private String investorName;
@SerializedName("due_date")
@Expose
private String dueDate;
@SerializedName("status")
@Expose
private Integer status;
@SerializedName("comment")
@Expose
private String comment;
public AdminReportInvestmentResponseData(String surveyId, String offeringId, String ukmName, String ukmOwner, String investorName, String dueDate, Integer status, String comment) {
this.surveyId = surveyId;
this.offeringId = offeringId;
this.ukmName = ukmName;
this.ukmOwner = ukmOwner;
this.investorName = investorName;
this.dueDate = dueDate;
this.status = status;
this.comment = comment;
}
public String getSurveyId() {
return surveyId;
}
public void setSurveyId(String surveyId) {
this.surveyId = surveyId;
}
public String getOfferingId() {
return offeringId;
}
public void setOfferingId(String offeringId) {
this.offeringId = offeringId;
}
public String getUkmName() {
return ukmName;
}
public void setUkmName(String ukmName) {
this.ukmName = ukmName;
}
public String getUkmOwner() {
return ukmOwner;
}
public void setUkmOwner(String ukmOwner) {
this.ukmOwner = ukmOwner;
}
public String getInvestorName() {
return investorName;
}
public void setInvestorName(String investorName) {
this.investorName = investorName;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.model.CheckEmail.CheckEmailRequest;
import ukmutilizer.project.com.ukm_utilizer.model.CheckEmail.CheckEmailResponse;
import ukmutilizer.project.com.ukm_utilizer.model.SendOtp.SendOtpRequest;
import ukmutilizer.project.com.ukm_utilizer.model.SendOtp.SendOtpResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
/**
* Created by rafi.farabi on 3/10/2018.
*/
public class CheckEmailPage extends AppCompatActivity {
@BindView(R.id.chkTxtEmail)
EditText txtChkEmail;
@BindView(R.id.chkEmailBtn)
Button btnChkEmail;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkemailpage);
ButterKnife.bind(this);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
}
@OnClick(R.id.chkEmailBtn)
void applicationLoadData() {
/*if(txtChkEmail.getText().toString().equals("1")){
redirectInsertPass();
}else if(txtChkEmail.getText().toString().equals("2")){
redirectCreatePassword();
}
else if(txtChkEmail.getText().toString().equals("3")){
redirectPreRegistration();
}*/
CheckEmailRequest checkEmailRequest = new CheckEmailRequest(txtChkEmail.getText().toString());
Call<CheckEmailResponse> call = apiService.getEmailStatus(checkEmailRequest);
call.enqueue(new Callback<CheckEmailResponse>() {
@Override
public void onResponse(Call<CheckEmailResponse> call, Response<CheckEmailResponse> response) {
ConstantVar.category = response.body().getData().getCategory();
if (response.isSuccessful() && response.body().getData().getStatus().equals("2")) {
//String checkEmailData = response.body().getData().getStatus();
String userCateg = response.body().getData().getCategory();
redirectInsertPass(userCateg);
// Log.d("Message : ", String.valueOf(checkEmailData));
} else if (response.isSuccessful() && response.body().getData().getStatus().equals("1")) {
String checkEmailData = response.body().getData().getStatus();
redirectInsertOtp(checkEmailData);
} else if (response.isSuccessful() && response.body().getData().getStatus().equals("3")) {
String checkEmailData = response.body().getData().getStatus();
redirectInsertOtp(checkEmailData);
} else {
Log.d("Message Response : ", response.body().getData().getStatus().toString());
Toast.makeText(CheckEmailPage.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<CheckEmailResponse> call, Throwable t) {
Toast.makeText(CheckEmailPage.this, "Failed Authenticate Email", Toast.LENGTH_SHORT).show();
Log.e("Failure : ", String.valueOf(t));
}
});
}
public void sendOtp() {
//redirectInsertOtp(statusCode);
SendOtpRequest sendOtpRequest = new SendOtpRequest(txtChkEmail.getText().toString());
Call<SendOtpResponse> call = apiService.sendOtp(sendOtpRequest);
call.enqueue(new Callback<SendOtpResponse>() {
@Override
public void onResponse(Call<SendOtpResponse> call, Response<SendOtpResponse> response) {
}
@Override
public void onFailure(Call<SendOtpResponse> call, Throwable t) {
Toast.makeText(CheckEmailPage.this, "Failed Send Verification Code", Toast.LENGTH_SHORT).show();
}
});
}
public void redirectInsertPass(String userCateg) {
Intent intent = new Intent(this, InsertPasswordPage.class);
String email = txtChkEmail.getText().toString();
intent.putExtra("emailInsertPassword", email);
intent.putExtra("userCateg", userCateg);
startActivity(intent);
}
public void redirectInsertOtp(String statusCode) {
sendOtp();
String email = txtChkEmail.getText().toString();
Intent intent = new Intent(this, InsertOtpPage.class);
intent.putExtra("statusCode", statusCode);
intent.putExtra("email", email);
startActivity(intent);
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.interfaces;
public interface OnInvestorFragmentPassing {
void sendInvPersonalName(String investorPersonalName);
void sendInvDob(String investorDob);
void sendInvGender(String investorGender);
void sendInvNikNumber(String investorNikNumber);
void sendInvPhotoKtp(String investorPhotoKtp);
//void sendInvEmail(String investorEmail);
void sendInvPhone(String investorPhone);
void sendInvAddress(String investorAddress);
void sendInvProvince(String investorProvince);
void sendInvCity(String investorCity);
void sendInvDistrict(String investorDistrict);
void sendInvSubDistrict(String investorSubDistrict);
void sendInvPostCode(String investorPostCode);
void sendInvOccupation(String investorOccupation);
//void sendInvCompanyName(String investorCompanyName);
void sendInvCompanyAddress(String investorCompanyAddress);
void sendInvCompanyProvince(String investorCompanyProvince);
void sendInvCompanyCity(String investorCompanyCity);
void sendInvCompanyDistrict(String investorCompanyDistrict);
void sendInvCompanySubDistrict(String investorCompanySubDistrict);
void sendInvCompanyPostCode(String investorCompanyPostCode);
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.CheckEmail;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by rafi.farabi on 3/10/2018.
*/
public class CheckEmailResponse {
public CheckEmailResponse(Integer code, String message, CheckEmailResponseData data) {
this.code = code;
this.message = message;
this.data = data;
}
@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private CheckEmailResponseData data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public CheckEmailResponseData getData() {
return data;
}
public void setData(CheckEmailResponseData data) {
this.data = data;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.registration.fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import ivb.com.materialstepper.stepperFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.interfaces.OnFragmentPassing;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetCityResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetCityResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKecamatanResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKecamatanResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKelurahanResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKelurahanResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetProvinceResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetProvinceResponseData;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
import static android.content.ContentValues.TAG;
/**
* Created by rafi.farabi on 3/21/2018.
*/
public class TokoAlamatStep extends stepperFragment {
//private String PROVINCE_ID, CITY_ID, KECAMATAN_ID, KELURAHAN_ID;
@BindView(R.id.txtAlamat)
EditText ownerAddress;
@BindView(R.id.txtProvince)
Spinner ownerProvince;
@BindView(R.id.txtCity)
Spinner ownerCity;
@BindView(R.id.txtKecamatan)
Spinner ownerDistrict;
@BindView(R.id.txtKelurahan)
Spinner ownerSubDistrict;
@BindView(R.id.txtPostCode)
EditText ownerPostalCode;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
public OnFragmentPassing mOnFragmentPassing;
private String getProvinceId, getCityId, getDistrictId, getSubDistrictId;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.alamat_step, container, false);
ButterKnife.bind(this, view);
initProvinceSpinner();
return view;
}
public void initProvinceSpinner() {
Call<GetProvinceResponse> call = apiService.getProvinceResponse();
call.enqueue(new Callback<GetProvinceResponse>() {
@Override
public void onResponse(Call<GetProvinceResponse> call, Response<GetProvinceResponse> response) {
final ArrayList<GetProvinceResponseData> provinceResponseData = response.body().getData();
List<String> listProvinceNameSpinner = new ArrayList<String>();
for(int i = 0; i<provinceResponseData.size();i++){
listProvinceNameSpinner.add(provinceResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listProvinceNameSpinner);
ownerProvince.setAdapter(adapter);
ownerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initCitySpinner(provinceResponseData.get(ownerProvince.getSelectedItemPosition()).getId());
getProvinceId = provinceResponseData.get(ownerProvince.getSelectedItemPosition()).getId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetProvinceResponse> call, Throwable t) {
}
});
}
public void initCitySpinner(String id){
Call<GetCityResponse> call = apiService.getCityResponse(id);
call.enqueue(new Callback<GetCityResponse>() {
@Override
public void onResponse(Call<GetCityResponse> call, Response<GetCityResponse> response) {
final ArrayList<GetCityResponseData> cityResponseData = response.body().getData();
List<String> listCityNameSpinner = new ArrayList<String>();
for(int i = 0; i<cityResponseData.size();i++){
listCityNameSpinner.add(cityResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listCityNameSpinner);
ownerCity.setAdapter(adapter);
ownerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initKecamatanSpinner(cityResponseData.get(ownerCity.getSelectedItemPosition()).getId());
getCityId = cityResponseData.get(ownerCity.getSelectedItemPosition()).getId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetCityResponse> call, Throwable t) {
}
});
}
public void initKecamatanSpinner(String id){
Call<GetKecamatanResponse> call = apiService.getKecamatanResponse(id);
call.enqueue(new Callback<GetKecamatanResponse>() {
@Override
public void onResponse(Call<GetKecamatanResponse> call, Response<GetKecamatanResponse> response) {
final ArrayList<GetKecamatanResponseData> kecamatanResponseData = response.body().getData();
List<String> listKecamatanNameSpinner = new ArrayList<String>();
for(int i = 0; i<kecamatanResponseData.size();i++){
listKecamatanNameSpinner.add(kecamatanResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listKecamatanNameSpinner);
ownerDistrict.setAdapter(adapter);
ownerDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initKelurahanSpinner(kecamatanResponseData.get(ownerDistrict.getSelectedItemPosition()).getId());
getDistrictId = kecamatanResponseData.get(ownerDistrict.getSelectedItemPosition()).getId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetKecamatanResponse> call, Throwable t) {
}
});
}
public void initKelurahanSpinner(String id){
Call<GetKelurahanResponse> call = apiService.getKelurahanResponse(id);
call.enqueue(new Callback<GetKelurahanResponse>() {
@Override
public void onResponse(Call<GetKelurahanResponse> call, Response<GetKelurahanResponse> response) {
final ArrayList<GetKelurahanResponseData> kelurahanResponseData = response.body().getData();
List<String> listKelurahanNameSpinner = new ArrayList<String>();
for(int i = 0; i<kelurahanResponseData.size();i++){
listKelurahanNameSpinner.add(kelurahanResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, listKelurahanNameSpinner);
ownerSubDistrict.setAdapter(adapter);
ownerSubDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//initCitySpinner(cityResponseData.get(cityToko.getSelectedItemPosition()).getId());
getSubDistrictId = kelurahanResponseData.get(ownerSubDistrict.getSelectedItemPosition()).getId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetKelurahanResponse> call, Throwable t) {
}
});
}
@Override
public boolean onNextButtonHandler() {
String mOwnerAlamat = ownerAddress.getText().toString();
String mOwnerProvince = getProvinceId;
String mOwnerCity = getCityId;
String mOwnerDistrict = getDistrictId;
String mOwnerSubDistrict = getSubDistrictId;
String mOwnerPostalCode = ownerPostalCode.getText().toString();
mOnFragmentPassing.sendAddress(mOwnerAlamat);
mOnFragmentPassing.sendAddressProvince(mOwnerProvince);
mOnFragmentPassing.sendAddressCity(mOwnerCity);
mOnFragmentPassing.sendAddressDistrict(mOwnerDistrict);
mOnFragmentPassing.sendAddressSubDistrict(mOwnerSubDistrict);
mOnFragmentPassing.sendAddressPostalCode(mOwnerPostalCode);
return true;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnFragmentPassing = (OnFragmentPassing) getActivity();
}catch(ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage() );
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.admin.UpdateUkmType;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetCityResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetCityResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKecamatanResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKecamatanResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKelurahanResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetKelurahanResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetProvinceResponse;
import ukmutilizer.project.com.ukm_utilizer.model.Address.GetProvinceResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.EditProfile.GetAllProfileResponse;
import ukmutilizer.project.com.ukm_utilizer.model.EditProfile.SubmitEditProfileRequest;
import ukmutilizer.project.com.ukm_utilizer.model.EditProfile.SubmitEditProfileResponse;
import ukmutilizer.project.com.ukm_utilizer.model.UploadImage.UploadImageResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class EditProfile extends AppCompatActivity {
@BindView(R.id.editProfileEmail)
EditText editProfileEmail;
@BindView(R.id.editProfileNik)
EditText editProfileNik;
@BindView(R.id.editProfileDob)
EditText editProfileDob;
@BindView(R.id.editProfileUsernme)
EditText editProfileUsernme;
@BindView(R.id.genderRegist)
RadioGroup genderRegist;
@BindView(R.id.editProfilePhone)
EditText editProfilePhone;
@BindView(R.id.editProfileAddress)
EditText editProfileAddress;
@BindView(R.id.editProfileProvince)
Spinner editProfileProvince;
@BindView(R.id.editProfileCity)
Spinner editProfileCity;
@BindView(R.id.editProfileKecamatan)
Spinner editProfileKecamatan;
@BindView(R.id.editProfileKelurahan)
Spinner editProfileKelurahan;
@BindView(R.id.editProfilePostCode)
EditText editProfilePostCode;
@BindView(R.id.getDataEditPhotoBtn)
Button getDataEditPhotoBtn;
@BindView(R.id.imageEditEktp)
ImageView imageEditEktp;
@BindView(R.id.sumitEditProfile)
Button sumitEditProfile;
String userId, category;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private static final int CAMERA_REQUEST_CODE = 1;
private static final String MEDIA_TYPE_JPG = "image/jpeg";
private static final int SELECT_FILE = 0;
private String IMAGE_PATH;
DatePickerDialog datePickerDialog;
Calendar calendar;
private int mYear, mMonth, mDay;
private Integer getProvinceId, getCityId, getDistrictId, getSubDistrictId;
private int getSelectedProvinceId;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ukm_dashboard, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.logout:
logoutDialog();
return true;
case R.id.edit_profile:
Toast.makeText(this, "Disable", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void logoutDialog(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Logout");
alertDialog.setMessage("Apakah Anda Yakin Untuk Logout?");
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
redirectCheckEmail();
//dialog.dismiss();
}
});
alertDialog.show();
}
public void redirectCheckEmail(){
Intent intent = new Intent(this, CheckEmailPage.class);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
ButterKnife.bind(this);
userId = ConstantVar.userId;
category = ConstantVar.category;
initProvinceSpinner();
getAllProfile(userId);
editProfileDob.setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(View v) {
calendar = Calendar.getInstance();
mYear = calendar.get(java.util.Calendar.YEAR);
mMonth = calendar.get(java.util.Calendar.MONTH);
mDay = calendar.get(java.util.Calendar.DAY_OF_MONTH);
datePickerDialog = new DatePickerDialog(EditProfile.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(android.widget.DatePicker view, int year, int month, int dayOfMonth) {
String dateSet = year + "-" + (month+1) + "-" +dayOfMonth;
editProfileDob.setText(dateSet);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
}
public void getAllProfile(String userId){
Call<GetAllProfileResponse> call = apiService.getAllProfile(userId);
call.enqueue(new Callback<GetAllProfileResponse>() {
@Override
public void onResponse(Call<GetAllProfileResponse> call, Response<GetAllProfileResponse> response) {
if(response.body().getCode().equals(1000)){
String outputDob = null;
String dob = response.body().getData().getDateofbirth();
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date dateDob = inputDateFormat.parse(dob);
outputDob = outputDateFormat.format(dateDob);
} catch (ParseException e) {
e.printStackTrace();
}
editProfileEmail.setText(response.body().getData().getEmail());
editProfileNik.setText(response.body().getData().getNikNumber());
editProfileDob.setText(outputDob);
editProfileUsernme.setText(response.body().getData().getName());
//genderRegist.setText(response.body().getData().getNikNumber());
editProfilePhone.setText(response.body().getData().getPhoneNumber());
editProfileAddress.setText(response.body().getData().getAddress());
//editProfileProvince.setText(response.body().getData().getNikNumber());
//editProfileCity.setText(response.body().getData().getNikNumber());
//editProfileKecamatan.setText(response.body().getData().getNikNumber());
// editProfileKelurahan.setText(response.body().getData().getNikNumber());
editProfilePostCode.setText(response.body().getData().getPostcode().toString());
// imageEditEktp.setText(response.body().getData().getNikNumber());
if(response.body().getData().getGender().equals(1)){
genderRegist.check(R.id.genderL);
}else if(response.body().getData().getGender().equals(2)){
genderRegist.check(R.id.genderL);
}
String getPhoto = "https://s3.us-east-2.amazonaws.com/ukm-document-storage/07cc3c56-bcb9-41f8-938f-6e2e7273da9b";
if(response.body().getData().getPhotoKtp() !=""){
Picasso.get().load(response.body().getData().getPhotoKtp()).into(imageEditEktp);
}else{
Picasso.get().load(getPhoto).into(imageEditEktp);
}
}
}
@Override
public void onFailure(Call<GetAllProfileResponse> call, Throwable t) {
}
});
}
public void initProvinceSpinner() {
Call<GetProvinceResponse> call = apiService.getProvinceResponse();
call.enqueue(new Callback<GetProvinceResponse>() {
@Override
public void onResponse(Call<GetProvinceResponse> call, Response<GetProvinceResponse> response) {
final ArrayList<GetProvinceResponseData> provinceResponseData = response.body().getData();
List<String> listProvinceNameSpinner = new ArrayList<String>();
for(int i = 0; i<provinceResponseData.size();i++){
listProvinceNameSpinner.add(provinceResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditProfile.this, android.R.layout.simple_spinner_dropdown_item, listProvinceNameSpinner);
editProfileProvince.setAdapter(adapter);
editProfileProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initCitySpinner(provinceResponseData.get(editProfileProvince.getSelectedItemPosition()).getId());
getProvinceId = Integer.valueOf(provinceResponseData.get(editProfileProvince.getSelectedItemPosition()).getId());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetProvinceResponse> call, Throwable t) {
}
});
}
public void initCitySpinner(String id){
Call<GetCityResponse> call = apiService.getCityResponse(id);
call.enqueue(new Callback<GetCityResponse>() {
@Override
public void onResponse(Call<GetCityResponse> call, Response<GetCityResponse> response) {
final ArrayList<GetCityResponseData> cityResponseData = response.body().getData();
List<String> listCityNameSpinner = new ArrayList<String>();
for(int i = 0; i<cityResponseData.size();i++){
listCityNameSpinner.add(cityResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditProfile.this, android.R.layout.simple_spinner_dropdown_item, listCityNameSpinner);
editProfileCity.setAdapter(adapter);
editProfileCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initKecamatanSpinner(cityResponseData.get(editProfileCity.getSelectedItemPosition()).getId());
getCityId = Integer.valueOf(cityResponseData.get(editProfileCity.getSelectedItemPosition()).getId());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetCityResponse> call, Throwable t) {
}
});
}
public void initKecamatanSpinner(String id){
Call<GetKecamatanResponse> call = apiService.getKecamatanResponse(id);
call.enqueue(new Callback<GetKecamatanResponse>() {
@Override
public void onResponse(Call<GetKecamatanResponse> call, Response<GetKecamatanResponse> response) {
final ArrayList<GetKecamatanResponseData> kecamatanResponseData = response.body().getData();
List<String> listKecamatanNameSpinner = new ArrayList<String>();
for(int i = 0; i<kecamatanResponseData.size();i++){
listKecamatanNameSpinner.add(kecamatanResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditProfile.this, android.R.layout.simple_spinner_dropdown_item, listKecamatanNameSpinner);
editProfileKecamatan.setAdapter(adapter);
editProfileKecamatan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
initKelurahanSpinner(kecamatanResponseData.get(editProfileKecamatan.getSelectedItemPosition()).getId());
getDistrictId = Integer.valueOf(kecamatanResponseData.get(editProfileKecamatan.getSelectedItemPosition()).getId());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetKecamatanResponse> call, Throwable t) {
}
});
}
public void initKelurahanSpinner(String id){
Call<GetKelurahanResponse> call = apiService.getKelurahanResponse(id);
call.enqueue(new Callback<GetKelurahanResponse>() {
@Override
public void onResponse(Call<GetKelurahanResponse> call, Response<GetKelurahanResponse> response) {
final ArrayList<GetKelurahanResponseData> kelurahanResponseData = response.body().getData();
List<String> listKelurahanNameSpinner = new ArrayList<String>();
for(int i = 0; i<kelurahanResponseData.size();i++){
listKelurahanNameSpinner.add(kelurahanResponseData.get(i).getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(EditProfile.this, android.R.layout.simple_spinner_dropdown_item, listKelurahanNameSpinner);
editProfileKelurahan.setAdapter(adapter);
editProfileKelurahan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//initCitySpinner(cityResponseData.get(cityToko.getSelectedItemPosition()).getId());
getSubDistrictId = Integer.valueOf(kelurahanResponseData.get(editProfileKelurahan.getSelectedItemPosition()).getId());
editProfilePostCode.setText(kelurahanResponseData.get(editProfileKelurahan.getSelectedItemPosition()).getPostal_code());
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
@Override
public void onFailure(Call<GetKelurahanResponse> call, Throwable t) {
}
});
}
@OnClick(R.id.getDataEditPhotoBtn)
public void getImage(){
CharSequence menu[] = new CharSequence[]{"Take From Galery", "Open Camera"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0){
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
}else if(i == 1){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context applicationContext = this;
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST_CODE) {
Bundle bundle = data.getExtras();
final Bitmap bitmap = (Bitmap) bundle.get("data");
imageEditEktp.setImageBitmap(bitmap);
Uri tempUri = getImageUri(applicationContext, bitmap);
uploadFile(tempUri);
//File file = new File(get);
//RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType()))
} else if (requestCode == SELECT_FILE) {
Uri selectedImage = data.getData();
imageEditEktp.setImageURI(selectedImage);
uploadFile(selectedImage);
Log.d("selected image : ", selectedImage.toString());
} else {
Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadFile(Uri fileUri){
File imageFile = new File(getRealPathFromURI(fileUri));
String realPath = imageFile.getAbsolutePath()+"/"+imageFile.getName();
RequestBody requestFile = RequestBody.create(MediaType.parse(MEDIA_TYPE_JPG), imageFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", realPath, requestFile);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<UploadImageResponse> call = apiService.uploadImage(body);
call.enqueue(new Callback<UploadImageResponse>() {
@Override
public void onResponse(Call<UploadImageResponse> call, Response<UploadImageResponse> response) {
if(response.isSuccessful()) {
String getUrlResponse = response.body().getMessage();
IMAGE_PATH = getUrlResponse;
Toast.makeText(EditProfile.this, "Successfully Upload File", Toast.LENGTH_SHORT).show();
//submitUpdateUkm.setVisibility(View.VISIBLE);
//finish();
}else{
Log.d("Message Response : ", response.body().getMessage());
Toast.makeText(EditProfile.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UploadImageResponse> call, Throwable t) {
Toast.makeText(EditProfile.this, "Something went wrong", Toast.LENGTH_SHORT).show();
Log.e("Failure : ", String.valueOf(t));
}
});
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(EditProfile.this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
@OnClick(R.id.sumitEditProfile)
public void submitEditProfile(){
String gender = null;
if(genderRegist.getCheckedRadioButtonId() == R.id.genderL){
gender = "l";
}else if(genderRegist.getCheckedRadioButtonId() == R.id.genderP){
gender = "2";
}
String userid = ConstantVar.userId;
String categ = ConstantVar.category;
String mEditProfileEmail = editProfileEmail.getText().toString();
String mEditProfileNik = editProfileNik.getText().toString();
String mEditProfileDob = editProfileDob.getText().toString();
String mEditProfileUsernme = editProfileUsernme.getText().toString();
String mEditGenderRegist = gender;
String mEditProfilePhone = editProfilePhone.getText().toString();
String mEditProfileAddress = editProfileAddress.getText().toString();
Integer mEditProfileProvince = getProvinceId;
Integer mEditProfileCity = getCityId;
Integer mEditProfileKecamatan = getDistrictId;
Integer mEditProfileKelurahan = getSubDistrictId;
Integer mEditProfilePostCode = Integer.parseInt( editProfilePostCode.getText().toString());
//String mEditProfileEmail = editProfileEmail.getText().toString();
SubmitEditProfileRequest submitEditProfileRequest = new SubmitEditProfileRequest(userId, category, mEditProfileUsernme, mEditProfileDob
, mEditGenderRegist, mEditProfileNik, IMAGE_PATH, mEditProfileEmail, mEditProfilePhone, mEditProfileAddress, mEditProfileProvince,
mEditProfileCity, mEditProfileKecamatan, mEditProfileKelurahan, mEditProfilePostCode);
Call<SubmitEditProfileResponse> call = apiService.submitEditProfile(submitEditProfileRequest);
call.enqueue(new Callback<SubmitEditProfileResponse>() {
@Override
public void onResponse(Call<SubmitEditProfileResponse> call, Response<SubmitEditProfileResponse> response) {
if(response.body().getCode().equals(1000)){
Toast.makeText(EditProfile.this, response.body().getData(), Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onFailure(Call<SubmitEditProfileResponse> call, Throwable t) {
}
});
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.Registration;
import java.util.ArrayList;
/**
* Created by rafi.farabi on 4/5/2018.
*/
public class UkmRegistrationRequest {
private String category;
private String name;
private String dateofbirth;
private String gender;
private String nik_number;
private String photo_ktp;
private String email;
private String phone_number;
private String address;
private String province;
private String city;
private String district;
private String sub_district;
private String postcode;
private String ukm_name;
private String ukm_type;
private String photo_ukm;
private String ukm_address;
private String ukm_province;
private String ukm_city;
private String ukm_district;
private String ukm_sub_district;
private String ukm_postcode;
public UkmRegistrationRequest(String category, String name, String dateofbirth, String gender, String nikNumber, String photoKtp, String email, String phoneNumber, String address, String province, String city, String district, String subDistrict, String postcode, String ukmName, String ukmType, String photo_ukm, String ukmAddress, String ukmProvince, String ukmCity, String ukmDistrict, String ukmSubDistrict, String ukmPostcode) {
this.category = category;
this.name = name;
this.dateofbirth = dateofbirth;
this.gender = gender;
this.nik_number = nikNumber;
this.photo_ktp = photoKtp;
this.email = email;
this.phone_number = phoneNumber;
this.address = address;
this.province = province;
this.city = city;
this.district = district;
this.sub_district = subDistrict;
this.postcode = postcode;
this.ukm_name = ukmName;
this.ukm_type = ukmType;
this.ukm_address = ukmAddress;
this.ukm_province = ukmProvince;
this.ukm_city = ukmCity;
this.ukm_district = ukmDistrict;
this.ukm_sub_district = ukmSubDistrict;
this.ukm_postcode = ukmPostcode;
this.photo_ukm = photo_ukm;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDateofbirth() {
return dateofbirth;
}
public void setDateofbirth(String dateofbirth) {
this.dateofbirth = dateofbirth;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNikNumber() {
return nik_number;
}
public void setNikNumber(String nikNumber) {
this.nik_number = nikNumber;
}
public String getPhotoKtp() {
return photo_ktp;
}
public void setPhotoKtp(String photoKtp) {
this.photo_ktp = photoKtp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phone_number;
}
public void setPhoneNumber(String phoneNumber) {
this.phone_number = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getSubDistrict() {
return sub_district;
}
public void setSubDistrict(String subDistrict) {
this.sub_district = subDistrict;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getUkmName() {
return ukm_name;
}
public void setUkmName(String ukmName) {
this.ukm_name = ukmName;
}
public String getUkmType() {
return ukm_type;
}
public void setUkmType(String ukmType) {
this.ukm_type = ukmType;
}
public String getUkmAddress() {
return ukm_address;
}
public void setUkmAddress(String ukmAddress) {
this.ukm_address = ukmAddress;
}
public String getUkmProvince() {
return ukm_province;
}
public void setUkmProvince(String ukmProvince) {
this.ukm_province = ukmProvince;
}
public String getUkmCity() {
return ukm_city;
}
public void setUkmCity(String ukmCity) {
this.ukm_city = ukmCity;
}
public String getUkmDistrict() {
return ukm_district;
}
public void setUkmDistrict(String ukmDistrict) {
this.ukm_district = ukmDistrict;
}
public String getUkmSubDistrict() {
return ukm_sub_district;
}
public void setUkmSubDistrict(String ukmSubDistrict) {
this.ukm_sub_district = ukmSubDistrict;
}
public String getUkmPostcode() {
return ukm_postcode;
}
public void setUkmPostcode(String ukmPostcode) {
this.ukm_postcode = ukmPostcode;
}
public String getPhoto_ukm() {
return photo_ukm;
}
public void setPhoto_ukm(String photo_ukm) {
this.photo_ukm = photo_ukm;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.admin;
import android.app.AlertDialog;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.admin.AdminDashboardFragment.AdminManageParam;
import ukmutilizer.project.com.ukm_utilizer.model.ManageParamUkmType.ManageUkmTypeRequest;
import ukmutilizer.project.com.ukm_utilizer.model.ManageParamUkmType.ManageParamResponse;
import ukmutilizer.project.com.ukm_utilizer.model.UploadImage.UploadImageResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class UpdateUkmType extends AppCompatActivity {
@BindView(R.id.updParamUkmType)
EditText updParamUkmType;
@BindView(R.id.btnUpdUkmType)
Button btnUpdUkmType;
@BindView(R.id.updParamUkmIcon)
ImageView updParamUkmIcon;
@BindView(R.id.submitUpdateUkm)
Button submitUpdateUkm;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private android.support.v4.app.Fragment fragment;
private static final String MEDIA_TYPE_JPG = "image/jpeg";
private static final int SELECT_FILE = 0;
private String IMAGE_PATH;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_manageparam_update_ukm);
ButterKnife.bind(this);
final int getUkmTypeId = getIntent().getIntExtra("manageUkmTypeId", 0);
String getUkmTitle = getIntent().getStringExtra("manageUkmTitle");
String getUkmIcon = getIntent().getStringExtra("manageUkmIcon");
IMAGE_PATH = getUkmIcon;
updParamUkmType.setText(getUkmTitle);
String getPhoto = "https://s3.us-east-2.amazonaws.com/ukm-document-storage/07cc3c56-bcb9-41f8-938f-6e2e7273da9b";
if(!getUkmIcon.equals("")){
Picasso.get().load(getUkmIcon).into(updParamUkmIcon);
}else{
Picasso.get().load(getPhoto).into(updParamUkmIcon);
}
submitUpdateUkm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setSubmitUpdateUkm(getUkmTypeId);
}
});
}
@OnClick(R.id.btnUpdUkmType)
public void getImage(){
CharSequence menu[] = new CharSequence[]{"Take From Galery"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a Picture");
builder.setItems(menu, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, SELECT_FILE);
}
});
builder.show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Context applicationContext = this;
Uri selectedImage = data.getData();
updParamUkmIcon.setImageURI(selectedImage);
submitUpdateUkm.setVisibility(View.INVISIBLE);
uploadFile(selectedImage);
Log.d("selected image : ", selectedImage.toString());
}
private void uploadFile(Uri fileUri){
File imageFile = new File(getRealPathFromURI(fileUri));
String realPath = imageFile.getAbsolutePath()+"/"+imageFile.getName();
RequestBody requestFile = RequestBody.create(MediaType.parse(MEDIA_TYPE_JPG), imageFile);
MultipartBody.Part body = MultipartBody.Part.createFormData("file", realPath, requestFile);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<UploadImageResponse> call = apiService.uploadImage(body);
call.enqueue(new Callback<UploadImageResponse>() {
@Override
public void onResponse(Call<UploadImageResponse> call, Response<UploadImageResponse> response) {
if(response.isSuccessful()) {
String getUrlResponse = response.body().getMessage();
IMAGE_PATH = getUrlResponse;
Toast.makeText(UpdateUkmType.this, "Successfully Upload File", Toast.LENGTH_SHORT).show();
submitUpdateUkm.setVisibility(View.VISIBLE);
}else{
Log.d("Message Response : ", response.body().getMessage());
Toast.makeText(UpdateUkmType.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UploadImageResponse> call, Throwable t) {
Toast.makeText(UpdateUkmType.this, "Something went wrong", Toast.LENGTH_SHORT).show();
Log.e("Failure : ", String.valueOf(t));
}
});
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(UpdateUkmType.this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
public void setSubmitUpdateUkm(int getUkmTypeId){
String updatedTitle = updParamUkmType.getText().toString();
String updatedIcon = IMAGE_PATH;
Toast.makeText(this, updatedTitle + " " + updatedIcon, Toast.LENGTH_SHORT).show();
if(getUkmTypeId == 0){
ManageUkmTypeRequest manageUkmTypeRequest = new ManageUkmTypeRequest(getUkmTypeId, updatedTitle, updatedIcon);
Call<ManageParamResponse> call = apiService.insertUkmType(manageUkmTypeRequest);
call.enqueue(new Callback<ManageParamResponse>() {
@Override
public void onResponse(Call<ManageParamResponse> call, Response<ManageParamResponse> response) {
Toast.makeText(UpdateUkmType.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
Bundle admManageParam = new Bundle();
//homeBundle.putString("viewUkmId", UkmID);
fragment = new AdminManageParam();
fragment.setArguments(admManageParam);
finish();
}
@Override
public void onFailure(Call<ManageParamResponse> call, Throwable t) {
Toast.makeText(UpdateUkmType.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}else{
ManageUkmTypeRequest manageUkmTypeRequest = new ManageUkmTypeRequest(getUkmTypeId, updatedTitle, updatedIcon);
Call<ManageParamResponse> call = apiService.updateUkmType(manageUkmTypeRequest);
call.enqueue(new Callback<ManageParamResponse>() {
@Override
public void onResponse(Call<ManageParamResponse> call, Response<ManageParamResponse> response) {
Toast.makeText(UpdateUkmType.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
Bundle admManageParam = new Bundle();
//homeBundle.putString("viewUkmId", UkmID);
fragment = new AdminManageParam();
fragment.setArguments(admManageParam);
finish();
}
@Override
public void onFailure(Call<ManageParamResponse> call, Throwable t) {
Toast.makeText(UpdateUkmType.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.Registration;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by rafi.farabi on 4/8/2018.
*/
public class UkmRegistrationResponse {
@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private UkmRegistrationResponseData data;
public UkmRegistrationResponse(Integer code, String message, UkmRegistrationResponseData data) {
this.code = code;
this.message = message;
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public UkmRegistrationResponseData getData() {
return data;
}
public void setData(UkmRegistrationResponseData data) {
this.data = data;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.InsertNewPeriod;
public class InsertNewPeriodRequest {
private String ukm_id;
private String start_date;
private String end_date;
private Integer amount;
public InsertNewPeriodRequest(String ukm_id, String start_date, String end_date, Integer amount) {
this.ukm_id = ukm_id;
this.start_date = start_date;
this.end_date = end_date;
this.amount = amount;
}
public String getUkm_id() {
return ukm_id;
}
public void setUkm_id(String ukm_id) {
this.ukm_id = ukm_id;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getEnd_date() {
return end_date;
}
public void setEnd_date(String end_date) {
this.end_date = end_date;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.InvestorOfferingFunds;
public class InvestorOfferingFundsRequest {
private String investor_id;
private String ukm_id;
private int funds;
private int installment;
private String interest;
private String notes;
public InvestorOfferingFundsRequest(String investor_id, String ukm_id, int funds, int installment, String interest, String notes) {
this.investor_id = investor_id;
this.ukm_id = ukm_id;
this.funds = funds;
this.installment = installment;
this.interest = interest;
this.notes = notes;
}
public String getInvestor_id() {
return investor_id;
}
public void setInvestor_id(String investor_id) {
this.investor_id = investor_id;
}
public String getUkm_id() {
return ukm_id;
}
public void setUkm_id(String ukm_id) {
this.ukm_id = ukm_id;
}
public int getFunds() {
return funds;
}
public void setFunds(int funds) {
this.funds = funds;
}
public int getInstallment() {
return installment;
}
public void setInstallment(int installment) {
this.installment = installment;
}
public String getInterest() {
return interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.lib;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class String2DateFormatter {
/*private String pattern;
private String originalDate;
private Date date;
public String2DateFormatter(String pattern, String originalDate, Date date) {
this.pattern = pattern;
this.originalDate = originalDate;
this.date = date;
}*/
public String dateFormatter(String originalDate, String inputFormat, String outputFormat) throws ParseException {
DateFormat output = new SimpleDateFormat(outputFormat);
DateFormat input = new SimpleDateFormat(inputFormat);
String inputText = originalDate;
Date date = input.parse(inputText);
String outputText = outputFormat.format(String.valueOf(date));
return outputText;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.model.UkmPublishPeriod.UkmPublishPeriodResponse;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter.UkmViewDataDetailAdapter;
import ukmutilizer.project.com.ukm_utilizer.constant_var.ConstantVar;
import ukmutilizer.project.com.ukm_utilizer.model.InsertPeriodDetail.InsertPeriodDetailRequest;
import ukmutilizer.project.com.ukm_utilizer.model.InsertPeriodDetail.InsertPeriodDetailResponse;
import ukmutilizer.project.com.ukm_utilizer.model.ReportDetail.ViewReportDetailRequest;
import ukmutilizer.project.com.ukm_utilizer.model.ReportDetail.ViewReportDetailResponse;
import ukmutilizer.project.com.ukm_utilizer.model.ReportDetail.ViewReportDetailResponseDataList;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
/**
* below class isn't fragment
* below class handle activity for add detail period popup
*/
public class UkmDashboardViewDetail extends AppCompatActivity {
@BindView(R.id.txtViewDetailStartDate)
EditText txtViewDetailStartDate;
@BindView(R.id.txtViewDetailEndDate)
EditText txtViewDetailEndDate;
@BindView(R.id.txtViewDetailFund)
EditText txtViewDetailFund;
@BindView(R.id.ukmViewDetailList)
ListView ukmViewDetailList;
@BindView(R.id.btnAddViewDetail)
Button btnAddViewDetail;
@BindView(R.id.btnPublishViewDetail)
Button btnPublishViewDetail;
EditText txtViewDetailAddFund;
EditText txtViewDetailAddDesc;
EditText txtViewDetailAddDate;
RadioGroup txtViewDetailAddType;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
String ukmId;
String ukmReportId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_dashboard_view_detail);
ButterKnife.bind(this);
ukmId = getIntent().getExtras().getString("viewDetailUkmId");
ukmReportId = getIntent().getExtras().getString("viewDetailReportId");
btnPublishViewDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
publishViewDetail();
}
});
btnAddViewDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addViewDetailDialog();
}
});
//Toast.makeText(this, ConstantVar.category, Toast.LENGTH_SHORT).show();
String getCategory = ConstantVar.category;
if(getCategory.equals("2")){
btnAddViewDetail.setVisibility(View.INVISIBLE);
btnPublishViewDetail.setVisibility(View.INVISIBLE);
}
getViewDetailPeriod(ukmId, ukmReportId);
}
public void publishViewDetail(){
Call<UkmPublishPeriodResponse> call = apiService.publishPeriod(ukmReportId, ukmId);
call.enqueue(new Callback<UkmPublishPeriodResponse>() {
@Override
public void onResponse(Call<UkmPublishPeriodResponse> call, Response<UkmPublishPeriodResponse> response) {
Toast.makeText(UkmDashboardViewDetail.this, "Successfully Publish", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onFailure(Call<UkmPublishPeriodResponse> call, Throwable t) {
Toast.makeText(UkmDashboardViewDetail.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
public void getViewDetailPeriod(final String ukmId, final String ukmReportId) {
ViewReportDetailRequest viewReportDetailRequest = new ViewReportDetailRequest(ukmId, ukmReportId);
Call<ViewReportDetailResponse> call = apiService.viewReportDetail(viewReportDetailRequest);
call.enqueue(new Callback<ViewReportDetailResponse>() {
@Override
public void onResponse(Call<ViewReportDetailResponse> call, Response<ViewReportDetailResponse> response) {
String outputDateStart = null;
String outputDateEnd = null;
String periodeStart = response.body().getData().getStartDate();
String periodeEnd = response.body().getData().getEndDate();
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date dateStart = inputDateFormat.parse(periodeStart);
Date dateEnd = inputDateFormat.parse(periodeEnd);
outputDateStart = outputDateFormat.format(dateStart);
outputDateEnd = outputDateFormat.format(dateEnd);
} catch (ParseException e) {
e.printStackTrace();
}
txtViewDetailStartDate.setText(outputDateStart);
txtViewDetailEndDate.setText(outputDateEnd);
txtViewDetailFund.setText(response.body().getData().getFund().toString());
if (response.body().getCode() == 1000) {
if (response.body().getData().getData() != null) {
final ArrayList<ViewReportDetailResponseDataList> viewReportDetailResponseDataLists = response.body().getData().getData();
ListView listView = findViewById(R.id.ukmViewDetailList);
UkmViewDataDetailAdapter adapter = new UkmViewDataDetailAdapter(viewReportDetailResponseDataLists, UkmDashboardViewDetail.this, ukmId, ukmReportId);
listView.setAdapter(adapter);
}
} else {
Toast.makeText(UkmDashboardViewDetail.this, "Failed Get Detail Report", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ViewReportDetailResponse> call, Throwable t) {
Log.e("error view detail : ", String.valueOf(t));
Toast.makeText(UkmDashboardViewDetail.this, "Error!", Toast.LENGTH_SHORT).show();
}
});
}
public void addViewDetailDialog() {
LayoutInflater inflater = LayoutInflater.from(UkmDashboardViewDetail.this);
View view = inflater.inflate(R.layout.fragment_dashboard_view_detail_add, null, false);
txtViewDetailAddFund = view.findViewById(R.id.txtViewDetailAddFund);
txtViewDetailAddDesc = view.findViewById(R.id.txtViewDetailAddDesc);
txtViewDetailAddDate = view.findViewById(R.id.txtViewDetailAddDate);
txtViewDetailAddType = view.findViewById(R.id.txtViewDetailAddType);
//txtViewDetailAddDate.addTextChangedListener(dateWatcher);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(UkmDashboardViewDetail.this);
alertDialog.setView(view);
alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
insertDetailPeriodList();
dialog.dismiss();
getViewDetailPeriod(ukmId, ukmReportId);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
@SuppressLint("ResourceType")
public void insertDetailPeriodList(){
String periodDetailid = null;
int txtType = 0;
if(txtViewDetailAddType.getCheckedRadioButtonId() == R.id.pengeluaran){
txtType = 1;
}else if(txtViewDetailAddType.getCheckedRadioButtonId() == R.id.pemasukan){
txtType = 2;
}
int fund = Integer.parseInt(txtViewDetailAddFund.getText().toString());
int type = txtType;
String trxDate = txtViewDetailAddDate.getText().toString();
String desc = txtViewDetailAddDesc.getText().toString();
InsertPeriodDetailRequest insertPeriodDetailRequest = new InsertPeriodDetailRequest(periodDetailid, ukmId, ukmReportId, type, fund, trxDate, desc);
Call<InsertPeriodDetailResponse> call = apiService.insertPeriodDetail(insertPeriodDetailRequest);
call.enqueue(new Callback<InsertPeriodDetailResponse>() {
@Override
public void onResponse(Call<InsertPeriodDetailResponse> call, Response<InsertPeriodDetailResponse> response) {
Toast.makeText(UkmDashboardViewDetail.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
getViewDetailPeriod(ukmId, ukmReportId);
}
@SuppressLint("LongLogTag")
@Override
public void onFailure(Call<InsertPeriodDetailResponse> call, Throwable t) {
Toast.makeText(UkmDashboardViewDetail.this, "Error Insert", Toast.LENGTH_SHORT).show();
Log.e("error insert period detail : ", String.valueOf(t));
}
});
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter;
import android.content.Context;
import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment.UkmDashboardViewDetail;
import ukmutilizer.project.com.ukm_utilizer.model.Report.ViewReportResponseData;
public class UkmViewDataAdapter extends BaseAdapter {
private Context context;
private ArrayList<ViewReportResponseData> viewReportResponses;
@Override
public int getCount() {
return viewReportResponses.size();
}
@Override
public Object getItem(int position) {
return viewReportResponses.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public UkmViewDataAdapter(ArrayList<ViewReportResponseData> viewReportResponseData, Context context){
super();
this.viewReportResponses = viewReportResponseData;
this.context = context;
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Toast.makeText(context, "test", Toast.LENGTH_SHORT).show();
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.fragment_dashboard_view_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
String outputDateStart = null;
String outputDateEnd = null;
String periodeStart = viewReportResponses.get(position).getStartDate().toString();
String periodeEnd = viewReportResponses.get(position).getEndDate().toString();
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date dateStart = inputDateFormat.parse(periodeStart);
Date dateEnd = inputDateFormat.parse(periodeEnd);
outputDateStart = outputDateFormat.format(dateStart);
outputDateEnd = outputDateFormat.format(dateEnd);
} catch (ParseException e) {
e.printStackTrace();
}
String viewPeriodeText = outputDateStart + " - " + outputDateEnd;
holder.viewPeriode.setText(viewPeriodeText);
holder.viewFund.setText(viewReportResponses.get(position).getAmount().toString());
holder.ukm_id = viewReportResponses.get(position).getUkmId();
holder.report_id = viewReportResponses.get(position).getId();
return convertView;
}
public class ViewHolder {
public TextView viewPeriode;
public TextView viewFund;
public String ukm_id, report_id;
public ViewHolder(View view){
viewPeriode = view.findViewById(R.id.viewPeriode);
viewFund = view.findViewById(R.id.viewFund);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UkmDashboardViewDetail.class);
String ukmId = ukm_id;
String reportId = report_id;
intent.putExtra("viewDetailUkmId", ukmId);
intent.putExtra("viewDetailReportId", reportId);
v.getContext().startActivity(intent);
}
});
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.admin.AdminDashboardFragment;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.ChooseCategory;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.admin.AdminAdapter.AdminCategParamAdapter;
import ukmutilizer.project.com.ukm_utilizer.admin.AdminAdapter.AdminJobTypeParamAdapter;
import ukmutilizer.project.com.ukm_utilizer.admin.AdminAdapter.AdminUkmTypeParamAdapter;
import ukmutilizer.project.com.ukm_utilizer.admin.UpdateJobType;
import ukmutilizer.project.com.ukm_utilizer.admin.UpdateUkmType;
import ukmutilizer.project.com.ukm_utilizer.model.ChooseCategory.ChooseCategoryResponse;
import ukmutilizer.project.com.ukm_utilizer.model.ChooseCategory.ChooseCategoryResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.GetJobType.GetJobTypeResponse;
import ukmutilizer.project.com.ukm_utilizer.model.GetJobType.GetJobTypeResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.GetUkmType.GetUkmTypeResponse;
import ukmutilizer.project.com.ukm_utilizer.model.GetUkmType.GetUkmTypeResponseData;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter.CategoryDataAdapter;
public class AdminManageParam extends Fragment {
private AdminManageParam.OnFragmentInteractionListener mListener;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private ArrayList<GetUkmTypeResponseData> ukmTypeResponseDataList;
private ArrayList<GetJobTypeResponseData> jobTypeResponseDataList;
private ArrayList<ChooseCategoryResponseData> categResponseDataList;
private AdminUkmTypeParamAdapter adminUkmTypeParamAdapter;
private AdminJobTypeParamAdapter adminJobTypeParamAdapter;
private AdminCategParamAdapter adminCategParamAdapter;
@BindView(R.id.spinnerTableParam)
Spinner spinnerTableParam;
@BindView(R.id.submitManageParam)
Button submitManageParam;
@BindView(R.id.btnCreateNewParam)
Button btnCreateNewParam;
@BindView(R.id.manageParamList)
RecyclerView manageParamList;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_admin_manage_param, container, false);
ButterKnife.bind(this, view);
btnCreateNewParam.setVisibility(View.INVISIBLE);
String[] statusVal = new String[]{
"Ukm Type", "Job Type", "Category"
};
final List<String> statusList = new ArrayList<>(Arrays.asList(statusVal));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(view.getContext(),R.layout.manage_param_spinner_item, statusList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.manage_param_spinner_item);
spinnerTableParam.setAdapter(spinnerArrayAdapter);
submitManageParam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedTableParam = spinnerTableParam.getSelectedItemPosition();
if(selectedTableParam == 0){
getUkmType();
btnCreateNewParam.setVisibility(View.VISIBLE);
btnCreateNewParam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UpdateUkmType.class);
intent.putExtra("manageUkmTypeId", "");
intent.putExtra("manageUkmTitle", "");
intent.putExtra("manageUkmIcon", "");
v.getContext().startActivity(intent);
}
});
}else if(selectedTableParam == 1){
getJobType();
btnCreateNewParam.setVisibility(View.VISIBLE);
btnCreateNewParam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UpdateJobType.class);
intent.putExtra("manageJobTypeId", "");
intent.putExtra("manageJobTitle", "");
v.getContext().startActivity(intent);
}
});
}else if(selectedTableParam == 2){
getCateg();
btnCreateNewParam.setVisibility(View.INVISIBLE);
}
}
});
return view;
}
public void getUkmType(){
Call<GetUkmTypeResponse> call = apiService.getUkmTypeResponse();
call.enqueue(new Callback<GetUkmTypeResponse>() {
@Override
public void onResponse(Call<GetUkmTypeResponse> call, Response<GetUkmTypeResponse> response) {
if (response.body().getData()!=null) {
ukmTypeResponseDataList = response.body().getData();
//recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
adminUkmTypeParamAdapter = new AdminUkmTypeParamAdapter(ukmTypeResponseDataList, getContext());
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getContext());
manageParamList.setLayoutManager(eLayoutManager);
//chooseCategoryRecycler.setItemAnimator(new DefaultItemAnimator());
manageParamList.setAdapter(adminUkmTypeParamAdapter);
}else{
Toast.makeText(getContext(), "TIDAK ADA DATA", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<GetUkmTypeResponse> call, Throwable t) {
Toast.makeText(getContext(), "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
public void getJobType(){
Call<GetJobTypeResponse> call = apiService.getJobTypeResponse();
call.enqueue(new Callback<GetJobTypeResponse>() {
@Override
public void onResponse(Call<GetJobTypeResponse> call, Response<GetJobTypeResponse> response) {
if (response.body().getData()!=null) {
jobTypeResponseDataList = response.body().getData();
//recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
adminJobTypeParamAdapter = new AdminJobTypeParamAdapter(jobTypeResponseDataList, getContext());
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getContext());
manageParamList.setLayoutManager(eLayoutManager);
//chooseCategoryRecycler.setItemAnimator(new DefaultItemAnimator());
manageParamList.setAdapter(adminJobTypeParamAdapter);
}else{
Toast.makeText(getContext(), "TIDAK ADA DATA", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<GetJobTypeResponse> call, Throwable t) {
Toast.makeText(getContext(), "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
public void getCateg(){
Call<ChooseCategoryResponse> call = apiService.getResponse();
call.enqueue(new Callback<ChooseCategoryResponse>() {
@Override
public void onResponse(Call<ChooseCategoryResponse> call, Response<ChooseCategoryResponse> response) {
if (response.body().getData()!=null) {
categResponseDataList = response.body().getData();
//recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
adminCategParamAdapter = new AdminCategParamAdapter(categResponseDataList);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getContext());
manageParamList.setLayoutManager(eLayoutManager);
//chooseCategoryRecycler.setItemAnimator(new DefaultItemAnimator());
manageParamList.setAdapter(adminCategParamAdapter);
}else{
Toast.makeText(getContext(), "TIDAK ADA DATA", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ChooseCategoryResponse> call, Throwable t) {
Log.e("Get Category : ", String.valueOf(t));
Toast.makeText(getContext(), "Failed Get Category", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onStart() {
super.onStart();
try {
mListener = (AdminManageParam.OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.admin.AdminAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.admin.AdminDashboardFragment.AdminSurveyUpdate;
import ukmutilizer.project.com.ukm_utilizer.model.AdminDashboard.AdminHomeResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.AdminViewSurvey.AdminViewSurveyResponseData;
import ukmutilizer.project.com.ukm_utilizer.model.UpdateStatusSurvey.UpdateStatusSurveyRequest;
import ukmutilizer.project.com.ukm_utilizer.model.UpdateStatusSurvey.UpdateStatusSurveyResponse;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class AdminSurveyAdapter extends BaseAdapter {
EditText submitUpdSurveyUkmName;
EditText submitUpdSurveyInvName;
EditText submitUpdSurveyDueDate;
EditText submitUpdSurveyComment;
Spinner submitUpdSurveyStatus;
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
private Context context;
private ArrayList<AdminViewSurveyResponseData> adminViewSurveyResponseData;
@Override
public int getCount() {
return adminViewSurveyResponseData.size();
}
@Override
public Object getItem(int position) {
return adminViewSurveyResponseData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public AdminSurveyAdapter(ArrayList<AdminViewSurveyResponseData> adminViewSurveyResponseData, Context context) {
this.adminViewSurveyResponseData = adminViewSurveyResponseData;
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_admin_update_survey_list, parent, false);
holder = new AdminSurveyAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}else {
holder = (AdminSurveyAdapter.ViewHolder)convertView.getTag();
}
holder.admUpdateSurveyUkmName.setText(adminViewSurveyResponseData.get(position).getUkmName());
holder.admUpdateSurveyUkmOwner.setText(adminViewSurveyResponseData.get(position).getOwnerUkmName());
holder.admUpdateSurveyInvName.setText("Investment from " + adminViewSurveyResponseData.get(position).getInvestorName());
/*String status = "";
if(adminViewSurveyResponseData.get(position).getStatus().equals(1)){
status = "On Progress";
}else if(adminViewSurveyResponseData.get(position).getStatus().equals(2)){
status = "Approved";
}else if(adminViewSurveyResponseData.get(position).getStatus().equals(3)){
status = "Rejected";
}else if(adminViewSurveyResponseData.get(position).getStatus().equals(4)){
status = "Need More Survey";
}*/
holder.admUpdateSurveyStatus.setText(adminViewSurveyResponseData.get(position).getStatus());
holder.offeringId = adminViewSurveyResponseData.get(position).getOfferingId();
holder.ukmName = adminViewSurveyResponseData.get(position).getUkmName();
holder.invName = adminViewSurveyResponseData.get(position).getInvestorName();
//holder.dueDate = adminHomeResponseData.get(position).ge
holder.status = adminViewSurveyResponseData.get(position).getStatus();
return convertView;
}
public void updateSurveyStatusDialog(final String surveyId, final String offeringId, String ukmName, String invName, final String dueDate, final String status, final String comment){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_admin_update_survey_dialog, null, false);
submitUpdSurveyUkmName = view.findViewById(R.id.submitUpdSurveyUkmName);
submitUpdSurveyInvName = view.findViewById(R.id.submitUpdSurveyInvName);
submitUpdSurveyDueDate = view.findViewById(R.id.submitUpdSurveyDueDate);
submitUpdSurveyComment = view.findViewById(R.id.submitUpdSurveyComment);
submitUpdSurveyStatus = view.findViewById(R.id.submitUpdSurveyStatus);
submitUpdSurveyUkmName.setText(ukmName);
submitUpdSurveyInvName.setText(invName);
submitUpdSurveyDueDate.setText(dueDate);
String[] statusVal = new String[]{
"On Progress", "Approved", "Rejected", "More Survey"
};
final List<String> statusList = new ArrayList<>(Arrays.asList(statusVal));
// Initializing an ArrayAdapter
final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(view.getContext(),R.layout.update_survey_spinner_item, statusList);
spinnerArrayAdapter.setDropDownViewResource(R.layout.update_survey_spinner_item);
submitUpdSurveyStatus.setAdapter(spinnerArrayAdapter);
if(status.equals("on progress")){
submitUpdSurveyStatus.setSelection(0);
}else if(status.equals("approved")){
submitUpdSurveyStatus.setSelection(1);
}else if(status.equals("rejected")){
submitUpdSurveyStatus.setSelection(2);
}else if(status.equals("more survey")){
submitUpdSurveyStatus.setSelection(3);
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());
alertDialog.setView(view);
alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*update data*/
final String editedDueDate = submitUpdSurveyDueDate.getText().toString();
final String editedComment = submitUpdSurveyComment.getText().toString();
int selectedStatus = submitUpdSurveyStatus.getSelectedItemPosition();
int statusVal = 0;
if(selectedStatus == 0){
statusVal = 1;
}else if(selectedStatus == 1){
statusVal = 2;
}else if(selectedStatus == 2){
statusVal = 3;
}if(selectedStatus == 3){
statusVal = 4;
}
submitUpdateStatusSurvey(surveyId, offeringId, statusVal, editedComment, editedDueDate);
dialog.dismiss();
//getViewDetailPeriod(ukmId, ukmReportId);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void submitUpdateStatusSurvey(String surveyId, String offeringId, int status, String comment, String dueDate){
//Toast.makeText(context, status + " " + comment + " " + dueDate, Toast.LENGTH_SHORT).show();
UpdateStatusSurveyRequest updateStatusSurveyRequest = new UpdateStatusSurveyRequest(surveyId, offeringId, status, comment, dueDate);
Call<UpdateStatusSurveyResponse> call = apiService.updateStatusSurvey(updateStatusSurveyRequest);
call.enqueue(new Callback<UpdateStatusSurveyResponse>() {
@Override
public void onResponse(Call<UpdateStatusSurveyResponse> call, Response<UpdateStatusSurveyResponse> response) {
if(!response.body().getData().equals(1000)){
Toast.makeText(context, response.body().getMessage(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Failed to Update", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<UpdateStatusSurveyResponse> call, Throwable t) {
Toast.makeText(context, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
});
}
public class ViewHolder {
public TextView admUpdateSurveyUkmName;
public TextView admUpdateSurveyUkmOwner;
public TextView admUpdateSurveyInvName;
public TextView admUpdateSurveyStatus;
public String surveyId, offeringId, ukmName, invName, dueDate, comment, status;
//public int status;
public ViewHolder(View view){
admUpdateSurveyUkmName = view.findViewById(R.id.reportInvUkmOwn);
admUpdateSurveyUkmOwner = view.findViewById(R.id.admUpdSurveyUkmOwner);
admUpdateSurveyInvName = view.findViewById(R.id.admUpdSurveyInvName);
admUpdateSurveyStatus = view.findViewById(R.id.admUpdSurveyStatus);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateSurveyStatusDialog(surveyId, offeringId, ukmName, invName, dueDate, status, comment);
}
});
}
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.model.GetUserProfile;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GetUserProfileResponseData {
@SerializedName("email")
@Expose
private String email;
@SerializedName("status")
@Expose
private String status;
@SerializedName("name")
@Expose
private String name;
@SerializedName("category")
@Expose
private String category;
@SerializedName("id_user")
@Expose
private String idUser;
@SerializedName("add_id")
@Expose
private String addId;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getIdUser() {
return idUser;
}
public void setIdUser(String idUser) {
this.idUser = idUser;
}
public String getAddId() {
return addId;
}
public void setAddId(String addId) {
this.addId = addId;
}
}
<file_sep>package ukmutilizer.project.com.ukm_utilizer.ukm.UkmAdapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ukmutilizer.project.com.ukm_utilizer.R;
import ukmutilizer.project.com.ukm_utilizer.ukm.UkmDashboardFragment.UkmDashboardViewDetail;
import ukmutilizer.project.com.ukm_utilizer.model.InsertPeriodDetail.InsertPeriodDetailRequest;
import ukmutilizer.project.com.ukm_utilizer.model.InsertPeriodDetail.InsertPeriodDetailResponse;
import ukmutilizer.project.com.ukm_utilizer.model.ReportDetail.ViewReportDetailResponseDataList;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiClient;
import ukmutilizer.project.com.ukm_utilizer.rest.ApiInterface;
public class UkmViewDataDetailAdapter extends BaseAdapter {
EditText txtViewDetailUpdateFund;
EditText txtViewDetailUpdateDesc;
EditText txtViewDetailUpdateDate;
RadioGroup txtViewDetailUpdateType;
String ukmId, ukmReportId;
private Context context;
private ArrayList<ViewReportDetailResponseDataList> viewReportDetailResponseDataLists;
@Override
public int getCount() {
return viewReportDetailResponseDataLists.size();
}
@Override
public Object getItem(int position) {
return viewReportDetailResponseDataLists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public UkmViewDataDetailAdapter(ArrayList<ViewReportDetailResponseDataList> viewReportDetailResponseDataLists, Context context, String ukmId, String ukmReportId) {
this.context = context;
this.viewReportDetailResponseDataLists = viewReportDetailResponseDataLists;
this.ukmId = ukmId;
this.ukmReportId = ukmReportId;
}
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.fragment_dashboard_view_detail_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.ukmId = ukmId;
holder.ukmReportId = ukmReportId;
holder.amount.setText(viewReportDetailResponseDataLists.get(position).getAmount().toString());
holder.desc.setText(viewReportDetailResponseDataLists.get(position).getDescription());
holder.typeText.setText(viewReportDetailResponseDataLists.get(position).getType().toString());
holder.periodDetailId = viewReportDetailResponseDataLists.get(position).getId();
holder.detailFund = Integer.parseInt(viewReportDetailResponseDataLists.get(position).getAmount().toString());
holder.detailDesc = viewReportDetailResponseDataLists.get(position).getDescription();
holder.detailType = viewReportDetailResponseDataLists.get(position).getType();
return convertView;
}
public void updateViewDetailDialog(final String periodDetailId, final String ukmId, String periodReportId, int detailType, int detailFund, String detailDate, String detailDesc){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_dashboard_view_detail_update, null, false);
txtViewDetailUpdateFund = view.findViewById(R.id.txtViewDetailUpdateFund);
txtViewDetailUpdateDesc = view.findViewById(R.id.txtViewDetailUpdateDesc);
txtViewDetailUpdateDate = view.findViewById(R.id.txtViewDetailUpdateDate);
txtViewDetailUpdateType = view.findViewById(R.id.txtViewDetailUpdateType);
/*show existing data*/
txtViewDetailUpdateFund.setText(String.valueOf(detailFund));
txtViewDetailUpdateDate.setText(detailDate);
txtViewDetailUpdateDesc.setText(detailDesc);
if(detailType == 1){
txtViewDetailUpdateType.check(R.id.pengeluaran);
}else if(detailType == 2){
txtViewDetailUpdateType.check(R.id.pemasukan);
}
AlertDialog.Builder alertDialog = new AlertDialog.Builder(view.getContext());
alertDialog.setView(view);
alertDialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
/*update data*/
final int editedFund = Integer.parseInt(txtViewDetailUpdateFund.getText().toString());
final String editedDesc = txtViewDetailUpdateDesc.getText().toString();
final String editedDate = txtViewDetailUpdateDate.getText().toString();
int editedTxtType = 0;
if(txtViewDetailUpdateType.getCheckedRadioButtonId() == R.id.pengeluaran){
editedTxtType = 1;
}else if(txtViewDetailUpdateType.getCheckedRadioButtonId() == R.id.pemasukan){
editedTxtType = 2;
}
final int editedType = editedTxtType;
updateDetailPeriodList(periodDetailId, ukmId, ukmReportId, editedType, editedFund, editedDate, editedDesc);
dialog.dismiss();
//getViewDetailPeriod(ukmId, ukmReportId);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void updateDetailPeriodList(String periodDetailid, final String ukmId, final String ukmReportId, int type, int fund, String trxDate, String desc){
Toast.makeText(context, desc + " "+ trxDate, Toast.LENGTH_SHORT).show();
InsertPeriodDetailRequest updatePeriodDetailRequest = new InsertPeriodDetailRequest(periodDetailid, ukmId, ukmReportId, type, fund, trxDate, desc);
Call<InsertPeriodDetailResponse> call = apiService.insertPeriodDetail(updatePeriodDetailRequest);
call.enqueue(new Callback<InsertPeriodDetailResponse>() {
@Override
public void onResponse(Call<InsertPeriodDetailResponse> call, Response<InsertPeriodDetailResponse> response) {
Toast.makeText(context, response.body().getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, UkmDashboardViewDetail.class);
String ukm_id = ukmId;
String report_id = ukmReportId;
intent.putExtra("viewDetailUkmId", ukm_id);
intent.putExtra("viewDetailReportId", report_id);
context.startActivity(intent);
}
@SuppressLint("LongLogTag")
@Override
public void onFailure(Call<InsertPeriodDetailResponse> call, Throwable t) {
Toast.makeText(context, "Error Insert", Toast.LENGTH_SHORT).show();
Log.e("error insert period detail : ", String.valueOf(t));
}
});
}
public class ViewHolder{
public TextView trxDate, desc, amount, typeText;
public RadioGroup type;
public String periodDetailId, ukmId, ukmReportId;
String detailDesc, detailDate;
int detailFund, detailType;
public ViewHolder(View view){
trxDate = view.findViewById(R.id.viewDetailListTrxDate);
desc = view.findViewById(R.id.viewDetailListDescription);
amount = view.findViewById(R.id.viewDetailListAmount);
typeText = view.findViewById(R.id.viewDetailListType);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateViewDetailDialog(periodDetailId, ukmId, ukmReportId, detailType, detailFund, detailDate, detailDesc);
}
});
}
}
}
| a8097dbc9c5741511f486a9113ab06cdcad2dad7 | [
"Java",
"Gradle"
] | 34 | Java | rafitio/UKM_UTILIZER | 915058e06b2f6ad90fb730091951524366196df7 | 3803a6c40f1c264544189f7f0d6357d5cf71b867 |
refs/heads/master | <file_sep>#!/usr/bin/env pybricks-micropython
#This project is to drive around a robot
#Note There was only 2 TouchSensors/buttons
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
from threading import Thread
left = Motor(Port.B)
right = Motor(Port.C)
robot = DriveBase(left, right, 56, 114)
sensorU = UltrasonicSensor(Port.S1)
sensorD = UltrasonicSensor(Port.S4)
touch2 = TouchSensor(Port.S2)
touch3 = TouchSensor(Port.S3)
def func1(): #commands to drive left/right/forward and to stop given obstruction or drop (e.g. a cliff or step)
while touch3.pressed() and touch2.pressed():
if sensorU.distance() < 50:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
if sensorD.distance() > 150:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
robot.drive(100,0)
while touch2.pressed() and touch3.pressed()==0:
if sensorU.distance() < 50:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
if sensorD.distance() > 150:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
left.run(100)
while touch3.pressed() and touch2.pressed()==0:
if sensorU.distance() < 50:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
if sensorD.distance() > 150:
robot.stop()
brick.sound.file(SoundFile.ERROR, 90)
break
right.run(100)
robot.stop()
def func2():
if sensorU.distance() < 50 or sensorD.distance() > 150: #robot will reverse if stop condition of func1 was met
while touch3.pressed() and touch2.pressed():
robot.drive(-100,0)
else:
func1()
while True:
func2()
<file_sep>Select DISTINCT A.[AcctDesc] ,L.[UploadDesc], E.[EntDesc], V.*
from dbo.[Values] V
INNER JOIN dbo.[AccountDetails] A ON A.[AcctID] = V.[AcctID]
INNER JOIN dbo.[Logs] L ON L.[LogID] = V.[LogID]
INNER JOIN dbo.[EntityDetails] E on E.[EntID] = V.[EntID]
<file_sep>This was an assignment for a job application to PwC
<file_sep>#!/usr/bin/env pybricks-micropython
#This project is for an extension I built called holder
#This program will raise/lower a tea bag into hot water
from pybricks import ev3brick as brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import (Port, Stop, Direction, Button, Color,
SoundFile, ImageFile, Align)
from pybricks.tools import print, wait, StopWatch
from pybricks.robotics import DriveBase
holder = Motor(Port.A)
touch2 = TouchSensor(Port.S2)
touch3 = TouchSensor(Port.S3)
list = [x for x in range(0,500)]
def tea(): #function to lower/raise teabag for 7ms multiplied by max of list
if touch2.pressed():
for x in list:
if touch3.pressed():
break
if x%2==0:
holder.run(-200)
wait(700)
holder.stop()
if x%2 !=0:
holder.run(200)
wait(700)
holder.stop()
while True:
tea()
<file_sep># Completed-projects
Download html to view properly
The MicroPython is for Lego MindStorm ev3 kit/robot
# Basic website
https://gorfrinds-web-development.weebly.com/
| c06ca6b191ed39e23af3c890e3c29659b046cafd | [
"Markdown",
"SQL",
"Python"
] | 5 | Python | Gorfrind/Completed-projects | 251a367cbcdff013ecc719bd38c5c2909643a85b | c88ac60867f1b99d0369f96685c099d2ab8bc4f1 |
refs/heads/master | <file_sep># Hash with symbols
hash = { prime_rib: "<NAME>", filet_mignon: "<NAME>", top_sirloin: "Sangiovese",
lamb: "Malbec", veal: "Zinfandel", venison: "Montepulciano d'Abruzzo"}
puts hash
<file_sep>weather = 'cloudy'
case weather
when 'sunny'
puts "Yay! Grab a pair of your favorite jorts and don't forget your shades!"
when 'rainy'
puts "Yeek! You will need an umbrella and cute boots!"
when 'cloudy'
puts "No sun. Get your moto jacket and jeans."
when 'foggy'
puts "The fog comes\n on little cat feet...Dress in bright yellow & pinks."
when 'snowy'
puts "Yay snow! Warm clother, hat, gloves, and uggs. Grab a warm beverage."
else
puts "Hmmm...my mother used to say, dress in layers!"
end
<file_sep>class Pet
# :name is a symbol
attr_accessor :name, :owner_name
end
class Ferret < Pet
def squeal
return "squeeeee"
end
end
class Chinchilla < Pet
def squeek
return "eeeep"
end
end
class Parrot < Pet
def tweet
return "chirp"
end
end
my_ferret = Ferret.new
my_ferret.name = "Fredo"
ferret_name = my_ferret.name
my_parrot = Parrot.new
my_parrot.name = "Budgie"
parrot_name = my_parrot.name
my_chinchilla = Chinchilla.new
my_chinchilla.name = "Dali"
chinchilla_name = my_chinchilla.name
puts "#{ferret_name} says #{my_ferret.squeal},
#{parrot_name} says #{my_parrot.tweet},
and #{chinchilla_name} says #{my_chinchilla.squeek}."
puts my_ferret.inspect
puts my_parrot.inspect
puts my_chinchilla.inspect
<file_sep>def add_two_nums(num1, num2)
answer = num1 + num2
puts "#{num1} + #{num2} = #{answer}"
end
add_two_nums(2, 2)
add_two_nums(3, 5)
add_two_nums(107, 258)
<file_sep>puts "I'm on a new branch!"
<file_sep># Awww Love Note!
inf = (+1.0/0)
time = Time.new.hour
love = "\033[31mlove\033[0m"
while time < inf
puts "I #{love} you"
end
<file_sep>#
def greeting
return "Hello World"
end
greeting
<file_sep># My first class object
class Dinner
attr_accessor :meat, :topping, :sauce
end
class Pizza < Dinner
def cooking_time
return "30 min"
end
end
class Lasagna < Dinner
def cooking_time
return "50 min"
end
end
class Pasta < Dinner
def cooking_time
return "10 min"
end
end
my_pizza = Pizza.new
my_pizza.meat = "Italian sausage"
my_pizza.topping = "Cheese"
my_pizza.sauce = "White"
pizza_meat = my_pizza.meat
pizza_topping = my_pizza.topping.downcase
pizza_sauce = my_pizza.sauce.downcase
my_pasta = Pasta.new
my_pasta.meat = "Shrimp"
my_pasta.topping = "Parmesan cheese"
my_pasta.sauce = "Creole"
pasta_meat = my_pasta.meat.downcase
pasta_topping = my_pasta.topping.downcase
pasta_sauce = my_pasta.sauce
my_lasagna = Lasagna.new
my_lasagna.meat = "Ground beef"
my_lasagna.topping = "Three cheeses"
my_lasagna.sauce = "Tomato"
lasagna_meat = my_lasagna.meat.downcase
lasagna_topping = my_lasagna.topping.downcase
lasagna_sauce = my_lasagna.sauce.downcase
puts "Pizza with #{pizza_meat}, #{pizza_topping}, and #{pizza_sauce} sauce. Cooking time = #{my_pizza.cooking_time}."
puts "Pasta with #{pasta_meat}, #{pasta_topping}, and #{pasta_sauce} sauce. Cooking time = #{my_pasta.cooking_time}."
puts "Lasagna with #{lasagna_meat}, #{lasagna_topping} and #{lasagna_sauce} sauce. Cooking time = #{my_lasagna.cooking_time}."
puts my_pizza.inspect
puts my_pasta.inspect
puts my_lasagna.inspect
<file_sep># Refactor First Object challenge to use attribute accessors
class Pizza
attr_accessor :topping, :sauce
end
my_pizza = Pizza.new
my_pizza.topping = "Cheese"
my_pizza.sauce = "Tomato"
pizza_topping = my_pizza.topping
pizza_sauce = my_pizza.sauce
puts my_pizza.inspect
puts "Custom-made #{pizza_topping} pizza with #{pizza_sauce} sauce."
<file_sep>require 'sinatra'
def get_birth_path_number (birthdate)
number = birthdate[0].to_i + birthdate[1].to_i + birthdate[2].to_i + birthdate[3].to_i + birthdate[4].to_i + birthdate[5].to_i + birthdate[6].to_i + birthdate[7].to_i
number_str = number.to_s
birth_number = number_str[0].to_i + number_str[1].to_i
if birth_number > 9
number2_str = birth_number.to_s
birth_number = number2_str[0].to_i + number2_str[1].to_i
end
return birth_number
end
def setup_index_view
get "/newpage/" do
erb :newpage
end
get '/' do
erb :form
end
post '/' do
# birthdate = params[:birthdate].gsub("-","")
birthdate = params[:birthdate]
@error = "\nSorry, invalid input. Please enter your birthdate in mmddyyyy format."
if valid_birthdate(birthdate)
birth_path_number = get_birth_path_number(birthdate)
redirect "/message/#{birth_path_number}"
else
erb :form
end
end
get '/message/:birth_path_number' do
@birth_path_number = params[:birth_path_number].to_i
@message = get_profound_message(@birth_path_number)
erb :message
end
end
# check if the input is valid. Birthdate should be mmddyyyy format
def valid_birthdate(input)
if input.length == 8 and input.match(/^[0-9]+[0-9]$/)
return true
else
return false
end
end
# Method determines numerology message
def get_profound_message (birth_number)
case birth_number
when 1
return "One is the leader. The number one indicates the ability to stand alone, and is a strong vibration. Ruled by the Sun."
when 2
return "This is the mediator and peace-lover. The number two indicates the desire for harmony. It is a gentle, considerate, and sensitive vibration. Ruled by the Moon."
when 3
return "Number Three is a sociable, friendly, and outgoing vibration. Kind, positive, and optimistic, Three's enjoy life and have a good sense of humor. Ruled by Jupiter."
when 4
return "This is the worker. Practical, with a love of detail, Fours are trustworthy, hard-working, and helpful. Ruled by Uranus."
when 5
return "This is the freedom lover. The number five is an intellectual vibration. These are 'idea' people with a love of variety and the ability to adapt to most situations. Ruled by Mercury."
when 6
return "This is the peace lover. The number six is a loving, stable, and harmonious vibration. Ruled by Venus."
when 7
return "This is the deep thinker. The number seven is a spiritual vibration. These people are not very attached to material things, are introspective, and generally quiet. Ruled by Neptune."
when 8
return "This is the manager. Number Eight is a strong, successful, and material vibration. Ruled by Saturn."
when 9
return "This is the teacher. Number Nine is a tolerant, somewhat impractical, and sympathetic vibration. Ruled by Mars."
else
return "Not a number between 1 and 9. Enter a valid birthdate MMDDYYYY"
end
end
setup_index_view
| 6ba8a7b55b566bdb130c5222c0fa58c7c275d366 | [
"Ruby"
] | 10 | Ruby | natalya-patrikeeva/ruby-challenges | 07b1b764d39ce35eb82ed5252f5cfc5ed28958f8 | 51a1d3755fab84e545a951768f3477481aacf5e0 |
refs/heads/master | <file_sep>package org.proxy;
import java.lang.reflect.Method;
import org.store.Store;
public class MailProxy<T> implements MethodInterceptor
{
@Override
public Object interceptBefore(Object proxy, Method method, Object[] params, Object realtarget) throws Exception
{
System.out.println("Hi From Mail API Before intercept");
return "Hi From Mail API Before intercept";
}
@Override
public void interceptAfter(Object proxy, Method method, Object[] params, Object realtarget, Store store, Object retObject, Object interceptBeforeReturnObject) throws Exception
{
System.out.println("Hi From Mail API after intercept");
}
}
<file_sep>package org.proxy;
import java.lang.reflect.Method;
import org.store.Store;
public interface MethodInterceptor
{
Object interceptBefore(Object proxy, Method method, Object[] params, Object realtarget) throws Exception;
void interceptAfter(Object proxy, Method method, Object[] params, Object realtarget, Store store, Object retObject, Object interceptBeforeReturnObject) throws Exception;
}
<file_sep>package org.store;
import com.tcs.vfw.util.jdbc.JDBCSession;
public class SessionStore
{
private JDBCSession o2oGlobalSession;
private JDBCSession customerSession;
public JDBCSession getO2OGlobalSession()
{
return this.o2oGlobalSession;
}
public void setO2OGlobalSession(JDBCSession o2oGlobalSession)
{
this.o2oGlobalSession = o2oGlobalSession;
}
public JDBCSession getCustomerSession()
{
return this.customerSession;
}
public void setCustomerSession(JDBCSession customerSession)
{
this.customerSession = customerSession;
}
}
<file_sep>package main.java.org.java8.bpn;
public class AppleFancyFormatter implements AppleFormatter{
@Override
public String accept(Apple apple) {
String characteristic = apple.getWeight() > 150 ? "heavy" : "light";
return "A " + characteristic + " " + apple.getColour() + " Apple";
}
}
<file_sep>package org.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.store.Store;
/**
* @author <NAME>(1006792)
* This is the invocation handler for all the method interceptors created in the solution.
*/
public class ProxyInvocationHandler implements InvocationHandler
{
private Object realtarget = null;
public void setRealTarget(Object realtarget_)
{
this.realtarget = realtarget_;
}
Object[] methodInterceptors = null;
public void setMethodInterceptors(Object[] methodInterceptors_)
{
this.methodInterceptors = methodInterceptors_;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
try
{
Object[] retInterceptBefore = null;
if (methodInterceptors != null && methodInterceptors.length > 0)
{
retInterceptBefore = new Object[methodInterceptors.length];
for (int i = 0; i < methodInterceptors.length; i++)
{
if (methodInterceptors[i] != null)
{
retInterceptBefore[i] = ((MethodInterceptor) methodInterceptors[i]).interceptBefore(proxy, method, args, realtarget);
}
}
}
Object retObject = method.invoke(realtarget, args);
if (methodInterceptors != null)
{
for (int i = 0; i < methodInterceptors.length; i++)
{
if (methodInterceptors[i] != null)
{
((MethodInterceptor) methodInterceptors[i]).interceptAfter(proxy, method, args, realtarget, (Store) args[0], retObject, retInterceptBefore[i]);
}
}
}
return retObject;
}
catch (InvocationTargetException e)
{
throw e.getTargetException();
}
catch (Exception e)
{
throw e;
}
}
}
<file_sep>package bo;
public interface BusinessObjectInterface
{
public String doExecute(String in) throws Exception;
}
<file_sep># Java Repo
<file_sep>package org.proxy;
import java.lang.reflect.Proxy;
import java.util.List;
/**
* @author <NAME>(1006792)
* @category - Parent Service- Should be extended by all the services
* @param <T>
*/
public class ParentService<T>
{
@SuppressWarnings("unchecked")
public T getProxyInstance(List<InterceptorFunction> interceptors)
{
try
{
if (!interceptors.contains(InterceptorFunction.PROXY))
{
interceptors.add(0, InterceptorFunction.PROXY);
}
else if(interceptors.indexOf(InterceptorFunction.PROXY)!=0){
interceptors.remove(InterceptorFunction.PROXY);
interceptors.add(0, InterceptorFunction.PROXY);
}
if (interceptors != null && interceptors.size() > 0)
{
ProxyInvocationHandler invocationHandler = new ProxyInvocationHandler();
Object[] interceptorObjects = getInterceptors(interceptors);
invocationHandler.setRealTarget(this);
invocationHandler.setMethodInterceptors(interceptorObjects);
final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(this.getClass());
return (T) Proxy.newProxyInstance(ParentService.class.getClassLoader(), new Class<?>[]
{
interfaces.get(0)
}, invocationHandler);
}
}
catch (Throwable e)
{
e.printStackTrace();
}
return null;
}
private static Object getInterceptor(String interceptors) throws Exception
{
return Class.forName(interceptors).newInstance();
}
private static Object[] getInterceptors(List<InterceptorFunction> interceptors) throws Exception
{
Object[] objInterceptors = new Object[interceptors.size()];
for (int i = 0; i < interceptors.size(); i++)
{
objInterceptors[i] = getInterceptor(interceptors.get(i).getClassName());
}
return objInterceptors;
}
}
<file_sep>package main.java.org.java8.bpn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ApplePrint {
static List<Apple> appleList = new ArrayList<>();
public void prettyPrintApple(List<Apple> inventory, AppleFormatter formatter) {
for(Apple apple:inventory) {
String output = formatter.accept(apple);
System.out.println(output);
}
}
public static void main(String[] args) {
ApplePrint ap = new ApplePrint();
List<Apple> inventory = Arrays.asList(new Apple(45, "Red"),
new Apple(98, "Green"),
new Apple(225, "Dark Red"));
Apple a1 = new Apple();
a1.setColour("red");
a1.setWeight(45);
Apple a2 = new Apple();
a2.setColour("green");
a2.setWeight(58);
Apple a3 = new Apple();
a3.setColour("Red");
a3.setWeight(205);
appleList.add(a1);
appleList.add(a2);
appleList.add(a3);
ap.prettyPrintApple(appleList, new AppleSimpleFormatter());
ap.prettyPrintApple(inventory, new AppleFancyFormatter());
}
}
<file_sep>package org.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
public interface JDBCSession
{
void commitTransaction() throws SQLException;
void rollbackTransaction() throws SQLException;
void stopSession() throws SQLException;
Connection getConnection() throws SQLException;
Query prepareQuery(String sql) throws SQLException;
InsertQuery prepareInsertQuery() throws SQLException;
UpdateQuery prepareUpdateQuery() throws SQLException;
SelectQuery prepareSelectQuery() throws SQLException;
}
<file_sep>package main.java.org.java8.streams;
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamsTest {
static List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH) );
public static void main(String[] args) {
List<String> threeHighCalorieDishes =
menu.stream()
.filter(d->d.getCalories() > 300)
.map(Dish::getName)
.limit(3)
.collect(toList());
List<Dish> vegDishes = menu.stream()
.filter(Dish::isVegetarian)
.collect(toList());
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream()
.filter(i -> i % 2 == 0)
.distinct()
.forEach(System.out::println);
List<Dish> dishes = menu.stream()
.filter(d -> d.getCalories() > 300)
.skip(2)
.collect(toList());
List<Dish> dishesLim =
menu.stream()
.filter(d -> d.getType() == Dish.Type.MEAT)
.limit(2)
.collect(toList());
List<String> words = Arrays.asList("Java8", "Lambdas", "In", "Action");
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(toList());
List<Integer> dishNameLengths = menu.stream()
.map(Dish::getName)
.map(String::length)
.collect(toList());
String[] arrayOfWords = {"Goodbye", "World"};
Stream<String> streamOfwords = Arrays.stream(arrayOfWords);
List<String> uniqueCharacters = words.stream()
.map(w -> w.split(""))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
List<Integer> numbersSq = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbersSq.stream()
.map(n -> n * n)
.collect(toList());
System.out.println(squares);
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> pairs = numbers1.stream()
.flatMap(i -> numbers2.stream().map(j -> new int[]{i,j}))
.collect(toList());
List<int[]> pairsDivisibleBy3 = numbers1.stream()
.flatMap(i -> numbers2.stream()
.filter(j -> (i+j) % 3 ==0)
.map(j -> new int[] {i,j}))
.collect(toList());
for(int i =0 ; i< pairs.size() ; i++){
System.out.print(pairs.get(i)[0] + ","+pairs.get(i)[1] +"\t" );
}
System.out.println();
for(int i =0 ; i< pairsDivisibleBy3.size() ; i++){
System.out.print(pairsDivisibleBy3.get(i)[0] + ","+pairsDivisibleBy3.get(i)[1] +"\t" );
}
if(menu.stream().anyMatch(Dish::isVegetarian)){
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}
boolean isHealthy = menu.stream()
.allMatch(d -> d.getCalories() < 1000);
boolean isHealthyN = menu.stream()
.noneMatch(d -> d.getCalories() >= 1000);
Optional<Dish> dish = menu.stream()
.filter(Dish::isVegetarian)
.findAny();
List<Integer> someNumbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquareDivisibleByThree =
someNumbers.stream()
.map(x -> x * x)
.filter(x -> (x % 3 == 0))
.findFirst();
int sum = someNumbers.stream()
.reduce(0, (a, b) -> a + b);
int sumM = someNumbers.stream()
.reduce(0, Integer::sum);
Optional<Integer> sumOP = someNumbers.stream()
.reduce(Integer::sum);
Optional<Integer> max = someNumbers.stream()
.reduce(Integer::max);
//Specialized Stream
int calories = menu.stream()
.mapToInt(Dish::getCalories)
.sum();
//boxing to nonspecialized stream
IntStream intStream = menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed();
OptionalInt maxCalories = menu.stream()
.mapToInt(Dish::getCalories)
.max();
int maxCal = maxCalories.orElse(1);
IntStream evenNumbers = IntStream.rangeClosed(1, 100)
.filter(d -> d % 2 == 0);
System.out.println(evenNumbers.count());
//fibonacci
Stream.iterate(new int[] {0,1}, t -> new int[]{t[1], t[0]+t[1]})
.limit(10)
.forEach(t -> System.out.println("(" + t[0] + "," + t[1] +")"));
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
IntStream intStream1 = new Random().ints(1,100000, 999999);
intStream1.forEach(System.out::println);
}
}
<file_sep>import com.sun.xml.internal.ws.util.StringUtils;
public class TestError {
public static void main(String[] args) {
}
}
| b086b52c1106e966ff887f18b9b6c6d8cced351a | [
"Markdown",
"Java"
] | 12 | Java | raviraizada10/Java | e578bf42b063a2baa8b181f6d08c76b8a62212c1 | 74d2c96c180d368076490f38c8ac5e43b2853ec8 |
refs/heads/master | <repo_name>manukko/Gesture_Glove_Harmonizer<file_sep>/js/index.js
const renderer = new THREE.WebGLRenderer({canvas: document.querySelector(".hand_canvas")});
const camera = new THREE.PerspectiveCamera(3, window.innerWidth / window.innerHeight, 10, 50);
// Harmonics variables
var h1 = 1,
h2b = Math.pow(2, 1/12),
h2 = Math.pow(2, 2/12),
h3b = Math.pow(2, 3/12),
h3 = Math.pow(2, 4/12),
h4 = Math.pow(2, 5/12),
h5b = Math.pow(2, 6/12),
h5 = Math.pow(2, 7/12),
h6b = Math.pow(2, 8/12),
h6 = Math.pow(2, 9/12),
h7b = Math.pow(2, 10/12),
h7 = Math.pow(2, 11/12),
h8 = 2;
var h = 0; // variable for the first harmonization
var hh = 0; // variable for the second harmonization
var h_left = h5;
var h_right = h5;
var h_up = h8;
var h_down = h1;
// variables for the octave choice
var actual_octaveLeft = 2;
var actual_octaveUp = 2;
var actual_octaveRight = 1/2;
var actual_octaveDown = 1/2;
var roll = 0;
var pitch = 0;
// micro:bit variables representing UUID for BLE protocol
var ACCEL_SRV = 'e95d0753-251d-470a-a062-fa1922dfa9a8'
var ACCEL_DATA = 'e95dca4b-251d-470a-a062-fa1922dfa9a8'
var ACCEL_PERIOD = 'e95dfb24-251d-470a-a062-fa1922dfa9a8'
var MAGNETO_SRV = 'e95df2d8-251d-470a-a062-fa1922dfa9a8'
var MAGNETO_DATA = 'e95dfb11-251d-470a-a062-fa1922dfa9a8'
var MAGNETO_PERIOD = 'e95d386c-251d-470a-a062-fa1922dfa9a8'
var MAGNETO_BEARING = 'e95d9715-251d-470a-a062-fa1922dfa9a8'
var BTN_SRV = 'e95d9882-251d-470a-a062-fa1922dfa9a8'
var BTN_A_STATE = 'e95dda90-251d-470a-a062-fa1922dfa9a8'
var BTN_B_STATE = 'e95dda91-251d-470a-a062-fa1922dfa9a8'
var IO_PIN_SRV = 'e95d127b-251d-470a-a062-fa1922dfa9a8'
var IO_PIN_DATA = 'e95d8d00-251d-470a-a062-fa1922dfa9a8'
var IO_AD_CONFIG = 'e95d5899-251d-470a-a062-fa1922dfa9a8'
var IO_PIN_CONFIG = 'e95db9fe-251d-470a-a062-fa1922dfa9a8'
var IO_PIN_PWM = 'e95dd822-251d-470a-a062-fa1922dfa9a8'
var LED_SRV = 'e95dd91d-251d-470a-a062-fa1922dfa9a8'
var LED_STATE = 'e95d7b77-251d-470a-a062-fa1922dfa9a8'
var LED_TEXT = 'e95d93ee-251d-470a-a062-fa1922dfa9a8'
var LED_SCROLL = 'e95d0d2d-251d-470a-a062-fa1922dfa9a8'
var TEMP_SRV = 'e95d6100-251d-470a-a062-fa1922dfa9a8'
var TEMP_DATA = 'e95d9250-251d-470a-a062-fa1922dfa9a8'
var TEMP_PERIOD = 'e95d1b25-251d-470a-a062-fa1922dfa9a8'
// sounds frequency samples using MATLAB script
var SINWAVE1f = [1.000];
var SINWAVE1a = [250];
var ELPIANO1f = [1.0000, 1.0121, 1.0287, 1.9955];
var ELPIANO1a = [243.1425 , 16.9380 , 7.6275 , 76.5855];
var ORGAN1f = [1.0000, 1.9659, 1.9924, 3.9053, 3.9811, 7.9356];
var ORGAN1a = [124.1516 , 5.3789 , 80.0809 , 4.2104 ,103.2640 , 80.6335];
var ORGAN2f = [0.2538, 0.3788, 0.8977, 1.0000, 1.0985, 1.9886, 2.0038, 2.8902, 2.9886];
var ORGAN2a = [2.4191 , 4.5088 , 2.6226 , 251.2533 , 2.7177 , 42.7642 , 15.2599 , 2.5116 , 86.1271];
var PIANO1f = [0.1425, 0.2104, 0.9367, 1.0000, 1.0452, 1.2059, 1.9977, 3.0068, 4.0113, 5.0339];
var PIANO1a = [ 2.6407 , 3.5024 , 7.1984 , 250.9229 , 5.8227 , 2.2781 , 14.7993 , 10.0962 , 6.4306 , 3.5564];
var TRI1f = [0.5950, 0.6923, 0.7941, 0.8914, 1.0000, 1.1041, 1.2353, 1.3032, 2.9887, 4.9887, 6.9842, 8.9774, 10.9729, 12.9661, 14.9615];
var TRI1a = [0.4154,0.5529,0.8356,1.2794,247.5712,1.5090,0.6740,0.5449,8.5996,5.6198,2.2270,1.6043,1.0385,0.5842,0.6101];
var SYNTH1f = [0.5011, 1.0000, 1.4989, 1.9977, 2.4966, 2.9955, 3.4943, 3.9932];
var SYNTH1a = [145.2846 , 209.7553 , 22.4301 , 33.8246 , 21.3655 , 12.9702 , 10.5142 , 2.7954];
var MANU1f = [0.2012, 0.4009, 0.6006, 0.8003, 1.0000, 1.0209, 1.1982, 1.3934, 1.5946, 1.6110, 1.7869, 1.7928, 1.9642, 1.9925, 2.1923, 4.3741];
var MANU1a = [96.3986 , 64.2564 , 34.8488 , 51.4745 , 156.3458 , 16.5059 , 97.2270 , 27.8127 , 67.0118 , 32.9409, 51.2886 , 71.3372 , 8.7134 , 20.4526 , 6.9899 , 6.2132];
var FEDE1f = [1.0000, 1.0381, 1.9905, 2.9714, 3.9429, 3.9714, 4.0095, 4.9524, 5.9333, 6.8762, 6.9048, 6.9429, 7.8286, 7.8857, 7.9333];
var FEDE1a = [118.9386 , 10.1337 , 45.9867 , 49.5579 , 40.1862 , 29.8920 , 6.1446 , 9.2931 , 11.9226 , 7.5846, 12.2400 , 7.4334 , 12.9246 , 20.2221 , 9.4980];
var TEMP1f = [1];
var TEMP1a = [250];
var TEMP11f = [1.0000, 1.0034, 1.0125, 1.9977, 2.9955, 3.9932, 4.9909, 5.9887, 6.9864];
var TEMP11a = [249.0762 , 0.3195 , 0.3126 , 6.9777 , 24.6345 , 0.3557 , 2.4907 , 0.4688 , 0.3737];
var TEMP21f = [0.0038, 0.9029, 1.0000, 1.0076, 1.0971, 1.9962, 2.0152, 2.9943, 3.9371, 3.9905, 4.0248, 4.9867, 5.9810, 6.9771, 7.9771, 8.9752, 9.7714, 9.9714, 9.9752, 10.9676, 10.9829, 11.9600, 11.9867, 12.9543, 13.9619, 14.9524, 15.9162, 15.9486, 16.9448, 17.9314, 17.9410, 18.9371, 18.9448, 19.9410, 19.9505, 20.9333, 20.9562, 21.9257, 22.9257, 23.9219, 25.8952, 25.9143, 26.8990, 26.9067, 27.9029, 27.9181, 28.9143, 29.8952];
var TEMP21a = [10.3711 , 1.4606 ,243.7306 , 11.2517 , 1.3325 , 32.2438 ,
2.2370 , 9.0842 , 1.2722 , 79.3661 ,1.2948 , 16.5578 , 29.9546 , 12.1790 ,
4.9596 , 9.2006 , 1.1551 , 33.4985 ,10.5384 , 22.5108, 3.3346 ,26.8001 , 3.0158 ,
15.4318 , 8.6117 , 29.4394 , 1.0457 , 8.3710 , 11.5478 , 9.4130,
12.7303 , 2.9191 , 1.2137 , 4.7462 , 2.1374 , 9.1195 , 3.0437 ,
7.2163 , 8.8678 , 1.6068, 0.9886 , 1.2600 , 2.3902 , 3.1836 , 2.7130 , 1.5430 , 1.2665 , 1.2763];
var noisegain = 0.002;
var vect1 = ELPIANO1f;
var amp1 = ELPIANO1a;
var max = vect1.length*3;
var gates = [];
var oscStop = [];
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
/*----------------MICROBIT part----------------*/
class uBit {
constructor() {
this.accelerometer = {
x: 0,
y: 0,
z: 0
};
this.magnetometer_raw = {
x: 0,
y: 0,
z: 0
};
this.magnetometer_bearing = 0;
this.temperature = 0;
this.buttonA = 0;
this.buttonACallBack=function(){};
this.buttonB = 0;
this.buttonBCallBack=function(){};
this.connected = false;
this.onConnectCallback=function(){};
this.onDisconnectCallback=function(){
btLabel.bt_log = "Device not connected"
};
this.onBLENotifyCallback=function(){};
this.characteristic = {
IO_PIN_DATA: {},
IO_AD_CONFIG: {},
IO_PIN_CONFIG: {},
IO_PIN_PWM: {},
LED_STATE: {},
LED_TEXT: {},
LED_SCROLL: {},
}
}
getAccelerometer() {
return this.accelerometer;
}
onConnect(callbackFunction){
this.onConnectCallback=callbackFunction;
}
onDisconnect(callbackFunction){
this.onDisconnectCallback=callbackFunction;
}
onBleNotify(callbackFunction){
this.onBLENotifyCallback=callbackFunction;
}
characteristic_updated(event) {
this.onBLENotifyCallback();
//ACCELEROMETER CHARACTERISTIC
if (event.target.uuid == ACCEL_DATA) {
this.accelerometer.x = event.target.value.getInt16(0, true);
this.accelerometer.y = event.target.value.getInt16(2, true);
this.accelerometer.z = event.target.value.getInt16(4, true);
}
if (event.target.uuid == ACCEL_PERIOD) {
}
}
searchDevice() {
filters: []
var options = {};
options.acceptAllDevices = true;
options.optionalServices = [ACCEL_SRV, MAGNETO_SRV, BTN_SRV, IO_PIN_SRV, LED_SRV, TEMP_SRV];
console.log('Requesting Bluetooth Device...');
btLabel.bt_log = 'Requesting Bluetooth Device...';
console.log('with ' + JSON.stringify(options));
navigator.bluetooth.requestDevice(options)
.then(device => {
console.log('> Name: ' + device.name);
console.log('> Id: ' + device.id);
device.addEventListener('gattserverdisconnected', this.onDisconnectCallback);
// Attempts to connect to remote GATT Server.
return device.gatt.connect();
})
.then(server => {
// Note that we could also get all services that match a specific UUID by
// passing it to getPrimaryServices().
this.onConnectCallback();
console.log('Getting Services...');
return server.getPrimaryServices();
})
.then(services => {
console.log('Getting Characteristics...');
let queue = Promise.resolve();
services.forEach(service => {
queue = queue.then(_ => service.getCharacteristics().then(characteristics => {
console.log('> Service: ' + service.uuid);
characteristics.forEach(characteristic => {
console.log('>> Characteristic: ' + characteristic.uuid + ' ' +
getSupportedProperties(characteristic));
//need to store all the characteristic I want to write to be able to access them later.
switch (characteristic.uuid) {
case ACCEL_PERIOD:
this.characteristic.ACCEL_PERIOD = characteristic;
break;
case IO_PIN_DATA:
this.characteristic.IO_PIN_DATA = characteristic;
break;
case IO_AD_CONFIG:
this.characteristic.IO_AD_CONFIG = characteristic;
break;
case IO_PIN_CONFIG:
this.characteristic.IO_PIN_CONFIG = characteristic;
break;
case IO_PIN_PWM:
this.characteristic.IO_PIN_PWM = characteristic;
break;
case LED_STATE:
this.characteristic.LED_STATE = characteristic;
this.connected = true;
break;
case LED_TEXT:
this.characteristic.LED_TEXT = characteristic;
break;
case LED_SCROLL:
this.characteristic.LED_SCROLL = characteristic;
break;
default:
}
if (getSupportedProperties(characteristic).includes('NOTIFY')) {
characteristic.startNotifications().catch(err => console.log('startNotifications', err));
characteristic.addEventListener('characteristicvaluechanged',
this.characteristic_updated.bind(this));
}
});
}));
});
return queue;
}
)
.catch(error => {
console.log('Argh! ' + error);
btLabel.bt_log = 'Argh! ' + error;
});
}
}
// Utils
function isWebBluetoothEnabled() {
if (navigator.bluetooth) {
return true;
} else {
ChromeSamples.setStatus('Web Bluetooth API is not available.\n' +
'Please make sure the "Experimental Web Platform features" flag is enabled.');
return false;
}
}
function getSupportedProperties(characteristic) {
let supportedProperties = [];
for (const p in characteristic.properties) {
if (characteristic.properties[p] === true) {
supportedProperties.push(p.toUpperCase());
}
}
return '[' + supportedProperties.join(', ') + ']';
}
/*----------------VUE PART----------------*/
// bluetooth log information
var btLabel = new Vue({
el: '#bt-label',
data: {
bt_log: "Device not connected"
}
});
// led objects for hand gesture
var ledLeft = new Vue({
el: '#left_led',
data: {
ledOn: false
}
});
var ledRight = new Vue({
el: '#right_led',
data: {
ledOn: false
}
});
var ledUp = new Vue({
el: '#up_led',
data: {
ledOn: false
}
});
var ledDown = new Vue({
el: '#down_led',
data: {
ledOn: false
}
});
// Dropdown menu for sound and harmonization selection
const DropdownMenu = Vue.component('dropdown', {
template: `
<div>
<button @click='toggleShow' class='anchor labels' style = "font-size: 10px;font-weight:bold; color: #b7b2ae; line-height: 10px">
{{text}}
</button>
<div v-if='showMenu' class='menu'>
<div class='menu-item' v-for='item in this.items' @click='itemClicked(item)'>{{item}}</div>
</div>
</div>
`,
data: function() {
return {
showMenu: false
}
},
props: {
onClick: 'function',
items: {
type: 'Object',
default: []
},
text: 'String'
},
methods: {
toggleShow: function() {
this.showMenu = !this.showMenu;
},
itemClicked: function(item) {
this.toggleShow();
this.onClick(item);
}
}
});
var Dropdown_octave_right = new Vue({
el: '#dropmenu_octave_right',
components: {
DropdownMenu
},
data: {
text: "Octave",
activeOct: 'octave -1',
octaves: [
'octave +1',
'octave 0',
'octave -1'
]
},
methods: {
changeOctave: function(octave) {
this.activeOct = octave;
octaveRightLabel.updateOctave();
switch (this.activeOct) {
case 'octave 0':
actual_octaveRight = 1;
break;
case 'octave +1':
actual_octaveRight = 2;
break;
case 'octave -1':
actual_octaveRight = 1/2;
break;
}
}
}
});
var octaveRightLabel = new Vue ({
el: '#label_octave_right',
data: {
labelOct: Dropdown_octave_right.activeOct
},
methods: {
updateOctave: function() {
this.labelOct = Dropdown_octave_right.activeOct;
}
}
});
var Dropdown_octave_left = new Vue({
el: '#dropmenu_octave_left',
components: {
DropdownMenu
},
data: {
text: "Octave",
activeOct: 'octave +1',
octaves: [
'octave +1',
'octave 0',
'octave -1'
]
},
methods: {
changeOctave: function(octave) {
this.activeOct = octave;
octaveLeftLabel.updateOctave();
switch (this.activeOct) {
case 'octave 0':
actual_octaveLeft = 1;
break;
case 'octave +1':
actual_octaveLeft = 2;
break;
case 'octave -1':
actual_octaveLeft = 1/2;
break;
}
}
}
});
var octaveLeftLabel = new Vue ({
el: '#label_octave_left',
data: {
labelOct: Dropdown_octave_left.activeOct
},
methods: {
updateOctave: function() {
this.labelOct = Dropdown_octave_left.activeOct;
}
}
});
var Dropdown_octave_up = new Vue({
el: '#dropmenu_octave_up',
components: {
DropdownMenu
},
data: {
text: "Octave",
activeOct: 'octave +1',
octaves: [
'octave +1',
'octave 0',
'octave -1'
]
},
methods: {
changeOctave: function(octave) {
this.activeOct = octave;
octaveUpLabel.updateOctave();
switch (this.activeOct) {
case 'octave 0':
actual_octaveUp = 1;
break;
case 'octave +1':
actual_octaveUp = 2;
break;
case 'octave -1':
actual_octaveUp = 1/2;
break;
}
}
}
});
var octaveUpLabel = new Vue ({
el: '#label_octave_up',
data: {
labelOct: Dropdown_octave_up.activeOct
},
methods: {
updateOctave: function() {
this.labelOct = Dropdown_octave_up.activeOct;
}
}
});
var Dropdown_octave_down = new Vue({
el: '#dropmenu_octave_down',
components: {
DropdownMenu
},
data: {
text: "Octave",
activeOct: 'octave -1',
octaves: [
'octave +1',
'octave 0',
'octave -1'
]
},
methods: {
changeOctave: function(octave) {
this.activeOct = octave;
octaveDownLabel.updateOctave();
switch (this.activeOct) {
case 'octave 0':
actual_octaveDown = 1;
break;
case 'octave +1':
actual_octaveDown = 2;
break;
case 'octave -1':
actual_octaveDown = 1/2;
break;
}
}
}
});
var octaveDownLabel = new Vue ({
el: '#label_octave_down',
data: {
labelOct: Dropdown_octave_down.activeOct
},
methods: {
updateOctave: function() {
this.labelOct = Dropdown_octave_down.activeOct;
}
}
});
var Dropdown_left = new Vue({
el: '#dropmenu_left',
components: {
DropdownMenu
},
data: {
text: "Left",
activeHarm: '5th',
harmonics: [
'Fundamental',
'2nd minor',
'2nd Major',
'3rd minor',
'3rd Major',
'4th',
'5th minor',
'5th',
'6th minor',
'6th Major',
'7th minor',
'7th Major',
'Octave'
]
},
methods: {
changeHarmonic: function(harmonic) {
this.activeHarm = harmonic;
leftLabel.updateLabel();
switch (this.activeHarm) {
case 'Fundamental':
h_left = h1;
break;
case '2nd minor':
h_left = h2b;
break;
case '2nd Major':
h_left = h2;
break;
case '3rd minor':
h_left = h3b;
break;
case '3rd Major':
h_left = h3;
break;
case '4th':
h_left = h4;
break;
case '5th minor':
h_left = h5b;
break;
case '5th':
h_left = h5;
break;
case '6th minor':
h_left = h6b;
break;
case '6th Major':
h_left = h6;
break;
case '7th minor':
h_left = h7b;
break;
case '7th Major':
h_left = h7;
break;
case 'Octave':
h_left = h8;
break;
}
}
}
});
var leftLabel = new Vue ({
el: '#label_left',
data: {
labelHarm: Dropdown_left.activeHarm
},
methods: {
updateLabel: function() {
this.labelHarm = Dropdown_left.activeHarm;
}
}
});
var Dropdown_right = new Vue({
el: '#dropmenu_right',
components: {
DropdownMenu
},
data: {
text: "Right",
activeHarm: '5th',
harmonics: [
'Fundamental',
'2nd minor',
'2nd Major',
'3rd minor',
'3rd Major',
'4th',
'5th minor',
'5th',
'6th minor',
'6th Major',
'7th minor',
'7th Major',
'Octave'
]
},
methods: {
changeHarmonic: function(harmonic) {
this.activeHarm = harmonic;
rightLabel.updateLabel();
switch (this.activeHarm) {
case 'Fundamental':
h_right = h1;
break;
case '2nd minor':
h_right = h2b;
break;
case '2nd Major':
h_right = h2;
break;
case '3rd minor':
h_right = h3b;
break;
case '3rd Major':
h_right = h3;
break;
case '4th':
h_right = h4;
break;
case '5th minor':
h_right = h5b;
break;
case '5th':
h_right = h5;
break;
case '6th minor':
h_right = h6b;
break;
case '6th Major':
h_right = h6;
break;
case '7th minor':
h_right = h7b;
break;
case '7th Major':
h_right = h7;
break;
case 'Octave':
h_right = h8;
break;
}
}
}
});
var rightLabel = new Vue ({
el: '#label_right',
data: {
labelHarm: Dropdown_right.activeHarm
},
methods: {
updateLabel: function() {
this.labelHarm = Dropdown_right.activeHarm;
}
}
});
var Dropdown_up = new Vue({
el: '#dropmenu_up',
components: {
DropdownMenu
},
data: {
text: "Up",
activeHarm: 'Octave',
harmonics: [
'Fundamental',
'2nd minor',
'2nd Major',
'3rd minor',
'3rd Major',
'4th',
'5th minor',
'5th',
'6th minor',
'6th Major',
'7th minor',
'7th Major',
'Octave'
]
},
methods: {
changeHarmonic: function(harmonic) {
this.activeHarm = harmonic;
upLabel.updateLabel();
switch (this.activeHarm) {
case 'Fundamental':
h_up = h1;
break;
case '2nd minor':
h_up = h2b;
break;
case '2nd Major':
h_up = h2;
break;
case '3rd minor':
h_up = h3b;
break;
case '3rd Major':
h_up = h3;
break;
case '4th':
h_up = h4;
break;
case '5th minor':
h_up = h5b;
break;
case '5th':
h_up = h5;
break;
case '6th minor':
h_up = h6b;
break;
case '6th Major':
h_up = h6;
break;
case '7th minor':
h_up = h7b;
break;
case '7th Major':
h_up = h7;
break;
case 'Octave':
h_up = h8;
break;
}
}
}
});
var upLabel = new Vue ({
el: '#label_up',
data: {
labelHarm: Dropdown_up.activeHarm
},
methods: {
updateLabel: function() {
this.labelHarm = Dropdown_up.activeHarm;
}
}
});
var Dropdown_down = new Vue({
el: '#dropmenu_down',
components: {
DropdownMenu
},
data: {
text: "Down",
activeHarm: 'Fundamental',
harmonics: [
'Fundamental',
'2nd minor',
'2nd Major',
'3rd minor',
'3rd Major',
'4th',
'5th minor',
'5th',
'6th minor',
'6th Major',
'7th minor',
'7th Major',
'Octave'
]
},
methods: {
changeHarmonic: function(harmonic) {
this.activeHarm = harmonic;
downLabel.updateLabel();
switch (this.activeHarm) {
case 'Fundamental':
h_down = h1;
break;
case '2nd minor':
h_down = h2b;
break;
case '2nd Major':
h_down = h2;
break;
case '3rd minor':
h_down = h3b;
break;
case '3rd Major':
h_down = h3;
break;
case '4th':
h_down = h4;
break;
case '5th minor':
h_down = h5b;
break;
case '5th':
h_down = h5;
break;
case '6th minor':
h_down = h6b;
break;
case '6th Major':
h_down = h6;
break;
case '7th minor':
h_down = h7b;
break;
case '7th Major':
h_down = h7;
break;
case 'Octave':
h_down = h8;
break;
}
}
}
});
var downLabel = new Vue ({
el: '#label_down',
data: {
labelHarm: Dropdown_down.activeHarm
},
methods: {
updateLabel: function() {
this.labelHarm = Dropdown_down.activeHarm;
}
}
});
var Dropdown = new Vue({
el: '#dropmenu',
components: {
DropdownMenu
},
data: {
text: "Sound",
activeInstrument: 'El. Piano 1',
instruments: [
'El. Piano 1',
'Piano',
'Rock Organ 1',
'Rock Organ 2',
'Synth Triangle',
'Synth',
'Voce Manu',
'Voce Fede',
'Flute',
'Trumpet',
'Temp',
]
},
methods: {
changeInstrument: function(instrument) {
this.activeInstrument = instrument;
switch (this.activeInstrument) {
case 'El. Piano 1':
vect1 = ELPIANO1f;
amp1 = ELPIANO1a;
max = vect1.length*3;
noisegain = 0.002;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0;
Envelope.form.decayTime = 0.221;
Envelope.form.sustainLevel = 0.48;
Envelope.form.releaseTime = 0.05;
break;
case 'Rock Organ 1':
vect1 = ORGAN1f;
amp1 = ORGAN1a;
max = vect1.length*3;
noisegain = 0.012;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0;
Envelope.form.decayTime = 0.001;
Envelope.form.sustainLevel = 1;
Envelope.form.releaseTime = 0.05;
break;
case 'Piano':
vect1 = PIANO1f;
amp1 = PIANO1a;
max = vect1.length*3;
noisegain = 0.001;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0.01;
Envelope.form.decayTime = 0.271;
Envelope.form.sustainLevel = 0.33;
Envelope.form.releaseTime = 0.1;
break;
case 'Rock Organ 2':
vect1 = ORGAN2f;
amp1 = ORGAN2a;
max = vect1.length*3;
noisegain = 0.010;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0;
Envelope.form.decayTime = 0.001;
Envelope.form.sustainLevel = 1;
Envelope.form.releaseTime = 0.05;
break;
case 'Synth Triangle':
vect1 = TRI1f;
amp1 = TRI1a;
max = vect1.length*3;
noisegain = 0.003;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0;
Envelope.form.decayTime = 0.001;
Envelope.form.sustainLevel = 1;
Envelope.form.releaseTime = 0.01;
break;
case 'Synth':
vect1 = SYNTH1f;
amp1 = SYNTH1a;
max = vect1.length*3;
noisegain = 0.008;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0.05;
Envelope.form.decayTime = 0.05;
Envelope.form.sustainLevel = 0.6;
Envelope.form.releaseTime = 0.01;
break;
case 'Voce Manu':
vect1 = MANU1f;
amp1 = MANU1a;
max = vect1.length*3;
noisegain = 0.010;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
break;
case 'Voce Fede':
vect1 = FEDE1f;
amp1 = FEDE1a;
max = vect1.length*3;
noisegain = 0.014;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
break;
case 'Temp':
vect1 = TEMP1f;
amp1 = TEMP1a;
max = vect1.length*3;
noisegain = 0.002;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
break;
case 'Flute':
vect1 = TEMP11f;
amp1 = TEMP11a;
max = vect1.length*3;
noisegain = 0.008;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0.04;
Envelope.form.decayTime = 0.401;
Envelope.form.sustainLevel = 0.26;
Envelope.form.releaseTime = 0.26;
break;
case 'Trumpet':
vect1 = TEMP21f;
amp1 = TEMP21a;
max = vect1.length*3;
noisegain = 0.010;
for(i=0;i<max;i++){
gates[i] = [];
oscStop[i] = [];
}
Envelope.form.attackTime = 0.01;
Envelope.form.decayTime = 0.051;
Envelope.form.sustainLevel = 0.58;
Envelope.form.releaseTime = 0.19;
break;
}
}
}
});
// Vue component for the ADSR diagram
const EnvelopeGenerator = Vue.component('envelope-generator', {
name: 'EnvelopeGenerator',
template: "#adsr",
props: {
width: {
type: Number,
default: 640
},
height: {
type: Number,
default: 480
},
attack: {
type: Number,
required: true,
validaor: v => 0 <= v && v <= 1
},
decay: {
type: Number,
required: true,
validaor: v => 0 <= v && v <= 1
},
sustain: {
type: Number,
required: true,
validaor: v => 0 <= v && v <= 1
},
release: {
type: Number,
required: true,
validaor: v => 0 <= v && v <= 1
}
},
data () {
return {
path: '',
array: []
}
},
mounted() {
this.draw();
},
watch: {
attack: function () { this.draw(); },
decay: function () { this.draw(); },
sustain: function () { this.draw(); },
release: function () { this.draw(); }
},
methods: {
draw() {
const wRetio = this.width / 6;
const hRetio = this.height / 1;
this.array=[];
var paths = this.array;
let x, y;
x = y = 0;
// attack
x = (this.attack * wRetio)+7;
y = 7;
paths.push(`${x}`);
paths.push(`${y}`);
// decay
x += this.decay * wRetio;
if (this.sustain * hRetio == this.height){
y = this.height - this.sustain * hRetio +7;
} else {
y = this.height-11 - this.sustain * hRetio;
}
paths.push(`${x}`);
paths.push(`${y}`);
// sustain
x += 1 * wRetio;
paths.push(`${x}`);
paths.push(`${y}`);
// release
x += this.release * wRetio;
y = this.height-11;
paths.push(`${x}`);
paths.push(`${y}`);
this.path = `M7 ${this.height-11},` + paths.join(',');
}
}
});
Envelope = new Vue({
el: '#app',
components: { EnvelopeGenerator },
data() {
return {
form: {
attackTime: 0, //Envelope.form.attackTime
decayTime: 0.221,
sustainLevel: 0.48,
releaseTime: 0.05
},
ctx: new AudioContext(),
osc: null,
adsr: null
}
},
methods: {
start() {
this.osc = this.ctx.createOscillator();
this.adsr = this.ctx.createGain();
// osc -> gain -> output
this.osc.connect(this.adsr);
this.adsr.connect(this.ctx.destination);
const t0 = this.ctx.currentTime;
this.osc.start(t0);
// vol:0
this.adsr.gain.setValueAtTime(0, t0);
// attack
const t1 = t0 + this.form.attackTime;
this.adsr.gain.linearRampToValueAtTime(1, t1);
// decay
const t2 = this.form.decayTime;
this.adsr.gain.setTargetAtTime(this.form.sustainLevel, t1, t2);
},
stop() {
const t = this.ctx.currentTime;
this.adsr.gain.cancelScheduledValues(t);
this.adsr.gain.setValueAtTime(this.adsr.gain.value, t);
this.adsr.gain.setTargetAtTime(0, t, this.form.releaseTime);
const stop = setInterval(() => {
if (this.adsr.gain.value < 0.01) {
this.osc.stop();
clearInterval(stop);
}
}, 10);
},
}
});
// Vue objects for volume sliders
Master = new Vue({
el: '.master-volume',
data: {
m_volume: 50
}
});
H1_volume = new Vue({
el: '.h1-volume',
data: {
h1_volume: 50
}
});
H2_volume = new Vue({
el: '.h2-volume',
data: {
h2_volume: 50
}
});
/*----------------MICROBIT bluetooth pairing----------------*/
var microbit = new uBit();
microbit.onConnect(function(){
btLabel.bt_log = "Device connected"
console.log("connected");
});
document.querySelector("#bt_button").addEventListener('click', event => {
microbit.searchDevice();
});
microbit.onBleNotify(function(){
aX = microbit.getAccelerometer().x;
aY = microbit.getAccelerometer().y;
aZ = microbit.getAccelerometer().z;
pitch = Math.atan(aX / Math.sqrt(Math.pow(aY, 2) + Math.pow(aZ, 2)));
roll = Math.atan(aY / Math.sqrt(Math.pow(aX, 2) + Math.pow(aZ, 2)));
//convert radians into degrees
pitch = pitch * (180.0 / Math.PI);
roll = -1 * roll * (180.0 / Math.PI);
// harmonic activation after a certain roll, pitch value
if(pitch>25) {
hh=h_up*actual_octaveUp;
ledUp.ledOn = true;
} else if(pitch<-25) {
hh=h_down*actual_octaveDown;
ledDown.ledOn = true;
} else {
hh = 0;
ledUp.ledOn = false;
ledDown.ledOn = false;
}
if(roll>25){
h=h_right*actual_octaveRight;
ledRight.ledOn = true;
} else if(roll<-25){
h=h_left*actual_octaveLeft;
ledLeft.ledOn = true;
} else {
h=0;
ledLeft.ledOn = false;
ledRight.ledOn = false;
}
});
/*----------------MIDI part----------------*/
// request MIDI access
if (navigator.requestMIDIAccess) {
navigator.requestMIDIAccess({
sysex: false
}).then(onMIDISuccess, onMIDIFailure);
} else {
alert("No MIDI support in your browser.");
}
var midi, data;
var temp;
var c = new AudioContext();
c.resume();
var notePresent = 0;
var bufferSize = 4096;
// noise generation for sounds
var pinkNoise = (function() {
var b0, b1, b2, b3, b4, b5, b6;
b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0.0;
var node = c.createScriptProcessor(bufferSize, 1, 1);
node.onaudioprocess = function(e) {
var output = e.outputBuffer.getChannelData(0);
for (var i = 0; i < bufferSize; i++) {
var white = Math.random() * 2 - 1;
b0 = 0.99886 * b0 + white * 0.0555179;
b1 = 0.99332 * b1 + white * 0.0750759;
b2 = 0.96900 * b2 + white * 0.1538520;
b3 = 0.86650 * b3 + white * 0.3104856;
b4 = 0.55000 * b4 + white * 0.5329522;
b5 = -0.7616 * b5 - white * 0.0168980;
output[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362;
output[i] *= 0.11; // (roughly) compensate for gain
b6 = white * 0.115926;
}
}
return node;
})();
var gp = c.createGain();
pinkNoise.connect(gp);
gp.gain.value = 0;
gp.connect(c.destination);
var now=[];
// initializing ADSR and Harmonics variables
var at = Envelope.form.attackTime;
var rt = Envelope.form.releaseTime;
var dt = Envelope.form.decayTime;
var h1_vol = H1_volume.h1_volume;
var h2_vol = H2_volume.h2_volume;
var master_vol = Master.m_volume;
var sustain_level = Envelope.form.sustainLevel;
var canvas = document.querySelector("#canvas");
var ctx = canvas.getContext("2d");
var analyser = c.createAnalyser();
analyser.fftSize =2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
function attack(midiNote, volume) {
h1_vol = H1_volume.h1_volume;
h2_vol = H2_volume.h2_volume;
at = Envelope.form.attackTime;
dt = Envelope.form.decayTime;
master_vol = Master.m_volume;
sustain_level = Envelope.form.sustainLevel;
notePresent++; // noise variable
//check if harmonics (to be played) are present or not
// h represents the first harmonic (Left/Right gesture), hh the second harmonic (Up/Down gesture)
if(h != 0 && hh != 0 ){
var vect2 = vect1.map(function(element) {
return element*h;
});
var amp2 = amp1.map(function(element) {
return element*(h1_vol/100);
});
var vect3 = vect1.map(function(element) {
return element*hh;
});
var amp3 = amp1.map(function(element) {
return element*(h2_vol/100);
});
var vect = vect1.concat(vect2);
vect = vect3.concat(vect);
var amp = amp1.concat(amp2);
amp = amp3.concat(amp);
}
else if(h != 0 ){
var vect2 = vect1.map(function(element) {
return element*h;//invece che *2 metti il valore microbit
});
var amp2 = amp1.map(function(element) {
return element*(h1_vol/100);
});
var vect = vect1.concat(vect2);
var amp = amp1.concat(amp2);
}
else if(hh != 0 ){
var vect2 = vect1.map(function(element) {
return element*hh;//invece che *2 metti il valore microbit
});
var amp2 = amp1.map(function(element) {
return element*(h2_vol/100);
});
var vect = vect1.concat(vect2);
var amp = amp1.concat(amp2);
}
else{
var vect = vect1;
var amp = amp1;
}
// voulume controls
volume = (master_vol/2000 + volume/1600)/3;
if (master_vol == 0) volume = 0;
// midi note
const freq = Math.pow(2, (midiNote-69)/12)*440;
//harmonic amplitudes oscillators and gains initialization
var ha = [];
var o = [];
var g = [];
gp.gain.value = noisegain*(master_vol/50);
// iteration to create the timbre summing sinusoids
for(i=0;i<max;i++){
o[i] = c.createOscillator();
}
for(i=0;i<max;i++){
g[i] = c.createGain();
}
for(i=0;i<max;i++){
g[i].connect(analyser);
}
for(i=0;i<max;i++){
o[i].connect(g[i])
}
analyser.connect(c.destination);
for(i=0;i<max;i++){
g[i].connect(c.destination);
}
// Cutting the frequency of the timbre that are higher than 22000hz
for(i=0;i<max;i++){
if(freq*vect[i]<22000){
o[i].frequency.value = freq*vect[i];
}
else {
o[i].frequency.value = 0;
}
}
// same as above with volume
for(i=0;i<max;i++){
if(freq*vect[i]<22000){
ha[i] = amp[i]; //volume array
}
else {
ha[i] = 0; //multiple of fundamental frequency array
}
}
// gain creation
for(i=0;i<max;i++){
g[i].gain.value = 0;
}
now[freq]= c.currentTime;
for(i=0;i<max;i++){
g[i].gain.linearRampToValueAtTime(volume/124*ha[i],now[freq]+at);
}
for(i=0;i<max;i++){
g[i].gain.linearRampToValueAtTime(sustain_level*volume/124*ha[i],now[freq]+at+dt);
}
// SOUND!!!!!!!!!!!!!
for(i=0;i<max;i++){
o[i].start();
}
// Filling gates and oscStop vectors that will be used in release
for(i=0;i<max;i++){
gates[i][freq] = g[i];
}
for(i=0;i<max;i++){
oscStop[i][midiNote] = o[i];
}
}
function release(midiNote) {
rt = Envelope.form.releaseTime; // release time
const freq = Math.pow(2, (midiNote-69)/12)*440; // midi note to release
notePresent--; // noise variable
if(notePresent==0) {
gp.gain.value = 0;
}
gates[0][freq].gain.linearRampToValueAtTime(0,c.currentTime+rt);
oscStop[0][midiNote].stop(c.currentTime+rt+0.01);
// controls to release the sound if the pressed key time is less than attack time
if(c.currentTime-now[freq]<at+dt){
for(i=1;i<max;i++){
gates[i][freq].gain.linearRampToValueAtTime(0,now[freq]+at+dt);
}
for(i=1;i<max;i++){
oscStop[i][midiNote].stop(c.currentTime+at+dt+0.01);
}
}
else{
for(i=1;i<max;i++){
gates[i][freq].gain.linearRampToValueAtTime(0,c.currentTime+rt);
}
for(i=1;i<max;i++){
oscStop[i][midiNote].stop(c.currentTime+rt+0.01);
}
}
// canvas harmonics design
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function onMIDISuccess(midiAccess) {
// when we get a succesful response, run this code
midi = midiAccess; // this is our raw MIDI data, inputs, outputs, and sysex status
var inputs = midi.inputs.values();
// loop over all available inputs and listen for any MIDI input
for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
// each time there is a midi message call the onMIDIMessage function
input.value.onmidimessage = onMIDIMessage;
}
}
function onMIDIFailure(error) {
// when we get a failed response, run this code
console.log("No access to MIDI devices or your browser doesn't support WebMIDI API. Please use WebMIDIAPIShim " + error);
}
function onMIDIMessage(message) {
data = message.data; // this gives us our [command/channel, note, velocity] data.
// MIDI data [144, 63, 73] in order type, key and velocity
var [command, key, velocity] = data;
if (command === 254) return; //because my keyboard sends command = 254 without stopping
else if (command === 144 && velocity!=0) {
attack(key, velocity);
// RELEASE command: keyboard Gianmarco = 128 --- keyboard Federico = 144 as attack command
} else if (command === 128 || (command === 144 && velocity === 0)) {
release(key);
}
}
/*----------------GRAPHIC PART----------------*/
//canvas drawing functions for frequency peaks
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//grid width and height
var bw = 400;
var bh = 400;
//padding around grid
var p = 0;
function drawCross() {
ctx.globalAlpha = 0.9
ctx.strokeStyle = 'rgba(125, 125, 125, 0.5)';
ctx.beginPath();
drawBoard();
};
function drawBoard() {
for (var x = 0; x <= bw; x += 2*(x/8+1)) {
ctx.moveTo(0.5 + x + p, p);
ctx.lineTo(0.5 + x + p, bh + p);
}
for (var x = 0; x <= bh; x += 10) {
ctx.moveTo(p, 0.5 + x + p);
ctx.lineTo(bw + p, 0.5 + x + p);
}
ctx.strokeStyle = 'rgba(125, 125, 125, 0.3)';
ctx.stroke();
};
// scene generation for three js part
camera.position.set(0,0,20);
const scene = new THREE.Scene();
var loader = new THREE.ObjectLoader();
var myObj;
var pivot = new THREE.Group();
var offsetX = -20;
var offsetY = -21;
var font_loader = new THREE.FontLoader(); // load the hand model
loader.load("./js/hand-for-lane.json",
// onLoad
function ( obj ) {
myObj = obj;
scene.add( obj );
myObj.rotation.x = offsetX;
myObj.rotation.y = offsetY;
var box = new THREE.Box3().setFromObject( myObj );
box.getCenter( myObj.position ); // this re-sets the mesh position
myObj.position.multiplyScalar( - 1 );
scene.add( pivot );
pivot.add( myObj );
},
// onProgress callback
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// onError callback
function ( err ) {
console.error( 'An error happened' );
}
);
// light point for the object
const light1 = new THREE.PointLight(0xffffff, 2, 0);
light1.position.set(200, 100, 500);
scene.add(light1);
function resizeCanvasToDisplaySize() {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (canvas.width !== width ||canvas.height !== height) {
// you must pass false here or three.js sadly fights the browser
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
}
function animate() {
requestAnimationFrame( animate );
render();
resizeCanvasToDisplaySize();
}
function render() {
pivot.rotation.x = -Math.PI*pitch/150;
camera.rotation.z = Math.PI*roll/150;
renderer.render(scene, camera);
}
animate();
// rendering of frequency peaks in canvas
function drawSamples() {
analyser.getByteFrequencyData(dataArray);
/* get the context of the image */
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawCross();
for(var i=0; i<dataArray.length; i++) {
ctx.fillRect(i, 285, 1, -dataArray[i]);
}
requestAnimationFrame(drawSamples);
}
drawSamples();
<file_sep>/README.md
# GESTURE GLOVE HARMONIZER
The WebApp has the purpose of adding to the fundamental MIDI note some harmonics that are chosen from the user according to the movement of the hand through the use of the BBC micro:bit.
The sound is synthesized directly by the WebApp which has its own timbra library.
The WebApp can be also used without the connection to the BBC micro:bit.
### Prequisites:
- Ultimate Gesture GLOVE white version (aka BBC micro:bit)
- MIDI Keyboard
### Installing:
As a WebApp, it can be executed in the browser, either online (https://manukko.github.io/Gesture_Glove_Harmonizer/) or downloading it and running in localhost.
It is necessary to host it in a webserver due to CORS policy limitations: this can be done for example by creating a web server in python (that has to be installed) with the command:
```
python -m http.server
```
Moreover, the micro:bit need a script that is downloadable here: https://makecode.microbit.org/_e9J5fpT64DJ5 in order to communicate via Bluetooth with the computer.
## Running the app
To properly interface with the WebApp, before opening it the MIDI keyboard must be connected to the PC. It is then possible to connect the micro:bit clicking on the "pair" button.
'LEFT' and 'RIGHT' are referred to the BBC micro:bit roll movement
'UP' and 'DOWN'are referred to the BBC micro:bit pitch movement
Each 'OCTAVE' button below each of the movement button allow the user to choose which octave the harmonization above is referred to:
-1 for the lower octave, 0 for the actual octave, 1 for the upper octave.
It is possible to change the timbre of the sound with the tools library pressing the key 'SOUND'.
It is possible to modify the Attack Decay Sustain Release (ADSR) of each musical instrument using the sliders
under the ADSR.
The lower right canvas represents the spectrum of the audio signal generated by the WebApp.
## Components
### Audio part
- MIDI sound generation
- Audio synthesis part
The code handles MIDI messages from the MIDI keyboard to start the attack and release functions. They generates a certain number of harmonics according to the synthesized sound: every time we press a key, the former allows us to generate the sound of the selected synthesizer with the proper number of harmonics. For each selected harmonic there is an oscillator which is connected with a proper gain to the output. Attack, release, sustain and decay are handled in JS with linear ramps.
A clever and simple algorithm on MATLAB select the proper number of harmonics from real recorded sample sound: for each sound, this number is the result of a compromise of reality and reproducibility in a web scenario (see "Synth effect" folder for code and samples).
In JS we have a static copy of the vector generated by this algorithm of the selected harmonics for each available sound on the dropmenu. If we select to reproduce one or two harmonics based on the position of the glove, both the fundamental note and the harmonics will sound with the same timbre. Among the default sounds which are selected by the algorithm, as an experiment, we proposed the synthesized version of the voice of two us to be chosen as a possible instrument. A pink noise has been added in some sounds to enrich them. See comments on code for further details.
### Graphic part
The GUI of the WebApp has been developed using VueJS Framework, to simplify the data responsiveness and data syncronization. In particular, there are different VueJS components, the most important are the ADSR part for envelope settings, the leds for harmonics activation and all the buttons, dropmenus and sliders of the interface.
As far as the envelope component is concerned, it has been drawn in svg to allow the refreshing of the diagram based on ADSR values.
In the upper part of the GUI there is a canvas, in which a 3d model (imported as a JSON object) replicates hand's movements of the micro:bit. It has been developed with ThreeJS, a WebGL API used for 3D Computer Graphics in web browser. To manage hand's orientation, roll rotation has been simulated by rotating the object around x axis, while pitch rotation by rotating the camera around z axis (to keep the pitch orientation reference).
### BBC micro:bit bluetooth communication
From 2017,thanks to the Web Bluetooth API of Google Chrome it is possible to connect to an application a BLE (Bluetooth Low Energy) device reading information from it and receiving notifications when certain values change. The connection to the device is only possible as a result of a voluntary action by the user (as in this case a click on the proper button on the graphical interface).
- https://www.html.it/articoli/introduzione-alle-web-bluetooth-api/
In particular, in order to transmit data to handle the harmonics to be reproduced, the accellerometer service has been used. It is worth mentioning the fact that a BLE service eats too much RAM memory to let the button service be used simultaneously with it without causing an overflow error. This would have prevented activating and deactivating the microprocessor without the need of shutting it down and pairing it again. Anyway accellerometer values on the three cartesian axis (properly converted into roll and pitch informations) are sufficient for our task. The bluetooth code pairing implementation has been developed by Bitty Software:
- http://www.bittysoftware.com/downloads.html
## Future implementations
One next step will be to integrate in this project a client-side JavaScript implementation, in a browser environment, of the Pitch shifting operation for a human voice recorded directly from a live input such as a microphone. Pitch shifting is a widely used operation, as an example, in all major commercial and open source Digital Audio Workstations and Mixing Softwares. There are algorithms that work in time domain, like Overlap and Add (OLA), Waveform Similarity based OLA (WSOLA) and delay line modulation, and others that work in the frequency domain, like the Phase Vocoder and Spectral Modelling. At the moment, ScriptProcessorNodes and AudioWorkers are operating on the time domain buffer data, on which FFT is computed. For what concerns frequency operations, like pitch shifting, the burden of the computational cost is due to the javascript implementation of FFT. A well-done improvement of this work would surely consist in analyzing computational costs and existence of audio artefacts in the implementation of such algorithms in the Web-audio-API itself.
A simple pitch detection algorithm for voice input (whose value is given in Hz), as a starting point, is shown hereafter.
- Code:
https://github.com/manukko/pitch_detection_future_work?fbclid=IwAR1jirUJ5YyZACAgVgIpi74W2hIuCxlgXkoYg0ED2AnhgUOZZNeTjbY_OXQ
- Try it:
https://manukko.github.io/pitch_detection_future_work/?fbclid=IwAR0VBmscqbVY3mNi3FPgexqmfSUKxLOySTJZA2QutbPY_liTolFjLiIYsko
## Framework used
- https://threejs.org/
- https://vuejs.org/
## PROMO Video (in italian)
https://1drv.ms/v/s!AnnhkH9OXjhOh91YWXE5xGYWvUX_gg
| 43f3d22c30b0649eb1c4261182e1a8b6b581ec26 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | manukko/Gesture_Glove_Harmonizer | 4bc33efa0bb32569c0ddad3f2de4717fd88b826a | cfaf24bb11d40852a143361ff75271c42cc7438b |
refs/heads/master | <repo_name>lynner123/gpst-js-basic-collection-practice<file_sep>/main/section-1/practice-4.js
'use strict';
module.exports = function collectSameElements(collectionA, objectB) {
let arr = collectionA.map(ele => ele.key).filter(key => objectB.value.includes(key));
return arr;
}; | 6823ca46588365e4d771eda0ca240de0dd5d9451 | [
"JavaScript"
] | 1 | JavaScript | lynner123/gpst-js-basic-collection-practice | 771acfb454e11a5dd38038a60904d53dcb14fed3 | 99f82d2086b1aaf9166adc947cd4127e89c1433c |
refs/heads/master | <repo_name>yennhi2404/DemoAngular<file_sep>/src/app/ip.component.ts
// import { Component } from '@angular/core';
// import { HttpClient } from '@angular/common/http';
// import { Observable } from 'rxjs';
// @Component({
// selector: 'app-ip',
// template: '<h3>ip comment</h3>',
// })
// export class IpComponent {
// constructor(private http: HttpClient){
// this.http.get('https://api.ipify.org/?format=json')
// .toPromise()
// .then(resJson => console.log(resJson))
// .catch(err => console.log(err));
// }
// }
<file_sep>/src/app/sign-in.component.ts
import { Component } from '@angular/core';
//import { Http, Headers } from '@angular/core';
@Component({
selector: 'app-sign-in',
template: `
<form (ngSubmit)="onSubmit(formSignIn);" #formSignIn="ngForm">
<input placeholder="Email" ngModel #txtEmail="ngModel" name="email" required email>
<!-- <p *ngIf = "formSignIn.controls.email?.errors?.required"> -->
<p *ngIf="txtEmail.touched && txtEmail.errors?.required">
Email is required
</p>
<p *ngIf="txtEmail.touched && txtEmail.errors?.email">
Email is not valid
</p>
<br><br>
<input type="<PASSWORD>" placeholder="<PASSWORD>" ngModel #txtPassword="ngModel" name="password" minlength="6" pattern="[a-z]*">
<br><br>
<div ngModelGroup="subjects">
<label><input type="checkbox" [ngModel]="false" name="NodeJS">NodeJS</label>
<label><input type="checkbox" [ngModel]="false" name="Angular">Angular</label>
<label><input type="checkbox" [ngModel]="false" name="ReactJS">ReactJS</label>
</div>
<br><br>
<button [disabled]="formSignIn.invalid">Submit</button>
</form>
<button>POST</button>
<p>{{ txtEmail.errors | json }}</p>
<p>{{ txtPassword.errors | json }}</p>
<p>{{ formSignIn.value | json }}</p>
`
})
export class SignInComponent{
onSubmit(formSignIn){
console.log(formSignIn);
throw new Error('Form is invalid');
}
} | 67393037cdab296d552c5357759245a125b620a7 | [
"TypeScript"
] | 2 | TypeScript | yennhi2404/DemoAngular | 5e94cdf319f656ed857d98ecdea381bc1a94483b | 882ce6372af0fed11f1017c5a8c46974732c1a46 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldController : MonoBehaviour {
HexWorld hexWorld;
public int width = 5;
public int height = 4;
public int TextureWidth = 144;
public int TextureHeight = 144;
public Projector projector;
[SerializeField]
Texture2D mouseHexTex;
Texture2D whiteTex;
Texture2D blackTex;
Texture2D falloffTex;
Material mat;
GenerateMouseHexTexture genMouseHexTex = new GenerateMouseHexTexture();
// Use this for initialization
void Start () {
// Initialize empty texture
mouseHexTex = new Texture2D( TextureWidth, TextureHeight, TextureFormat.RGB24, false );
whiteTex = new Texture2D( TextureWidth, TextureHeight, TextureFormat.RGB24, true );
blackTex = new Texture2D( TextureWidth, TextureHeight, TextureFormat.RGB24, true );
falloffTex = new Texture2D( 16, 1, TextureFormat.RGBA32, false );
falloffTex.alphaIsTransparency = true;
falloffTex.SetPixel(0,0,Color.black);
Color[] black = new Color[( TextureWidth * TextureHeight )];
for( int i = 0; i < black.Length; i++ ) {
black[i] = new Color( 0, 0, 0 );
}
mouseHexTex.SetPixels( 0, 0, TextureWidth, TextureHeight, black );
hexWorld = new HexWorld(width, height);
for( int x = 0; x < hexWorld.Width; x++ ) {
for( int y = 0; y < hexWorld.Height; y++ ) {
HexTile hexTile_data = hexWorld.GetHexTileAt( x, y );
GameObject hexTile_go = GameObject.CreatePrimitive( PrimitiveType.Cylinder );
hexTile_go.transform.position = hexTile_data.tilePosition;
hexTile_go.transform.localScale = new Vector3( 1, 0.1f, 1 );
}
}
//genMouseHexTex.SetRadius(32f, 48f);
//genMouseHexTex.SetColor( Color.black, Color.black );
genMouseHexTex.Generate( mouseHexTex, LineDrawer.LineWidth.Medium, LineDrawer.LineWidth.Medium);
mouseHexTex.wrapMode = TextureWrapMode.Clamp;
mat = new Material( Shader.Find( "Projector/Light" ) );
//mat = new Material( Shader.Find( "Projector/Multiply" ) );
mat.SetTexture( "_ShadowTex", mouseHexTex );
mat.SetTexture( "_FalloffTex", falloffTex );
mat.SetColor( "_Color", Color.red);
projector.material = mat;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TreeGen : MonoBehaviour {
Tree tree;
void Start () {
tree = new Tree( 2, 0.5f, 5 );
tree.newTree( "hallo", new Vector3(0,0,0) );
}
void Update () {
if(Input.GetKeyDown("space")) {
//tree.updateStem( Random.Range( ( 0.5f ), 10f ), Random.Range(( 0.2f ), 2f ));
tree.updateCrown();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexWorld {
HexTile[,] hexTiles;
int width;
public int Width {
get {
return width;
}
}
int height;
public int Height {
get {
return height;
}
}
public HexWorld(int width=5, int height=4) {
this.width = width;
this.height = height;
hexTiles = new HexTile[width, height];
for( int x = 0; x < width; x++ ) {
for( int y = 0; y < height; y++ ) {
hexTiles[x, y] = new HexTile( this, x, y );
}
}
//Debug.Log((width*height)+" HexTiles created!");
}
public HexTile GetHexTileAt(int x, int y) {
if( x > width || x < 0 || y > height || y < 0 ) {
//Debug.Log( "Tile ("+x+", "+y+") is out of range!" );
return null;
}
return hexTiles[x,y];
}
public bool IsInGrid(int x, int y) {
if( x > width || x < 0 || y > height || y < 0 ) {
//Debug.Log( "Tile (" + x + ", " + y + ") is not part of the grid!" );
return false;
}
return true;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexagonTile : MonoBehaviour{
Helper helper = new Helper();
public int x, y;
public Vector3 hexagonPosition;
public List<float> neighbors = new List<float>();
public Vector3[] borderWaypoints;
float rowOffset = Mathf.Sqrt( Mathf.Pow( 1, 2 ) - Mathf.Pow( 0.5f, 2 ) );
public HexagonTile(int _x, int _y) {
x = _x;
y = _y;
Debug.Log( "hexagonPosition" );
hexagonPosition = getTransform();
Debug.Log( "getNeighbours()" );
getNeighbours();
// generate a cylinder
GameObject hex = GameObject.CreatePrimitive( PrimitiveType.Cylinder );
hex.transform.position = hexagonPosition;
hex.transform.localScale = new Vector3(1,0.1f,1);
}
Vector3 getTransform() {
Vector3 xyz = new Vector3();
// set x based on the row
if(helper.isOdd(y)) { xyz.x = x + 0.5f; }
else { xyz.x = x; }
// set y based on het row
xyz.z = y * rowOffset;
// get height based on the terrain
xyz.y = getTerrainHeight( xyz.x, xyz.z );
return xyz;
}
float getTerrainHeight( float _x, float _y ) {
float height=0;
// add raycast
return height;
}
void getNeighbours() {
// calculate the height of the neighbours based on the terrain
neighbors.Add( getTerrainHeight( hexagonPosition.x - 0.5f, hexagonPosition.z + rowOffset ));
neighbors.Add( getTerrainHeight( hexagonPosition.x + 0.5f, hexagonPosition.z + rowOffset ));
neighbors.Add( getTerrainHeight( hexagonPosition.x +1, hexagonPosition.z ));
neighbors.Add( getTerrainHeight( hexagonPosition.x + 0.5f, hexagonPosition.z - rowOffset ));
neighbors.Add( getTerrainHeight( hexagonPosition.x - 0.5f, hexagonPosition.z - rowOffset ));
neighbors.Add( getTerrainHeight( hexagonPosition.x - 1, hexagonPosition.z ));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Tree {
public float stemHeight = 1f;
public float stemHeightMin;
public float stemHeightMax;
public float stemDia = 0.5f;
public float crownHeight = 3f;
public float crownHeightMin = 0.5f;
public float crownHeightMax = 15f;
public float crownDia = 3f;
public float crownDiaMin = 1.5f;
public float crownDiaMax = 10f;
public GameObject tree;
public GameObject stem;
public GameObject crown;
public Tree(float stemheight, float stemdiameter, float crownheight, float crowndiameter) {
stemHeight = stemheight;
stemDia = stemdiameter;
crownHeight = crownheight;
crownDia = crowndiameter;
tree = new GameObject();
}
public Tree( float stemheight, float stemdiameter, float crowndiameter ) {
stemHeight = stemheight;
stemDia = stemdiameter;
crownHeight = crowndiameter;
crownDia = crowndiameter;
tree = new GameObject();
}
public void newTree(string name, Vector3 worldposition) {
tree.name = name;
tree.transform.position = worldposition;
genStem();
genCrown();
}
public void updateStem( float stemheight, float stemdiameter ) {
stemHeight = stemheight;
stemDia = stemdiameter;
stemTransform();
crownTransform();
}
public void updateCrown() {
crownTransform();
}
void stemTransform() {
stem.transform.localScale = new Vector3( stemDia, stemHeight, stemDia );
stem.transform.position = new Vector3( 0, stemHeight, 0 );
}
public void genStem() {
stem = GameObject.CreatePrimitive( PrimitiveType.Cylinder );
stemTransform();
stem.transform.SetParent( tree.transform );
}
void crownTransform() {
crownHeight = Random.Range( crownHeightMin, crownHeightMax );
crownDia = Random.Range( ( stemDia * crownDiaMin ), ( stemDia * crownDiaMax ) );
crown.transform.localScale = new Vector3( crownDia, crownHeight, crownDia );
crown.transform.position = new Vector3( 0, ( ( (stemHeight * 2) + ( crownHeight / 2 ) ) - ( crownHeight / 30 ) ), 0 );
}
public void genCrown() {
crown = GameObject.CreatePrimitive( PrimitiveType.Sphere );
crownTransform();
crown.transform.SetParent( tree.transform );
}
public void setStemDiaRange( float min, float max ) {
}
public void setCrownDiaRange( float min, float max ) {
crownDiaMin = min;
crownDiaMax = max;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexagonGen : MonoBehaviour {
// Use this for initialization
void Start () {
for( int i = 0; i < 5; i++ ) {
for( int j = 0; j < 4; j++ ) {
HexagonTile hex = new HexagonTile( i, j );
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HexTile {
Helper helper;
float rowOffset = Mathf.Sqrt( Mathf.Pow( 1, 2 ) - Mathf.Pow( 0.5f, 2 ) );
HexWorld hexWorld;
int x;
int y;
public Vector3 tilePosition;
public Vector3[] neighbours = new Vector3[6];
public HexTile ( HexWorld hexGen, int x, int y) {
helper = new Helper();
this.hexWorld = hexGen;
this.x = x;
this.y = y;
tilePosition = getTransform();
PopulateNeighbours();
}
Vector3 getTransform() {
Vector3 xyz = new Vector3();
// set x based on the row
if( helper.isOdd( y ) ) { xyz.x = x + 0.5f; }
else { xyz.x = x; }
// set y based on het row
xyz.z = y * rowOffset;
// get height based on the terrain
xyz.y = getTerrainHeight( xyz.x, xyz.z );
return xyz;
}
float getTerrainHeight( float x, float y ) {
float height = 0;
// add raycast
return height;
}
void getNeighbour(int index, int x, int y) {
if( hexWorld.IsInGrid( x, y ) ) {
neighbours[index] = new Vector3( x - 1, y + 1, getTerrainHeight( x - 1, y + 1 ) );
}
else {
neighbours[index] = new Vector3(-1,-1,-1);
}
}
void PopulateNeighbours() {
// Neighbours Vector3( (int) grid x position, (int) grid y position, (float) world height position )
getNeighbour(0, x - 1, y + 1 );
getNeighbour(1, x + 1, y + 1 );
getNeighbour(2, x + 1, y );
getNeighbour(3, x + 1, y - 1 );
getNeighbour(4, x - 1, y - 1 );
getNeighbour(5, x - 1, y );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public Transform LookTransform;
public float planetDistance = 15f;
public float speed = 5f;
public float maxVelocityChange = 10.0f;
public float jumpForce = 5.0f;
public float groundHeight = 1.1f;
private float xRotation;
private float yRotation;
Rigidbody rb;
void Start() {
rb = this.GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate () {
RaycastHit groudedHit;
bool grounded = Physics.Raycast( transform.position, -transform.up, out groudedHit, groundHeight );
if (grounded) {
Vector3 forward = Vector3.Cross( transform.up, -LookTransform.right ).normalized;
Vector3 right = Vector3.Cross( transform.up, -LookTransform.forward ).normalized;
Vector3 targetVelocity = (forward * Input.GetAxis("Vertical") + right * Input.GetAxis("Horizontal")) * speed;
Vector3 velocity = transform.InverseTransformDirection(rb.velocity);
velocity.y = 0;
velocity = transform.TransformDirection(velocity);
Vector3 velocityChange = transform.InverseTransformDirection(targetVelocity - velocity);
velocityChange.x = Mathf.Clamp( velocityChange.x, -maxVelocityChange, maxVelocityChange );
velocityChange.z = Mathf.Clamp( velocityChange.z, -maxVelocityChange, maxVelocityChange );
velocityChange.y = 0;
velocityChange = transform.TransformDirection(velocityChange);
rb.AddForce(velocityChange, ForceMode.VelocityChange);
if (Input.GetButton("Jump")) {
rb.AddForce(transform.up * jumpForce, ForceMode.VelocityChange);
RaycastHit planetHit;
bool newPlanet = Physics.Raycast( transform.position, transform.up, out planetHit, planetDistance );
if (newPlanet) {
Debug.Log( "Switching to "+planetHit.collider.name);
transform.GetComponent<PlanetGravity>().setPlanet(planetHit.collider.transform);
}
}
}
Debug.DrawRay( transform.position, transform.up * planetDistance, Color.blue );
//Vector3 v = new Vector3( Input.GetAxis( "Horizontal" ), 0, Input.GetAxis( "Vertical" ) );
//rb.AddRelativeForce( v * speed);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Helper{
public Helper() {
}
public bool isOdd( int value ) {
return value % 2 != 0;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateMouseHexTexture : MonoBehaviour {
LineDrawer lineDrawer = new LineDrawer();
float ir = 48f;
float or = 64f;
Color icol = Color.white;
Color ocol = Color.white;
public void SetRadius(float innerRadius, float outerRadius) {
ir = innerRadius;
or = outerRadius;
}
public void SetColor( Color color ) {
icol = color;
ocol = color;
}
public void SetColor( Color innerColor, Color outerColor ) {
icol = innerColor;
ocol = outerColor;
}
public void Generate( Texture2D tex, LineDrawer.LineWidth innerLineWidth, LineDrawer.LineWidth outerLineWidth ) {
float x, y;
float cx = (tex.width / 2)-1;
float cy = (tex.height / 2)-1;
switch( outerLineWidth ) {
case LineDrawer.LineWidth.Thin:
if( or > cx ) or = cx-1;
if( or > cy ) or = cy-1;
break;
case LineDrawer.LineWidth.Medium:
if( or > cx-1 ) or = cx-2;
if( or > cy-1 ) or = cy-2;
break;
case LineDrawer.LineWidth.Thick:
if( or > cx - 2 ) or = cx - 3;
if( or > cy - 2 ) or = cy - 3;
break;
}
Vector2[] pInner = new Vector2[6];
Vector2[] pOuter = new Vector2[6];
for( int i = 0; i < 6; i++ ) {
y = cx + ir * Mathf.Cos( 2 * Mathf.PI * i / 6 );
x = cy + ir * Mathf.Sin( 2 * Mathf.PI * i / 6 );
//Debug.Log("Point "+i+": "+x+", "+y);
pInner[i].x = x;
pInner[i].y = y;
}
for( int i = 0; i < 6; i++ ) {
y = cx + or * Mathf.Cos( 2 * Mathf.PI * i / 6 );
x = cy + or * Mathf.Sin( 2 * Mathf.PI * i / 6 );
//Debug.Log("Point "+i+": "+x+", "+y);
pOuter[i].x = x;
pOuter[i].y = y;
}
for( int i = 0; i < 5; i++ ) {
// set linewidth;
lineDrawer.lw = outerLineWidth;
lineDrawer.DrawLine( tex, pInner[i], pOuter[i], ocol, false );
// set linewidth;
lineDrawer.lw = innerLineWidth;
lineDrawer.DrawLine( tex, pInner[i], pInner[i+1], icol );
}
// set linewidth;
lineDrawer.lw = outerLineWidth;
lineDrawer.DrawLine( tex, pInner[5], pOuter[5], ocol, false );
// set linewidth;
lineDrawer.lw = innerLineWidth;
lineDrawer.DrawLine( tex, pInner[5], pInner[0], icol );
lineDrawer.Apply( tex );
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlanetGravity : MonoBehaviour {
public Transform planet;
public bool AlignToPlanet;
public float gravity = 9.8f;
Rigidbody rb;
void Start() {
rb = transform.GetComponent<Rigidbody>();
}
void FixedUpdate() {
Vector3 gravityDirection = (planet.position - transform.position).normalized;
rb = transform.GetComponent<Rigidbody>();
Vector3 force = gravityDirection * gravity;
rb.AddForce(force, ForceMode.Acceleration);
Debug.DrawRay(transform.position, force, Color.red);
if (AlignToPlanet) {
Quaternion q = Quaternion.FromToRotation( transform.up, -gravityDirection );
q = q * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, q, 1);
}
}
public void setPlanet(Transform planet) {
this.planet = planet;
}
}
| 6708dbc8c9f61fb1b4745e6269aaae6101df23a5 | [
"C#"
] | 11 | C# | Blackwolfn/GameConcept | 31e8c72c6638af4372070c53bb86ad47d3b789dd | 6c49cf4987a3a0ab93d607ce3868da3fe887ba04 |
refs/heads/master | <file_sep>//
// BeerCell.swift
// StretchyHeaders
//
// Created by <NAME> on 7/4/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class BeerCell: UICollectionViewCell {
let TAG = NSStringFromClass(BeerCell)
@IBOutlet var beerImageView: UIImageView!
@IBOutlet var beerNameLabel: UILabel!
@IBOutlet var sinceLabel: UILabel!
var beer: Beer? {
didSet {
if let beer = self.beer {
beerImageView.image = UIImage(named: beer.image)
beerNameLabel.text = beer.title
sinceLabel.text = beer.since
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
<file_sep>//
// ScheduleHeaderView.swift
// StretchyHeaders
//
// Created by <NAME> on 7/4/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class CollectionHeaderView: UICollectionReusableView {
// custom your background image here
}<file_sep>//
// ViewController.swift
// StretchyHeaders
//
// Created by <NAME> on 7/3/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet var collectionView: UICollectionView!
var beers:[Beer] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
beers = Beer.getTestData()
setUpCollectionView()
}
func setUpCollectionView() {
let width = CGRectGetWidth(collectionView!.bounds)
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize(width: width, height: 180)
// custom all cell height here or you can custom height for each cell in UICollectionViewDataSource
layout.itemSize = CGSize(width: width, height: 62)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return beers.count
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "CollectionHeaderView", forIndexPath: indexPath) as! CollectionHeaderView
return header
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BeerCell", forIndexPath: indexPath) as! BeerCell
// let cellHeight:CGFloat = 600
// cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, cellHeight)
cell.beer = beers[indexPath.row]
return cell
}
// func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
// sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
// let width: CGFloat = self.view.bounds.width
//
// return CGSizeMake(width, 600);
// }
}
<file_sep>//
// Beer.swift
// StretchyHeaders
//
// Created by <NAME> on 7/4/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
import UIKit
class Beer {
var title: String
var image: String
var since: String
init(title: String, image:String, since: String) {
self.title = title
self.image = image
self.since = since
}
static func getTestData() -> [Beer]{
var beers:[Beer] = []
let bluemoon = Beer(title: "Blue Moon", image: "Bluemoon", since: "1995")
let budlight = Beer(title: "Bud light", image: "Budlight", since: "1876")
let budweiser = Beer(title: "Budweiser", image: "Budweiser", since: "1876")
let coolslight = Beer(title: "Cools light", image: "Coolslight", since: "1978")
let corona = Beer(title: "Corona", image: "Corona", since: "1925")
let guinness = Beer(title: "Guinness", image: "Guinness", since: "1759")
let pbr = Beer(title: "PBR", image: "PBR", since: "1844")
let select = Beer(title: "Select", image: "Select", since: "1876")
beers.append(bluemoon)
beers.append(budlight)
beers.append(budweiser)
beers.append(coolslight)
beers.append(corona)
beers.append(guinness)
beers.append(pbr)
beers.append(select)
return beers
}
}
| 4ebb0fbd5acc6b150247d34ca40d4550fdda7f24 | [
"Swift"
] | 4 | Swift | eclipsegst/ios-stretchy-header | 9dcd3b88ca0d4aeca40d45d6ef1b42154521ea96 | b125645999b00c0fba157436f8d84a8fbaf1eb67 |
refs/heads/master | <file_sep>import React from "react";
import {Redirect, Route, Switch} from "react-router-dom";
import {Home} from "./home/Home";
import {Profile} from "./profile/Profile";
import {useSelector} from "react-redux";
import {AddAdForm} from "./AddAdForm/AddAdForm";
import {OneAd} from "./oneAd/OneAd";
export const Routers = () => {
const isAuth = useSelector(({AuthReducer}) => AuthReducer.isAuth)
if (isAuth) {
return <Switch>
<Route exact path={'/'} component={Home}/>
<Route path={'/profile/:params?'} component={Profile}/>
<Route path={'/addAd/:adId?'} component={AddAdForm}/>
<Route path={'/ad/:adId?'} component={OneAd}/>
<Redirect to='/'/>
</Switch>
}
else{
return <Switch>
<Route path={'/:params?'} component={Home}/>
<Redirect to='/'/>
</Switch>
}
}
<file_sep>import {API_MESSAGE, IS_AUTH, IS_LOAD_AUTH} from "./AuthReducer";
import {authAPI} from "../../API/Api";
export const AuthActions = {
isAuthAC: (payload) => ({type: IS_AUTH, payload}),
messageApiAC: (messageApi) => ({type: API_MESSAGE, messageApi}),
isLoadAuthAC:(isLoadAuth)=>({type:IS_LOAD_AUTH,isLoadAuth})
}
export const registrationThunk = ({...form}) => async dispatch => {
try {
dispatch(AuthActions.isLoadAuthAC(false))
const data = await authAPI.registerAPI({...form})
dispatch(AuthActions.isLoadAuthAC(true))
if (data.isRegistered) {
dispatch(AuthActions.messageApiAC(data.message))
}
else{
console.log(data)
}
} catch (e) {
dispatch(AuthActions.messageApiAC('Ошибка регистрации. Попробуйте снова'))
}
}
export const loginThunk = ({...form}) => async dispatch => {
try {
dispatch(AuthActions.isLoadAuthAC(false))
const data = await authAPI.loginAPI({...form})
dispatch(AuthActions.isLoadAuthAC(false))
if (data.isAuth) {
dispatch(AuthActions.isAuthAC(data))
}
} catch (e) {
dispatch(AuthActions.messageApiAC('Неверный логин или пароль'))
}
}<file_sep>import React from "react";
import './MyAds.scss'
import {Link} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {getMyAdsThunk} from "../../redux/profile/ProfileActions";
import {Ad} from "../../components/ad/Ad";
import {Preloader} from "../../components/preloaders/Preloader";
export const MyAds = () => {
const dispatch = useDispatch()
const {userId, token, myAds, isLoad} = useSelector(state => {
return {
userId: state.AuthReducer.userId,
token: state.AuthReducer.token,
myAds: state.ProfileReducer.myAds,
isLoad: state.ProfileReducer.isLoad
}
})
React.useEffect(() => {
dispatch(getMyAdsThunk(userId, token))
}, [dispatch,userId,token])
return <div className='ads'>
{myAds
? <>{isLoad
? <>{
myAds.map(m =><div className='ads__block' key={m._id}>
<div className='line'/>
<Ad {...m}/>
</div>)
}</>
: <Preloader/>
}</>
: <>
<h1> Мои объявления</h1>
<p>У вас пока нет объявлений</p>
<button className='ads__button'><Link to='/addAd'>Подать объявление</Link></button>
</>}
</div>
}<file_sep>import React from "react";
import './AddAdForm.scss'
import {Link,Redirect,useParams} from "react-router-dom";
import {addOrEditAdThunk, getMyAdsThunk, ProfileActions} from "../../redux/profile/ProfileActions";
import {useDispatch, useSelector} from "react-redux";
import cn from 'classnames'
import {Preloader} from "../../components/preloaders/Preloader";
import avito_logo from '../../assets/image/avito_logo.png'
export const AddAdForm = () => {
const dispatch = useDispatch()
let {adId} = useParams();
const date = new Date();
const currentDate = date.getDate() + '.' + date.getMonth() + '.' + date.getFullYear()
const {userName, userId,isAddedAd,myAds,token,isLoad} = useSelector(state => {
return {
userId: state.AuthReducer.userId,
userName: state.AuthReducer.userName,
isAddedAd:state.ProfileReducer.isAddedAd,
myAds:state.ProfileReducer.myAds,
token: state.AuthReducer.token,
isLoad: state.ProfileReducer.isLoad,
}
})
React.useEffect( ()=> {
if (adId) {
dispatch(ProfileActions.isAddedAdAC(false))
dispatch(getMyAdsThunk(userId, token))
}
},[dispatch,adId,userId,token])
React.useEffect(()=>{
if(isLoad && adId){
const a = myAds.filter(f => f._id === adId)
setForm(a[0])
}
},[myAds,isLoad,adId])
const [form, setForm] = React.useState({
title: '',
address: '',
email:'',
phone: '',
description: '',
userId,
price: '',
date: currentDate,
userName
})
const changeHandler = event => {
setForm({...form, [event.target.name]: event.target.value})
}
const changeFiles = async event => {
let photo = event.target.files[0]
let typeList = photo.type.split('/')
if (typeList[0] === 'image') {
let basePhoto = await convertBase64(photo)
setForm({...form, photo: basePhoto})
}
}
const convertBase64 = file => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.readAsDataURL(file)
fileReader.onload = () => {
resolve(fileReader.result)
}
fileReader.onerror = (error) => {
reject(error)
}
})
}
const addFormHandler = (event) => {
event.preventDefault()
dispatch(addOrEditAdThunk(form,adId,token))
}
if(isAddedAd){
return <Redirect to='/profile/myAds'/>
}
if(!isLoad){
return<Preloader/>
}
return <div className='formContainer'>
<form className='form'>
<label className='title' htmlFor='title'>
<h3>Название</h3>
<input className='input'
type='text'
id='title'
name='title'
value={form.title}
onChange={changeHandler}
placeholder='Введите название'/>
</label>
<label className='address' htmlFor='address'>
<h3>Адрес</h3>
<input className='input'
type='text'
id='address'
name='address'
value={form.address}
onChange={changeHandler}
placeholder='Введите адрес'/>
</label>
<div className='contacts'>
<h3>Контакты</h3>
<label htmlFor='email'>
<p>Электронная почта</p>
<input className='input'
type='email'
id='email'
name='email'
value={form.email}
onChange={changeHandler}
placeholder='Введите электронную почту'/>
</label>
<label htmlFor='phone'>
<p>Телефон</p>
<input className='input'
type="tel"
id='phone'
name='phone'
value={form.phone}
onChange={changeHandler}
placeholder='Введите адрес'/>
</label>
</div>
<div className='description'>
<label htmlFor='description'>
<h3>Описание</h3>
<textarea className='textarea'
id='description'
name='description'
value={form.description}
onChange={changeHandler}
placeholder='Введите описание'/>
</label>
</div>
<label className='price' htmlFor='price'>
<h3>Цена</h3>
<input className='input'
type='number'
id='price'
name='price'
value={form.price}
onChange={changeHandler}
placeholder='Введите цену'/>
</label>
<label className='photos' htmlFor='photos'>
<h3>фотографии</h3>
<input className='photos'
type='file'
id='photos'
name='photos'
onChange={changeFiles}/>
<img alt='preview photo' src={form.photo || avito_logo}/>
</label>
<button onClick={addFormHandler}
className={cn('blueButton', 'buttonPosition')}>
Добавить
</button>
<button className={cn('whiteButton', 'buttonPosition')}>
<Link to={'/profile/myAds'}>
Отмена
</Link>
</button>
</form>
</div>
}<file_sep>import React from 'react'
import {Link} from "react-router-dom";
import './Login.scss'
import cn from 'classnames'
import {loginThunk} from "../../redux/auth/AuthActions";
import {useDispatch, useSelector} from "react-redux";
export const Login = () => {
const dispatch = useDispatch()
const {message, isLoadAuth} = useSelector(({AuthReducer}) => {
return {
message: AuthReducer.message,
isLoadAuth: AuthReducer.isLoadAuth
}
})
const [form, setForm] = React.useState({
login: '', password: ''
})
const changeHandler = event => {
setForm({...form, [event.target.name]: event.target.value})
}
const submitForm = () => {
dispatch(loginThunk(form))
}
return <div className='login'>
<div className='login__form'>
<h3>Вход</h3>
<input type='text'
name='login'
value={form.login}
onChange={changeHandler}
placeholder='Телефон или электронная почта'/>
<input type='<PASSWORD>'
name='password'
onChange={changeHandler}
value={form.password}
placeholder='<PASSWORD>'/>
<div className='status'>
{message && <p>
{message}
</p>}
</div>
<button disabled={!isLoadAuth} onClick={submitForm} className={cn('blueButton', 'padding')}>
{isLoadAuth
? <>Войти</>
: <>...вход</>
}
</button>
</div>
<div className='login__sn'>
</div>
<div className='login__registerButton'>
<button className='button'>
<Link to='/signUp'>Зарегистрироваться</Link>
</button>
</div>
<Link className='login__close' to={'/'}>
<div className='closeButton'/>
</Link>
</div>
}<file_sep>export const IS_AUTH='IS_AUTH'
export const API_MESSAGE='API_MESSAGE'
export const IS_LOAD_AUTH='IS_LOAD_AUTH'
const initialState = {
isAuth:false,
token:'',
userId:0,
message:'',
userName:'',
isLoadAuth:true
}
export const AuthReducer = (state=initialState,action)=>{
switch (action.type) {
case IS_AUTH:
const storageName = 'userData';
const{isAuth,token,userId:id,userName}=action.payload
localStorage.setItem(storageName, JSON.stringify({
userId:id, token,isAuth,userName
}))
return{
...state,
isAuth: isAuth,
token:token,
userId:id,
userName
}
case API_MESSAGE:
return{
...state,
message: action.messageApi
}
case IS_LOAD_AUTH:
return{
...state,
isLoadAuth: action.isLoadAuth
}
default:
return state
}
}<file_sep>import React from "react";
import './Popup.scss'
import {useDispatch, useSelector} from "react-redux";
import {deleteOneAd} from "../../redux/profile/ProfileActions";
import {Link} from "react-router-dom";
export const Popup = ({setVisiblePopup, id}) => {
const {myAds, token} = useSelector(state => ({
myAds: state.ProfileReducer.myAds,
token: state.AuthReducer.token
}))
const dispatch = useDispatch()
const editAdHandler = (event) => {
event.preventDefault()
setVisiblePopup(false)
}
const deleteAdHandler = () => {
dispatch(deleteOneAd(id, myAds,token))
setVisiblePopup(false)
}
return <div className='popup'>
<ul>
<li onClick={editAdHandler}><Link to={`/addAd/${id}`}>Исправить</Link></li>
<li onClick={deleteAdHandler}>Удалить</li>
</ul>
</div>
}<file_sep>import axios from "axios";
export const authAPI = {
registerAPI({...form}) {
return axios.post('/api/auth/register', {...form}).then(res => res.data)
},
loginAPI({...form}) {
return axios.post('/api/auth/login', {...form}).then(res => res.data)
}
}
export const profileAPI = {
addAdAPI({...form}) {
return axios.post(`/ad`, {...form}).then(res => res.data)
},
getAds() {
return axios.get('/ad').then(res => res.data)
},
getMyAds(userId, token) {
return axios.get(`/user/${userId}`, {
headers: {
Authorization: `Bearer ${token}`
}
}).then(res => res.data)
},
getOneAd(adId) {
return axios.get(`/ad/${adId}`).then(res => res.data)
},
deleteAd(adId,token) {
return axios.delete(`/ad/`+adId, { headers: {
Authorization: `Bearer ${token}`
}
}).then(res=>res.data)
},
editAd(id,form,token){
return axios.put('/ad',{adId:id,form},{headers: {
Authorization: `Bearer ${token}`
}}).then(res=>res.data)
}
}<file_sep>import { GET_ADS, GET_MY_ADS, GET_ONE_AD, IS_ADDED_AD, IS_LOAD, IS_MY_ADS} from "./ProfileReducer";
import {profileAPI} from "../../API/Api";
export const ProfileActions = {
getAdsAC: (ads) => ({type: GET_ADS, ads}),
getMyAdsAC: (myAds) => ({type: GET_MY_ADS, myAds}),
getOneAdAC: (oneAd) => ({type: GET_ONE_AD, oneAd}),
isLoadAC: (isLoad) => ({type: IS_LOAD, isLoad}),
isAddedAdAC: (isAddedAd) => ({type: IS_ADDED_AD, isAddedAd}),
isMyAdsAC:(isMyAds)=>({type:IS_MY_ADS,isMyAds})
}
export const addOrEditAdThunk = (form,adId,token) => async dispatch => {
try {
let data
if(adId){
data = await profileAPI.editAd(adId,form,token)
}else {
data = await profileAPI.addAdAPI({...form})
}
if (data.isAddedAd || data.isEditAd) {
dispatch(ProfileActions.isAddedAdAC(true))
}
} catch (e) {
console.log('error add ad')
}
}
export const GetAdsThunk = () => async dispatch => {
try {
dispatch(ProfileActions.isLoadAC(false))
const data = await profileAPI.getAds()
dispatch(ProfileActions.getAdsAC(data))
dispatch(ProfileActions.isLoadAC(true))
} catch (e) {
console.log('error getAds')
}
}
export const getMyAdsThunk = (userId, token) => async dispatch => {
try {
dispatch(ProfileActions.isLoadAC(false))
const data = await profileAPI.getMyAds(userId, token)
dispatch(ProfileActions.getMyAdsAC(data))
dispatch(ProfileActions.isLoadAC(true))
} catch (e) {
console.log('error getMyAds')
}
}
export const getOneAdThunk = (adId) => async dispatch => {
try {
dispatch(ProfileActions.isLoadAC(false))
const data = await profileAPI.getOneAd(adId)
dispatch(ProfileActions.getOneAdAC(data))
dispatch(ProfileActions.isLoadAC(true))
} catch (e) {
console.log('error getMyAds')
}
}
export const deleteOneAd = (adId,myAds,token)=>async dispatch=>{
try{
const data= await profileAPI.deleteAd(adId,token)
if(data.isDeleted){
const newMyAds=myAds.filter(f=>f._id!==adId)
dispatch(ProfileActions.getMyAdsAC(newMyAds))
}
}catch (e) {
console.log('error delete Ad')
}
}
<file_sep>import React from "react";
import './Preloader.scss'
import preloader from'../../assets/image/Preloader.gif'
export const Preloader = () =>{
return<div className='preloader' ><img alt='preloader' src={preloader} /></div>
}<file_sep>import React from "react";
export const Textarea =({input, meta, ...props}) => {
const hasError= meta.touched && meta.error;
return <div className={ 'formControl' + (hasError ? 'error' :"")}>
<div>
<textarea { ...input} { ...props} />
</div>
{hasError && <span className={'error'}>{meta.error}</span>}
</div>
}
export const Input =({input, error, ...props}) => {
const hasError= error;
return <div className={ 'formControl' + (hasError ? 'error' :"")}>
<div>
<input { ...input} { ...props} />
</div>
{hasError && <span className={'error'}>{error}</span>}
</div>
}<file_sep>import React from 'react'
import './Header.scss'
import logo from '../../assets/image/header/logo.svg'
import {Link} from "react-router-dom";
import {useSelector} from "react-redux";
export const Header = () => {
const {isAuth,userName} =useSelector(({AuthReducer})=>{
return{
isAuth:AuthReducer.isAuth,
userName:AuthReducer.userName
}
})
return <div className='header'>
<div className='header__buttons'>
<div className='buttonContainer'>
{!isAuth
?<button className='button'>
<Link to={'/signIn'}> вход и регистрация</Link>
</button>
:<button className='button'>
<Link to={'/profile/myAds'}>{userName}</Link>
</button>
}
<button className='blueButton'>
<Link to='/addAd'>Подать объявление</Link>
</button>
</div>
</div>
<div className='container'>
<Link className='container__logo' to={'/'}><img alt='logo' src={logo} /></Link>
<div className='container__search'>
<select className='categories'>
<option className='categories__category'>любая категория</option>
<option className='categories__category'>категория 1</option>
<option className='categories__category'>категория 2</option>
</select>
<input type='search' placeholder='поиск по объявлениям' className='container__inputSearch'/>
<select className='cites'>
<option className='cites__city'>наседенный пункт 1</option>
<option className='cites__city'>наседенный Пункт 2</option>
<option className='cites__city'>наседенный Пункт 3</option>
</select>
<select className='changeRadius'>
<option className='changeRadius__radius'>радиус</option>
<option className='changeRadius__radius'>2 км</option>
<option className='changeRadius__radius'>5 км</option>
</select>
<button className='whiteButton'>найти</button>
</div>
</div>
</div>
}<file_sep>export const GET_MY_ADS = 'GET_MY_ADS'
export const GET_ADS = 'GET_ADS'
export const GET_ONE_AD = 'GET_ONE_AD'
export const DELETE_MY_AD = 'DELETE_MY_AD'
export const IS_LOAD='IS_LOAD'
export const IS_ADDED_AD='IS_ADDED_AD'
export const IS_MY_ADS='IS_MY_ADS'
const initialState = {
ad: {
title: '',
address: '',
email: '',
phone: '',
description: '',
userId:'',
price: '',
date: 'currentDate',
userName:''
},
ads: [],
myAds: [],
adId:'',
isLoad:false,
isAddedAd:false,
isMyAds:false
}
export const ProfileReducer = (state = initialState, action) => {
switch (action.type) {
case GET_ADS:
return {
...state,
ads: action.ads
}
case GET_MY_ADS:
return {
...state,
myAds: action.myAds
}
case GET_ONE_AD:
return {
...state,
ad: action.oneAd
}
case IS_LOAD:
return {
...state,
isLoad:action.isLoad
}
case IS_ADDED_AD:
return{
...state,
isAddedAd:action.isAddedAd
}
case IS_MY_ADS:
return{
...state,
isMyAds:action.isMyAds
}
case DELETE_MY_AD:
return{
...state,
}
default:
return state
}
}<file_sep>import React from 'react'
import {useDispatch, useSelector} from "react-redux";
import {Login} from "../../components/login/Login";
import {Link, useParams, useHistory} from 'react-router-dom'
import './Home.scss'
import {CSSTransition, TransitionGroup} from "react-transition-group";
import {Registration} from "../../components/registration/Registration";
import {Ad} from "../../components/ad/Ad";
import {ProfileActions, GetAdsThunk} from "../../redux/profile/ProfileActions";
import {Preloader} from "../../components/preloaders/Preloader";
export const Home = () => {
const dispatch = useDispatch()
const {isAuth, ads, isLoad} = useSelector(state => {
return {
isAuth: state.AuthReducer.isAuth,
ads: state.ProfileReducer.ads,
isLoad: state.ProfileReducer.isLoad
}
})
let {params} = useParams();
let history = useHistory();
React.useEffect(() => {
if (isAuth) {
history.push('/')
}
}, [isAuth, history])
React.useEffect(() => {
dispatch(GetAdsThunk())
}, [dispatch])
React.useEffect(() => {
if(params!=='myAds'){
dispatch(ProfileActions.isMyAdsAC(false))
}
},[dispatch,params])
const adElement = ads.map(m => <Ad key={m._id} {...m} />)
return <div className='home'>
<TransitionGroup>
{params === 'signIn' && <CSSTransition classNames='animate' timeout={500}>
<>
<Login/>
<Link to={'/'}>
<div className='background'/>
</Link>
</>
</CSSTransition>}
</TransitionGroup>
<TransitionGroup>
{params === 'signUp' && <CSSTransition classNames='animate' timeout={500}>
<>
<Registration/>
<Link to={'/'}>
<div className='background'/>
</Link>
</>
</CSSTransition>}
</TransitionGroup>
{isLoad
? <>{adElement &&
adElement
}</>
: <Preloader/>
}
</div>
} | 3bab309d051896cbfe03b90b18d959c058fcdec6 | [
"JavaScript"
] | 14 | JavaScript | papyrinIS/copy_avito_frontend | 27bc6d684c5c2773e8d0b0640ff7fde4383bb171 | f4a25465c0a2f0c7660becbece7a4014c93f124c |
refs/heads/master | <file_sep><?php
if(!isset($_GET['id']) && !isset($_POST['submit'])){
echo "Invalid parameter";
exit;
}
// update driver here
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "uber";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$sql = "UPDATE drivers"
." SET name='".$_POST['name']."',"
." phone='".$_POST['phone']."',"
." fare=".$_POST['fare'].","
." total_driven=".$_POST['total_driven'].","
." car_type='".$_POST['car_type']."',"
." car_number='".$_POST['car_number']."',"
." passenger_size=".$_POST['passenger_size']
." WHERE id=".intval($_POST['id']);
if ($conn->query($sql) === TRUE) {
echo "Driver updated successfully";
} else {
echo "Error updating driver: " . $conn->error;
}
$conn->close();
exit;
}
//
$row = [];
if($_GET['id']){
$sql = "SELECT * FROM drivers WHERE id=".intval($_GET['id']);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
} else {
echo "Driver not found";
exit;
}
}
?>
<!DOCTYPE html>
<!--[if lte IE 6]><html class="preIE7 preIE8 preIE9"><![endif]-->
<!--[if IE 7]><html class="preIE8 preIE9"><![endif]-->
<!--[if IE 8]><html class="preIE9"><![endif]-->
<!--[if gte IE 9]><!--><html><!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Driver Update</title>
<meta name="author" content="name">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" >
<link rel='stylesheet' href='/assets/css/style.css' type='text/css'>
</head>
<body>
<div class="container">
<div class="center"><h3>Update All Driver Info</h3>
<form method="POST" action="" >
<input type="text" name="name" placeholder="name" value="<?php echo $row['name']; ?>" /></br></br>
<input type="text" name="phone" placeholder="phone" value="<?php echo $row['phone']; ?>" /></br></br>
<input type="number" name="fare" placeholder="fare" value="<?php echo $row['fare']; ?>" /></br></br>
<input type="number" name="total_driven" placeholder="total_driven" value="<?php echo $row['total_driven']; ?>" /></br></br>
<input type="text" name="car_type" placeholder="car_type" value="<?php echo $row['car_type']; ?>" /></br></br>
<input type="text" name="car_number" placeholder="car_number" value="<?php echo $row['car_number']; ?>" /></br></br>
<input type="number" name="passenger_size" placeholder="passenger_size" value="<?php echo $row['passenger_size']; ?>"/></br></br>
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>"/>
<input type="submit" name="submit" />
</form>
</div>
</div>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep><?php
// update driver here
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "uber";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM drivers";
if(@$_GET['capacity'])
$sql = "SELECT * FROM drivers WHERE passenger_size>=".intval($_GET['capacity']);
if(@$_GET['sort'] == "rating")
$sql = "SELECT * FROM drivers order by rating DESC limit 5;";
if(@$_GET['sort']=='fined')
$sql = "SELECT * FROM drivers order by fined_count DESC limit 5;";
if(@$_GET['sort']=='earned')
$sql = "SELECT * FROM drivers order by total_driven DESC limit 5;";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<!--[if lte IE 6]><html class="preIE7 preIE8 preIE9"><![endif]-->
<!--[if IE 7]><html class="preIE8 preIE9"><![endif]-->
<!--[if IE 8]><html class="preIE9"><![endif]-->
<!--[if gte IE 9]><!--><html><!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Car Lists</title>
<meta name="author" content="name">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css" >
<link rel='stylesheet' href='assets/css/style.css' type='text/css'>
</head>
<body>
<div class="container">
<div class="row">
<h4>Filter By</h4>
<button onclick="window.location='car_list.php?sort=rating'" class="btn btn-primary">Rating</button>
<button onclick="window.location='car_list.php?sort=fined'" class="btn btn-primary">Fined</button>
<button onclick="window.location='car_list.php?sort=earned'" class="btn btn-primary">Earned</button>
</div>
<?php while($row = $result->fetch_assoc()): ?>
<div class="row">
<div class="col-xs-12 col-sm-3 col-md-3"><a href="#"><img src="assets\images\bmw-i8.jpg" class="img-responsive img-box img-thumbnail"></a></div>
<div class="col-xs-12 col-sm-9 col-md-9">
<div class="list-group">
<div class="list-group-item">
<div class="row-picture"><a href="#" title="sintret"><img class="circle img-thumbnail img-box" src="assets\images\bmw-i8.jpg" alt=""></a></div>
<div class="row-content">
<div class="list-group-item-heading"><a href="#" title="sintret"><small><?php echo $row['name']; ?></small></a></div>
<small>
<i class=""></i> Car Type <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['car_type']; ?></a></span> </br>
<i class=""></i> Capacity <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['passenger_size']; ?></a></span> </br>
<i class=""></i> Total Driven <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['total_driven']; ?> Kilometres</a></span> </br>
<i class=""></i> Car Number <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['car_number']; ?> </a></span> </br>
<i class=""></i> Fare <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['fare']; ?>/Kilometre </a></span></br>
<i class=""></i> Fined <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['fined_count']; ?> </a></span></br>
<i class=""></i> Earned <span class="twitter"> <i class="fa fa-twitter"></i> <a target="_blank" href="" alt="sintret" title="sintret">: <?php echo $row['total_driven']; ?> </a></span></br>
</small>
</div>
<div class="rating-block">
<h4>Average user rating</h4>
<h2 class="bold padding-bottom-7"><?php echo $row['rating']; ?><small>/ 5</small></h2>
<?php
for($i= 1; $i<= 5; $i++){
if($i<= $row['rating']){
echo '<button type="button" class="btn btn-warning btn-sm" aria-label="Left Align"><span class="glyphicon glyphicon-star" aria-hidden="true"></span></button>';
}else{
echo '<button type="button" class="btn btn-default btn-grey btn-sm" aria-label="Left Align"><span class="glyphicon glyphicon-star" aria-hidden="true"></span></button>';
}
}
?>
</div>
</div>
</div>
<hr>
</div>
</div>
<?php endwhile; ?>
</div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Oct 14, 2016 at 08:09 PM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 7.0.8
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: `uber`
--
-- --------------------------------------------------------
--
-- Table structure for table `drivers`
--
CREATE TABLE `drivers` (
`id` int(11) NOT NULL,
`name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`fare` int(11) NOT NULL,
`total_driven` int(11) NOT NULL,
`car_type` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`car_number` int(11) NOT NULL,
`passenger_size` int(11) NOT NULL,
`fined_count` int(11) NOT NULL,
`fine_sum` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `drivers`
--
INSERT INTO `drivers` (`id`, `name`, `phone`, `fare`, `total_driven`, `car_type`, `car_number`, `passenger_size`, `fined_count`, `fine_sum`, `rating`, `created_at`, `updated_at`) VALUES
(1, '<NAME>', '01744420401', 40, 500, 'Medium', 8848041, 4, 0, 0, 5, '2016-10-14 16:52:22', '2016-10-13 15:59:03'),
(2, '<NAME>', '8888888888', 34, 3554, 'Small', 21474836, 4, 1, 500, 4, '2016-10-14 17:07:16', '2016-10-13 16:19:54'),
(3, '<NAME>', '01719449891', 500, 900, 'Medium', 9922564, 4, 2, 800, 4, NULL, '2016-10-14 06:54:54'),
(4, '<NAME>', '65223', 200, 5000, 'Small', 26599, 2, 0, 0, 4, NULL, '2016-10-14 06:57:47'),
(6, 'Probhas', '893453', 2, 2, '0', 12135281, 2, 0, 0, 5, NULL, '2016-10-14 07:11:27'),
(7, 'Demo driver', '0172146095', 10, 1200, 'small car', 859522, 2, 0, 0, 0, NULL, '2016-10-14 16:55:12'),
(8, 'Mr Ruhul', '856625', 250, 4000, 'Medium', 566565, 5, 3, 1500, 5, NULL, '2016-10-14 06:54:54'),
(9, 'Probhas', '893453', 500, 4000, 'Medium', 852147, 4, 3, 1800, 5, NULL, '2016-10-14 07:11:27');
-- --------------------------------------------------------
--
-- Table structure for table `locations`
--
CREATE TABLE `locations` (
`id` int(11) NOT NULL,
`driverid` int(11) NOT NULL,
`latitude` decimal(10,0) NOT NULL,
`longitude` decimal(10,0) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `drivers`
--
ALTER TABLE `drivers`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `drivers`
--
ALTER TABLE `drivers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
/*!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># Uber
Ride anywhere
# Installation
```
git clone https://github.com/probasranjan/Uber.git
cd Uber
bower install
```
## MySQL Database Setup
Please consider uber.sql as a dummy data and feel to use import the dump to 'uber' database.
Alternately You can create tables manually.
```
CREATE DATABASE uber;
```
```
CREATE TABLE `drivers` (
`id` int(11) NOT NULL,
`name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`fare` int(11) NOT NULL,
`total_driven` int(11) NOT NULL,
`car_type` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`car_number` int(11) NOT NULL,
`passenger_size` int(11) NOT NULL,
`fined_count` int(11) NOT NULL,
`fine_sum` int(11) NOT NULL,
`rating` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
```
```
CREATE TABLE `locations` (
`id` int(11) NOT NULL,
`driverid` int(11) NOT NULL,
`latitude` decimal(10,0) NOT NULL,
`longitude` decimal(10,0) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
```
## Environments
```
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "uber";
```
## System Requirements
* PHP
* MYSQL
* NPM (For bower install)
## Run
Use your preferred HTTP Server to run this project.
# Screenshot
### Search Driver
```
localhost/
```

### Filter By Rating
```
localhost/car_list.php?sort=rating
```

### Filter By Top Earner
```
localhost/car_list.php?sort=earned
```

### Filter By Fines
```
localhost/car_list.php?sort=fined
```

### Add Driver
```
localhost/admin/add_driver.php
```

### update Driver
```
localhost/admin/update_driver.php?id=2
```

# License
You are free to do whatever you want.
# Conclusion
I strongly recommend you not to consider this is a complete project. But I would really love to learn more from you. Please feel free to give your valuable feedback to this quick draft.
Thank you for your time :)
<file_sep><?php
if(isset($_POST['submit'])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "uber";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO drivers (name, phone, fare,total_driven,car_type,car_number,passenger_size)
VALUES (
'".$_POST['name']."',
'".$_POST['phone']."',
".$_POST['fare'].",
".$_POST['total_driven'].",
'".$_POST['car_type']."',
'".$_POST['car_number']."',
".$_POST['passenger_size']
.")";
if ($conn->query($sql) === TRUE) {
echo "New driver successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
exit;
}
?>
<!DOCTYPE html>
<!--[if lte IE 6]><html class="preIE7 preIE8 preIE9"><![endif]-->
<!--[if IE 7]><html class="preIE8 preIE9"><![endif]-->
<!--[if IE 8]><html class="preIE9"><![endif]-->
<!--[if gte IE 9]><!--><html><!--<![endif]-->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>title</title>
<meta name="author" content="name">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">
<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" >
<link rel='stylesheet' href='/assets/css/style.css' type='text/css'>
</head>
<body>
<div class="container">
<div class="center"><h4>Add drivers</h4>
<form method="POST" action="">
<input type="text" name="name" placeholder="Driver Name" /></br></br>
<input type="text" name="phone" placeholder="Phone Number" /></br></br>
<input type="number" name="fare" placeholder="Fare/Km" /></br></br>
<input type="number" name="total_driven" placeholder="Total Driven" /></br></br>
<input type="text" name="car_type" placeholder="Car Type" /></br></br>
<input type="text" name="car_number" placeholder="Car Number" /></br></br>
<input type="number" name="passenger_size" placeholder="Passenger Size" /></br></br>
<div class="row">
<h2>
<div class="col-md-12">
<button type="submit" name ="submit" class="btn btn-labeled btn-success">
<span class="btn-label"><i class="glyphicon glyphicon-ok"></i></span>Submit</button>
<br />
</h2>
</div>
</form>
</div>
</div>
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
<script src="/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</html>
| 88da44258d9204e23c25420bcc2ba124d6bb7c85 | [
"Markdown",
"SQL",
"PHP"
] | 5 | PHP | probasranjan/Uber | d0cbb2825218c333ff8f3bf560d354ad93dd9541 | 33e623a64fc3fba263005c08d9c38016199f4979 |
refs/heads/master | <repo_name>Micaonthego/activerecord-costume-store-todo-nyc-web-career-012819<file_sep>/db/migrate/002_create_costume_stores.rb
class CreateCostumeStores < ActiveRecord::Migration[4.2]
# Create your costume_stores migration here
def change
create_table :costume_stores do |t|
t.string :name
t.string :location
t.integer :costume_inventory
t.integer :num_of_employees
t.boolean :still_in_business
t.datetime :opening_time
t.datetime :closing_time
t.timestamps null: false
end
end
end
| c34a1e17997cae53b9007e0f2c3401b8bd1633ef | [
"Ruby"
] | 1 | Ruby | Micaonthego/activerecord-costume-store-todo-nyc-web-career-012819 | ac866c2b1ea216eaddf68873da1a726e86e65e07 | b964a637803710545ce80e3e3a4b683389fd0879 |
refs/heads/master | <file_sep>package actionlib
import (
"fmt"
"sync"
"github.com/fetchrobotics/rosgo/ros"
)
type goalIDGenerator struct {
goals int
goalsMutex sync.RWMutex
nodeName string
}
func newGoalIDGenerator(nodeName string) *goalIDGenerator {
return &goalIDGenerator{
nodeName: nodeName,
}
}
func (g *goalIDGenerator) generateID() string {
g.goalsMutex.Lock()
defer g.goalsMutex.Unlock()
g.goals++
timeNow := ros.Now()
return fmt.Sprintf("%s-%d-%d-%d", g.nodeName, g.goals, timeNow.Sec, timeNow.NSec)
}
<file_sep>package ros
import (
"io"
)
// Reader implements io.Reader interface and provides a no-copy way to read N
// bytes via Next() method. Reader is used by generated message to de-serialize
// byte arrays ([]uint8) without/ copying underlying data.
type Reader struct {
s []byte
i int
}
// NewReader creates new Reader and adopts the byte slice.
// The caller must not modify the slice after this call.
func NewReader(s []byte) *Reader {
return &Reader{s, 0}
}
// Read implements the io.Reader interface. Like the other reader
// implementations, this implementation copies data from the original slice
// into "b".
func (r *Reader) Read(b []byte) (n int, err error) {
if r.i >= len(r.s) {
return 0, io.EOF
}
n = copy(b, r.s[r.i:])
r.i += n
return
}
// Next returns a slice containing the next n bytes from the buffer, advancing
// the buffer as if the bytes had been returned by Read. The resulting slice is
// a sub-slice of the original slice.
//
// Asking for more bytes than available would returns only the remaining bytes.
// Calling Next on an empty buffer, or after the buffer has been exhausted,
// returns an empty slice.
func (r *Reader) Next(n int) []byte {
m := len(r.s) - r.i
if n > m {
n = m
}
data := r.s[r.i : r.i+n]
r.i += n
return data
}
// Let implements the length remaining in the buffer
func (r *Reader) Len() int {
return len(r.s) - r.i
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"reflect"
"std_msgs"
"sync"
"time"
"github.com/fetchrobotics/rosgo/ros"
)
type defaultActionServer struct {
node ros.Node
autoStart bool
started bool
action string
actionType ActionType
actionResult ros.MessageType
actionResultType ros.MessageType
actionFeedback ros.MessageType
actionGoal ros.MessageType
statusMutex sync.RWMutex
statusFrequency ros.Rate
statusTimer *time.Ticker
handlers map[string]*serverGoalHandler
handlersTimeout ros.Duration
handlersMutex sync.Mutex
goalCallback interface{}
cancelCallback interface{}
lastCancel ros.Time
pubQueueSize int
subQueueSize int
goalSub ros.Subscriber
cancelSub ros.Subscriber
resultPub ros.Publisher
feedbackPub ros.Publisher
statusPub ros.Publisher
statusPubChan chan struct{}
goalIDGen *goalIDGenerator
shutdownChan chan struct{}
}
func newDefaultActionServer(node ros.Node, action string, actType ActionType, goalCb interface{}, cancelCb interface{}, start bool) *defaultActionServer {
return &defaultActionServer{
node: node,
autoStart: start,
started: false,
action: action,
actionType: actType,
actionResult: actType.ResultType(),
actionFeedback: actType.FeedbackType(),
actionGoal: actType.GoalType(),
handlersTimeout: ros.NewDuration(60, 0),
goalCallback: goalCb,
cancelCallback: cancelCb,
lastCancel: ros.Now(),
}
}
func (as *defaultActionServer) init() {
as.statusPubChan = make(chan struct{}, 10)
as.shutdownChan = make(chan struct{}, 10)
// setup goal id generator and goal handlers
as.goalIDGen = newGoalIDGenerator(as.node.Name())
as.handlers = map[string]*serverGoalHandler{}
// setup action result type so that we can create default result messages
res := as.actionResult.NewMessage().(ActionResult).GetResult()
as.actionResultType = res.Type()
// get frequency from ros params
as.statusFrequency = ros.NewRate(5.0)
// get queue sizes from ros params
// queue sizes not implemented by ros.Node yet
as.pubQueueSize = 50
as.subQueueSize = 50
as.goalSub = as.node.NewSubscriber(fmt.Sprintf("%s/goal", as.action), as.actionType.GoalType(), as.internalGoalCallback)
as.cancelSub = as.node.NewSubscriber(fmt.Sprintf("%s/cancel", as.action), actionlib_msgs.MsgGoalID, as.internalCancelCallback)
as.resultPub = as.node.NewPublisher(fmt.Sprintf("%s/result", as.action), as.actionType.ResultType())
as.feedbackPub = as.node.NewPublisher(fmt.Sprintf("%s/feedback", as.action), as.actionType.FeedbackType())
as.statusPub = as.node.NewPublisher(fmt.Sprintf("%s/status", as.action), actionlib_msgs.MsgGoalStatusArray)
}
func (as *defaultActionServer) Start() {
logger := as.node.Logger()
defer func() {
logger.Debug("defaultActionServer.start exit")
as.started = false
}()
// initialize subscribers and publishers
as.init()
// start status publish ticker that notifies at 5hz
as.statusTimer = time.NewTicker(time.Second / 5.0)
defer as.statusTimer.Stop()
as.started = true
for {
select {
case <-as.shutdownChan:
return
case <-as.statusTimer.C:
as.PublishStatus()
case <-as.statusPubChan:
arr := as.getStatus()
as.statusPub.Publish(arr)
}
}
}
// PublishResult publishes action result message
func (as *defaultActionServer) PublishResult(status actionlib_msgs.GoalStatus, result ros.Message) {
msg := as.actionResult.NewMessage().(ActionResult)
msg.SetHeader(std_msgs.Header{Stamp: ros.Now()})
msg.SetStatus(status)
msg.SetResult(result)
as.resultPub.Publish(msg)
}
// PublishFeedback publishes action feedback messages
func (as *defaultActionServer) PublishFeedback(status actionlib_msgs.GoalStatus, feedback ros.Message) {
msg := as.actionFeedback.NewMessage().(ActionFeedback)
msg.SetHeader(std_msgs.Header{Stamp: ros.Now()})
msg.SetStatus(status)
msg.SetFeedback(feedback)
as.feedbackPub.Publish(msg)
}
func (as *defaultActionServer) getStatus() *actionlib_msgs.GoalStatusArray {
as.handlersMutex.Lock()
defer as.handlersMutex.Unlock()
var statusList []actionlib_msgs.GoalStatus
if as.node.OK() {
for id, gh := range as.handlers {
handlerTime := gh.GetHandlerDestructionTime()
destroyTime := handlerTime.Add(as.handlersTimeout)
if !handlerTime.IsZero() && destroyTime.Cmp(ros.Now()) <= 0 {
delete(as.handlers, id)
continue
}
statusList = append(statusList, gh.GetGoalStatus())
}
}
goalStatus := &actionlib_msgs.GoalStatusArray{}
goalStatus.Header.Stamp = ros.Now()
goalStatus.StatusList = statusList
return goalStatus
}
func (as *defaultActionServer) PublishStatus() {
as.statusPubChan <- struct{}{}
}
// internalCancelCallback recieves cancel message from client
func (as *defaultActionServer) internalCancelCallback(goalID *actionlib_msgs.GoalID, event ros.MessageEvent) {
as.handlersMutex.Lock()
defer as.handlersMutex.Unlock()
goalFound := false
logger := as.node.Logger()
logger.Debug("Action server has received a new cancel request")
for id, gh := range as.handlers {
cancelAll := (goalID.Id == "" && goalID.Stamp.IsZero())
cancelCurrent := (goalID.Id == id)
st := gh.GetGoalStatus()
cancelBeforeStamp := (!goalID.Stamp.IsZero() && st.GoalId.Stamp.Cmp(goalID.Stamp) <= 0)
if cancelAll || cancelCurrent || cancelBeforeStamp {
if goalID.Id == st.GoalId.Id {
goalFound = true
}
if gh.SetCancelRequested() {
args := []reflect.Value{reflect.ValueOf(goalID)}
fun := reflect.ValueOf(as.cancelCallback)
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded <= 1 {
fun.Call(args[0:numArgsNeeded])
}
}
}
}
if goalID.Id != "" && !goalFound {
gh := newServerGoalHandlerWithGoalId(as, goalID)
as.handlers[goalID.Id] = gh
gh.SetHandlerDestructionTime(ros.Now())
}
if goalID.Stamp.Cmp(as.lastCancel) > 0 {
as.lastCancel = goalID.Stamp
}
}
// internalGoalCallback recieves the goals from client and checks if
// the goalID already exists in the status list. If not, it will call
// server's goalCallback with goal that was recieved from the client.
func (as *defaultActionServer) internalGoalCallback(goal ActionGoal, event ros.MessageEvent) {
as.handlersMutex.Lock()
defer as.handlersMutex.Unlock()
logger := as.node.Logger()
goalID := goal.GetGoalId()
for id, gh := range as.handlers {
if goalID.Id == id {
st := gh.GetGoalStatus()
logger.Debugf("Goal %s was already in the status list with status %+v", goalID.Id, st.Status)
if st.Status == actionlib_msgs.RECALLING {
st.Status = actionlib_msgs.RECALLED
result := as.actionResultType.NewMessage()
as.PublishResult(st, result)
}
gh.SetHandlerDestructionTime(ros.Now())
return
}
}
id := goalID.Id
if len(id) == 0 {
id = as.goalIDGen.generateID()
goal.SetGoalId(actionlib_msgs.GoalID{
Id: id,
Stamp: goalID.Stamp,
})
}
gh := newServerGoalHandlerWithGoal(as, goal)
as.handlers[id] = gh
if !goalID.Stamp.IsZero() && goalID.Stamp.Cmp(as.lastCancel) <= 0 {
gh.SetCancelled(nil, "timestamp older than last goal cancel")
return
}
args := []reflect.Value{reflect.ValueOf(goal), reflect.ValueOf(event)}
fun := reflect.ValueOf(as.goalCallback)
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded <= 1 {
fun.Call(args[0:numArgsNeeded])
}
}
func (as *defaultActionServer) getHandler(id string) *serverGoalHandler {
handler := as.handlers[id]
return handler
}
// RegisterGoalCallback replaces existing goal callback function with newly
// provided goal callback function.
func (as *defaultActionServer) RegisterGoalCallback(goalCb interface{}) {
as.goalCallback = goalCb
}
func (as *defaultActionServer) RegisterCancelCallback(cancelCb interface{}) {
as.cancelCallback = cancelCb
}
func (as *defaultActionServer) Shutdown() {
as.shutdownChan <- struct{}{}
}
<file_sep># actionlib [WIP]
## Package Summary
A pure go implementation for ROS action library built on top of ROSGO. This package is unstable and the API can change in future.
## Prerequisites
This library uses messages `GoalID`, `GoalStatus` and `GoalStatusArray` from `actionlib_msgs` package. Please generate Go code for the messages in `actionlib_msgs` package and place them in your `$GOPATH/src`.
Use the following commands after install `gengo`.
```cmd
gengo -out=$GOPATH/src msg actionlib_msgs/GoalID
gengo -out=$GOPATH/src msg actionlib_msgs/GoalStatus
gengo -out=$GOPATH/src msg actionlib_msgs/GoalStatusArray
```
## Status
This package implements all the features of actionlib library but is still very unstable and is still a work in progress to fix known issues and make this packge more robust. Following are the features that are implemented and what's to be added in the future.
### Implemented
- Action Client
- Action Server
- Simple Action Client
- Simple Action Server
- Client Goal Handler
- Server Goal Handler
- Go code generation from action definitons
### To Be Added
- Tests
- Documentation
- Fix for golint issues
- Go mod
## How To Use
Examples of client and server usage can be found in `rosgo/test` folder.
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"sync"
)
type Event uint8
const (
CancelRequest Event = iota + 1
Cancel
Reject
Accept
Succeed
Abort
)
func (e Event) String() string {
switch e {
case CancelRequest:
return "CANCEL_REQUEST"
case Cancel:
return "CANCEL"
case Reject:
return "REJECT"
case Accept:
return "ACCEPT"
case Succeed:
return "SUCCEED"
case Abort:
return "ABORT"
default:
return "UNKNOWN"
}
}
type serverStateMachine struct {
goalStatus actionlib_msgs.GoalStatus
mutex sync.RWMutex
}
func newServerStateMachine(goalID actionlib_msgs.GoalID) *serverStateMachine {
return &serverStateMachine{
goalStatus: actionlib_msgs.GoalStatus{
GoalId: goalID,
Status: actionlib_msgs.PENDING,
},
}
}
func (sm *serverStateMachine) transition(event Event, text string) (actionlib_msgs.GoalStatus, error) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
nextState := sm.goalStatus.Status
switch sm.goalStatus.Status {
case actionlib_msgs.PENDING:
switch event {
case Reject:
nextState = actionlib_msgs.REJECTED
break
case CancelRequest:
nextState = actionlib_msgs.RECALLING
break
case Cancel:
nextState = actionlib_msgs.RECALLED
break
case Accept:
nextState = actionlib_msgs.ACTIVE
break
default:
return sm.goalStatus, fmt.Errorf("invalid transition Event")
}
case actionlib_msgs.RECALLING:
switch event {
case Reject:
nextState = actionlib_msgs.REJECTED
break
case Cancel:
nextState = actionlib_msgs.RECALLED
break
case Accept:
nextState = actionlib_msgs.PREEMPTING
break
default:
return sm.goalStatus, fmt.Errorf("invalid transition Event")
}
case actionlib_msgs.ACTIVE:
switch event {
case Succeed:
nextState = actionlib_msgs.SUCCEEDED
break
case CancelRequest:
nextState = actionlib_msgs.PREEMPTING
break
case Cancel:
nextState = actionlib_msgs.PREEMPTED
break
case Abort:
nextState = actionlib_msgs.ABORTED
break
default:
return sm.goalStatus, fmt.Errorf("invalid transition Event")
}
case actionlib_msgs.PREEMPTING:
switch event {
case Succeed:
nextState = actionlib_msgs.SUCCEEDED
break
case Cancel:
nextState = actionlib_msgs.PREEMPTED
break
case Abort:
nextState = actionlib_msgs.ABORTED
break
default:
return sm.goalStatus, fmt.Errorf("invalid transition Event")
}
case actionlib_msgs.REJECTED:
break
case actionlib_msgs.RECALLED:
break
case actionlib_msgs.SUCCEEDED:
break
case actionlib_msgs.PREEMPTED:
break
case actionlib_msgs.ABORTED:
break
default:
return sm.goalStatus, fmt.Errorf("invalid state")
}
sm.goalStatus.Status = nextState
sm.goalStatus.Text = text
return sm.goalStatus, nil
}
func (sm *serverStateMachine) getStatus() actionlib_msgs.GoalStatus {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
return sm.goalStatus
}
<file_sep>package main
import (
"testing"
)
func assertEqual(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Fatalf("%s != %s", a, b)
}
}
<file_sep>package main
//go:generate gengo action actionlib_tutorials/Averaging
import (
"actionlib_tutorials"
"fmt"
"math"
"os"
"std_msgs"
"github.com/fetchrobotics/rosgo/actionlib"
"github.com/fetchrobotics/rosgo/ros"
)
type averagingServer struct {
node ros.Node
as actionlib.SimpleActionServer
dataCount int32
goal int32
sum float32
sumSq float64
feedback *actionlib_tutorials.AveragingFeedback
result *actionlib_tutorials.AveragingResult
sub ros.Subscriber
logger ros.Logger
}
func newAveragingServer(node ros.Node, name string) {
avg := new(averagingServer)
avg.node = node
avg.logger = node.Logger()
avg.as = actionlib.NewSimpleActionServer(node, name, actionlib_tutorials.ActionAveraging, nil, false)
avg.sub = node.NewSubscriber("/random_number", std_msgs.MsgFloat32, avg.analysisCallback)
avg.as.RegisterGoalCallback(avg.goalCallback)
avg.as.RegisterPreemptCallback(avg.preemptCallback)
avg.as.Start()
}
func (avg *averagingServer) goalCallback() {
avg.dataCount = 0
avg.sum = 0
avg.sumSq = 0
goal, err := avg.as.AcceptNewGoal()
if err != nil {
avg.logger.Errorf("Error accepting new goal: %v", err)
return
}
avgGoal, ok := goal.(*actionlib_tutorials.AveragingGoal)
if !ok {
avg.logger.Errorf("Error accepting new goal: expected averaging action goal")
return
}
avg.goal = avgGoal.Samples
}
func (avg *averagingServer) preemptCallback() {
avg.as.SetPreempted(nil, "")
}
func (avg *averagingServer) analysisCallback(msg *std_msgs.Float32) {
if !avg.as.IsActive() {
return
}
avg.dataCount++
avg.sum += msg.Data
avg.feedback.Sample = avg.dataCount
avg.feedback.Data = msg.Data
avg.feedback.Mean = avg.sum / float32(avg.dataCount)
avg.sumSq = math.Pow(float64(msg.Data), 2)
avg.feedback.StdDev = float32(math.Sqrt(math.Abs((avg.sumSq/float64(msg.Data) - math.Pow(float64(avg.feedback.Mean), 2)))))
if avg.dataCount > avg.goal {
avg.result.Mean = avg.feedback.Mean
avg.result.StdDev = avg.feedback.StdDev
if avg.result.Mean < 5.0 {
avg.logger.Info("Averaging action aborted")
avg.as.SetAborted(avg.result, "")
} else {
avg.logger.Info("Averaging action succeeded")
avg.as.SetSucceeded(avg.result, "")
}
}
}
func main() {
node, err := ros.NewNode("test_averaging_server", os.Args)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer node.Shutdown()
newAveragingServer(node, "averaging")
node.Spin()
}
<file_sep>## rosgo
[](https://godoc.org/github.com/fetchrobotics/rosgo)
[](https://travis-ci.org/fetchrobotics/rosgo)
## Package Summary
**rosgo** is pure Go implementation of [ROS](http://www.ros.org/) client library.
- Author: <NAME>
- Maintainer: Fetch Robotics
- License: Apache License 2.0
- Source: git [https://github.com/fetchrobotics/rosgo](https://github.com/fetchrobotics/rosgo)
- ROS Version Support: [Indigo] [Jade] [Melodic] [Noetic]
## Prerequisites
To use this library you should have installed ROS: [Install](wiki.ros.org/noetic/Installation/Ubuntu).
To run the tests please install all sensor msgs: `sudo apt install ros-noetic-desktop-full` for Ubuntu
## Status
**rosgo** is under development to implement all features of [ROS Client Library Requiements](http://www.ros.org/wiki/Implementing%20Client%20Libraries).
At present, following basic functions are provided.
- Parameter API (get/set/search....)
- ROS Slave API (with some exceptions)
- Publisher/Subscriber API (with TCPROS)
- Remapping
- Message Generation
- Action Servers
- Bus Statistics
Work to do:
- Go Module Support
- Tutorials
- ROS 2 Support
## How to use
Please look in the [test](test) folder for how to use rosgo in your projects.
## See also
- [rosgo in ROS Wiki](http://www.ros.org/wiki/rosgo)
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"std_msgs"
"sync"
"github.com/fetchrobotics/rosgo/ros"
)
type defaultActionClient struct {
started bool
node ros.Node
action string
actionType ActionType
actionResult ros.MessageType
actionResultType ros.MessageType
actionFeedback ros.MessageType
actionGoal ros.MessageType
goalPub ros.Publisher
cancelPub ros.Publisher
resultSub ros.Subscriber
feedbackSub ros.Subscriber
statusSub ros.Subscriber
logger ros.Logger
handlers []*clientGoalHandler
handlersMutex sync.RWMutex
goalIDGen *goalIDGenerator
statusReceived bool
callerID string
}
func newDefaultActionClient(node ros.Node, action string, actType ActionType) *defaultActionClient {
ac := &defaultActionClient{
node: node,
action: action,
actionType: actType,
actionResult: actType.ResultType(),
actionFeedback: actType.FeedbackType(),
actionGoal: actType.GoalType(),
logger: node.Logger(),
statusReceived: false,
goalIDGen: newGoalIDGenerator(node.Name()),
}
ac.goalPub = node.NewPublisher(fmt.Sprintf("%s/goal", action), actType.GoalType())
ac.cancelPub = node.NewPublisher(fmt.Sprintf("%s/cancel", action), actionlib_msgs.MsgGoalID)
ac.resultSub = node.NewSubscriber(fmt.Sprintf("%s/result", action), actType.ResultType(), ac.internalResultCallback)
ac.feedbackSub = node.NewSubscriber(fmt.Sprintf("%s/feedback", action), actType.FeedbackType(), ac.internalFeedbackCallback)
ac.statusSub = node.NewSubscriber(fmt.Sprintf("%s/status", action), actionlib_msgs.MsgGoalStatusArray, ac.internalStatusCallback)
return ac
}
func (ac *defaultActionClient) SendGoal(goal ros.Message, transitionCb, feedbackCb interface{}) ClientGoalHandler {
if !ac.started {
ac.logger.Error("[ActionClient] Trying to send a goal on an inactive ActionClient")
}
ag := ac.actionType.GoalType().NewMessage().(ActionGoal)
goalID := actionlib_msgs.GoalID{Id: ac.goalIDGen.generateID(), Stamp: ros.Now()}
header := std_msgs.Header{Stamp: ros.Now()}
ag.SetGoal(goal)
ag.SetGoalId(goalID)
ag.SetHeader(header)
ac.PublishActionGoal(ag)
handler := newClientGoalHandler(ac, ag, transitionCb, feedbackCb)
ac.handlersMutex.Lock()
ac.handlers = append(ac.handlers, handler)
ac.handlersMutex.Unlock()
return handler
}
func (ac *defaultActionClient) CancelAllGoals() {
if !ac.started {
ac.logger.Error("[ActionClient] Trying to cancel goals on an inactive ActionClient")
return
}
ac.cancelPub.Publish(&actionlib_msgs.GoalID{})
}
func (ac *defaultActionClient) CancelAllGoalsBeforeTime(stamp ros.Time) {
if !ac.started {
ac.logger.Error("[ActionClient] Trying to cancel goals on an inactive ActionClient")
return
}
cancelMsg := &actionlib_msgs.GoalID{Stamp: stamp}
ac.cancelPub.Publish(cancelMsg)
}
func (ac *defaultActionClient) Shutdown() {
ac.handlersMutex.Lock()
defer ac.handlersMutex.Unlock()
ac.started = false
for _, h := range ac.handlers {
h.Shutdown(false)
}
ac.handlers = nil
ac.node.Shutdown()
}
func (ac *defaultActionClient) PublishActionGoal(ag ActionGoal) {
if ac.started {
ac.goalPub.Publish(ag)
}
}
func (ac *defaultActionClient) PublishCancel(cancel *actionlib_msgs.GoalID) {
if ac.started {
ac.cancelPub.Publish(cancel)
}
}
func (ac *defaultActionClient) WaitForServer(timeout ros.Duration) bool {
started := false
ac.logger.Info("[ActionClient] Waiting action server to start")
rate := ros.CycleTime(ros.NewDuration(0, 10000000))
waitStart := ros.Now()
LOOP:
for !started {
gSubs := ac.goalPub.GetNumSubscribers()
cSubs := ac.cancelPub.GetNumSubscribers()
fPubs := ac.feedbackSub.GetNumPublishers()
rPubs := ac.resultSub.GetNumPublishers()
sPubs := ac.statusSub.GetNumPublishers()
started = (gSubs > 0 && cSubs > 0 && fPubs > 0 && rPubs > 0 && sPubs > 0)
now := ros.Now()
diff := now.Diff(waitStart)
if !timeout.IsZero() && diff.Cmp(timeout) >= 0 {
break LOOP
}
rate.Sleep()
}
if started {
ac.started = started
}
return started
}
func (ac *defaultActionClient) DeleteGoalHandler(gh *clientGoalHandler) {
ac.handlersMutex.Lock()
defer ac.handlersMutex.Unlock()
for i, h := range ac.handlers {
if h == gh {
ac.handlers[i] = ac.handlers[len(ac.handlers)-1]
ac.handlers[len(ac.handlers)-1] = nil
ac.handlers = ac.handlers[:len(ac.handlers)-1]
}
}
}
func (ac *defaultActionClient) internalResultCallback(result ActionResult, event ros.MessageEvent) {
ac.handlersMutex.RLock()
defer ac.handlersMutex.RUnlock()
for _, h := range ac.handlers {
if err := h.updateResult(result); err != nil {
ac.logger.Error(err)
}
}
}
func (ac *defaultActionClient) internalFeedbackCallback(feedback ActionFeedback, event ros.MessageEvent) {
ac.handlersMutex.RLock()
defer ac.handlersMutex.RUnlock()
for _, h := range ac.handlers {
h.updateFeedback(feedback)
}
}
func (ac *defaultActionClient) internalStatusCallback(statusArr *actionlib_msgs.GoalStatusArray, event ros.MessageEvent) {
ac.handlersMutex.RLock()
defer ac.handlersMutex.RUnlock()
if !ac.statusReceived {
ac.statusReceived = true
ac.logger.Debug("Recieved first status message from action server ")
} else if ac.callerID != event.PublisherName {
ac.logger.Debug("Previously received status from %s, now from %s. Did the action server change", ac.callerID, event.PublisherName)
}
ac.callerID = event.PublisherName
for _, h := range ac.handlers {
if err := h.updateStatus(statusArr); err != nil {
ac.logger.Error(err)
}
}
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"github.com/fetchrobotics/rosgo/ros"
)
func NewActionClient(node ros.Node, action string, actionType ActionType) ActionClient {
return newDefaultActionClient(node, action, actionType)
}
func NewActionServer(node ros.Node, action string, actionType ActionType, goalCb, cancelCb interface{}, autoStart bool) ActionServer {
return newDefaultActionServer(node, action, actionType, goalCb, cancelCb, autoStart)
}
func NewSimpleActionClient(node ros.Node, action string, actionType ActionType) SimpleActionClient {
return newSimpleActionClient(node, action, actionType)
}
func NewSimpleActionServer(node ros.Node, action string, actionType ActionType, executeCb interface{}, autoStart bool) SimpleActionServer {
return newSimpleActionServer(node, action, actionType, executeCb, autoStart)
}
func NewServerGoalHandlerWithGoal(as ActionServer, goal ActionGoal) ServerGoalHandler {
return newServerGoalHandlerWithGoal(as, goal)
}
func NewServerGoalHandlerWithGoalId(as ActionServer, goalID *actionlib_msgs.GoalID) ServerGoalHandler {
return newServerGoalHandlerWithGoalId(as, goalID)
}
type ActionClient interface {
WaitForServer(timeout ros.Duration) bool
SendGoal(goal ros.Message, transitionCallback interface{}, feedbackCallback interface{}) ClientGoalHandler
CancelAllGoals()
CancelAllGoalsBeforeTime(stamp ros.Time)
}
type ActionServer interface {
Start()
Shutdown()
PublishResult(status actionlib_msgs.GoalStatus, result ros.Message)
PublishFeedback(status actionlib_msgs.GoalStatus, feedback ros.Message)
PublishStatus()
RegisterGoalCallback(interface{})
RegisterCancelCallback(interface{})
}
type SimpleActionClient interface {
SendGoal(goal ros.Message, doneCb, activeCb, feedbackCb interface{})
SendGoalAndWait(goal ros.Message, executeTimeout, preeptTimeout ros.Duration) (uint8, error)
WaitForServer(timeout ros.Duration) bool
WaitForResult(timeout ros.Duration) bool
GetResult() (ros.Message, error)
GetState() (uint8, error)
GetGoalStatusText() (string, error)
CancelAllGoals()
CancelAllGoalsBeforeTime(stamp ros.Time)
CancelGoal() error
StopTrackingGoal()
}
type SimpleActionServer interface {
Start()
IsNewGoalAvailable() bool
IsPreemptRequested() bool
IsActive() bool
SetSucceeded(result ros.Message, text string) error
SetAborted(result ros.Message, text string) error
SetPreempted(result ros.Message, text string) error
AcceptNewGoal() (ros.Message, error)
PublishFeedback(feedback ros.Message)
GetDefaultResult() ros.Message
RegisterGoalCallback(callback interface{}) error
RegisterPreemptCallback(callback interface{})
}
type ClientGoalHandler interface {
IsExpired() bool
GetCommState() (CommState, error)
GetGoalStatus() (uint8, error)
GetGoalStatusText() (string, error)
GetTerminalState() (uint8, error)
GetResult() (ros.Message, error)
Resend() error
Cancel() error
}
type ServerGoalHandler interface {
SetAccepted(string) error
SetCancelled(ros.Message, string) error
SetRejected(ros.Message, string) error
SetAborted(ros.Message, string) error
SetSucceeded(ros.Message, string) error
SetCancelRequested() bool
PublishFeedback(ros.Message)
GetGoal() ros.Message
GetGoalId() actionlib_msgs.GoalID
GetGoalStatus() actionlib_msgs.GoalStatus
Equal(ServerGoalHandler) bool
NotEqual(ServerGoalHandler) bool
Hash() uint32
GetHandlerDestructionTime() ros.Time
SetHandlerDestructionTime(ros.Time)
}
<file_sep>package main
import (
"bytes"
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
)
func isRosPackage(dir string) bool {
files, err := ioutil.ReadDir(dir)
if err != nil {
return false
}
for _, f := range files {
if f.Name() == "package.xml" {
return true
}
}
return false
}
func findPackages(pkgType string, rosPkgPaths []string) (map[string]string, error) {
pkgs := make(map[string]string)
for _, p := range rosPkgPaths {
files, err := ioutil.ReadDir(p)
if err != nil {
continue
}
for _, f := range files {
if !f.IsDir() {
continue
}
pkgPath := filepath.Join(p, f.Name())
if isRosPackage(pkgPath) {
pkgName := filepath.Base(pkgPath)
msgPath := filepath.Join(pkgPath, pkgType)
msgPaths, err := filepath.Glob(msgPath + fmt.Sprintf("/*.%s", pkgType))
if err != nil {
continue
}
for _, m := range msgPaths {
basename := filepath.Base(m)
rootname := basename[:len(basename)-len(pkgType)-1]
fullname := pkgName + "/" + rootname
pkgs[fullname] = m
}
}
}
}
return pkgs, nil
}
func findAllMessages(rosPkgPaths []string) (map[string]string, error) {
return findPackages("msg", rosPkgPaths)
}
func findAllServices(rosPkgPaths []string) (map[string]string, error) {
return findPackages("srv", rosPkgPaths)
}
func findAllActions(rosPkgPaths []string) (map[string]string, error) {
return findPackages("action", rosPkgPaths)
}
type MsgContext struct {
msgPathMap map[string]string
srvPathMap map[string]string
actionPathMap map[string]string
msgRegistry map[string]*MsgSpec
}
func NewMsgContext(rosPkgPaths []string) (*MsgContext, error) {
ctx := new(MsgContext)
msgs, err := findAllMessages(rosPkgPaths)
if err != nil {
return nil, err
}
ctx.msgPathMap = msgs
srvs, err := findAllServices(rosPkgPaths)
if err != nil {
return nil, err
}
ctx.srvPathMap = srvs
acts, err := findAllActions(rosPkgPaths)
if err != nil {
return nil, err
}
ctx.actionPathMap = acts
ctx.msgRegistry = make(map[string]*MsgSpec)
return ctx, nil
}
func (ctx *MsgContext) Register(fullname string, spec *MsgSpec) {
ctx.msgRegistry[fullname] = spec
}
func (ctx *MsgContext) LoadMsgFromString(text string, fullname string) (*MsgSpec, error) {
packageName, shortName, e := packageResourceName(fullname)
if e != nil {
return nil, e
}
var fields []Field
var constants []Constant
for lineno, origLine := range strings.Split(text, "\n") {
cleanLine := stripComment(origLine)
if len(cleanLine) == 0 {
// Skip empty line
continue
} else if strings.Contains(cleanLine, ConstChar) {
constant, e := loadConstantLine(origLine)
if e != nil {
return nil, NewSyntaxError(fullname, lineno, e.Error())
}
constants = append(constants, *constant)
} else {
field, e := loadFieldLine(origLine, packageName)
if e != nil {
return nil, NewSyntaxError(fullname, lineno, e.Error())
}
fields = append(fields, *field)
}
}
spec, _ := NewMsgSpec(fields, constants, text, fullname, OptionPackageName(packageName), OptionShortName(shortName))
var err error
md5sum, err := ctx.ComputeMsgMD5(spec)
if err != nil {
return nil, err
}
spec.MD5Sum = md5sum
ctx.Register(fullname, spec)
return spec, nil
}
func (ctx *MsgContext) LoadMsgFromFile(filePath string, fullname string) (*MsgSpec, error) {
bytes, e := ioutil.ReadFile(filePath)
if e != nil {
return nil, e
}
text := string(bytes)
return ctx.LoadMsgFromString(text, fullname)
}
func (ctx *MsgContext) LoadMsg(fullname string) (*MsgSpec, error) {
if spec, ok := ctx.msgRegistry[fullname]; ok {
return spec, nil
} else {
if path, ok := ctx.msgPathMap[fullname]; ok {
spec, err := ctx.LoadMsgFromFile(path, fullname)
if err != nil {
return nil, err
} else {
ctx.msgRegistry[fullname] = spec
return spec, nil
}
} else {
return nil, fmt.Errorf("Message definition of `%s` is not found", fullname)
}
}
}
func (ctx *MsgContext) LoadSrvFromString(text string, fullname string) (*SrvSpec, error) {
packageName, shortName, err := packageResourceName(fullname)
if err != nil {
return nil, err
}
components := strings.Split(text, "---")
if len(components) != 2 {
return nil, fmt.Errorf("Syntax error: missing '---'")
}
reqText := components[0]
resText := components[1]
reqSpec, err := ctx.LoadMsgFromString(reqText, fullname+"Request")
if err != nil {
return nil, err
}
resSpec, err := ctx.LoadMsgFromString(resText, fullname+"Response")
if err != nil {
return nil, err
}
spec := &SrvSpec{
packageName, shortName, fullname, text, "", reqSpec, resSpec,
}
md5sum, err := ctx.ComputeSrvMD5(spec)
if err != nil {
return nil, err
}
spec.MD5Sum = md5sum
return spec, nil
}
func (ctx *MsgContext) LoadSrvFromFile(filePath string, fullname string) (*SrvSpec, error) {
bytes, e := ioutil.ReadFile(filePath)
if e != nil {
return nil, e
}
text := string(bytes)
return ctx.LoadSrvFromString(text, fullname)
}
func (ctx *MsgContext) LoadSrv(fullname string) (*SrvSpec, error) {
if path, ok := ctx.srvPathMap[fullname]; ok {
spec, err := ctx.LoadSrvFromFile(path, fullname)
if err != nil {
return nil, err
} else {
return spec, nil
}
} else {
return nil, fmt.Errorf("Service definition of `%s` is not found", fullname)
}
}
func (ctx *MsgContext) LoadActionFromString(text string, fullname string) (*ActionSpec, error) {
packageName, shortName, err := packageResourceName(fullname)
if err != nil {
return nil, err
}
components := strings.Split(text, "---")
if len(components) != 3 {
return nil, fmt.Errorf("Syntax error: missing '---'")
}
goalText := components[0]
resultText := components[1]
feedbackText := components[2]
goalSpec, err := ctx.LoadMsgFromString(goalText, fullname+"Goal")
if err != nil {
return nil, err
}
actionGoalText := "Header header\nactionlib_msgs/GoalID goal_id\n" + fullname + "Goal goal\n"
actionGoalSpec, err := ctx.LoadMsgFromString(actionGoalText, fullname+"ActionGoal")
if err != nil {
return nil, err
}
feedbackSpec, err := ctx.LoadMsgFromString(feedbackText, fullname+"Feedback")
if err != nil {
return nil, err
}
actionFeedbackText := "Header header\nactionlib_msgs/GoalStatus status\n" + fullname + "Feedback feedback"
actionFeedbackSpec, err := ctx.LoadMsgFromString(actionFeedbackText, fullname+"ActionFeedback")
if err != nil {
return nil, err
}
resultSpec, err := ctx.LoadMsgFromString(resultText, fullname+"Result")
if err != nil {
return nil, err
}
actionResultText := "Header header\nactionlib_msgs/GoalStatus status\n" + fullname + "Result result"
actionResultSpec, err := ctx.LoadMsgFromString(actionResultText, fullname+"ActionResult")
if err != nil {
return nil, err
}
spec := &ActionSpec{
Package: packageName,
ShortName: shortName,
FullName: fullname,
Text: text,
Goal: goalSpec,
Feedback: feedbackSpec,
Result: resultSpec,
ActionGoal: actionGoalSpec,
ActionFeedback: actionFeedbackSpec,
ActionResult: actionResultSpec,
}
md5sum, err := ctx.ComputeActionMD5(spec)
if err != nil {
return nil, err
}
spec.MD5Sum = md5sum
return spec, nil
}
func (ctx *MsgContext) LoadActionFromFile(filePath string, fullname string) (*ActionSpec, error) {
bytes, e := ioutil.ReadFile(filePath)
if e != nil {
return nil, e
}
text := string(bytes)
return ctx.LoadActionFromString(text, fullname)
}
func (ctx *MsgContext) LoadAction(fullname string) (*ActionSpec, error) {
if path, ok := ctx.actionPathMap[fullname]; ok {
spec, err := ctx.LoadActionFromFile(path, fullname)
if err != nil {
return nil, err
} else {
return spec, nil
}
} else {
return nil, fmt.Errorf("Action definition of `%s` is not found", fullname)
}
}
func (ctx *MsgContext) ComputeMD5Text(spec *MsgSpec) (string, error) {
var buf bytes.Buffer
for _, c := range spec.Constants {
buf.WriteString(fmt.Sprintf("%s %s=%s\n", c.Type, c.Name, c.ValueText))
}
for _, f := range spec.Fields {
if f.Package == "" {
buf.WriteString(fmt.Sprintf("%s\n", f.String()))
} else {
subspec, err := ctx.LoadMsg(f.Package + "/" + f.Type)
if err != nil {
return "", nil
}
submd5, err := ctx.ComputeMsgMD5(subspec)
if err != nil {
return "", nil
}
buf.WriteString(fmt.Sprintf("%s %s\n", submd5, f.Name))
}
}
return strings.Trim(buf.String(), "\n"), nil
}
func (ctx *MsgContext) ComputeMsgMD5(spec *MsgSpec) (string, error) {
md5text, err := ctx.ComputeMD5Text(spec)
if err != nil {
return "", err
}
hash := md5.New()
hash.Write([]byte(md5text))
sum := hash.Sum(nil)
md5sum := hex.EncodeToString(sum)
return md5sum, nil
}
func (ctx *MsgContext) ComputeActionMD5(spec *ActionSpec) (string, error) {
goalText, err := ctx.ComputeMD5Text(spec.ActionGoal)
if err != nil {
return "", err
}
feedbackText, err := ctx.ComputeMD5Text(spec.ActionFeedback)
if err != nil {
return "", err
}
resultText, err := ctx.ComputeMD5Text(spec.ActionResult)
if err != nil {
return "", err
}
hash := md5.New()
hash.Write([]byte(goalText))
hash.Write([]byte(feedbackText))
hash.Write([]byte(resultText))
sum := hash.Sum(nil)
md5sum := hex.EncodeToString(sum)
return md5sum, nil
}
func (ctx *MsgContext) ComputeSrvMD5(spec *SrvSpec) (string, error) {
reqText, err := ctx.ComputeMD5Text(spec.Request)
if err != nil {
return "", err
}
resText, err := ctx.ComputeMD5Text(spec.Response)
if err != nil {
return "", err
}
hash := md5.New()
hash.Write([]byte(reqText))
hash.Write([]byte(resText))
sum := hash.Sum(nil)
md5sum := hex.EncodeToString(sum)
return md5sum, nil
}
<file_sep>package ros
import (
"time"
)
// Node defines interface for a ros node
type Node interface {
// NewPublisher creates a publisher for specified topic and message type.
NewPublisher(topic string, msgType MessageType) Publisher
// NewPublisherWithCallbacks creates a publisher which gives you callbacks when subscribers
// connect and disconnect. The callbacks are called in their own
// goroutines, so they don't need to return immediately to let the
// connection proceed.
NewPublisherWithCallbacks(topic string, msgType MessageType, connectCallback, disconnectCallback func(SingleSubscriberPublisher)) Publisher
// NewSubscriber creates a subscriber to specified topic, where
// the messages are of a given type. callback should be a function
// which takes 0, 1, or 2 arguments.If it takes 0 arguments, it will
// simply be called without the message. 1-argument functions are
// the normal case, and the argument should be of the generated message type.
// If the function takes 2 arguments, the first argument should be of the
// generated message type and the second argument should be of type MessageEvent.
NewSubscriber(topic string, msgType MessageType, callback interface{}) Subscriber
NewServiceClient(service string, srvType ServiceType, options ...ServiceClientOption) ServiceClient
NewServiceServer(service string, srvType ServiceType, callback interface{}, options ...ServiceServerOption) ServiceServer
OK() bool
SpinOnce()
Spin()
Shutdown()
GetParam(name string) (interface{}, error)
SetParam(name string, value interface{}) error
HasParam(name string) (bool, error)
SearchParam(name string) (string, error)
DeleteParam(name string) error
Logger() Logger
NonRosArgs() []string
Name() string
}
// NodeOption allows to customize created nodes.
type NodeOption func(n *defaultNode)
// NodeServiceClientOptions specifies default options applied to the service clients created in this node.
func NodeServiceClientOptions(opts ...ServiceClientOption) NodeOption {
return func(n *defaultNode) {
n.srvClientOpts = opts
}
}
// NodeServiceServerOptions specifies default options applied to the service servers created in this node.
func NodeServiceServerOptions(opts ...ServiceServerOption) NodeOption {
return func(n *defaultNode) {
n.srvServerOpts = opts
}
}
func NewNode(name string, args []string, opts ...NodeOption) (Node, error) {
return newDefaultNode(name, args, opts...)
}
type Publisher interface {
Publish(msg Message)
GetNumSubscribers() int
Shutdown()
}
// SingleSubscriberPublisher is a publisher which only sends to one specific subscriber.
// This is sent as an argument to the connect and disconnect callback
// functions passed to Node.NewPublisherWithCallbacks().
type SingleSubscriberPublisher interface {
Publish(msg Message)
GetSubscriberName() string
GetTopic() string
}
type Subscriber interface {
GetNumPublishers() int
Shutdown()
}
// MessageEvent is an optional second argument to a Subscriber callback.
type MessageEvent struct {
PublisherName string
ReceiptTime time.Time
ConnectionHeader map[string]string
}
type ServiceHandler interface{}
type ServiceFactory interface {
Name() string
MD5Sum() string
}
type ServiceServer interface {
Shutdown()
}
type ServiceClient interface {
Call(srv Service) error
Shutdown()
}
<file_sep>package main
import (
"actionlib_tutorials"
"fmt"
"os"
"github.com/fetchrobotics/rosgo/actionlib"
"github.com/fetchrobotics/rosgo/ros"
)
func main() {
node, err := ros.NewNode("test_fibonacci_client", os.Args)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
logger := node.Logger()
defer node.Shutdown()
go node.Spin()
ac := actionlib.NewSimpleActionClient(node, "fibonacci", actionlib_tutorials.ActionFibonacci)
logger.Info("Waiting for server to start")
started := ac.WaitForServer(ros.NewDuration(0, 0))
if !started {
logger.Info("Action server failed to start within timeout period.")
return
}
logger.Info("Action server started, sending goal.")
goal := &actionlib_tutorials.FibonacciGoal{Order: 20}
ac.SendGoal(goal, nil, nil, nil)
finished := ac.WaitForResult(ros.NewDuration(60, 0))
if finished {
state, err := ac.GetState()
if err != nil {
logger.Errorf("Error getting state: %v", err)
return
}
logger.Infof("Action finished: %v", state)
} else {
logger.Errorf("Action did not finish before the timeout")
}
}
<file_sep>// Copyright 2018, <NAME> All rights reserved
package main
import (
// "math"
"os"
"reflect"
"strings"
"testing"
)
func TestConvertConstantValue(t *testing.T) {
var tests = []struct {
fieldType string
valueLiteral string
expected interface{}
expectError bool
}{
{"bool", "0", false, false},
{"bool", "1", true, false},
{"bool", "2", true, false},
{"bool", "-2", true, true},
{"bool", "True", true, false},
{"bool", "False", false, false},
{"bool", "None", false, false},
{"float32", "2.72", float32(2.72), false},
{"float64", "-3.14", float64(-3.14), false},
{"int8", "-129", 0, true},
{"int8", "-128", int8(-128), false},
{"int8", "127", int8(127), false},
{"int8", "128", 0, true},
{"int16", "-32769", 0, true},
{"int16", "-32768", int16(-32768), false},
{"int16", "32767", int16(32767), false},
{"int16", "32768", 0, true},
{"int32", "-2147483649", 0, true},
{"int32", "-2147483648", int32(-2147483648), false},
{"int32", "2147483647", int32(2147483647), false},
{"int32", "2147483648", 0, true},
{"int64", "-9223372036854775809", 0, true},
{"int64", "-9223372036854775808", int64(-9223372036854775808), false},
{"int64", "9223372036854775807", int64(9223372036854775807), false},
{"int64", "9223372036854775808", 0, true},
{"uint8", "-1", 0, true},
{"uint8", "0", uint8(0), false},
{"uint8", "255", uint8(255), false},
{"uint8", "256", 0, true},
{"uint16", "-1", 0, true},
{"uint16", "0", uint16(0), false},
{"uint16", "65535", uint16(65535), false},
{"uint16", "65536", 0, true},
{"uint32", "-1", 0, true},
{"uint32", "0", uint32(0), false},
{"uint32", "4294967295", uint32(4294967295), false},
{"uint32", "4294967296", 0, true},
{"uint64", "-1", 0, true},
{"uint64", "0", uint64(0), false},
{"uint64", "18446744073709551615", uint64(18446744073709551615), false},
{"uint64", "18446744073709551616", 0, true},
{"string", "Lorem Ipsum", "Lorem Ipsum", false},
}
for _, test := range tests {
result, e := convertConstantValue(test.fieldType, test.valueLiteral)
if test.expectError {
if e == nil {
t.Errorf("INPUT(%s : %s) | should fail but succeeded", test.valueLiteral, test.fieldType)
}
} else {
if e != nil {
t.Errorf("INPUT(%s : %s) | %s", test.valueLiteral, test.fieldType, e.Error())
} else if result != test.expected {
format := "INPUT(%s : %s) | Expected: [%v: %v], Actual: [%v : %v]"
t.Errorf(format, test.valueLiteral, test.fieldType, test.expected, reflect.TypeOf(test.expected), result, reflect.TypeOf(result))
}
}
}
}
func TestParseMessage(t *testing.T) {
const text string = `
# Comment
bool B = 1
int8 I8 = -128
int16 I16 = -32768
int32 I32 = -2147483648
int64 I64 = -9223372036854775808
uint8 U8 = 255
uint16 U16 = 65535
uint32 U32 = 4294967295
uint64 U64 = 18446744073709551615
string S = Lorem Ipsum # Comment is ignored
Header header
bool b
int8 i8
uint8 u8
int16 i16
uint16 u16
int32 i32
uint32 u32
int64 i64
uint64 u64
float32 f32
float64 f64
string s
time t
duration d
string[] sva
string[42] sfa
std_msgs/Empty e
std_msgs/Empty[] eva
std_msgs/Empty[42] efa
Bar x
Bar[] xva
Bar[42] xfa
`
rosPkgPath := os.Getenv("ROS_PACKAGE_PATH")
ctx, e := NewMsgContext(strings.Split(rosPkgPath, ":"))
if e != nil {
t.Errorf("Failed to create MsgContext.")
}
// var spec *MsgSpec
_, e = ctx.LoadMsgFromString(text, "foo/Foo")
if e != nil {
t.Errorf("Failed to parse: %v", e)
}
// fmt.Println("---")
// fmt.Println(spec.String())
}
func TestMD5_std_msgs(t *testing.T) {
var std_msgs = map[string]string{
"std_msgs/Bool": "8b94c1b53db61fb6aed406028ad6332a",
"std_msgs/Byte": "ad736a2e8818154c487bb80fe42ce43b",
"std_msgs/ByteMultiArray": "70ea476cbcfd65ac2f68f3cda1e891fe",
"std_msgs/Char": "1bf77f25acecdedba0e224b162199717",
"std_msgs/ColorRGBA": "a29a96539573343b1310c73607334b00",
"std_msgs/Duration": "3e286caf4241d664e55f3ad380e2ae46",
"std_msgs/Empty": "d41d8cd98f00b204e9800998ecf8427e",
"std_msgs/Float32": "73fcbf46b49191e672908e50842a83d4",
"std_msgs/Float32MultiArray": "6a40e0ffa6a17a503ac3f8616991b1f6",
"std_msgs/Float64": "fdb28210bfa9d7c91146260178d9a584",
"std_msgs/Float64MultiArray": "4b7d974086d4060e7db4613a7e6c3ba4",
"std_msgs/Header": "2176decaecbce78abc3b96ef049fabed",
"std_msgs/Int16": "8524586e34fbd7cb1c08c5f5f1ca0e57",
"std_msgs/Int16MultiArray": "d9338d7f523fcb692fae9d0a0e9f067c",
"std_msgs/Int32": "da5909fbe378aeaf85e547e830cc1bb7",
"std_msgs/Int32MultiArray": "1d99f79f8b325b44fee908053e9c945b",
"std_msgs/Int64": "34add168574510e6e17f5d23ecc077ef",
"std_msgs/Int64MultiArray": "54865aa6c65be0448113a2afc6a49270",
"std_msgs/Int8": "27ffa0c9c4b8fb8492252bcad9e5c57b",
"std_msgs/Int8MultiArray": "d7c1af35a1b4781bbe79e03dd94b7c13",
"std_msgs/MultiArrayDimension": "4cd0c83a8683deae40ecdac60e53bfa8",
"std_msgs/MultiArrayLayout": "0fed2a11c13e11c5571b4e2a995a91a3",
"std_msgs/String": "992ce8a1687cec8c8bd883ec73ca41d1",
"std_msgs/Time": "cd7166c74c552c311fbcc2fe5a7bc289",
"std_msgs/UInt16": "1df79edf208b629fe6b81923a544552d",
"std_msgs/UInt16MultiArray": "52f264f1c973c4b73790d384c6cb4484",
"std_msgs/UInt32": "304a39449588c7f8ce2df6e8001c5fce",
"std_msgs/UInt32MultiArray": "4d6a180abc9be191b96a7eda6c8a233d",
"std_msgs/UInt64": "1b2a79973e8bf53d7b53acb71299cb57",
"std_msgs/UInt64MultiArray": "6088f127afb1d6c72927aa1247e945af",
"std_msgs/UInt8": "7c8164229e7d2c17eb95e9231617fdee",
}
rosPkgPath := os.Getenv("ROS_PACKAGE_PATH")
ctx, e := NewMsgContext(strings.Split(rosPkgPath, ":"))
if e != nil {
t.Errorf("Failed to create MsgContext.")
} else {
for fullname, md5 := range std_msgs {
_, shortName, _ := packageResourceName(fullname)
t.Run(shortName, func(t *testing.T) {
var spec *MsgSpec
spec, e := ctx.LoadMsg(fullname)
if e != nil {
t.Errorf("Failed to parse: %v", e)
} else {
assertEqual(t, spec.MD5Sum, md5)
}
})
}
}
}
func TestMD5_sensor_msgs(t *testing.T) {
var sensor_msgs = map[string]string{
"sensor_msgs/BatteryState": "476f837fa6771f6e16e3bf4ef96f8770",
"sensor_msgs/CameraInfo": "c9a58c1b0b154e0e6da7578cb991d214",
"sensor_msgs/ChannelFloat32": "3d40139cdd33dfedcb71ffeeeb42ae7f",
"sensor_msgs/CompressedImage": "8f7a12909da2c9d3332d540a0977563f",
"sensor_msgs/FluidPressure": "804dc5cea1c5306d6a2eb80b9833befe",
"sensor_msgs/Illuminance": "8cf5febb0952fca9d650c3d11a81a188",
"sensor_msgs/Image": "060021388200f6f0f447d0fcd9c64743",
"sensor_msgs/Imu": "6a62c6daae103f4ff57a132d6f95cec2",
"sensor_msgs/JointState": "3066dcd76a6cfaef579bd0f34173e9fd",
"sensor_msgs/Joy": "5a9ea5f83505693b71e785041e67a8bb",
"sensor_msgs/JoyFeedback": "f4dcd73460360d98f36e55ee7f2e46f1",
"sensor_msgs/JoyFeedbackArray": "cde5730a895b1fc4dee6f91b754b213d",
"sensor_msgs/LaserEcho": "8bc5ae449b200fba4d552b4225586696",
"sensor_msgs/LaserScan": "90c7ef2dc6895d81024acba2ac42f369",
"sensor_msgs/MagneticField": "2f3b0b43eed0c9501de0fa3ff89a45aa",
"sensor_msgs/MultiDOFJointState": "690f272f0640d2631c305eeb8301e59d",
"sensor_msgs/MultiEchoLaserScan": "6fefb0c6da89d7c8abe4b339f5c2f8fb",
"sensor_msgs/NavSatFix": "2d3a8cd499b9b4a0249fb98fd05cfa48",
"sensor_msgs/NavSatStatus": "331cdbddfa4bc96ffc3b9ad98900a54c",
"sensor_msgs/PointCloud": "d8e9c3f5afbdd8a130fd1d2763945fca",
"sensor_msgs/PointCloud2": "1158d486dd51d683ce2f1be655c3c181",
"sensor_msgs/PointField": "268eacb2962780ceac86cbd17e328150",
"sensor_msgs/Range": "c005c34273dc426c67a020a87bc24148",
"sensor_msgs/RegionOfInterest": "bdb633039d588fcccb441a4d43ccfe09",
"sensor_msgs/RelativeHumidity": "8730015b05955b7e992ce29a2678d90f",
"sensor_msgs/Temperature": "ff71b307acdbe7c871a5a6d7ed359100",
"sensor_msgs/TimeReference": "fded64a0265108ba86c3d38fb11c0c16",
}
rosPkgPath := os.Getenv("ROS_PACKAGE_PATH")
ctx, e := NewMsgContext(strings.Split(rosPkgPath, ":"))
if e != nil {
t.Errorf("Failed to create MsgContext.")
}
for fullname, md5 := range sensor_msgs {
_, shortName, _ := packageResourceName(fullname)
t.Run(shortName, func(t *testing.T) {
var spec *MsgSpec
spec, e := ctx.LoadMsg(fullname)
if e != nil {
t.Errorf("Failed to parse: %v", e)
} else {
assertEqual(t, spec.MD5Sum, md5)
}
})
}
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"container/list"
"fmt"
"reflect"
"sync"
)
type CommState uint8
const (
WaitingForGoalAck CommState = iota
Pending
Active
WaitingForResult
WaitingForCancelAck
Recalling
Preempting
Done
Lost
)
func (cs CommState) String() string {
switch cs {
case WaitingForGoalAck:
return "WAITING_FOR_GOAL_ACK"
case Pending:
return "PENDING"
case Active:
return "ACTIVE"
case WaitingForResult:
return "WAITING_FOR_RESULT"
case WaitingForCancelAck:
return "WAITING_FOR_CANCEL_ACK"
case Recalling:
return "RECALLING"
case Preempting:
return "PREEMPTING"
case Done:
return "DONE"
case Lost:
return "LOST"
default:
return "UNKNOWN"
}
}
type clientStateMachine struct {
state CommState
goalStatus actionlib_msgs.GoalStatus
goalResult ActionResult
mutex sync.RWMutex
}
func newClientStateMachine() *clientStateMachine {
return &clientStateMachine{
state: WaitingForGoalAck,
goalStatus: actionlib_msgs.GoalStatus{Status: actionlib_msgs.PENDING},
}
}
func (sm *clientStateMachine) getState() CommState {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
return sm.state
}
func (sm *clientStateMachine) getGoalStatus() actionlib_msgs.GoalStatus {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
return sm.goalStatus
}
func (sm *clientStateMachine) getGoalResult() ActionResult {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
return sm.goalResult
}
func (sm *clientStateMachine) setState(state CommState) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
sm.state = state
}
func (sm *clientStateMachine) setGoalStatus(id actionlib_msgs.GoalID, status uint8, text string) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
sm.goalStatus.GoalId = id
sm.goalStatus.Status = status
sm.goalStatus.Text = text
}
func (sm *clientStateMachine) setGoalResult(result ActionResult) {
sm.mutex.Lock()
defer sm.mutex.Unlock()
sm.goalResult = result
}
func (sm *clientStateMachine) setAsLost() {
sm.mutex.Lock()
defer sm.mutex.Unlock()
sm.goalStatus.Status = uint8(Lost)
}
func (sm *clientStateMachine) transitionTo(state CommState, gh ClientGoalHandler, callback interface{}) {
sm.setState(state)
if callback != nil {
fun := reflect.ValueOf(callback)
args := []reflect.Value{reflect.ValueOf(gh)}
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded <= 1 {
fun.Call(args[:numArgsNeeded])
}
}
}
func (sm *clientStateMachine) getTransitions(goalStatus actionlib_msgs.GoalStatus) (stateList list.List, err error) {
sm.mutex.RLock()
defer sm.mutex.RUnlock()
status := goalStatus.Status
switch sm.state {
case WaitingForGoalAck:
switch status {
case actionlib_msgs.PENDING:
stateList.PushBack(Pending)
break
case actionlib_msgs.ACTIVE:
stateList.PushBack(Active)
break
case actionlib_msgs.REJECTED:
stateList.PushBack(Pending)
stateList.PushBack(WaitingForCancelAck)
break
case actionlib_msgs.RECALLING:
stateList.PushBack(Pending)
stateList.PushBack(Recalling)
break
case actionlib_msgs.RECALLED:
stateList.PushBack(Pending)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(Active)
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(Active)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(Active)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
stateList.PushBack(Active)
stateList.PushBack(Preempting)
break
}
break
case Pending:
switch status {
case actionlib_msgs.PENDING:
break
case actionlib_msgs.ACTIVE:
stateList.PushBack(Active)
break
case actionlib_msgs.REJECTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.RECALLING:
stateList.PushBack(Recalling)
break
case actionlib_msgs.RECALLED:
stateList.PushBack(Recalling)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(Active)
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(Active)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(Active)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
stateList.PushBack(Active)
stateList.PushBack(Preempting)
break
}
break
case Active:
switch status {
case actionlib_msgs.PENDING:
err = fmt.Errorf("invalid transition from Active to Pending")
break
case actionlib_msgs.ACTIVE:
break
case actionlib_msgs.REJECTED:
err = fmt.Errorf("invalid transition from Active to Rejected")
break
case actionlib_msgs.RECALLING:
err = fmt.Errorf("invalid transition from Active to Recalling")
break
case actionlib_msgs.RECALLED:
err = fmt.Errorf("invalid transition from Active to Recalled")
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
stateList.PushBack(Preempting)
break
}
break
case WaitingForResult:
switch status {
case actionlib_msgs.PENDING:
err = fmt.Errorf("invalid transition from WaitingForResult to Pending")
break
case actionlib_msgs.ACTIVE:
break
case actionlib_msgs.REJECTED:
break
case actionlib_msgs.RECALLING:
err = fmt.Errorf("invalid transition from WaitingForResult to Recalling")
break
case actionlib_msgs.RECALLED:
break
case actionlib_msgs.PREEMPTED:
break
case actionlib_msgs.SUCCEEDED:
break
case actionlib_msgs.ABORTED:
break
case actionlib_msgs.PREEMPTING:
err = fmt.Errorf("invalid transition from WaitingForResult to Preempting")
break
}
break
case WaitingForCancelAck:
switch status {
case actionlib_msgs.PENDING:
break
case actionlib_msgs.ACTIVE:
break
case actionlib_msgs.REJECTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.RECALLING:
stateList.PushBack(Recalling)
break
case actionlib_msgs.RECALLED:
stateList.PushBack(Recalling)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(Recalling)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(Recalling)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
stateList.PushBack(Preempting)
break
}
break
case Recalling:
switch status {
case actionlib_msgs.PENDING:
err = fmt.Errorf("invalid transition from Recalling to Pending")
break
case actionlib_msgs.ACTIVE:
err = fmt.Errorf("invalid transition from Recalling to Active")
break
case actionlib_msgs.REJECTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.RECALLING:
break
case actionlib_msgs.RECALLED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(Preempting)
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
stateList.PushBack(Preempting)
break
}
break
case Preempting:
switch status {
case actionlib_msgs.PENDING:
err = fmt.Errorf("invalid transition from Preempting to Pending")
break
case actionlib_msgs.ACTIVE:
err = fmt.Errorf("invalid transition from Preempting to Active")
break
case actionlib_msgs.REJECTED:
err = fmt.Errorf("invalid transition from Preempting to Rejected")
break
case actionlib_msgs.RECALLING:
err = fmt.Errorf("invalid transition from Preempting to Recalling")
break
case actionlib_msgs.RECALLED:
err = fmt.Errorf("invalid transition from Preempting to Recalled")
break
case actionlib_msgs.PREEMPTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.SUCCEEDED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.ABORTED:
stateList.PushBack(WaitingForResult)
break
case actionlib_msgs.PREEMPTING:
break
}
break
case Done:
switch status {
case actionlib_msgs.PENDING:
err = fmt.Errorf("invalid transition from Done to Pending")
break
case actionlib_msgs.ACTIVE:
err = fmt.Errorf("invalid transition from Done to Active")
break
case actionlib_msgs.REJECTED:
break
case actionlib_msgs.RECALLING:
err = fmt.Errorf("invalid transition from Done to Recalling")
break
case actionlib_msgs.RECALLED:
break
case actionlib_msgs.PREEMPTED:
break
case actionlib_msgs.SUCCEEDED:
break
case actionlib_msgs.ABORTED:
break
case actionlib_msgs.PREEMPTING:
err = fmt.Errorf("invalid transition from Done to Preempting")
break
}
break
}
return
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"reflect"
"github.com/fetchrobotics/rosgo/ros"
)
type clientGoalHandler struct {
actionClient *defaultActionClient
stateMachine *clientStateMachine
actionGoal ActionGoal
actionGoalID string
transitionCb interface{}
feedbackCb interface{}
logger ros.Logger
}
func newClientGoalHandler(ac *defaultActionClient, ag ActionGoal, transitionCb, feedbackCb interface{}) *clientGoalHandler {
return &clientGoalHandler{
actionClient: ac,
stateMachine: newClientStateMachine(),
actionGoal: ag,
actionGoalID: ag.GetGoalId().Id,
transitionCb: transitionCb,
feedbackCb: feedbackCb,
logger: ac.logger,
}
}
func findGoalStatus(statusArr *actionlib_msgs.GoalStatusArray, id string) *actionlib_msgs.GoalStatus {
var status actionlib_msgs.GoalStatus
for _, st := range statusArr.StatusList {
if st.GoalId.Id == id {
status = st
break
}
}
return &status
}
func (gh *clientGoalHandler) GetCommState() (CommState, error) {
if gh.stateMachine == nil {
return Lost, fmt.Errorf("trying to get state on an inactive ClientGoalHandler")
}
return gh.stateMachine.getState(), nil
}
func (gh *clientGoalHandler) GetGoalStatus() (uint8, error) {
if gh.stateMachine == nil {
return actionlib_msgs.LOST, fmt.Errorf("trying to get goal status on an inactive ClientGoalHandler")
}
return gh.stateMachine.getGoalStatus().Status, nil
}
func (gh *clientGoalHandler) GetGoalStatusText() (string, error) {
if gh.stateMachine == nil {
return "", fmt.Errorf("trying to get goal status text on an inactive ClientGoalHandler")
}
return gh.stateMachine.getGoalStatus().Text, nil
}
func (gh *clientGoalHandler) GetTerminalState() (uint8, error) {
if gh.stateMachine == nil {
return 0, fmt.Errorf("trying to get goal status on inactive clientGoalHandler")
}
if gh.stateMachine.state != Done {
gh.actionClient.logger.Warnf("Asking for terminal state when we are in state %v", gh.stateMachine.state)
}
// implement get status
goalStatus := gh.stateMachine.getGoalStatus().Status
if goalStatus == actionlib_msgs.PREEMPTED ||
goalStatus == actionlib_msgs.SUCCEEDED ||
goalStatus == actionlib_msgs.ABORTED ||
goalStatus == actionlib_msgs.REJECTED ||
goalStatus == actionlib_msgs.RECALLED ||
goalStatus == actionlib_msgs.LOST {
return goalStatus, nil
}
gh.actionClient.logger.Warnf("Asking for terminal state when latest goal is in %v", goalStatus)
return actionlib_msgs.LOST, nil
}
func (gh *clientGoalHandler) GetResult() (ros.Message, error) {
if gh.stateMachine == nil {
return nil, fmt.Errorf("trying to get goal status on inactive clientGoalHandler")
}
result := gh.stateMachine.getGoalResult()
if result == nil {
return nil, fmt.Errorf("trying to get result when no result has been recieved")
}
return result.GetResult(), nil
}
func (gh *clientGoalHandler) Resend() error {
if gh.stateMachine == nil {
return fmt.Errorf("trying to call resend on inactive client goal hanlder")
}
gh.actionClient.goalPub.Publish(gh.actionGoal)
return nil
}
func (gh *clientGoalHandler) IsExpired() bool {
return gh.stateMachine == nil
}
func (gh *clientGoalHandler) Cancel() error {
if gh.stateMachine == nil {
return fmt.Errorf("trying to call cancel on inactive client goal hanlder")
}
cancelMsg := &actionlib_msgs.GoalID{
Stamp: ros.Now(),
Id: gh.actionGoalID}
gh.actionClient.cancelPub.Publish(cancelMsg)
gh.stateMachine.transitionTo(WaitingForCancelAck, gh, gh.transitionCb)
return nil
}
func (gh *clientGoalHandler) Shutdown(deleteFromManager bool) {
gh.stateMachine = nil
if deleteFromManager {
gh.actionClient.DeleteGoalHandler(gh)
}
}
func (gh *clientGoalHandler) updateFeedback(af ActionFeedback) {
if gh.actionGoalID != af.GetStatus().GoalId.Id {
return
}
if gh.feedbackCb != nil && gh.stateMachine.getState() != Done {
fun := reflect.ValueOf(gh.feedbackCb)
args := []reflect.Value{reflect.ValueOf(gh), reflect.ValueOf(af.GetFeedback())}
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded == 2 {
fun.Call(args)
}
}
}
func (gh *clientGoalHandler) updateResult(result ActionResult) error {
if gh.actionGoalID != result.GetStatus().GoalId.Id {
return nil
}
status := result.GetStatus()
state := gh.stateMachine.getState()
gh.stateMachine.setGoalStatus(status.GoalId, status.Status, status.Text)
gh.stateMachine.setGoalResult(result)
if state == WaitingForGoalAck ||
state == WaitingForCancelAck ||
state == Pending ||
state == Active ||
state == WaitingForResult ||
state == Recalling ||
state == Preempting {
statusArr := new(actionlib_msgs.GoalStatusArray)
statusArr.StatusList = append(statusArr.StatusList, result.GetStatus())
if err := gh.updateStatus(statusArr); err != nil {
return err
}
gh.stateMachine.transitionTo(Done, gh, gh.transitionCb)
return nil
} else if state == Done {
return fmt.Errorf("got a result when we are in the `DONE` state")
} else {
return fmt.Errorf("unknown state %v", state)
}
}
func (gh *clientGoalHandler) updateStatus(statusArr *actionlib_msgs.GoalStatusArray) error {
state := gh.stateMachine.getState()
if state == Done {
return nil
}
status := findGoalStatus(statusArr, gh.actionGoalID)
if status == nil {
if state != WaitingForGoalAck &&
state != WaitingForResult &&
state != Done {
gh.logger.Warn("Transitioning goal to `Lost`")
gh.stateMachine.setAsLost()
gh.stateMachine.transitionTo(Done, gh, gh.transitionCb)
}
return nil
}
gh.stateMachine.setGoalStatus(status.GoalId, status.Status, status.Text)
nextStates, err := gh.stateMachine.getTransitions(*status)
if err != nil {
return fmt.Errorf("error getting transitions: %v", err)
}
for e := nextStates.Front(); e != nil; e = e.Next() {
gh.stateMachine.transitionTo(e.Value.(CommState), gh, gh.transitionCb)
}
return nil
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"hash/fnv"
"sync"
"github.com/fetchrobotics/rosgo/ros"
)
type serverGoalHandler struct {
as ActionServer
sm *serverStateMachine
goal ActionGoal
handlerDestructionTime ros.Time
handlerMutex sync.RWMutex
}
func newServerGoalHandlerWithGoal(as ActionServer, goal ActionGoal) *serverGoalHandler {
return &serverGoalHandler{
as: as,
sm: newServerStateMachine(goal.GetGoalId()),
goal: goal,
}
}
func newServerGoalHandlerWithGoalId(as ActionServer, goalID *actionlib_msgs.GoalID) *serverGoalHandler {
return &serverGoalHandler{
as: as,
sm: newServerStateMachine(*goalID),
}
}
func (gh *serverGoalHandler) GetHandlerDestructionTime() ros.Time {
gh.handlerMutex.RLock()
defer gh.handlerMutex.RUnlock()
return gh.handlerDestructionTime
}
func (gh *serverGoalHandler) SetHandlerDestructionTime(t ros.Time) {
gh.handlerMutex.Lock()
defer gh.handlerMutex.Unlock()
gh.handlerDestructionTime = t
}
func (gh *serverGoalHandler) SetAccepted(text string) error {
if gh.goal == nil {
return fmt.Errorf("attempt to set handler on an uninitialized handler")
}
if status, err := gh.sm.transition(Accept, text); err != nil {
return fmt.Errorf("to transition to an active state, the goal must be in a pending"+
"or recalling state, it is currently in state: %d", status.Status)
}
gh.as.PublishStatus()
return nil
}
func (gh *serverGoalHandler) SetCancelled(result ros.Message, text string) error {
if gh.goal == nil {
return fmt.Errorf("attempt to set handler on an uninitialized handler handler")
}
status, err := gh.sm.transition(Cancel, text)
if err != nil {
return fmt.Errorf("to transition to an Canceled state, the goal must be in a pending"+
" or recalling state, it is currently in state: %d", status.Status)
}
gh.SetHandlerDestructionTime(ros.Now())
gh.as.PublishResult(status, result)
return nil
}
func (gh *serverGoalHandler) SetRejected(result ros.Message, text string) error {
if gh.goal == nil {
return fmt.Errorf("attempt to set handler on an uninitialized handler handler")
}
status, err := gh.sm.transition(Reject, text)
if err != nil {
return fmt.Errorf("to transition to an Rejected state, the goal must be in a pending"+
"or recalling state, it is currently in state: %d", status.Status)
}
gh.SetHandlerDestructionTime(ros.Now())
gh.as.PublishResult(status, result)
return nil
}
func (gh *serverGoalHandler) SetAborted(result ros.Message, text string) error {
if gh.goal == nil {
return fmt.Errorf("attempt to set handler on an uninitialized handler handler")
}
status, err := gh.sm.transition(Abort, text)
if err != nil {
return fmt.Errorf("to transition to an Aborted state, the goal must be in a pending"+
"or recalling state, it is currently in state: %d", status.Status)
}
gh.SetHandlerDestructionTime(ros.Now())
gh.as.PublishResult(status, result)
return nil
}
func (gh *serverGoalHandler) SetSucceeded(result ros.Message, text string) error {
if gh.goal == nil {
return fmt.Errorf("attempt to set handler on an uninitialized handler handler")
}
status, err := gh.sm.transition(Succeed, text)
if err != nil {
return fmt.Errorf("to transition to an Succeeded state, the goal must be in a pending"+
"or recalling state, it is currently in state: %d", status.Status)
}
gh.SetHandlerDestructionTime(ros.Now())
gh.as.PublishResult(status, result)
return nil
}
func (gh *serverGoalHandler) SetCancelRequested() bool {
if gh.goal == nil {
return false
}
if _, err := gh.sm.transition(CancelRequest, "Cancel requested"); err != nil {
return false
}
gh.SetHandlerDestructionTime(ros.Now())
return true
}
func (gh *serverGoalHandler) PublishFeedback(feedback ros.Message) {
gh.as.PublishFeedback(gh.sm.getStatus(), feedback)
}
func (gh *serverGoalHandler) GetGoal() ros.Message {
if gh.goal == nil {
return nil
}
return gh.goal.GetGoal()
}
func (gh *serverGoalHandler) GetGoalId() actionlib_msgs.GoalID {
if gh.goal == nil {
return actionlib_msgs.GoalID{}
}
return gh.goal.GetGoalId()
}
func (gh *serverGoalHandler) GetGoalStatus() actionlib_msgs.GoalStatus {
status := gh.sm.getStatus()
if status.Status != 0 && gh.goal != nil && gh.goal.GetGoalId().Id != "" {
return status
}
return actionlib_msgs.GoalStatus{}
}
func (gh *serverGoalHandler) Equal(other ServerGoalHandler) bool {
if gh.goal == nil || other == nil {
return false
}
return gh.goal.GetGoalId().Id == other.GetGoalId().Id
}
func (gh *serverGoalHandler) NotEqual(other ServerGoalHandler) bool {
return !gh.Equal(other)
}
func (gh *serverGoalHandler) Hash() uint32 {
id := gh.goal.GetGoalId().Id
hs := fnv.New32a()
hs.Write([]byte(id))
return hs.Sum32()
}
<file_sep>#!/bin/bash
source /opt/ros/noetic/setup.bash
export PATH=$PWD/bin:/usr/local/go/bin:$PATH
export GOPATH=$PWD:/usr/local/go
roscore &
go install github.com/fetchrobotics/rosgo/gengo
go generate github.com/fetchrobotics/rosgo/test/test_message
go test github.com/fetchrobotics/rosgo/xmlrpc
go test github.com/fetchrobotics/rosgo/ros
go test github.com/fetchrobotics/rosgo/test/test_message
<file_sep>package actionlib
import (
"actionlib_msgs"
"std_msgs"
"github.com/fetchrobotics/rosgo/ros"
)
type ActionType interface {
MD5Sum() string
Name() string
GoalType() ros.MessageType
FeedbackType() ros.MessageType
ResultType() ros.MessageType
NewAction() Action
}
type Action interface {
GetActionGoal() ActionGoal
GetActionFeedback() ActionFeedback
GetActionResult() ActionResult
}
type ActionGoal interface {
ros.Message
GetHeader() std_msgs.Header
GetGoalId() actionlib_msgs.GoalID
GetGoal() ros.Message
SetHeader(std_msgs.Header)
SetGoalId(actionlib_msgs.GoalID)
SetGoal(ros.Message)
}
type ActionFeedback interface {
ros.Message
GetHeader() std_msgs.Header
GetStatus() actionlib_msgs.GoalStatus
GetFeedback() ros.Message
SetHeader(std_msgs.Header)
SetStatus(actionlib_msgs.GoalStatus)
SetFeedback(ros.Message)
}
type ActionResult interface {
ros.Message
GetHeader() std_msgs.Header
GetStatus() actionlib_msgs.GoalStatus
GetResult() ros.Message
SetHeader(std_msgs.Header)
SetStatus(actionlib_msgs.GoalStatus)
SetResult(ros.Message)
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"reflect"
"time"
"github.com/fetchrobotics/rosgo/ros"
)
const (
SimpleStatePending uint8 = 0
SimpleStateActive uint8 = 1
SimpleStateDone uint8 = 2
)
type simpleActionClient struct {
ac *defaultActionClient
simpleState uint8
gh ClientGoalHandler
doneCb interface{}
activeCb interface{}
feedbackCb interface{}
doneChan chan struct{}
logger ros.Logger
}
func newSimpleActionClient(node ros.Node, action string, actionType ActionType) *simpleActionClient {
return &simpleActionClient{
ac: newDefaultActionClient(node, action, actionType),
simpleState: SimpleStateDone,
doneChan: make(chan struct{}, 10),
logger: node.Logger(),
}
}
func (sc *simpleActionClient) SendGoal(goal ros.Message, doneCb, activeCb, feedbackCb interface{}) {
sc.StopTrackingGoal()
sc.doneCb = doneCb
sc.activeCb = activeCb
sc.feedbackCb = feedbackCb
sc.setSimpleState(SimpleStatePending)
sc.gh = sc.ac.SendGoal(goal, sc.transitionHandler, sc.feedbackHandler)
}
func (sc *simpleActionClient) SendGoalAndWait(goal ros.Message, executeTimeout, preeptTimeout ros.Duration) (uint8, error) {
sc.SendGoal(goal, nil, nil, nil)
if !sc.WaitForResult(executeTimeout) {
sc.logger.Debug("Cancelling goal")
sc.CancelGoal()
if sc.WaitForResult(preeptTimeout) {
sc.logger.Debug("Preempt finished within specified timeout")
} else {
sc.logger.Debug("Preempt did not finish within specified timeout")
}
}
return sc.GetState()
}
func (sc *simpleActionClient) WaitForServer(timeout ros.Duration) bool {
return sc.ac.WaitForServer(timeout)
}
func (sc *simpleActionClient) WaitForResult(timeout ros.Duration) bool {
if sc.gh == nil {
sc.logger.Errorf("[SimpleActionClient] Called WaitForResult when no goal exists")
return false
}
waitStart := ros.Now()
waitStart = waitStart.Add(timeout)
LOOP:
for {
select {
case <-sc.doneChan:
break LOOP
case <-time.After(100 * time.Millisecond):
}
if !timeout.IsZero() && waitStart.Cmp(ros.Now()) <= 0 {
break LOOP
}
}
return sc.simpleState == SimpleStateDone
}
func (sc *simpleActionClient) GetResult() (ros.Message, error) {
if sc.gh == nil {
return nil, fmt.Errorf("called get result when no goal running")
}
return sc.gh.GetResult()
}
func (sc *simpleActionClient) GetState() (uint8, error) {
if sc.gh == nil {
return actionlib_msgs.LOST, fmt.Errorf("called get state when no goal running")
}
status, err := sc.gh.GetGoalStatus()
if err != nil {
return actionlib_msgs.LOST, err
}
if status == actionlib_msgs.RECALLING {
status = actionlib_msgs.PENDING
} else if status == actionlib_msgs.PREEMPTING {
status = actionlib_msgs.ACTIVE
}
return status, nil
}
func (sc *simpleActionClient) GetGoalStatusText() (string, error) {
if sc.gh == nil {
return "", fmt.Errorf("called GetGoalStatusText when no goal is running")
}
return sc.gh.GetGoalStatusText()
}
func (sc *simpleActionClient) CancelAllGoals() {
sc.ac.CancelAllGoals()
}
func (sc *simpleActionClient) CancelAllGoalsBeforeTime(stamp ros.Time) {
sc.ac.CancelAllGoalsBeforeTime(stamp)
}
func (sc *simpleActionClient) CancelGoal() error {
if sc.gh == nil {
return nil
}
return sc.gh.Cancel()
}
func (sc *simpleActionClient) StopTrackingGoal() {
sc.gh = nil
}
func (sc *simpleActionClient) transitionHandler(gh ClientGoalHandler) {
commState, err := gh.GetCommState()
if err != nil {
sc.logger.Errorf("Error getting CommState: %v", err)
return
}
errMsg := fmt.Errorf("received comm state %s when in simple state %d with SimpleActionClient in NS %s",
commState, sc.simpleState, sc.ac.node.Name())
var callbackType string
var args []reflect.Value
switch commState {
case Active:
switch sc.simpleState {
case SimpleStatePending:
sc.setSimpleState(SimpleStateActive)
callbackType = "active"
case SimpleStateDone:
sc.logger.Errorf("[SimpleActionClient] %v", errMsg)
}
case Recalling:
switch sc.simpleState {
case SimpleStateActive, SimpleStateDone:
sc.logger.Errorf("[SimpleActionClient] %v", errMsg)
}
case Preempting:
switch sc.simpleState {
case SimpleStatePending:
sc.setSimpleState(SimpleStateActive)
callbackType = "active"
case SimpleStateDone:
sc.logger.Errorf("[SimpleActionClient] %v", errMsg)
}
case Done:
switch sc.simpleState {
case SimpleStatePending, SimpleStateActive:
sc.setSimpleState(SimpleStateDone)
sc.sendDone()
if sc.doneCb == nil {
break
}
status, err := gh.GetGoalStatus()
if err != nil {
sc.logger.Errorf("[SimpleActionClient] Error getting status: %v", err)
break
}
result, err := gh.GetResult()
if err != nil {
sc.logger.Errorf("[SimpleActionClient] Error getting result: %v", err)
break
}
callbackType = "done"
args = append(args, reflect.ValueOf(status))
args = append(args, reflect.ValueOf(result))
case SimpleStateDone:
sc.logger.Errorf("[SimpleActionClient] received DONE twice")
}
}
if len(callbackType) > 0 {
sc.runCallback(callbackType, args)
}
}
func (sc *simpleActionClient) sendDone() {
select {
case sc.doneChan <- struct{}{}:
default:
sc.logger.Errorf("[SimpleActionClient] Error sending done notification. Channel full.")
}
}
func (sc *simpleActionClient) feedbackHandler(gh ClientGoalHandler, msg ros.Message) {
if sc.gh == nil || sc.gh != gh {
return
}
sc.runCallback("feedback", []reflect.Value{reflect.ValueOf(msg)})
}
func (sc *simpleActionClient) setSimpleState(state uint8) {
sc.logger.Debugf("[SimpleActionClient] Transitioning from %d to %d", sc.simpleState, state)
sc.simpleState = state
}
func (sc *simpleActionClient) runCallback(cbType string, args []reflect.Value) {
var callback interface{}
switch cbType {
case "active":
callback = sc.activeCb
case "feedback":
callback = sc.feedbackCb
case "done":
callback = sc.doneCb
default:
sc.logger.Errorf("[SimpleActionClient] Unknown callback %s", cbType)
}
if callback == nil {
return
}
fun := reflect.ValueOf(callback)
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded > len(args) {
sc.logger.Errorf("[SimpleActionClient] Unexpected arguments:"+
"callback %s expects %d arguments but %d arguments provided", cbType, numArgsNeeded, len(args))
return
}
sc.logger.Debugf("[SimpleActionClient] Calling %s callback with %d arguments", cbType, len(args))
fun.Call(args[0:numArgsNeeded])
}
<file_sep>package main
//go:generate gengo action actionlib_tutorials/Fibonacci
import (
"actionlib_tutorials"
"fmt"
"os"
"time"
"github.com/fetchrobotics/rosgo/actionlib"
"github.com/fetchrobotics/rosgo/ros"
)
// fibonacciServer implements a fibonacci simple action server
// using the execute callback
type fibonacciServer struct {
node ros.Node
logger ros.Logger
as actionlib.SimpleActionServer
name string
fb ros.Message
result ros.Message
}
// newfibonacciServer creates a new fibonacci action server and starts it
func newFibonacciServer(node ros.Node, name string) {
s := &fibonacciServer{
node: node,
name: name,
logger: node.Logger(),
}
s.as = actionlib.NewSimpleActionServer(node, name,
actionlib_tutorials.ActionFibonacci, s.executeCallback, false)
s.as.Start()
}
func (s *fibonacciServer) executeCallback(goal *actionlib_tutorials.FibonacciGoal) {
feed := &actionlib_tutorials.FibonacciFeedback{}
feed.Sequence = append(feed.Sequence, 0)
feed.Sequence = append(feed.Sequence, 1)
success := true
for i := 1; i < int(goal.Order); i++ {
if s.as.IsPreemptRequested() {
success = false
if err := s.as.SetPreempted(nil, ""); err != nil {
s.logger.Error(err)
}
break
}
val := feed.Sequence[i] + feed.Sequence[i-1]
feed.Sequence = append(feed.Sequence, val)
s.as.PublishFeedback(feed)
time.Sleep(1000 * time.Millisecond)
}
if success {
result := &actionlib_tutorials.FibonacciResult{Sequence: feed.Sequence}
if err := s.as.SetSucceeded(result, "goal"); err != nil {
s.logger.Error(err)
}
}
}
func main() {
node, err := ros.NewNode("test_fibonacci_server", os.Args)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer node.Shutdown()
newFibonacciServer(node, "fibonacci")
node.Spin()
}
<file_sep>package main
//go:generate gengo action actionlib_tutorials/Fibonacci
import (
"actionlib_tutorials"
"fmt"
"os"
"github.com/fetchrobotics/rosgo/actionlib"
"github.com/fetchrobotics/rosgo/ros"
)
type fibonacciClient struct {
node ros.Node
name string
ac actionlib.SimpleActionClient
logger ros.Logger
}
func newfibonacciClient(node ros.Node, name string) *fibonacciClient {
fc := &fibonacciClient{
node: node,
ac: actionlib.NewSimpleActionClient(node, name, actionlib_tutorials.ActionFibonacci),
logger: node.Logger(),
}
fc.logger.Info("Waiting for server to start")
fc.ac.WaitForServer(ros.NewDuration(0, 0))
fc.logger.Info("Server started")
return fc
}
func (fc *fibonacciClient) activeCb() {
fc.logger.Info("Goal just went active")
}
func (fc *fibonacciClient) feedbackCb(fb *actionlib_tutorials.FibonacciFeedback) {
fc.logger.Infof("Got feedback of from server: %v", fb.Sequence)
}
func (fc *fibonacciClient) doneCb(state uint8, result *actionlib_tutorials.FibonacciResult) {
fc.logger.Infof("Finished in state %v", state)
fc.logger.Infof("Sequence: %v", result.Sequence)
fc.node.Shutdown()
}
func (fc *fibonacciClient) sendGoal(order int32) {
goal := &actionlib_tutorials.FibonacciGoal{Order: order}
fc.ac.SendGoal(goal, fc.doneCb, fc.activeCb, fc.feedbackCb)
}
func main() {
node, err := ros.NewNode("test_fibonacci_client", os.Args)
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
fc := newfibonacciClient(node, "fibonacci")
fc.sendGoal(10)
node.Spin()
}
<file_sep>package actionlib
import (
"actionlib_msgs"
"fmt"
"reflect"
"sync"
"time"
"github.com/fetchrobotics/rosgo/ros"
)
type simpleActionServer struct {
actionServer *defaultActionServer
currentGoal *serverGoalHandler
nextGoal *serverGoalHandler
goalMutex sync.RWMutex
newGoal bool
preemptRequest bool
newGoalPreemptRequest bool
logger ros.Logger
goalCallback interface{}
preemptCallback interface{}
executeCb interface{}
executorCh chan struct{}
}
func newSimpleActionServer(node ros.Node, action string, actType ActionType, executeCb interface{}, start bool) *simpleActionServer {
s := new(simpleActionServer)
s.actionServer = newDefaultActionServer(node, action, actType, s.internalGoalCallback, s.internalPreemptCallback, start)
s.newGoal = false
s.preemptRequest = false
s.newGoalPreemptRequest = false
s.executeCb = executeCb
s.logger = node.Logger()
s.executorCh = make(chan struct{}, 100)
return s
}
func (s *simpleActionServer) Start() {
if s.executeCb != nil {
go s.goalExecutor()
}
go s.actionServer.Start()
}
func (s *simpleActionServer) IsNewGoalAvailable() bool {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
return s.newGoal
}
func (s *simpleActionServer) IsPreemptRequested() bool {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
return s.preemptRequest
}
func (s *simpleActionServer) AcceptNewGoal() (ros.Message, error) {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
if !s.newGoal || s.nextGoal == nil {
return nil, fmt.Errorf("attempting to accept the next goal when a new goal is not available")
}
// check if we need to send a preempted message for the goal that we're currently pursuing
if s.IsActive() && s.currentGoal != nil && s.currentGoal.NotEqual(s.nextGoal) {
s.currentGoal.SetCancelled(s.GetDefaultResult(),
"This goal was canceled because another goal was received by the simple action server")
}
s.logger.Debug("Accepting a new goal")
// accept the next goal
s.currentGoal = s.nextGoal
s.newGoal = false
// set preempt to request to equal the preempt state of the new goal
s.preemptRequest = s.newGoalPreemptRequest
s.newGoalPreemptRequest = false
// set the status of the current goal to be active
s.currentGoal.SetAccepted("This goal has been accepted by the simple action server")
return s.currentGoal.GetGoal(), nil
}
func (s *simpleActionServer) IsActive() bool {
if s.currentGoal == nil || s.currentGoal.GetGoalId().Id == "" {
return false
}
status := s.currentGoal.GetGoalStatus().Status
if status == actionlib_msgs.ACTIVE || status == actionlib_msgs.PREEMPTING {
return true
}
return false
}
func (s *simpleActionServer) SetSucceeded(result ros.Message, text string) error {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
if result == nil {
result = s.GetDefaultResult()
}
return s.currentGoal.SetSucceeded(result, text)
}
func (s *simpleActionServer) SetAborted(result ros.Message, text string) error {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
if result == nil {
result = s.GetDefaultResult()
}
return s.currentGoal.SetAborted(result, text)
}
func (s *simpleActionServer) SetPreempted(result ros.Message, text string) error {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
if result == nil {
result = s.GetDefaultResult()
}
return s.currentGoal.SetCancelled(result, text)
}
func (s *simpleActionServer) PublishFeedback(feedback ros.Message) {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
s.currentGoal.PublishFeedback(feedback)
}
func (s *simpleActionServer) GetDefaultResult() ros.Message {
return s.actionServer.actionResultType.NewMessage()
}
func (s *simpleActionServer) RegisterGoalCallback(cb interface{}) error {
if s.executeCb != nil {
return fmt.Errorf("execute callback if present: not registering goal callback")
}
s.goalCallback = cb
return nil
}
func (s *simpleActionServer) RegisterPreemptCallback(cb interface{}) {
s.preemptCallback = cb
}
func (s *simpleActionServer) internalGoalCallback(ag ActionGoal) {
goalHandler := s.actionServer.getHandler(ag.GetGoalId().Id)
s.logger.Infof("[SimpleActionServer] Server received new goal with id %s", goalHandler.GetGoalId().Id)
var goalStamp, nextGoalStamp ros.Time
goalStamp = goalHandler.GetGoalId().Stamp
if s.nextGoal != nil {
nextGoalStamp = s.nextGoal.GetGoalId().Stamp
}
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
if (s.currentGoal == nil || goalStamp.Cmp(s.currentGoal.GetGoalId().Stamp) >= 0) &&
(s.nextGoal == nil || nextGoalStamp.Cmp(s.currentGoal.GetGoalId().Stamp) >= 0) {
if (s.nextGoal != nil) &&
(s.currentGoal == nil || s.nextGoal.NotEqual(s.currentGoal)) {
s.nextGoal.SetCancelled(s.GetDefaultResult(),
"This goal was canceled because another goal was received by the simple action server")
}
s.nextGoal = goalHandler
s.newGoal = true
s.newGoalPreemptRequest = false
goal := goalHandler.GetGoal()
args := []reflect.Value{reflect.ValueOf(goal)}
if s.IsActive() {
s.preemptRequest = true
if err := s.runCallback("preempt", args); err != nil {
s.logger.Error(err)
}
}
if err := s.runCallback("goal", args); err != nil {
s.logger.Error(err)
}
// notify executor that a new goal is available
select {
case s.executorCh <- struct{}{}:
default:
s.logger.Error("[SimpleActionServer] Exectuor new goal notification error: Channel full.")
}
} else {
goalHandler.SetCancelled(s.GetDefaultResult(),
"This goal was canceled because another goal was received by the simple action server")
}
}
func (s *simpleActionServer) internalPreemptCallback(gID *actionlib_msgs.GoalID) {
s.goalMutex.Lock()
defer s.goalMutex.Unlock()
goalHandler := s.actionServer.getHandler(gID.Id)
s.logger.Infof("[SimpleActionServer] Server received preempt call for goal with id %s",
goalHandler.GetGoalId().Id)
if goalHandler.GetGoalId().Id == s.currentGoal.GetGoalId().Id {
s.preemptRequest = true
goal := goalHandler.GetGoal()
args := []reflect.Value{reflect.ValueOf(goal)}
if err := s.runCallback("preempt", args); err != nil {
s.logger.Error(err)
}
} else {
s.newGoalPreemptRequest = true
}
}
func (s *simpleActionServer) goalExecutor() {
intervalCh := time.NewTicker(1 * time.Second)
defer intervalCh.Stop()
for s.actionServer.node.OK() {
select {
case <-s.executorCh:
if err := s.execute(); err != nil {
s.logger.Error(err)
return
}
case <-intervalCh.C:
if err := s.execute(); err != nil {
s.logger.Error(err)
return
}
}
}
}
func (s *simpleActionServer) execute() error {
if s.IsActive() {
return fmt.Errorf("should never reach this code with an active goal")
}
if s.IsNewGoalAvailable() {
goal, err := s.AcceptNewGoal()
if err != nil {
return err
}
if s.executeCb == nil {
return fmt.Errorf("execute callback must exist. This is a bug in SimpleActionServer")
}
args := []reflect.Value{reflect.ValueOf(goal)}
if err := s.runCallback("execute", args); err != nil {
return err
}
if s.IsActive() {
s.logger.Warn("Your executeCallback did not set the goal to a terminal status." +
"This is a bug in your ActionServer implementation. Fix your code!" +
"For now, the ActionServer will set this goal to aborted")
if err := s.SetAborted(nil, ""); err != nil {
return err
}
}
}
return nil
}
func (s *simpleActionServer) runCallback(cbType string, args []reflect.Value) error {
var callback interface{}
switch cbType {
case "goal":
callback = s.goalCallback
case "preempt":
callback = s.preemptCallback
case "execute":
callback = s.executeCb
default:
return fmt.Errorf("unknown callback type called")
}
if callback == nil {
return nil
}
fun := reflect.ValueOf(callback)
numArgsNeeded := fun.Type().NumIn()
if numArgsNeeded <= 1 {
fun.Call(args[0:numArgsNeeded])
} else {
return fmt.Errorf("unexepcted number of arguments for callback")
}
return nil
}
<file_sep>package ros
import (
"io"
"testing"
"google3/third_party/golang/cmp/cmp"
)
func TestReader(t *testing.T) {
type nextOp struct {
n int
want []byte
}
type readOp struct {
buffer []byte
want []byte
wantN int
wantErr error
}
type op struct {
read *readOp
next *nextOp
}
for _, tc := range []struct {
name string
data []byte
ops []op
}{
{
name: "ReadAll",
data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24},
ops: []op{
{read: &readOp{
buffer: make([]byte, 8),
want: []byte{1, 2, 3, 4, 5, 6, 7, 8},
wantN: 8,
}},
{read: &readOp{
buffer: make([]byte, 8),
want: []byte{9, 10, 11, 12, 13, 14, 15, 16},
wantN: 8,
}},
{read: &readOp{
buffer: make([]byte, 16),
want: []byte{17, 18, 19, 20, 21, 22, 23, 24, 0, 0, 0, 0, 0, 0, 0, 0},
wantN: 8,
}},
{read: &readOp{
buffer: make([]byte, 1),
want: []byte{0},
wantN: 0,
wantErr: io.EOF,
}},
},
},
{
name: "NextAll",
data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24},
ops: []op{
{next: &nextOp{
n: 8,
want: []byte{1, 2, 3, 4, 5, 6, 7, 8},
}},
{next: &nextOp{
n: 8,
want: []byte{9, 10, 11, 12, 13, 14, 15, 16},
}},
{next: &nextOp{
n: 16,
want: []byte{17, 18, 19, 20, 21, 22, 23, 24},
}},
{next: &nextOp{
n: 8,
want: []byte{},
}},
},
},
{
name: "ReadAndNextAll",
data: []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24},
ops: []op{
{read: &readOp{
buffer: make([]byte, 8),
want: []byte{1, 2, 3, 4, 5, 6, 7, 8},
wantN: 8,
}},
{next: &nextOp{
n: 8,
want: []byte{9, 10, 11, 12, 13, 14, 15, 16},
}},
{read: &readOp{
buffer: make([]byte, 16),
want: []byte{17, 18, 19, 20, 21, 22, 23, 24, 0, 0, 0, 0, 0, 0, 0, 0},
wantN: 8,
}},
{next: &nextOp{
n: 8,
want: []byte{},
}},
},
},
{
name: "ReadEmtpyBuffer",
data: []byte{},
ops: []op{
{read: &readOp{
buffer: make([]byte, 1),
want: []byte{0},
wantN: 0,
wantErr: io.EOF,
}},
},
},
{
name: "ReadEmtpyBufferEmptyRead",
data: []byte{},
ops: []op{
{read: &readOp{
buffer: make([]byte, 0),
want: []byte{},
wantN: 0,
wantErr: io.EOF,
}},
},
},
{
name: "NextEmtpyBuffer",
data: []byte{},
ops: []op{
{next: &nextOp{
n: 1,
want: []byte{},
}},
},
},
{
name: "NextEmtpyBufferZeroBytes",
data: []byte{},
ops: []op{
{next: &nextOp{
n: 0,
want: []byte{},
}},
},
},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
r := NewReader(tc.data)
for _, op := range tc.ops {
if op.read != nil {
n, err := r.Read(op.read.buffer)
if diff := cmp.Diff(op.read.want, op.read.buffer); diff != "" {
t.Errorf("Read(%v) read unexpected bytes: diff (-want +got): %v\nreader: %+v", op.read.buffer, diff, r)
}
if op.read.wantN != n {
t.Errorf("Read(%v) read unexpected number of bytes: got %v, want %v\nreader: %+v", op.read.buffer, n, op.read.wantN, r)
}
if op.read.wantErr != err {
t.Errorf("Read(%v) returned unexpected error: got %v, want %v\nreader: %+v", op.read.buffer, err, op.read.wantErr, r)
}
} else if op.next != nil {
got := r.Next(op.next.n)
if diff := cmp.Diff(op.next.want, got); diff != "" {
t.Errorf("Next(%v) returned unexpected bytes: diff (-want +got): %v\nreader: %+v", op.next.n, diff, r)
}
}
}
})
}
}
| 62b9485e5263fe6a6c4994a54cabf1a9386f651a | [
"Markdown",
"Go",
"Shell"
] | 24 | Go | fetchrobotics/rosgo | bcec6a992f59d463336d8dcd2f399452d8e522ea | 3be4711f5eaa719af14ade61d744642f5a5bf78c |
refs/heads/master | <repo_name>sonali718/Sonali1<file_sep>/skillenzaviews (2).R
views = read.csv("C:/Users/lenovo/Desktop/viewstrain.csv")
names(views)
summary(views)
str(views)
views = views[,c(-5,-6,-7,-8,-9,-18,-15,-20,-21)]
str(views)
names(views)
library(lubridate)
views$publish_date = dmy(views$publish_date)
views$trending_date =dmy(views$trending_date)
views$dislike = as.integer(views$dislike)
views$Video_id = as.integer(views$Video_id)
views$views = as.integer(views$views)
str(views)
views$Tag_count = as.integer(views$Tag_count)
views$Trend_tag_count = as.integer(views$Trend_tag_count)
str(views)
views$category_id = as.integer(views$category_id)
str(views)
summary(views)
library(VIM)
imputed = kNN(views)
summary(imputed)
imputed = imputed[,c(1:12)]
str(imputed)
views$Tag_count = ifelse(views$Tag_count == " ",NA,views$Tag_count)
views$Trend_tag_count = ifelse(views$Trend_tag_count == " ",NA,views$Tag_count)
views$comment_count = ifelse(views$comment_count == " ",NA,views$comment_count)
views$likes = ifelse(views$likes == " ",NA,views$likes)
impute_num = imputed[sapply(imputed,is.numeric)]
impute_char = imputed[sapply(imputed,is.factor)]
varnames = names(impute_num)
for (i in 2:9)
{
impute_num[,i+8] <- ifelse(impute_num[,i] > quantile((impute_num[,i]),c(0.95)),
quantile(impute_num[,i],c(0.95)),impute_num[,i])
}
impute_num = impute_num[,c(1,10:17)]
names(impute_num) = varnames
library(caret)
impute_num_nzv = nearZeroVar(impute_num)
impute_num_nzv
views_final = cbind(impute_num,impute_char)
views_final$publish_date = views$publish_date
views_final$trending_date = views$trending_date
summary(views_final)
table(views_final$views)
library(caTools)
set.seed(100)
sample = sample.split(views_final$views,SplitRatio = 0.8)
train = subset(views_final,sample == T)
test = subset(views_final,sample == F)
names(train)
model = lm(views~.,data = train)
summary(model)
predict_test = predict(model,newdata = test)
head(predict_test)
test$predicted = predict_test
test$error = test$views - test$predicted
install.packages("Metrics")
library(Metrics)
rmse(test$views,test$predicted)
#_______________________________decision-tree--------------------------------------
names(train)
library(rpart)
mtree = rpart(views~.,data = train[,c(-1)],
control = rpart.control(minsplit = 500,minbucket = 300,maxdepth = 30,cp=0.001,xval = 10))
plot(mtree)
library(rattle)
library(rpart.plot)
library(RColorBrewer)
fancyRpartPlot(mtree,main = "deci_tree for views for a video",sub = "prediction for views",
caption = TRUE,palettes = "BuGn",type = 2)
prp(mtree,faclen = 1,cex = 0.8,extra = 1)
pred = predict(mtree,test[,c(-1)])
table(train$views)
head(pred,100)
pred = as.data.frame(pred)
library(Metrics)
summary(train)
str(train)
str(test)
summary(pred)
summary(test$views)
rmse(test$views,pred$pred)
#----------------------------validation data----------------------------------
str(train)
validation = read.csv("C:/Users/lenovo/Desktop/viewstest.csv")
str(validation)
library(VIM)
validation = kNN(validation)
summary(validation)
validation = validation[,c(1:18)]
names(validation)
validation=validation[,c(-5,-6,-7,-8,-9,-18)]
summary(validation)
str(validation)
library(lubridate)
validation$publish_date = ymd(validation$publish_date)
validation$trending_date = ymd(validation$trending_date)
validation$comment_disabled=as.factor(validation$comment_disabled)
validation$Video_id = as.integer(validation$Video_id)
names(validation)
pred_valid = predict(model,validation)
head(pred_valid)
pred_final = as.data.frame(pred_valid)
validation$views = pred_final
names(validation)
validation = validation[,c(1,13)]
write.csv(validation,"submission1.csv")
getwd()
<file_sep>/upvotes_linear_reg.R
upvotes1 = read.csv("C:/Users/lenovo/Downloads/upvotestraindata.csv",nrows = 20000)
summary(upvotes1)
str(upvotes1)
head(upvotes1)
upvotes1[is.na(upvotes1)]=0
summary(upvotes1)
library(Amelia)
missmap(upvotes1,legend = TRUE,main = "to find out the upvotes",
y.cex = 0.8,x.cex = 0.8)
str(upvotes1)
upvotes_num = upvotes1[sapply(upvotes1,is.numeric)]
upvotes_char = upvotes1[sapply(upvotes1,is.factor)]
names(upvotes_num)
for (i in 2:6)
{
upvotes_num[,i+5] <- ifelse(upvotes_num[,i] > quantile(abs(upvotes_num[,i]),c(0.99)),
quantile(upvotes_num[,i],c(0.99)),upvotes_num[,i] )
}
names(upvotes_num)
summary(upvotes_num)
upvotes_num = upvotes_num[,c(1,7:11)]
names(upvotes_num) = c("ID","Repuations","Answers","Usernames","Views","Upvotes")
library(caret)
upvotes_nzv = (nearZeroVar(upvotes_num))
upvotes_nzv
merged_data = cbind(upvotes_num,upvotes_char)
names(merged_data)
merged_data = merged_data[,-1]
library(caTools)
set.seed(200)
sample = sample.split(merged_data,SplitRatio = 0.8)
train = subset(merged_data,sample == T)
test = subset(merged_data,sample == F)
names(train)
linear_reg = lm(Upvotes~.,data = train)
summary(linear_reg)
predict_test = predict(linear_reg,newdata = test)
summary(predict_test)
plot(linear_reg)
test$predicted = predict_test
test$predicted
test$error = test$Upvotes-test$predicted
head(upvotes1)
| b15d28f85c47b50cd6f788b466e81359333b84dd | [
"R"
] | 2 | R | sonali718/Sonali1 | 0c50d2ea8b12157dab7d77bf020fde7c068ed996 | 00ba205552b6f748db24d098f3e41b225ff9071d |
refs/heads/main | <repo_name>ahmed531998/IoT<file_sep>/CoAP Network/Sensor/node.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "contiki.h"
#include "coap-engine.h"
#include "sys/etimer.h"
#include "coap-blocking-api.h"
#include "random.h"
#include "node-id.h"
#include "whatever.h"
/* Log configuration */
#include "sys/log.h"
#define LOG_MODULE "App"
#define LOG_LEVEL LOG_LEVEL_APP
#define SERVER "coap://[fd00::1]:5683"
static struct etimer myPeriodicTimer;
bool registered = false;
static int period = 0;
void client_chunk_handler(coap_message_t *response)
{
const uint8_t *chunk;
if(response == NULL) {
LOG_INFO("Request timed out");
return;
}
registered = true;
int len = coap_get_payload(response, &chunk);
LOG_INFO("|%.*s \n", len, (char *)chunk);
}
PROCESS(node, "node");
AUTOSTART_PROCESSES(&node);
int temperatureValue = 37;
extern coap_resource_t ledAlarm;
extern coap_resource_t temperature;
#define MAXTEMP 41
#define MINTEMP 35
int measure_temperature(){
int measuredValue = (rand() % (MAXTEMP-MINTEMP+1)) + MINTEMP;
return measuredValue;
}
PROCESS_THREAD(node, ev, data)
{
srand(time(NULL));
static coap_endpoint_t myServer;
static coap_message_t request[1];
PROCESS_BEGIN();
PROCESS_PAUSE();
LOG_INFO("Starting sensor node\n");
coap_activate_resource(&ledAlarm, "alarm");
coap_activate_resource(&temperature, "temperature");
coap_endpoint_parse(SERVER, strlen(SERVER), &myServer);
coap_init_message(request, COAP_TYPE_CON, COAP_GET, 0);
coap_set_header_uri_path(request, "registry");
LOG_DBG("Registering with server\n");
COAP_BLOCKING_REQUEST(&myServer, request, client_chunk_handler);
while(!registered){
LOG_DBG("Retrying with server\n");
COAP_BLOCKING_REQUEST(&myServer, request, client_chunk_handler);
}
etimer_set(&myPeriodicTimer, 30*CLOCK_SECOND);
while(1) {
PROCESS_WAIT_EVENT();
if (ev == PROCESS_EVENT_TIMER && data == &myPeriodicTimer){
temperatureValue = measure_temperature();
temperature.trigger();
if(period%5==0) {
LOG_DBG("Retrying/Pinging the server\n");
COAP_BLOCKING_REQUEST(&myServer, request, client_chunk_handler);
}
period++;
etimer_reset(&myPeriodicTimer);
}
}
PROCESS_END();
}
<file_sep>/CoAP Network/Sensor/resources/temperature.c
#include <stdlib.h>
#include <string.h>
#include "coap-engine.h"
#include <stdio.h>
#include "coap-observe.h"
#include "../whatever.h"
//API FUNCTION DEFINITIONS
static void res_get_handler(coap_message_t *request, coap_message_t *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset);
static void res_event_handler(void);
//RESOURCE DEFINITION
EVENT_RESOURCE(temperature,
"title=\"Temperature Sensor\";obs;rt=\"Temperature\"",
res_get_handler,
NULL,
NULL,
NULL,
res_event_handler);
//API FUNCTIONS IMPLEMENTATIONS
static void res_event_handler(void){
coap_notify_observers(&temperature);
}
static void res_get_handler(coap_message_t *request, coap_message_t *response, uint8_t *buffer, uint16_t preferred_size, int32_t *offset){
unsigned int accept = -1;
coap_get_header_accept(request, &accept);
if (accept == -1) {
coap_set_header_content_format(response, APPLICATION_JSON);
snprintf((char *)buffer, COAP_MAX_CHUNK_SIZE, "{\"temperature\": %d, \"timestamp\": %lu, \"unit\": \"celsius\"}", temperatureValue, clock_seconds());
coap_set_payload(response, (uint8_t *)buffer, strlen((char *)buffer));
}
else if (accept == APPLICATION_JSON){
coap_set_header_content_format(response, APPLICATION_JSON);
snprintf((char *)buffer, COAP_MAX_CHUNK_SIZE, "{\"temperature\": %d, \"timestamp\": %lu, \"unit\": \"celsius\"}", temperatureValue, clock_seconds());
coap_set_payload(response, buffer, strlen((char *)buffer));
}
else {
coap_set_status_code(response, NOT_ACCEPTABLE_4_06);
const char *msg = "Supporting content-type application/json";
coap_set_payload(response, msg, strlen(msg));
}
}
<file_sep>/my-app/iot.unipi.it/src/main/java/iot/unipi/it/DBControl.java
package iot.unipi.it;
import java.sql.*;
public class DBControl {
private Connection c = null;
private PreparedStatement pStmt = null;
private ResultSet rs = null;
private String myTable;
private String myTableAttributes[];
public DBControl(String DB_URL, String username, String password, String myTable, String myTableAttributes[]) throws SQLException{
try {
this.myTable = myTable;
this.myTableAttributes = myTableAttributes;
this.c = DriverManager.getConnection(DB_URL, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean addReading(String URI, Integer timestamp, Integer reading, boolean state)
throws SQLException{
try {
String query = "insert into " + myTable +
" (" + myTableAttributes[1] + ", " +
myTableAttributes[2] + ", " +
myTableAttributes[3] + ", " +
myTableAttributes[4] + ") VALUES (?, ?, ?, ?)";
pStmt = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pStmt.setString (1, URI);
pStmt.setInt (2, timestamp);
pStmt.setInt (3, reading);
pStmt.setBoolean(4, state);
pStmt.execute();
pStmt = null;
rs = null;
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean deleteReadingOfNode(String URI) throws SQLException{
try {
String query = "delete from "+myTable+" where "+myTableAttributes[1]+" = ?";
pStmt = c.prepareStatement(query);
pStmt.setString(1, URI);
pStmt.execute();
pStmt = null;
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean deleteSpecificReadingOfNode(String URI, Integer timestamp) {
try {
String query = "delete from "+myTable+" where "+myTableAttributes[1]+ " = ? and "
+ myTableAttributes[2] + " = ?";
pStmt = c.prepareStatement(query);
pStmt.setString(1, URI);
pStmt.execute();
pStmt = null;
return true;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public void getReadingOfNode(String URI) throws SQLException{
try {
String query = "select * from " + myTable + " where " + myTableAttributes[1] + " = ?";
pStmt = c.prepareStatement(query);
pStmt.setString (1, URI);
rs = pStmt.executeQuery();
while (rs.next()) {
System.out.println("Node: "+rs.getString(myTableAttributes[1])+
"\ttime: "+rs.getInt(myTableAttributes[2])+
"\tvalue: "+rs.getInt(myTableAttributes[3])+
" celsius\talarm on? "+rs.getBoolean(myTableAttributes[4]));
}
pStmt = null;
rs = null;
}catch (SQLException e) {
e.printStackTrace();
}
}
public void getSpecificReadingOfNode(String URI, Integer timestamp) {
try {
String query = "select * from " + myTable + " where " + myTableAttributes[1] + " = ? and "
+ myTableAttributes[2] + " = ?";
pStmt = c.prepareStatement(query);
pStmt.setString (1, URI);
pStmt.setInt(2, timestamp);
rs = pStmt.executeQuery();
while (rs.next()) {
System.out.println("Node: "+rs.getString(myTableAttributes[1])+
"\ttime: "+rs.getInt(myTableAttributes[2])+
"\tvalue: "+rs.getInt(myTableAttributes[3])+
" celsius\talarm on? "+rs.getBoolean(myTableAttributes[4]));
}
pStmt = null;
rs = null;
}catch (SQLException e) {
e.printStackTrace();
}
}
}
<file_sep>/CoAP Network/Sensor/whatever.h
extern int temperatureValue;
<file_sep>/my-app/.metadata/version.ini
#Mon May 31 22:04:19 EDT 2021
org.eclipse.core.runtime=2
org.eclipse.platform=4.14.0.v20191210-0610
<file_sep>/my-app/iot.unipi.it/src/main/java/iot/unipi/it/Collector.java
package iot.unipi.it;
import java.sql.SQLException;
import java.util.ArrayList;
public class Collector {
//DB CONFIG
private static String DB_URL = "jdbc:mysql://localhost/ahmed?serverTimezone=UTC";
private static String table = "patients";
private static String tableAttributes[] = {"id", "URI", "timestamp", "value", "state"};
//RESOURCE STORAGE
protected static ArrayList<Thermometer> thermometers = new ArrayList<Thermometer>();
protected static ArrayList<Alarm> alarms = new ArrayList<Alarm>();
//DB CONTROLLER
protected static DBControl db;
//MQTT CLIENT
private static CollectorMqttClient mc = null;
//START THREAD FOR THE SERVER THAT CREATES THE CoAP OBSERVER CLIENTS
public static void runServer() {
new Thread() {
public void run() {
CollectorServer server = new CollectorServer();
server.startServer();
}
}.start();
}
public static void createMqttClient() throws InterruptedException{
mc = new CollectorMqttClient();
}
public static void main(String[] args) throws SQLException, InterruptedException{
db = new DBControl(DB_URL, "root", "root", table, tableAttributes);
runServer();
createMqttClient();
}
}
<file_sep>/README.md
# IoT Project 2021 - AIDE - UNIPI
An IoT-based system that is intended to keep track of patients temperatures at the hospital and take action accordingly by triggering an alarm (simulated by a led) if necessary.
# Instructions Manual
# Locally, on the virtual machine,
1) Save the repo under contiki-ng/examples directory.
2) Load the simulation from the repo
3) Compile border-router.c under the "CoAP Network"/"Border Router"/ directory and node.c under the "CoAP Network"/"Sensor"/ directory
4) Start the simulation
5) Run this command under the "CoAP Network"/"Border Router"/ directory ==> make TARGET=cooja connect-router-cooja
# Remotely, on the testbed,
1) Connect to the remote testbed via ssh tunneling
2) In the terminal, type sudo vi /etc/mosquitto/mosquitto.conf
3) Add the following 3 lines:
1- allow_anonymous true
2- listener 1883 fd00::1
3- listener 1883 localhost
4) Save the modifications.
5) Under the Mqtt Network directory, modify the PANID in the project-conf.h of the border router to your PANID (If it is to be executed on the remote testbed)
6) Start mosquitto (see instructions.txt)
7) Deploy the code under the Mqtt Network directory on the remote sensors (one for the border router and another for the sensor) (see instructions.txt)
# Locally, on the virtual machine,
1) modify the database configuration in the Collector.java file under the my-app java folder inside the iot.unipi.it package
2) run "mvn clean install" in terminal
3) run the code
| 9ff95b757a5616d3427758f615dfd359f0b15e8a | [
"Java",
"C",
"Markdown",
"INI"
] | 7 | C | ahmed531998/IoT | 2f45d3b1deac95449701b3604afdca8f20ab9305 | ecf4e84d013556b4b8ec85112ae6deca4c1dbc4c |
refs/heads/master | <file_sep>SDBMWCCAAX-PHP
==============
San Diego BMW CCA Autocross Administration - PHP
<file_sep><?php
ini_set('session.bug_compat_warn', 0);
ini_set('session.bug_compat_42', 0);
//php function definitions
function ccaaemail($subject, $message){
return ccaemail("Webmaster", "...", $subject, $message);
}
function ccaemail($name, $email, $subject, $message){ //emails from general website
$hmessage = $message;
$hmessage = '
<html>
<head>
<title>SDBMWCCA Website</title>
<link rel="shortcut icon" href="..." />
<link rel="stylesheet" href=".." type="text/css" />
</head>
<body>
<div id="top-logo" >
<img src="..." width="165" height="165" alt="San Diego BMW CCA logo" /><img src="..." width="700" height="165" alt="San Diego Bay with BMWs" />
</div>
<div id="calendar">
<p><strong>
'.$hmessage.'
</strong></p>
</div>
<div id="bottom-info">
<table width="100%" border="0" cellpadding="5px">
<tr>
<th scope="col"><a href="..." target="_new"><img src="..." alt="Like us on Facebook" /></a></th>
<th scope="col"><a href="..." target="_new"><img src="..." alt="Follow sdbmw on Twitter" height="35"/></a></th>
</tr>
</table>
</div>
<div id="bottom-logo" >
<img src="..." alt="" />
</div>
</body>
</html>
';
$args = array(
'key' => '...',
'message' => array(
"html" => $hmessage,
"text" => $message,
"from_email" => "...",
"from_name" => "...",
"subject" => $subject,
"to" => array(array("email" => $email, "name" => $name)),
"track_opens" => true,
"track_clicks" => true,
"auto_text" => true
)
);
$curl = curl_init('https://mandrillapp.com/api/1.0/messages/send.json' );
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($args));
$response = curl_exec($curl);
curl_close( $curl );
if(strpos($response,"sent") != false)
return true;
else
return false;
}
////////////////////////////////////DATABASE FUNCTIONS
//currently using mysqli, but all db interaction occurs via these functions, allowing any abstraction layer to be easily implemented.
$Db_Link = NULL;
function Sql_Connect(){
global $Db_Link;
if(!isset($Db_Link))
{
$Db_Link = mysqli_connect(...);
if(mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
}
return true;
}
function Sql_Query($query){
global $Db_Link;
$result = mysqli_query($Db_Link,$query);
//$result = $Db_Link->prepare($query);
if($result == FALSE)
{
$email = 'Error in this query: "'.$query.'"<br>Error: '. mysqli_error($Db_Link)." on page ".$_SERVER['PHP_SELF']."?".http_build_query($_GET);
ccaaemail("SQL ERROR", $email);
echo "An error has occurred, the administrator has been notified.";
Sql_Disconnect();
die();
}
return $result;
}
function Sql_Insert_Id(){
global $Db_Link;
return $Db_Link->insert_id;
}
function Sql_Affected_Rows(){
global $Db_Link;
return $Db_Link->affected_rows;
}
function Sql_Num_Rows($result){
return $result->num_rows;
}
function Sql_Num_Field($result){
return $result->field_count;
}
function Sql_Result($result, $num, $name){
global $Db_Link;
$result->data_seek($num);
$dataset = $result->fetch_assoc();
return $dataset[$name];
}
function Sql_Fetch_Row($result){
global $Db_Link;
return $result->fetch_row();
}
function Sql_CleanInput($input){
global $Db_Link;
$input = stripslashes($input);
$input = $Db_Link->real_escape_string($input);
return $input;
}
function Sql_Disconnect(){
global $Db_Link;
if(isset($Db_Link)){
mysqli_close($Db_Link);
$Db_Link = NULL;
}
return true;
}
?>
| 49db37cb54a740ae9c9c29426dae6d8c77f4c647 | [
"Markdown",
"PHP"
] | 2 | Markdown | ganeshtheju/SDBMWCCAAX-PHP | f6a4e1dc70b7cd628e891bfd43d53782761e1746 | fe5cf139ac153236fa733ecdd071a5ae0d05cdf2 |
refs/heads/master | <file_sep>export enum EnumType {}
<file_sep>import { FmComplexAction } from "../../../state/actions";
export type DecrementHook = (decrement: number) => FmComplexAction;
<file_sep>import { FmComplexAction, FmComplexActions } from "./actions";
import { IFmComplexState, initialState } from "./state";
export const fmComplex = (
state: IFmComplexState = initialState,
action: FmComplexAction
): IFmComplexState => {
switch (action.type) {
case FmComplexActions.INCREMENT: {
return {
...state,
count: state.count + action.payload,
};
}
case FmComplexActions.DECREMENT: {
return {
...state,
count: state.count - action.payload,
};
}
case FmComplexActions.RANDOM_INCREMENT: {
return {
...state,
count: state.count + action.payload,
};
}
default: {
return state;
}
}
};
<file_sep>import { useCallback } from "react";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { FmComplexAction, FmComplexActions } from "../../state/actions";
import { DecrementHook } from "../models/hooks/decrement";
export const useDecrementHook = (): DecrementHook => {
const dispatch = useDispatch<Dispatch<FmComplexAction>>();
const decrement = useCallback(
(decrement: number) =>
dispatch({
type: FmComplexActions.DECREMENT,
payload: decrement,
}),
[dispatch]
);
return decrement;
};
<file_sep>export interface IFmComplexState {
count: number;
}
export const initialState: IFmComplexState = {
count: 0,
};
<file_sep>import { TypedUseSelectorHook, useSelector } from "react-redux";
import { store } from "../store";
type RootState = ReturnType<typeof store.getState>;
export const useRootStateSelector: TypedUseSelectorHook<RootState> =
useSelector;
<file_sep>export * from "./hooks/root-state-selector";
export * from "./Provider";
<file_sep>import { FmComplexAction } from "../../../state/actions";
export type IncrementHook = (increment: number) => FmComplexAction;
<file_sep>import { EnumType } from "../enum/enum-type";
export type Action<E extends typeof EnumType, T> = {
type: E;
payload: T;
};
<file_sep>export interface IStore {
[reducer: string]: unknown;
}
<file_sep>export * from "./models/enum/enum-type";
export * from "./models/store/action";
export * from "./models/store/store";
<file_sep>export interface IGetRandomIncrementResponse {
increment: number;
}
<file_sep>import { IGetRandomIncrementResponse } from "../models/response/counter/get-random-increment";
export class CounterService {
static async getRandomIncrement(): Promise<IGetRandomIncrementResponse> {
try {
const response: IGetRandomIncrementResponse = await new Promise(
(resolve) => {
setTimeout(() => {
resolve({
increment: Math.floor(Math.random() * 100),
} as IGetRandomIncrementResponse);
}, 500);
}
);
return response;
} catch (error) {
throw error;
}
}
}
<file_sep>import { useCallback } from "react";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { FmComplexAction, FmComplexActions } from "../../state/actions";
import { IncrementHook } from "../models/hooks/increment";
export const useIncrementHook = (): IncrementHook => {
const dispatch = useDispatch<Dispatch<FmComplexAction>>();
const increment = useCallback(
(increment: number) =>
dispatch({
type: FmComplexActions.INCREMENT,
payload: increment,
}),
[dispatch]
);
return increment;
};
<file_sep>import { useCallback, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { Dispatch } from "redux";
import { FmComplexAction, FmComplexActions } from "../../state/actions";
import { RandomIncrementHook } from "../models/hooks/random-increment";
import { CounterService } from "../../../../services/counter";
export const useRandomIncrementHook = (): RandomIncrementHook => {
const [getRandom, setGetRandom] = useState<string>("");
const dispatch = useDispatch<Dispatch<FmComplexAction>>();
const generateRandom = () => {
setGetRandom(`random-${Math.random() * 1000000000000}`);
};
const randomIncrement = useCallback(
(increment: number) =>
dispatch({
type: FmComplexActions.RANDOM_INCREMENT,
payload: increment,
}),
[dispatch]
);
useEffect(() => {
const getRandomIncrement = async () => {
try {
const response = await CounterService.getRandomIncrement();
randomIncrement(response.increment);
} catch (error) {
alert("Error: getCountIncrement");
}
};
getRandomIncrement();
}, [getRandom, randomIncrement]);
return generateRandom;
};
<file_sep>import { combineReducers } from "redux";
import { fmComplex } from "./components/fm-complex/state/reducer";
export * from "./components/fm-complex/FmComplex";
export const featureModule = combineReducers({
fmComplex,
});
<file_sep>import { createStore, combineReducers, compose } from "redux";
import { featureModule } from "src/modules/feature-module";
declare global {
interface Window {
__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
}
}
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
export const store = createStore(
combineReducers({
featureModule,
}),
composeEnhancers()
);
| 4f03b73c3feff346e07418e84a813840d72ca1ed | [
"TypeScript"
] | 17 | TypeScript | tibor-mirnic-htec/redux-example | 2e9948f235e7d56a22489351834e47c3d2e5de91 | b1ab41093787b9b4e8759fab1df7a951f185f400 |
refs/heads/master | <repo_name>zhirou-zhou/respiratory-illness-project<file_sep>/README.md
# Respiratory Illness Project
This is the final project of BST-432 High Dimensional Data Analysis.
The project aims to apply Decision Tree and Random forest to predit whether an infant had a respiratory illness at a particular visit to hospital.
The target variables are 'is_illness' and 'precedes_illness', whose values are 'TRUE' or 'FALSE', representing whether the infant had an illness or precedes illness.
<file_sep>/Code/RandomForest.R
---
title: "Random Forest"
author: "<NAME>"
date: "12/13/2019"
output: html_document
---
```{r random forest for is_illness}
# Prepare 10-fold cross-validation blocked by Alias
nfold = 10
data_illness = data_illness %>% group_by(Alias)
data_illness$id = c()
data_illness$id = data_illness %>% group_indices(Alias)
size = floor(length(unique(data_illness$id)) / nfold)
set.seed(1211)
fold_id = sample(1:length(unique(data_illness$id)), length(unique(data_illness$id)))
g1_id = fold_id[1:size]
g2_id = fold_id[(size + 1):(size * 2)]
g3_id = fold_id[(size*2 + 1):(size * 3)]
g4_id = fold_id[(size*3 + 1):(size * 4)]
g5_id = fold_id[(size*4 + 1):(size * 5)]
g6_id = fold_id[(size*5 + 1):(size * 6)]
g7_id = fold_id[(size*6 + 1):(size * 7)]
g8_id = fold_id[(size*7 + 1):(size * 8)]
g9_id = fold_id[(size*8 + 1):(size * 9)]
g10_id = fold_id[(size*9 + 1):length(fold_id)]
data_g1 = as.data.frame(data_illness[data_illness$id %in% g1_id, ])
data_g2 = as.data.frame(data_illness[data_illness$id %in% g2_id, ])
data_g3 = as.data.frame(data_illness[data_illness$id %in% g3_id, ])
data_g4 = as.data.frame(data_illness[data_illness$id %in% g4_id, ])
data_g5 = as.data.frame(data_illness[data_illness$id %in% g5_id, ])
data_g6 = as.data.frame(data_illness[data_illness$id %in% g6_id, ])
data_g7 = as.data.frame(data_illness[data_illness$id %in% g7_id, ])
data_g8 = as.data.frame(data_illness[data_illness$id %in% g8_id, ])
data_g9 = as.data.frame(data_illness[data_illness$id %in% g9_id, ])
data_g10 = as.data.frame(data_illness[data_illness$id %in% g10_id, ])
data_fold = list(data_g1, data_g2, data_g3, data_g4, data_g5, data_g6, data_g7,data_g8, data_g9,
data_g10)
# Oversample the data within each group to balance `is_illness`
over_sample = function(data) {
times = floor(table(data$is_illness)[1] / table(data$is_illness)[2])
data_true = as.data.frame(data[which(data$is_illness == TRUE), ])
data_false = as.data.frame(data[which(data$is_illness == FALSE), ])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data = as.data.frame(rbind(data_true, data_false))
return(data)
}
data_fold = lapply(data_fold, over_sample)
data_fold_test = data_fold[[1]]
for (i in 2:length(data_fold)) {
data_fold_test = rbind(data_fold_test, data_fold[[i]])
}
# Generate the grid of `mtry` and `nodesize`
hyper_grid = expand.grid(mtry = seq(10, 60, by = 10), nodesize = seq(50, 1000, by = 100))
# 10-fold Cross-validation
forest_is = list()
forest_is_predict = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, precedes_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, precedes_illness)))
for (l in 1:nrow(hyper_grid)) {
forest_is[[l]] = randomForest(is_illness ~ ., data = train, importance = TRUE, mtry = hyper_grid$mtry[i],
nodesize = hyper_grid$nodesize[i], replace = FALSE)
}
forest_is_predict[[i]] = lapply(forest_is, predict, test)
}
# Combine the predictions by each random forest
predict_forest = list()
predict_fold = forest_is_predict[[1]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = NULL
predict_forest[[j]] = as.factor(prediction)
}
for (i in 2:nfold) {
predict_fold = forest_is_predict[[i]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = names(predict_forest[[j]])
predict_forest[[j]] = c(as.character(predict_forest[[j]]), as.character(prediction))
predict_forest[[j]] = as.factor(predict_forest[[j]])
}
}
# Tuning parameters by confusion matrices
forest_is_conf = list()
forest_is_conf = lapply(predict_forest, confusionMatrix,
data_fold_test$is_illness, positive = "TRUE")
prune = hyper_grid %>%
mutate(test_sensitivity = map_dbl(forest_is_conf, get_sensitivity),
test_specificity = map_dbl(forest_is_conf, get_specificity),
test_precision = map_dbl(forest_is_conf, get_precision),
test_recall = map_dbl(forest_is_conf, get_recall),
test_f1 = map_dbl(forest_is_conf, get_f1))
prune = prune[order(prune$test_precision, decreasing = TRUE), ]
head(prune)
save(forest_is, forest_is_predict, forest_is_conf, prune, file = "forest_is.rdata")
prune_mtry = prune[which(prune$nodesize == 450), ]
prune_nodesize = prune[which(prune$mtry == 30), ]
prune_mtry_err = prune_mtry %>% gather('metric', 'err', test_sensitivity, test_specificity, test_precision,
test_recall, test_f1)
prune_nodesize_err = prune_nodesize %>% gather('metric', 'err', test_sensitivity, test_specificity,
test_precision, test_recall, test_f1)
plot_mtry = ggplot(prune_mtry_err, aes(x = mtry, color = metric, y = err)) + geom_line()
plot_nodesize = ggplot(prune_nodesize_err, aes(x = nodesize, color = metric, y = err)) + geom_line()
plot_mtry
plot_nodesize
# Generate the optimal forest
data_true = as.data.frame(data_illness[which(data_illness$is_illness == TRUE), ])
data_false = as.data.frame(data_illness[which(data_illness$is_illness == FALSE), ])
times = floor(table(data_illness$is_illness)[1] / table(data_illness$is_illness)[2])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data_opti = as.data.frame(rbind(data_true, data_false))
data_train = as.data.frame(subset(data_opti, select = -c(Alias, visit_id, precedes_illness)))
data_test = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness, precedes_illness)))
data_test_1 = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, precedes_illness)))
opti_forest_is = randomForest(is_illness ~ ., data = data_train, importance = TRUE, mtry = 100,
nodesize = 1000, replace = FALSE)
# 10-fold Cross-validation using optimal forest
opti_is = list()
opti_predict_is_class = list()
opti_predict_is_prob = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, precedes_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, precedes_illness)))
opti_is[[i]] = randomForest(is_illness ~ ., data = train, importance = TRUE, mtry = 100,
nodesize = 1000, replace = FALSE)
opti_predict_is_class[[i]] = predict(opti_is[[i]], test)
opti_predict_is_prob[[i]] = predict(opti_is[[i]], test, type = "prob")
}
save(opti_is, opti_predict_is_class, opti_predict_is_prob, file = "opti_forest_is.rdata")
# Get class and confidence predictions
opti_predict_is_class_c = opti_predict_is_class[[1]]
names(opti_predict_is_class_c) = NULL
opti_predict_is_class_c = as.factor(opti_predict_is_class_c)
for (i in 2:nfold) {
predict = opti_predict_is_class[[i]]
names(predict) = NULL
opti_predict_is_class_c = c(as.character(opti_predict_is_class_c), as.character(predict))
opti_predict_is_class_c = as.factor(opti_predict_is_class_c)
}
opti_predict_is_prob_c = as.data.frame(opti_predict_is_prob[[1]])
for (i in 2:nfold) {
predict = as.data.frame(opti_predict_is_prob[[i]])
opti_predict_is_prob_c = rbind(opti_predict_is_prob_c, predict)
}
# Check the optimal threshold for predictions
opti_predict_is_class_thre = list()
threshold = seq(0.1, 0.9, 0.05)
for (i in 1:length(threshold)) {
opti_predict_is_class_thre[[i]] = ifelse(opti_predict_is_prob_c[, 2] > threshold[i], TRUE, FALSE)
opti_predict_is_class_thre[[i]] = factor(opti_predict_is_class_thre[[i]], levels = c(FALSE, TRUE))
}
confusion_is = list()
confusion_is = lapply(opti_predict_is_class_thre, confusionMatrix, data_fold_test$is_illness,
positive = "TRUE")
threshold = as.data.frame(threshold)
threshold = threshold %>% mutate(sensitivity = map_dbl(confusion_is, get_sensitivity),
specificity = map_dbl(confusion_is, get_specificity),
ppv = map_dbl(confusion_is, get_ppv),
npv = map_dbl(confusion_is, get_npv),
f1 = map_dbl(confusion_is, get_f1))
threshold_err = threshold %>% gather('metric', 'err', sensitivity, specificity, ppv, npv, f1)
plot_threshold = ggplot(threshold_err, aes(x = threshold, color = metric, y = err)) + geom_line()
plot_threshold
# Generate the new class prediction using optimal threshold
opti_predict_is_class = list()
for (i in 1:nfold) {
prob = opti_predict_is_prob[[i]]
opti_predict_is_class[[i]] = ifelse(prob[, 2] > 0.375, TRUE, FALSE)
opti_predict_is_class[[i]] = factor(opti_predict_is_class[[i]], levels = c(FALSE, TRUE))
}
# Compare performance of each fold using confusion matrices
opti_conf = list()
for (i in 1:nfold) {
opti_conf[[i]] = confusionMatrix(opti_predict_is_class[[i]], data_fold[[i]]$is_illness, positive = "TRUE")
}
fold = as.data.frame(seq(1, 10, 1))
colnames(fold) = "fold"
fold = fold %>% mutate(test_sensitivity = map_dbl(opti_conf, get_sensitivity),
test_specificity = map_dbl(opti_conf, get_specificity),
test_ppv = map_dbl(opti_conf, get_ppv),
test_npv = map_dbl(opti_conf, get_npv),
test_f1 = map_dbl(opti_conf, get_f1))
# Generate ROC curve for each fold
pred_is = list()
perf_is_plot = list()
for (i in 1:nfold) {
predict = as.data.frame(opti_predict_is_prob[[i]])
pred_is[[i]] = prediction(predict[, 2], data_fold[[i]]$is_illness)
perf_is_plot[[i]] = performance(pred_is[[i]], "sens", "spec")
}
plot(perf_is_plot[[1]])
plot(perf_is_plot[[2]], add = TRUE, col = 2)
plot(perf_is_plot[[3]], add = TRUE, col = 3)
plot(perf_is_plot[[4]], add = TRUE, col = 4)
plot(perf_is_plot[[5]], add = TRUE, col = 5)
plot(perf_is_plot[[6]], add = TRUE, col = 6)
plot(perf_is_plot[[7]], add = TRUE, col = 7)
plot(perf_is_plot[[8]], add = TRUE, col = 8)
plot(perf_is_plot[[9]], add = TRUE, col = 9)
plot(perf_is_plot[[10]], add = TRUE, col = 10)
# Generate the overall confusion matrix and AUC
pred_is_c = prediction(opti_predict_is_prob_c[, 2], data_fold_test$is_illness)
perf_is_auc = performance(pred_is_c, measure = "auc")
perf_is_auc@y.values[[1]]
confusion_is = confusionMatrix(opti_predict_is_class_c, data_fold_test$is_illness, positive = "TRUE")
confusion_is
```
```{r random forest for precedes_illness}
# Oversample the data within each group to balance `precedes_illness`
over_sample_precedes = function(data) {
times = floor(table(data$precedes_illness)[1] / table(data$precedes_illness)[2])
data_true = as.data.frame(data[which(data$precedes_illness == TRUE), ])
data_false = as.data.frame(data[which(data$precedes_illness == FALSE), ])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data = as.data.frame(rbind(data_true, data_false))
return(data)
}
data_fold = lapply(data_fold, over_sample_precedes)
data_fold_test = data_fold[[1]]
for (i in 2:length(data_fold)) {
data_fold_test = rbind(data_fold_test, data_fold[[i]])
}
# Generate the grid for `mtry` and `nodesize`
hyper_grid = expand.grid(mtry = c(20, 60, 100), nodesize = c(50, 500, 1000))
# 10-fold Cross-validation
forest_precedes = list()
forest_precedes_predict = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, is_illness)))
for (l in 1:nrow(hyper_grid)) {
forest_precedes[[l]] = randomForest(is_precedes ~ ., data = train, importance = TRUE,
mtry = hyper_grid$mtry[i],
nodesize = hyper_grid$nodesize[i],
replace = FALSE)
}
trees_precedes_predict[[i]] = lapply(trees_precedes, predict, test)
}
# Combine the predictions by each forest
predict_forest = list()
predict_fold = forest_is_predict[[1]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = NULL
predict_forest[[j]] = as.factor(prediction)
}
for (i in 2:nfold) {
predict_fold = forest_is_predict[[i]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = names(predict_forest[[j]])
predict_forest[[j]] = c(as.character(predict_forest[[j]]), as.character(prediction))
predict_forest[[j]] = as.factor(predict_forest[[j]])
}
}
# Tuning parameters by confusion matrices
forest_precedes_conf = list()
forest_precedes_conf = lapply(predict_forest, confusionMatrix,
data_fold_test$precedes_illness, positive = "TRUE")
prune_precedes = hyper_grid %>%
mutate(test_sensitivity = map_dbl(forest_precedes_conf, get_sensitivity),
test_specificity = map_dbl(forest_precedes_conf, get_specificity),
test_precision = map_dbl(forest_precedes_conf, get_precision),
test_recall = map_dbl(forest_precedes_conf, get_recall),
test_f1 = map_dbl(forest_precedes_conf, get_f1))
prune_precedes = prune_precedes[order(prune_precedes$test_precision, decreasing = TRUE), ]
head(prune_precedes)
save(forest_precedes, forest_precedes_predict, forest_precedes_conf, prune_precedes,
file = "forest_precedes.rdata")
#load("forest_precedes.rdata")
prune_precedes_mtry = prune_precedes[which(prune_precedes$mtry == 60), ]
prune_precedes_nodesize = prune_precedes[which(prune_precedes$nodesize == 500), ]
prune_precedes_mtry_err = prune_precedes_mtry %>% gather('metric', 'err', test_sensitivity, test_specificity,
test_precision, test_recall, test_f1)
prune_precedes_nodesize_err = prune_precedes_nodesize %>% gather('metric', 'err', test_sensitivity,
test_specificity, test_precision,
test_recall, test_f1)
plot_mtry = ggplot(prune_precedes_mtry_err, aes(x = mtry, color = metric, y = err)) + geom_line()
plot_nodesize = ggplot(prune_precedes_nodesize_err, aes(x = nodesize, color = metric, y = err)) + geom_line()
plot_mtry
plot_nodesize
# Generate the optimal forest
data_true = as.data.frame(data_illness[which(data_illness$precedes_illness == TRUE), ])
data_false = as.data.frame(data_illness[which(data_illness$precedes_illness == FALSE), ])
times = floor(table(data_illness$precedes_illness)[1] / table(data_illness$precedes_illness)[2])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data_opti = as.data.frame(rbind(data_true, data_false))
data_train = as.data.frame(subset(data_opti, select = -c(Alias, visit_id, is_illness)))
data_test = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness, precedes_illness)))
data_test_1 = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness)))
opti_forest_precedes = randomForest(precedes_illness ~ ., data = data_train, importance = TRUE,
mtry = 20, nodesize = 100, replace = FALSE)
# 10-fold Cross-validation using optimal forest
opti_precedes = list()
opti_predict_precedes_class = list()
opti_predict_precedes_prob = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, precedes_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, precedes_illness)))
opti_precedes[[i]] = randomForest(precedes_illness ~ ., data = data_train, importance = TRUE,
mtry = 20,
nodesize = 100,
replace = FALSE)
opti_predict_precedes_class[[i]] = predict(opti_precedes[[i]], test)
opti_predict_precedes_prob[[i]] = predict(opti_precedes[[i]], test, type = "prob")
}
save(opti_precedes, opti_predict_precedes_class, opti_predict_precedes_prob,
file = "opti_forest_precedes.rdata")
#load("opti_forest_precedes.rdata")
# Get class and confidence predictions
opti_predict_precedes_class_c = opti_predict_precedes_class[[1]]
names(opti_predict_precedes_class_c) = NULL
opti_predict_precedes_class_c = as.factor(opti_predict_precedes_class_c)
for (i in 2:nfold) {
predict = opti_predict_precedes_class[[i]]
names(predict) = NULL
opti_predict_precedes_class_c = c(as.character(opti_predict_precedes_class_c), as.character(predict))
opti_predict_precedes_class_c = as.factor(opti_predict_precedes_class_c)
}
opti_predict_precedes_prob_c = as.data.frame(opti_predict_precedes_prob[[1]])
for (i in 2:nfold) {
predict = as.data.frame(opti_predict_precedes_prob[[i]])
opti_predict_precedes_prob_c = rbind(opti_predict_precedes_prob_c, predict)
}
# Check the optimal threshold for predictions
opti_predict_precedes_class_thre = list()
threshold = seq(0.1, 0.9, 0.05)
for (i in 1:length(threshold)) {
opti_predict_precedes_class_thre[[i]] = ifelse(opti_predict_precedes_prob_c[, 2] > threshold[i],
TRUE, FALSE)
opti_predict_precedes_class_thre[[i]] = factor(opti_predict_precedes_class_thre[[i]],
levels = c(FALSE, TRUE))
}
confusion_precedes = list()
confusion_precedes = lapply(opti_predict_precedes_class_thre, confusionMatrix, data_fold_test$precedes_illness,
positive = "TRUE")
threshold = as.data.frame(threshold)
threshold = threshold %>% mutate(sensitivity = map_dbl(confusion_precedes, get_sensitivity),
specificity = map_dbl(confusion_precedes, get_specificity),
ppv = map_dbl(confusion_precedes, get_ppv),
npv = map_dbl(confusion_precedes, get_npv),
f1 = map_dbl(confusion_precedes, get_f1))
threshold_err = threshold %>% gather('metric', 'err', sensitivity, specificity, ppv, npv, f1)
plot_threshold = ggplot(threshold_err, aes(x = threshold, color = metric, y = err)) + geom_line()
plot_threshold
# Generate the new class prediction using optimal threshold
opti_predict_precedes_class = list()
for (i in 1:nfold) {
prob = opti_predict_precedes_prob[[i]]
opti_predict_precedes_class[[i]] = ifelse(prob[, 2] > 0.625, TRUE, FALSE)
opti_predict_precedes_class[[i]] = factor(opti_predict_precedes_class[[i]], levels = c(FALSE, TRUE))
}
# Compare performance of each fold using confusion matrices
opti_conf = list()
for (i in 1:nfold) {
opti_conf[[i]] = confusionMatrix(opti_predict_precedes_class[[i]], data_fold[[i]]$precedes_illness, positive = "TRUE")
}
fold = as.data.frame(seq(1, 10, 1))
colnames(fold) = "fold"
fold = fold %>% mutate(test_sensitivity = map_dbl(opti_conf, get_sensitivity),
test_specificity = map_dbl(opti_conf, get_specificity),
test_ppv = map_dbl(opti_conf, get_ppv),
test_npv = map_dbl(opti_conf, get_npv),
test_f1 = map_dbl(opti_conf, get_f1))
# Generate ROC curve for each fold
pred_precedes = list()
perf_precedes_plot = list()
for (i in 1:nfold) {
predict = as.data.frame(opti_predict_precedes_prob[[i]])
pred_precedes[[i]] = prediction(predict[, 2], data_fold[[i]]$precedes_illness)
perf_precedes_plot[[i]] = performance(pred_precedes[[i]], "sens", "spec")
}
plot(perf_precedes_plot[[1]])
plot(perf_precedes_plot[[2]], add = TRUE, col = 2)
plot(perf_precedes_plot[[3]], add = TRUE, col = 3)
plot(perf_precedes_plot[[4]], add = TRUE, col = 4)
plot(perf_precedes_plot[[5]], add = TRUE, col = 5)
plot(perf_precedes_plot[[6]], add = TRUE, col = 6)
plot(perf_precedes_plot[[7]], add = TRUE, col = 7)
plot(perf_precedes_plot[[8]], add = TRUE, col = 8)
plot(perf_precedes_plot[[9]], add = TRUE, col = 9)
plot(perf_precedes_plot[[10]], add = TRUE, col = 10)
# Generate the overall confusion matrix and AUC
pred_precedes_c = prediction(opti_predict_precedes_prob_c[, 2], data_fold_test$precedes_illness)
perf_precedes_auc = performance(pred_precedes_c, measure = "auc")
perf_precedes_auc@y.values[[1]]
confusion_precedes = confusionMatrix(opti_predict_precedes_class_c, data_fold_test$precedes_illness,
positive = "TRUE")
confusion_precedes
```
<file_sep>/Code/FeatureSelection.R
---
title: "Feature Selection"
author: "<NAME>"
date: "12/13/2019"
output: html_document
---
```{r feature selection}
apply(data_illness[, c(4, 5, 10:25, 27:46, 48:105)], MARGIN = 2, table)
apply(data_illness[, c(6:9, 26, 47)], MARGIN = 2, sd)
# check correlation
data_cor = data_illness[, c(6:8, 26, 9, 47)]
cor(data_cor)
# collapse infrequent discrete classes
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 50] == 4) {
data_illness[i, 50] = 3
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 53] > 5) {
data_illness[i, 53] = 5
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 103] > 49) {
data_illness[i, 103] = 49
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 104] > 73) {
data_illness[i, 104] = 73
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 105] > 31) {
data_illness[i, 105] = 31
}
}
# duplicate subjects with infrequent binary category
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 55] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 15), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 58] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 5), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 63] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 10), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 64] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 5), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 68] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 10), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 70] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 5), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 71] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 5), ])
}
}
for (i in 1:nrow(data_illness)) {
if (data_illness[i, 91] == TRUE) {
data_illness = rbind(data_illness, data_illness[rep(i, 3), ])
}
}
# remove extremely unbalanced categorical variables
data_illness$`C. pneu` = NULL
data_illness$`MMR (dose 1)` = NULL
# remove highly correlated features
data_illness$birth.length = NULL
data_illness$birth.weights = NULL
data_illness$head.circumference = NULL
# save `ndata_illness`
save(data_illness, file = "ndata_illness.RData")
```
<file_sep>/Code/Preprocessing.R
---
title: "Preprocessing"
author: "<NAME>"
date: "12/13/2019"
output: html_document
---
```{r setup, warning = FALSE, message = FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(MASS)
library(tidyverse)
library(phytools)
library(zoo)
library(glmnet)
library(rpart)
library(rattle)
library(rpart.plot)
library(RColorBrewer)
library(ROCR)
library(partykit)
library(caret)
library(purrr)
library(randomForest)
```
```{r read in data, message = FALSE, warning = FALSE}
files = data_frame(files = list.files('train_360_DOL/', pattern = '*.tsv', full.names = TRUE)) %>%
mutate(names = str_match(files, '//([a-z12_]+)')[,2])
files = files %>% rowwise() %>%
mutate(data = list(read_tsv(files)), nrow = nrow(data), nfeature = ncol(data))
get_tbl = function(name) filter(files, names == name) %>% .$data %>% .[[1]]
# Read in 14 tables
base = get_tbl('base')
demo = get_tbl('demo')
fam = get_tbl('fam')
oxy = get_tbl('oxy')
preg = get_tbl('preg')
flowcytometry = get_tbl('flowcytometry')
fup1 = get_tbl('fup1')
fup2 = get_tbl('fup2')
illness_control = get_tbl('illness_control')
nas_microbiome = get_tbl('nas_microbiome')
rec_microbiome = get_tbl('rec_microbiome')
thr_microbiome = get_tbl('thr_microbiome')
tlda = get_tbl('tlda')
vaccines = get_tbl('vaccines')
#nas_rooted_tree = read.newick("nas_rooted_tree.nwk")
#rec_rooted_tree = read.newick("rec_rooted_tree.nwk")
```
```{r preprocess base, warning = FALSE}
# Preprocessing `base`, resulting in `base_new`
base = base[order(base$Alias), ]
base_new = base %>% select(Alias)
# Scale variables
base_new$birth.weights = (base$`Birth Weight (gms)` - mean(base$`Birth Weight (gms)`)) / sd(base$`Birth Weight (gms)`)
base_new$head.circumference = (base$`Head Circumference (cm)` - mean(base$`Head Circumference (cm)`)) / sd(base$`Head Circumference (cm)`)
base_new$birth.length = (base$`Birth Length (cm)` - mean(base$`Birth Length (cm)`)) / sd(base$`Birth Length (cm)`)
base_new$temp = (base$`Temp at first NICU admission (C)` - mean(base$`Temp at first NICU admission (C)`)) / sd(base$`Temp at first NICU admission (C)`)
base_new = base_new %>% mutate(apgar.1 = base$`APGAR at 1 min`)
base_new = base_new %>% mutate(apgar.5 = base$`APGAR at 5 min`)
# Combine variables about birth order
base_new$multiple = ifelse(base$`Multiple Birth` == "No", 0,
base$`Birth Order` / base$`Total # of Births`)
# Change to categorical variables
base_new$birth.location = as.factor(ifelse(base$`Birth Location` == "Born inside the study center", 1, 0))
base_new$stablization = as.factor(ifelse(base$`Stabilization Procedure Provided` == "Yes", 1, 0))
base_new$supo2 = as.factor(ifelse(is.na(base$`Supplemental O2`), 0, 1))
base_new$cpap = as.factor(ifelse(is.na(base$CPAP), 0, 1))
base_new$ventilation = as.factor(ifelse(is.na(base$`Non-invasive positive pressure ventilation with flow inflating or self inflating bag`), 0, 1))
base_new$tpiece = as.factor(ifelse(is.na(base$`T-Piece resuscitator`), 0, 1))
base_new$intubation = as.factor(ifelse(is.na(base$Intubation), 0, 1))
base_new$chest.compression = as.factor(ifelse(is.na(base$`Chest Compression`), 0, 1))
base_new$cardiac.drugs = as.factor(ifelse(is.na(base$`Cardiac drugs (Epinenphrine)`), 0, 1))
base_new$surfactant.admin = as.factor(ifelse(is.na(base$`Surfactant administration`), 0, 1))
base_new$prophylactic.indomethacin = as.factor(ifelse(base$`Prophylactic Indomethacin given within first 24 hours of life` == "Yes", 1, 0))
sum(is.na(base_new))
```
```{r preprocess demo, warning = FALSE}
# Preprocessing `demo`, resulting in `demo_new`
demo = demo[order(demo$Alias), ]
demo_new = demo %>% select(Alias)
# Change to categorical variables
demo_new$gender = as.factor(ifelse(demo$Gender == "Male", 1, 0))
demo_new = demo_new %>% mutate(birth.season = demo$`Birth Season`)
demo_new$birth.season = demo_new$birth.season %>% as.factor()
levels(demo_new$birth.season) = c(3, 1, 0, 2)
demo_new$birth.season = demo_new$birth.season %>% as.numeric()
# Scale variables
demo_new$gestational.age = demo$`GA at Birth (BLIS Calculated)` - 39
sum(is.na(demo_new))
```
```{r preprocess fam, warning = FALSE}
# Preprocessing `fam`, resulting in `fam_new`
fam = fam[order(fam$Alias), ]
fam_new = fam %>% select(Alias)
# Change to categorical variables
fam_new = fam_new %>% mutate(education = fam$`Mother Education`)
fam_new$education = fam_new$education %>% as.factor()
levels(fam_new$education) = c(1, 4, 5, 2, 0, 3, NA)
fam_new$education = fam_new$education %>% as.numeric()
# fill the unknown as means
for (i in 1:nrow(fam_new)) {
if (is.na(fam_new$education[i]) == TRUE) {
fam_new$education[i] = mean(fam_new$education, na.rm = TRUE)
}
}
sum(is.na(fam_new))
```
```{r preprocess oxy, warning = FALSE}
# Preprocessing `oxy`, resulting in `oxy_new`
oxy = oxy[order(oxy$Alias), ]
oxy_new = oxy %>% select(Alias)
# Change to categorical variables
for (i in 1:nrow(oxy)) {
if (oxy$`Auc O2exposure 7d`[i] == 0) {
oxy_new$auc[i] = 0
} else if (oxy$`Auc O2exposure 7d`[i] > 0 & oxy$`Auc O2exposure 7d`[i] <= 51) {
oxy_new$auc[i] = 1
} else if (oxy$`Auc O2exposure 7d`[i] > 51 & oxy$`Auc O2exposure 7d`[i] <= 100) {
oxy_new$auc[i] = 2
} else if (oxy$`Auc O2exposure 7d`[i] > 100 & oxy$`Auc O2exposure 7d`[i] <= 500) {
oxy_new$auc[i] = 3
} else if (oxy$`Auc O2exposure 7d`[i] > 500 & oxy$`Auc O2exposure 7d`[i] <= 1000) {
oxy_new$auc[i] = 4
} else if (oxy$`Auc O2exposure 7d`[i] > 1000 & oxy$`Auc O2exposure 7d`[i] <= 2000) {
oxy_new$auc[i] = 5
} else if (oxy$`Auc O2exposure 7d`[i] > 2000 & oxy$`Auc O2exposure 7d`[i] <= 4000) {
oxy_new$auc[i] = 6
} else {oxy_new$auc[i] = 7}
}
for (i in 1:nrow(oxy_new)) {
if ((oxy$`Auc O2exposure 14d`[i] - oxy$`Auc O2exposure 7d`[i]) > oxy$`Auc O2exposure 7d`[i]) {
oxy_new$auc[i] = oxy_new$auc[i] + 1
}
}
oxy_new$auc = as.factor(oxy_new$auc)
sum(is.na(oxy_new))
```
```{r preprocess preg and join, warning = FALSE}
# Preprocessing `preg`, resulting in `preg_new`
preg = preg[order(preg$Alias), ]
preg_new = preg %>% select(Alias)
# Change to categorical variables
# diabetes
for (i in 1:nrow(preg)) {
if (preg[i, 1] == "No") {
preg_new$diabetes[i] = 0
} else if(is.na(preg[i, 2]) == FALSE & preg[i, 2] == "Yes") {
preg_new$diabetes[i] = 1
} else if (is.na(preg[i, 2]) == TRUE) {
preg_new$diabetes[i] = NA
} else {preg_new$diabetes[i] = 2}
}
# fill the unknown as means
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$diabetes[i]) == TRUE) {
preg_new$diabetes[i] = mean(preg_new$diabetes, na.rm = TRUE)
}
}
# hypertension
for (i in 1:nrow(preg)) {
if (preg[i, 3] == "No") {
preg_new$hypertension[i] = 0
} else if(is.na(preg[i, 4]) == FALSE & preg[i, 4] == "Yes") {
preg_new$hypertension[i] = 1
} else if (is.na(preg[i, 4]) == TRUE) {
preg_new$hypertension[i] = NA
} else {preg_new$hypertension[i] = 2}
}
# fill the unknown as means
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$hypertension[i]) == TRUE) {
preg_new$hypertension[i] = mean(preg_new$hypertension, na.rm = TRUE)
}
}
# asthma
for (i in 1:nrow(preg)) {
if (preg[i, 5] == "No") {
preg_new$asthma[i] = 0
} else if(is.na(preg[i, 6]) == FALSE & preg[i, 6] == "Yes") {
preg_new$asthma[i] = 1
} else if (is.na(preg[i, 6]) == TRUE) {
preg_new$asthma[i] = NA
} else {preg_new$asthma[i] = 2}
}
# fill the unknown as means
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$asthma[i]) == TRUE) {
preg_new$asthma[i] = mean(preg_new$asthma, na.rm = TRUE)
}
}
# membrane rupture
for (i in 1:nrow(preg)) {
if (preg[i, 27] == "No") {
preg_new$rupture[i] = 0
} else if(is.na(preg[i, 28]) == FALSE & preg[i, 28] == "No") {
preg_new$rupture[i] = 1
} else if (is.na(preg[i, 28]) == TRUE) {
preg_new$rupture[i] = NA
} else {preg_new$rupture[i] = 2}
}
# fill the unknown as means
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$rupture[i]) == TRUE) {
preg_new$rupture[i] = mean(preg_new$rupture, na.rm = TRUE)
}
}
# placental pathology
for (i in 1:nrow(preg)) {
if (preg[i, 30] == "No") {
preg_new$placental.pathology[i] = 0
} else if(is.na(preg[i, 31]) == FALSE & preg[i, 31] == "No") {
preg_new$placental.pathology[i] = 1
} else if (is.na(preg[i, 31]) == TRUE) {
preg_new$placental.pathology[i] = NA
} else {preg_new$placental.pathology[i] = 2}
}
# fill the unknown as means
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$placental.pathology[i]) == TRUE) {
preg_new$placental.pathology[i] = mean(preg_new$placental.pathology, na.rm = TRUE)
}
}
# other binary variables
preg_new$other.respiratory.illness = as.factor(ifelse(preg[, 7] == "Yes", 1, 0))
preg_new$prolong.pregnancy = as.factor(ifelse(preg[, 9] == "Yes", 1, 0))
preg_new$mother.smoke = as.factor(ifelse(preg[, 19] == "Yes", 1, 0))
preg_new$other.smoke = as.factor(ifelse(preg[, 20] == "Yes", 1, 0))
preg_new$alcohol = as.factor(ifelse(preg[, 21] == "Yes", 1, 0))
preg_new$placental.abruption = as.factor(ifelse(preg[, 26] == "Yes", 1, 0))
preg_new$chorioamnionitis = as.factor(ifelse(preg[, 29] == "Yes", 1, 0))
preg_new$antibiotics = as.factor(ifelse(preg[, 32] == "Yes", 1, 0))
preg_new$corticosteroids = as.factor(ifelse(preg[, 38] == "Yes", 1, 0))
preg_new$magnesium.sulfate = as.factor(ifelse(preg[, 41] == "Yes", 1, 0))
preg_new$onset = as.factor(ifelse(preg[, 43] == "Yes", 0, 1))
preg_new$delivery = as.factor(ifelse(preg[, 44] == "Caesarean Section", 0, 1))
preg_new$preeclampsia = as.factor(ifelse(preg[, 43] == "Yes", 1, 0))
# Scale BMI
preg_new$bmi = as.numeric(unlist(preg[, 45]))
for (i in 1:nrow(preg_new)) {
if (is.na(preg_new$bmi[i]) == TRUE) {
preg_new$bmi[i] = mean(preg_new$bmi, na.rm = TRUE)
}
}
preg_new$bmi = (preg_new$bmi - mean(preg_new$bmi)) / sd(preg_new$bmi)
sum(is.na(oxy_new))
# Join first five dataset as `profiles`
profiles = full_join(base_new, demo_new, by = "Alias") %>% full_join(fam_new, by = "Alias") %>%
full_join(oxy_new, by = "Alias") %>% full_join(preg_new, by = "Alias")
sum(is.na(profiles))
```
```{r preprocess illness_control and join}
# Preprocessing `illness_control`, resulting in `illness_new`
illness_new = illness_control[,c(2,3,5,1,4)]
illness_new = illness_new[order(illness_new$Alias, illness_new$visit_id), ]
sum(is.na(illness_new))
# Join `profiles` to `illness_new`, result in `data_illness`
data_illness = left_join(illness_new, profiles, by = c("Alias"))
sum(is.na(data_illness))
```
```{r preprocess fup1 and join}
# Preprocessing `fup1`, resulting in `fup1_new`
fup1 = fup1[order(fup1$Alias, fup1$pCGA), ]
fup1_new = fup1 %>% select(Alias, pCGA)
# Change to categorical variables
fup1_new$receive.breast.milk = as.factor(ifelse(fup1[, 1] == "Yes", 1, 0))
fup1_new$non.milk.foods = as.factor(ifelse(fup1[, 5] == "Yes", 1, 0))
# Interpolate missing values
fup1_new = fup1_new %>% group_by(Alias) %>%
mutate(receive.breast.milk = ifelse(is.na(receive.breast.milk),
na.locf(fup1_new$receive.breast.milk,
fromLast = TRUE), receive.breast.milk))
fup1_new = fup1_new %>% group_by(Alias) %>%
mutate(non.milk.foods = ifelse(is.na(non.milk.foods),
na.locf(fup1_new$non.milk.foods, fromLast = TRUE),
non.milk.foods))
# Join `fup1_new` to `data_illness`
data_illness = left_join(data_illness, fup1_new, by = c("Alias", "pCGA"))
first_value = function(x) {x[1]}
data_illness = data_illness %>% group_by(Alias, visit_id, pCGA) %>% summarise_all(first_value)
data_illness = data_illness %>% group_by(Alias) %>%
mutate(receive.breast.milk = ifelse(is.na(receive.breast.milk),
na.locf(data_illness$receive.breast.milk,
fromLast = TRUE), receive.breast.milk))
data_illness = data_illness %>% group_by(Alias) %>%
mutate(non.milk.foods = ifelse(is.na(non.milk.foods),
na.locf(data_illness$non.milk.foods, fromLast = TRUE),
non.milk.foods))
sum(is.na(data_illness))
```
```{r preprocess fup2 and join, warning = FALSE}
# Preprocessing `fup2`, resulting in `fup2_new`
fup2 = fup2[order(fup2$Alias, fup2$pCGA), ]
fup2_new = fup2 %>% select(Alias, pCGA)
# Number of smokers at home
fup2_new = fup2_new %>% mutate(smoker = fup2$`How many smokers in home`)
for (i in 1:nrow(fup2_new)) {
if (is.na(fup2_new$smoker[i])) {
fup2_new$smoker[i] = 0
} else if (fup2[i, 3] == "Yes") {
fup2_new$smoker[i] = fup2_new$smoker[i] + 1
}
}
# Exposed to smoke at home
fup2_new = fup2_new %>% mutate(exposed.to.smoke = fup2$`Exposed to smoke at HOME`)
fup2_new$exposed.to.smoke = fup2_new$exposed.to.smoke %>% as.factor()
levels(fup2_new$exposed.to.smoke) = c(0, 1)
# heater, stove or fireplace
fup2_new = fup2_new %>% mutate(fire = fup2$`Kerosene heater, wood burning stove, or fireplace`)
fup2_new$fire = fup2_new$fire %>% as.factor()
levels(fup2_new$fire) = c(0, 1)
# Number of pets
fup2_new = fup2_new %>% mutate(pets = fup2$`How many pets`)
for (i in 1:nrow(fup2_new)) {
if (is.na(fup2_new$pets[i])) {
fup2_new$pets[i] = 0
} else if (fup2[i, 15] == "Yes") {
fup2_new$pets[i] = fup2_new$pets[i] - 1
}
}
# Interpolate missing values
fup2_new = fup2_new %>% group_by(Alias) %>%
mutate(fire = ifelse(is.na(fire), na.locf(fup2_new$fire, fromLast = TRUE), fire))
sum(is.na(fup2_new))
# Join `fup2_new` to `data_illness`
data_illness = left_join(data_illness, fup2_new, by = c("Alias", "pCGA"))
data_illness = data_illness %>% group_by(Alias) %>%
mutate(smoker = ifelse(is.na(smoker), na.locf(data_illness$smoker, fromLast = TRUE), smoker),
exposed.to.smoke = ifelse(is.na(exposed.to.smoke),
na.locf(data_illness$exposed.to.smoke, fromLast = TRUE),
exposed.to.smoke),
fire = ifelse(is.na(fire), na.locf(data_illness$fire, fromLast = TRUE), fire),
pets = ifelse(is.na(pets), na.locf(data_illness$pets, fromLast = TRUE), pets))
sum(is.na(data_illness))
```
```{r preprocess tlda and join}
# Preprocessing `tlda`, resulting in `tlda_new`
tlda_new = tlda %>% select(Target, Positive, Alias, visit_id) %>% spread(Target, Positive)
tlda_new = tlda_new[order(tlda_new$Alias, tlda_new$visit_id), ]
carry_forward = function(x) {
for(i in 1:(length(x)-1)) if(is.na(x[i])) x[i] = x[i + 1]
x
}
carry_forward_2 = function(x) {
for(i in 1:(length(x)-1)) if(is.na(x[i])) x[i] = x[i + 2]
x
}
carry_backward = function(x) {
for(i in seq_along(x)[-1]) if(is.na(x[i])) x[i] = x[i - 1]
x
}
tlda_new = tlda_new %>% group_by(Alias) %>% mutate_at(vars(Adeno:Urea), carry_backward)
sum(is.na(tlda_new))
# Join `tlda_new` to `data_illness`
data_illness = left_join(data_illness, tlda_new, by = c("Alias", "visit_id"))
data_illness = data_illness %>% group_by(Alias) %>% mutate_at(vars(Adeno:Urea), carry_backward) %>%
mutate_at(vars(Adeno:Urea), carry_forward) %>% mutate_at(vars(Adeno:Urea), carry_forward_2)
data_illness = data_illness %>% group_by(Alias) %>% mutate_at(vars(Adeno:Urea), carry_backward) %>%
mutate_at(vars(Adeno:Urea), carry_forward) %>% mutate_at(vars(Adeno:Urea), carry_forward_2)
sum(is.na(data_illness))
```
```{r preprocess vaccines and join, warning = FALSE}
# Preprocessing `vaccines`, resulting in `vaccines_new`
vaccines_new = vaccines %>% select(Alias, pCGA, Key, `Vaccination Type`)
vaccines_new$`Vaccination Type` = 1
vaccines_new = vaccines_new %>% spread(Key, `Vaccination Type`)
vaccines_new = vaccines_new[order(vaccines_new$Alias, vaccines_new$pCGA), ]
vaccines_new = vaccines_new %>% group_by(Alias) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_backward)
vaccines_new[is.na(vaccines_new)] = 0
sum(is.na(vaccines_new))
# Join `vaccines_new` to `data_illness`
data_illness = left_join(data_illness, vaccines_new, by = c("Alias", "pCGA"))
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_backward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward_2)
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_backward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward_2)
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_backward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), carry_forward_2)
# fill the unknown as most frequent result among same `pCGA`
input_mode = function(x) {
uniqx = unique(na.omit(x))
mode = uniqx[which.max(tabulate(match(x, uniqx)))]
for(i in seq_along(x)) if(is.na(x[i])) x[i] = mode
x
}
data_illness = data_illness %>% group_by(pCGA) %>%
mutate_at(vars(`DTaP (2 months)`:`RSV prophylaxis (1st dose)`), input_mode)
sum(is.na(data_illness))
```
```{r preprocess microbiome and join}
# Preprocessing three datasets regarding microbiome, resulting in `microbiome_new`
nas_microbiome = nas_microbiome[order(nas_microbiome$Alias, nas_microbiome$visit_id, nas_microbiome$pCGA), ]
nas_new = nas_microbiome %>% select(Alias, visit_id, pCGA)
nas_new$nas_microbiome = 0
for (i in 1:nrow(nas_microbiome)) {
nas_new$nas_microbiome[i] = sum(nas_microbiome[i, -c(1:5)] > 0)
}
rec_microbiome = rec_microbiome[order(rec_microbiome$Alias, rec_microbiome$visit_id, rec_microbiome$pCGA), ]
rec_new = rec_microbiome %>% select(Alias, visit_id, pCGA)
rec_new$rec_microbiome = 0
for (i in 1:nrow(rec_microbiome)) {
rec_new$rec_microbiome[i] = sum(rec_microbiome[i, -c(1:5)] > 0)
}
thr_microbiome = thr_microbiome[order(thr_microbiome$Alias, thr_microbiome$visit_id, thr_microbiome$pCGA), ]
thr_new = thr_microbiome %>% select(Alias, visit_id, pCGA)
thr_new$thr_microbiome = 0
for (i in 1:nrow(thr_microbiome)) {
thr_new$thr_microbiome[i] = sum(thr_microbiome[i, -c(1:5)] > 0)
}
microbiome_new = full_join(nas_new, rec_new, by = c("Alias", "visit_id", "pCGA"))
microbiome_new = full_join(microbiome_new, thr_new, by = c("Alias", "visit_id", "pCGA"))
microbiome_new = microbiome_new %>% group_by(Alias) %>%
mutate(nas_microbiome = ifelse(is.na(nas_microbiome),
na.locf(microbiome_new$nas_microbiome, fromLast = TRUE),
nas_microbiome)) %>%
mutate(rec_microbiome = ifelse(is.na(rec_microbiome),
na.locf(microbiome_new$rec_microbiome, fromLast = TRUE),
rec_microbiome)) %>%
mutate(thr_microbiome = ifelse(is.na(thr_microbiome),
na.locf(microbiome_new$thr_microbiome, fromLast = TRUE),
thr_microbiome))
sum(is.na(microbiome_new))
# Join `microbiome_new` to `data_illness`
data_illness = left_join(data_illness, microbiome_new, by = c("Alias", "visit_id", "pCGA"))
data_illness = data_illness %>% group_by(Alias, visit_id, pCGA) %>% summarise_all(first_value)
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_backward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward_2)
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_backward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward_2)
data_illness = data_illness %>% group_by(Alias) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_backward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward) %>%
mutate_at(vars(nas_microbiome:thr_microbiome), carry_forward_2)
# fill the unknown as means
for (i in 1:nrow(data_illness)) {
if (is.na(data_illness$nas_microbiome[i]) == TRUE) {
data_illness$nas_microbiome[i] = mean(data_illness$nas_microbiome, na.rm = TRUE)
}
if (is.na(data_illness$rec_microbiome[i]) == TRUE) {
data_illness$rec_microbiome[i] = mean(data_illness$rec_microbiome, na.rm = TRUE)
}
if (is.na(data_illness$thr_microbiome[i]) == TRUE) {
data_illness$thr_microbiome[i] = mean(data_illness$thr_microbiome, na.rm = TRUE)
}
}
sum(is.na(data_illness))
```
<file_sep>/Code/ClassificationTree.R
---
title: "Classification Tree"
author: "<NAME>"
date: "12/13/2019"
output: html_document
---
```{r classification tree for is_illness}
data_illness$is_illness = factor(data_illness$is_illness)
data_illness$precedes_illness = factor(data_illness$precedes_illness)
# Prepare 10-fold cross-validation blocked by Alias
nfold = 10
data_illness = data_illness %>% group_by(Alias)
data_illness$id = c()
data_illness$id = data_illness %>% group_indices(Alias)
size = floor(length(unique(data_illness$id)) / nfold)
set.seed(300)
fold_id = sample(1:length(unique(data_illness$id)), length(unique(data_illness$id)))
g1_id = fold_id[1:size]
g2_id = fold_id[(size + 1):(size * 2)]
g3_id = fold_id[(size*2 + 1):(size * 3)]
g4_id = fold_id[(size*3 + 1):(size * 4)]
g5_id = fold_id[(size*4 + 1):(size * 5)]
g6_id = fold_id[(size*5 + 1):(size * 6)]
g7_id = fold_id[(size*6 + 1):(size * 7)]
g8_id = fold_id[(size*7 + 1):(size * 8)]
g9_id = fold_id[(size*8 + 1):(size * 9)]
g10_id = fold_id[(size*9 + 1):length(fold_id)]
data_g1 = as.data.frame(data_illness[data_illness$id %in% g1_id, ])
data_g2 = as.data.frame(data_illness[data_illness$id %in% g2_id, ])
data_g3 = as.data.frame(data_illness[data_illness$id %in% g3_id, ])
data_g4 = as.data.frame(data_illness[data_illness$id %in% g4_id, ])
data_g5 = as.data.frame(data_illness[data_illness$id %in% g5_id, ])
data_g6 = as.data.frame(data_illness[data_illness$id %in% g6_id, ])
data_g7 = as.data.frame(data_illness[data_illness$id %in% g7_id, ])
data_g8 = as.data.frame(data_illness[data_illness$id %in% g8_id, ])
data_g9 = as.data.frame(data_illness[data_illness$id %in% g9_id, ])
data_g10 = as.data.frame(data_illness[data_illness$id %in% g10_id, ])
data_fold = list(data_g1, data_g2, data_g3, data_g4, data_g5, data_g6, data_g7,data_g8, data_g9,
data_g10)
# Oversample the data within each group to balance `is_illness`
over_sample = function(data) {
times = floor(table(data$is_illness)[1] / table(data$is_illness)[2])
data_true = as.data.frame(data[which(data$is_illness == TRUE), ])
data_false = as.data.frame(data[which(data$is_illness == FALSE), ])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data = as.data.frame(rbind(data_true, data_false))
return(data)
}
data_fold = lapply(data_fold, over_sample)
data_fold_test = data_fold[[1]]
for (i in 2:length(data_fold)) {
data_fold_test = rbind(data_fold_test, data_fold[[i]])
}
#prop.table(table(data_fold[[1]]$is_illness))
# Function to get sensitivity, specificity, precision and recall
get_sensitivity = function(x) {
sensitivity = x$byClass[1]
}
get_specificity = function(x) {
specificity = x$byClass[2]
}
get_ppv = function(x) {
ppv = x$byClass[3]
}
get_npv = function(x) {
npv = x$byClass[4]
}
get_f1 = function(x) {
recall = x$byClass[7]
}
# Set the grid of values of `minbucket` and `cp`
hyper_grid = expand.grid(minbucket = c(30, 100, 200, 300, 400, 900, 1200, 1500), cp = seq(0.01, 0.25, 0.02))
# 10-fold Cross-validation
trees_is = list()
trees_is_predict = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, precedes_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, precedes_illness)))
for (l in 1:nrow(hyper_grid)) {
trees_is[[l]] = rpart(is_illness ~ ., data = train,
control = list(minbucket = hyper_grid$minbucket[l],
maxdepth = 30, xval = 10, cp = hyper_grid$cp[l],
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
}
trees_is_predict[[i]] = lapply(trees_is, predict, test, type = "class")
}
# Combine the predictions by each tree
predict_tree = list()
predict_fold = trees_is_predict[[1]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = NULL
predict_tree[[j]] = as.factor(prediction)
}
for (i in 2:nfold) {
predict_fold = trees_is_predict[[i]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = names(predict_tree[[j]])
predict_tree[[j]] = c(as.character(predict_tree[[j]]), as.character(prediction))
predict_tree[[j]] = as.factor(predict_tree[[j]])
}
}
# Tune parameters by confusion matrices
trees_is_conf = list()
trees_is_conf = lapply(predict_tree, confusionMatrix, data_fold_test$is_illness, positive = "TRUE")
prune = hyper_grid %>%
mutate(test_sensitivity = map_dbl(trees_is_conf, get_sensitivity),
test_specificity = map_dbl(trees_is_conf, get_specificity),
test_ppv = map_dbl(trees_is_conf, get_ppv),
test_npv = map_dbl(trees_is_conf, get_npv),
test_f1 = map_dbl(trees_is_conf, get_f1))
prune = prune[order(prune$f1, decreasing = TRUE), ]
head(prune)
save(trees_is, trees_is_predict, trees_is_conf, prune, file = "trees_is.rdata")
prune_cp = prune[which(prune$minbucket == 50), ]
prune_minbucket = prune[which(prune$cp == 0.03), ]
prune_cp_err = prune_cp %>% gather('metric', 'err', test_sensitivity, test_specificity, test_ppv, test_npv,
test_f1)
prune_minbucket_err = prune_minbucket %>% gather('metric', 'err', test_sensitivity, test_specificity,
test_ppv, test_npv, test_f1)
plot_cp = ggplot(prune_cp_err, aes(x = cp, color = metric, y = err)) + geom_line()
plot_minbucket = ggplot(prune_minbucket_err, aes(x = minbucket, color = metric, y = err)) + geom_line()
plot_cp
plot_minbucket
# Grow the tree and plot using optimal `minsplit` and `cp`
data_true = as.data.frame(data_illness[which(data_illness$is_illness == TRUE), ])
data_false = as.data.frame(data_illness[which(data_illness$is_illness == FALSE), ])
times = floor(table(data_illness$is_illness)[1] / table(data_illness$is_illness)[2])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data_opti = as.data.frame(rbind(data_true, data_false))
data_train = as.data.frame(subset(data_opti, select = -c(Alias, visit_id, precedes_illness)))
data_test = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness, precedes_illness)))
data_test_1 = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, precedes_illness)))
opti_tree_is = rpart(is_illness ~ ., data = data_train,
control = list(minbucket = 50, maxdepth = 30, xval = 10, cp = 0.03,
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
rparty_tree_is = as.party(opti_tree_is)
rparty_tree_is
plot(rparty_tree_is, main = "Pruned Classification Tree for is_illness",
tp_args = list(text = "vertical", ymax = 1))
# Cross-validation by optimal tree
opti_predict_is_class = list()
opti_predict_is_prob = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, precedes_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, precedes_illness)))
trees_is[[i]] = rpart(is_illness ~ ., data = train,
control = list(minbucket = 50,
maxdepth = 30, xval = 10, cp = 0.03,
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
opti_predict_is_class[[i]] = predict(trees_is[[i]], test, type = "class")
opti_predict_is_prob[[i]] = predict(trees_is[[i]], test, type = "prob")
}
# Get class and confidence predictions
opti_predict_is_class_c = opti_predict_is_class[[1]]
names(opti_predict_is_class_c) = NULL
opti_predict_is_class_c = as.factor(opti_predict_is_class_c)
for (i in 2:nfold) {
predict = opti_predict_is_class[[i]]
names(predict) = NULL
opti_predict_is_class_c = c(as.character(opti_predict_is_class_c), as.character(predict))
opti_predict_is_class_c = as.factor(opti_predict_is_class_c)
}
opti_predict_is_prob_c = as.data.frame(opti_predict_is_prob[[1]])
for (i in 2:nfold) {
predict = as.data.frame(opti_predict_is_prob[[i]])
opti_predict_is_prob_c = rbind(opti_predict_is_prob_c, predict)
}
# Check the optimal threshold for predictions
opti_predict_is_class_thre = list()
threshold = seq(0.1, 0.9, 0.05)
for (i in 1:length(threshold)) {
opti_predict_is_class_thre[[i]] = ifelse(opti_predict_is_prob_c[, 2] > threshold[i], TRUE, FALSE)
opti_predict_is_class_thre[[i]] = factor(opti_predict_is_class_thre[[i]], levels = c(FALSE, TRUE))
}
confusion_is = list()
confusion_is = lapply(opti_predict_is_class_thre, confusionMatrix, data_fold_test$is_illness,
positive = "TRUE")
threshold = as.data.frame(threshold)
threshold = threshold %>% mutate(sensitivity = map_dbl(confusion_is, get_sensitivity),
specificity = map_dbl(confusion_is, get_specificity),
ppv = map_dbl(confusion_is, get_ppv),
npv = map_dbl(confusion_is, get_npv),
f1 = map_dbl(confusion_is, get_f1))
threshold_err = threshold %>% gather('metric', 'err', sensitivity, specificity, ppv, npv, f1)
plot_threshold = ggplot(threshold_err, aes(x = threshold, color = metric, y = err)) + geom_line()
plot_threshold
# Compare performance of each fold using confusion matrices
for (i in 1:nfold) {
opti_conf[[i]] = confusionMatrix(opti_predict_is_class[[i]], data_fold[[i]]$is_illness, positive = "TRUE")
}
fold = as.data.frame(seq(1, 10, 1))
colnames(fold) = "fold"
fold = fold %>% mutate(test_sensitivity = map_dbl(opti_conf, get_sensitivity),
test_specificity = map_dbl(opti_conf, get_specificity),
test_ppv = map_dbl(opti_conf, get_ppv),
test_npv = map_dbl(opti_conf, get_npv),
test_f1 = map_dbl(opti_conf, get_f1))
# Generate ROC curve for each fold
pred_is = list()
perf_is_plot = list()
for (i in 1:nfold) {
predict = as.data.frame(opti_predict_is_prob[[i]])
pred_is[[i]] = prediction(predict[, 2], data_fold[[i]]$is_illness)
perf_is_plot[[i]] = performance(pred_is[[i]], "sens", "spec")
}
plot(perf_is_plot[[1]])
plot(perf_is_plot[[2]], add = TRUE, col = 2)
plot(perf_is_plot[[3]], add = TRUE, col = 3)
plot(perf_is_plot[[4]], add = TRUE, col = 4)
plot(perf_is_plot[[5]], add = TRUE, col = 5)
plot(perf_is_plot[[6]], add = TRUE, col = 6)
plot(perf_is_plot[[7]], add = TRUE, col = 7)
plot(perf_is_plot[[8]], add = TRUE, col = 8)
plot(perf_is_plot[[9]], add = TRUE, col = 9)
plot(perf_is_plot[[10]], add = TRUE, col = 10)
# Generate the overall confusion matrix and AUC
pred_is_c = prediction(opti_predict_is_prob_c[, 2], data_fold_test$is_illness)
perf_is_auc = performance(pred_is_c, measure = "auc")
<EMAIL>[[1]]
confusion_is = confusionMatrix(opti_predict_is_class_c, data_fold_test$is_illness, positive = "TRUE")
confusion_is
```
```{r classification tree for precedes_illness}
# Oversample the data within each group to balance `precedes_illness`
over_sample_precedes = function(data) {
times = floor(table(data$precedes_illness)[1] / table(data$precedes_illness)[2])
data_true = as.data.frame(data[which(data$precedes_illness == TRUE), ])
data_false = as.data.frame(data[which(data$precedes_illness == FALSE), ])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data = as.data.frame(rbind(data_true, data_false))
return(data)
}
data_fold = lapply(data_fold, over_sample_precedes)
data_fold_test = data_fold[[1]]
for (i in 2:length(data_fold)) {
data_fold_test = rbind(data_fold_test, data_fold[[i]])
}
# Set the sequence of values of `minsplit` and `cp`
hyper_grid = expand.grid(minsplit = c(100, 300, 600, 900, 1200, 2700, 3600, 3700, 3800, 3900),
cp = seq(0.005, 0.11, 0.01))
# 10-fold Cross-validation
trees_precedes_predict = list()
trees_precedes = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, is_illness)))
for (l in 1:nrow(hyper_grid)) {
trees_precedes[[l]] = rpart(precedes_illness ~ ., data = train,
control = list(minsplit = hyper_grid$minsplit[l],
maxdepth = 30, xval = 10, cp = hyper_grid$cp[l],
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
}
trees_precedes_predict[[i]] = lapply(trees_precedes, predict, test, type = "class")
}
# Combine the predictions by each tree
predict_tree = list()
predict_fold = trees_precedes_predict[[1]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = NULL
predict_tree[[j]] = as.factor(prediction)
}
for (i in 2:nfold) {
predict_fold = trees_precedes_predict[[i]]
for (j in 1:nrow(hyper_grid)) {
prediction = predict_fold[[j]]
names(prediction) = names(predict_tree[[j]])
predict_tree[[j]] = c(as.character(predict_tree[[j]]), as.character(prediction))
predict_tree[[j]] = as.factor(predict_tree[[j]])
}
}
# Tuning parameters by confusion matrices
trees_precedes_conf = list()
trees_precedes_conf = lapply(predict_tree, confusionMatrix, data_fold_test$precedes_illness, positive = "TRUE")
prune_precedes = hyper_grid %>%
mutate(test_sensitivity = map_dbl(trees_precedes_conf, get_sensitivity),
test_specificity = map_dbl(trees_precedes_conf, get_specificity),
test_precision = map_dbl(trees_precedes_conf, get_precision),
test_recall = map_dbl(trees_precedes_conf, get_recall),
test_f1 = map_dbl(trees_precedes_conf, get_f1))
prune_precedes = prune_precedes[order(prune_precedes$test_precision, decreasing = TRUE), ]
head(prune_precedes)
save(trees_precedes, trees_precedes_predict, trees_precedes_conf, prune_precedes,
file = "trees_precedes.rdata")
prune_precedes_cp = prune_precedes[which(prune_precedes$minsplit == 300), ]
prune_precedes_minsplit = prune_precedes[which(prune_precedes$cp == 0.005), ]
prune_precedes_cp_err = prune_precedes_cp %>% gather('metric', 'err', test_sensitivity, test_specificity, test_precision, test_recall, test_f1)
prune_precedes_minsplit_err = prune_precedes_minsplit %>% gather('metric', 'err', test_sensitivity, test_specificity, test_precision, test_recall, test_f1)
plot_cp = ggplot(prune_precedes_cp_err, aes(x = cp, color = metric, y = err)) + geom_line()
plot_minsplit = ggplot(prune_precedes_minsplit_err, aes(x = minsplit, color = metric, y = err)) + geom_line()
plot_cp
plot_minsplit
# Prune the tree and plot using optimal `minsplit` and `cp`
data_true = as.data.frame(data_illness[which(data_illness$precedes_illness == TRUE), ])
data_false = as.data.frame(data_illness[which(data_illness$precedes_illness == FALSE), ])
times = floor(table(data_illness$precedes_illness)[1] / table(data_illness$precedes_illness)[2])
data_true = data_true[rep(seq_len(nrow(data_true)), each = times), ]
data_opti = as.data.frame(rbind(data_true, data_false))
data_train = as.data.frame(subset(data_opti, select = -c(Alias, visit_id, is_illness)))
data_test = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness, precedes_illness)))
data_test_1 = as.data.frame(subset(data_illness, select = -c(Alias, visit_id, is_illness)))
opti_tree_precedes = rpart(precedes_illness ~ ., data = data_train,
control = list(minsplit = 1200,
maxdepth = 30, xval = 10, cp = 0.005,
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
rparty_tree_precedes = as.party(opti_tree_precedes)
rparty_tree_precedes
plot(rparty_tree_precedes, tp_args = list(text = "vertical", ymax = 1),
main = "Pruned Classification Tree for precedes_illness")
plot(rparty_tree_precedes, tp_args = list(text = "vertical", ymax = 1))
# 10-fold Cross-validation using optimal tree
opti_predict_precedes_class = list()
opti_predict_precedes_prob = list()
trees_precedes = list()
for (i in 1:nfold) {
test = data_fold[[i]]
test_1 = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness)))
test = as.data.frame(subset(test, select = -c(Alias, visit_id, is_illness, precedes_illness)))
n_train = seq(1, nfold, 1)
n_train = n_train[n_train != i]
h = n_train[1]
train = data_fold[[h]]
for (j in 2:(length(n_train))) {
k = n_train[j]
train = as.data.frame(rbind(train, data_fold[[k]]))
}
train = as.data.frame(subset(train, select = -c(Alias, visit_id, is_illness)))
trees_precedes[[i]] = rpart(precedes_illness ~ ., data = train,
control = list(minsplit = 1200,
maxdepth = 30, xval = 10, cp = 0.005,
parms = list(loss = matrix(c(0, 1, 3, 0), nrow = 2))))
opti_predict_precedes_class[[i]] = predict(trees_precedes[[i]], test, type = "class")
opti_predict_precedes_prob[[i]] = predict(trees_precedes[[i]], test, type = "prob")
}
# Get class and confidence predictions
opti_predict_precedes_class_c = opti_predict_precedes_class[[1]]
names(opti_predict_precedes_class_c) = NULL
opti_predict_precedes_class_c = as.factor(opti_predict_precedes_class_c)
for (i in 2:nfold) {
predict = opti_predict_precedes_class[[i]]
names(predict) = NULL
opti_predict_precedes_class_c = c(as.character(opti_predict_precedes_class_c), as.character(predict))
opti_predict_precedes_class_c = as.factor(opti_predict_precedes_class_c)
}
opti_predict_precedes_prob_c = as.data.frame(opti_predict_precedes_prob[[1]])
for (i in 2:nfold) {
predict = as.data.frame(opti_predict_precedes_prob[[i]])
opti_predict_precedes_prob_c = rbind(opti_predict_precedes_prob_c, predict)
}
# Check the optimal threshold for predictions
opti_predict_precedes_class_thre = list()
threshold = seq(0.1, 0.9, 0.05)
for (i in 1:length(threshold)) {
opti_predict_precedes_class_thre[[i]] = ifelse(opti_predict_precedes_prob_c[, 2] > threshold[i], TRUE, FALSE)
opti_predict_precedes_class_thre[[i]] = factor(opti_predict_precedes_class_thre[[i]],
levels = c(FALSE, TRUE))
}
confusion_precedes = list()
confusion_precedes = lapply(opti_predict_precedes_class_thre, confusionMatrix,
data_fold_test$precedes_illness, positive = "TRUE")
threshold = as.data.frame(threshold)
threshold = threshold %>% mutate(sensitivity = map_dbl(confusion_precedes, get_sensitivity),
specificity = map_dbl(confusion_precedes, get_specificity),
ppv = map_dbl(confusion_precedes, get_ppv),
npv = map_dbl(confusion_precedes, get_npv),
f1 = map_dbl(confusion_precedes, get_f1))
threshold_err = threshold %>% gather('metric', 'err', sensitivity, specificity, ppv, npv, f1)
plot_threshold = ggplot(threshold_err, aes(x = threshold, color = metric, y = err)) + geom_line()
plot_threshold
# Generate the new class prediction using optimal threshold
opti_predict_precedes_class = list()
for (i in 1:nfold) {
prob = opti_predict_is_prob[[i]]
opti_predict_is_class[[i]] = ifelse(prob[, 2] > 0.65, TRUE, FALSE)
opti_predict_is_class[[i]] = factor(opti_predict_is_class[[i]], levels = c(FALSE, TRUE))
}
# Compare performance of each fold using confusion matrices
opti_conf = list()
for (i in 1:nfold) {
opti_conf[[i]] = confusionMatrix(opti_predict_precedes_class[[i]], data_fold[[i]]$precedes_illness,
positive = "TRUE")
}
fold = as.data.frame(seq(1, 10, 1))
colnames(fold) = "fold"
fold = fold %>% mutate(test_sensitivity = map_dbl(opti_conf, get_sensitivity),
test_specificity = map_dbl(opti_conf, get_specificity),
test_ppv = map_dbl(opti_conf, get_ppv),
test_npv = map_dbl(opti_conf, get_npv),
test_f1 = map_dbl(opti_conf, get_f1))
# Generate ROC curve for each fold
pred_precedes = list()
perf_precedes_plot = list()
for (i in 1:nfold) {
predict = as.data.frame(opti_predict_precedes_prob[[i]])
pred_precedes[[i]] = prediction(predict[, 2], data_fold[[i]]$precedes_illness)
perf_precedes_plot[[i]] = performance(pred_precedes[[i]], "sens", "spec")
}
plot(perf_precedes_plot[[1]])
plot(perf_precedes_plot[[2]], add = TRUE, col = 2)
plot(perf_precedes_plot[[3]], add = TRUE, col = 3)
plot(perf_precedes_plot[[4]], add = TRUE, col = 4)
plot(perf_precedes_plot[[5]], add = TRUE, col = 5)
plot(perf_precedes_plot[[6]], add = TRUE, col = 6)
plot(perf_precedes_plot[[7]], add = TRUE, col = 7)
plot(perf_precedes_plot[[8]], add = TRUE, col = 8)
plot(perf_precedes_plot[[9]], add = TRUE, col = 9)
plot(perf_precedes_plot[[10]], add = TRUE, col = 10)
# Generate the overall confusion matrix and AUC
pred_precedes_c = prediction(opti_predict_precedes_prob_c[, 2], data_fold_test$precedes_illness)
perf_precedes_auc = performance(pred_precedes_c, measure = "auc")
perf_precedes_<EMAIL>.values[[1]]
confusion_precedes = confusionMatrix(opti_predict_precedes_class_c, data_fold_test$precedes_illness,
positive = "TRUE")
confusion_precedes
```
| 4501c53ff54c015e1af99f665728c3da19c3b644 | [
"Markdown",
"R"
] | 5 | Markdown | zhirou-zhou/respiratory-illness-project | 2732ca800074250f888837696baf8547dc422d0c | 367d36396e34c1acc2a2e535c75015d0c16611f7 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "btree.h"
#define T 3
#define TRUE 1
#define FALSE 0
struct btree
{
int fd; //file descriptor do ficheiro onde se encontra a b-tree
struct node *root; //raíz da b-tree
int size; //tamanho da btree
};
struct no *no_novo()
{
struct no *no = malloc(sizeof(struct node));
no->n = 0;
no->leaf = TRUE;
return no;
}
struct btree *btree_nova()
{
struct btree *bt = malloc(sizeof(struct btree));
struct no *no = new_no();
node->leaf = TRUE;
bt->root = no;
bt->size = 1;
return bt;
}
struct btree *open_btree()
{
//int status;
struct btree *bt = btree_nova();
bt->fd = open("novo.dat", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
//printf("file descriptor: %d\n", bt->fd);
if (bt->fd == -1)
{
//free para limpar mem
perror("cant open or create file");
return NULL;
}
/*
status = read_root(bt);
//printf("Estou aqui status: %d\n", status);
if (status == -1)
{
free
perror("Cant read file");
return NULL;
}
if (status == 0)
{
bt->root.head = 0;
bt->root.used = 0; esta parte vai para o disck write e disk read
status = write_root(bt);
//printf("E aqui!\n");
if (status == -1)
{
perror("Cant write file");
return NULL;
}
else { //printf("TA tudo bem\n") };
}
*/
return bt;
}
/*
void split_child(struct btree *bt, struct node *node, int index, int nodeIndex)
{
struct node *childNode = disk_read(bt, node->child[index]);
struct node *newNode = new_node();
bt->size++;
newNode->leaf = childNode->leaf;
newNode->n = T-1;
for (int j = 0; j < T-1; j++)
strcpy(newNode->element[j].word, childNode->element[j + T].word);
if (childNode->leaf == FALSE)
{
for (int j = 0; j < T; j++)
newNode->child[j] = childNode->child[j + T];
}
childNode->n = T - 1;
for (int j = node->n; j >= index+1; j--)
node->child[j + 1] = node->child[j];
node->child[index + 1] = bt->size; //size corresponde à localização do newNode, uma vez que foi o ultimo nó criado;
for (int j = node->n - 1; j >= index; j--)
strcpy(node->element[j + 1].word, node->element[j].word);
strcpy(node->element[index].word, childNode->element[T].word);
node->n++;
//printf("\n3\n");
disk_write(bt, childNode, node->child[index]);
//free(childNode);
//printf("\n2\n");
disk_write(bt, newNode, node->child[index + 1]);
//free(newNode);
//printf("\n1\n");
disk_write(bt, node, nodeIndex);
//free(node);
free(newNode);
free(childNode);
}
*/
void btree_insert(struct btree *bt, char *word)
{
struct node *root = bt->root;
//printf("ola tou aqui\n");
if (root->n == 2*T - 1) //verifica se a raíz está cheia
{
struct node *newNode = new_node();
newNode->leaf = FALSE;
newNode->n = 0;
newNode->child[0] = bt->rootPos; //atribui a pos da raiz anterior oa filho da nova raiz
free(root);
bt->root = newNode;
bt->size++; //incrementa o tamanho da btree
bt->rootPos = bt->size; //atribui a nova pos da raíz
disk_write(bt, newNode, bt->rootPos);
//free(newNode);
//printf("\nraiz cheia\n");
split_child(bt, bt->root, 0, bt->rootPos);
insert_nonfull(bt, bt->root, word, bt->rootPos);
//free(newNode);
}
else {
//printf("\nraiz não cheia\n");
insert_nonfull(bt, root, word, bt->rootPos);
}
//free(root);
}
int pesquisa(btree *t, int v)
{
int i;
for (i=0; i < t->n; i++) {
if (t->chave[i] == v) {
return 1;
}
else if (t->chave[i] > v) {
break;
}
}
if (t->folha) return 0;
else return pesquisa(t->filho[i], v);
}
<file_sep>#include "btree.h"
int main()
{
struct btree *bt = open_btree();
size_t len = 0;
ssize_t read;
char *buf;
char *res;
while ((read = getline(&buf, &len, stdin)) != -1)
{
res = strtok(buf,"\n");
btree_insere(bt, res);
}
close(bt->fd);
free(bt);
//struct btree *b = malloc(sizeof( struct btree));
/*bt->fd = open("words_en.txt",O_RDONLY);
FILE *fp = fopen("words_en.txt","r");
while ((read = getline(&buf, &len, fp)) != -1)
{
res = strtok(buf,"\n");
// printf("%d\n", res[strlen(res)+1]);
//strcat(res,"\0");
}
fclose(fp);
free(b);
int i = 0;
while(fgets(buf,sizeof(buf),fp)){
//getline( &buf, &len, fp );
//printf("%s\n",buf );
btree_insere(bt,buf);
//printf("Y\n");
}
*/
//btree_close(bt);
return 0;
}
<file_sep># Data-Structure-and-Algorithms-2<file_sep>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define T 3
#define MAX_STR_LENGTH 28
#define TRUE 1
#define FALSE 0
struct element
{
char word[MAX_STR_LENGTH];
};
struct no
{
int n;
struct element element[2*T-1];
int child[2*T];
int leaf;
};
struct btree
{
int fd;
struct no *root;
int size;
};
no *no_novo();
btree *btree_nova();
btree *open_btree();
void btree_insere();
void btree_destroy();
int btree_existe();
<file_sep>int TrieIsMember(trieADT trie, char keys[])
{
/* Start at the top level. */
trieNodeT *level = trie->root;
/* Start at beginning of key. */
int i = 0;
for (;;) {
trieNodeT *found = NULL;
trieNodeT *curr;
for (curr = level; curr != NULL; curr = curr->next) {
/*
* Want a node at this level to match
* the current character in the key.
*/
if (curr->key == keys[i]) {
found = curr;
break;
}
}
/*
* If either no nodes at this level or none
* with next character in key, then key not
* present.
*/
if (found == NULL)
return 0;
/* If we matched end of key, it's there! */
if (keys[i] == '\0')
return 1;
/* Go to next level. */
level = found->children;
/* Advance in string key. */
i++;
}
}
| fad4a0254cd8ba3aaaf54a569c9e347f01c31a9c | [
"Markdown",
"C"
] | 5 | C | raquigomes/Data-Structure-and-Algorithms-2 | cfe2a7f37c5e748714f355042c47ea352da5fce0 | ac7b9f5ea915542c73ff9a851dd50c0b8d754f8a |
refs/heads/master | <repo_name>vsemionov/wordbase<file_sep>/src/wordbase/master.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import socket
import signal
import errno
import logging
import core
_sock = None
logger = None
def _sigterm_handler(signum, frame):
logger.info("caught SIGTERM; terminating")
sys.exit()
def _accept_connections(sock, timeout, mp):
suppress_eintr = mp.is_subproc and hasattr(signal, "siginterrupt") and hasattr(signal, "SIGCHLD")
logger.info("waiting for connections")
while True:
try:
if suppress_eintr: signal.siginterrupt(signal.SIGCHLD, True)
conn, addr = sock.accept()
if suppress_eintr: signal.siginterrupt(signal.SIGCHLD, False)
except IOError as ioe:
if ioe.errno == errno.EINTR: continue
else: raise
host, port = addr
logger.debug("accepted connection from address %s:%d", host, port)
conn.settimeout(timeout)
mp.process(core.process_session, conn, addr)
def init(address, backlog):
global logger
logger = logging.getLogger(__name__)
logger.info("server starting")
signal.signal(signal.SIGTERM, _sigterm_handler)
global _sock
_sock = socket.socket()
_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
_sock.bind(address)
_sock.listen(backlog)
host, port = address
logger.info("listening at address %s:%d", host, port)
def run(timeout, mp):
pid = os.getpid()
try:
_accept_connections(_sock, timeout, mp)
finally:
if os.getpid() == pid:
logger.info("server stopped")
<file_sep>/src/wordbase/util/srvmon.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import threading
import itertools
import socket
import time
import random
import logging
logger = None
_enabled = False
_interval = 0
_timeout = 0
def configure(config):
global _enabled, _interval, _timeout
_enabled = config.getboolean("enable", True)
_interval = config.getint("interval", 1)
_timeout = config.getint("timeout", 5)
if not _timeout:
raise ValueError("invalid srvmon timeout value")
global logger
logger = logging.getLogger(__name__)
def _log_status(address, status):
host, port = address
if status:
logger.info("server {}:{} is up".format(host, port))
else:
logger.warning("server {}:{} is down".format(host, port))
class _HeartbeatThread(threading.Thread):
def __init__(self, statuses, index, address, timeout):
super().__init__()
self.daemon = True
self._statuses = statuses
self._index = index
self._address = address
self._timeout = timeout
def run(self):
init_sleep = random.random() * 1.0
time.sleep(init_sleep)
while True:
try:
sock = socket.create_connection(self._address, self._timeout)
sock.close()
status = True
except socket.error:
status = False
except Exception:
logger.exception("unhandled exception; heartbeat thread terminating")
return
if self._statuses[self._index] != status:
# ignoring the race condition here, because it is not important
_log_status(self._address, status)
self._statuses[self._index] = status
time.sleep(_interval)
class ServerMonitor():
def __init__(self, servers, timeout):
timeout = timeout or _timeout
self._servers = list(servers)
self._statuses = [True for server in servers]
if not _enabled:
return
self._threads = [_HeartbeatThread(self._statuses, index, server, timeout) for (index, server) in enumerate(servers)]
for thread in self._threads:
thread.start()
def get_server_index(self, key):
key_hash = hash(key)
server_index = key_hash % len(self._servers)
if not self._statuses[server_index]:
compressor = itertools.compress(self._servers, self._statuses)
avail_list = list(compressor)
navail = len(avail_list)
if navail == 0:
return None
avail_index = key_hash % navail
server = avail_list[avail_index]
server_index = self._servers.index(server)
return server_index
def notify_server_down(self, index):
if not _enabled:
return
if self._statuses[index]:
_log_status(self._servers[index], False)
self._statuses[index] = False
<file_sep>/src/tools/dict2pgsql.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import re
import pgutil
script_name = os.path.basename(__file__)
def usage():
print("Usage: {} [-f conf_file] [-o db_order] name index_file dict_file".format(script_name), file=sys.stderr)
print("Imports a dict dictionary into pgsql.", file=sys.stderr)
def decode(encoded):
s = encoded.rstrip('=')
num = 0
cur = 0
for ch in s:
c = ord(ch)
if ord('A') <= c <= ord('Z'):
cur = c - ord('A')
elif ord('a') <= c <= ord('z'):
cur = c - ord('a') + 26
elif ord('0') <= c <= ord('9'):
cur = c - ord('0') + 52
elif ch == '+':
cur = 62
elif ch == '/':
cur = 63
else:
raise ValueError("invalid encoding")
num = (num * 64) + cur
return num
def read_def(f, offset, size):
f.seek(offset)
raw_def = bytes()
while len(raw_def) < size:
raw_def += f.read(size - len(raw_def))
definition = raw_def.decode('utf-8')
return definition.replace('\r', "")
def is_special(word):
return word.startswith("00-database-")
options, (name, index_file, dict_file) = pgutil.get_pgsql_params("o:", 3, 3, usage)
db_order = options.get("-o")
if db_order is not None:
db_order = int(db_order)
short_desc = None
info = None
defs = []
with open(index_file, encoding="utf-8") as index:
with open(dict_file, "rb") as data:
for entry in index:
word, offset, size = entry.strip().split('\t')
offset = decode(offset)
size = decode(size)
definition = read_def(data, offset, size)
if is_special(word):
if word == "00-database-short" and short_desc == None:
short_desc = re.sub(r"\A(\s*00-database-short)?\s*(.*?)\s*$.*\Z", r"\2", definition, flags=re.MULTILINE|re.DOTALL)
elif word == "00-database-info" and info == None:
info = re.sub(r"\A(\s*00-database-info)?\s*^(.*?)\s*\Z", r"\2", definition, flags=re.MULTILINE|re.DOTALL)
elif word == "00-database-8bit-new":
print("8-bit encoding is not supported")
sys.exit(1)
else:
continue
else:
defs.append((word, definition))
pgutil.process_pgsql_task(pgutil.import_task, db_order, name, short_desc, info, defs)
<file_sep>/src/tools/virt_pgsql.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the virt_name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import pgutil
insert_dictionary = "INSERT INTO {}.dictionaries (dict_id, db_order, name, short_desc, info) " \
"VALUES (NULL, %s, %s, %s, %s);"
select_virt_id = "SELECT virt_id FROM {}.dictionaries WHERE name = %s;"
prepare_insert_virtual_dictionary = "PREPARE insert_virtual_dictionary(VARCHAR) AS " \
"INSERT INTO {0}.virtual_dictionaries (virt_id, dict_id) " \
"VALUES (%s, (" \
"SELECT dict_id FROM {0}.dictionaries WHERE name = $1)" \
");"
execute_insert_virtual_dictionary = "EXECUTE insert_virtual_dictionary(%s);"
script_name = os.path.basename(__file__)
def usage():
print("Usage: {} [-f conf_file] [-o db_order] [-i info_file] virt_name short_desc dict_name dict_name [...]", file=sys.stderr)
print("Adds virtual dictionaries in pgsql.", file=sys.stderr)
def add_vdict(cur, schema, db_order, virt_name, short_desc, info, dict_names):
cur.execute(insert_dictionary.format(schema), (db_order, virt_name, short_desc, info))
cur.execute(select_virt_id.format(schema), (virt_name, ))
virt_id = cur.fetchone()[0]
cur.execute(prepare_insert_virtual_dictionary.format(schema), (virt_id, ))
for dict_name in dict_names:
cur.execute(execute_insert_virtual_dictionary, (dict_name, ))
options, args = pgutil.get_pgsql_params("o:i:", 4, None, usage)
db_order = options.get("-o")
if db_order is not None:
db_order = int(db_order)
info_file = options.get("-i")
virt_name, short_desc, *dict_names = args
if info_file is not None:
with open(info_file, encoding="utf-8") as f:
info = f.read()
else:
info = None
pgutil.process_pgsql_task(add_vdict, db_order, virt_name, short_desc, info, dict_names)
<file_sep>/src/wordbase/match.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import string
import collections
import functools
import itertools
class InvalidStrategyError(ValueError):
pass
_no_punctuation = {ord(c): None for c in string.punctuation}
def _preprocess(word):
return ' '.join(word.translate(_no_punctuation).split()).lower()
def _match_exact(word, headword):
return headword == word
def _match_prefix(word, headword):
return headword.startswith(word)
_strategies = collections.OrderedDict((
("exact", ("Match headwords exactly", _match_exact)),
("prefix", ("Match prefixes", _match_prefix)),
))
_default_strategy = "prefix"
def preprocessed(headwords):
preprocessor = map(_preprocess, headwords)
return list(preprocessor)
def _filter_words(test, word, headwords, preprocessed):
word = _preprocess(word)
matcher = functools.partial(test, word)
selectors = map(matcher, preprocessed)
matches = itertools.compress(headwords, selectors)
return list(matches)
def get_filter(strategy=None):
if strategy is None:
strategy = _default_strategy
try:
strat = _strategies[strategy]
except KeyError:
raise InvalidStrategyError("invalid strategy: {}".format(strategy))
desc, test = strat
del desc
word_filter = functools.partial(_filter_words, test)
return word_filter
def get_strategies():
func = None
func = func
strats = collections.OrderedDict([(name, desc) for name, (desc, func) in _strategies.items()])
return strats
def configure(config):
strategies = config.get("strategies", "")
if strategies:
parts = strategies.split(':')
default, strats = parts
global _strategies, _default_strategy
user_strats = collections.OrderedDict()
for strat in strats.split(','):
name = strat.strip()
if name:
if name not in _strategies:
raise ValueError("unsupported strategy: {}".format(name))
user_strats[name] = _strategies[name]
_strategies = user_strats
default = default.strip()
if default not in _strategies:
raise ValueError("default strategy not in list of advertised strategies")
_default_strategy = default
<file_sep>/src/wordbase/net.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import io
import logging
import debug
import log
DICT_EOL = '\r\n'
logger = None
class NetworkError(IOError):
pass
def init():
global logger
logger = logging.getLogger(__name__)
def net_exc(func):
def wrap_net_exc(*args, **kwargs):
try:
return func(*args, **kwargs)
except (IOError, EOFError, UnicodeDecodeError, BufferError) as ex:
exc_info = sys.exc_info() if debug.enabled else None
logger.error(ex, exc_info=exc_info)
raise NetworkError(ex)
return wrap_net_exc
class Connection:
def __init__(self, sock):
self._sio = sock.makefile(mode="rw", encoding="utf-8", newline='')
@net_exc
def read_line(self):
"""reads a line of input
The trailing EOL is stripped.
throws socket.timeout, EOFError, BufferError
"""
buff = io.StringIO(newline='\n')
count = 0
have_cr = False
while count < 1024:
ch = self._sio.read(1)
if not ch:
raise EOFError("connection closed by client")
buff.write(ch)
count += 1
if ch == '\n' and have_cr:
line = buff.getvalue()[:-2]
log.trace_client(line)
return line
have_cr = ch == '\r'
else:
raise BufferError("maximum command line length exceeded by client")
@staticmethod
def _split_line(line):
l = len(line)
i = 0
while i < l:
n, pre = (1022, '') if line[i] != '.' else (1021, '.')
chunk = ''.join((pre, line[i:i+n]))
i += n
yield chunk
else:
if l == 0:
yield line
@classmethod
def _trunc_line(cls, line):
return next(cls._split_line(line))
def _write(self, line):
data = ''.join((line, DICT_EOL))
self._sio.write(data)
self._sio.flush()
log.trace_server(line)
@net_exc
def write_line(self, line, split=True):
"""writes a line of output
The line argument should not end with an EOL.
The first leading '.' char is doubled.
If split is True, lines with above-maximum length are split to multiple lines.
If split is False, lines with above-maximum length are truncated.
"""
if split:
for subline in self.__class__._split_line(line):
self._write(subline)
else:
self._write(self.__class__._trunc_line(line))
@net_exc
def write_status(self, code, message):
line = "{:03d} {:s}".format(code, message)
self.write_line(line, split=False)
@net_exc
def write_text_end(self):
self._write('.')
@net_exc
def write_text(self, lines):
for line in lines:
self.write_line(line)
self.write_text_end()
@net_exc
def close(self):
self._sio.close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
<file_sep>/src/wordbase/core.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import socket
import logging
import random
import modules
import net
import cmdparser
import db
import cache
import handlers
logger = None
_fqdn = ""
_server_string = ""
_domain = ""
def _send_banner(conn):
local = "{}.{}".format(random.randint(0, 9999), random.randint(0, 9999))
msg_id = "<{}@{}>".format(local, _domain)
conn.write_status(220, "{} {} {}".format(_fqdn, _server_string, msg_id))
def _session(conn):
try:
with modules.db().Backend() as backend, modules.cache().Cache() as cacher:
_send_banner(conn)
end = False
while not end:
line = conn.read_line()
correct, command = cmdparser.parse_command(line)
if correct:
end = handlers.handle_command(conn, backend, cacher, command)
else:
handlers.handle_syntax_error(conn, command)
except net.NetworkError:
pass
except (db.BackendError, cache.CacheError):
conn.write_status(420, "Server temporarily unavailable")
except Exception:
logger.exception("unexpected error")
def configure(config):
global _fqdn, _server_string, _domain
_fqdn = socket.getfqdn()
_server_string = config.get("server", "wordbase")
_domain = config.get("domain", "example.com")
global logger
logger = logging.getLogger(__name__)
net.init()
cmdparser.init()
info = config.get("info", "")
handlers.configure(_server_string, info)
def process_session(sock, addr):
with sock, net.Connection(sock) as conn:
host, port = addr
logger.info("session started from address %s:%d", host, port)
try:
_session(conn)
finally:
logger.info("session ended")
logger.debug("closing client connection")
<file_sep>/src/wordbase/cache/redis.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import logging
import redis
import debug
import cache
import util.srvmon
logger = None
_servers = []
_timeout = 0
_ttl = 0
_monitor = None
def _init_monitor():
servers = [(host, port) for (host, port, db, password) in _servers]
global _monitor
_monitor = util.srvmon.ServerMonitor(servers, _timeout)
def configure(config):
global _servers, _timeout, _ttl
servers = config.get("servers", "")
for server in servers.split(','):
server = servers.strip()
if not server:
continue
parts = server.split('@')
if len(parts) == 1:
password = None
else:
password = '@'.join(parts[:-1])
database = parts[-1]
parts = database.split(':')
if len(parts) == 1:
db = 0
elif len(parts) == 2:
db = int(parts[1])
else:
raise ValueError("invalid redis connection string format")
address = parts[0]
parts = address.split(':')
if len(parts) == 1:
port = 6379
elif len(parts) == 2:
port = int(parts[1])
else:
raise ValueError("invalid redis connection string format")
host = parts[0]
_servers.append((host, port, db, password))
if not len(_servers):
raise ValueError("no redis connection strings specified")
_timeout = config.getint("timeout", 5) or None
_ttl = config.getint("ttl", 0)
_init_monitor()
global logger
logger = logging.getLogger(__name__)
logger.debug("initialized")
def redis_exc(func):
def wrap_redis_exc(*args):
try:
return func(*args)
except redis.RedisError as ex:
exc_info = sys.exc_info() if debug.enabled else None
logger.error(ex, exc_info=exc_info)
raise cache.CacheError(ex)
return wrap_redis_exc
def redis_index(func):
def wrap_redis_index(key, *args):
try:
index = _monitor.get_server_index(key)
if index is None:
return None
return func(key, *args, index=index)
except redis.ConnectionError:
_monitor.notify_server_down(index)
return None
return wrap_redis_index
class Cache(cache.CacheBase):
def __init__(self):
self._databases = [redis.Redis(host=host, port=port, db=db, password=<PASSWORD>, socket_timeout=_timeout) for (host, port, db, password) in _servers]
self._pipelines = [database.pipeline() for database in self._databases] if _ttl else None
@redis_exc
def connect(self):
pass
@redis_exc
def close(self):
for db in self._databases:
pool = db.connection_pool
pool.disconnect()
@redis_exc
@redis_index
def get(self, key, index=None):
if not _ttl:
db = self._databases[index]
value = db.get(key)
else:
pipe = self._pipelines[index]
pipe.get(key)
pipe.expire(key, _ttl)
result = pipe.execute()
value = result[0]
return value
@redis_exc
@redis_index
def set(self, key, value, index=None):
if not _ttl:
db = self._databases[index]
db.set(key, value)
else:
pipe = self._pipelines[index]
pipe.set(key, value)
pipe.expire(key, _ttl)
pipe.execute()
<file_sep>/src/wordbase/mp/fork.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import signal
import time
import logging
import mp
_children = []
_max_children = 0
logger = None
is_threaded = False
is_subproc = True
Lock = mp.DummyLock
def _sigchld_handler(signum, frame):
logger.debug("caught SIGCHLD; waiting for status")
pid, status = os.waitpid(-1, os.WNOHANG)
del status
if pid:
global _children
_children.remove(pid)
logger.debug("child process %d terminated", pid)
def configure(config):
global _max_children
_max_children = config.getint("max-clients", 20)
signal.signal(signal.SIGCHLD, _sigchld_handler)
global logger
logger = logging.getLogger(__name__)
logger.debug("initialized")
def process(task, sock, *args):
global _children, _max_children
if _max_children:
overload_logged = False
while len(_children) >= _max_children:
if not overload_logged:
logger.warning("max-clients limit exceeded; waiting for a child to terminate")
overload_logged = True
time.sleep(1)
pid = os.fork()
if pid == 0:
logger.debug("process started")
status = 0
try:
task(sock, *args)
except Exception:
logger.exception("unhandled exception")
status = 1
finally:
logger.debug("process exiting")
sys.exit(status)
else:
_children.append(pid)
sock.close()
<file_sep>/src/tools/bedic2pgsql.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import re
import pgutil
script_name = os.path.basename(__file__)
def usage():
print("Usage: {} [-f conf_file] [-o db_order] [-i info_file] name short_desc dict_file".format(script_name), file=sys.stderr)
print("Imports a bedic dictionary into pgsql.", file=sys.stderr)
options, (name, short_desc, dict_file) = pgutil.get_pgsql_params("o:i:", 3, 3, usage)
db_order = options.get("-o")
if db_order is not None:
db_order = int(db_order)
info_file = options.get("-i")
if info_file is not None:
with open(info_file, encoding="utf-8") as f:
info = f.read()
else:
info = None
defs = []
transcription = re.compile(r"^(\[[^\[\]\n]+\]) {2}", re.MULTILINE)
with open(dict_file, encoding="cp1251") as f:
for item in f.read().split('\0')[1:-1]:
word, definition = item.split('\n', 1)
definition = transcription.sub(r"\1\n", definition)
defs.append((word, definition))
pgutil.process_pgsql_task(pgutil.import_task, db_order, name, short_desc, info, defs)
<file_sep>/src/tools/initdb_pgsql.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import pgutil
create_schema = "CREATE SCHEMA {};"
create_dict_id_seq = "CREATE SEQUENCE {}.dictionaries_dict_id_seq;"
create_virt_id_seq = "CREATE SEQUENCE {}.dictionaries_virt_id_seq;"
create_dictionaries = "CREATE TABLE {0}.dictionaries (" \
"id SERIAL PRIMARY KEY, " \
"dict_id INTEGER UNIQUE DEFAULT nextval('{0}.dictionaries_dict_id_seq'), " \
"virt_id INTEGER UNIQUE DEFAULT nextval('{0}.dictionaries_virt_id_seq'), " \
"db_order INTEGER UNIQUE, " \
"name VARCHAR UNIQUE NOT NULL CHECK (position(E'\\n' in name) = 0 AND name NOT IN ('*', '!') AND name ~ '^[^ ''\"\\\\\\\\]+$'), " \
"short_desc VARCHAR NOT NULL CHECK(position(E'\\n' in short_desc) = 0), " \
"info TEXT, " \
"CHECK ((dict_id IS NOT NULL AND virt_id IS NULL) OR (dict_id IS NULL AND virt_id IS NOT NULL) OR (name = '--exit--' AND dict_id IS NULL AND virt_id IS NULL AND info IS NULL))" \
");"
create_definitions = "CREATE TABLE {0}.definitions (" \
"id SERIAL PRIMARY KEY, " \
"dict_id INTEGER NOT NULL REFERENCES {0}.dictionaries(dict_id) ON DELETE CASCADE, " \
"word VARCHAR NOT NULL CHECK(position(E'\\n' in word) = 0), " \
"definition TEXT NOT NULL" \
");"
create_virtual_dictionaries = "CREATE TABLE {0}.virtual_dictionaries (" \
"virt_id INTEGER NOT NULL REFERENCES {0}.dictionaries(virt_id) ON DELETE CASCADE, " \
"dict_id INTEGER NOT NULL REFERENCES {0}.dictionaries(dict_id) ON DELETE CASCADE, " \
"PRIMARY KEY (virt_id, dict_id)" \
");" \
alter_dict_id_seq = "ALTER SEQUENCE {0}.dictionaries_dict_id_seq OWNED BY {0}.dictionaries.dict_id;"
alter_virt_id_seq = "ALTER SEQUENCE {0}.dictionaries_virt_id_seq OWNED BY {0}.dictionaries.virt_id;"
create_definitions_dict_id_word_idx = "CREATE INDEX definitions_dict_id_word_idx ON {}.definitions (dict_id, word);"
script_name = os.path.basename(__file__)
def usage():
print("Usage: {} [-f conf_file]".format(script_name), file=sys.stderr)
print("Initializes a wordbase pgsql schema.", file=sys.stderr)
def init_pgsql_task(cur, schema):
if schema != "public":
cur.execute(create_schema.format(schema))
cur.execute(create_dict_id_seq.format(schema))
cur.execute(create_virt_id_seq.format(schema))
cur.execute(create_dictionaries.format(schema))
cur.execute(create_definitions.format(schema))
cur.execute(create_virtual_dictionaries.format(schema))
cur.execute(alter_dict_id_seq.format(schema))
cur.execute(alter_virt_id_seq.format(schema))
cur.execute(create_definitions_dict_id_word_idx.format(schema))
pgutil.get_pgsql_params(None, 0, 0, usage)
pgutil.process_pgsql_task(init_pgsql_task)
<file_sep>/src/wordbase/cmdparser.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
from pyparsing import ParserElement, Empty, Word, CharsNotIn, White, Optional, ZeroOrMore, OneOrMore, StringStart, StringEnd, Combine, Group, Suppress, nums, ParseException
import debug
import modules
logger = None
CTL = ''.join(chr(i) for i in range(0, 32)) + chr(127)
WS = " \t"
ParserElement.setDefaultWhitespaceChars(WS)
_ws = White(WS)
_quoted_pair = Suppress('\\') + CharsNotIn("", exact=1)
_dqtext = CharsNotIn("\"\\" + CTL, exact=1)
_dqstring = Combine(Suppress('"') + ZeroOrMore(_dqtext | _quoted_pair) + Suppress('"'))
_sqtext = CharsNotIn("'\\" + CTL, exact=1)
_sqstring = Combine(Suppress('\'') + ZeroOrMore(_sqtext | _quoted_pair) + Suppress('\''))
_atom = Empty() + CharsNotIn(" '\"\\" + CTL)
_string = Combine(OneOrMore(_dqstring | _sqstring | _quoted_pair))
_word = Combine(OneOrMore(_atom | _string))
_ws_state = ""
def _ws_action(t):
global _ws_state
_ws_state = t[0]
return ""
def _word_action(t):
global _ws_state
if _ws_state:
r = ''.join((_ws_state, t[0]))
_ws_state = ""
return r
def _text_action(t):
global _ws_state
_ws_state = ""
_text = Combine(OneOrMore(_word.copy().setParseAction(_word_action) | _ws.copy().setParseAction(_ws_action))).setParseAction(_text_action).setFailAction(lambda s, l, ex, err: _text_action(None))
_description = _text.copy()
_decimal = Word(nums).setParseAction(lambda t: int(t[0]))
_cmd_state = None
def _get_reset_cmd_state_action(cmd):
def _reset_cmd_state_action(t):
global _cmd_state
if cmd is None or (_cmd_state is not None and _cmd_state == cmd):
_cmd_state = None
return Empty().setParseAction(_reset_cmd_state_action)
def _get_keyword_action(kw):
def _keyword_action(s, l, t):
if t[0].upper() != kw.upper():
raise ParseException(s, l, "expected keyword")
return kw
return _keyword_action
def _keyword(kw):
return _word.copy().setParseAction(_get_keyword_action(kw))
def _get_cmd_action(cmd):
def _cmd_action(t):
global _cmd_state
if _cmd_state is None:
_cmd_state = cmd
return cmd
return _cmd_action
def _command(name, real=None):
cmd = _keyword(name) if name else Empty()
return cmd.addParseAction(_get_cmd_action(real or name))
_start = StringStart()
_end = StringEnd()
def _bound_command(body):
return _start + body + _end
def _command_string(body):
cmd_str = _bound_command(body)
if debug.enabled:
cmd_str |= _bound_command(_command("T") + _decimal + _get_reset_cmd_state_action("T") + Group(body))
return cmd_str
def _shortcut(s):
return Empty().addParseAction(lambda t: s)
def make_grammar():
show_db = _keyword("DB") | _keyword("DATABASES")
show_strat = _keyword("STRAT") | _keyword("STRATEGIES")
show_info = _keyword("INFO") + _word
show_server = _keyword("SERVER") + Optional(_text)
show_params = show_db | show_strat | show_info | show_server
grammar = _command_string(_command("") + _get_reset_cmd_state_action(None))
grammar |= _command_string(_command("DEFINE") + _word + _word) | _command_string(_command("D", "DEFINE") + _shortcut("*") + _word) | _command_string(_command("D", "DEFINE") + _word + _word)
grammar |= _command_string(_command("MATCH") + _word + _word + _word) | _command_string(_command("M", "MATCH") + _shortcut("*") + _shortcut(".") + _word) | _command_string(_command("M", "MATCH") + _shortcut("*") + _word + _word) | _command_string(_command("M", "MATCH") + _word + _word + _word)
grammar |= _command_string(_command("SHOW") + show_params)
grammar |= _command_string(_command("CLIENT") + Optional(_text, default=""))
grammar |= _command_string(_command("STATUS") + Optional(_text)) | _command_string(_command("S", "STATUS") + Optional(_text))
grammar |= _command_string(_command("HELP") + Optional(_text)) | _command_string(_command("H", "HELP") + Optional(_text))
grammar |= _command_string(_command("QUIT") + Optional(_text)) | _command_string(_command("Q", "QUIT") + Optional(_text))
grammar |= _command_string(_command("OPTION") + Optional(_text)) # not supported, therefore defined liberally
grammar |= _command_string(_command("AUTH") + Optional(_text)) # not supported, therefore defined liberally
grammar |= _command_string(_command("SASLAUTH") + Optional(_text)) # not supported, therefore defined liberally
grammar |= _command_string(_command("SASLRESP") + Optional(_text)) # not supported, therefore defined liberally
grammar.parseWithTabs()
return grammar
_grammar = None
_parser_lock = None
def parse_command(line):
with _parser_lock:
try:
results = _grammar.parseString(line)
return True, results
except ParseException as pe:
logger.debug(pe)
return False, _cmd_state
def init():
global logger
logger = logging.getLogger(__name__)
global _parser_lock
_parser_lock = modules.mp().Lock()
global _grammar
_grammar = make_grammar()
<file_sep>/src/wordbase/modules.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
logger = None
_mp = None
_db = None
_cache = None
def mp():
return _mp
def db():
return _db
def cache():
return _cache
def _init_module(config, mtype, defmod, *args):
modules_conf = config["modules"]
mname = modules_conf.get(mtype, defmod)
mconf = config[mname] if mname != "none" else None
fullname = mtype + "." + mname
logger.debug("initializing module %s", fullname)
pkg = __import__(fullname)
mod = getattr(pkg, mname)
mod.configure(mconf, *args)
return mod
def init(config):
global logger
logger = logging.getLogger(__name__)
global _mp, _db, _cache
_mp = _init_module(config, "mp", "thread")
_db = _init_module(config, "db", "pgsql")
_cache = _init_module(config, "cache", "none")
<file_sep>/src/wordbase/handlers.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
import time
import collections
import debug
import helpmsg
import db
import match
logger = None
STOP_DB_NAME = "--exit--"
_server_string = ""
_server_info = ""
def handle_550(func):
def error_550_wrapper(conn, *args):
try:
func(conn, *args)
except db.InvalidDatabaseError as ide:
logger.debug(ide)
conn.write_status(550, "Invalid database, use \"SHOW DB\" for list of databases")
return error_550_wrapper
def _validate_db_name(name):
if name == STOP_DB_NAME:
db.BackendBase.invalid_db(name)
def _escaped(s):
return s.replace('\\', "\\\\").replace('"', "\\\"")
def _send_text(conn, text):
lines = text.splitlines()
for line in lines:
conn.write_line(line)
def _null_handler(*args):
pass
def _not_implemented(conn, *args):
conn.write_status(502, "Command not implemented")
def _handle_quit(conn, *args):
conn.write_status(221, "Closing Connection")
return True
def _handle_help(conn, *args):
conn.write_status(113, "help text follows")
conn.write_text(helpmsg.help_lines)
conn.write_status(250, "ok")
def _handle_status(conn, *args):
conn.write_status(210, "up")
def _handle_client(conn, backend, cacher, command):
logger.info("client: %s", command[1])
conn.write_status(250, "ok")
def _show_db(conn, backend):
dbs = backend.get_databases()
n = len(dbs)
if n:
conn.write_status(110, "{} databases present - text follows".format(n))
dbs.sort(key=lambda t: t[1])
for db in dbs:
name, virtual, short_desc = db
del virtual
line = "{} \"{}\"".format(name, _escaped(short_desc))
conn.write_line(line)
conn.write_text_end()
conn.write_status(250, "ok")
else:
conn.write_status(554, "No databases present")
def _show_strat(conn):
strats = match.get_strategies()
num_strats = len(strats)
if not num_strats:
conn.write_status(555, "No strategies available")
return
conn.write_status(111, "{} strategies available - text follows".format(num_strats))
for name, desc in strats.items():
escaped_desc = _escaped(desc)
conn.write_line("{} \"{}\"".format(name, escaped_desc))
conn.write_text_end()
@handle_550
def _show_info(conn, backend, database):
_validate_db_name(database)
virtual, info = backend.get_database_info(database)
conn.write_status(112, "database information follows")
if info:
_send_text(conn, info)
elif virtual:
names = backend.get_virtual_database(database)
for name in names:
virtual, info = backend.get_database_info(database)
conn.write_line("================ {} ================".format(name))
if info:
_send_text(conn, info)
conn.write_text_end()
conn.write_status(250, "ok")
def _show_server(conn):
info = open(_server_info) if _server_info else None
try:
conn.write_status(114, "server information follows")
conn.write_line(_server_string)
if info:
for line in info:
conn.write_line(line.rstrip('\n'))
finally:
if info:
info.close()
conn.write_text_end()
conn.write_status(250, "ok")
def _handle_show(conn, backend, cacher, command):
param = command[1]
if param in ["DB", "DATABASES"]:
_show_db(conn, backend)
elif param in ["STRAT", "STRATEGIES"]:
_show_strat(conn)
elif param == "INFO":
database = command[2]
_show_info(conn, backend, database)
elif param == "SERVER":
_show_server(conn)
else:
assert False, "unhandled SHOW command"
def _retrieve_words(backend, cacher, db_name):
def parse_list(data):
items = data.splitlines()
return items
def format_list(items):
mangle = len(items) > 0 and len(items[-1]) == 0
if mangle:
items.append("")
formatted = '\n'.join(items)
if mangle:
del items[-1]
return formatted
words_name = "words:{}".format(db_name)
preproc_name = "preproc:{}".format(db_name)
words_cache = cacher.get(words_name)
if words_cache is not None:
words = parse_list(words_cache)
else:
words = backend.get_words(db_name)
formatted = format_list(words)
cacher.set(words_name, formatted)
preproc_cache = cacher.get(preproc_name)
if preproc_cache is not None:
preprocessed = parse_list(preproc_cache)
else:
preprocessed = match.preprocessed(words)
formatted = format_list(preprocessed)
cacher.set(preproc_name, formatted)
return words, preprocessed
def _find_matches(conn, backend, cacher, dbs, database, strategy, word, defs):
def get_matches(db_name):
def add_matches(db_name):
words, preprocessed = _retrieve_words(backend, cacher, db_name)
filtered = word_filter(word, words, preprocessed)
if defs:
matches = [(wd, []) for wd in filtered]
else:
matches = filtered
item = (db_name, matches)
ml.append(item)
return len(matches)
nmatches = 0
ml = []
virtual, short_desc = dbs[db_name]
del short_desc
if not virtual:
nmatches += add_matches(db_name)
else:
for name in backend.get_virtual_database(db_name):
nmatches += add_matches(name)
return nmatches, ml
_validate_db_name(database)
strat = strategy if strategy != "." else None
try:
word_filter = match.get_filter(strat)
except match.InvalidStrategyError as ise:
logger.debug(ise)
conn.write_status(551, "Invalid strategy, use \"SHOW STRAT\" for a list of strategies")
return
num_matches = 0
db_match_defs = []
if database in ("*", "!"):
for name, (virtual, short_desc) in dbs.items():
del short_desc
if virtual:
continue
if name == STOP_DB_NAME:
break
nm, ml = get_matches(name)
assert len(ml) == 1, "virtual database detected"
db_match_defs.extend(ml)
num_matches += nm
if database == "!":
if nm:
break
else:
nm, ml = get_matches(database)
db_match_defs.extend(ml)
num_matches = nm
return db_match_defs, num_matches
def _get_dbs(backend):
dbs = collections.OrderedDict([(name, (virtual, short_desc)) for (name, virtual, short_desc) in backend.get_databases()])
return dbs
@handle_550
def _handle_match(conn, backend, cacher, command):
database = command[1]
strategy = command[2]
word = command[3]
dbs = _get_dbs(backend)
db_matches, num_matches = _find_matches(conn, backend, cacher, dbs, database, strategy, word, False)
if not num_matches:
conn.write_status(552, "No match")
return
conn.write_status(152, "{} matches found - text follows".format(num_matches))
for name, matches in db_matches:
for m in matches:
escaped_match = _escaped(m)
conn.write_line("{} \"{}\"".format(name, escaped_match))
conn.write_text_end()
conn.write_status(250, "ok")
@handle_550
def _handle_define(conn, backend, cacher, command):
database = command[1]
word = command[2]
dbs = _get_dbs(backend)
db_match_defs, num_matches = _find_matches(conn, backend, cacher, dbs, database, "exact", word, True)
del num_matches
num_defs = 0
for name, matches in db_match_defs:
for wd, defs in matches:
res = backend.get_definitions(name, wd)
defs.extend(res)
num_defs += len(res)
if not num_defs:
conn.write_status(552, "No match")
return
conn.write_status(150, "{} definitions retrieved - definitions follow".format(num_defs))
for name, matches in db_match_defs:
virtual, short_desc = dbs[name]
del virtual
escaped_short_desc = _escaped(short_desc)
for wd, defs in matches:
escaped_word = _escaped(wd)
for definition in defs:
conn.write_status(151, "\"{}\" {} \"{}\" - text follows".format(escaped_word, name, escaped_short_desc))
_send_text(conn, definition)
conn.write_text_end()
conn.write_status(250, "ok")
def _handle_time_command(conn, backend, cacher, command):
start = time.clock()
null_conn = debug.NullConnection()
n = command[1]
subcmd = command[2]
for i in range(n):
del i
handle_command(null_conn, backend, cacher, subcmd)
end = time.clock()
elapsed = end - start
handle_command(conn, backend, cacher, subcmd)
conn.write_status(280, "time: {:.3f} s".format(elapsed))
_cmd_handlers = {
"": _null_handler,
"DEFINE": _handle_define,
"MATCH": _handle_match,
"SHOW": _handle_show,
"CLIENT": _handle_client,
"STATUS": _handle_status,
"HELP": _handle_help,
"QUIT": _handle_quit,
"T": _handle_time_command
}
def handle_syntax_error(conn, command):
if command is None:
code, msg = 500, "Syntax error, command not recognized"
else:
code, msg = 501, "Syntax error, illegal parameters"
conn.write_status(code, msg)
def handle_command(conn, backend, cacher, command):
name = command[0]
handler = _cmd_handlers.get(name, _not_implemented)
return handler(conn, backend, cacher, command)
def configure(server_string, server_info):
global _server_string, _server_info
_server_string = server_string
_server_info = server_info
global logger
logger = logging.getLogger(__name__)
<file_sep>/src/wordbase/mp/thread.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import threading
import logging
_max_threads = 0
_guard_sem = None
logger = None
is_threaded = True
is_subproc = False
Lock = threading.Lock
def configure(config):
global _max_threads, _guard_sem
_max_threads = config.getint("max-clients", 20)
if _max_threads:
_guard_sem = threading.Semaphore(_max_threads)
global logger
logger = logging.getLogger(__name__)
logger.debug("initialized")
def thread_task(task, sock, *args):
logger.debug("thread started")
try:
task(sock, *args)
except Exception:
logger.exception("unhandled exception")
finally:
logger.debug("thread exiting")
if _max_threads:
_guard_sem.release()
def process(task, sock, *args):
if _max_threads:
if not _guard_sem.acquire(False):
logger.warning("max-clients limit exceeded; waiting for a thread to terminate")
_guard_sem.acquire()
thr = threading.Thread(target=thread_task, args = (task, sock) + args)
thr.daemon = True
thr.start()
<file_sep>/src/wordbase/wordbase.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import os
import getopt
import configparser
import logging
import random
import daemon
import debug
import log
import util.srvmon
import modules
import match
import core
import master
PROGRAM_NAME = "wordbase"
PROGRAM_VERSION = "0.5-dev"
script_name = os.path.basename(__file__)
logger = None
version_info = \
"""{name} {version}
Copyright (C) 2011 <NAME>"""
usage_help = \
"""Usage: {name} [-f conf_file] [-d command] [-D]
Options:
-v print version information and exit
-h print this help message and exit
-f conf_file read the specified configuration file
-d daemon mode
-D debug mode
Daemon control commands:
start start daemon
stop stop daemon
restart restart daemon"""
help_hint = "Try '{name} -h' for more information."
class WBDaemon(daemon.Daemon):
def __init__(self, name, pidfile, task, *args):
super().__init__(name, pidfile)
self.run_task = task
self.run_args = args
def run(self):
self.run_task(*self.run_args)
def get_default_conf_path():
return "/etc/" + PROGRAM_NAME + ".conf"
def print_usage():
print(usage_help.format(name=script_name))
def print_version():
print(version_info.format(name=PROGRAM_NAME, version=PROGRAM_VERSION))
def print_help_hint():
print(help_hint.format(name=script_name), file=sys.stderr)
def drop_privs(wbconfig):
user = wbconfig.get("user", "nobody")
group = wbconfig.get("group", "")
try:
import pwd, grp
except ImportError:
return
uentry = pwd.getpwnam(user)
uid = uentry[2]
gid = grp.getgrnam(group)[2] if group else uentry[3]
try:
os.setgid(gid)
os.setuid(uid)
except AttributeError:
return
def start_server(wbconfig, mp):
host = wbconfig.get("host", "0.0.0.0")
port = wbconfig.getint("port", 2628)
backlog = wbconfig.getint("backlog", 512)
timeout = wbconfig.getint("timeout", 60) or None
address = (host, port)
master.init(address, backlog)
drop_privs(wbconfig)
master.run(timeout, mp)
def server_control(config, daemon_cmd):
start_cmd = "start"
stop_cmd = "stop"
restart_cmd = "restart"
wbconfig = config["wordbase"]
pidfile = wbconfig.get("pidfile", "/var/run/" + PROGRAM_NAME + ".pid")
wbdaemon = WBDaemon(PROGRAM_NAME, pidfile, start_server)
control_func = None
if daemon_cmd in (None, start_cmd, restart_cmd):
random.seed()
smconfig = config["srvmon"]
util.srvmon.configure(smconfig)
modules.init(config)
dconfig = config["dict"]
match.configure(dconfig)
core.configure(dconfig)
wbdaemon.run_args = (wbconfig, modules.mp())
if daemon_cmd == start_cmd:
control_func = wbdaemon.start
elif daemon_cmd == restart_cmd:
control_func = wbdaemon.restart
elif daemon_cmd is None:
control_func = wbdaemon.run
else:
assert False, "unhandled command"
log_init = True
elif daemon_cmd == stop_cmd:
control_func = wbdaemon.stop
log_init = False
else:
print("command \"{}\" not recognized".format(daemon_cmd), file=sys.stderr)
print_help_hint()
sys.exit(2)
if log_init:
logger.debug("initialized")
control_func()
def main():
conf_path = None
daemon = None
try:
opts, args = getopt.getopt(sys.argv[1:], "vhf:d:D")
except getopt.GetoptError as ge:
print(ge, file=sys.stderr)
print_help_hint()
sys.exit(2)
if len(args):
print("excess argument(s)", file=sys.stderr)
print_help_hint()
sys.exit(2)
for opt, arg in opts:
if opt == "-v":
print_version()
return
elif opt == "-h":
print_usage()
return
elif opt == "-f":
conf_path = arg
elif opt == "-d":
daemon = arg
elif opt == "-D":
debug.enabled = True
else:
assert False, "unhandled option"
if conf_path is None:
conf_path = get_default_conf_path()
log.configure(conf_path)
global logger
logger = logging.getLogger(PROGRAM_NAME)
with open(conf_path) as conf:
config = configparser.ConfigParser(delimiters="=", inline_comment_prefixes="#")
config.read_file(conf, conf_path)
server_control(config, daemon)
try:
main()
except KeyboardInterrupt:
pass
except Exception as ex:
err_msg = "{}: {}".format(ex.__class__.__name__, ex)
log_msg = "terminating on unhandled exception"
exc_info = sys.exc_info() if debug.enabled else None
if logger:
logger.critical(log_msg, exc_info=exc_info)
else:
logging.critical(log_msg, exc_info=exc_info)
print(err_msg, file=sys.stderr)
sys.exit(1)
<file_sep>/src/tools/pgutil.py
#!/usr/bin/env python3
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import getopt
import configparser
import psycopg2 as dbapi
_host = _port = _user = _password = _database = _schema = None
_insert_dictionary = "INSERT INTO {}.dictionaries (virt_id, db_order, name, short_desc, info) " \
"VALUES (NULL, %s, %s, %s, %s);"
_select_dict_id = "SELECT dict_id FROM {}.dictionaries WHERE name = %s;"
_prepare_insert_definition = "PREPARE insert_definition(VARCHAR, TEXT) AS " \
"INSERT INTO {}.definitions (dict_id, word, definition) " \
"VALUES (%s, $1, $2);"
_execute_insert_definition = "EXECUTE insert_definition(%s, %s);"
def get_default_conf_path():
return "/etc/wordbase.conf"
def get_pgsql_params(fmt, minargs, maxargs, usage):
try:
opts, args = getopt.getopt(sys.argv[1:], "f:" + (fmt or ""))
except getopt.GetoptError:
usage()
sys.exit(2)
if (minargs is not None and len(args) < minargs) or (maxargs is not None and len(args) > maxargs):
usage()
sys.exit(2)
conf_path = None
options = {}
for opt, arg in opts:
if opt == "-f":
conf_path = arg
else:
options[opt] = arg
if conf_path is None:
conf_path = get_default_conf_path()
with open(conf_path) as conf:
config = configparser.ConfigParser(inline_comment_prefixes="#")
config.read_file(conf, conf_path)
pgconfig = config["pgsql"]
global _host, _port, _user, _password, _database, _schema
_host = pgconfig.get("host", "localhost")
_port = pgconfig.getint("port", 5432)
_user = pgconfig.get("user", "nobody")
_password = pgconfig.get("password", "")
_database = pgconfig.get("database", "wordbase")
_schema = pgconfig.get("schema", "") or "public"
return options, args
def process_pgsql_task(task, *args):
conn = dbapi.connect(host=_host, port=_port, user=_user, password=_password, database=_database)
try:
conn.autocommit = False
cur = conn.cursor()
try:
task(cur, _schema, *args)
finally:
cur.close()
conn.commit()
finally:
conn.close()
def import_task(cur, schema, db_order, name, short_desc, info, defs, quiet=False):
cur.execute(_insert_dictionary.format(schema), (db_order, name, short_desc, info))
cur.execute(_select_dict_id.format(schema), (name, ))
dict_id = cur.fetchone()[0]
cur.execute(_prepare_insert_definition.format(schema), (dict_id, ))
for word, definition in defs:
cur.execute(_execute_insert_definition, (word, definition))
if not quiet:
print("{} definitions imported".format(len(defs)))
<file_sep>/src/wordbase/helpmsg.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
help_lines = (
"DEFINE database word -- look up word in database",
"MATCH database strategy word -- match word in database using strategy",
"SHOW DB -- list all accessible databases",
"SHOW DATABASES -- list all accessible databases",
"SHOW STRAT -- list available matching strategies",
"SHOW STRATEGIES -- list available matching strategies",
"SHOW INFO database -- provide information about the database",
"SHOW SERVER -- provide site-specific information",
"OPTION MIME -- use MIME headers",
"CLIENT info -- identify client to server",
"AUTH user string -- provide authentication information",
"STATUS -- display timing information",
"HELP -- display this help information",
"QUIT -- terminate connection",
"",
"The following commands are unofficial server extensions for debugging",
"only. You may find them useful if you are using telnet as a client.",
"If you are writing a client, you MUST NOT use these commands, since",
"they won't be supported on any other server!",
"",
"D word -- DEFINE * word",
"D database word -- DEFINE database word",
"M word -- MATCH * . word",
"M strategy word -- MATCH * strategy word",
"M database strategy word -- MATCH database strategy word",
"S -- STATUS",
"H -- HELP",
"Q -- QUIT",
)
<file_sep>/src/wordbase/debug.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import traceback
enabled = False
def not_impl(self, name=None):
method = name or traceback.extract_stack()[-2][2]
raise NotImplementedError("{}.{} not implemented".format(self.__class__.__name__, method))
class NullConnection:
def write_line(self, line, split=True):
pass
def write_status(self, code, message):
pass
def write_text_end(self):
pass
def write_text(self, lines):
pass
def __getattr__(self, name):
not_impl(self, name)
<file_sep>/src/wordbase/db/pgsql.py
# Copyright (C) 2011 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of the contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import logging
import psycopg2 as dbapi
import debug
import db
logger = None
_host = ""
_port = 0
_user = ""
_password = ""
_database = ""
_schema = ""
def configure(config):
global _host, _port, _user, _password, _database, _schema
_host = config.get("host", "localhost")
_port = config.getint("port", 5432)
_user = config.get("user", "nobody")
_password = config.get("password", "")
_database = config.get("database", "wordbase")
_schema = config.get("schema", "") or "public"
global logger
logger = logging.getLogger(__name__)
logger.debug("initialized")
def _statement(stmt):
return stmt.format(_schema)
def pg_exc(func):
def wrap_pg_exc(*args):
try:
return func(*args)
except (dbapi.Error, dbapi.Warning) as ex:
exc_info = sys.exc_info() if debug.enabled else None
logger.error(ex, exc_info=exc_info)
raise db.BackendError(ex)
return wrap_pg_exc
def pg_conn(func):
def wrap_pg_conn(self, *args):
if self._cur is None:
self._connect_real()
return func(self, *args)
return wrap_pg_conn
class Backend(db.BackendBase):
def __init__(self):
self._conn = None
self._cur = None
def _connect_real(self):
self.close()
self._conn = dbapi.connect(host=_host, port=_port, user=_user, password=_<PASSWORD>, database=_database)
self._conn.autocommit = True
self._cur = self._conn.cursor()
logger.debug("connected to pgsql")
@pg_exc
def connect(self):
pass
@pg_exc
def close(self):
if self._cur is not None:
self._cur.close()
self._cur = None
if self._conn is not None:
self._conn.close()
self._conn = None
logger.debug("closed the pgsql connection")
@pg_exc
@pg_conn
def get_databases(self):
cur = self._cur
stmt = "SELECT name, (virt_id IS NOT NULL) AS virtual, short_desc FROM {}.dictionaries ORDER BY db_order;".format(_schema)
cur.execute(stmt)
rs = cur.fetchall()
return rs
@pg_exc
@pg_conn
def get_database_info(self, database):
cur = self._cur
stmt = "SELECT (virt_id IS NOT NULL) AS virtual, info FROM {}.dictionaries WHERE name = %s;".format(_schema)
cur.execute(stmt, (database,))
if cur.rowcount < 1:
self.__class__.invalid_db(database)
row = cur.fetchone()
return row
def _get_ids(self, database):
cur = self._cur
stmt = "SELECT dict_id, virt_id FROM {}.dictionaries WHERE name = %s;".format(_schema)
cur.execute(stmt, (database,))
if cur.rowcount >= 1:
ids = cur.fetchone()
dict_id, virt_id = ids
if dict_id is not None or virt_id is not None:
return ids
self.__class__.invalid_db(database)
def _get_words_real(self, dict_id):
cur = self._cur
stmt = "SELECT DISTINCT word FROM {}.definitions WHERE dict_id = %s ORDER BY word;".format(_schema)
cur.execute(stmt, (dict_id,))
rs = cur.fetchall()
return list(zip(*rs))[0]
def _get_virt_dict(self, virt_id):
cur = self._cur
stmt = "SELECT name FROM {0}.dictionaries INNER JOIN {0}.virtual_dictionaries USING (dict_id) WHERE {0}.virtual_dictionaries.virt_id = %s ORDER BY db_order;".format(_schema)
cur.execute(stmt, (virt_id,))
rs = cur.fetchall()
return list(zip(*rs))[0]
@pg_exc
@pg_conn
def get_words(self, database):
dict_id, virt_id = self._get_ids(database)
del virt_id
if dict_id is None:
raise db.VirtualDatabaseError("database {} is not real".format(database))
words = self._get_words_real(dict_id)
return words
@pg_exc
@pg_conn
def get_virtual_database(self, database):
dict_id, virt_id = self._get_ids(database)
del dict_id
if virt_id is None:
raise db.VirtualDatabaseError("database {} is not virtual".format(database))
virt_dict = self._get_virt_dict(virt_id)
return virt_dict
@pg_exc
@pg_conn
def get_definitions(self, database, word):
cur = self._cur
stmt = "SELECT definition FROM {0}.definitions WHERE dict_id = (SELECT dict_id FROM {0}.dictionaries WHERE name = %s) AND word = %s;".format(_schema)
cur.execute(stmt, (database, word))
rs = cur.fetchall()
return list(zip(*rs))[0]
| 476cfa8c403a6b76434bc7d61a0defd032ffd154 | [
"Python"
] | 20 | Python | vsemionov/wordbase | 62a34c223e3acc6db9b26147e3773c623640ab00 | 9cb886ae74880aed4898dc294c3c5a5f12d687f7 |
refs/heads/master | <repo_name>vedant297/ScanersDice<file_sep>/app/src/main/java/com/example/vedantpatel/scanersdice/MainActivity.java
package com.example.vedantpatel.scanersdice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public int user_overall_score=0;
public int user_turn_score=0;
public int computer_overall_score=0;
public int computer_turn_score=0;
public int fexit=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button roll = (Button)findViewById(R.id.roll);
roll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
userroll();
}
});
Button Hold = (Button)findViewById(R.id.hold);
Hold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
user_overall_score = user_overall_score+user_turn_score;
TextView textView = (TextView)findViewById(R.id.dis_yourscore);
textView.setText(String.valueOf(user_overall_score));
user_turn_score=0;
textView=(TextView)findViewById(R.id.dis_yourcurrentscore);
textView.setText(String.valueOf(user_turn_score));
computer_event();
}
});
Button Roll = (Button) findViewById(R.id.roll);
Roll.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this,"computer score "+computer_turn_score,Toast.LENGTH_SHORT).show();
computer_overall_score = computer_overall_score+computer_turn_score;
computer_turn_score=0;
TextView textView = (TextView)findViewById(R.id.dis_comcurrentscore);
textView.setText(String.valueOf(computer_turn_score));
textView= (TextView)findViewById(R.id.dis_computerscore);
textView.setText(String.valueOf(computer_overall_score));
userroll();
}
});
Button Reset = (Button)findViewById(R.id.reset);
Reset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
user_turn_score=0;
user_overall_score=0;
computer_turn_score=0;
computer_overall_score=0;
TextView textView = (TextView) findViewById(R.id.dis_yourcurrentscore);
textView.setText(String.valueOf(user_turn_score));
textView = (TextView) findViewById(R.id.dis_yourscore);
textView.setText(String.valueOf(user_overall_score));
textView = (TextView) findViewById(R.id.dis_comcurrentscore);
textView.setText(String.valueOf(computer_turn_score));
textView = (TextView) findViewById(R.id.dis_computerscore);
textView.setText(String.valueOf(computer_overall_score));
}
});
}
public void userroll(){
android.os.Handler handler=new android.os.Handler();
TextView textView = (TextView)findViewById(R.id.dis_yourcurrentscore);
textView.setText(String.valueOf(user_turn_score));
computer_turn_score=0;
int dice_number=new Random().nextInt(6)+1;
ImageView image=(ImageView)findViewById(R.id.imageView);
//long mili=1500;
if(user_overall_score<100){
switch (dice_number){
case 1:
image.setImageResource(R.drawable.dice1);
handler.postDelayed(new Runnable() {
@Override
public void run() {
computer_event();
}
},800);
break;
case 2:
image.setImageResource(R.drawable.dice2);
break;
case 3:
image.setImageResource(R.drawable.dice3);
break;
case 4:
image.setImageResource(R.drawable.dice4);
break;
case 5:
image.setImageResource(R.drawable.dice5);
break;
case 6:
image.setImageResource(R.drawable.dice6);
break;
}
user_turn_score = user_turn_score+dice_number;
textView = (TextView)findViewById(R.id.dis_yourcurrentscore);
textView.setText(String.valueOf(user_turn_score));
}
else {
Toast.makeText(MainActivity.this,"You have won the game",Toast.LENGTH_SHORT).show();
}
}
public void computer_event(){
int dice_number=new Random().nextInt(6)+1;
ImageView image=(ImageView)findViewById(R.id.imageView);
image.setImageResource(R.drawable.dice1);
user_turn_score=0;
TextView temp = (TextView)findViewById(R.id.dis_yourcurrentscore);
temp.setText(String.valueOf(user_turn_score));
if(computer_overall_score<100)
{
switch (dice_number){
case 1:
image.setImageResource(R.drawable.dice1);
computer_turn_score=0;
temp = (TextView)findViewById(R.id.dis_comcurrentscore);
temp.setText(String.valueOf(0));
Toast.makeText(MainActivity.this,"Roll over"+computer_turn_score,Toast.LENGTH_SHORT).show();
userroll();
break;
case 2:
image.setImageResource(R.drawable.dice2);
break;
case 3:
image.setImageResource(R.drawable.dice3);
break;
case 4:
image.setImageResource(R.drawable.dice4);
break;
case 5:
image.setImageResource(R.drawable.dice5);
break;
case 6:
image.setImageResource(R.drawable.dice6);
break;
}
computer_turn_score = computer_turn_score+dice_number;
temp = (TextView)findViewById(R.id.dis_comcurrentscore);
temp.setText(String.valueOf(computer_turn_score));
}
else {
Toast.makeText(MainActivity.this,"You have won the game",Toast.LENGTH_SHORT).show();
}
}
}
| 2250d26c36597648cbe4a9704ac8cf12c8e9b1dc | [
"Java"
] | 1 | Java | vedant297/ScanersDice | b9f527c7383215ed8fe8d54347e48c8f5668c074 | b2a29ca4dbc212db872f5c7fa38d757641dc917a |
refs/heads/master | <repo_name>Hussein-Dahir/Yamsafer-Backend-Interview<file_sep>/app/Http/Controllers/SubscribersController.php
<?php
namespace App\Http\Controllers;
use Validator;
use App\Subscriber;
use Illuminate\Http\Request;
class SubscribersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$subscribers = Subscriber::all();
return $subscribers;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$url = $request->input('url');
$validator = Validator::make($request->all(), [
'url' => 'required|unique:subscribers|url'
]);
$errors = $validator->errors();
if ($errors->any()){
return $errors;
}
$subscriber = Subscriber::create(compact('url'));
$eventIds = $request->input('eventIds');
$subscriber->events()->attach($eventIds);
return "Subscriber Succesfully added";
}
/**
* Display the specified resource.
*
* @param \App\Subscriber $subscriber
* @return \Illuminate\Http\Response
*/
public function show(Subscriber $subscriber)
{
return $subscriber;
}
}
<file_sep>/app/Event.php
<?php
namespace App;
class Event extends Model
{
public function subscribers(){
return $this -> belongsToMany(Subscriber::class);
}
}
<file_sep>/app/Http/Controllers/EventsController.php
<?php
namespace App\Http\Controllers;
use App\Event;
use Illuminate\Http\Request;
class EventsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$events = Event::all();
return $events;
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store()
{
$event = Event::create(request(['name']));
event(new \App\Events\SubscriptionEvent($event));
return "Event Succesfully added";
}
/**
* Display the specified resource.
*
* @param \App\Event $event
* @return \Illuminate\Http\Response
*/
public function show(Event $event)
{
return $event;
}
}
<file_sep>/app/Subscriber.php
<?php
namespace App;
class Subscriber extends Model
{
public function events(){
return $this -> belongsToMany(Event::class);
}
}
<file_sep>/app/Listeners/SubscriptionEventListener.php
<?php
namespace App\Listeners;
use App\Event;
use App\Events\SubscriptionEvent;
use App\Subscriber;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SubscriptionEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param SubscriptionEvent $event
* @return void
*/
public function handle(SubscriptionEvent $subscriptionEvent)
{
//var_dump($event->eventObject['name'] . ' event triggered !');
$eventArray = $subscriptionEvent->event;
$eventId = $eventArray['id'];
$event = \App\Event::find($eventId);
$urls = $event->subscribers()->pluck('url');
//dd($urls);
foreach ($urls as $url) {
// send notification
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "eventId=" . $eventId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
}
}
}
<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('/events', 'EventsController@index');
Route::get('/events/{event}', 'EventsController@show');
Route::post('/events', 'EventsController@store');
Route::get('/subscribers', 'SubscribersController@index');
Route::get('/subscribers/{subscriber}', 'SubscribersController@show');
Route::post('/subscribers', 'SubscribersController@store'); | 8eddfdcd70a077cac44e8ad31f5d1eda4d04ec76 | [
"PHP"
] | 6 | PHP | Hussein-Dahir/Yamsafer-Backend-Interview | 4d43ebbc605c6acbbf7705abeb30a2083707996b | b0a238f84d1a26bd8ae02a17a37502872d1eca9f |
refs/heads/master | <repo_name>kmustyxl/tensorflow_learn<file_sep>/README.md
# tensorflow_learn
实战Google深度学习框架
<file_sep>/Line regression.py
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# a = tf.constant(2)
# b = tf.constant(3)
# with tf.Session() as sess:
# print('a = 2, b = 3')
# print('Addition with constants: %d' %sess.run(a+b))
# print('Multiplication with constants: %d' %sess.run(a*b))
# a = tf.placeholder(tf.int16)
# b = tf.placeholder(tf.int16)
# add = tf.add(a,b)
# mul = tf.multiply(a,b)
# with tf.Session() as sess:
# print('Addition with variables: %i'%sess.run(add, feed_dict={a:2,b:3}))
# print('Multiplication with variables: %i'%sess.run(mul, feed_dict={a:2, b:3}))
# matrix1 = tf.constant([[3,3]])
# matrix2 = tf.constant([[2],[2]])
# product = tf.matmul(matrix1, matrix2)
# with tf.Session() as sess:
# print(sess.run(product))
rng = np.random
#Parameters
learning_rate = 0.01
training_epochs = 2000
display_step = 50
#Training Data
train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y = np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_samples = train_X.shape[0]
#tf Graph Input
X = tf.placeholder('float')
Y = tf.placeholder('float')
#Create Model
#Set model weights
W = tf.Variable(np.random.randn(),name='weight')
b = tf.Variable(np.random.randn(),name='bias')
#Constant a linear model
activation = tf.add(tf.multiply(W,X), b)
#Minimize the squared errors
cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
#Initializer the variables
init = tf.initialize_all_variables()
step = []
costt = []
#Launch the graph
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
for (x,y) in zip(train_X,train_Y):
sess.run(optimizer, feed_dict={X:x, Y:y})
if training_epochs%display_step == 0:
step.append(epoch)
costt.append(sess.run(cost, feed_dict={X:train_X, Y:train_Y}))
print('epoch: %04d'%(epoch+1),'cost=','{:.9f}'.format(sess.run(cost, feed_dict={X:train_X, Y:train_Y})), 'W=',sess.run(W),'b=', sess.run(b))
print('Optimization Finished!')
print('cost = ',sess.run(cost,feed_dict={X:train_X, Y:train_Y}),'W=',sess.run(W),'b=',sess.run(b))
fig = plt.figure()
fig1 = fig.add_subplot(121)
fig1.plot(train_X, train_Y, 'ro', label='Original data')
fig1.plot(train_X, sess.run(W)*train_X+sess.run(b),label='Fitted line')
fig1.legend()
fig2 = fig.add_subplot(122)
fig2.plot(step,costt)
plt.show()
<file_sep>/mnist/mnist_inference.py
# -*- coding:utf-8 -*-
import tensorflow as tf
INPUT_NODE = 784
OUTPUT_NODE = 10
LAYER1_NODE = 500
def get_weight_variable(shape, regularizer):
weights = tf.get_variable('weights',shape,initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None:
tf.add_to_collection('losses', regularizer(weights))
return weights
def inference(input_tensor, regularizer, reuse=False):
with tf.variable_scope('layer1',reuse=reuse):
weights = get_weight_variable([INPUT_NODE,LAYER1_NODE],regularizer)
biases = tf.get_variable('biases',shape=[LAYER1_NODE], initializer=tf.constant_initializer(0.0))
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)
with tf.variable_scope('layer2', reuse=reuse):
weights = get_weight_variable([LAYER1_NODE,OUTPUT_NODE],regularizer)
biases = tf.get_variable('biases',shape=[OUTPUT_NODE], initializer=tf.constant_initializer(0.0))
layer2 = tf.matmul(layer1, weights) + biases
return layer2
<file_sep>/Logistic regression.py
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#Parameters
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1
#tf Graph Input
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None,10])
#set model weights
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
#Construct model
pred = tf.nn.softmax(tf.multiply(W, x)+b)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred)), reduction_indices=1)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples/batch_size)
for i in range(batch_size):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(optimizer)
c = sess.run(cost, feed_dict={x:batch_xs, y:batch_ys})
avg_cost += c/total_batch
if (epoch+1)%display_step == 0:
print('epoch:','%04d'%(epoch+1),'cost=','{:.9f}'.format(avg_cost))
print('Optimization Finished!')
correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', accuracy)
<file_sep>/mnist/mnist_nn.py
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt
#MNIST数据集相关的常数
INPUT_NODE = 784
OUTPUT_NODE = 10
#配置神经网络参数0
LAYER1_NODE = 500
BATCH_SIZE = 100
LEARNNING_RATE_BASE = 0.8
LEARNNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001
TRAINING_STEPS = 1000
MOVING_AVERAGE_DECAY = 0.99
#辅助函数,给定神经网络所需参数,返回输出
def inference(input_tensor, avg_class, reuse=False):
if avg_class == None:
with tf.variable_scope('layer1',reuse=reuse):
weights = tf.get_variable('weights',[INPUT_NODE, LAYER1_NODE], initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable('biases',[LAYER1_NODE],initializer=tf.constant_initializer(0.0))
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights)+biases)
with tf.variable_scope('layer2',reuse=reuse):
weights = tf.get_variable('weights',[LAYER1_NODE,OUTPUT_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable('biases',[OUTPUT_NODE],initializer=tf.constant_initializer(0.0))
layer2 = tf.matmul(layer1, weights)+biases
return layer2
else:
with tf.variable_scope('layer1',reuse=reuse):
weights = tf.get_variable('weights',[INPUT_NODE, LAYER1_NODE], initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable('biases',[LAYER1_NODE],initializer=tf.constant_initializer(0.0))
layer1 = tf.nn.relu(tf.matmul(input_tensor, avg_class.average(weights))+avg_class.average(biases))
with tf.variable_scope('layer2',reuse=reuse):
weights = tf.get_variable('weights',[LAYER1_NODE,OUTPUT_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))
biases = tf.get_variable('biases',[OUTPUT_NODE],initializer=tf.constant_initializer(0.0))
layer2 = tf.matmul(layer1, avg_class.average(weights))+avg_class.average(biases)
return layer2
#训练模型过程
def train(mnist):
accuracy_plot = []
x_label = []
x = tf.placeholder(tf.float32, shape=(None, INPUT_NODE), name='x-input')
y_ = tf.placeholder(tf.float32, shape=(None,OUTPUT_NODE), name = 'y-output')
y = inference(x,None)
global_step = tf.Variable(0, trainable=False)
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
variable_averages_op = variable_averages.apply(tf.trainable_variables())
average_y = inference(x,variable_averages,reuse=True)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y,labels=y_)
cross_entropy_mean = tf.reduce_mean(cross_entropy)
regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
with tf.variable_scope('',reuse=True):
regularization = regularizer(tf.get_variable('layer1/weights')) + regularizer(tf.get_variable('layer2/weights'))
loss = cross_entropy_mean + regularization
learning_rate = tf.train.exponential_decay(LEARNNING_RATE_BASE, global_step,mnist.train.num_examples/BATCH_SIZE,
LEARNNING_RATE_DECAY)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
train_op = tf.group(train_step, variable_averages_op)
correct_prediction = tf.equal(tf.argmax(average_y,1),tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init = tf.initialize_all_variables()
with tf.Session() as sess:
sess.run(init)
validate_feed = {x:mnist.validation.images,y_:mnist.validation.labels}
test_feed = {x:mnist.test.images,y_:mnist.test.labels}
for i in range(TRAINING_STEPS):
if i%10 == 0:
validate_acc = sess.run(accuracy, feed_dict=validate_feed)
print('After %d training step(s),accuracy of model is %.4f'%(i,validate_acc))
x_label.append(i)
accuracy_plot.append(validate_acc)
xs,ys = mnist.train.next_batch(BATCH_SIZE)
sess.run(train_op, feed_dict={x:xs,y_:ys})
test_acc = sess.run(accuracy,feed_dict=test_feed)
print('After %d training step(s),test accuracy is %.4f'%(TRAINING_STEPS,test_acc))
fig = plt.figure()
plt.plot(x_label, accuracy_plot,'r',label='Accuracy curve')
plt.xlabel('Iterations')
plt.ylabel('Accuracy')
plt.grid()
plt.legend()
plt.show()
def main(argv=None):
mnist = input_data.read_data_sets('MNIST_data/',one_hot=True)
train(mnist)
if __name__ == '__main__':
tf.app.run() | 608f162ffa6ae154aaeaa08f145216830ac9f841 | [
"Markdown",
"Python"
] | 5 | Markdown | kmustyxl/tensorflow_learn | 37c9f7e878c7cfae08db6b946ee7b7f580956833 | ebb9634072e0c95a8699ea6a2f5926f529722153 |
refs/heads/master | <repo_name>margordn/Oil-Patterns-on-Bowling-Lanes<file_sep>/margordn_presentationcode.py
GlowScript 2.7 VPython
#create lane
lane = box(pos=vec(11.5,0,-(.167/2+.10915)), size=vec(23,1,.167), color=color.orange)
#initialize ball
bowlingBall = sphere(pos=vec(0,0,0), radius=.10915, mass=7.27, color=color.purple, texture=textures.earth) #mass and radius copied from tjhsst study
#initialize gutters
gutter1 = box(pos=vec(11.5,.5,-(.167/2+.10915)), size=vec(23,0.23495,0.167), color= color.white) #width found on wiki
gutter2 = box(pos=vec(11.5,-.5,-(.167/2+.10915)), size=vec(23,0.23495,.167), color= color.white)
#set "pin" locations
pin1 = sphere(pos=vec(20,0, 0), radius=.0605) #radius from wikipedia; center of first pin is 60ft from where ball is released
rowDist = .30 * sqrt(3)/2
pin2 = sphere(pos=vec(20+rowDist,.30/2,0), radius=.0605)
pin3 = sphere(pos=vec(20+rowDist,-.30/2,0), radius=.0605)
pin4 = sphere(pos=vec(20+2*rowDist,.30,0), radius=.0605)
pin5 = sphere(pos=vec(20+2*rowDist,0, 0), radius=.0605)
pin6 = sphere(pos=vec(20+2*rowDist,-.30,0), radius=.0605)
pin7 = sphere(pos=vec(20+3*rowDist,3*.30/2,0), radius=.0605)
pin8 = sphere(pos=vec(20+3*rowDist,-.30/2,0), radius=.0605)
pin9 = sphere(pos=vec(20+3*rowDist,.30/2,0), radius=.0605)
pin10 = sphere(pos=vec(20+3*rowDist,-3*.30/2,0), radius=.0605)
def check_pins():
if ((bowlingBall.pos.x <= (pin1.pos.x + pin1.radius)) and (bowlingBall.pos.x >= (pin1.pos.x - pin1.radius))):
if ((bowlingBall.pos.y >= pin1.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin1.pos.y + bowlingBall.radius)):
print("Pin 1 hit!")
if ((bowlingBall.pos.x <= (pin2.pos.x + pin1.radius)) and (bowlingBall.pos.x >= (pin2.pos.x - pin1.radius))):
if ((bowlingBall.pos.y >= pin2.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin2.pos.y + bowlingBall.radius)):
print("Pin 2 hit!")
if ((bowlingBall.pos.y >= pin3.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin3.pos.y + bowlingBall.radius)):
print("Pin 3 hit!")
if ((bowlingBall.pos.x <= (pin4.pos.x + pin1.radius)) and (bowlingBall.pos.x >= (pin4.pos.x - pin1.radius))):
if ((bowlingBall.pos.y >= pin4.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin4.pos.y + bowlingBall.radius)):
print("Pin 4 hit!")
if ((bowlingBall.pos.y >= pin5.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin5.pos.y + bowlingBall.radius)):
print("Pin 5 hit!")
pin = 5
if ((bowlingBall.pos.y >= pin6.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin6.pos.y + bowlingBall.radius)):
print("Pin 6 hit!")
if ((bowlingBall.pos.x <= (pin7.pos.x + pin1.radius)) and (bowlingBall.pos.x >= (pin7.pos.x - pin1.radius))):
if ((bowlingBall.pos.y >= pin7.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin7.pos.y + bowlingBall.radius)):
print("Pin 7 hit!")
if ((bowlingBall.pos.y >= pin8.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin8.pos.y + bowlingBall.radius)):
print("Pin 8 hit!")
if ((bowlingBall.pos.y >= pin9.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin9.pos.y + bowlingBall.radius)):
print("Pin 9 hit!")
if ((bowlingBall.pos.y >= pin10.pos.y - bowlingBall.radius) and (bowlingBall.pos.y <= pin10.pos.y + bowlingBall.radius)):
print("Pin 10 hit!")
def check_gutter():
fallsIntoGutter = False
if ((bowlingBall.pos.y > .5) or (bowlingBall.pos.y < -.5)):
print("Gutter ball!")
fallsIntoGutter = True
return fallsIntoGutter
#Tower of Pisa pattern
def getOilAndCOF():
#segmented into 37 unit widths
widSeg = lane.size.y / 37
#dark blue of pattern
if ((bowlingBall.pos.x < (25/3)) and (bowlingBall.pos.y > - ((37/2-9) * widSeg)) and (bowlingBall.pos.y < ((37/2-130) * widSeg))):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
else if ((bowlingBall.pos.x < (22.5/3)) and (bowlingBall.pos.y > - ((37/2-8) * widSeg)) and (bowlingBall.pos.y < ((37/2-11) * widSeg))):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
else if ((bowlingBall.pos.x < (20/3)) and (bowlingBall.pos.y > - ((37/2-7) * widSeg)) and (bowlingBall.pos.y < ((37/2-9) * widSeg))):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
else if ((bowlingBall.pos.x < (15/3)) and (bowlingBall.pos.y > - ((37/2-6) * widSeg)) and (bowlingBall.pos.y < ((37/2-7) * widSeg))):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
else if ((bowlingBall.pos.x < (10/3)) and (bowlingBall.pos.y > - ((37/2-5) * widSeg)) and (bowlingBall.pos.y < ((37/2-5) * widSeg))):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
else if (bowlingBall.pos.x < (8/3)):
lane.color = color.red
u = .04 #lowest COF is when there is most oil
#mid blue of pattern
else if (bowlingBall.pos.x < (10/3)):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (12.5/3)) and (bowlingBall.pos.y > - ((37/2-5) * widSeg)) and (bowlingBall.pos.y < ((37/2-5) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (17.5/3)) and (bowlingBall.pos.y > - ((37/2-6) * widSeg)) and (bowlingBall.pos.y < ((37/2-6) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (20/3)) and (bowlingBall.pos.y > - ((37/2-7) * widSeg)) and (bowlingBall.pos.y < ((37/2-7) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (22.5/3)) and (bowlingBall.pos.y > - ((37/2-8) * widSeg)) and (bowlingBall.pos.y < ((37/2-8) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (29/3)) and (bowlingBall.pos.y > - ((37/2-9) * widSeg)) and (bowlingBall.pos.y < ((37/2-12) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
else if ((bowlingBall.pos.x < (32/3)) and (bowlingBall.pos.y > - ((37/2-10) * widSeg)) and (bowlingBall.pos.y < ((37/2-14) * widSeg))):
lane.color = color.orange
u = .06 #mid COF
#light blue of pattern
else:
lane.color = color.yellow
u = .08 #higher COF for minimal oil
#u = 1.5 * u
#after 40 ft there is NO oil
if (bowlingBall.pos.x > (40/3)):
lane.color = color.magenta
u = .12 #highest COF is when there is no oil
return u
attach_trail(bowlingBall)
t = 0
dt = .01
bowlingBall.vel = vec(9,-.5,0)
vCP = bowlingBall.vel
bowlingBall.w = vec(-(50**.5), 50**.5, 0)
bowlingBall.I = .035
angle = 0 #angle between vCP and vel
b_angle = 0 #axis tilt angle
c_angle = 0 #axis rotation angle
l = bowlingBall.I * bowlingBall.w
_radius = vec(0,0,-bowlingBall.radius)
temp = 0 #initializing to be immediately altered by while loop
while ((t < 10) and (bowlingBall.pos.x < 23)):
rate(100)
check_pins()
oilu = getOilAndCOF()
if (check_gutter()):
t = 10 #exits while loop
temp = mag(bowlingBall.w * bowlingBall.radius)
angle = mag(bowlingBall.vel)**2 + 2*temp*mag(bowlingBall.vel)*cos(b_angle)*sin(c_angle) + (temp*cos(b_angle))**2
angle = angle**-1
angle = angle * (temp * cos(b_angle) * cos(c_angle))
#simplified but similar to true Frictional Force as in lower oilu resultis in lower FrictionaForce
tanVel = vec(norm(bowlingBall.vel).y, norm(bowlingBall.vel).x, norm(bowlingBall.vel).z)
vCP = mag(vCP) * (-cos(angle)*tanVel + sin(angle)*norm(bowlingBall.vel))
print("vCP: " + vCP)
FrictionalForce = (oilu * bowlingBall.mass * 9.81) * -vCP / (mag(vCP))
torque = cross(_radius, FrictionalForce)
l = l + torque * dt
bowlingBall.w = l / bowlingBall.I
b_angle = (bowlingBall.w.y) * dt
c_angle = (bowlingBall.w.z) * dt
#slipping (happens first)
if (abs(mag(bowlingBall.vel - vCP)) < .1):
print("slipping")
bowlingBall.vel = bowlingBall.vel - FrictionalForce * dt / bowlingBall.mass
#rolling (happens last)
else if ((bowlingBall.vel + cross(bowlingBall.w, _radius)) == vec(0,0,0)):
print("rolling")
bowlingBall.vel = cross(bowlingBall.w, _radius)
#rolling and slipping (happens in between slipping and rolling and is the HOOK)
else:
#print("hooking")
bowlingBall.vel = bowlingBall.vel + (FrictionalForce / bowlingBall.mass) * dt
bowlingBall.pos = bowlingBall.pos + bowlingBall.vel * dt
t = t + dt
print("done")
| 5d359af31478facbb40f58414957b46dd39fc4f3 | [
"Python"
] | 1 | Python | margordn/Oil-Patterns-on-Bowling-Lanes | bdafa19be666a21e31ac3b4ec1d1efa55e862433 | c7ca62da35ff7a72b0d8d5d3372a431afd8f5276 |
refs/heads/master | <file_sep>#region Header
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sandbox.ModAPI.Ingame;
using Sandbox.ModAPI.Interfaces;
using SpaceEngineers.Game.ModAPI;
using SpaceEngineers.Game.ModAPI.Ingame;
using VRage;
using VRage.Game.ModAPI.Ingame;
using VRageMath;
namespace SpaceEngineersScripting
{
public class Wrapper
{
static void Main()
{
new CodeEditorEmulator().Main ("");
}
}
class CodeEditorEmulator : Sandbox.ModAPI.Ingame.MyGridProgram
{
#endregion
#region CodeEditor
//Configuration
//--------------------
const string
nameController = "Remote Control";
const double
//angle between gravity and thrust direction that causes it to disable
angleSafetyCutoff = 120.0 * (Math.PI / 180.0);
//Definitions
//--------------------
//Opcodes for use as arguments
//-commands may be issued directly
const string
command_Initialise = "Init"; //args: <none>
//Utility definitions
static Vector3D GridToWorld(Vector3I gridVector, IMyCubeGrid grid){
//convert a grid vector for the specified grid into a world direction vector
return Vector3D.Subtract (
grid.GridIntegerToWorld (gridVector),
grid.GridIntegerToWorld (Vector3I.Zero) );
}
static readonly double
safetyCutoff = Math.Cos(angleSafetyCutoff);
//Internal Types
//--------------------
public struct Status
{
//program data not persistent across restarts
public bool
initialised;
//configuration constants
private const char
delimiter = ';';
//Operations
public void Initialise(){ //data setup
//no data persistent across restarts
}
public string Store()
{
return "";
}
public bool TryRestore(string storage)
{
string[] elements = storage.Split(delimiter);
return
(elements.Length == 1)
&& elements[0] == "";
}
}
//Global variables
//--------------------
bool restarted = true;
Status status;
IMyShipController controller;
List<IMyTerminalBlock> temp = new List<IMyTerminalBlock>();
//Program
//--------------------
public void Main(string argument)
{
//First ensure the system is able to process commands
//-if necessary, perform first time setup
//-if necessary or requested, initialise the system
// >otherwise, check that the setup is still valid
if (restarted) {
//script has been reloaded
//-may be first time running
//-world may have been reloaded (or script recompiled)
if (Storage == null) {
//use default values
status.Initialise();
} else {
//attempt to restore saved values
// -otherwise use defaults
Echo ("restoring saved state...");
if ( !status.TryRestore(Storage) ){
Echo ("restoration failed.");
status.Initialise();
}
}
status.initialised = false; //we are not initialised after restart
Storage = null; //will be resaved iff initialisation is successful
restarted = false;
}
if ( !status.initialised || argument == command_Initialise) {
//if we cannot initialise, end here
if ( !Initialise() )
return;
}
else if ( !Validate() ) {
//if saved state is not valid, try re-initialising
//if we cannot initialise, end here
if ( !Initialise() )
return;
}
//Perform main processing
Update ();
//Save current status
Storage = status.Store();
Echo (Storage);
}
private void Update(){
//-Prepare data
// >get local gravity vector
// >normalise vector to simplify angle calculation
Vector3D
worldGravity = controller.GetNaturalGravity ();
worldGravity.Normalize();
//Check each thruster to see if it is safe to enable
//-only check thrusters on our grid
//-check that we have access to the thruster
//-disable any that are pointing down
// >(with safetyCutoff tolerance)
// >enable any others
GridTerminalSystem.GetBlocksOfType<IMyThrust>(temp);
int count = 0;
for (int i=0; i<temp.Count; i++) {
IMyThrust thruster = (IMyThrust)temp[i];
if (thruster.CubeGrid != controller.CubeGrid)
continue;
count++;
//Check if we can actually use the thruster
if ( ValidateBlock (thruster, callbackRequired: false) ) {
Vector3D
worldThruster = GridToWorld (
Base6Directions.GetIntVector(thruster.Orientation.Forward),
thruster.CubeGrid);
//Compare the dot product of gravity and thrust direction (normalised)
// 1.0 => 0 degrees
// 0.0 => 90 degrees
//-1.0 => 180 degrees
//safe iff angle <= safetyCutoffAngle
//=> safe iff dot product >= cos(safetyCutoffAngle)
bool
safe = Vector3D.Dot(worldGravity, worldThruster) >= safetyCutoff * worldThruster.Length();
if (thruster.Enabled != safe)
thruster.RequestEnable (safe);
}
} //end for
Echo(temp.Count.ToString() +" thrusters found.");
Echo(count.ToString() +" processed.");
}
private bool Initialise()
{
status.initialised = false;
Echo ("initialising...");
//Find Controller
controller = null;
GridTerminalSystem.GetBlocksOfType<IMyShipController> (temp);
for (int i=0; i < temp.Count; i++){
if (temp[i].CustomName == nameController) {
if (controller == null) {
controller = (IMyShipController)temp[i];
} else {
Echo ("ERROR: duplicate name \"" +nameController +"\"");
return false;
}
}
}
//verify that the Controller was found
if (controller == null) {
Echo ("ERROR: block not found \"" +nameController +"\"");
return false;
}
//validate that the Controller is operable
if ( ! ValidateBlock (controller, callbackRequired:false) ) return false;
status.initialised = true;
Echo ("Initialisation completed with no errors.");
return true;
}
private bool ValidateBlock(IMyTerminalBlock block, bool callbackRequired=true)
{
//check for block deletion?
//check that we have required permissions to control the block
if ( ! Me.HasPlayerAccess(block.OwnerId) ) {
Echo ("ERROR: no permissions for \"" +block.CustomName +"\"");
return false;
}
//check that the block has required permissions to make callbacks
if ( callbackRequired && !block.HasPlayerAccess(Me.OwnerId) ) {
Echo ("ERROR: no permissions on \"" +block.CustomName +"\"");
return false;
}
//check that block is functional
if (!block.IsFunctional) {
Echo ("ERROR: non-functional block \"" +block.CustomName +"\"");
return false;
}
return true;
}
private bool Validate(){
bool valid =
ValidateBlock (controller, callbackRequired: false);
if ( !valid ) {
Echo ("Validation of saved blocks failed.");
}
return valid;
}
#endregion
#region footer
}
}
#endregion<file_sep># SE_ThrusterSafety
Space Engineers: Disables thusters providing thrust in the same direction as natural gravity.
> This project is configured to be built within a separate IDE to allow for error checking, code completion etc..
> Only the section in `#region CodeEditor` should be copied into the Space Engineers editor. This region has been automatically extracted into the corresponding `txt` file.
##Description
Determines whether a thruster should be enabled by checking it's orientation compared to natural gravity.
+ checks all thrusters on the same grid as the configured Remote Control
+ compares angle to a configured cutoff angle
- relative to local natural gravity
- accounting for ship orientation
+ enables thrusters within the safe range
+ disables thusters outside the safe range
##Hardware
| Block(s) | number | Configurable |
| ------------- | ------------- | ------------- |
| Ship Controller | single | by name constant
| Thrusters | [all] | no*
*but limited by the algorithm to those on the same grid as the Remote Control
##Configuration
+ `nameController`: the name of the Remote Control used to identify the main grid and get local gravity
+ `angleSafetyCutoff`: the angle from gravity above which thrusters will be disabled (in radians)
##Standard Blocks
+ `ValidateBlock()`: check that found blocks are usable
+ Status/Initialise/Validate framework | d7ff4b3ab6eadea10232881a793cd489c4602589 | [
"Markdown",
"C#"
] | 2 | C# | darkthing41/SE_ThrusterSafety | 18ff42cb3893344ab7c5948f447af052239966ea | 9e520076522cd5c0731941ab3600f9459c49f7f9 |
refs/heads/master | <file_sep>[package]
name = "libsodium-sys"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
[dependencies]
[build-dependencies]
cc = { version = "1.0", features = ["parallel"] }
<file_sep>#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
pub const SODIUM_VERSION_STRING: &'static [u8; 7usize] = b"1.0.16\0";
pub const SODIUM_LIBRARY_VERSION_MAJOR: u32 = 10;
pub const SODIUM_LIBRARY_VERSION_MINOR: u32 = 1;
pub const crypto_aead_aes256gcm_KEYBYTES: u32 = 32;
pub const crypto_aead_aes256gcm_NSECBYTES: u32 = 0;
pub const crypto_aead_aes256gcm_NPUBBYTES: u32 = 12;
pub const crypto_aead_aes256gcm_ABYTES: u32 = 16;
pub const crypto_aead_chacha20poly1305_ietf_KEYBYTES: u32 = 32;
pub const crypto_aead_chacha20poly1305_ietf_NSECBYTES: u32 = 0;
pub const crypto_aead_chacha20poly1305_ietf_NPUBBYTES: u32 = 12;
pub const crypto_aead_chacha20poly1305_ietf_ABYTES: u32 = 16;
pub const crypto_aead_chacha20poly1305_KEYBYTES: u32 = 32;
pub const crypto_aead_chacha20poly1305_NSECBYTES: u32 = 0;
pub const crypto_aead_chacha20poly1305_NPUBBYTES: u32 = 8;
pub const crypto_aead_chacha20poly1305_ABYTES: u32 = 16;
pub const crypto_aead_chacha20poly1305_IETF_KEYBYTES: u32 = 32;
pub const crypto_aead_chacha20poly1305_IETF_NSECBYTES: u32 = 0;
pub const crypto_aead_chacha20poly1305_IETF_NPUBBYTES: u32 = 12;
pub const crypto_aead_chacha20poly1305_IETF_ABYTES: u32 = 16;
pub const crypto_aead_xchacha20poly1305_ietf_KEYBYTES: u32 = 32;
pub const crypto_aead_xchacha20poly1305_ietf_NSECBYTES: u32 = 0;
pub const crypto_aead_xchacha20poly1305_ietf_NPUBBYTES: u32 = 24;
pub const crypto_aead_xchacha20poly1305_ietf_ABYTES: u32 = 16;
pub const crypto_aead_xchacha20poly1305_IETF_KEYBYTES: u32 = 32;
pub const crypto_aead_xchacha20poly1305_IETF_NSECBYTES: u32 = 0;
pub const crypto_aead_xchacha20poly1305_IETF_NPUBBYTES: u32 = 24;
pub const crypto_aead_xchacha20poly1305_IETF_ABYTES: u32 = 16;
pub const _STDINT_H: u32 = 1;
pub const _FEATURES_H: u32 = 1;
pub const _DEFAULT_SOURCE: u32 = 1;
pub const __USE_ISOC11: u32 = 1;
pub const __USE_ISOC99: u32 = 1;
pub const __USE_ISOC95: u32 = 1;
pub const __USE_POSIX_IMPLICITLY: u32 = 1;
pub const _POSIX_SOURCE: u32 = 1;
pub const _POSIX_C_SOURCE: u32 = 200809;
pub const __USE_POSIX: u32 = 1;
pub const __USE_POSIX2: u32 = 1;
pub const __USE_POSIX199309: u32 = 1;
pub const __USE_POSIX199506: u32 = 1;
pub const __USE_XOPEN2K: u32 = 1;
pub const __USE_XOPEN2K8: u32 = 1;
pub const _ATFILE_SOURCE: u32 = 1;
pub const __USE_MISC: u32 = 1;
pub const __USE_ATFILE: u32 = 1;
pub const __USE_FORTIFY_LEVEL: u32 = 0;
pub const __GLIBC_USE_DEPRECATED_GETS: u32 = 0;
pub const _STDC_PREDEF_H: u32 = 1;
pub const __STDC_IEC_559__: u32 = 1;
pub const __STDC_IEC_559_COMPLEX__: u32 = 1;
pub const __STDC_ISO_10646__: u32 = 201706;
pub const __STDC_NO_THREADS__: u32 = 1;
pub const __GNU_LIBRARY__: u32 = 6;
pub const __GLIBC__: u32 = 2;
pub const __GLIBC_MINOR__: u32 = 27;
pub const _SYS_CDEFS_H: u32 = 1;
pub const __glibc_c99_flexarr_available: u32 = 1;
pub const __WORDSIZE: u32 = 64;
pub const __WORDSIZE_TIME64_COMPAT32: u32 = 1;
pub const __SYSCALL_WORDSIZE: u32 = 64;
pub const __HAVE_GENERIC_SELECTION: u32 = 1;
pub const __GLIBC_USE_LIB_EXT2: u32 = 0;
pub const __GLIBC_USE_IEC_60559_BFP_EXT: u32 = 0;
pub const __GLIBC_USE_IEC_60559_FUNCS_EXT: u32 = 0;
pub const __GLIBC_USE_IEC_60559_TYPES_EXT: u32 = 0;
pub const _BITS_TYPES_H: u32 = 1;
pub const _BITS_TYPESIZES_H: u32 = 1;
pub const __OFF_T_MATCHES_OFF64_T: u32 = 1;
pub const __INO_T_MATCHES_INO64_T: u32 = 1;
pub const __RLIM_T_MATCHES_RLIM64_T: u32 = 1;
pub const __FD_SETSIZE: u32 = 1024;
pub const _BITS_WCHAR_H: u32 = 1;
pub const _BITS_STDINT_INTN_H: u32 = 1;
pub const _BITS_STDINT_UINTN_H: u32 = 1;
pub const INT8_MIN: i32 = -128;
pub const INT16_MIN: i32 = -32768;
pub const INT32_MIN: i32 = -2147483648;
pub const INT8_MAX: u32 = 127;
pub const INT16_MAX: u32 = 32767;
pub const INT32_MAX: u32 = 2147483647;
pub const UINT8_MAX: u32 = 255;
pub const UINT16_MAX: u32 = 65535;
pub const UINT32_MAX: u32 = 4294967295;
pub const INT_LEAST8_MIN: i32 = -128;
pub const INT_LEAST16_MIN: i32 = -32768;
pub const INT_LEAST32_MIN: i32 = -2147483648;
pub const INT_LEAST8_MAX: u32 = 127;
pub const INT_LEAST16_MAX: u32 = 32767;
pub const INT_LEAST32_MAX: u32 = 2147483647;
pub const UINT_LEAST8_MAX: u32 = 255;
pub const UINT_LEAST16_MAX: u32 = 65535;
pub const UINT_LEAST32_MAX: u32 = 4294967295;
pub const INT_FAST8_MIN: i32 = -128;
pub const INT_FAST16_MIN: i64 = -9223372036854775808;
pub const INT_FAST32_MIN: i64 = -9223372036854775808;
pub const INT_FAST8_MAX: u32 = 127;
pub const INT_FAST16_MAX: u64 = 9223372036854775807;
pub const INT_FAST32_MAX: u64 = 9223372036854775807;
pub const UINT_FAST8_MAX: u32 = 255;
pub const UINT_FAST16_MAX: i32 = -1;
pub const UINT_FAST32_MAX: i32 = -1;
pub const INTPTR_MIN: i64 = -9223372036854775808;
pub const INTPTR_MAX: u64 = 9223372036854775807;
pub const UINTPTR_MAX: i32 = -1;
pub const PTRDIFF_MIN: i64 = -9223372036854775808;
pub const PTRDIFF_MAX: u64 = 9223372036854775807;
pub const SIG_ATOMIC_MIN: i32 = -2147483648;
pub const SIG_ATOMIC_MAX: u32 = 2147483647;
pub const SIZE_MAX: i32 = -1;
pub const WINT_MIN: u32 = 0;
pub const WINT_MAX: u32 = 4294967295;
pub const _STDLIB_H: u32 = 1;
pub const WNOHANG: u32 = 1;
pub const WUNTRACED: u32 = 2;
pub const WSTOPPED: u32 = 2;
pub const WEXITED: u32 = 4;
pub const WCONTINUED: u32 = 8;
pub const WNOWAIT: u32 = 16777216;
pub const __WNOTHREAD: u32 = 536870912;
pub const __WALL: u32 = 1073741824;
pub const __WCLONE: u32 = 2147483648;
pub const __W_CONTINUED: u32 = 65535;
pub const __WCOREFLAG: u32 = 128;
pub const __HAVE_FLOAT128: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT128: u32 = 0;
pub const __HAVE_FLOAT64X: u32 = 1;
pub const __HAVE_FLOAT64X_LONG_DOUBLE: u32 = 1;
pub const __HAVE_FLOAT16: u32 = 0;
pub const __HAVE_FLOAT32: u32 = 1;
pub const __HAVE_FLOAT64: u32 = 1;
pub const __HAVE_FLOAT32X: u32 = 1;
pub const __HAVE_FLOAT128X: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT16: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT32: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT64: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT32X: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT64X: u32 = 0;
pub const __HAVE_DISTINCT_FLOAT128X: u32 = 0;
pub const __HAVE_FLOATN_NOT_TYPEDEF: u32 = 0;
pub const __ldiv_t_defined: u32 = 1;
pub const __lldiv_t_defined: u32 = 1;
pub const RAND_MAX: u32 = 2147483647;
pub const EXIT_FAILURE: u32 = 1;
pub const EXIT_SUCCESS: u32 = 0;
pub const _SYS_TYPES_H: u32 = 1;
pub const __clock_t_defined: u32 = 1;
pub const __clockid_t_defined: u32 = 1;
pub const __time_t_defined: u32 = 1;
pub const __timer_t_defined: u32 = 1;
pub const __BIT_TYPES_DEFINED__: u32 = 1;
pub const _ENDIAN_H: u32 = 1;
pub const __LITTLE_ENDIAN: u32 = 1234;
pub const __BIG_ENDIAN: u32 = 4321;
pub const __PDP_ENDIAN: u32 = 3412;
pub const __BYTE_ORDER: u32 = 1234;
pub const __FLOAT_WORD_ORDER: u32 = 1234;
pub const LITTLE_ENDIAN: u32 = 1234;
pub const BIG_ENDIAN: u32 = 4321;
pub const PDP_ENDIAN: u32 = 3412;
pub const BYTE_ORDER: u32 = 1234;
pub const _BITS_BYTESWAP_H: u32 = 1;
pub const _BITS_UINTN_IDENTITY_H: u32 = 1;
pub const _SYS_SELECT_H: u32 = 1;
pub const __FD_ZERO_STOS: &'static [u8; 6usize] = b"stosq\0";
pub const __sigset_t_defined: u32 = 1;
pub const __timeval_defined: u32 = 1;
pub const __timespec_defined: u32 = 1;
pub const FD_SETSIZE: u32 = 1024;
pub const _SYS_SYSMACROS_H: u32 = 1;
pub const _BITS_SYSMACROS_H: u32 = 1;
pub const _BITS_PTHREADTYPES_COMMON_H: u32 = 1;
pub const _THREAD_SHARED_TYPES_H: u32 = 1;
pub const _BITS_PTHREADTYPES_ARCH_H: u32 = 1;
pub const __SIZEOF_PTHREAD_MUTEX_T: u32 = 40;
pub const __SIZEOF_PTHREAD_ATTR_T: u32 = 56;
pub const __SIZEOF_PTHREAD_RWLOCK_T: u32 = 56;
pub const __SIZEOF_PTHREAD_BARRIER_T: u32 = 32;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T: u32 = 4;
pub const __SIZEOF_PTHREAD_COND_T: u32 = 48;
pub const __SIZEOF_PTHREAD_CONDATTR_T: u32 = 4;
pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: u32 = 8;
pub const __SIZEOF_PTHREAD_BARRIERATTR_T: u32 = 4;
pub const __PTHREAD_MUTEX_LOCK_ELISION: u32 = 1;
pub const __PTHREAD_MUTEX_NUSERS_AFTER_KIND: u32 = 0;
pub const __PTHREAD_MUTEX_USE_UNION: u32 = 0;
pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED: u32 = 1;
pub const __PTHREAD_MUTEX_HAVE_PREV: u32 = 1;
pub const __have_pthread_attr_t: u32 = 1;
pub const _ALLOCA_H: u32 = 1;
pub const crypto_hash_sha512_BYTES: u32 = 64;
pub const crypto_auth_hmacsha512_BYTES: u32 = 64;
pub const crypto_auth_hmacsha512_KEYBYTES: u32 = 32;
pub const crypto_auth_hmacsha512256_BYTES: u32 = 32;
pub const crypto_auth_hmacsha512256_KEYBYTES: u32 = 32;
pub const crypto_auth_BYTES: u32 = 32;
pub const crypto_auth_KEYBYTES: u32 = 32;
pub const crypto_auth_PRIMITIVE: &'static [u8; 14usize] = b"hmacsha512256\0";
pub const crypto_hash_sha256_BYTES: u32 = 32;
pub const crypto_auth_hmacsha256_BYTES: u32 = 32;
pub const crypto_auth_hmacsha256_KEYBYTES: u32 = 32;
pub const crypto_stream_xsalsa20_KEYBYTES: u32 = 32;
pub const crypto_stream_xsalsa20_NONCEBYTES: u32 = 24;
pub const crypto_box_curve25519xsalsa20poly1305_SEEDBYTES: u32 = 32;
pub const crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES: u32 = 32;
pub const crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES: u32 = 32;
pub const crypto_box_curve25519xsalsa20poly1305_BEFORENMBYTES: u32 = 32;
pub const crypto_box_curve25519xsalsa20poly1305_NONCEBYTES: u32 = 24;
pub const crypto_box_curve25519xsalsa20poly1305_MACBYTES: u32 = 16;
pub const crypto_box_curve25519xsalsa20poly1305_BOXZEROBYTES: u32 = 16;
pub const crypto_box_curve25519xsalsa20poly1305_ZEROBYTES: u32 = 32;
pub const crypto_box_SEEDBYTES: u32 = 32;
pub const crypto_box_PUBLICKEYBYTES: u32 = 32;
pub const crypto_box_SECRETKEYBYTES: u32 = 32;
pub const crypto_box_NONCEBYTES: u32 = 24;
pub const crypto_box_MACBYTES: u32 = 16;
pub const crypto_box_PRIMITIVE: &'static [u8; 27usize] = b"curve25519xsalsa20poly1305\0";
pub const crypto_box_BEFORENMBYTES: u32 = 32;
pub const crypto_box_SEALBYTES: u32 = 48;
pub const crypto_box_ZEROBYTES: u32 = 32;
pub const crypto_box_BOXZEROBYTES: u32 = 16;
pub const crypto_core_hsalsa20_OUTPUTBYTES: u32 = 32;
pub const crypto_core_hsalsa20_INPUTBYTES: u32 = 16;
pub const crypto_core_hsalsa20_KEYBYTES: u32 = 32;
pub const crypto_core_hsalsa20_CONSTBYTES: u32 = 16;
pub const crypto_core_hchacha20_OUTPUTBYTES: u32 = 32;
pub const crypto_core_hchacha20_INPUTBYTES: u32 = 16;
pub const crypto_core_hchacha20_KEYBYTES: u32 = 32;
pub const crypto_core_hchacha20_CONSTBYTES: u32 = 16;
pub const crypto_core_salsa20_OUTPUTBYTES: u32 = 64;
pub const crypto_core_salsa20_INPUTBYTES: u32 = 16;
pub const crypto_core_salsa20_KEYBYTES: u32 = 32;
pub const crypto_core_salsa20_CONSTBYTES: u32 = 16;
pub const crypto_core_salsa2012_OUTPUTBYTES: u32 = 64;
pub const crypto_core_salsa2012_INPUTBYTES: u32 = 16;
pub const crypto_core_salsa2012_KEYBYTES: u32 = 32;
pub const crypto_core_salsa2012_CONSTBYTES: u32 = 16;
pub const crypto_core_salsa208_OUTPUTBYTES: u32 = 64;
pub const crypto_core_salsa208_INPUTBYTES: u32 = 16;
pub const crypto_core_salsa208_KEYBYTES: u32 = 32;
pub const crypto_core_salsa208_CONSTBYTES: u32 = 16;
pub const crypto_generichash_blake2b_BYTES_MIN: u32 = 16;
pub const crypto_generichash_blake2b_BYTES_MAX: u32 = 64;
pub const crypto_generichash_blake2b_BYTES: u32 = 32;
pub const crypto_generichash_blake2b_KEYBYTES_MIN: u32 = 16;
pub const crypto_generichash_blake2b_KEYBYTES_MAX: u32 = 64;
pub const crypto_generichash_blake2b_KEYBYTES: u32 = 32;
pub const crypto_generichash_blake2b_SALTBYTES: u32 = 16;
pub const crypto_generichash_blake2b_PERSONALBYTES: u32 = 16;
pub const crypto_generichash_BYTES_MIN: u32 = 16;
pub const crypto_generichash_BYTES_MAX: u32 = 64;
pub const crypto_generichash_BYTES: u32 = 32;
pub const crypto_generichash_KEYBYTES_MIN: u32 = 16;
pub const crypto_generichash_KEYBYTES_MAX: u32 = 64;
pub const crypto_generichash_KEYBYTES: u32 = 32;
pub const crypto_generichash_PRIMITIVE: &'static [u8; 8usize] = b"blake2b\0";
pub const crypto_hash_BYTES: u32 = 64;
pub const crypto_hash_PRIMITIVE: &'static [u8; 7usize] = b"sha512\0";
pub const crypto_kdf_blake2b_BYTES_MIN: u32 = 16;
pub const crypto_kdf_blake2b_BYTES_MAX: u32 = 64;
pub const crypto_kdf_blake2b_CONTEXTBYTES: u32 = 8;
pub const crypto_kdf_blake2b_KEYBYTES: u32 = 32;
pub const crypto_kdf_BYTES_MIN: u32 = 16;
pub const crypto_kdf_BYTES_MAX: u32 = 64;
pub const crypto_kdf_CONTEXTBYTES: u32 = 8;
pub const crypto_kdf_KEYBYTES: u32 = 32;
pub const crypto_kdf_PRIMITIVE: &'static [u8; 8usize] = b"blake2b\0";
pub const crypto_kx_PUBLICKEYBYTES: u32 = 32;
pub const crypto_kx_SECRETKEYBYTES: u32 = 32;
pub const crypto_kx_SEEDBYTES: u32 = 32;
pub const crypto_kx_SESSIONKEYBYTES: u32 = 32;
pub const crypto_kx_PRIMITIVE: &'static [u8; 14usize] = b"x25519blake2b\0";
pub const _STDIO_H: u32 = 1;
pub const ____FILE_defined: u32 = 1;
pub const __FILE_defined: u32 = 1;
pub const _BITS_LIBIO_H: u32 = 1;
pub const _BITS_G_CONFIG_H: u32 = 1;
pub const ____mbstate_t_defined: u32 = 1;
pub const _G_HAVE_MMAP: u32 = 1;
pub const _G_HAVE_MREMAP: u32 = 1;
pub const _G_IO_IO_FILE_VERSION: u32 = 131073;
pub const _G_BUFSIZ: u32 = 8192;
pub const _IO_BUFSIZ: u32 = 8192;
pub const __GNUC_VA_LIST: u32 = 1;
pub const _IO_UNIFIED_JUMPTABLES: u32 = 1;
pub const EOF: i32 = -1;
pub const _IOS_INPUT: u32 = 1;
pub const _IOS_OUTPUT: u32 = 2;
pub const _IOS_ATEND: u32 = 4;
pub const _IOS_APPEND: u32 = 8;
pub const _IOS_TRUNC: u32 = 16;
pub const _IOS_NOCREATE: u32 = 32;
pub const _IOS_NOREPLACE: u32 = 64;
pub const _IOS_BIN: u32 = 128;
pub const _IO_MAGIC: u32 = 4222418944;
pub const _OLD_STDIO_MAGIC: u32 = 4206624768;
pub const _IO_MAGIC_MASK: u32 = 4294901760;
pub const _IO_USER_BUF: u32 = 1;
pub const _IO_UNBUFFERED: u32 = 2;
pub const _IO_NO_READS: u32 = 4;
pub const _IO_NO_WRITES: u32 = 8;
pub const _IO_EOF_SEEN: u32 = 16;
pub const _IO_ERR_SEEN: u32 = 32;
pub const _IO_DELETE_DONT_CLOSE: u32 = 64;
pub const _IO_LINKED: u32 = 128;
pub const _IO_IN_BACKUP: u32 = 256;
pub const _IO_LINE_BUF: u32 = 512;
pub const _IO_TIED_PUT_GET: u32 = 1024;
pub const _IO_CURRENTLY_PUTTING: u32 = 2048;
pub const _IO_IS_APPENDING: u32 = 4096;
pub const _IO_IS_FILEBUF: u32 = 8192;
pub const _IO_BAD_SEEN: u32 = 16384;
pub const _IO_USER_LOCK: u32 = 32768;
pub const _IO_FLAGS2_MMAP: u32 = 1;
pub const _IO_FLAGS2_NOTCANCEL: u32 = 2;
pub const _IO_FLAGS2_USER_WBUF: u32 = 8;
pub const _IO_SKIPWS: u32 = 1;
pub const _IO_LEFT: u32 = 2;
pub const _IO_RIGHT: u32 = 4;
pub const _IO_INTERNAL: u32 = 8;
pub const _IO_DEC: u32 = 16;
pub const _IO_OCT: u32 = 32;
pub const _IO_HEX: u32 = 64;
pub const _IO_SHOWBASE: u32 = 128;
pub const _IO_SHOWPOINT: u32 = 256;
pub const _IO_UPPERCASE: u32 = 512;
pub const _IO_SHOWPOS: u32 = 1024;
pub const _IO_SCIENTIFIC: u32 = 2048;
pub const _IO_FIXED: u32 = 4096;
pub const _IO_UNITBUF: u32 = 8192;
pub const _IO_STDIO: u32 = 16384;
pub const _IO_DONT_CLOSE: u32 = 32768;
pub const _IO_BOOLALPHA: u32 = 65536;
pub const _IOFBF: u32 = 0;
pub const _IOLBF: u32 = 1;
pub const _IONBF: u32 = 2;
pub const BUFSIZ: u32 = 8192;
pub const SEEK_SET: u32 = 0;
pub const SEEK_CUR: u32 = 1;
pub const SEEK_END: u32 = 2;
pub const P_tmpdir: &'static [u8; 5usize] = b"/tmp\0";
pub const _BITS_STDIO_LIM_H: u32 = 1;
pub const L_tmpnam: u32 = 20;
pub const TMP_MAX: u32 = 238328;
pub const FILENAME_MAX: u32 = 4096;
pub const L_ctermid: u32 = 9;
pub const FOPEN_MAX: u32 = 16;
pub const crypto_onetimeauth_poly1305_BYTES: u32 = 16;
pub const crypto_onetimeauth_poly1305_KEYBYTES: u32 = 32;
pub const crypto_onetimeauth_BYTES: u32 = 16;
pub const crypto_onetimeauth_KEYBYTES: u32 = 32;
pub const crypto_onetimeauth_PRIMITIVE: &'static [u8; 9usize] = b"poly1305\0";
pub const _LIBC_LIMITS_H_: u32 = 1;
pub const MB_LEN_MAX: u32 = 16;
pub const _BITS_POSIX1_LIM_H: u32 = 1;
pub const _POSIX_AIO_LISTIO_MAX: u32 = 2;
pub const _POSIX_AIO_MAX: u32 = 1;
pub const _POSIX_ARG_MAX: u32 = 4096;
pub const _POSIX_CHILD_MAX: u32 = 25;
pub const _POSIX_DELAYTIMER_MAX: u32 = 32;
pub const _POSIX_HOST_NAME_MAX: u32 = 255;
pub const _POSIX_LINK_MAX: u32 = 8;
pub const _POSIX_LOGIN_NAME_MAX: u32 = 9;
pub const _POSIX_MAX_CANON: u32 = 255;
pub const _POSIX_MAX_INPUT: u32 = 255;
pub const _POSIX_MQ_OPEN_MAX: u32 = 8;
pub const _POSIX_MQ_PRIO_MAX: u32 = 32;
pub const _POSIX_NAME_MAX: u32 = 14;
pub const _POSIX_NGROUPS_MAX: u32 = 8;
pub const _POSIX_OPEN_MAX: u32 = 20;
pub const _POSIX_PATH_MAX: u32 = 256;
pub const _POSIX_PIPE_BUF: u32 = 512;
pub const _POSIX_RE_DUP_MAX: u32 = 255;
pub const _POSIX_RTSIG_MAX: u32 = 8;
pub const _POSIX_SEM_NSEMS_MAX: u32 = 256;
pub const _POSIX_SEM_VALUE_MAX: u32 = 32767;
pub const _POSIX_SIGQUEUE_MAX: u32 = 32;
pub const _POSIX_SSIZE_MAX: u32 = 32767;
pub const _POSIX_STREAM_MAX: u32 = 8;
pub const _POSIX_SYMLINK_MAX: u32 = 255;
pub const _POSIX_SYMLOOP_MAX: u32 = 8;
pub const _POSIX_TIMER_MAX: u32 = 32;
pub const _POSIX_TTY_NAME_MAX: u32 = 9;
pub const _POSIX_TZNAME_MAX: u32 = 6;
pub const _POSIX_CLOCKRES_MIN: u32 = 20000000;
pub const NR_OPEN: u32 = 1024;
pub const NGROUPS_MAX: u32 = 65536;
pub const ARG_MAX: u32 = 131072;
pub const LINK_MAX: u32 = 127;
pub const MAX_CANON: u32 = 255;
pub const MAX_INPUT: u32 = 255;
pub const NAME_MAX: u32 = 255;
pub const PATH_MAX: u32 = 4096;
pub const PIPE_BUF: u32 = 4096;
pub const XATTR_NAME_MAX: u32 = 255;
pub const XATTR_SIZE_MAX: u32 = 65536;
pub const XATTR_LIST_MAX: u32 = 65536;
pub const RTSIG_MAX: u32 = 32;
pub const _POSIX_THREAD_KEYS_MAX: u32 = 128;
pub const PTHREAD_KEYS_MAX: u32 = 1024;
pub const _POSIX_THREAD_DESTRUCTOR_ITERATIONS: u32 = 4;
pub const PTHREAD_DESTRUCTOR_ITERATIONS: u32 = 4;
pub const _POSIX_THREAD_THREADS_MAX: u32 = 64;
pub const AIO_PRIO_DELTA_MAX: u32 = 20;
pub const PTHREAD_STACK_MIN: u32 = 16384;
pub const DELAYTIMER_MAX: u32 = 2147483647;
pub const TTY_NAME_MAX: u32 = 32;
pub const LOGIN_NAME_MAX: u32 = 256;
pub const HOST_NAME_MAX: u32 = 64;
pub const MQ_PRIO_MAX: u32 = 32768;
pub const SEM_VALUE_MAX: u32 = 2147483647;
pub const _BITS_POSIX2_LIM_H: u32 = 1;
pub const _POSIX2_BC_BASE_MAX: u32 = 99;
pub const _POSIX2_BC_DIM_MAX: u32 = 2048;
pub const _POSIX2_BC_SCALE_MAX: u32 = 99;
pub const _POSIX2_BC_STRING_MAX: u32 = 1000;
pub const _POSIX2_COLL_WEIGHTS_MAX: u32 = 2;
pub const _POSIX2_EXPR_NEST_MAX: u32 = 32;
pub const _POSIX2_LINE_MAX: u32 = 2048;
pub const _POSIX2_RE_DUP_MAX: u32 = 255;
pub const _POSIX2_CHARCLASS_NAME_MAX: u32 = 14;
pub const BC_BASE_MAX: u32 = 99;
pub const BC_DIM_MAX: u32 = 2048;
pub const BC_SCALE_MAX: u32 = 99;
pub const BC_STRING_MAX: u32 = 1000;
pub const COLL_WEIGHTS_MAX: u32 = 255;
pub const EXPR_NEST_MAX: u32 = 32;
pub const LINE_MAX: u32 = 2048;
pub const CHARCLASS_NAME_MAX: u32 = 2048;
pub const RE_DUP_MAX: u32 = 32767;
pub const crypto_pwhash_argon2i_ALG_ARGON2I13: u32 = 1;
pub const crypto_pwhash_argon2i_BYTES_MIN: u32 = 16;
pub const crypto_pwhash_argon2i_PASSWD_MIN: u32 = 0;
pub const crypto_pwhash_argon2i_PASSWD_MAX: u32 = 4294967295;
pub const crypto_pwhash_argon2i_SALTBYTES: u32 = 16;
pub const crypto_pwhash_argon2i_STRBYTES: u32 = 128;
pub const crypto_pwhash_argon2i_STRPREFIX: &'static [u8; 10usize] = b"$argon2i$\0";
pub const crypto_pwhash_argon2i_OPSLIMIT_MIN: u32 = 3;
pub const crypto_pwhash_argon2i_OPSLIMIT_MAX: u32 = 4294967295;
pub const crypto_pwhash_argon2i_MEMLIMIT_MIN: u32 = 8192;
pub const crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE: u32 = 4;
pub const crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE: u32 = 33554432;
pub const crypto_pwhash_argon2i_OPSLIMIT_MODERATE: u32 = 6;
pub const crypto_pwhash_argon2i_MEMLIMIT_MODERATE: u32 = 134217728;
pub const crypto_pwhash_argon2i_OPSLIMIT_SENSITIVE: u32 = 8;
pub const crypto_pwhash_argon2i_MEMLIMIT_SENSITIVE: u32 = 536870912;
pub const crypto_pwhash_argon2id_ALG_ARGON2ID13: u32 = 2;
pub const crypto_pwhash_argon2id_BYTES_MIN: u32 = 16;
pub const crypto_pwhash_argon2id_PASSWD_MIN: u32 = 0;
pub const crypto_pwhash_argon2id_PASSWD_MAX: u32 = 4294967295;
pub const crypto_pwhash_argon2id_SALTBYTES: u32 = 16;
pub const crypto_pwhash_argon2id_STRBYTES: u32 = 128;
pub const crypto_pwhash_argon2id_STRPREFIX: &'static [u8; 11usize] = b"$argon2id$\0";
pub const crypto_pwhash_argon2id_OPSLIMIT_MIN: u32 = 1;
pub const crypto_pwhash_argon2id_OPSLIMIT_MAX: u32 = 4294967295;
pub const crypto_pwhash_argon2id_MEMLIMIT_MIN: u32 = 8192;
pub const crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE: u32 = 2;
pub const crypto_pwhash_argon2id_MEMLIMIT_INTERACTIVE: u32 = 67108864;
pub const crypto_pwhash_argon2id_OPSLIMIT_MODERATE: u32 = 3;
pub const crypto_pwhash_argon2id_MEMLIMIT_MODERATE: u32 = 268435456;
pub const crypto_pwhash_argon2id_OPSLIMIT_SENSITIVE: u32 = 4;
pub const crypto_pwhash_argon2id_MEMLIMIT_SENSITIVE: u32 = 1073741824;
pub const crypto_pwhash_ALG_ARGON2I13: u32 = 1;
pub const crypto_pwhash_ALG_ARGON2ID13: u32 = 2;
pub const crypto_pwhash_ALG_DEFAULT: u32 = 2;
pub const crypto_pwhash_BYTES_MIN: u32 = 16;
pub const crypto_pwhash_PASSWD_MIN: u32 = 0;
pub const crypto_pwhash_PASSWD_MAX: u32 = 4294967295;
pub const crypto_pwhash_SALTBYTES: u32 = 16;
pub const crypto_pwhash_STRBYTES: u32 = 128;
pub const crypto_pwhash_STRPREFIX: &'static [u8; 11usize] = b"$argon2id$\0";
pub const crypto_pwhash_OPSLIMIT_MIN: u32 = 1;
pub const crypto_pwhash_OPSLIMIT_MAX: u32 = 4294967295;
pub const crypto_pwhash_MEMLIMIT_MIN: u32 = 8192;
pub const crypto_pwhash_OPSLIMIT_INTERACTIVE: u32 = 2;
pub const crypto_pwhash_MEMLIMIT_INTERACTIVE: u32 = 67108864;
pub const crypto_pwhash_OPSLIMIT_MODERATE: u32 = 3;
pub const crypto_pwhash_MEMLIMIT_MODERATE: u32 = 268435456;
pub const crypto_pwhash_OPSLIMIT_SENSITIVE: u32 = 4;
pub const crypto_pwhash_MEMLIMIT_SENSITIVE: u32 = 1073741824;
pub const crypto_pwhash_PRIMITIVE: &'static [u8; 8usize] = b"argon2i\0";
pub const crypto_scalarmult_curve25519_BYTES: u32 = 32;
pub const crypto_scalarmult_curve25519_SCALARBYTES: u32 = 32;
pub const crypto_scalarmult_BYTES: u32 = 32;
pub const crypto_scalarmult_SCALARBYTES: u32 = 32;
pub const crypto_scalarmult_PRIMITIVE: &'static [u8; 11usize] = b"curve25519\0";
pub const crypto_secretbox_xsalsa20poly1305_KEYBYTES: u32 = 32;
pub const crypto_secretbox_xsalsa20poly1305_NONCEBYTES: u32 = 24;
pub const crypto_secretbox_xsalsa20poly1305_MACBYTES: u32 = 16;
pub const crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES: u32 = 16;
pub const crypto_secretbox_xsalsa20poly1305_ZEROBYTES: u32 = 32;
pub const crypto_secretbox_KEYBYTES: u32 = 32;
pub const crypto_secretbox_NONCEBYTES: u32 = 24;
pub const crypto_secretbox_MACBYTES: u32 = 16;
pub const crypto_secretbox_PRIMITIVE: &'static [u8; 17usize] = b"xsalsa20poly1305\0";
pub const crypto_secretbox_ZEROBYTES: u32 = 32;
pub const crypto_secretbox_BOXZEROBYTES: u32 = 16;
pub const crypto_stream_chacha20_KEYBYTES: u32 = 32;
pub const crypto_stream_chacha20_NONCEBYTES: u32 = 8;
pub const crypto_stream_chacha20_ietf_KEYBYTES: u32 = 32;
pub const crypto_stream_chacha20_ietf_NONCEBYTES: u32 = 12;
pub const crypto_stream_chacha20_IETF_KEYBYTES: u32 = 32;
pub const crypto_stream_chacha20_IETF_NONCEBYTES: u32 = 12;
pub const crypto_secretstream_xchacha20poly1305_ABYTES: u32 = 17;
pub const crypto_secretstream_xchacha20poly1305_HEADERBYTES: u32 = 24;
pub const crypto_secretstream_xchacha20poly1305_KEYBYTES: u32 = 32;
pub const crypto_secretstream_xchacha20poly1305_TAG_MESSAGE: u32 = 0;
pub const crypto_secretstream_xchacha20poly1305_TAG_PUSH: u32 = 1;
pub const crypto_secretstream_xchacha20poly1305_TAG_REKEY: u32 = 2;
pub const crypto_secretstream_xchacha20poly1305_TAG_FINAL: u32 = 3;
pub const crypto_shorthash_siphash24_BYTES: u32 = 8;
pub const crypto_shorthash_siphash24_KEYBYTES: u32 = 16;
pub const crypto_shorthash_siphashx24_BYTES: u32 = 16;
pub const crypto_shorthash_siphashx24_KEYBYTES: u32 = 16;
pub const crypto_shorthash_BYTES: u32 = 8;
pub const crypto_shorthash_KEYBYTES: u32 = 16;
pub const crypto_shorthash_PRIMITIVE: &'static [u8; 10usize] = b"siphash24\0";
pub const crypto_sign_ed25519_BYTES: u32 = 64;
pub const crypto_sign_ed25519_SEEDBYTES: u32 = 32;
pub const crypto_sign_ed25519_PUBLICKEYBYTES: u32 = 32;
pub const crypto_sign_ed25519_SECRETKEYBYTES: u32 = 64;
pub const crypto_sign_BYTES: u32 = 64;
pub const crypto_sign_SEEDBYTES: u32 = 32;
pub const crypto_sign_PUBLICKEYBYTES: u32 = 32;
pub const crypto_sign_SECRETKEYBYTES: u32 = 64;
pub const crypto_sign_PRIMITIVE: &'static [u8; 8usize] = b"ed25519\0";
pub const crypto_stream_KEYBYTES: u32 = 32;
pub const crypto_stream_NONCEBYTES: u32 = 24;
pub const crypto_stream_PRIMITIVE: &'static [u8; 9usize] = b"xsalsa20\0";
pub const crypto_stream_salsa20_KEYBYTES: u32 = 32;
pub const crypto_stream_salsa20_NONCEBYTES: u32 = 8;
pub const crypto_verify_16_BYTES: u32 = 16;
pub const crypto_verify_32_BYTES: u32 = 32;
pub const crypto_verify_64_BYTES: u32 = 64;
pub const randombytes_SEEDBYTES: u32 = 32;
pub const sodium_base64_VARIANT_ORIGINAL: u32 = 1;
pub const sodium_base64_VARIANT_ORIGINAL_NO_PADDING: u32 = 3;
pub const sodium_base64_VARIANT_URLSAFE: u32 = 5;
pub const sodium_base64_VARIANT_URLSAFE_NO_PADDING: u32 = 7;
pub const crypto_stream_xchacha20_KEYBYTES: u32 = 32;
pub const crypto_stream_xchacha20_NONCEBYTES: u32 = 24;
pub const crypto_box_curve25519xchacha20poly1305_SEEDBYTES: u32 = 32;
pub const crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES: u32 = 32;
pub const crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES: u32 = 32;
pub const crypto_box_curve25519xchacha20poly1305_BEFORENMBYTES: u32 = 32;
pub const crypto_box_curve25519xchacha20poly1305_NONCEBYTES: u32 = 24;
pub const crypto_box_curve25519xchacha20poly1305_MACBYTES: u32 = 16;
pub const crypto_box_curve25519xchacha20poly1305_SEALBYTES: u32 = 48;
pub const crypto_core_ed25519_BYTES: u32 = 32;
pub const crypto_core_ed25519_UNIFORMBYTES: u32 = 32;
pub const crypto_scalarmult_ed25519_BYTES: u32 = 32;
pub const crypto_scalarmult_ed25519_SCALARBYTES: u32 = 32;
pub const crypto_secretbox_xchacha20poly1305_KEYBYTES: u32 = 32;
pub const crypto_secretbox_xchacha20poly1305_NONCEBYTES: u32 = 24;
pub const crypto_secretbox_xchacha20poly1305_MACBYTES: u32 = 16;
pub const crypto_pwhash_scryptsalsa208sha256_BYTES_MIN: u32 = 16;
pub const crypto_pwhash_scryptsalsa208sha256_PASSWD_MIN: u32 = 0;
pub const crypto_pwhash_scryptsalsa208sha256_SALTBYTES: u32 = 32;
pub const crypto_pwhash_scryptsalsa208sha256_STRBYTES: u32 = 102;
pub const crypto_pwhash_scryptsalsa208sha256_STRPREFIX: &'static [u8; 4usize] = b"$7$\0";
pub const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN: u32 = 32768;
pub const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX: u32 = 4294967295;
pub const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN: u32 = 16777216;
pub const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE: u32 = 524288;
pub const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE: u32 = 16777216;
pub const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE: u32 = 33554432;
pub const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE: u32 = 1073741824;
pub const crypto_stream_salsa2012_KEYBYTES: u32 = 32;
pub const crypto_stream_salsa2012_NONCEBYTES: u32 = 8;
pub const crypto_stream_salsa208_KEYBYTES: u32 = 32;
pub const crypto_stream_salsa208_NONCEBYTES: u32 = 8;
extern "C" {
pub fn sodium_version_string() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn sodium_library_version_major() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_library_version_minor() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_library_minimal() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_init() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_set_misuse_handler(
handler: ::std::option::Option<unsafe extern "C" fn()>,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_misuse();
}
pub type wchar_t = ::std::os::raw::c_int;
extern "C" {
pub fn crypto_aead_aes256gcm_is_available() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_keybytes() -> usize;
}
extern "C" {
pub fn crypto_aead_aes256gcm_nsecbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_aes256gcm_npubbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_aes256gcm_abytes() -> usize;
}
extern "C" {
pub fn crypto_aead_aes256gcm_messagebytes_max() -> usize;
}
pub type crypto_aead_aes256gcm_state = [::std::os::raw::c_uchar; 512usize];
extern "C" {
pub fn crypto_aead_aes256gcm_statebytes() -> usize;
}
extern "C" {
pub fn crypto_aead_aes256gcm_encrypt(
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_decrypt(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_encrypt_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
maclen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_decrypt_detached(
m: *mut ::std::os::raw::c_uchar,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
mac: *const ::std::os::raw::c_uchar,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_beforenm(
ctx_: *mut crypto_aead_aes256gcm_state,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_encrypt_afternm(
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
ctx_: *const crypto_aead_aes256gcm_state,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_decrypt_afternm(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
ctx_: *const crypto_aead_aes256gcm_state,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_encrypt_detached_afternm(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
maclen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
ctx_: *const crypto_aead_aes256gcm_state,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_decrypt_detached_afternm(
m: *mut ::std::os::raw::c_uchar,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
mac: *const ::std::os::raw::c_uchar,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
ctx_: *const crypto_aead_aes256gcm_state,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_aes256gcm_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_keybytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_nsecbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_npubbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_abytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_encrypt(
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_decrypt(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_encrypt_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
maclen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_decrypt_detached(
m: *mut ::std::os::raw::c_uchar,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
mac: *const ::std::os::raw::c_uchar,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_ietf_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_keybytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_nsecbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_npubbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_abytes() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_encrypt(
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_decrypt(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_encrypt_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
maclen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_decrypt_detached(
m: *mut ::std::os::raw::c_uchar,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
mac: *const ::std::os::raw::c_uchar,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_chacha20poly1305_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_keybytes() -> usize;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_nsecbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_npubbytes() -> usize;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_abytes() -> usize;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_encrypt(
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_decrypt(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_encrypt_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
maclen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
nsec: *const ::std::os::raw::c_uchar,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_decrypt_detached(
m: *mut ::std::os::raw::c_uchar,
nsec: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
mac: *const ::std::os::raw::c_uchar,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
npub: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_aead_xchacha20poly1305_ietf_keygen(k: *mut ::std::os::raw::c_uchar);
}
pub type __u_char = ::std::os::raw::c_uchar;
pub type __u_short = ::std::os::raw::c_ushort;
pub type __u_int = ::std::os::raw::c_uint;
pub type __u_long = ::std::os::raw::c_ulong;
pub type __int8_t = ::std::os::raw::c_schar;
pub type __uint8_t = ::std::os::raw::c_uchar;
pub type __int16_t = ::std::os::raw::c_short;
pub type __uint16_t = ::std::os::raw::c_ushort;
pub type __int32_t = ::std::os::raw::c_int;
pub type __uint32_t = ::std::os::raw::c_uint;
pub type __int64_t = ::std::os::raw::c_long;
pub type __uint64_t = ::std::os::raw::c_ulong;
pub type __quad_t = ::std::os::raw::c_long;
pub type __u_quad_t = ::std::os::raw::c_ulong;
pub type __intmax_t = ::std::os::raw::c_long;
pub type __uintmax_t = ::std::os::raw::c_ulong;
pub type __dev_t = ::std::os::raw::c_ulong;
pub type __uid_t = ::std::os::raw::c_uint;
pub type __gid_t = ::std::os::raw::c_uint;
pub type __ino_t = ::std::os::raw::c_ulong;
pub type __ino64_t = ::std::os::raw::c_ulong;
pub type __mode_t = ::std::os::raw::c_uint;
pub type __nlink_t = ::std::os::raw::c_ulong;
pub type __off_t = ::std::os::raw::c_long;
pub type __off64_t = ::std::os::raw::c_long;
pub type __pid_t = ::std::os::raw::c_int;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __fsid_t {
pub __val: [::std::os::raw::c_int; 2usize],
}
#[test]
fn bindgen_test_layout___fsid_t() {
assert_eq!(
::std::mem::size_of::<__fsid_t>(),
8usize,
concat!("Size of: ", stringify!(__fsid_t))
);
assert_eq!(
::std::mem::align_of::<__fsid_t>(),
4usize,
concat!("Alignment of ", stringify!(__fsid_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__fsid_t>())).__val as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__fsid_t),
"::",
stringify!(__val)
)
);
}
pub type __clock_t = ::std::os::raw::c_long;
pub type __rlim_t = ::std::os::raw::c_ulong;
pub type __rlim64_t = ::std::os::raw::c_ulong;
pub type __id_t = ::std::os::raw::c_uint;
pub type __time_t = ::std::os::raw::c_long;
pub type __useconds_t = ::std::os::raw::c_uint;
pub type __suseconds_t = ::std::os::raw::c_long;
pub type __daddr_t = ::std::os::raw::c_int;
pub type __key_t = ::std::os::raw::c_int;
pub type __clockid_t = ::std::os::raw::c_int;
pub type __timer_t = *mut ::std::os::raw::c_void;
pub type __blksize_t = ::std::os::raw::c_long;
pub type __blkcnt_t = ::std::os::raw::c_long;
pub type __blkcnt64_t = ::std::os::raw::c_long;
pub type __fsblkcnt_t = ::std::os::raw::c_ulong;
pub type __fsblkcnt64_t = ::std::os::raw::c_ulong;
pub type __fsfilcnt_t = ::std::os::raw::c_ulong;
pub type __fsfilcnt64_t = ::std::os::raw::c_ulong;
pub type __fsword_t = ::std::os::raw::c_long;
pub type __ssize_t = ::std::os::raw::c_long;
pub type __syscall_slong_t = ::std::os::raw::c_long;
pub type __syscall_ulong_t = ::std::os::raw::c_ulong;
pub type __loff_t = __off64_t;
pub type __caddr_t = *mut ::std::os::raw::c_char;
pub type __intptr_t = ::std::os::raw::c_long;
pub type __socklen_t = ::std::os::raw::c_uint;
pub type __sig_atomic_t = ::std::os::raw::c_int;
pub type int_least8_t = ::std::os::raw::c_schar;
pub type int_least16_t = ::std::os::raw::c_short;
pub type int_least32_t = ::std::os::raw::c_int;
pub type int_least64_t = ::std::os::raw::c_long;
pub type uint_least8_t = ::std::os::raw::c_uchar;
pub type uint_least16_t = ::std::os::raw::c_ushort;
pub type uint_least32_t = ::std::os::raw::c_uint;
pub type uint_least64_t = ::std::os::raw::c_ulong;
pub type int_fast8_t = ::std::os::raw::c_schar;
pub type int_fast16_t = ::std::os::raw::c_long;
pub type int_fast32_t = ::std::os::raw::c_long;
pub type int_fast64_t = ::std::os::raw::c_long;
pub type uint_fast8_t = ::std::os::raw::c_uchar;
pub type uint_fast16_t = ::std::os::raw::c_ulong;
pub type uint_fast32_t = ::std::os::raw::c_ulong;
pub type uint_fast64_t = ::std::os::raw::c_ulong;
pub type intmax_t = __intmax_t;
pub type uintmax_t = __uintmax_t;
pub type _Float32 = f32;
pub type _Float64 = f64;
pub type _Float32x = f64;
pub type _Float64x = f64;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct div_t {
pub quot: ::std::os::raw::c_int,
pub rem: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_div_t() {
assert_eq!(
::std::mem::size_of::<div_t>(),
8usize,
concat!("Size of: ", stringify!(div_t))
);
assert_eq!(
::std::mem::align_of::<div_t>(),
4usize,
concat!("Alignment of ", stringify!(div_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<div_t>())).quot as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(div_t),
"::",
stringify!(quot)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<div_t>())).rem as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(div_t),
"::",
stringify!(rem)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ldiv_t {
pub quot: ::std::os::raw::c_long,
pub rem: ::std::os::raw::c_long,
}
#[test]
fn bindgen_test_layout_ldiv_t() {
assert_eq!(
::std::mem::size_of::<ldiv_t>(),
16usize,
concat!("Size of: ", stringify!(ldiv_t))
);
assert_eq!(
::std::mem::align_of::<ldiv_t>(),
8usize,
concat!("Alignment of ", stringify!(ldiv_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ldiv_t>())).quot as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(ldiv_t),
"::",
stringify!(quot)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ldiv_t>())).rem as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(ldiv_t),
"::",
stringify!(rem)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct lldiv_t {
pub quot: ::std::os::raw::c_longlong,
pub rem: ::std::os::raw::c_longlong,
}
#[test]
fn bindgen_test_layout_lldiv_t() {
assert_eq!(
::std::mem::size_of::<lldiv_t>(),
16usize,
concat!("Size of: ", stringify!(lldiv_t))
);
assert_eq!(
::std::mem::align_of::<lldiv_t>(),
8usize,
concat!("Alignment of ", stringify!(lldiv_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<lldiv_t>())).quot as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(lldiv_t),
"::",
stringify!(quot)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<lldiv_t>())).rem as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(lldiv_t),
"::",
stringify!(rem)
)
);
}
extern "C" {
pub fn __ctype_get_mb_cur_max() -> usize;
}
extern "C" {
pub fn atof(__nptr: *const ::std::os::raw::c_char) -> f64;
}
extern "C" {
pub fn atoi(__nptr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn atol(__nptr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn atoll(__nptr: *const ::std::os::raw::c_char) -> ::std::os::raw::c_longlong;
}
extern "C" {
pub fn strtod(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
) -> f64;
}
extern "C" {
pub fn strtof(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
) -> f32;
}
extern "C" {
pub fn strtold(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
) -> f64;
}
extern "C" {
pub fn strtol(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn strtoul(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_ulong;
}
extern "C" {
pub fn strtoq(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_longlong;
}
extern "C" {
pub fn strtouq(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_ulonglong;
}
extern "C" {
pub fn strtoll(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_longlong;
}
extern "C" {
pub fn strtoull(
__nptr: *const ::std::os::raw::c_char,
__endptr: *mut *mut ::std::os::raw::c_char,
__base: ::std::os::raw::c_int,
) -> ::std::os::raw::c_ulonglong;
}
extern "C" {
pub fn l64a(__n: ::std::os::raw::c_long) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn a64l(__s: *const ::std::os::raw::c_char) -> ::std::os::raw::c_long;
}
pub type u_char = __u_char;
pub type u_short = __u_short;
pub type u_int = __u_int;
pub type u_long = __u_long;
pub type quad_t = __quad_t;
pub type u_quad_t = __u_quad_t;
pub type fsid_t = __fsid_t;
pub type loff_t = __loff_t;
pub type ino_t = __ino_t;
pub type dev_t = __dev_t;
pub type gid_t = __gid_t;
pub type mode_t = __mode_t;
pub type nlink_t = __nlink_t;
pub type uid_t = __uid_t;
pub type off_t = __off_t;
pub type pid_t = __pid_t;
pub type id_t = __id_t;
pub type daddr_t = __daddr_t;
pub type caddr_t = __caddr_t;
pub type key_t = __key_t;
pub type clock_t = __clock_t;
pub type clockid_t = __clockid_t;
pub type time_t = __time_t;
pub type timer_t = __timer_t;
pub type ulong = ::std::os::raw::c_ulong;
pub type ushort = ::std::os::raw::c_ushort;
pub type uint = ::std::os::raw::c_uint;
pub type u_int8_t = ::std::os::raw::c_uchar;
pub type u_int16_t = ::std::os::raw::c_ushort;
pub type u_int32_t = ::std::os::raw::c_uint;
pub type u_int64_t = ::std::os::raw::c_ulong;
pub type register_t = ::std::os::raw::c_long;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __sigset_t {
pub __val: [::std::os::raw::c_ulong; 16usize],
}
#[test]
fn bindgen_test_layout___sigset_t() {
assert_eq!(
::std::mem::size_of::<__sigset_t>(),
128usize,
concat!("Size of: ", stringify!(__sigset_t))
);
assert_eq!(
::std::mem::align_of::<__sigset_t>(),
8usize,
concat!("Alignment of ", stringify!(__sigset_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__sigset_t>())).__val as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__sigset_t),
"::",
stringify!(__val)
)
);
}
pub type sigset_t = __sigset_t;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct timeval {
pub tv_sec: __time_t,
pub tv_usec: __suseconds_t,
}
#[test]
fn bindgen_test_layout_timeval() {
assert_eq!(
::std::mem::size_of::<timeval>(),
16usize,
concat!("Size of: ", stringify!(timeval))
);
assert_eq!(
::std::mem::align_of::<timeval>(),
8usize,
concat!("Alignment of ", stringify!(timeval))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<timeval>())).tv_sec as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(timeval),
"::",
stringify!(tv_sec)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<timeval>())).tv_usec as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(timeval),
"::",
stringify!(tv_usec)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct timespec {
pub tv_sec: __time_t,
pub tv_nsec: __syscall_slong_t,
}
#[test]
fn bindgen_test_layout_timespec() {
assert_eq!(
::std::mem::size_of::<timespec>(),
16usize,
concat!("Size of: ", stringify!(timespec))
);
assert_eq!(
::std::mem::align_of::<timespec>(),
8usize,
concat!("Alignment of ", stringify!(timespec))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<timespec>())).tv_sec as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(timespec),
"::",
stringify!(tv_sec)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<timespec>())).tv_nsec as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(timespec),
"::",
stringify!(tv_nsec)
)
);
}
pub type suseconds_t = __suseconds_t;
pub type __fd_mask = ::std::os::raw::c_long;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct fd_set {
pub __fds_bits: [__fd_mask; 16usize],
}
#[test]
fn bindgen_test_layout_fd_set() {
assert_eq!(
::std::mem::size_of::<fd_set>(),
128usize,
concat!("Size of: ", stringify!(fd_set))
);
assert_eq!(
::std::mem::align_of::<fd_set>(),
8usize,
concat!("Alignment of ", stringify!(fd_set))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<fd_set>())).__fds_bits as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(fd_set),
"::",
stringify!(__fds_bits)
)
);
}
pub type fd_mask = __fd_mask;
extern "C" {
pub fn select(
__nfds: ::std::os::raw::c_int,
__readfds: *mut fd_set,
__writefds: *mut fd_set,
__exceptfds: *mut fd_set,
__timeout: *mut timeval,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn pselect(
__nfds: ::std::os::raw::c_int,
__readfds: *mut fd_set,
__writefds: *mut fd_set,
__exceptfds: *mut fd_set,
__timeout: *const timespec,
__sigmask: *const __sigset_t,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn gnu_dev_major(__dev: __dev_t) -> ::std::os::raw::c_uint;
}
extern "C" {
pub fn gnu_dev_minor(__dev: __dev_t) -> ::std::os::raw::c_uint;
}
extern "C" {
pub fn gnu_dev_makedev(
__major: ::std::os::raw::c_uint,
__minor: ::std::os::raw::c_uint,
) -> __dev_t;
}
pub type blksize_t = __blksize_t;
pub type blkcnt_t = __blkcnt_t;
pub type fsblkcnt_t = __fsblkcnt_t;
pub type fsfilcnt_t = __fsfilcnt_t;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_rwlock_arch_t {
pub __readers: ::std::os::raw::c_uint,
pub __writers: ::std::os::raw::c_uint,
pub __wrphase_futex: ::std::os::raw::c_uint,
pub __writers_futex: ::std::os::raw::c_uint,
pub __pad3: ::std::os::raw::c_uint,
pub __pad4: ::std::os::raw::c_uint,
pub __cur_writer: ::std::os::raw::c_int,
pub __shared: ::std::os::raw::c_int,
pub __rwelision: ::std::os::raw::c_schar,
pub __pad1: [::std::os::raw::c_uchar; 7usize],
pub __pad2: ::std::os::raw::c_ulong,
pub __flags: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout___pthread_rwlock_arch_t() {
assert_eq!(
::std::mem::size_of::<__pthread_rwlock_arch_t>(),
56usize,
concat!("Size of: ", stringify!(__pthread_rwlock_arch_t))
);
assert_eq!(
::std::mem::align_of::<__pthread_rwlock_arch_t>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_rwlock_arch_t))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__readers as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__readers)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__writers as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__writers)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__wrphase_futex as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__wrphase_futex)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__writers_futex as *const _ as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__writers_futex)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__pad3 as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__pad3)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__pad4 as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__pad4)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__cur_writer as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__cur_writer)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__shared as *const _ as usize
},
28usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__shared)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__rwelision as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__rwelision)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__pad1 as *const _ as usize },
33usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__pad1)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__pad2 as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__pad2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_rwlock_arch_t>())).__flags as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(__pthread_rwlock_arch_t),
"::",
stringify!(__flags)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_internal_list {
pub __prev: *mut __pthread_internal_list,
pub __next: *mut __pthread_internal_list,
}
#[test]
fn bindgen_test_layout___pthread_internal_list() {
assert_eq!(
::std::mem::size_of::<__pthread_internal_list>(),
16usize,
concat!("Size of: ", stringify!(__pthread_internal_list))
);
assert_eq!(
::std::mem::align_of::<__pthread_internal_list>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_internal_list))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_internal_list>())).__prev as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_internal_list),
"::",
stringify!(__prev)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_internal_list>())).__next as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(__pthread_internal_list),
"::",
stringify!(__next)
)
);
}
pub type __pthread_list_t = __pthread_internal_list;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_mutex_s {
pub __lock: ::std::os::raw::c_int,
pub __count: ::std::os::raw::c_uint,
pub __owner: ::std::os::raw::c_int,
pub __nusers: ::std::os::raw::c_uint,
pub __kind: ::std::os::raw::c_int,
pub __spins: ::std::os::raw::c_short,
pub __elision: ::std::os::raw::c_short,
pub __list: __pthread_list_t,
}
#[test]
fn bindgen_test_layout___pthread_mutex_s() {
assert_eq!(
::std::mem::size_of::<__pthread_mutex_s>(),
40usize,
concat!("Size of: ", stringify!(__pthread_mutex_s))
);
assert_eq!(
::std::mem::align_of::<__pthread_mutex_s>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_mutex_s))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__lock as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__count as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__count)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__owner as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__owner)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__nusers as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__nusers)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__kind as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__kind)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__spins as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__spins)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__elision as *const _ as usize },
22usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__elision)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__list as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__list)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct __pthread_cond_s {
pub __bindgen_anon_1: __pthread_cond_s__bindgen_ty_1,
pub __bindgen_anon_2: __pthread_cond_s__bindgen_ty_2,
pub __g_refs: [::std::os::raw::c_uint; 2usize],
pub __g_size: [::std::os::raw::c_uint; 2usize],
pub __g1_orig_size: ::std::os::raw::c_uint,
pub __wrefs: ::std::os::raw::c_uint,
pub __g_signals: [::std::os::raw::c_uint; 2usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union __pthread_cond_s__bindgen_ty_1 {
pub __wseq: ::std::os::raw::c_ulonglong,
pub __wseq32: __pthread_cond_s__bindgen_ty_1__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 {
pub __low: ::std::os::raw::c_uint,
pub __high: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>())).__low
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(__low)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>())).__high
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(__high)
)
);
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(__pthread_cond_s__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s__bindgen_ty_1))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1>())).__wseq as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1),
"::",
stringify!(__wseq)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1>())).__wseq32 as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1),
"::",
stringify!(__wseq32)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union __pthread_cond_s__bindgen_ty_2 {
pub __g1_start: ::std::os::raw::c_ulonglong,
pub __g1_start32: __pthread_cond_s__bindgen_ty_2__bindgen_ty_1,
_bindgen_union_align: u64,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 {
pub __low: ::std::os::raw::c_uint,
pub __high: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>())).__low
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1),
"::",
stringify!(__low)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>())).__high
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1),
"::",
stringify!(__high)
)
);
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_2>(),
8usize,
concat!("Size of: ", stringify!(__pthread_cond_s__bindgen_ty_2))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_2>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s__bindgen_ty_2))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2>())).__g1_start as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2),
"::",
stringify!(__g1_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2>())).__g1_start32 as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2),
"::",
stringify!(__g1_start32)
)
);
}
#[test]
fn bindgen_test_layout___pthread_cond_s() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s>(),
48usize,
concat!("Size of: ", stringify!(__pthread_cond_s))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_refs as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_refs)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_size as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g1_orig_size as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g1_orig_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__wrefs as *const _ as usize },
36usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__wrefs)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_signals as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_signals)
)
);
}
pub type pthread_t = ::std::os::raw::c_ulong;
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_mutexattr_t {
pub __size: [::std::os::raw::c_char; 4usize],
pub __align: ::std::os::raw::c_int,
_bindgen_union_align: u32,
}
#[test]
fn bindgen_test_layout_pthread_mutexattr_t() {
assert_eq!(
::std::mem::size_of::<pthread_mutexattr_t>(),
4usize,
concat!("Size of: ", stringify!(pthread_mutexattr_t))
);
assert_eq!(
::std::mem::align_of::<pthread_mutexattr_t>(),
4usize,
concat!("Alignment of ", stringify!(pthread_mutexattr_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutexattr_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutexattr_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutexattr_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutexattr_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_condattr_t {
pub __size: [::std::os::raw::c_char; 4usize],
pub __align: ::std::os::raw::c_int,
_bindgen_union_align: u32,
}
#[test]
fn bindgen_test_layout_pthread_condattr_t() {
assert_eq!(
::std::mem::size_of::<pthread_condattr_t>(),
4usize,
concat!("Size of: ", stringify!(pthread_condattr_t))
);
assert_eq!(
::std::mem::align_of::<pthread_condattr_t>(),
4usize,
concat!("Alignment of ", stringify!(pthread_condattr_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_condattr_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_condattr_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_condattr_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_condattr_t),
"::",
stringify!(__align)
)
);
}
pub type pthread_key_t = ::std::os::raw::c_uint;
pub type pthread_once_t = ::std::os::raw::c_int;
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_attr_t {
pub __size: [::std::os::raw::c_char; 56usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 7usize],
}
#[test]
fn bindgen_test_layout_pthread_attr_t() {
assert_eq!(
::std::mem::size_of::<pthread_attr_t>(),
56usize,
concat!("Size of: ", stringify!(pthread_attr_t))
);
assert_eq!(
::std::mem::align_of::<pthread_attr_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_attr_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_attr_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_attr_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_attr_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_attr_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_mutex_t {
pub __data: __pthread_mutex_s,
pub __size: [::std::os::raw::c_char; 40usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 5usize],
}
#[test]
fn bindgen_test_layout_pthread_mutex_t() {
assert_eq!(
::std::mem::size_of::<pthread_mutex_t>(),
40usize,
concat!("Size of: ", stringify!(pthread_mutex_t))
);
assert_eq!(
::std::mem::align_of::<pthread_mutex_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_mutex_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_cond_t {
pub __data: __pthread_cond_s,
pub __size: [::std::os::raw::c_char; 48usize],
pub __align: ::std::os::raw::c_longlong,
_bindgen_union_align: [u64; 6usize],
}
#[test]
fn bindgen_test_layout_pthread_cond_t() {
assert_eq!(
::std::mem::size_of::<pthread_cond_t>(),
48usize,
concat!("Size of: ", stringify!(pthread_cond_t))
);
assert_eq!(
::std::mem::align_of::<pthread_cond_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_cond_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_rwlock_t {
pub __data: __pthread_rwlock_arch_t,
pub __size: [::std::os::raw::c_char; 56usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 7usize],
}
#[test]
fn bindgen_test_layout_pthread_rwlock_t() {
assert_eq!(
::std::mem::size_of::<pthread_rwlock_t>(),
56usize,
concat!("Size of: ", stringify!(pthread_rwlock_t))
);
assert_eq!(
::std::mem::align_of::<pthread_rwlock_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_rwlock_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_rwlock_t>())).__data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_rwlock_t),
"::",
stringify!(__data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_rwlock_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_rwlock_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_rwlock_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_rwlock_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_rwlockattr_t {
pub __size: [::std::os::raw::c_char; 8usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: u64,
}
#[test]
fn bindgen_test_layout_pthread_rwlockattr_t() {
assert_eq!(
::std::mem::size_of::<pthread_rwlockattr_t>(),
8usize,
concat!("Size of: ", stringify!(pthread_rwlockattr_t))
);
assert_eq!(
::std::mem::align_of::<pthread_rwlockattr_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_rwlockattr_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_rwlockattr_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_rwlockattr_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_rwlockattr_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_rwlockattr_t),
"::",
stringify!(__align)
)
);
}
pub type pthread_spinlock_t = ::std::os::raw::c_int;
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_barrier_t {
pub __size: [::std::os::raw::c_char; 32usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 4usize],
}
#[test]
fn bindgen_test_layout_pthread_barrier_t() {
assert_eq!(
::std::mem::size_of::<pthread_barrier_t>(),
32usize,
concat!("Size of: ", stringify!(pthread_barrier_t))
);
assert_eq!(
::std::mem::align_of::<pthread_barrier_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_barrier_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_barrier_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_barrier_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_barrier_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_barrier_t),
"::",
stringify!(__align)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_barrierattr_t {
pub __size: [::std::os::raw::c_char; 4usize],
pub __align: ::std::os::raw::c_int,
_bindgen_union_align: u32,
}
#[test]
fn bindgen_test_layout_pthread_barrierattr_t() {
assert_eq!(
::std::mem::size_of::<pthread_barrierattr_t>(),
4usize,
concat!("Size of: ", stringify!(pthread_barrierattr_t))
);
assert_eq!(
::std::mem::align_of::<pthread_barrierattr_t>(),
4usize,
concat!("Alignment of ", stringify!(pthread_barrierattr_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_barrierattr_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_barrierattr_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_barrierattr_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_barrierattr_t),
"::",
stringify!(__align)
)
);
}
extern "C" {
pub fn random() -> ::std::os::raw::c_long;
}
extern "C" {
pub fn srandom(__seed: ::std::os::raw::c_uint);
}
extern "C" {
pub fn initstate(
__seed: ::std::os::raw::c_uint,
__statebuf: *mut ::std::os::raw::c_char,
__statelen: usize,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn setstate(__statebuf: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct random_data {
pub fptr: *mut i32,
pub rptr: *mut i32,
pub state: *mut i32,
pub rand_type: ::std::os::raw::c_int,
pub rand_deg: ::std::os::raw::c_int,
pub rand_sep: ::std::os::raw::c_int,
pub end_ptr: *mut i32,
}
#[test]
fn bindgen_test_layout_random_data() {
assert_eq!(
::std::mem::size_of::<random_data>(),
48usize,
concat!("Size of: ", stringify!(random_data))
);
assert_eq!(
::std::mem::align_of::<random_data>(),
8usize,
concat!("Alignment of ", stringify!(random_data))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).fptr as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(fptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).rptr as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(rptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).state as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(state)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).rand_type as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(rand_type)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).rand_deg as *const _ as usize },
28usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(rand_deg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).rand_sep as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(rand_sep)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<random_data>())).end_ptr as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(random_data),
"::",
stringify!(end_ptr)
)
);
}
extern "C" {
pub fn random_r(__buf: *mut random_data, __result: *mut i32) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn srandom_r(
__seed: ::std::os::raw::c_uint,
__buf: *mut random_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn initstate_r(
__seed: ::std::os::raw::c_uint,
__statebuf: *mut ::std::os::raw::c_char,
__statelen: usize,
__buf: *mut random_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn setstate_r(
__statebuf: *mut ::std::os::raw::c_char,
__buf: *mut random_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn rand() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn srand(__seed: ::std::os::raw::c_uint);
}
extern "C" {
pub fn rand_r(__seed: *mut ::std::os::raw::c_uint) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn drand48() -> f64;
}
extern "C" {
pub fn erand48(__xsubi: *mut ::std::os::raw::c_ushort) -> f64;
}
extern "C" {
pub fn lrand48() -> ::std::os::raw::c_long;
}
extern "C" {
pub fn nrand48(__xsubi: *mut ::std::os::raw::c_ushort) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn mrand48() -> ::std::os::raw::c_long;
}
extern "C" {
pub fn jrand48(__xsubi: *mut ::std::os::raw::c_ushort) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn srand48(__seedval: ::std::os::raw::c_long);
}
extern "C" {
pub fn seed48(__seed16v: *mut ::std::os::raw::c_ushort) -> *mut ::std::os::raw::c_ushort;
}
extern "C" {
pub fn lcong48(__param: *mut ::std::os::raw::c_ushort);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct drand48_data {
pub __x: [::std::os::raw::c_ushort; 3usize],
pub __old_x: [::std::os::raw::c_ushort; 3usize],
pub __c: ::std::os::raw::c_ushort,
pub __init: ::std::os::raw::c_ushort,
pub __a: ::std::os::raw::c_ulonglong,
}
#[test]
fn bindgen_test_layout_drand48_data() {
assert_eq!(
::std::mem::size_of::<drand48_data>(),
24usize,
concat!("Size of: ", stringify!(drand48_data))
);
assert_eq!(
::std::mem::align_of::<drand48_data>(),
8usize,
concat!("Alignment of ", stringify!(drand48_data))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<drand48_data>())).__x as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(drand48_data),
"::",
stringify!(__x)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<drand48_data>())).__old_x as *const _ as usize },
6usize,
concat!(
"Offset of field: ",
stringify!(drand48_data),
"::",
stringify!(__old_x)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<drand48_data>())).__c as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(drand48_data),
"::",
stringify!(__c)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<drand48_data>())).__init as *const _ as usize },
14usize,
concat!(
"Offset of field: ",
stringify!(drand48_data),
"::",
stringify!(__init)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<drand48_data>())).__a as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(drand48_data),
"::",
stringify!(__a)
)
);
}
extern "C" {
pub fn drand48_r(__buffer: *mut drand48_data, __result: *mut f64) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn erand48_r(
__xsubi: *mut ::std::os::raw::c_ushort,
__buffer: *mut drand48_data,
__result: *mut f64,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn lrand48_r(
__buffer: *mut drand48_data,
__result: *mut ::std::os::raw::c_long,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn nrand48_r(
__xsubi: *mut ::std::os::raw::c_ushort,
__buffer: *mut drand48_data,
__result: *mut ::std::os::raw::c_long,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mrand48_r(
__buffer: *mut drand48_data,
__result: *mut ::std::os::raw::c_long,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn jrand48_r(
__xsubi: *mut ::std::os::raw::c_ushort,
__buffer: *mut drand48_data,
__result: *mut ::std::os::raw::c_long,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn srand48_r(
__seedval: ::std::os::raw::c_long,
__buffer: *mut drand48_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn seed48_r(
__seed16v: *mut ::std::os::raw::c_ushort,
__buffer: *mut drand48_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn lcong48_r(
__param: *mut ::std::os::raw::c_ushort,
__buffer: *mut drand48_data,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn malloc(__size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn calloc(__nmemb: usize, __size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn realloc(
__ptr: *mut ::std::os::raw::c_void,
__size: usize,
) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn free(__ptr: *mut ::std::os::raw::c_void);
}
extern "C" {
pub fn alloca(__size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn valloc(__size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn posix_memalign(
__memptr: *mut *mut ::std::os::raw::c_void,
__alignment: usize,
__size: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn aligned_alloc(__alignment: usize, __size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn abort();
}
extern "C" {
pub fn atexit(__func: ::std::option::Option<unsafe extern "C" fn()>) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn at_quick_exit(
__func: ::std::option::Option<unsafe extern "C" fn()>,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn on_exit(
__func: ::std::option::Option<
unsafe extern "C" fn(
__status: ::std::os::raw::c_int,
__arg: *mut ::std::os::raw::c_void,
),
>,
__arg: *mut ::std::os::raw::c_void,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn exit(__status: ::std::os::raw::c_int);
}
extern "C" {
pub fn quick_exit(__status: ::std::os::raw::c_int);
}
extern "C" {
pub fn _Exit(__status: ::std::os::raw::c_int);
}
extern "C" {
pub fn getenv(__name: *const ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn putenv(__string: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn setenv(
__name: *const ::std::os::raw::c_char,
__value: *const ::std::os::raw::c_char,
__replace: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn unsetenv(__name: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn clearenv() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mktemp(__template: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn mkstemp(__template: *mut ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mkstemps(
__template: *mut ::std::os::raw::c_char,
__suffixlen: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mkdtemp(__template: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn system(__command: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn realpath(
__name: *const ::std::os::raw::c_char,
__resolved: *mut ::std::os::raw::c_char,
) -> *mut ::std::os::raw::c_char;
}
pub type __compar_fn_t = ::std::option::Option<
unsafe extern "C" fn(arg1: *const ::std::os::raw::c_void, arg2: *const ::std::os::raw::c_void)
-> ::std::os::raw::c_int,
>;
extern "C" {
pub fn bsearch(
__key: *const ::std::os::raw::c_void,
__base: *const ::std::os::raw::c_void,
__nmemb: usize,
__size: usize,
__compar: __compar_fn_t,
) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn qsort(
__base: *mut ::std::os::raw::c_void,
__nmemb: usize,
__size: usize,
__compar: __compar_fn_t,
);
}
extern "C" {
pub fn abs(__x: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn labs(__x: ::std::os::raw::c_long) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn llabs(__x: ::std::os::raw::c_longlong) -> ::std::os::raw::c_longlong;
}
extern "C" {
pub fn div(__numer: ::std::os::raw::c_int, __denom: ::std::os::raw::c_int) -> div_t;
}
extern "C" {
pub fn ldiv(__numer: ::std::os::raw::c_long, __denom: ::std::os::raw::c_long) -> ldiv_t;
}
extern "C" {
pub fn lldiv(
__numer: ::std::os::raw::c_longlong,
__denom: ::std::os::raw::c_longlong,
) -> lldiv_t;
}
extern "C" {
pub fn ecvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn fcvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn gcvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn qecvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn qfcvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn qgcvt(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn ecvt_r(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
__len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fcvt_r(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
__len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn qecvt_r(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
__len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn qfcvt_r(
__value: f64,
__ndigit: ::std::os::raw::c_int,
__decpt: *mut ::std::os::raw::c_int,
__sign: *mut ::std::os::raw::c_int,
__buf: *mut ::std::os::raw::c_char,
__len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mblen(__s: *const ::std::os::raw::c_char, __n: usize) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mbtowc(
__pwc: *mut wchar_t,
__s: *const ::std::os::raw::c_char,
__n: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn wctomb(__s: *mut ::std::os::raw::c_char, __wchar: wchar_t) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn mbstowcs(__pwcs: *mut wchar_t, __s: *const ::std::os::raw::c_char, __n: usize) -> usize;
}
extern "C" {
pub fn wcstombs(__s: *mut ::std::os::raw::c_char, __pwcs: *const wchar_t, __n: usize) -> usize;
}
extern "C" {
pub fn rpmatch(__response: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getsubopt(
__optionp: *mut *mut ::std::os::raw::c_char,
__tokens: *const *mut ::std::os::raw::c_char,
__valuep: *mut *mut ::std::os::raw::c_char,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getloadavg(__loadavg: *mut f64, __nelem: ::std::os::raw::c_int)
-> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_hash_sha512_state {
pub state: [u64; 8usize],
pub count: [u64; 2usize],
pub buf: [u8; 128usize],
}
#[test]
fn bindgen_test_layout_crypto_hash_sha512_state() {
assert_eq!(
::std::mem::size_of::<crypto_hash_sha512_state>(),
208usize,
concat!("Size of: ", stringify!(crypto_hash_sha512_state))
);
assert_eq!(
::std::mem::align_of::<crypto_hash_sha512_state>(),
8usize,
concat!("Alignment of ", stringify!(crypto_hash_sha512_state))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha512_state>())).state as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha512_state),
"::",
stringify!(state)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha512_state>())).count as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha512_state),
"::",
stringify!(count)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha512_state>())).buf as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha512_state),
"::",
stringify!(buf)
)
);
}
extern "C" {
pub fn crypto_hash_sha512_statebytes() -> usize;
}
extern "C" {
pub fn crypto_hash_sha512_bytes() -> usize;
}
extern "C" {
pub fn crypto_hash_sha512(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha512_init(state: *mut crypto_hash_sha512_state) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha512_update(
state: *mut crypto_hash_sha512_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha512_final(
state: *mut crypto_hash_sha512_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512_bytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512_keybytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_auth_hmacsha512_state {
pub ictx: crypto_hash_sha512_state,
pub octx: crypto_hash_sha512_state,
}
#[test]
fn bindgen_test_layout_crypto_auth_hmacsha512_state() {
assert_eq!(
::std::mem::size_of::<crypto_auth_hmacsha512_state>(),
416usize,
concat!("Size of: ", stringify!(crypto_auth_hmacsha512_state))
);
assert_eq!(
::std::mem::align_of::<crypto_auth_hmacsha512_state>(),
8usize,
concat!("Alignment of ", stringify!(crypto_auth_hmacsha512_state))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_auth_hmacsha512_state>())).ictx as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_auth_hmacsha512_state),
"::",
stringify!(ictx)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_auth_hmacsha512_state>())).octx as *const _ as usize
},
208usize,
concat!(
"Offset of field: ",
stringify!(crypto_auth_hmacsha512_state),
"::",
stringify!(octx)
)
);
}
extern "C" {
pub fn crypto_auth_hmacsha512_statebytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512_init(
state: *mut crypto_auth_hmacsha512_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512_update(
state: *mut crypto_auth_hmacsha512_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512_final(
state: *mut crypto_auth_hmacsha512_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_auth_hmacsha512256_bytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_keybytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512256(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
pub type crypto_auth_hmacsha512256_state = crypto_auth_hmacsha512_state;
extern "C" {
pub fn crypto_auth_hmacsha512256_statebytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_init(
state: *mut crypto_auth_hmacsha512256_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_update(
state: *mut crypto_auth_hmacsha512256_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_final(
state: *mut crypto_auth_hmacsha512256_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha512256_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_auth_bytes() -> usize;
}
extern "C" {
pub fn crypto_auth_keybytes() -> usize;
}
extern "C" {
pub fn crypto_auth_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_auth(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_keygen(k: *mut ::std::os::raw::c_uchar);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_hash_sha256_state {
pub state: [u32; 8usize],
pub count: u64,
pub buf: [u8; 64usize],
}
#[test]
fn bindgen_test_layout_crypto_hash_sha256_state() {
assert_eq!(
::std::mem::size_of::<crypto_hash_sha256_state>(),
104usize,
concat!("Size of: ", stringify!(crypto_hash_sha256_state))
);
assert_eq!(
::std::mem::align_of::<crypto_hash_sha256_state>(),
8usize,
concat!("Alignment of ", stringify!(crypto_hash_sha256_state))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha256_state>())).state as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha256_state),
"::",
stringify!(state)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha256_state>())).count as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha256_state),
"::",
stringify!(count)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_hash_sha256_state>())).buf as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(crypto_hash_sha256_state),
"::",
stringify!(buf)
)
);
}
extern "C" {
pub fn crypto_hash_sha256_statebytes() -> usize;
}
extern "C" {
pub fn crypto_hash_sha256_bytes() -> usize;
}
extern "C" {
pub fn crypto_hash_sha256(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha256_init(state: *mut crypto_hash_sha256_state) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha256_update(
state: *mut crypto_hash_sha256_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_sha256_final(
state: *mut crypto_hash_sha256_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha256_bytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha256_keybytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha256(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha256_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_auth_hmacsha256_state {
pub ictx: crypto_hash_sha256_state,
pub octx: crypto_hash_sha256_state,
}
#[test]
fn bindgen_test_layout_crypto_auth_hmacsha256_state() {
assert_eq!(
::std::mem::size_of::<crypto_auth_hmacsha256_state>(),
208usize,
concat!("Size of: ", stringify!(crypto_auth_hmacsha256_state))
);
assert_eq!(
::std::mem::align_of::<crypto_auth_hmacsha256_state>(),
8usize,
concat!("Alignment of ", stringify!(crypto_auth_hmacsha256_state))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_auth_hmacsha256_state>())).ictx as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_auth_hmacsha256_state),
"::",
stringify!(ictx)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_auth_hmacsha256_state>())).octx as *const _ as usize
},
104usize,
concat!(
"Offset of field: ",
stringify!(crypto_auth_hmacsha256_state),
"::",
stringify!(octx)
)
);
}
extern "C" {
pub fn crypto_auth_hmacsha256_statebytes() -> usize;
}
extern "C" {
pub fn crypto_auth_hmacsha256_init(
state: *mut crypto_auth_hmacsha256_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha256_update(
state: *mut crypto_auth_hmacsha256_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha256_final(
state: *mut crypto_auth_hmacsha256_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_auth_hmacsha256_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_stream_xsalsa20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_xsalsa20_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_xsalsa20_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_xsalsa20(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xsalsa20_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xsalsa20_xor_ic(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
ic: u64,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xsalsa20_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_beforenmbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_macbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_beforenm(
k: *mut ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_boxzerobytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_zerobytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_afternm(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xsalsa20poly1305_open_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_box_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_box_macbytes() -> usize;
}
extern "C" {
pub fn crypto_box_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_box_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_box_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_easy(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open_easy(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open_detached(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_beforenmbytes() -> usize;
}
extern "C" {
pub fn crypto_box_beforenm(
k: *mut ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_easy_afternm(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open_easy_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_detached_afternm(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open_detached_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_sealbytes() -> usize;
}
extern "C" {
pub fn crypto_box_seal(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_seal_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_zerobytes() -> usize;
}
extern "C" {
pub fn crypto_box_boxzerobytes() -> usize;
}
extern "C" {
pub fn crypto_box(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_afternm(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_open_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_hsalsa20_outputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hsalsa20_inputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hsalsa20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_core_hsalsa20_constbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hsalsa20(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_hchacha20_outputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hchacha20_inputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hchacha20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_core_hchacha20_constbytes() -> usize;
}
extern "C" {
pub fn crypto_core_hchacha20(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_salsa20_outputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa20_inputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa20_constbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa20(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_salsa2012_outputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa2012_inputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa2012_keybytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa2012_constbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa2012(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_salsa208_outputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa208_inputbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa208_keybytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa208_constbytes() -> usize;
}
extern "C" {
pub fn crypto_core_salsa208(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_generichash_blake2b_state {
pub h: [u64; 8usize],
pub t: [u64; 2usize],
pub f: [u64; 2usize],
pub buf: [u8; 256usize],
pub buflen: usize,
pub last_node: u8,
pub __bindgen_padding_0: [u8; 23usize],
}
#[test]
fn bindgen_test_layout_crypto_generichash_blake2b_state() {
assert_eq!(
::std::mem::size_of::<crypto_generichash_blake2b_state>(),
384usize,
concat!("Size of: ", stringify!(crypto_generichash_blake2b_state))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).h as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(h)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).t as *const _ as usize
},
64usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(t)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).f as *const _ as usize
},
80usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(f)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).buf as *const _ as usize
},
96usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(buf)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).buflen as *const _ as usize
},
352usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(buflen)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_generichash_blake2b_state>())).last_node as *const _
as usize
},
360usize,
concat!(
"Offset of field: ",
stringify!(crypto_generichash_blake2b_state),
"::",
stringify!(last_node)
)
);
}
extern "C" {
pub fn crypto_generichash_blake2b_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_bytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_keybytes_min() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_keybytes_max() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_keybytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_saltbytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_personalbytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b_statebytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_blake2b(
out: *mut ::std::os::raw::c_uchar,
outlen: usize,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_salt_personal(
out: *mut ::std::os::raw::c_uchar,
outlen: usize,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
salt: *const ::std::os::raw::c_uchar,
personal: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_init(
state: *mut crypto_generichash_blake2b_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
outlen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_init_salt_personal(
state: *mut crypto_generichash_blake2b_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
outlen: usize,
salt: *const ::std::os::raw::c_uchar,
personal: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_update(
state: *mut crypto_generichash_blake2b_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_final(
state: *mut crypto_generichash_blake2b_state,
out: *mut ::std::os::raw::c_uchar,
outlen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_blake2b_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_generichash_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_generichash_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_generichash_bytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_keybytes_min() -> usize;
}
extern "C" {
pub fn crypto_generichash_keybytes_max() -> usize;
}
extern "C" {
pub fn crypto_generichash_keybytes() -> usize;
}
extern "C" {
pub fn crypto_generichash_primitive() -> *const ::std::os::raw::c_char;
}
pub type crypto_generichash_state = crypto_generichash_blake2b_state;
extern "C" {
pub fn crypto_generichash_statebytes() -> usize;
}
extern "C" {
pub fn crypto_generichash(
out: *mut ::std::os::raw::c_uchar,
outlen: usize,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_init(
state: *mut crypto_generichash_state,
key: *const ::std::os::raw::c_uchar,
keylen: usize,
outlen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_update(
state: *mut crypto_generichash_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_final(
state: *mut crypto_generichash_state,
out: *mut ::std::os::raw::c_uchar,
outlen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_generichash_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_hash_bytes() -> usize;
}
extern "C" {
pub fn crypto_hash(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_hash_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_kdf_blake2b_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_kdf_blake2b_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_kdf_blake2b_contextbytes() -> usize;
}
extern "C" {
pub fn crypto_kdf_blake2b_keybytes() -> usize;
}
extern "C" {
pub fn crypto_kdf_blake2b_derive_from_key(
subkey: *mut ::std::os::raw::c_uchar,
subkey_len: usize,
subkey_id: u64,
ctx: *const ::std::os::raw::c_char,
key: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_kdf_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_kdf_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_kdf_contextbytes() -> usize;
}
extern "C" {
pub fn crypto_kdf_keybytes() -> usize;
}
extern "C" {
pub fn crypto_kdf_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_kdf_derive_from_key(
subkey: *mut ::std::os::raw::c_uchar,
subkey_len: usize,
subkey_id: u64,
ctx: *const ::std::os::raw::c_char,
key: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_kdf_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_kx_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_kx_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_kx_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_kx_sessionkeybytes() -> usize;
}
extern "C" {
pub fn crypto_kx_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_kx_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_kx_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_kx_client_session_keys(
rx: *mut ::std::os::raw::c_uchar,
tx: *mut ::std::os::raw::c_uchar,
client_pk: *const ::std::os::raw::c_uchar,
client_sk: *const ::std::os::raw::c_uchar,
server_pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_kx_server_session_keys(
rx: *mut ::std::os::raw::c_uchar,
tx: *mut ::std::os::raw::c_uchar,
server_pk: *const ::std::os::raw::c_uchar,
server_sk: *const ::std::os::raw::c_uchar,
client_pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
pub type __FILE = _IO_FILE;
pub type FILE = _IO_FILE;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct __mbstate_t {
pub __count: ::std::os::raw::c_int,
pub __value: __mbstate_t__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union __mbstate_t__bindgen_ty_1 {
pub __wch: ::std::os::raw::c_uint,
pub __wchb: [::std::os::raw::c_char; 4usize],
_bindgen_union_align: u32,
}
#[test]
fn bindgen_test_layout___mbstate_t__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__mbstate_t__bindgen_ty_1>(),
4usize,
concat!("Size of: ", stringify!(__mbstate_t__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<__mbstate_t__bindgen_ty_1>(),
4usize,
concat!("Alignment of ", stringify!(__mbstate_t__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__mbstate_t__bindgen_ty_1>())).__wch as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__mbstate_t__bindgen_ty_1),
"::",
stringify!(__wch)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__mbstate_t__bindgen_ty_1>())).__wchb as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__mbstate_t__bindgen_ty_1),
"::",
stringify!(__wchb)
)
);
}
#[test]
fn bindgen_test_layout___mbstate_t() {
assert_eq!(
::std::mem::size_of::<__mbstate_t>(),
8usize,
concat!("Size of: ", stringify!(__mbstate_t))
);
assert_eq!(
::std::mem::align_of::<__mbstate_t>(),
4usize,
concat!("Alignment of ", stringify!(__mbstate_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__mbstate_t>())).__count as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__mbstate_t),
"::",
stringify!(__count)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__mbstate_t>())).__value as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(__mbstate_t),
"::",
stringify!(__value)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _G_fpos_t {
pub __pos: __off_t,
pub __state: __mbstate_t,
}
#[test]
fn bindgen_test_layout__G_fpos_t() {
assert_eq!(
::std::mem::size_of::<_G_fpos_t>(),
16usize,
concat!("Size of: ", stringify!(_G_fpos_t))
);
assert_eq!(
::std::mem::align_of::<_G_fpos_t>(),
8usize,
concat!("Alignment of ", stringify!(_G_fpos_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_G_fpos_t>())).__pos as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_G_fpos_t),
"::",
stringify!(__pos)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_G_fpos_t>())).__state as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_G_fpos_t),
"::",
stringify!(__state)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct _G_fpos64_t {
pub __pos: __off64_t,
pub __state: __mbstate_t,
}
#[test]
fn bindgen_test_layout__G_fpos64_t() {
assert_eq!(
::std::mem::size_of::<_G_fpos64_t>(),
16usize,
concat!("Size of: ", stringify!(_G_fpos64_t))
);
assert_eq!(
::std::mem::align_of::<_G_fpos64_t>(),
8usize,
concat!("Alignment of ", stringify!(_G_fpos64_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_G_fpos64_t>())).__pos as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_G_fpos64_t),
"::",
stringify!(__pos)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_G_fpos64_t>())).__state as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_G_fpos64_t),
"::",
stringify!(__state)
)
);
}
pub type va_list = __builtin_va_list;
pub type __gnuc_va_list = __builtin_va_list;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_jump_t {
_unused: [u8; 0],
}
pub type _IO_lock_t = ::std::os::raw::c_void;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_marker {
pub _next: *mut _IO_marker,
pub _sbuf: *mut _IO_FILE,
pub _pos: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout__IO_marker() {
assert_eq!(
::std::mem::size_of::<_IO_marker>(),
24usize,
concat!("Size of: ", stringify!(_IO_marker))
);
assert_eq!(
::std::mem::align_of::<_IO_marker>(),
8usize,
concat!("Alignment of ", stringify!(_IO_marker))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_marker>()))._next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_IO_marker),
"::",
stringify!(_next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_marker>()))._sbuf as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IO_marker),
"::",
stringify!(_sbuf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_marker>()))._pos as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(_IO_marker),
"::",
stringify!(_pos)
)
);
}
pub const __codecvt_result___codecvt_ok: __codecvt_result = 0;
pub const __codecvt_result___codecvt_partial: __codecvt_result = 1;
pub const __codecvt_result___codecvt_error: __codecvt_result = 2;
pub const __codecvt_result___codecvt_noconv: __codecvt_result = 3;
pub type __codecvt_result = u32;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_FILE {
pub _flags: ::std::os::raw::c_int,
pub _IO_read_ptr: *mut ::std::os::raw::c_char,
pub _IO_read_end: *mut ::std::os::raw::c_char,
pub _IO_read_base: *mut ::std::os::raw::c_char,
pub _IO_write_base: *mut ::std::os::raw::c_char,
pub _IO_write_ptr: *mut ::std::os::raw::c_char,
pub _IO_write_end: *mut ::std::os::raw::c_char,
pub _IO_buf_base: *mut ::std::os::raw::c_char,
pub _IO_buf_end: *mut ::std::os::raw::c_char,
pub _IO_save_base: *mut ::std::os::raw::c_char,
pub _IO_backup_base: *mut ::std::os::raw::c_char,
pub _IO_save_end: *mut ::std::os::raw::c_char,
pub _markers: *mut _IO_marker,
pub _chain: *mut _IO_FILE,
pub _fileno: ::std::os::raw::c_int,
pub _flags2: ::std::os::raw::c_int,
pub _old_offset: __off_t,
pub _cur_column: ::std::os::raw::c_ushort,
pub _vtable_offset: ::std::os::raw::c_schar,
pub _shortbuf: [::std::os::raw::c_char; 1usize],
pub _lock: *mut _IO_lock_t,
pub _offset: __off64_t,
pub __pad1: *mut ::std::os::raw::c_void,
pub __pad2: *mut ::std::os::raw::c_void,
pub __pad3: *mut ::std::os::raw::c_void,
pub __pad4: *mut ::std::os::raw::c_void,
pub __pad5: usize,
pub _mode: ::std::os::raw::c_int,
pub _unused2: [::std::os::raw::c_char; 20usize],
}
#[test]
fn bindgen_test_layout__IO_FILE() {
assert_eq!(
::std::mem::size_of::<_IO_FILE>(),
216usize,
concat!("Size of: ", stringify!(_IO_FILE))
);
assert_eq!(
::std::mem::align_of::<_IO_FILE>(),
8usize,
concat!("Alignment of ", stringify!(_IO_FILE))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._flags as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_flags)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_ptr as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_ptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_end as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_read_base as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_read_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_base as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_ptr as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_ptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_write_end as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_write_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_buf_base as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_buf_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_buf_end as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_buf_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_save_base as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_save_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_backup_base as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_backup_base)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._IO_save_end as *const _ as usize },
88usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_IO_save_end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._markers as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_markers)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._chain as *const _ as usize },
104usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_chain)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._fileno as *const _ as usize },
112usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_fileno)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._flags2 as *const _ as usize },
116usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_flags2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._old_offset as *const _ as usize },
120usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_old_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._cur_column as *const _ as usize },
128usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_cur_column)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._vtable_offset as *const _ as usize },
130usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_vtable_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._shortbuf as *const _ as usize },
131usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_shortbuf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._lock as *const _ as usize },
136usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._offset as *const _ as usize },
144usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad1 as *const _ as usize },
152usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad1)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad2 as *const _ as usize },
160usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad2)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad3 as *const _ as usize },
168usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad3)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad4 as *const _ as usize },
176usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad4)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>())).__pad5 as *const _ as usize },
184usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(__pad5)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._mode as *const _ as usize },
192usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_mode)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<_IO_FILE>()))._unused2 as *const _ as usize },
196usize,
concat!(
"Offset of field: ",
stringify!(_IO_FILE),
"::",
stringify!(_unused2)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct _IO_FILE_plus {
_unused: [u8; 0],
}
extern "C" {
#[link_name = "\u{1}_IO_2_1_stdin_"]
pub static mut _IO_2_1_stdin_: _IO_FILE_plus;
}
extern "C" {
#[link_name = "\u{1}_IO_2_1_stdout_"]
pub static mut _IO_2_1_stdout_: _IO_FILE_plus;
}
extern "C" {
#[link_name = "\u{1}_IO_2_1_stderr_"]
pub static mut _IO_2_1_stderr_: _IO_FILE_plus;
}
pub type __io_read_fn = ::std::option::Option<
unsafe extern "C" fn(
__cookie: *mut ::std::os::raw::c_void,
__buf: *mut ::std::os::raw::c_char,
__nbytes: usize,
) -> __ssize_t,
>;
pub type __io_write_fn = ::std::option::Option<
unsafe extern "C" fn(
__cookie: *mut ::std::os::raw::c_void,
__buf: *const ::std::os::raw::c_char,
__n: usize,
) -> __ssize_t,
>;
pub type __io_seek_fn = ::std::option::Option<
unsafe extern "C" fn(
__cookie: *mut ::std::os::raw::c_void,
__pos: *mut __off64_t,
__w: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int,
>;
pub type __io_close_fn = ::std::option::Option<
unsafe extern "C" fn(__cookie: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int,
>;
extern "C" {
pub fn __underflow(arg1: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn __uflow(arg1: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn __overflow(arg1: *mut _IO_FILE, arg2: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_getc(__fp: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_putc(__c: ::std::os::raw::c_int, __fp: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_feof(__fp: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_ferror(__fp: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_peekc_locked(__fp: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_flockfile(arg1: *mut _IO_FILE);
}
extern "C" {
pub fn _IO_funlockfile(arg1: *mut _IO_FILE);
}
extern "C" {
pub fn _IO_ftrylockfile(arg1: *mut _IO_FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_vfscanf(
arg1: *mut _IO_FILE,
arg2: *const ::std::os::raw::c_char,
arg3: *mut __va_list_tag,
arg4: *mut ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_vfprintf(
arg1: *mut _IO_FILE,
arg2: *const ::std::os::raw::c_char,
arg3: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _IO_padn(arg1: *mut _IO_FILE, arg2: ::std::os::raw::c_int, arg3: __ssize_t)
-> __ssize_t;
}
extern "C" {
pub fn _IO_sgetn(arg1: *mut _IO_FILE, arg2: *mut ::std::os::raw::c_void, arg3: usize) -> usize;
}
extern "C" {
pub fn _IO_seekoff(
arg1: *mut _IO_FILE,
arg2: __off64_t,
arg3: ::std::os::raw::c_int,
arg4: ::std::os::raw::c_int,
) -> __off64_t;
}
extern "C" {
pub fn _IO_seekpos(
arg1: *mut _IO_FILE,
arg2: __off64_t,
arg3: ::std::os::raw::c_int,
) -> __off64_t;
}
extern "C" {
pub fn _IO_free_backup_area(arg1: *mut _IO_FILE);
}
pub type fpos_t = _G_fpos_t;
extern "C" {
#[link_name = "\u{1}stdin"]
pub static mut stdin: *mut _IO_FILE;
}
extern "C" {
#[link_name = "\u{1}stdout"]
pub static mut stdout: *mut _IO_FILE;
}
extern "C" {
#[link_name = "\u{1}stderr"]
pub static mut stderr: *mut _IO_FILE;
}
extern "C" {
pub fn remove(__filename: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn rename(
__old: *const ::std::os::raw::c_char,
__new: *const ::std::os::raw::c_char,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn renameat(
__oldfd: ::std::os::raw::c_int,
__old: *const ::std::os::raw::c_char,
__newfd: ::std::os::raw::c_int,
__new: *const ::std::os::raw::c_char,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn tmpfile() -> *mut FILE;
}
extern "C" {
pub fn tmpnam(__s: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn tmpnam_r(__s: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn tempnam(
__dir: *const ::std::os::raw::c_char,
__pfx: *const ::std::os::raw::c_char,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn fclose(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fflush(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fflush_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fopen(
__filename: *const ::std::os::raw::c_char,
__modes: *const ::std::os::raw::c_char,
) -> *mut FILE;
}
extern "C" {
pub fn freopen(
__filename: *const ::std::os::raw::c_char,
__modes: *const ::std::os::raw::c_char,
__stream: *mut FILE,
) -> *mut FILE;
}
extern "C" {
pub fn fdopen(__fd: ::std::os::raw::c_int, __modes: *const ::std::os::raw::c_char)
-> *mut FILE;
}
extern "C" {
pub fn fmemopen(
__s: *mut ::std::os::raw::c_void,
__len: usize,
__modes: *const ::std::os::raw::c_char,
) -> *mut FILE;
}
extern "C" {
pub fn open_memstream(
__bufloc: *mut *mut ::std::os::raw::c_char,
__sizeloc: *mut usize,
) -> *mut FILE;
}
extern "C" {
pub fn setbuf(__stream: *mut FILE, __buf: *mut ::std::os::raw::c_char);
}
extern "C" {
pub fn setvbuf(
__stream: *mut FILE,
__buf: *mut ::std::os::raw::c_char,
__modes: ::std::os::raw::c_int,
__n: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn setbuffer(__stream: *mut FILE, __buf: *mut ::std::os::raw::c_char, __size: usize);
}
extern "C" {
pub fn setlinebuf(__stream: *mut FILE);
}
extern "C" {
pub fn fprintf(
__stream: *mut FILE,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn printf(__format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sprintf(
__s: *mut ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vfprintf(
__s: *mut FILE,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vprintf(
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vsprintf(
__s: *mut ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn snprintf(
__s: *mut ::std::os::raw::c_char,
__maxlen: usize,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vsnprintf(
__s: *mut ::std::os::raw::c_char,
__maxlen: usize,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vdprintf(
__fd: ::std::os::raw::c_int,
__fmt: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn dprintf(
__fd: ::std::os::raw::c_int,
__fmt: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fscanf(
__stream: *mut FILE,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn scanf(__format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sscanf(
__s: *const ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_fscanf"]
pub fn fscanf1(
__stream: *mut FILE,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_scanf"]
pub fn scanf1(__format: *const ::std::os::raw::c_char, ...) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_sscanf"]
pub fn sscanf1(
__s: *const ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
...
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vfscanf(
__s: *mut FILE,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vscanf(
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn vsscanf(
__s: *const ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_vfscanf"]
pub fn vfscanf1(
__s: *mut FILE,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_vscanf"]
pub fn vscanf1(
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}__isoc99_vsscanf"]
pub fn vsscanf1(
__s: *const ::std::os::raw::c_char,
__format: *const ::std::os::raw::c_char,
__arg: *mut __va_list_tag,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fgetc(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getc(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getchar() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getc_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getchar_unlocked() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fgetc_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fputc(__c: ::std::os::raw::c_int, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn putc(__c: ::std::os::raw::c_int, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn putchar(__c: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fputc_unlocked(__c: ::std::os::raw::c_int, __stream: *mut FILE)
-> ::std::os::raw::c_int;
}
extern "C" {
pub fn putc_unlocked(__c: ::std::os::raw::c_int, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn putchar_unlocked(__c: ::std::os::raw::c_int) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn getw(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn putw(__w: ::std::os::raw::c_int, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fgets(
__s: *mut ::std::os::raw::c_char,
__n: ::std::os::raw::c_int,
__stream: *mut FILE,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn __getdelim(
__lineptr: *mut *mut ::std::os::raw::c_char,
__n: *mut usize,
__delimiter: ::std::os::raw::c_int,
__stream: *mut FILE,
) -> __ssize_t;
}
extern "C" {
pub fn getdelim(
__lineptr: *mut *mut ::std::os::raw::c_char,
__n: *mut usize,
__delimiter: ::std::os::raw::c_int,
__stream: *mut FILE,
) -> __ssize_t;
}
extern "C" {
pub fn getline(
__lineptr: *mut *mut ::std::os::raw::c_char,
__n: *mut usize,
__stream: *mut FILE,
) -> __ssize_t;
}
extern "C" {
pub fn fputs(__s: *const ::std::os::raw::c_char, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn puts(__s: *const ::std::os::raw::c_char) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ungetc(__c: ::std::os::raw::c_int, __stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fread(
__ptr: *mut ::std::os::raw::c_void,
__size: usize,
__n: usize,
__stream: *mut FILE,
) -> usize;
}
extern "C" {
pub fn fwrite(
__ptr: *const ::std::os::raw::c_void,
__size: usize,
__n: usize,
__s: *mut FILE,
) -> usize;
}
extern "C" {
pub fn fread_unlocked(
__ptr: *mut ::std::os::raw::c_void,
__size: usize,
__n: usize,
__stream: *mut FILE,
) -> usize;
}
extern "C" {
pub fn fwrite_unlocked(
__ptr: *const ::std::os::raw::c_void,
__size: usize,
__n: usize,
__stream: *mut FILE,
) -> usize;
}
extern "C" {
pub fn fseek(
__stream: *mut FILE,
__off: ::std::os::raw::c_long,
__whence: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ftell(__stream: *mut FILE) -> ::std::os::raw::c_long;
}
extern "C" {
pub fn rewind(__stream: *mut FILE);
}
extern "C" {
pub fn fseeko(
__stream: *mut FILE,
__off: __off_t,
__whence: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ftello(__stream: *mut FILE) -> __off_t;
}
extern "C" {
pub fn fgetpos(__stream: *mut FILE, __pos: *mut fpos_t) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fsetpos(__stream: *mut FILE, __pos: *const fpos_t) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn clearerr(__stream: *mut FILE);
}
extern "C" {
pub fn feof(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ferror(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn clearerr_unlocked(__stream: *mut FILE);
}
extern "C" {
pub fn feof_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ferror_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn perror(__s: *const ::std::os::raw::c_char);
}
extern "C" {
#[link_name = "\u{1}sys_nerr"]
pub static mut sys_nerr: ::std::os::raw::c_int;
}
extern "C" {
#[link_name = "\u{1}sys_errlist"]
pub static mut sys_errlist: [*const ::std::os::raw::c_char; 0usize];
}
extern "C" {
pub fn fileno(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn fileno_unlocked(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn popen(
__command: *const ::std::os::raw::c_char,
__modes: *const ::std::os::raw::c_char,
) -> *mut FILE;
}
extern "C" {
pub fn pclose(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ctermid(__s: *mut ::std::os::raw::c_char) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn flockfile(__stream: *mut FILE);
}
extern "C" {
pub fn ftrylockfile(__stream: *mut FILE) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn funlockfile(__stream: *mut FILE);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_onetimeauth_poly1305_state {
pub opaque: [::std::os::raw::c_uchar; 256usize],
}
#[test]
fn bindgen_test_layout_crypto_onetimeauth_poly1305_state() {
assert_eq!(
::std::mem::size_of::<crypto_onetimeauth_poly1305_state>(),
256usize,
concat!("Size of: ", stringify!(crypto_onetimeauth_poly1305_state))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_onetimeauth_poly1305_state>())).opaque as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_onetimeauth_poly1305_state),
"::",
stringify!(opaque)
)
);
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_statebytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_bytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_keybytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_init(
state: *mut crypto_onetimeauth_poly1305_state,
key: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_update(
state: *mut crypto_onetimeauth_poly1305_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_final(
state: *mut crypto_onetimeauth_poly1305_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_poly1305_keygen(k: *mut ::std::os::raw::c_uchar);
}
pub type crypto_onetimeauth_state = crypto_onetimeauth_poly1305_state;
extern "C" {
pub fn crypto_onetimeauth_statebytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_bytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_keybytes() -> usize;
}
extern "C" {
pub fn crypto_onetimeauth_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_onetimeauth(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_verify(
h: *const ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_init(
state: *mut crypto_onetimeauth_state,
key: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_update(
state: *mut crypto_onetimeauth_state,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_final(
state: *mut crypto_onetimeauth_state,
out: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_onetimeauth_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_pwhash_argon2i_alg_argon2i13() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2i_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_passwd_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_passwd_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_saltbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_strbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_strprefix() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_pwhash_argon2i_opslimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_opslimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_memlimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_memlimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_opslimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_memlimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_opslimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_memlimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_opslimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i_memlimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2i(
out: *mut ::std::os::raw::c_uchar,
outlen: ::std::os::raw::c_ulonglong,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
salt: *const ::std::os::raw::c_uchar,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
alg: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2i_str(
out: *mut ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2i_str_verify(
str: *const ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2i_str_needs_rehash(
str: *const ::std::os::raw::c_char,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2id_alg_argon2id13() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2id_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_passwd_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_passwd_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_saltbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_strbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_strprefix() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_pwhash_argon2id_opslimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_opslimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_memlimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_memlimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_opslimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_memlimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_opslimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_memlimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_opslimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id_memlimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_argon2id(
out: *mut ::std::os::raw::c_uchar,
outlen: ::std::os::raw::c_ulonglong,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
salt: *const ::std::os::raw::c_uchar,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
alg: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2id_str(
out: *mut ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2id_str_verify(
str: *const ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_argon2id_str_needs_rehash(
str: *const ::std::os::raw::c_char,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_alg_argon2i13() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_alg_argon2id13() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_alg_default() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_passwd_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_passwd_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_saltbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_strbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_strprefix() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_pwhash_opslimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_opslimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_memlimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_memlimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_opslimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_memlimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_opslimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_memlimit_moderate() -> usize;
}
extern "C" {
pub fn crypto_pwhash_opslimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_memlimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash(
out: *mut ::std::os::raw::c_uchar,
outlen: ::std::os::raw::c_ulonglong,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
salt: *const ::std::os::raw::c_uchar,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
alg: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_str(
out: *mut ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_str_alg(
out: *mut ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
alg: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_str_verify(
str: *const ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_str_needs_rehash(
str: *const ::std::os::raw::c_char,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_scalarmult_curve25519_bytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_curve25519_scalarbytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_curve25519(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
p: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_scalarmult_curve25519_base(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_scalarmult_bytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_scalarbytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_scalarmult_base(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_scalarmult(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
p: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_keybytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_macbytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_boxzerobytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xsalsa20poly1305_zerobytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_keybytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_macbytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_secretbox_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_secretbox_easy(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_open_easy(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_open_detached(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_secretbox_zerobytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_boxzerobytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_xor_ic(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
ic: u64,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_xor_ic(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
ic: u32,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_chacha20_ietf_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_abytes() -> usize;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_headerbytes() -> usize;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_keybytes() -> usize;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_tag_message() -> ::std::os::raw::c_uchar;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_tag_push() -> ::std::os::raw::c_uchar;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_tag_rekey() -> ::std::os::raw::c_uchar;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_tag_final() -> ::std::os::raw::c_uchar;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct crypto_secretstream_xchacha20poly1305_state {
pub k: [::std::os::raw::c_uchar; 32usize],
pub nonce: [::std::os::raw::c_uchar; 12usize],
pub _pad: [::std::os::raw::c_uchar; 8usize],
}
#[test]
fn bindgen_test_layout_crypto_secretstream_xchacha20poly1305_state() {
assert_eq!(
::std::mem::size_of::<crypto_secretstream_xchacha20poly1305_state>(),
52usize,
concat!(
"Size of: ",
stringify!(crypto_secretstream_xchacha20poly1305_state)
)
);
assert_eq!(
::std::mem::align_of::<crypto_secretstream_xchacha20poly1305_state>(),
1usize,
concat!(
"Alignment of ",
stringify!(crypto_secretstream_xchacha20poly1305_state)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_secretstream_xchacha20poly1305_state>())).k as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_secretstream_xchacha20poly1305_state),
"::",
stringify!(k)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_secretstream_xchacha20poly1305_state>())).nonce
as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(crypto_secretstream_xchacha20poly1305_state),
"::",
stringify!(nonce)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<crypto_secretstream_xchacha20poly1305_state>()))._pad as *const _
as usize
},
44usize,
concat!(
"Offset of field: ",
stringify!(crypto_secretstream_xchacha20poly1305_state),
"::",
stringify!(_pad)
)
);
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_statebytes() -> usize;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_init_push(
state: *mut crypto_secretstream_xchacha20poly1305_state,
header: *mut ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_push(
state: *mut crypto_secretstream_xchacha20poly1305_state,
c: *mut ::std::os::raw::c_uchar,
clen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
tag: ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_init_pull(
state: *mut crypto_secretstream_xchacha20poly1305_state,
header: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_pull(
state: *mut crypto_secretstream_xchacha20poly1305_state,
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
tag_p: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
ad: *const ::std::os::raw::c_uchar,
adlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretstream_xchacha20poly1305_rekey(
state: *mut crypto_secretstream_xchacha20poly1305_state,
);
}
extern "C" {
pub fn crypto_shorthash_siphash24_bytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_siphash24_keybytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_siphash24(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_shorthash_siphashx24_bytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_siphashx24_keybytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_siphashx24(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_shorthash_bytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_keybytes() -> usize;
}
extern "C" {
pub fn crypto_shorthash_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_shorthash(
out: *mut ::std::os::raw::c_uchar,
in_: *const ::std::os::raw::c_uchar,
inlen: ::std::os::raw::c_ulonglong,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_shorthash_keygen(k: *mut ::std::os::raw::c_uchar);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct crypto_sign_ed25519ph_state {
pub hs: crypto_hash_sha512_state,
}
#[test]
fn bindgen_test_layout_crypto_sign_ed25519ph_state() {
assert_eq!(
::std::mem::size_of::<crypto_sign_ed25519ph_state>(),
208usize,
concat!("Size of: ", stringify!(crypto_sign_ed25519ph_state))
);
assert_eq!(
::std::mem::align_of::<crypto_sign_ed25519ph_state>(),
8usize,
concat!("Alignment of ", stringify!(crypto_sign_ed25519ph_state))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<crypto_sign_ed25519ph_state>())).hs as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(crypto_sign_ed25519ph_state),
"::",
stringify!(hs)
)
);
}
extern "C" {
pub fn crypto_sign_ed25519ph_statebytes() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519_bytes() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_sign_ed25519(
sm: *mut ::std::os::raw::c_uchar,
smlen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_open(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
sm: *const ::std::os::raw::c_uchar,
smlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_detached(
sig: *mut ::std::os::raw::c_uchar,
siglen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_verify_detached(
sig: *const ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_pk_to_curve25519(
curve25519_pk: *mut ::std::os::raw::c_uchar,
ed25519_pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_sk_to_curve25519(
curve25519_sk: *mut ::std::os::raw::c_uchar,
ed25519_sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_sk_to_seed(
seed: *mut ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519_sk_to_pk(
pk: *mut ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519ph_init(
state: *mut crypto_sign_ed25519ph_state,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519ph_update(
state: *mut crypto_sign_ed25519ph_state,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519ph_final_create(
state: *mut crypto_sign_ed25519ph_state,
sig: *mut ::std::os::raw::c_uchar,
siglen_p: *mut ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_ed25519ph_final_verify(
state: *mut crypto_sign_ed25519ph_state,
sig: *mut ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
pub type crypto_sign_state = crypto_sign_ed25519ph_state;
extern "C" {
pub fn crypto_sign_statebytes() -> usize;
}
extern "C" {
pub fn crypto_sign_bytes() -> usize;
}
extern "C" {
pub fn crypto_sign_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_sign_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_sign_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_sign_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_sign_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_sign_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign(
sm: *mut ::std::os::raw::c_uchar,
smlen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_open(
m: *mut ::std::os::raw::c_uchar,
mlen_p: *mut ::std::os::raw::c_ulonglong,
sm: *const ::std::os::raw::c_uchar,
smlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_detached(
sig: *mut ::std::os::raw::c_uchar,
siglen_p: *mut ::std::os::raw::c_ulonglong,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_verify_detached(
sig: *const ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_init(state: *mut crypto_sign_state) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_update(
state: *mut crypto_sign_state,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_final_create(
state: *mut crypto_sign_state,
sig: *mut ::std::os::raw::c_uchar,
siglen_p: *mut ::std::os::raw::c_ulonglong,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_sign_final_verify(
state: *mut crypto_sign_state,
sig: *mut ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_primitive() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_stream(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_stream_salsa20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa20_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa20_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa20(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa20_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa20_xor_ic(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
ic: u64,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa20_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_verify_16_bytes() -> usize;
}
extern "C" {
pub fn crypto_verify_16(
x: *const ::std::os::raw::c_uchar,
y: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_verify_32_bytes() -> usize;
}
extern "C" {
pub fn crypto_verify_32(
x: *const ::std::os::raw::c_uchar,
y: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_verify_64_bytes() -> usize;
}
extern "C" {
pub fn crypto_verify_64(
x: *const ::std::os::raw::c_uchar,
y: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct randombytes_implementation {
pub implementation_name:
::std::option::Option<unsafe extern "C" fn() -> *const ::std::os::raw::c_char>,
pub random: ::std::option::Option<unsafe extern "C" fn() -> u32>,
pub stir: ::std::option::Option<unsafe extern "C" fn()>,
pub uniform: ::std::option::Option<unsafe extern "C" fn(upper_bound: u32) -> u32>,
pub buf:
::std::option::Option<unsafe extern "C" fn(buf: *mut ::std::os::raw::c_void, size: usize)>,
pub close: ::std::option::Option<unsafe extern "C" fn() -> ::std::os::raw::c_int>,
}
#[test]
fn bindgen_test_layout_randombytes_implementation() {
assert_eq!(
::std::mem::size_of::<randombytes_implementation>(),
48usize,
concat!("Size of: ", stringify!(randombytes_implementation))
);
assert_eq!(
::std::mem::align_of::<randombytes_implementation>(),
8usize,
concat!("Alignment of ", stringify!(randombytes_implementation))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<randombytes_implementation>())).implementation_name as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(implementation_name)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<randombytes_implementation>())).random as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(random)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<randombytes_implementation>())).stir as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(stir)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<randombytes_implementation>())).uniform as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(uniform)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<randombytes_implementation>())).buf as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(buf)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<randombytes_implementation>())).close as *const _ as usize
},
40usize,
concat!(
"Offset of field: ",
stringify!(randombytes_implementation),
"::",
stringify!(close)
)
);
}
extern "C" {
pub fn randombytes_seedbytes() -> usize;
}
extern "C" {
pub fn randombytes_buf(buf: *mut ::std::os::raw::c_void, size: usize);
}
extern "C" {
pub fn randombytes_buf_deterministic(
buf: *mut ::std::os::raw::c_void,
size: usize,
seed: *const ::std::os::raw::c_uchar,
);
}
extern "C" {
pub fn randombytes_random() -> u32;
}
extern "C" {
pub fn randombytes_uniform(upper_bound: u32) -> u32;
}
extern "C" {
pub fn randombytes_stir();
}
extern "C" {
pub fn randombytes_close() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn randombytes_set_implementation(
impl_: *mut randombytes_implementation,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn randombytes_implementation_name() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn randombytes(buf: *mut ::std::os::raw::c_uchar, buf_len: ::std::os::raw::c_ulonglong);
}
extern "C" {
#[link_name = "\u{1}randombytes_salsa20_implementation"]
pub static mut randombytes_salsa20_implementation: randombytes_implementation;
}
extern "C" {
#[link_name = "\u{1}randombytes_sysrandom_implementation"]
pub static mut randombytes_sysrandom_implementation: randombytes_implementation;
}
extern "C" {
pub fn sodium_runtime_has_neon() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_sse2() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_sse3() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_ssse3() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_sse41() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_avx() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_avx2() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_avx512f() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_pclmul() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_aesni() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_runtime_has_rdrand() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _sodium_runtime_get_cpu_features() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_memzero(pnt: *mut ::std::os::raw::c_void, len: usize);
}
extern "C" {
pub fn sodium_stackzero(len: usize);
}
extern "C" {
pub fn sodium_memcmp(
b1_: *const ::std::os::raw::c_void,
b2_: *const ::std::os::raw::c_void,
len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_compare(
b1_: *const ::std::os::raw::c_uchar,
b2_: *const ::std::os::raw::c_uchar,
len: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_is_zero(n: *const ::std::os::raw::c_uchar, nlen: usize) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_increment(n: *mut ::std::os::raw::c_uchar, nlen: usize);
}
extern "C" {
pub fn sodium_add(
a: *mut ::std::os::raw::c_uchar,
b: *const ::std::os::raw::c_uchar,
len: usize,
);
}
extern "C" {
pub fn sodium_bin2hex(
hex: *mut ::std::os::raw::c_char,
hex_maxlen: usize,
bin: *const ::std::os::raw::c_uchar,
bin_len: usize,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn sodium_hex2bin(
bin: *mut ::std::os::raw::c_uchar,
bin_maxlen: usize,
hex: *const ::std::os::raw::c_char,
hex_len: usize,
ignore: *const ::std::os::raw::c_char,
bin_len: *mut usize,
hex_end: *mut *const ::std::os::raw::c_char,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_base64_encoded_len(bin_len: usize, variant: ::std::os::raw::c_int) -> usize;
}
extern "C" {
pub fn sodium_bin2base64(
b64: *mut ::std::os::raw::c_char,
b64_maxlen: usize,
bin: *const ::std::os::raw::c_uchar,
bin_len: usize,
variant: ::std::os::raw::c_int,
) -> *mut ::std::os::raw::c_char;
}
extern "C" {
pub fn sodium_base642bin(
bin: *mut ::std::os::raw::c_uchar,
bin_maxlen: usize,
b64: *const ::std::os::raw::c_char,
b64_len: usize,
ignore: *const ::std::os::raw::c_char,
bin_len: *mut usize,
b64_end: *mut *const ::std::os::raw::c_char,
variant: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_mlock(addr: *mut ::std::os::raw::c_void, len: usize) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_munlock(addr: *mut ::std::os::raw::c_void, len: usize) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_malloc(size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn sodium_allocarray(count: usize, size: usize) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn sodium_free(ptr: *mut ::std::os::raw::c_void);
}
extern "C" {
pub fn sodium_mprotect_noaccess(ptr: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_mprotect_readonly(ptr: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_mprotect_readwrite(ptr: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_pad(
padded_buflen_p: *mut usize,
buf: *mut ::std::os::raw::c_uchar,
unpadded_buflen: usize,
blocksize: usize,
max_buflen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn sodium_unpad(
unpadded_buflen_p: *mut usize,
buf: *const ::std::os::raw::c_uchar,
padded_buflen: usize,
blocksize: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn _sodium_alloc_init() -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xchacha20_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_xchacha20_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_xchacha20_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_xchacha20(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xchacha20_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xchacha20_xor_ic(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
ic: u64,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_xchacha20_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_seedbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_publickeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_secretkeybytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_beforenmbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_macbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_seed_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
seed: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_keypair(
pk: *mut ::std::os::raw::c_uchar,
sk: *mut ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_easy(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_open_easy(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_open_detached(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_beforenm(
k: *mut ::std::os::raw::c_uchar,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_easy_afternm(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_open_easy_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_detached_afternm(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_open_detached_afternm(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_sealbytes() -> usize;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_seal(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_box_curve25519xchacha20poly1305_seal_open(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
pk: *const ::std::os::raw::c_uchar,
sk: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_ed25519_bytes() -> usize;
}
extern "C" {
pub fn crypto_core_ed25519_uniformbytes() -> usize;
}
extern "C" {
pub fn crypto_core_ed25519_is_valid_point(
p: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_ed25519_add(
r: *mut ::std::os::raw::c_uchar,
p: *const ::std::os::raw::c_uchar,
q: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_ed25519_sub(
r: *mut ::std::os::raw::c_uchar,
p: *const ::std::os::raw::c_uchar,
q: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_core_ed25519_from_uniform(
p: *mut ::std::os::raw::c_uchar,
r: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_scalarmult_ed25519_bytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_ed25519_scalarbytes() -> usize;
}
extern "C" {
pub fn crypto_scalarmult_ed25519(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
p: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_scalarmult_ed25519_base(
q: *mut ::std::os::raw::c_uchar,
n: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_keybytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_macbytes() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_easy(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_open_easy(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_detached(
c: *mut ::std::os::raw::c_uchar,
mac: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_secretbox_xchacha20poly1305_open_detached(
m: *mut ::std::os::raw::c_uchar,
c: *const ::std::os::raw::c_uchar,
mac: *const ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_bytes_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_bytes_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_passwd_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_passwd_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_saltbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_strbytes() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_strprefix() -> *const ::std::os::raw::c_char;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_opslimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_opslimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_memlimit_min() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_memlimit_max() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_opslimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_memlimit_interactive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_opslimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_memlimit_sensitive() -> usize;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256(
out: *mut ::std::os::raw::c_uchar,
outlen: ::std::os::raw::c_ulonglong,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
salt: *const ::std::os::raw::c_uchar,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_str(
out: *mut ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_str_verify(
str: *const ::std::os::raw::c_char,
passwd: *const ::std::os::raw::c_char,
passwdlen: ::std::os::raw::c_ulonglong,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_ll(
passwd: *const u8,
passwdlen: usize,
salt: *const u8,
saltlen: usize,
N: u64,
r: u32,
p: u32,
buf: *mut u8,
buflen: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_pwhash_scryptsalsa208sha256_str_needs_rehash(
str: *const ::std::os::raw::c_char,
opslimit: ::std::os::raw::c_ulonglong,
memlimit: usize,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa2012_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa2012_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa2012_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa2012(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa2012_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa2012_keygen(k: *mut ::std::os::raw::c_uchar);
}
extern "C" {
pub fn crypto_stream_salsa208_keybytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa208_noncebytes() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa208_messagebytes_max() -> usize;
}
extern "C" {
pub fn crypto_stream_salsa208(
c: *mut ::std::os::raw::c_uchar,
clen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa208_xor(
c: *mut ::std::os::raw::c_uchar,
m: *const ::std::os::raw::c_uchar,
mlen: ::std::os::raw::c_ulonglong,
n: *const ::std::os::raw::c_uchar,
k: *const ::std::os::raw::c_uchar,
) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn crypto_stream_salsa208_keygen(k: *mut ::std::os::raw::c_uchar);
}
pub type __builtin_va_list = [__va_list_tag; 1usize];
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __va_list_tag {
pub gp_offset: ::std::os::raw::c_uint,
pub fp_offset: ::std::os::raw::c_uint,
pub overflow_arg_area: *mut ::std::os::raw::c_void,
pub reg_save_area: *mut ::std::os::raw::c_void,
}
#[test]
fn bindgen_test_layout___va_list_tag() {
assert_eq!(
::std::mem::size_of::<__va_list_tag>(),
24usize,
concat!("Size of: ", stringify!(__va_list_tag))
);
assert_eq!(
::std::mem::align_of::<__va_list_tag>(),
8usize,
concat!("Alignment of ", stringify!(__va_list_tag))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__va_list_tag>())).gp_offset as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__va_list_tag),
"::",
stringify!(gp_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__va_list_tag>())).fp_offset as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(__va_list_tag),
"::",
stringify!(fp_offset)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__va_list_tag>())).overflow_arg_area as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(__va_list_tag),
"::",
stringify!(overflow_arg_area)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__va_list_tag>())).reg_save_area as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__va_list_tag),
"::",
stringify!(reg_save_area)
)
);
}
<file_sep>extern crate cc;
fn main() {
cc::Build::new()
.define("CONFIGURED", "1")
.warnings(false)
.include("vendor/src/libsodium/crypto_sign/ed25519/ref10/")
.include("vendor/src/libsodium/crypto_core/ed25519/ref10/fe_51/")
.include("vendor/src/libsodium/crypto_core/ed25519/ref10/fe_25_5/")
.include("vendor/src/libsodium/crypto_onetimeauth/poly1305/")
.include("vendor/src/libsodium/crypto_onetimeauth/poly1305/donna/")
.include("vendor/src/libsodium/crypto_onetimeauth/poly1305/sse2/")
.include("vendor/src/libsodium/crypto_generichash/blake2b/ref/")
.include("vendor/src/libsodium/crypto_stream/chacha20/dolbeau/")
.include("vendor/src/libsodium/crypto_stream/chacha20/ref/")
.include("vendor/src/libsodium/crypto_stream/chacha20/")
.include("vendor/src/libsodium/crypto_stream/salsa20/xmm6/")
.include("vendor/src/libsodium/crypto_stream/salsa20/xmm6int/")
.include("vendor/src/libsodium/crypto_stream/salsa20/ref/")
.include("vendor/src/libsodium/crypto_stream/salsa20/")
.include("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/")
.include("vendor/src/libsodium/crypto_pwhash/argon2/")
.include("vendor/src/libsodium/crypto_scalarmult/curve25519/")
.include("vendor/src/libsodium/crypto_scalarmult/curve25519/sandy2x/")
.include("vendor/src/libsodium/crypto_scalarmult/curve25519/ref10/")
.include("vendor/src/libsodium/include/sodium/")
.include("vendor/src/libsodium/include/sodium/private/")
.include("vendor/src/libsodium/include/sodium/")
.include("vendor/src/libsodium/include/")
.include("vendor/src/libsodium/crypto_shorthash/siphash24/ref/")
.include("vendor/builds/msvc/")
.file("vendor/src/libsodium/crypto_verify/sodium/verify.c")
.file("vendor/src/libsodium/crypto_sign/crypto_sign.c")
.file("vendor/src/libsodium/crypto_sign/ed25519/sign_ed25519.c")
.file("vendor/src/libsodium/crypto_sign/ed25519/ref10/obsolete.c")
.file("vendor/src/libsodium/crypto_sign/ed25519/ref10/sign.c")
.file("vendor/src/libsodium/crypto_sign/ed25519/ref10/keypair.c")
.file("vendor/src/libsodium/crypto_sign/ed25519/ref10/open.c")
.file("vendor/src/libsodium/crypto_core/hchacha20/core_hchacha20.c")
.file("vendor/src/libsodium/crypto_core/salsa/ref/core_salsa_ref.c")
.file("vendor/src/libsodium/crypto_core/hsalsa20/ref2/core_hsalsa20_ref2.c")
.file("vendor/src/libsodium/crypto_core/hsalsa20/core_hsalsa20.c")
.file("vendor/src/libsodium/crypto_core/ed25519/core_ed25519.c")
.file("vendor/src/libsodium/crypto_core/ed25519/ref10/ed25519_ref10.c")
.file("vendor/src/libsodium/crypto_onetimeauth/crypto_onetimeauth.c")
.file("vendor/src/libsodium/crypto_onetimeauth/poly1305/onetimeauth_poly1305.c")
.file("vendor/src/libsodium/crypto_onetimeauth/poly1305/donna/poly1305_donna.c")
.file("vendor/src/libsodium/crypto_onetimeauth/poly1305/sse2/poly1305_sse2.c")
.file("vendor/src/libsodium/crypto_hash/sha512/cp/hash_sha512_cp.c")
.file("vendor/src/libsodium/crypto_hash/sha512/hash_sha512.c")
.file("vendor/src/libsodium/crypto_hash/crypto_hash.c")
.file("vendor/src/libsodium/crypto_hash/sha256/hash_sha256.c")
.file("vendor/src/libsodium/crypto_hash/sha256/cp/hash_sha256_cp.c")
.file("vendor/src/libsodium/crypto_aead/chacha20poly1305/sodium/aead_chacha20poly1305.c")
.file("vendor/src/libsodium/crypto_aead/aes256gcm/aesni/aead_aes256gcm_aesni.c")
.file("vendor/src/libsodium/crypto_aead/xchacha20poly1305/sodium/aead_xchacha20poly1305.c")
.file("vendor/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c")
.file("vendor/src/libsodium/randombytes/randombytes.c")
.file("vendor/src/libsodium/randombytes/salsa20/randombytes_salsa20_random.c")
.file("vendor/src/libsodium/randombytes/nativeclient/randombytes_nativeclient.c")
.file("vendor/src/libsodium/crypto_auth/hmacsha256/auth_hmacsha256.c")
.file("vendor/src/libsodium/crypto_auth/hmacsha512/auth_hmacsha512.c")
.file("vendor/src/libsodium/crypto_auth/hmacsha512256/auth_hmacsha512256.c")
.file("vendor/src/libsodium/crypto_auth/crypto_auth.c")
.file("vendor/src/libsodium/crypto_generichash/crypto_generichash.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/generichash_blake2.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/blake2b-compress-sse41.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/blake2b-compress-ssse3.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/blake2b-compress-ref.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/generichash_blake2b.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/blake2b-ref.c")
.file("vendor/src/libsodium/crypto_generichash/blake2b/ref/blake2b-compress-avx2.c")
.file("vendor/src/libsodium/crypto_stream/salsa208/stream_salsa208.c")
.file("vendor/src/libsodium/crypto_stream/salsa208/ref/stream_salsa208_ref.c")
.file("vendor/src/libsodium/crypto_stream/salsa2012/ref/stream_salsa2012_ref.c")
.file("vendor/src/libsodium/crypto_stream/salsa2012/stream_salsa2012.c")
.file("vendor/src/libsodium/crypto_stream/crypto_stream.c")
.file("vendor/src/libsodium/crypto_stream/xsalsa20/stream_xsalsa20.c")
.file("vendor/src/libsodium/crypto_stream/chacha20/stream_chacha20.c")
.file("vendor/src/libsodium/crypto_stream/chacha20/dolbeau/chacha20_dolbeau-ssse3.c")
.file("vendor/src/libsodium/crypto_stream/chacha20/dolbeau/chacha20_dolbeau-avx2.c")
.file("vendor/src/libsodium/crypto_stream/chacha20/ref/chacha20_ref.c")
.file("vendor/src/libsodium/crypto_stream/xchacha20/stream_xchacha20.c")
.file("vendor/src/libsodium/crypto_stream/salsa20/xmm6/salsa20_xmm6.c")
.file("vendor/src/libsodium/crypto_stream/salsa20/xmm6int/salsa20_xmm6int-avx2.c")
.file("vendor/src/libsodium/crypto_stream/salsa20/xmm6int/salsa20_xmm6int-sse2.c")
.file("vendor/src/libsodium/crypto_stream/salsa20/stream_salsa20.c")
.file("vendor/src/libsodium/crypto_stream/salsa20/ref/salsa20_ref.c")
.file("vendor/src/libsodium/crypto_kdf/crypto_kdf.c")
.file("vendor/src/libsodium/crypto_kdf/blake2b/kdf_blake2b.c")
.file("vendor/src/libsodium/crypto_secretstream/xchacha20poly1305/secretstream_xchacha20poly1305.c")
.file("vendor/src/libsodium/crypto_pwhash/crypto_pwhash.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/pbkdf2-sha256.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/scrypt_platform.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/pwhash_scryptsalsa208sha256.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/sse/pwhash_scryptsalsa208sha256_sse.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/nosse/pwhash_scryptsalsa208sha256_nosse.c")
.file("vendor/src/libsodium/crypto_pwhash/scryptsalsa208sha256/crypto_scrypt-common.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/pwhash_argon2i.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-fill-block-avx512f.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/blake2b-long.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/pwhash_argon2id.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-fill-block-ref.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-fill-block-ssse3.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-encoding.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-core.c")
.file("vendor/src/libsodium/crypto_pwhash/argon2/argon2-fill-block-avx2.c")
.file("vendor/src/libsodium/crypto_kx/crypto_kx.c")
.file("vendor/src/libsodium/sodium/runtime.c")
.file("vendor/src/libsodium/sodium/codecs.c")
.file("vendor/src/libsodium/sodium/core.c")
.file("vendor/src/libsodium/sodium/version.c")
.file("vendor/src/libsodium/sodium/utils.c")
.file("vendor/src/libsodium/crypto_scalarmult/crypto_scalarmult.c")
.file("vendor/src/libsodium/crypto_scalarmult/curve25519/sandy2x/fe51_invert.c")
.file("vendor/src/libsodium/crypto_scalarmult/curve25519/sandy2x/fe_frombytes_sandy2x.c")
.file("vendor/src/libsodium/crypto_scalarmult/curve25519/sandy2x/curve25519_sandy2x.c")
.file("vendor/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c")
.file("vendor/src/libsodium/crypto_scalarmult/curve25519/scalarmult_curve25519.c")
.file("vendor/src/libsodium/crypto_scalarmult/ed25519/ref10/scalarmult_ed25519_ref10.c")
.file("vendor/src/libsodium/crypto_box/curve25519xchacha20poly1305/box_seal_curve25519xchacha20poly1305.c")
.file("vendor/src/libsodium/crypto_box/curve25519xchacha20poly1305/box_curve25519xchacha20poly1305.c")
.file("vendor/src/libsodium/crypto_box/crypto_box.c")
.file("vendor/src/libsodium/crypto_box/crypto_box_seal.c")
.file("vendor/src/libsodium/crypto_box/crypto_box_easy.c")
.file("vendor/src/libsodium/crypto_box/curve25519xsalsa20poly1305/box_curve25519xsalsa20poly1305.c")
.file("vendor/src/libsodium/crypto_secretbox/crypto_secretbox.c")
.file("vendor/src/libsodium/crypto_secretbox/xsalsa20poly1305/secretbox_xsalsa20poly1305.c")
.file("vendor/src/libsodium/crypto_secretbox/crypto_secretbox_easy.c")
.file("vendor/src/libsodium/crypto_secretbox/xchacha20poly1305/secretbox_xchacha20poly1305.c")
.file("vendor/src/libsodium/crypto_shorthash/crypto_shorthash.c")
.file("vendor/src/libsodium/crypto_shorthash/siphash24/shorthash_siphashx24.c")
.file("vendor/src/libsodium/crypto_shorthash/siphash24/ref/shorthash_siphashx24_ref.c")
.file("vendor/src/libsodium/crypto_shorthash/siphash24/ref/shorthash_siphash24_ref.c")
.file("vendor/src/libsodium/crypto_shorthash/siphash24/shorthash_siphash24.c")
.compile("libsodium")
}
| c13c784dab79be9a1f64d468b184391f672b5d1a | [
"TOML",
"Rust"
] | 3 | TOML | canndrew/libsodium-sys | c78bd5dda67181f695edd855be873db8a85e3e0c | 0fdcd6725aca307243f092aebaf7cb8f8ec51eec |
refs/heads/master | <repo_name>yellappadamam/sampleapp<file_sep>/app/src/main/java/com/damam/wtestapp/io/ListResponse.java
package com.damam.wtestapp.io;
import java.util.ArrayList;
/**
* Created by Damam on 03-May-16.
*/
public class ListResponse {
public String title;
public ArrayList<ListItem> rows;
}
<file_sep>/app/src/main/java/com/damam/wtestapp/listener/GetListListener.java
package com.damam.wtestapp.listener;
import com.damam.wtestapp.io.ListResponse;
/**
* Created by Damam on 03-May-16.
*/
public interface GetListListener {
// Returns the result to UI.
void onSuccess(ListResponse listResponse);
// Return failure.
void onFailure();
}
| 2515e29b8fb1c73548ab3701d6a3016d0cac58c3 | [
"Java"
] | 2 | Java | yellappadamam/sampleapp | d25e48afef7f8d6c4d84d143acc8d0c7b4f8ed37 | 383f7406d503c7c6477341d6123bb470f3afbee3 |
refs/heads/master | <file_sep>../responsive_layout.py | 0188e15aa1868ea08e5b8a543f5d86a506c5771a | [
"Python"
] | 1 | Python | alexschneider/dotfiles | 11aa425af85a755e555e9b46765a7de9a81055c7 | b42e1fab10914910265e87cb7920929052af966d |
refs/heads/main | <file_sep>import React from 'react'
import {Link} from 'gatsby'
export default function article(props) {
return (
<div>
<Link to={props.to}>
<article key={props.id}>
<div>
<img src={"http://source.unsplash.com/150x150/?" + props.keywords} />
</div>
<div>
<h3>
{props.title}
</h3>
<div>
{props.excerpt}
</div>
</div>
</article>
</Link>
</div>
)
}
<file_sep>import React, { lazy, Suspense} from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Title from "../components/title"
// import ArticleList from '../components/article-list'
const ArticleList = lazy(() => import(`../components/article-list`));
//import styles from "./index.module.scss"
export default function Home({data}) {
return (
<div>
<Layout>
<Title text="Welcome" />
<Link to="/about">Search bar</Link>
<Link to="/orderHistory">OrderHistory</Link>
<p>Recent posts are here. Click for detail.</p>
<Suspense fallback={<div>still loading...</div>}>
<ArticleList />
</Suspense>
</Layout>
</div>
)
}
<file_sep>import React from 'react'
import { Link } from "gatsby"
import Layout from "../components/layout"
import Title from "../components/title"
import Search from "../components/SearchContainer"
export default function about() {
return (
<div>
<Layout>
<Search />
<Title text="Search bar" />
</Layout>
</div>
)
}
| 301cb9bad58ce009dfb99a7a7d1abf3bc7a5874a | [
"JavaScript"
] | 3 | JavaScript | Kakkoo/gatsby-starter-hello-world | 9f8ea5dc5523f3e763f79cce4438d158a73b63dc | f95fa356adcb901a1c8ea8a494ba8266651c3211 |
refs/heads/master | <file_sep># OGL_ModelData
OGMとかいう謎のモデルデータ
★注意点
・pmxをogmにコンバートした時、
テクスチャ画像とかはコンバートorコピーされないから、
ogmファイルからのパスでアクセス出来る所に手動でコピーしてあげてね。
・ogmと同じフォルダにshareTexとかいうの置いてあげてね。
(主に共有Toonとスフィア周りのごにょごにょ処理)<file_sep>//==========================
//===【OgmData.h】
//==========================
// Ogmデータを保持します。
// (OGL_D3D11で用いるモデルデータ)
//==========================
#pragma once
//=====================//
//===【インクルード記述】 ===//
//=====================//
#include"../PmxData/PmxData.h"
#include<string>
#include<vector>
namespace OGL
{
class PmxData;
class OgmData
{
public:
bool ImportFromModelData(PmxData* modelData);
bool ImportFromModelFile(std::string fileName);
bool ExportFile(std::string fileName);
struct T_VertexData
{
std::vector<D3DXVECTOR4> pos;
std::vector<D3DXVECTOR4> normal;
std::vector<D3DXVECTOR4> uv;
std::vector<D3DXVECTOR4> boneIndex;
std::vector<D3DXVECTOR4> boneWeight;
};
struct T_TextureIndex
{
int diffuse;
int toon;
int addSphere;
int mulSphere;
};
struct T_MaterialData
{
D3DXVECTOR4 diffuse;
D3DXVECTOR4 specular; //wはPower
D3DXVECTOR4 ambient;
};
private:
std::vector<int> m_vertexIndex;
T_VertexData m_vertexData;
std::vector<std::string> m_textureName;
std::vector<int> m_materialRefVertexIndexCount;
std::vector<T_TextureIndex> m_textureIndex;
std::vector<T_MaterialData> m_materialData;
public:
OgmData();
~OgmData();
}; //EndOf__class_OgmData
} //EndOf__namespace_OGL
/*
OGMファイルフォーマット
int インデックス数;
int[] インデックス配列;
int 頂点数;
D3DXVECTOR4[] pos;
D3DXVECTOR4[] normal;
D3DXVECTOR4[] uv;
D3DXVECTOR4[] boneIndex;
D3DXVECTOR4[] boneWeight;
int テクスチャ数;
配列
{
std::string::size_type 文字数
std::string[] テクスチャ名
}
int マテリアル数;
int[] マテリアル参照頂点インデックス数
T_TextureIndex[] テクスチャインデックス情報
T_MaterialData[] マテリアル情報
*/<file_sep>//==========================
//===【OgmData.cpp】
//==========================
// Ogmデータを保持します。
// (OGL_D3D11で用いるモデルデータ)
//==========================
//=====================//
//===【インクルード記述】 ===//
//=====================//
#include "OgmData.h"
#include<fstream>
OGL::OgmData::OgmData()
{
}
OGL::OgmData::~OgmData()
{
}
bool OGL::OgmData::ImportFromModelData(PmxData* modelData)
{
if (modelData->m_pmxVersion == 0)
{
MessageBox(NULL, TEXT("PmxDataにモデルが読み込まれていません。"), TEXT("Err"), MB_OK);
return false;
}
//インデックスデータロード
for (int i = 0; i < modelData->m_vertexIndex.size(); i++)
{
m_vertexIndex.push_back((int)modelData->m_vertexIndex[i].x);
m_vertexIndex.push_back((int)modelData->m_vertexIndex[i].y);
m_vertexIndex.push_back((int)modelData->m_vertexIndex[i].z);
}
//頂点データをロード
for (int i = 0; i < modelData->m_vertexData.size(); i++)
{
m_vertexData.pos.push_back(D3DXVECTOR4(modelData->m_vertexData[i].pos, 1));
m_vertexData.normal.push_back(D3DXVECTOR4(modelData->m_vertexData[i].normal, 1));
m_vertexData.uv.push_back(D3DXVECTOR4(modelData->m_vertexData[i].texUV.x, modelData->m_vertexData[i].texUV.y, 0, 0));
m_vertexData.boneIndex.push_back(D3DXVECTOR4(modelData->m_vertexData[i].boneIndex[0], modelData->m_vertexData[i].boneIndex[1], modelData->m_vertexData[i].boneIndex[2], modelData->m_vertexData[i].boneIndex[3]));
m_vertexData.boneWeight.push_back(D3DXVECTOR4(modelData->m_vertexData[i].boneWeight[0], modelData->m_vertexData[i].boneWeight[1], modelData->m_vertexData[i].boneWeight[2], modelData->m_vertexData[i].boneWeight[3]));
}
//テクスチャ名をロード
for (int i = 0; i < modelData->m_texturePass.size(); i++)
{
m_textureName.push_back(modelData->m_texturePass[i]);
}
m_textureName.push_back("shareTex/toon0.bmp");
m_textureName.push_back("shareTex/toon01.bmp");
m_textureName.push_back("shareTex/toon02.bmp");
m_textureName.push_back("shareTex/toon03.bmp");
m_textureName.push_back("shareTex/toon04.bmp");
m_textureName.push_back("shareTex/toon05.bmp");
m_textureName.push_back("shareTex/toon06.bmp");
m_textureName.push_back("shareTex/toon07.bmp");
m_textureName.push_back("shareTex/toon08.bmp");
m_textureName.push_back("shareTex/toon09.bmp");
m_textureName.push_back("shareTex/toon10.bmp");
m_textureName.push_back("shareTex/blackTexture.png");
m_textureName.push_back("shareTex/whiteTexture.png");
//マテリアル情報をロード
for (int i = 0; i < modelData->m_materialData.size(); i++)
{
m_materialRefVertexIndexCount.push_back(modelData->m_materialData[i].referenceVertexIndexCount);
T_TextureIndex temp;
if (modelData->m_materialData[i].diffuseTextureIndex == 255)
{
temp.diffuse = m_textureName.size() - 1;
}
else
{
temp.diffuse = modelData->m_materialData[i].diffuseTextureIndex;
}
if (modelData->m_materialData[i].toonTextureShareFlg == true)
{
temp.toon = m_textureName.size() - 12 + modelData->m_materialData[i].toonTextureShareIndex;
}
else
{
if (modelData->m_materialData[i].toonTextureIndex == 255)
{
temp.toon = m_textureName.size() - 1;
}
else
{
temp.toon = modelData->m_materialData[i].toonTextureIndex;
}
}
switch (modelData->m_materialData[i].sphereType)
{
case 0:
temp.addSphere = m_textureName.size() - 2;
temp.mulSphere = m_textureName.size() - 1;
break;
case 1:
temp.addSphere = m_textureName.size() - 2;
temp.mulSphere = modelData->m_materialData[i].sphereTextureIndex;
break;
case 2:
temp.addSphere = modelData->m_materialData[i].sphereTextureIndex;
temp.mulSphere = m_textureName.size() - 1;
break;
case 3:
MessageBox(NULL, TEXT("特殊スフィアマップは使えません"), TEXT("Err"), MB_OK);
return false;
break;
}
m_textureIndex.push_back(temp);
T_MaterialData mat_temp;
mat_temp.diffuse = modelData->m_materialData[i].diffuse;
mat_temp.ambient = D3DXVECTOR4(modelData->m_materialData[i].ambient,1);
mat_temp.specular = D3DXVECTOR4(modelData->m_materialData[i].specular, modelData->m_materialData[i].specularPower);
m_materialData.push_back(mat_temp);
}
return true;
}
bool OGL::OgmData::ImportFromModelFile(std::string fileName)
{
std::ifstream ogmFile(fileName, std::ios_base::in | std::ios_base::binary);
if (!ogmFile)
{
MessageBox(NULL, TEXT("ファイルを読み込めていません。"), TEXT("Err"), MB_OK);
return false;
}
int temp = 0;
ogmFile.read((char*)&temp, sizeof(int));
m_vertexIndex.resize(temp);
ogmFile.read((char*)&m_vertexIndex[0], sizeof(int)*temp);
ogmFile.read((char*)&temp, sizeof(int));
m_vertexData.pos.resize(temp);
ogmFile.read((char*)&m_vertexData.pos[0], sizeof(D3DXVECTOR4)*temp);
m_vertexData.normal.resize(temp);
ogmFile.read((char*)&m_vertexData.normal[0], sizeof(D3DXVECTOR4)*temp);
m_vertexData.uv.resize(temp);
ogmFile.read((char*)&m_vertexData.uv[0], sizeof(D3DXVECTOR4)*temp);
m_vertexData.boneIndex.resize(temp);
ogmFile.read((char*)&m_vertexData.boneIndex[0], sizeof(D3DXVECTOR4)*temp);
m_vertexData.boneWeight.resize(temp);
ogmFile.read((char*)&m_vertexData.boneWeight[0], sizeof(D3DXVECTOR4)*temp);
ogmFile.read((char*)&temp, sizeof(int));
for (int i = 0; i < temp; i++)
{
std::string::size_type strLen;
ogmFile.read((char*)&strLen, sizeof(std::string::size_type));
char* name = (char*)std::malloc(strLen + 1);
ogmFile.read(name, strLen);
name[strLen] = '\0';
std::string str(name);
m_textureName.push_back(str);
std::free(name);
}
ogmFile.read((char*)&temp, sizeof(int));
m_materialRefVertexIndexCount.resize(temp);
ogmFile.read((char*)&m_materialRefVertexIndexCount[0], sizeof(int)*temp);
m_textureIndex.resize(temp);
ogmFile.read((char*)&m_textureIndex[0], sizeof(T_TextureIndex)*temp);
m_materialData.resize(temp);
ogmFile.read((char*)&m_materialData[0], sizeof(T_MaterialData)*temp);
ogmFile.close();
return true;
}
bool OGL::OgmData::ExportFile(std::string fileName)
{
std::ofstream ogmFile(fileName, std::ios::out | std::ios::trunc | std::ios::binary);
int temp = m_vertexIndex.size();
ogmFile.write((const char*)&temp, sizeof(int));
ogmFile.write((const char*)&m_vertexIndex[0], sizeof(int)*temp);
temp = m_vertexData.pos.size();
ogmFile.write((const char*)&temp, sizeof(int));
ogmFile.write((const char*)&m_vertexData.pos[0], sizeof(D3DXVECTOR4)*temp);
ogmFile.write((const char*)&m_vertexData.normal[0], sizeof(D3DXVECTOR4)*temp);
ogmFile.write((const char*)&m_vertexData.uv[0], sizeof(D3DXVECTOR4)*temp);
ogmFile.write((const char*)&m_vertexData.boneIndex[0], sizeof(D3DXVECTOR4)*temp);
ogmFile.write((const char*)&m_vertexData.boneWeight[0], sizeof(D3DXVECTOR4)*temp);
temp = m_textureName.size();
ogmFile.write((const char*)&temp, sizeof(int));
for (int i = 0; i < temp; i++)
{
std::string::size_type strLen = m_textureName[i].size();
ogmFile.write((const char*)&strLen, sizeof(strLen));
ogmFile.write(m_textureName[i].c_str(), sizeof(char)*strLen);
}
temp = m_materialRefVertexIndexCount.size();
ogmFile.write((const char*)&temp, sizeof(int));
ogmFile.write((const char*)&m_materialRefVertexIndexCount[0], sizeof(int)*temp);
ogmFile.write((const char*)&m_textureIndex[0], sizeof(T_TextureIndex)*temp);
ogmFile.write((const char*)&m_materialData[0], sizeof(T_MaterialData)*temp);
ogmFile.close();
return true;
}<file_sep>//==========================
//===【PmxData.cpp】
//==========================
// Pmxデータを保持します。
//==========================
//=====================//
//===【インクルード記述】 ===//
//=====================//
#include "PmxData.h"
using namespace std;
OGL::PmxData::PmxData()
{
m_pmxVersion = 0;
}
OGL::PmxData::~PmxData()
{
}
#define Read(data,style)(pmxData.read((char*)&data, sizeof(style)))
//■■■■■■■■■■■//
//■■■【public】■■■//
//■■■■■■■■■■■//
//■■■■■■■■■■■■■■■■■■■■■■
//■■■ 機能:pmxファイルをロードします。
//■■■ 引数1:char*:ファイル名
//■■■ 返値:void
//■■■■■■■■■■■■■■■■■■■■■■
bool OGL::PmxData::LoadFile(char* fileName)
{
setlocale(LC_CTYPE, "");
pmxData.open(fileName, ios::in | ios::binary);
//▼▼▼テクスチャファイルパス用の文字列を生成▼▼▼//
string filePass = fileName;
filePass.erase(filePass.find_last_of('/') + 1, filePass.length());
if (pmxData.fail())
{
MessageBox(NULL, TEXT("ファイルの読み込みに失敗しました。\nファイルパスを間違えている可能性があります。"), TEXT("Err"), MB_OK);
return false;
}
byte pmxCheck[4];
Read(pmxCheck[0], byte);
Read(pmxCheck[1], byte);
Read(pmxCheck[2], byte);
Read(pmxCheck[3], byte);
if (!(pmxCheck[0] == 0x50 && pmxCheck[1] == 0x4d &&
pmxCheck[2] == 0x58 && pmxCheck[3] == 0x20))
{
MessageBox(NULL, TEXT("このファイルはPMX形式ではありません。"), TEXT("Err"), MB_OK);
return false;
}
Read(m_pmxVersion, float);
printf("PMX VERSION:%2f\n", m_pmxVersion);
byte headerSize=0;
Read(headerSize, byte);
for (int i = 0; i < headerSize; i++)
{
Read(m_headerData[i], byte);
}
if (m_headerData[HS_encodeStyle] != 0)
{
MessageBox(NULL, TEXT("PMXファイルのエンコード方式を\nUTF16に指定して下さい。"), TEXT("Err"), MB_OK);
return false;
}
m_modelNameJapanese = ReadText();
m_modelNameEnglish = ReadText();
m_commentEnglish = ReadText();
m_commentJapanese = ReadText();
//▼▼▼頂点数抽出▼▼▼//
int count = 0;
Read(count, int);
//▼▼▼頂点情報抽出▼▼▼//
for (int vertexNum = 0; vertexNum < count; vertexNum++)
{
T_PmxVertexData tempVertexData;
Read(tempVertexData.pos, D3DXVECTOR3);
Read(tempVertexData.normal, D3DXVECTOR3);
Read(tempVertexData.texUV, D3DXVECTOR2);
int addUVNum = 0;
for (addUVNum = 0; addUVNum < m_headerData[HS_addTexCount]; addUVNum++)
{
Read(tempVertexData.addTexUV[addUVNum], D3DXVECTOR4);
}
for (; addUVNum < 4; addUVNum++)
{
tempVertexData.addTexUV[addUVNum] = D3DXVECTOR4(0, 0, 0, 0);
}
Read(tempVertexData.boneWeightStyle, byte);
switch (tempVertexData.boneWeightStyle)
{
case BS_BDEF1:
tempVertexData.boneIndex[0] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneWeight[0] = 1;
tempVertexData.boneIndex[1] = 0;
tempVertexData.boneWeight[1] = 0;
tempVertexData.boneIndex[2] = 0;
tempVertexData.boneWeight[2] = 0;
tempVertexData.boneIndex[3] = 0;
tempVertexData.boneWeight[3] = 0;
break;
case BS_BDEF2:
tempVertexData.boneIndex[0] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneIndex[1] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
Read(tempVertexData.boneWeight[0], float);
tempVertexData.boneWeight[1] = 1 - tempVertexData.boneWeight[0];
tempVertexData.boneIndex[2] = 0;
tempVertexData.boneWeight[2] = 0;
tempVertexData.boneIndex[3] = 0;
tempVertexData.boneWeight[3] = 0;
break;
case BS_BDEF4:
tempVertexData.boneIndex[0] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneIndex[1] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneIndex[2] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneIndex[3] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
Read(tempVertexData.boneWeight[0], float);
Read(tempVertexData.boneWeight[1], float);
Read(tempVertexData.boneWeight[2], float);
Read(tempVertexData.boneWeight[3], float);
break;
case BS_SDEF:
tempVertexData.boneIndex[0] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
tempVertexData.boneIndex[1] = ReadStyleCast(m_headerData[HS_boneIndexSize]);
Read(tempVertexData.boneWeight[0], float);
tempVertexData.boneWeight[1] = 1 - tempVertexData.boneWeight[0];
tempVertexData.boneIndex[2] = 0;
tempVertexData.boneWeight[2] = 0;
tempVertexData.boneIndex[3] = 0;
tempVertexData.boneWeight[3] = 0;
Read(tempVertexData.sdefC, D3DXVECTOR3);
Read(tempVertexData.sdefR0, D3DXVECTOR3);
Read(tempVertexData.sdefR1, D3DXVECTOR3);
break;
}
Read(tempVertexData.edgeSize, float);
m_vertexData.push_back(tempVertexData);
}
//▼▼▼頂点インデックス数を抽出▼▼▼//
Read(count, int);
if (count % 3 != 0)
{
MessageBox(NULL, TEXT("このPMXファイルは全て三角形で構成されていません。"), TEXT("Err"), MB_OK);
return false;
}
//▼▼▼頂点インデックス情報を抽出▼▼▼//
for (int polygonNum = 0; polygonNum < count / 3; polygonNum++)
{
D3DXVECTOR3 tempPolygonIndex;
tempPolygonIndex.x = ReadStyleCast(m_headerData[HS_vertexIndexSize]);
tempPolygonIndex.y = ReadStyleCast(m_headerData[HS_vertexIndexSize]);
tempPolygonIndex.z = ReadStyleCast(m_headerData[HS_vertexIndexSize]);
m_vertexIndex.push_back(tempPolygonIndex);
}
//▼▼▼テクスチャ数▼▼▼//
Read(count, int);
//▼▼▼テクスチャ情報を抽出▼▼▼//
for (int textureCount = 0; textureCount < count; textureCount++)
{
std::string texPass;
texPass=ReadText();
// texPass = filePass + texPass;
m_texturePass.push_back(texPass);
}
//▼▼▼マテリアル数▼▼▼//
Read(count, int);
//▼▼▼マテリアル情報の抽出▼▼▼//
for (int materialCount = 0; materialCount < count; materialCount++)
{
T_PmxMaterialData materialData;
materialData.materialNameJapanese = ReadText();
materialData.materialNameEnglish = ReadText();
Read(materialData.diffuse, D3DXVECTOR4);
Read(materialData.specular, D3DXVECTOR3);
Read(materialData.specularPower, float);
Read(materialData.ambient, D3DXVECTOR3);
byte temp;
Read(temp, byte);
materialData.drawBothAspectFlg = temp & 0x01;
materialData.drawGroundShadowFlg = temp & 0x02;
materialData.drawSelfShadowMapFlg = temp & 0x04;
materialData.drawSelfShadowFlg = temp & 0x08;
materialData.drawEdgeFlg = temp & 0x10;
Read(materialData.edgeCollar, D3DXVECTOR4);
Read(materialData.edgeSize, float);
materialData.diffuseTextureIndex = ReadStyleCast(m_headerData[HS_texIndexSize]);
materialData.sphereTextureIndex = ReadStyleCast(m_headerData[HS_texIndexSize]);
Read(temp, byte);
switch (temp)
{
case 0:
materialData.sphereType = ST_NONE;
break;
case 1:
materialData.sphereType = ST_MUL;
break;
case 2:
materialData.sphereType = ST_ADD;
break;
case 3:
materialData.sphereType = ST_SUB;
break;
}
Read(temp, byte);
if (temp)
{
materialData.toonTextureShareFlg = true;
Read(materialData.toonTextureShareIndex, byte);
materialData.toonTextureIndex = -1;
}
else{
materialData.toonTextureShareFlg = false;
materialData.toonTextureIndex = ReadStyleCast(m_headerData[HS_texIndexSize]);
materialData.toonTextureShareIndex = -1;
}
materialData.comment = ReadText();
Read(materialData.referenceVertexIndexCount, int);
m_materialData.push_back(materialData);
}
pmxData.close();
return true;
}
//■■■■■■■■■■■■//
//■■■【private】 ■■■//
//■■■■■■■■■■■■//
//■■■■■■■■■■■■■■■■■■■■■■
//■■■ 機能:pmxファイルのテキスト部分のロードを行います。
//■■■ 引数1:void
//■■■ 返値:string:ロードしたテキスト
//■■■■■■■■■■■■■■■■■■■■■■
string OGL::PmxData::ReadText(void)
{
int size;
Read(size, int);
size = (size / 2);
wstring src(size,'a');
string strData;
for (int i = 0; i < size; i++)
{
wchar_t str;
Read(str, wchar_t);
src[i] = str;
}
char *mbs = new char[src.length() * MB_CUR_MAX + 1];
wcstombs(mbs, src.c_str(), src.length() * MB_CUR_MAX + 1);
strData = mbs;
delete[] mbs;
return strData;
}
//■■■■■■■■■■■■■■■■■■■■■■
//■■■ 機能:指定したバイト数を読み込み、intでキャストして返します。
//■■■ 引数1:byte:読み込むバイト数
//■■■ 返値:int:読み込んだ値
//■■■■■■■■■■■■■■■■■■■■■■
int OGL::PmxData::ReadStyleCast(byte readByte)
{
switch (readByte)
{
case 1:
byte b_buff;
Read(b_buff, byte);
return (int)b_buff;
break;
case 2:
short s_buff;
Read(s_buff, short);
return (int)s_buff;
break;
case 4:
int i_buff;
Read(i_buff, int);
return i_buff;
break;
default:
return 0;
break;
}
return 0;
}<file_sep>//==========================
//===【PmxData.h】
//==========================
// Pmxデータを保持します。
//==========================
#pragma once
//=====================//
//===【インクルード記述】 ===//
//=====================//
#include <d3dx9.h>
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<memory>
#include"../OgmData/OgmData.h"
namespace OGL
{
class OgmData;
class PmxData
{
enum HEADER_STYLE
{
HS_encodeStyle, //エンコード方式0
HS_addTexCount, //追加UV数1
HS_vertexIndexSize, //頂点インデックスサイズ2
HS_texIndexSize, //テクスチャインデックスサイズ3
HS_materialIndexSize,//マテリアルインデックスサイズ4
HS_boneIndexSize, //ボーンインデックスサイズ5
HS_morphIndexSize, //モーフインデックスサイズ6
HS_rigidBodyIndexSize,//剛体インデックスサイズ7
HS_MAX,
};
enum BONE_STYLE
{
BS_BDEF1,
BS_BDEF2,
BS_BDEF4,
BS_SDEF,
BS_MAX,
};
enum SPHERE_TYPE
{
ST_NONE,
ST_MUL,
ST_ADD,
ST_SUB,
};
struct T_PmxVertexData
{
D3DXVECTOR3 pos;
D3DXVECTOR3 normal;
D3DXVECTOR2 texUV;
D3DXVECTOR4 addTexUV[4];
byte boneWeightStyle;
int boneIndex[4];
float boneWeight[4];
D3DXVECTOR3 sdefC;
D3DXVECTOR3 sdefR0;
D3DXVECTOR3 sdefR1;
float edgeSize;
};
struct T_PmxMaterialData
{
std::string materialNameJapanese;
std::string materialNameEnglish;
D3DXVECTOR4 diffuse;
D3DXVECTOR3 specular;
float specularPower;
D3DXVECTOR3 ambient;
bool drawBothAspectFlg;
bool drawGroundShadowFlg;
bool drawSelfShadowMapFlg;
bool drawSelfShadowFlg;
bool drawEdgeFlg;
D3DXVECTOR4 edgeCollar;
float edgeSize;
int diffuseTextureIndex;
int sphereTextureIndex;
SPHERE_TYPE sphereType;
bool toonTextureShareFlg;
int toonTextureIndex;
byte toonTextureShareIndex;
std::string comment;
int referenceVertexIndexCount;
};
private:
std::ifstream pmxData;
float m_pmxVersion;
byte m_headerData[HS_MAX];
std::string m_modelNameEnglish;
std::string m_modelNameJapanese;
std::string m_commentEnglish;
std::string m_commentJapanese;
std::vector<T_PmxVertexData> m_vertexData;
std::vector<D3DXVECTOR3> m_vertexIndex;
std::vector<std::string> m_texturePass;
std::vector<T_PmxMaterialData> m_materialData;
private:
std::string ReadText(void);
int ReadStyleCast(byte readByte);
public:
PmxData();
~PmxData();
bool LoadFile(char* fileName);
friend OgmData;
}; //EndOf__class_PmxData
} //EndOf__namespace_OGL
<file_sep>#include<iostream>
#include"OgmData\OgmData.h"
#define _CRTDBG_MAP_ALLOC
int main(void)
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
OGL::PmxData pmx;
pmx.LoadFile("puronama/プロ生ちゃん.pmx");
OGL::OgmData ogm;
OGL::OgmData ogmm;
ogm.ImportFromModelData(&pmx);
ogm.ExportFile("puronama.ogm");
ogmm.ImportFromModelFile("puronama.ogm");
return 0;
} | ca8d874d7ffa2ed4fe4cb736eefdefb40552af9c | [
"Markdown",
"C++"
] | 6 | Markdown | manntera/OGL_ModelData | bbe6797abf36023bdf15fdeeb4601dc640b93c9c | 269910064c8e5b1d01d7c912b0c7f1206bdff8ff |
refs/heads/master | <file_sep>$(document).ready(function(){
$("#h1").click(function(){
location.reload(true);
});
});
$(document).ready(function(){
$("#text").css({width : "80%", position : "relative",top: "250px" , left : "10%",padding :"0.5%"});
});
function f1(){
}
var xhr = new XMLHttpRequest();
function f1(){
xhr.open('GET','https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY',true);
xhr.send();
xhr.onreadystatechange = function(){
if(this.readyState==4){
var x = JSON.parse(this.responseText);
document.body.style.backgroundImage = "url("+x.url+")";
document.getElementsByClassName("loader")[0].style.display = "none";
}
};
}
$("input").on("keyup",function(){
if(event.keyCode == 13){
var xhr = new XMLHttpRequest();
var y = document.getElementById("text").value;
xhr.open('GET','https://images-api.nasa.gov/search?q='+y);
xhr.send();
xhr.onreadystatechange = function(){
if(this.readyState == 4){
var x = JSON.parse(this.responseText);
var images = x.collection.items;
var i =0;
images.forEach(function(value,index){
var links = value.links;
links.forEach(function(value,index){
console.log(value.href);
document.getElementById("images").innerHTML += '<img class="img.thumbnail i rounded" src='+ value.href +'>';
});
});
};
}
};
});
<file_sep>var xhr = new XMLHttpRequest();
function reload(){
document.location.reload();
}
function getPictures(id){
xhr.open('GET','https://dog.ceo/api/breeds/image/random',true);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var x = JSON.parse(this.responseText);
document.getElementById("text").style.display = "none";
document.getElementById("image").src = x.message;
}
};
} | 5ec43288f5f712214bb17420d97849fb646c2542 | [
"JavaScript"
] | 2 | JavaScript | sbhalla98/frontEndprojects | 8e88415536e68ae7f6135452da7252827319bea8 | e328723b8835f9a8bc3aebb951ab04772851998f |
refs/heads/master | <repo_name>C-RojasA/reacttr<file_sep>/.eslintrc.js
module.exports = {
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
"tab"
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"always"
],
"spaced-comment": [
"error",
"always",
{ "exceptions":
["-", "+"]
}
],
"brace-style": [
"error",
"1tbs"
],
"curly": [
"error",
"all"
],
"eqeqeq": [
"error",
"smart"
],
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
"no-var": "warn",
"no-unreachable": "error",
"block-scoped-var": "error",
"no-eq-null": "error",
"require-await": "error",
"no-use-before-define": "error",
"callback-return": "error",
}
};
| 9794408637dcce7f595525bafdcdb36fb955586c | [
"JavaScript"
] | 1 | JavaScript | C-RojasA/reacttr | 84046e3793632c28d207294b49ed19954227c269 | e13400d4ee0875429b67587cfe4f423dea625366 |
refs/heads/master | <file_sep>/*
*********************************************************************************************************
*
* (c) Copyright 2003-2014; Micrium, Inc.; Weston, FL
*
* All rights reserved. Protected by international copyright laws.
* Knowledge of the source code may NOT be used to develop a similar product.
* Please help us continue to provide the Embedded community with the finest
* software available. Your honesty is greatly appreciated.
*********************************************************************************************************
*/
/*
*********************************************************************************************************
*
*
* Texas Instruments MSP430
* on the
* MSP-EXP430F5259LP
* Evaluation Board
*
* Filename : FileTxt.c
* Version : V1.00
* Programmer(s) : GLZ
*********************************************************************************************************
*/
#include <bsp.h>
char TimeString[20] = "20170804 16:00:00";
char File_name[]={"0:/20170314.txt"};
extern unsigned char time_buf[8];
//创建文件路径
void Create_filename()
{
//u32 Date,Time;
char string0[21] = {"0:/"}; //根目录
char string1[11] = {" "}; //目录
char string2[5] = {".txt"}; //文件类型
//文件名合成
string1[0]=((time_buf[0]>>4)&0x0f)+0x30; //2
string1[1]=(time_buf[0]&0x0f)+0x30; //0
string1[2]=((time_buf[1]>>4)&0x0f)+0x30; //1
string1[3]=(time_buf[1]&0x0f)+0x30; //7
string1[4]='-';
string1[5]=((time_buf[2]>>4)&0x0f)+0x30; //0
string1[6]=(time_buf[2]&0x0f)+0x30; //3
string1[7]='-';
string1[8]=((time_buf[3]>>4)&0x0f)+0x30; //0
string1[9]=(time_buf[3]&0x0f)+0x30; //6
strcat(string0,string1); //合成文件路径
strcat(string0,string2);
strcpy(File_name,string0);
}
void Write_dataToTxt(const char *file_path,char *dat)
{
FRESULT res;
FIL fsrc;
FATFS fs;
uint16_t bw;
#if DEBUG
OSBsp.Device.Usart2.WriteString("write file ......\n\r");
#endif
res=f_mount(0, &fs);
res=f_open(&fsrc,(char *)file_path, FA_OPEN_ALWAYS | FA_WRITE);
if(res != FR_OK)
{
OSBsp.Device.Usart2.WriteString("open file error\n\r");
}
else
{
#if DEBUG
OSBsp.Device.Usart2.WriteString("open file OK!\n\r");
#endif
f_lseek(&fsrc,fsrc.fsize); //移动指针到末尾
res = f_write(&fsrc, dat, strlen(dat), &bw); /* Write it to the dst file */
#if DEBUG
if(res == FR_OK)
{
unsigned int num_w;
num_w=strlen(dat);
SendByteToUart2(num_w/100+0x30);
SendByteToUart2(num_w%100/10+0x30);
SendByteToUart2(num_w%10+0x30);
OSBsp.Device.Usart2.WriteString(" bytes has been writted!\r\n");
OSBsp.Device.Usart2.WriteString("write data ok! \n\r");
}
else
{
OSBsp.Device.Usart2.WriteString("write data error \n\r");
}
#endif
/*close file */
f_close(&fsrc);
}
f_mount(0,NULL);
}
<file_sep>#ifndef FILETXT_H
#define FILETXT_H
extern char TimeString[20];
void Create_filename();
void Write_dataToTxt(const char *file_path,char *dat);
#endif
<file_sep>/*
*********************************************************************************************************
*
* (c) Copyright 2003-2014; Micrium, Inc.; Weston, FL
*
* All rights reserved. Protected by international copyright laws.
* Knowledge of the source code may NOT be used to develop a similar product.
* Please help us continue to provide the Embedded community with the finest
* software available. Your honesty is greatly appreciated.
*********************************************************************************************************
*/
/*
*********************************************************************************************************
*
*
* Texas Instruments MSP430
* on the
* MSP-EXP430F5259LP
* Evaluation Board
*
* Filename : g_DeviceRTC.c
* Version : V1.00
* Programmer(s) : GLZ
*********************************************************************************************************
*/
#include <bsp.h>
uint8_t time_string_buf[16] = {};
/*????????????????**************************************************/
uint8_t clock_flag;
//***********************************************************************
// DS1302_write_byte
//***********************************************************************
static void DS1302_write_byte(uint8_t addr, uint8_t d)
{
uint8_t i;
RESET_SET; //??????DS1302??????
/*??????????????ddr*/
IO_OUT;
addr = addr & 0xFE; //???????????�
for (i = 0; i < 8; i ++)
{
if (addr & 0x01)
{
IO_SET;
}
else
{
IO_CLR;
}
SCK_SET;
SCK_CLR;
addr = addr >> 1;
}
/*???????????d*/
IO_OUT;
for (i = 0; i < 8; i ++)
{
if (d & 0x01)
{
IO_SET;
}
else
{
IO_CLR;
}
SCK_SET;
SCK_CLR;
d = d >> 1;
}
RESET_CLR; //??DS1302??????
}
//***********************************************************************
// DS1302_read_byte
//***********************************************************************
static uint8_t DS1302_read_byte(uint8_t addr)
{
uint8_t i;
uint8_t temp;
RESET_SET; //??????DS1302??????
/*??????????????ddr*/
IO_OUT;
addr = addr | 0x01; //?????????�
for (i = 0; i < 8; i ++)
{
if (addr & 0x01)
{
IO_SET;
}
else
{
IO_CLR;
}
SCK_SET;
SCK_CLR;
addr = addr >> 1;
}
/*????????????emp*/
IO_IN;
for (i = 0; i < 8; i ++)
{
temp = temp >> 1;
if (IO_R)
{
temp |= 0x80;
}
else
{
temp &= 0x7F;
}
SCK_SET;
SCK_CLR;
}
RESET_CLR; //??DS1302??????
return temp;
}
//***********************************************************************
// ??S302?????????
//***********************************************************************
void DS1302_write_time(uint8_t *data,uint8_t dataType)
{
DS1302_write_byte(DS1302_control_add,0x00); //???????�
DS1302_write_byte(DS1302_sec_add,0x80); //???
//DS1302_write_byte(DS1302_charger_add,0xa9); //??????
switch(dataType){
case RealTime:{
DS1302_write_byte(DS1302_year_add,data[1]); //?�
DS1302_write_byte(DS1302_month_add,data[2]); //?�
DS1302_write_byte(DS1302_date_add,data[3]); //?�
DS1302_write_byte(DS1302_hr_add,data[4]); //?�
DS1302_write_byte(DS1302_min_add,data[5]); //?�
DS1302_write_byte(DS1302_sec_add,data[6]); //?�
DS1302_write_byte(DS1302_day_add,data[7]); //?�
}
break;
case AlarmData:{
DS1302_write_byte(DS1302_clock_hr_add,data[0]); //????�
DS1302_write_byte(DS1302_clock_min_add,data[1]); //????�
}
break;
case InnerRam:{
DS1302_write_byte(DS1302_FLASH,data[0]);
}
break;
}
DS1302_write_byte(DS1302_control_add,0x80); //???????�
}
//***********************************************************************
// ??S302?????????
//***********************************************************************
void DS1302_read_time(uint8_t *data,uint8_t dataType)
{
switch(dataType){
case RealTime:{
data[1]=DS1302_read_byte(DS1302_year_add); //?�
data[2]=DS1302_read_byte(DS1302_month_add); //?�
data[3]=DS1302_read_byte(DS1302_date_add); //?�
data[4]=DS1302_read_byte(DS1302_hr_add); //?�
data[5]=DS1302_read_byte(DS1302_min_add); //?�
data[6]=(DS1302_read_byte(DS1302_sec_add))&0x7F; //?�
data[7]=DS1302_read_byte(DS1302_day_add); //?�
}
break;
case AlarmData:{
data[0]=DS1302_read_byte(DS1302_clock_hr_add); //clock?�
data[1]=DS1302_read_byte(DS1302_clock_min_add); //clock?�
}
break;
case InnerRam:{
data[0]=DS1302_read_byte(DS1302_FLASH);
}
break;
}
}
//***********************************************************************
// DS302???????�
//***********************************************************************
void g_Device_ExtRTC_Init(void)
{
RESET_CLR; //RESET????�
SCK_CLR; //SCK????�
RESET_OUT; //RESET?????????
SCK_OUT; //SCK?????????
DS1302_write_byte(DS1302_sec_add,0x00); //???
OSBsp.Device.RTC.ReadExtTime = DS1302_read_time;
OSBsp.Device.RTC.ConfigExtTime = DS1302_write_time;
}
//***********************************************************************
//??????????�
//***********************************************************************
void Create_TimeData(uint8_t *p1,uint8_t *p2)
{
uint8_t time_buf[8];
memset(time_buf,0x0,8);
DS1302_read_time(time_buf,RealTime);
p1[3]=p2[0]=((time_buf[0]>>4)&0x0f)+0x30; //2 year
p1[4]=p2[1]=(time_buf[0]&0x0f)+0x30; //0
p1[5]=p2[2]=((time_buf[1]>>4)&0x0f)+0x30; //1
p1[6]=p2[3]=(time_buf[1]&0x0f)+0x30; //7
p1[7]=p2[5]=((time_buf[2]>>4)&0x0f)+0x30; //0 month
p1[8]=p2[6]=(time_buf[2]&0x0f)+0x30; //3
p1[9]=p2[8]=((time_buf[3]>>4)&0x0f)+0x30; //0 day
p1[10]=p2[9]=(time_buf[3]&0x0f)+0x30; //6
p2[11]=((time_buf[4]>>4)&0x0f)+0x30; //2 hour
p2[12]=(time_buf[4]&0x0f)+0x30; //0
p2[14]=((time_buf[5]>>4)&0x0f)+0x30; //5 min
p2[15]=(time_buf[5]&0x0f)+0x30; //6
p2[17]=((time_buf[6]>>4)&0x0f)+0x30; //0 sec
p2[18]=(time_buf[6]&0x0f)+0x30; //0
}
//***********************************************************************
//??????????�
//***********************************************************************
void Create_TimeString(uint8_t *p1,uint8_t *p2)
{
uint8_t time_buf[8];
memset(time_buf,0x0,8);
DS1302_read_time(time_buf,RealTime);
p1[3]=p2[0]=((time_buf[0]>>4)&0x0f)+0x30; //2 year
p1[4]=p2[1]=(time_buf[0]&0x0f)+0x30; //0
p1[5]=p2[2]=((time_buf[1]>>4)&0x0f)+0x30; //1
p1[6]=p2[3]=(time_buf[1]&0x0f)+0x30; //7
p1[7]=p2[4]=((time_buf[2]>>4)&0x0f)+0x30; //0 month
p1[8]=p2[5]=(time_buf[2]&0x0f)+0x30; //3
p1[9]=p2[6]=((time_buf[3]>>4)&0x0f)+0x30; //0 day
p1[10]=p2[7]=(time_buf[3]&0x0f)+0x30; //6
p2[9]=((time_buf[4]>>4)&0x0f)+0x30; //2 hour
p2[10]=(time_buf[4]&0x0f)+0x30; //0
p2[12]=((time_buf[5]>>4)&0x0f)+0x30; //5 min
p2[13]=(time_buf[5]&0x0f)+0x30; //6
p2[15]=((time_buf[6]>>4)&0x0f)+0x30; //0 sec
p2[16]=(time_buf[6]&0x0f)+0x30; //0
}
//??????RTC???????�
void g_Device_InnerRTC_Init(void)
{
RTCCTL01 = RTCMODE + RTCBCD + RTCHOLD + RTCTEV_0 + RTCSSEL_0; // Min. changed interrupt
RTCHOUR = 0x00; //???????�2000?�0?�0?�00:00:00
RTCMIN = 0x00;
RTCSEC = 0x00;
RTCDAY = 0x00;
RTCMON = 0x00;
RTCYEAR = 0x2000;
RTCCTL01 &= ~RTCHOLD;//?????????
RTCCTL0 |= RTCTEVIE;//?????????????�
// RTCCTL0 |= RTCRDYIE;//?????????????�
}
//????????TC???
void Write_info_RTC(uint8_t *time)
{
RTCCTL01 |= RTCHOLD;//?????????
RTCYEAR_L = time[1];
RTCMON = time[2];
RTCDAY = time[3];
RTCHOUR = time[4];
RTCMIN = time[5];
RTCSEC = time[6];
RTCADOWDAY = time[7];
RTCCTL01 &= ~RTCHOLD;//?????????
// RTCCTL0 |= RTCTEVIE;//?????????????�
// RTCCTL0 |= RTCRDYIE;//?????????????�
}
////?????????RTC???
void Read_info_RTC(uint8_t *time)
{
time[0] = (uint8_t)RTCYEAR;
time[1] = RTCMON;
time[2] = RTCDAY;
time[3] = RTCHOUR;
time[4] = RTCMIN;
time[5] = RTCSEC;
}
#pragma vector=RTC_VECTOR
__interrupt void RTC_ISR(void)
{
switch (__even_in_range(RTCIV, RTC_RT1PSIFG))
{
case RTC_NONE:
break;
case RTC_RTCTEVIFG://????????????????
{
} //RTC_RTCTEVIFG://????????????????
break;
case RTC_RTCRDYIFG://????????????????
{
//P1OUT ^= BIT7;
}
break;
default:
break;
}
}
| 11b9f608740cd410fe1414c2b20dd6208f91e133 | [
"C"
] | 3 | C | QikMa/msp430_ucOS_II | ed0bfcd4c903277e93ce3948a04ac07c677a01b4 | 6574c1bd88233fd230185415e6dd873df2d792f1 |
refs/heads/master | <file_sep>document.querySelector(".navbar-toggler").addEventListener("click", function () {
document.querySelector(".overlay").classList.toggle("hide");
});
| 3b25718f098352ad37b47cc1be7454129e8688eb | [
"JavaScript"
] | 1 | JavaScript | piotrmigas/easybank-landing-page | 9a27fcf9549485d67632db19bd42fbd69cb71ba3 | 6471a5e6213ecc07a228c510f36b8bfb41eff7d0 |
refs/heads/master | <repo_name>jgbrown32/esp8266_iot_nodes<file_sep>/root/main.py
# from config import config
# import utime
# import ujson
# import machine
def run():
print("Main is running...")
| cd588dd74f878fe1f0a2f42166087970d9f4da1c | [
"Python"
] | 1 | Python | jgbrown32/esp8266_iot_nodes | 1388a3c0a5a8d897d745d3a902da921b3650e4e8 | c3a578050dfb2fe2afb735c6d072fe51c4fcd337 |
refs/heads/master | <repo_name>barbosa97/covid<file_sep>/src/covid/COVID.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 covid;
import Control.Controlador;
import Vista.Registro;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
/**
*
* @author andres
*/
public class COVID {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Registro r = new Registro();
new Controlador(r);
r.setLocationRelativeTo(r);
r.setVisible(true);
}
}
| f86bd0295bfa6c69489ba088dfb8fd0317350517 | [
"Java"
] | 1 | Java | barbosa97/covid | 5365b97191645c35b0ebf7c2f7f3a208307940e1 | b4462426330569ea32f9a51a82f87b1bdbe0be92 |
refs/heads/master | <file_sep>import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.log4j.Logger;
import java.io.IOException;
public class SumRatingReducer extends Reducer<IntWritable, SumRatings, IntWritable, SumRatings> {
@Override
public void reduce(IntWritable key, Iterable<SumRatings> values,
Context context) throws IOException, InterruptedException {
final SumRatings result = new SumRatings();
for (SumRatings value : values) {
result.addSumRating(value);
}
context.write(key, result);
}
}
| 17260d413e9f9c7ac113f565b9749c7cb3bba08a | [
"Java"
] | 1 | Java | kamilkolodziejski/pbd-netflix-mapred | 021e4d1a53fcdd0701b00eb902e6f63ad64e0ca1 | 2c87db81be24344ca23387216004c7da52157252 |
refs/heads/master | <file_sep>import os
import sys
import time
from bs4 import BeautifulSoup
from selenium import webdriver
START_PAGE_URL = "https://www.amazon.com/"
REFRESH_INTERNAL = 60
def check_delivery_slot(page_source: str) -> bool:
soup = BeautifulSoup(page_source, "html5lib")
delivery_slots_elem = soup.find(id="slot-container-root")
if not delivery_slots_elem:
return False
for delivery_slot_elem in delivery_slots_elem.find_all(
class_="Date-slot-container"
):
if (
"No doorstep delivery windows are available for"
not in delivery_slot_elem.text
):
return True
return False
def alert_delivery_slot() -> None:
alert_text = "Found delivery slot! Please proceed to checkout."
alert_text_title = "Delivery Slot Found!"
print(alert_text)
if sys.platform == "darwin":
os.system(
f'osascript -e \'display notification "{alert_text}" with title "{alert_text_title}"\''
)
def confirm_and_continue(confirm_text: str) -> None:
while True:
r = input(f"Enter {confirm_text} to continue: ")
if r == confirm_text:
break
def main() -> None:
driver = webdriver.Chrome()
driver.get(START_PAGE_URL)
print(
"Log in to your account. Add items to cart. Then proceed to the page to reserve a delivery slot."
)
confirm_and_continue("OK")
while not check_delivery_slot(driver.page_source):
print(f"No delivery slot. Retry in {REFRESH_INTERNAL} seconds.")
time.sleep(REFRESH_INTERNAL)
driver.refresh()
alert_delivery_slot()
confirm_and_continue("OK")
if __name__ == "__main__":
main()
<file_sep>#!/usr/bin/env zsh
black ${@}
autoflake \
--in-place \
--remove-all-unused-imports \
--remove-unused-variables \
${@}
isort ${@}
<file_sep>beautifulsoup4==4.9.0
html5lib==1.0.1
selenium==3.141.0
<file_sep>#!/usr/bin/env zsh
find . -type f -name "*.py" | xargs ./clean.sh
<file_sep># amazon-delivery-slot
Alert on available delivery slot on Amazon Fresh/Whole Foods
<file_sep>autoflake==1.3.1
black==19.10b0
ipython==7.13.0
isort==4.3.21
pytest==5.4.1
<file_sep>from unittest import TestCase
from delivery_slot_checker_amazon_fresh import (
alert_delivery_slot,
check_delivery_slot,
)
class DeliverySlotCheckerAmazonFreshTest(TestCase):
def test_check_delivery_slot(self):
with open(
"delivery_slot_page_source/amazon_fresh_no.htm"
) as page_source_file:
page_source = page_source_file.read()
self.assertFalse(check_delivery_slot(page_source))
def test_alert_delivery_slot(self):
alert_delivery_slot()
| e47089621655b9aaf52819c1f86c6b46ab828393 | [
"Markdown",
"Python",
"Text",
"Shell"
] | 7 | Python | starforever/amazon-delivery-slot | 56d6d8f661a40434cd4709499fcf4f56d4028889 | 17c75844df64dd617c18b10efc669a156ade4b3a |
refs/heads/master | <repo_name>divyaaajc/waterlog<file_sep>/app/controllers/pages_controller.rb
class PagesController < ApplicationController
skip_before_action :authenticate_user!, only: [:home, :about, :random]
def home
@waters = Water.all.sample(9)
# added for sake of Demo -- for Sommelier section
@picked_water_1 = Water.find_by('name ILIKE ?', 'foz%')
@picked_water_2 = Water.find_by('name ILIKE ?', 'icelandic%')
@picked_water_3 = Water.find_by('name ILIKE ?', 'lahuenco%')
end
def about
end
def random
random_water
@review = Review.new
# the `geocoded` scope filters only flats with coordinates (latitude & longitude)
@markers = [
{
lat: @water.latitude,
lng: @water.longitude
}]
end
private
def random_water
@water = Water.all.sample(1).first
end
end
<file_sep>/app/javascript/plugins/init_mapbox.js
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
const buildMap = (mapElement) => {
mapboxgl.accessToken = mapElement.dataset.mapboxApiKey;
return new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/edmundparsons/ckpwebkhw5gms17me7pz91apg', zoom: 1.6
});
};
const addMarkersToMap = (map, markers) => {
markers.forEach((marker) => {
const popup = new mapboxgl.Popup().setHTML(marker.info_window);
// Create a HTML element for your custom marker
const element = document.createElement('div');
element.className = 'marker';
element.style.backgroundImage = `url(https://cdn1.iconfinder.com/data/icons/user-interface-16x16-vol-1/16/drop-512.png)`;
element.style.backgroundSize = 'contain';
element.style.width = '30px';
element.style.height = '30px';
// Pass the element as an argument to the new marker
new mapboxgl.Marker(element)
.setLngLat([marker.lng, marker.lat])
.addTo(map);
});
};
const fitMapToMarkers = (map, markers) => {
const bounds = new mapboxgl.LngLatBounds();
markers.forEach(marker => bounds.extend([ marker.lng, marker.lat ]));
map.fitBounds(bounds, { padding: 70, maxZoom: 6, duration: 500 });
};
const highlightCountries = (map, countries) => {
map.on('load', function() {
map.addLayer(
{
id: 'country-boundaries',
source: {
type: 'vector',
url: 'mapbox://mapbox.country-boundaries-v1',
},
'source-layer': 'country_boundaries',
type: 'fill',
paint: {
'fill-color': '#eabb5d',
'fill-opacity': 0.4,
},
},
'country-label'
);
let filteredCountries = ["in", "iso_3166_1_alpha_3"]
filteredCountries.push(countries)
map.setFilter('country-boundaries', filteredCountries.flat());
});
}
const initMapbox = () => {
setTimeout(() => {
const mapElement = document.getElementById('map');
if (mapElement) {
const map = buildMap(mapElement);
if (mapElement.dataset.markers) {
const markers = JSON.parse(mapElement.dataset.markers);
addMarkersToMap(map, markers);
fitMapToMarkers(map, markers);
}
if (mapElement.dataset.countries) {
const countries = JSON.parse(mapElement.dataset.countries);
highlightCountries(map, countries);
}
}
}, 200);
};
export { initMapbox };<file_sep>/app/javascript/plugins/init_review_slide.js
const reviewSlide = () => {
const slide = document.querySelector('#review-slide')
slide.addEventListener('click', (event) => {
event.preventDefault()
const text = slide.innerHTML
slide.innerHTML = slide.dataset.text
slide.setAttribute("data-text", text)
});
};
export { reviewSlide }<file_sep>/app/controllers/logs_controller.rb
class LogsController < ApplicationController
def index
@reviewed = params[:reviewed]
@waters = params[:all]
@logs = Log.where(user_id: current_user.id)
if @reviewed
@logs = current_user.reviews.map do |review|
review.water.logs.find_by(user: current_user)
end || []
end
@countries = @logs.map do |log|
country = Geocoder.search([log.water.latitude, log.water.longitude]).first.data["address"]["country"]
NormalizeCountry(country, to: :alpha3)
end
end
def destroy
@log = Log.find(params[:id])
@log.destroy
redirect_to logs_path, notice: "You have successfully deleted #{@log.water.name}."
end
end
<file_sep>/db/migrate/20210615150222_add_badges_to_waters.rb
class AddBadgesToWaters < ActiveRecord::Migration[6.0]
def change
add_column :waters, :rare, :boolean
add_column :waters, :highly_rated, :boolean
add_column :waters, :popular, :boolean
end
end
<file_sep>/app/models/water_tag.rb
class WaterTag < ApplicationRecord
belongs_to :water
belongs_to :tag
validates :water, uniqueness: { scope: :tag }
end
<file_sep>/db/seeds.rb
require 'open-uri'
require 'nokogiri'
Water.destroy_all
Review.destroy_all
Log.destroy_all
User.destroy_all
puts "Creating users..."
benjamin = User.create(email: "<EMAIL>", password: "<PASSWORD>", username: "benkennedy", admin: false)
lisa = User.create(email: "<EMAIL>", password: "<PASSWORD>", username: "lisasimpson", admin: false)
jimmy = User.create(email: "<EMAIL>", password: "<PASSWORD>", username: "jimmycat", admin: false)
admin = User.create(email: "<EMAIL>", password: "<PASSWORD>", username: "admin", admin: true)
url = "http://www.finewaters.com/bottled-waters-of-the-world/"
html_file = URI.open(url).read
html_doc = Nokogiri::HTML(html_file)
countries = []
urls = []
html_doc.search('.parent a').each do |element|
countries.push(element.text.strip)
end
countries.each do |country|
country.gsub!(" ", "-")
url = "http://www.finewaters.com/bottled-waters-of-the-world/#{country.downcase}"
html_file = URI.open(url).read
html_doc = Nokogiri::HTML(html_file)
html_doc.search('.list-title a').each do |element|
urls.push(element.attribute('href').value)
end
end
puts "Creating waters..."
urls.each do |url|
fine_waters = "http://www.finewaters.com/#{url}"
html_file = URI.open(fine_waters).read
html_doc = Nokogiri::HTML(html_file)
new_water = Water.new
html_doc.search('.page-header h2').each do |element|
new_water.name = element.text.strip
end
html_doc.search('.tbl-sec-src').each do |element|
new_water.country = element.search("td:contains('Country') + td").text.strip
new_water.country = "Colombia" if new_water.country == "Colomcia"
new_water.source = element.search("td:contains('Place') + td").text.strip
new_water.brand = element.search("td:contains('Company') + td").text.strip
end
text = html_doc.search('.located-beneath').map do |element|
element.text.strip.length < 5 ? nil : element.text.strip
end
new_water.description = text.compact.uniq.first
new_water.photo = "http://www.finewaters.com#{html_doc.search('.lft-part').first.search('img').attribute('src').value}"
html_doc.search('.wt-anlss').each do |element|
new_water.ph = element.search("td:contains('ph') + td").text.strip
# p element.search("td:contains('Hardness') + td").first.text.strip
# p element.search("td:contains('Minerality') + td").text.strip
# p element.search("td:contains('Balance') + td").text.strip
end
# p new_water.name
# p new_water.description
new_water.save
end
# get all waters where lon/lat was not set by "source" and set by "country"
Water.where(longitude: [nil, ""]).each do |water|
latitude = Geocoder.search(water.country).first.coordinates.first
longitude = Geocoder.search(water.country).first.coordinates.last
water.update(latitude: latitude, longitude: longitude)
end
puts "#{Water.count} waters saved!!!"
# puts "Creating waters..."
# acquapanna = Water.create(photo: 'https://ecom-su-static-prod.wtrecom.com/images/products/11/LN_437956_BP_11.jpg', name: "Acquapanna", brand: "Acquapanna", description: "Acqua Panna, the Italian natural spring water, comes from the Tuscany's hills. With its smooth taste, it's the right partner of all your life experiences.", ph: "8", source: "Tuscany", country: "Italy")
# orezza = Water.create(photo: 'https://produits.bienmanger.com/40000-0w600h600_Orezza_Sparkling_Mineral_Water_From_Corsica.jpg', name: "Orezza", brand: "Orezza", description: "Orezza water, is a natural mineral water, which has had the natural carbon dioxide from the spring re-added. It is acknowledged as one of the mineral waters with the highest iron levels in the world.", ph: "5.5", source: "Corsica", country: "France")
# evian = Water.create(photo: 'http://cdn.shopify.com/s/files/1/0078/7038/2195/products/EvianNaturalSpringWaterPlasticBottleMultipack_8x1.5L_1024x1024.png?v=1606545455', name: "Evian", brand: "Evian", description: "evian still natural mineral water. From the pristine Alps. ... From our pristine mountain Alpine source to you, evian natural mineral water is delicately crafted by nature through its 15 year journey, arriving at its protected source with a unique balance of minerals.", ph: "7.5", source: "Évian-les-Bains", country: "France")
# evian_virgil_abloh = Water.create(photo: 'http://cdn.shopify.com/s/files/1/0078/7038/2195/products/evian_virgil_bold_blue_500ml_1024x1024.png?v=1606545265', name: "Evian x Vir<NAME>", brand: "Evian", description: "The evian x Virgil Abloh Soma Collection features two highly-desirable, refillable 75cL evian glass bottles, designed as a hydration accessory for trendy and conscious consumers.", ph: "7.2", source: "Évian-les-Bains", country: "France")
# just_water = Water.create(photo: 'https://packagingeurope.com/downloads/4620/download/JUST2_210818.jpg?cb=24a40a636d11b24d02d9a96946f73cca&w=1200', name: "Just Water", brand: "Just Water", description: "JUST® delivers everyday products that are responsibly sourced and packaged for improved environmental and social impact. The JUST water bottle is not just a paper bottle, it's made up of 82% renewable resources while reducing CO2 emissions up to 74% compared to traditional plastic bottles", ph: "8", source: "Glens Falls", country: "USA")
# krystal = Water.create(photo: 'https://uploads.ifdesign.de/award_img_300/oex_large/146606_02_1800x1800-01.jpg', name: "Krystal", brand: "Krystal", description: "KRYSTAL flows from the pristine Lesser Khingan Mountains on the Chinese-Siberian frontier into the untouched underground Beian aquifer, where it is bottled at source. It is abundant in minerals and trace elements including sodium bicarbonate, metasilicic acid, calcium and silica.", ph: "8.4", source: "Heilongjiang", country: "China")
# finé = Water.create(photo: 'https://lh3.googleusercontent.com/proxy/yZ0NzANiZ4t0BGhQd5CBemEPaHu1oa2nyZMgaWRAWWVA1u6KlKBC4ObN7T<KEY>', name: "Finé", brand: "Finé", description: "Only after tens of thousands of years filtering naturally through 600 meters of ancient volcanic rock does water attain the mineral-rich, pollutant-free purity it needs to be deemed Eau Finé.", ph: "7.8", source: "Shuzenji", country: "Japan")
# veen = Water.create(photo: 'https://produits.bienmanger.com/37010-0w470h470_Veen_Velvet_Still_Water_From_Finland.jpg', name: "Veen", brand: "Veen", description: "VEEN’s natural mineral waters originate in the Eastern Himalayas in what is known as the “Last Shangri-La”, the Kingdom of Bhutan. The Bhutanese have treasured their natural environment, as it is seen as a source of all life and the abode of the gods and spirits.", ph: "7.2", source: "Samtse", country: "Bhutan")
# castello = Water.create(photo: 'https://lh3.googleusercontent.com/proxy/fm22htZx0eMkSQVYgtAohL1tSNnz3h_MUiIeebmv701N_HBy3MlxtzbmtSuYO4IiBBi5HXaJSVY4gos91In7bCUUmguAVLUuMeqVlWpxu-M930ExL8OL_awmWyF77fqs', name: "Castello", brand: "Castello", description: "CASTELLO is centenary water with springs in Pisões-Moura. It was launched in 1899 by the company <NAME> and remains a benchmark in the market sector of sparkling waters. ... Today, ÁGUA CASTELLO remains as fresh as the day the first drops were extracted from its spring.", ph: "5.35", source: "Baixo-Alentejo", country: "Portugal")
# belu = Water.create(photo: 'https://www.drinksupermarket.com/media/catalog/product/cache/0288c1cb4e2e8b328879830e17ef5901/b/e/belu-still-water-12x-75cl-glass-bottle_temp.jpg', name: "Belu", brand: "Belu", description: "Belu is a UK based drinks company. The company claims to produce carbon-neutral and ethically-sourced bottled waters and filtration systems, and to donate 100% of its profits to WaterAid.", ph: "7.5", source: "Shropshire", country: "United Kingdom")<file_sep>/app/javascript/plugins/init_sidebar.js
const initSidebar = () => {
const nav = document.getElementById("mySidenav");
const openNav = () => {
nav.style.width = "500px";
}
const closeNav = () => {
nav.style.width = "0px";
}
const burger = document.querySelector('.burger-dropdown');
const close = document.querySelector('.closebtn');
burger.addEventListener('click', (event) => {
openNav();
});
close.addEventListener('click', (event) => {
closeNav();
});
};
export { initSidebar };<file_sep>/config/routes.rb
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
devise_for :users
root to: 'pages#home'
get 'about', to: 'pages#about'
get 'random', to: 'pages#random'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :waters, only: [:show, :index] do
resources :reviews, only: :create
member do
post :add_water_to_log
end
end
resources :logs, only: [:index, :destroy]
resources :reviews, only: [:destroy, :update]
end
<file_sep>/db/migrate/20210607152912_remove_postcode.rb
class RemovePostcode < ActiveRecord::Migration[6.0]
def change
remove_column :users, :posctode, :string
end
end
<file_sep>/app/javascript/controllers/navbar_controller.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ 'reviewTitle' ];
connect() {
console.log(this.loggedValue, typeof(this.loggedValue));
}
showNav(event) {
const text = this.reviewTitleTarget.innerHTML;
this.reviewTitleTarget.innerHTML = this.reviewTitleTarget.dataset.text;
this.reviewTitleTarget.setAttribute("data-text", text)
}
}<file_sep>/app/controllers/water_tags_controller.rb
class WaterTagsController < ApplicationController
end
<file_sep>/app/controllers/waters_controller.rb
class WatersController < ApplicationController
skip_before_action :authenticate_user!, only: %i[index show]
def index
if params.dig(:search, :query).present?
@waters = Water.search_waters(params[:search][:query]).paginate(page: params[:page], per_page: 21)
else
@waters = Water.paginate(page: params[:page], per_page: 21)
end
end
def show
@water = Water.find(params[:id])
@review = Review.new
@reviewed = user_reviewed? if current_user
# the `geocoded` scope filters only flats with coordinates (latitude & longitude)
@markers = [
{
lat: @water.latitude,
lng: @water.longitude
}]
end
def add_water_to_log
@log = Log.new
@log.user = current_user
@water = Water.find(params[:id])
@log.water = @water
if @log.save
# flash[:alert] = "#{@water.name} has been successfully added to your waters! See it in "
else
flash.notice = "You have already tried this water"
end
end
def user_reviewed?
@user = current_user
@water = Water.find(params[:id])
@intersection = @user.reviews & @water.reviews
return false if @intersection.empty?
return true
end
end
<file_sep>/app/models/water.rb
class Water < ApplicationRecord
has_many :reviews, dependent: :destroy
has_many :water_tags, dependent: :destroy
has_many :tags, through: :water_tags, dependent: :destroy
has_many :logs, dependent: :destroy
geocoded_by :location
validates :name, presence: true, uniqueness: true
validates :country, :description, :source, presence: true
validates :ph, presence: true, numericality: true
include PgSearch::Model
pg_search_scope :search_waters,
against: [ :name, :brand, :description, :country, :source ],
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
after_validation :geocode, if: :will_save_change_to_source?
private
def location
"#{source} #{country}"
end
end
<file_sep>/app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
before_action :set_review, only: [:destroy, :edit, :update]
def create
@review = Review.new(strong_params)
@water = Water.find(params[:water_id])
@review.water = @water
@review.user = current_user
if @review.save
flash[:success] = 'Your review was successfully added! See it in '
redirect_to water_path(@water)
else
render 'waters/show'
end
Log.create(user: current_user, water: @water)
end
def update
if @review.update(strong_params)
redirect_to water_path(@review.water)
else
render 'waters/show'
end
end
def destroy
@review.destroy
redirect_to water_path(@review.water), notice: 'Review was successfully deleted'
end
private
def strong_params
params.require(:review).permit(:content, :rating)
end
def set_review
@review = Review.find(params[:id])
end
end
<file_sep>/app/models/log.rb
class Log < ApplicationRecord
belongs_to :water
belongs_to :user
before_destroy :delete_review
validates :water, uniqueness: { scope: :user }
def delete_review
review = self.water.reviews.find_by(user: self.user)
review.destroy if review
end
end
| a32a4ce1c54c3b9a54cbc30d56acb25af4558eba | [
"JavaScript",
"Ruby"
] | 16 | Ruby | divyaaajc/waterlog | 097ae02ee46204d3558ff67352a822948ec1847a | 87574781aa7291b7c18a70dc56ab4e2d8ef6cf90 |
refs/heads/master | <repo_name>oshogun/GenESyS-Reborn<file_sep>/OldObserver.cpp
/*
* 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.
*/
/*
* File: Observer.cpp
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:35
*/
#include "OldObserver.h"
OldObserver::OldObserver() {
}
OldObserver::OldObserver(const OldObserver& orig) {
}
OldObserver::~OldObserver() {
}
<file_sep>/Fitter.h
/*
* 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.
*/
/*
* File: Fitter.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 19:08
*/
#ifndef FITTER_H
#define FITTER_H
#include "Fitter_if.h"
class Fitter : public Fitter_if {
public:
Fitter(Fitter_if* fitter_impl) {
_fitter_impl = fitter_impl;
};
Fitter(const Fitter& orig);
virtual ~Fitter();
public:
void fitUniform(double *sqrerror, double *min, double *max) {
_fitter_impl->fitUniform(sqrerror, min, max);
};
void fitTriangular(double *sqrerror, double *min, double *mo, double *max) {
_fitter_impl->fitTriangular(sqrerror, min, mo, max);
};
void fitNormal(double *sqrerror, double *avg, double *stddev) {
_fitter_impl->fitNormal(sqrerror, avg, stddev);
};
void fitExpo(double *sqrerror, double *avg1) {
_fitter_impl->fitExpo(sqrerror, avg1);
};
void fitErlang(double *sqrerror, double *a, double *b, double *offset, double *mult) {
_fitter_impl->fitErlang(sqrerror, a, b, offset, mult);
};
void fitBeta(double *sqrerror, double *a, double *b, double *offset, double *mult) {
_fitter_impl->fitBeta(sqrerror, a, b, offset, mult);
};
void fitWeibull(double *sqrerror, double *a, double *b, double *offset, double *mult){
_fitter_impl->fitWeibull(sqrerror, a, b, offset, mult);
};
void fitAll(double *sqrerror, char *name) {
_fitter_impl->fitAll(sqrerror, name);
};
private:
Fitter_if* _fitter_impl;
};
#endif /* FITTER_H */
<file_sep>/Integrator.h
/*
* 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.
*/
/*
* File: Integrator.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 19:09
*/
#ifndef INTEGRATOR_H
#define INTEGRATOR_H
#include "Integrator_if.h"
class Integrator : public Integrator_if {
public:
Integrator(Integrator_if* integrator_impl) {
_integrator_impl = integrator_impl;
};
Integrator(const Integrator& orig);
virtual ~Integrator();
public:
double integrate(double min, double max, double (*f)(double), double p1) {
return _integrator_impl->integrate(min, max, f, p1);
};
double integrate(double min, double max, double (*f)(double, double), double p1, double p2) {
return _integrator_impl->integrate(min, max, f, p1, p2);
};
double integrate(double min, double max, double (*f)(double, double, double), double p1, double p2, double p3) {
return _integrator_impl->integrate(min, max, f, p1, p2, p3);
};
public:
static double uniform(double min, double max);
static double exponential(double mean);
static double erlang(double mean, int M);
static double normal(double mean, double stddev);
static double gamma(double mean, double alpha);
static double beta(double alpha, double beta);
static double weibull(double alpha, double scale);
static double logNormal(double mean, double stddev);
static double triangular(double min, double mode, double max);
private:
Integrator_if* _integrator_impl;
};
#endif /* INTEGRATOR_H */
<file_sep>/main.cpp
/*
* 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.
*/
/*
* File: main.cpp
* Author: cancian
*
* Created on 21 de Junho de 2018, 12:47
*/
#include <cstdlib>
#include <iostream>
#include "Simulator.h"
#include "Create.h"
#include "Delay.h"
#include "Listener.h"
#include "Dispose.h"
using namespace std;
void traceHandler(TraceEvent e) {
std::cout << e.getText() << std::endl;
}
void traceSimulationHandler(TraceSimulationEvent e) {
std::cout << e.getText() << std::endl;
}
void buildSimpleCreateDelayDisposeModel(Model* model) {
// traces handle simulation events to output them
model->addTraceListener(&traceHandler);
model->addTraceReportListener(&traceHandler);
model->addTraceSimulationListener(&traceSimulationHandler);
// create and insert model components to the model
Create* create1 = new Create(model);
create1->setTimeBetweenCreationsExpression("1.5");
create1->setTimeUnit(Util::TimeUnit::TU_minute);
Delay* delay1 = new Delay(model);
delay1->setDelayExpression("30");
Dispose* dispose1 = new Dispose(model);
List<ModelComponent*>* components = model->getComponents();
components->insert(create1);
components->insert(delay1);
components->insert(dispose1);
// connect model components to create a "workflow"
// should always start from a SourceModelComponent and end at a SinkModelComponent (it will be checked)
create1->getNextComponents()->insert(delay1);
delay1->getNextComponents()->insert(dispose1);
}
void buildModel(Model* model) {
// change next command to build different models
buildSimpleCreateDelayDisposeModel(model);
}
void buildSimulationSystem() {
//OldObserver* traceObserver = new OldObserver();
Simulator* simulator = new Simulator();
Model* model = new Model(simulator);
buildModel(model);
simulator->getModels()->insert(model);
model->startSimulation();
model->showReports();
}
/*
*
*/
int main(int argc, char** argv) {
buildSimulationSystem();
return 0;
}
<file_sep>/Entity.h
/*
* 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.
*/
/*
* File: Entity.h
* Author: cancian
*
* Created on 21 de Junho de 2018, 16:30
*/
#ifndef ENTITY_H
#define ENTITY_H
#include "Util.h"
#include "ModelInfrastructure.h"
#include <string>
#include <map>
#include "AttributeValue.h"
class Entity: public ModelInfrastructure {
public:
Entity();
Entity(const Entity& orig);
virtual ~Entity();
public:
std::map<std::string, AttributeValue*>* getAttributeValues() const;
private:
std::map<std::string, AttributeValue*>* _attributeValues;
};
#endif /* ENTITY_H */
<file_sep>/Statistics_if.h
/*
* 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.
*/
/*
* File: Statistics_if.h
* Author: cancian
*
* Created on 14 de Agosto de 2018, 13:47
*/
#ifndef STATISTICS_IF_H
#define STATISTICS_IF_H
class Statistics_if {
public: // get & set
virtual void setFilename(std::string _filename) = 0;
virtual std::string getFilename() const = 0;
public:
virtual unsigned int numElements() = 0;
virtual double min() = 0;
virtual double max() = 0;
virtual double average() = 0;
virtual double mode() = 0;
virtual double mediane() = 0;
virtual double variance() = 0;
virtual double stddeviation() = 0;
virtual double variationCoef() = 0;
virtual double halfWidth(double alpha) = 0;
virtual double quartil(unsigned short num) = 0;
virtual double decil(unsigned short num) = 0;
virtual double centil(unsigned short num) = 0;
virtual void setHistogramNumClasses(unsigned short num) = 0;
virtual unsigned short histogramNumClasses() = 0;
virtual double histogramClassLowerLimit(unsigned short classNum) = 0;
virtual double histogramClassFrequency(unsigned short classNum) = 0;
};
#endif /* STATISTICS_IF_H */
<file_sep>/nbproject/Makefile-Debug.mk
#
# Generated Makefile - do not edit!
#
# Edit the Makefile in the project folder instead (../Makefile). Each target
# has a -pre and a -post target defined where you can add customized code.
#
# This makefile implements configuration specific macros and targets.
# Environment
MKDIR=mkdir
CP=cp
GREP=grep
NM=nm
CCADMIN=CCadmin
RANLIB=ranlib
CC=gcc
CCC=g++
CXX=g++
FC=gfortran
AS=as
# Macros
CND_PLATFORM=GNU-Linux
CND_DLIB_EXT=so
CND_CONF=Debug
CND_DISTDIR=dist
CND_BUILDDIR=build
# Include project Makefile
include Makefile
# Object Directory
OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}
# Object Files
OBJECTFILES= \
${OBJECTDIR}/Analyser.o \
${OBJECTDIR}/AttributeValue.o \
${OBJECTDIR}/CollectorImpl1.o \
${OBJECTDIR}/Create.o \
${OBJECTDIR}/Delay.o \
${OBJECTDIR}/Dispose.o \
${OBJECTDIR}/Entity.o \
${OBJECTDIR}/EntityType.o \
${OBJECTDIR}/Event.o \
${OBJECTDIR}/Listener.o \
${OBJECTDIR}/Model.o \
${OBJECTDIR}/ModelComponent.o \
${OBJECTDIR}/ModelInfrastructure.o \
${OBJECTDIR}/OldEventObserv.o \
${OBJECTDIR}/OldObservable.o \
${OBJECTDIR}/OldObserver.o \
${OBJECTDIR}/Plugin.o \
${OBJECTDIR}/Simulator.o \
${OBJECTDIR}/SinkModelComponent.o \
${OBJECTDIR}/SourceModelComponent.o \
${OBJECTDIR}/Util.o \
${OBJECTDIR}/main.o
# C Compiler Flags
CFLAGS=
# CC Compiler Flags
CCFLAGS=-std=c++11 -fpermissive
CXXFLAGS=-std=c++11 -fpermissive
# Fortran Compiler Flags
FFLAGS=
# Assembler Flags
ASFLAGS=
# Link Libraries and Options
LDLIBSOPTIONS=
# Build Targets
.build-conf: ${BUILD_SUBPROJECTS}
"${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/rebornedgenesys
${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/rebornedgenesys: ${OBJECTFILES}
${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}
${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/rebornedgenesys ${OBJECTFILES} ${LDLIBSOPTIONS}
${OBJECTDIR}/Analyser.o: Analyser.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Analyser.o Analyser.cpp
${OBJECTDIR}/AttributeValue.o: AttributeValue.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/AttributeValue.o AttributeValue.cpp
${OBJECTDIR}/CollectorImpl1.o: CollectorImpl1.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/CollectorImpl1.o CollectorImpl1.cpp
${OBJECTDIR}/Create.o: Create.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Create.o Create.cpp
${OBJECTDIR}/Delay.o: Delay.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Delay.o Delay.cpp
${OBJECTDIR}/Dispose.o: Dispose.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Dispose.o Dispose.cpp
${OBJECTDIR}/Entity.o: Entity.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Entity.o Entity.cpp
${OBJECTDIR}/EntityType.o: EntityType.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/EntityType.o EntityType.cpp
${OBJECTDIR}/Event.o: Event.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Event.o Event.cpp
${OBJECTDIR}/Listener.o: Listener.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Listener.o Listener.cpp
${OBJECTDIR}/Model.o: Model.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Model.o Model.cpp
${OBJECTDIR}/ModelComponent.o: ModelComponent.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/ModelComponent.o ModelComponent.cpp
${OBJECTDIR}/ModelInfrastructure.o: ModelInfrastructure.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/ModelInfrastructure.o ModelInfrastructure.cpp
${OBJECTDIR}/OldEventObserv.o: OldEventObserv.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/OldEventObserv.o OldEventObserv.cpp
${OBJECTDIR}/OldObservable.o: OldObservable.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/OldObservable.o OldObservable.cpp
${OBJECTDIR}/OldObserver.o: OldObserver.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/OldObserver.o OldObserver.cpp
${OBJECTDIR}/Plugin.o: Plugin.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Plugin.o Plugin.cpp
${OBJECTDIR}/Simulator.o: Simulator.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Simulator.o Simulator.cpp
${OBJECTDIR}/SinkModelComponent.o: SinkModelComponent.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/SinkModelComponent.o SinkModelComponent.cpp
${OBJECTDIR}/SourceModelComponent.o: SourceModelComponent.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/SourceModelComponent.o SourceModelComponent.cpp
${OBJECTDIR}/Util.o: Util.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/Util.o Util.cpp
${OBJECTDIR}/main.o: main.cpp nbproject/Makefile-${CND_CONF}.mk
${MKDIR} -p ${OBJECTDIR}
${RM} "$@.d"
$(COMPILE.cc) -g -MMD -MP -MF "$@.d" -o ${OBJECTDIR}/main.o main.cpp
# Subprojects
.build-subprojects:
# Clean Targets
.clean-conf: ${CLEAN_SUBPROJECTS}
${RM} -r ${CND_BUILDDIR}/${CND_CONF}
# Subprojects
.clean-subprojects:
# Enable dependency checking
.dep.inc: .depcheck-impl
include .dep.inc
<file_sep>/MMC.h
/*
* 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.
*/
/*
* File: MMC.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 18:22
*/
#ifndef MMC_H
#define MMC_H
#include "MMC_if.h"
class MMC : public MMC_if {
public:
MMC(MMC_if* mmc_impl) {
_mmc_impl = mmc_impl;
};
MMC(const MMC& orig);
virtual ~MMC();
public: // probability distributions
double random() {
return _mmc_impl->random();
};
double uniform(double min, double max) {
return _mmc_impl->uniform(min, max);
}
double exponential(double mean) {
return _mmc_impl->exponential(mean);
};
double erlang(double mean, int M) {
return _mmc_impl->erlang(mean, M);
};
double normal(double mean, double stddev){
return _mmc_impl->normal(mean, stddev);
};
double gamma(double mean, double alpha){
return _mmc_impl->gamma(mean, alpha);
};
double beta(double alpha, double beta, double infLimit, double supLimit){
return _mmc_impl->beta(alpha, beta, infLimit, supLimit);
};
double weibull(double alpha, double scale){
return _mmc_impl->weibull(alpha, scale);
};
double logNormal(double mean, double stddev){
return _mmc_impl->logNormal(mean,stddev);
};
double triangular(double min, double mode, double max){
return _mmc_impl->triangular(min, mode, max);
};
double discrete(double value, double acumProb, ...){
//return _mmc_impl->;
};
public:
void setRNGparameters(RNG_Parameters param) {
_mmc_impl->setRNGparameters(param);
};
RNG_Parameters getRNGparameters() const {
return _mmc_impl->getRNGparameters();
};
private:
MMC_if* _mmc_impl;
};
#endif /* MMC_H */
<file_sep>/ModelInfrastructure.cpp
/*
* 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.
*/
/*
* File: ModelInfrastructure.cpp
* Author: cancian
*
* Created on 21 de Junho de 2018, 19:40
*/
#include <typeinfo>
#include "ModelInfrastructure.h"
ModelInfrastructure::ModelInfrastructure() {
_id = reinterpret_cast<Util::identitifcation>(this); // ID is always the address of this
// _name = "Infra " + std::to_string(Util::_S_generateNewIdOfType("ModelInfrastructure")); //// std::to_string(_id);
}
ModelInfrastructure::ModelInfrastructure(const ModelInfrastructure& orig) {
}
ModelInfrastructure::~ModelInfrastructure() {
}
std::string ModelInfrastructure::show(){
return "{id="+std::to_string(_id)+", name=\""+_name+"\"}";
}
Util::identitifcation ModelInfrastructure::getId() const {
return _id;
}
void ModelInfrastructure::setName(std::string _name) {
this->_name = _name;
}
std::string ModelInfrastructure::getName() const {
return _name;
}
<file_sep>/Statistics.h
/*
* 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.
*/
/*
* File: Statistics.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 18:32
*/
#ifndef STATISTICS_H
#define STATISTICS_H
#include <string>
#include "Statistics_if.h"
class Statistics : public Statistics_if {
public:
Statistics(Statistics_if* statistics_impl) {
_statistics_impl = statistics_impl;
};
Statistics(const Statistics& orig);
virtual ~Statistics();
public: // get & set
void setFilename(std::string filename){
_statistics_impl->setFilename(filename);
};
std::string getFilename() const {
return _statistics_impl->getFilename();
};
public:
unsigned int numElements(){
return _statistics_impl->numElements();
};
double min(){
return _statistics_impl->min();
};
double max(){
return _statistics_impl->max();
};
double average(){
return _statistics_impl->average();
};
double mode(){
return _statistics_impl->mode();
};
double mediane(){
return _statistics_impl->mediane();
};
double variance(){
return _statistics_impl->variance();
};
double stddeviation(){
return _statistics_impl->stddeviation();
};
double variationCoef(){
return _statistics_impl->variationCoef();
};
double halfWidth(double alpha){
return _statistics_impl->halfWidth(alpha);
};
double quartil(unsigned short num){
return _statistics_impl->quartil(num);
};
double decil(unsigned short num){
return _statistics_impl->decil(num);
};
double centil(unsigned short num){
return _statistics_impl->centil(num);
};
void setHistogramNumClasses(unsigned short num){
_statistics_impl->setHistogramNumClasses(num);
};
unsigned short histogramNumClasses(){
return _statistics_impl->histogramNumClasses();
};
double histogramClassLowerLimit(unsigned short classNum) {
return _statistics_impl->histogramClassLowerLimit();
};
double histogramClassFrequency(unsigned short classNum){
return _statistics_impl->histogramClassFrequency(classNum);
};
private:
Statistics_if* _statistics_impl;
};
#endif /* STATISTICS_H */
<file_sep>/Integrator_if.h
/*
* 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.
*/
/*
* File: Integrator_if.h
* Author: cancian
*
* Created on 14 de Agosto de 2018, 13:54
*/
#ifndef INTEGRATOR_IF_H
#define INTEGRATOR_IF_H
class Integrator_if {
public:
virtual double integrate(double min, double max, double (*f)(double), double p1) = 0;
virtual double integrate(double min, double max, double (*f)(double, double), double p1, double p2) = 0;
virtual double integrate(double min, double max, double (*f)(double, double,double), double p1, double p2, double p3) = 0;
public:
static double uniform(double min, double max);
static double exponential(double mean);
static double erlang(double mean, int M);
static double normal(double mean, double stddev);
static double gamma(double mean, double alpha);
static double beta(double alpha, double beta);
static double weibull(double alpha, double scale);
static double logNormal(double mean, double stddev);
static double triangular(double min, double mode, double max);
};
#endif /* INTEGRATOR_IF_H */
<file_sep>/Collector.h
/*
* 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.
*/
/*
* File: Collector.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 19:06
*/
#ifndef COLLECTOR_H
#define COLLECTOR_H
#include "Collector_if.h"
class Collector : public Collector_if {
public:
Collector(Collector_if* collector_impl) {
_collector_impl = collector_impl;
};
Collector(const Collector& orig);
virtual ~Collector();
public:
void clear() {
_collector_impl->clear();
};
void addValue(double value){
_collector_impl->addValue(value);
};
double value(unsigned int num) {
return _collector_impl->value(num);
};
unsigned int numElements() {
return _collector_impl->numElements();
};
std::string getFilename() {
return _collector_impl->getFilename();
};
void setFilename(std::string filename) {
_collector_impl->setFilename(filename);
};
std::string getName() {
return _collector_impl->getName();
};
void setName(std::string name) {
_collector_impl->setName(name) ;
};
private:
Collector_if* _collector_impl;
};
#endif /* COLLECTOR_H */
<file_sep>/CollectorImpl1.cpp
/*
* 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.
*/
/*
* File: CollectorImpl1.cpp
* Author: cancian
*
* Created on 14 de Agosto de 2018, 19:43
*/
#include "CollectorImpl1.h"
CollectorImpl1::CollectorImpl1() {
}
CollectorImpl1::CollectorImpl1(const CollectorImpl1& orig) {
}
CollectorImpl1::~CollectorImpl1() {
}
<file_sep>/OldEventObserv.h
/*
* 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.
*/
/*
* File: Event.h
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:37
*/
#ifndef EVENTOBSERV_H
#define EVENTOBSERV_H
class OldEventObserv {
public:
OldEventObserv();
OldEventObserv(const OldEventObserv& orig);
virtual ~OldEventObserv();
private:
};
#endif /* EVENTOBSERV_H */
<file_sep>/CollectorImpl1.h
/*
* 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.
*/
/*
* File: CollectorImpl1.h
* Author: cancian
*
* Created on 14 de Agosto de 2018, 19:43
*/
#ifndef COLLECTORIMPL1_H
#define COLLECTORIMPL1_H
#include <string>
#include "Collector_if.h"
class CollectorImpl1 : public Collector_if {
public:
CollectorImpl1();
CollectorImpl1(const CollectorImpl1& orig);
virtual ~CollectorImpl1();
public: // interface implementation
void clear() {
};
void addValue(double value) {
};
double value(unsigned int num) {
return 0.0;
};
unsigned int numElements() {
return 0;
};
std::string getFilename() {
return "";
};
void setFilename(std::string filename) {
};
std::string getName() {
return _name;
};
void setName(std::string name) {
_name = name;
};
private:
std::string _name;
};
#endif /* COLLECTORIMPL1_H */
<file_sep>/OldObservable.h
/*
* 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.
*/
/*
* File: Observable.h
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:36
*/
#ifndef OBSERVABLE_H
#define OBSERVABLE_H
#include <list>
class OldObserver;
class OldObservable {
public:
OldObservable();
OldObservable(const OldObservable& orig);
virtual ~OldObservable();
public:
void addObserver(OldObserver* observer);
void notify();
private:
std::list<OldObserver*>* _observers;
};
#endif /* OBSERVABLE_H */
<file_sep>/Analyser.cpp
/*
* 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.
*/
/*
* File: Analyser.cpp
* Author: cancian
*
* Created on 7 de Agosto de 2018, 19:03
*/
#include "Analyser.h"
Analyser::Analyser() {
}
Analyser::Analyser(const Analyser& orig) {
}
Analyser::~Analyser() {
}
<file_sep>/OldObservable.cpp
/*
* 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.
*/
/*
* File: Observable.cpp
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:36
*/
#include <list>
#include "OldObservable.h"
#include "OldObserver.h"
OldObservable::OldObservable() {
_observers = new std::list<OldObserver*>();
}
OldObservable::OldObservable(const OldObservable& orig) {
}
OldObservable::~OldObservable() {
}
void OldObservable::addObserver(OldObserver* observer) {
_observers->insert(_observers->end(), observer);
}
void OldObservable::notify() {
OldEventObserv event = OldEventObserv();
for (std::list<OldObserver*>::iterator it=_observers->begin(); it != _observers->end(); it++) {
(*it)->onNotify(this, event);
}
}<file_sep>/OldEventObserv.cpp
/*
* 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.
*/
/*
* File: Event.cpp
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:37
*/
#include "OldEventObserv.h"
OldEventObserv::OldEventObserv() {
}
OldEventObserv::OldEventObserv(const OldEventObserv& orig) {
}
OldEventObserv::~OldEventObserv() {
}
<file_sep>/Traits.h
/*
* 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.
*/
/*
* File: Traits.h
* Author: cancian
*
* Created on 14 de Agosto de 2018, 19:36
*/
#ifndef TRAITS_H
#define TRAITS_H
#include "Model.h"
#include "Collector_if.h"
#include "CollectorImpl1.h"
template <typename T>
struct Traits {
static const bool debugged = true;
};
template <> struct Traits<Model> {
};
template <> struct Traits<Collector_if> {
typedef CollectorImpl1 Collector_Impl;
};
#endif /* TRAITS_H */
<file_sep>/OldObserver.h
/*
* 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.
*/
/*
* File: Observer.h
* Author: cancian
*
* Created on 21 de Junho de 2018, 14:35
*/
#ifndef OBSERVER_H
#define OBSERVER_H
#include "OldObservable.h"
#include "OldEventObserv.h"
class OldObserver {
public:
OldObserver();
OldObserver(const OldObserver& orig);
virtual ~OldObserver();
public:
virtual void onNotify(OldObservable * entity, OldEventObserv event) = 0;
private:
};
#endif /* OBSERVER_H */
<file_sep>/Analyser.h
/*
* 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.
*/
/*
* File: Analyser.h
* Author: cancian
*
* Created on 7 de Agosto de 2018, 19:03
*/
#ifndef ANALYSER_H
#define ANALYSER_H
enum Comparition {
LESS_THAN = 1,
EQUAL = 2,
DIFFERENT = 3,
GREATER_THAN = 4
};
class Analyser {
public:
Analyser();
Analyser(const Analyser& orig);
~Analyser();
public:
double semiConfidenceInterval(double confidencelevel);
unsigned int newSampleLength(double confidencelevel);
bool isNormalDistribution(double confidencelevel);
bool testAverageDifference(double confidencelevel, double avg, Comparition comp, bool nullhipothesys);
bool testProportionDifference(double confidencelevel, double prop, Comparition comp, bool nullhipothesys);
bool testVarianceDifference(double confidencelevel, double var, Comparition comp, bool nullhipothesys);
bool testAverageDifference(double confidencelevel, char *filename2, Comparition comp, bool nullhipothesys);
unsigned int bachSize(double maxcovariance);
private:
//AnalyserImpl * _a;
};
#endif /* ANALYSER_H */
| 4aff1d087d9176d680d34e9a32a090e2cdbe11b6 | [
"Makefile",
"C++"
] | 22 | C++ | oshogun/GenESyS-Reborn | 350c9b5468be69316f0f037414308295e4c57339 | e6216e4520f8a018fb858bfab95b43d30a141e3b |
refs/heads/master | <file_sep>from antlr4 import *
from generated import EasyXMLVisitor, EasyXMLLexer, EasyXMLParser
from node.Node import Node
from visitor.visitor import MyVisitor
def main(xml_program: str) -> None:
input_stream = FileStream('xml_program.el')
lexer = EasyXMLLexer.EasyXMLLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = EasyXMLParser.EasyXMLParser(stream)
tree = parser.xml()
if parser.getNumberOfSyntaxErrors():
exit(1)
visitor = MyVisitor()
visitor.visit(tree)
print(1)
if __name__ == '__main__':
# if len(sys.argv) > 1:
# main(sys.argv[1])
main('')
<file_sep># Generated from EasyXML.g4 by ANTLR 4.9.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\64")
buf.write("\u0123\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7")
buf.write("\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16")
buf.write("\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23\t\23")
buf.write("\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\3\2\3\2\3\2\3")
buf.write("\2\3\2\3\2\3\2\5\2\66\n\2\3\2\3\2\3\2\3\2\5\2<\n\2\3\3")
buf.write("\3\3\3\3\3\3\5\3B\n\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4")
buf.write("\5\4L\n\4\3\4\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5")
buf.write("\3\5\3\5\3\5\5\5\\\n\5\3\5\7\5_\n\5\f\5\16\5b\13\5\3\6")
buf.write("\3\6\3\6\3\6\3\6\3\7\3\7\3\7\5\7l\n\7\3\7\3\7\3\7\3\b")
buf.write("\3\b\7\bs\n\b\f\b\16\bv\13\b\3\b\5\by\n\b\3\t\3\t\3\t")
buf.write("\3\t\3\t\7\t\u0080\n\t\f\t\16\t\u0083\13\t\3\t\3\t\3\n")
buf.write("\3\n\3\n\3\n\3\n\7\n\u008c\n\n\f\n\16\n\u008f\13\n\3\n")
buf.write("\3\n\3\13\3\13\3\13\3\13\7\13\u0097\n\13\f\13\16\13\u009a")
buf.write("\13\13\3\13\3\13\3\f\3\f\3\f\3\f\3\f\7\f\u00a3\n\f\f\f")
buf.write("\16\f\u00a6\13\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\7\r\u00af")
buf.write("\n\r\f\r\16\r\u00b2\13\r\3\r\3\r\3\16\3\16\3\16\5\16\u00b9")
buf.write("\n\16\3\16\3\16\3\16\7\16\u00be\n\16\f\16\16\16\u00c1")
buf.write("\13\16\3\16\3\16\5\16\u00c5\n\16\3\16\3\16\3\16\3\17\3")
buf.write("\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\20\3\21\5\21")
buf.write("\u00d5\n\21\3\21\3\21\3\21\5\21\u00da\n\21\3\21\7\21\u00dd")
buf.write("\n\21\f\21\16\21\u00e0\13\21\3\22\3\22\3\22\7\22\u00e5")
buf.write("\n\22\f\22\16\22\u00e8\13\22\3\22\3\22\3\22\7\22\u00ed")
buf.write("\n\22\f\22\16\22\u00f0\13\22\5\22\u00f2\n\22\3\23\3\23")
buf.write("\3\23\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\5\24\u00ff")
buf.write("\n\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\3\24\7\24\u0109")
buf.write("\n\24\f\24\16\24\u010c\13\24\3\25\3\25\3\25\5\25\u0111")
buf.write("\n\25\3\26\3\26\3\26\3\26\3\26\3\26\3\26\3\26\5\26\u011b")
buf.write("\n\26\3\27\3\27\6\27\u011f\n\27\r\27\16\27\u0120\3\27")
buf.write("\2\4\b&\30\2\4\6\b\n\f\16\20\22\24\26\30\32\34\36 \"$")
buf.write("&(*,\2\5\3\2\4\5\3\2\31\32\3\2\31\33\2\u0135\2;\3\2\2")
buf.write("\2\4=\3\2\2\2\6G\3\2\2\2\bQ\3\2\2\2\nc\3\2\2\2\fh\3\2")
buf.write("\2\2\16p\3\2\2\2\20z\3\2\2\2\22\u0086\3\2\2\2\24\u0092")
buf.write("\3\2\2\2\26\u009d\3\2\2\2\30\u00a9\3\2\2\2\32\u00b5\3")
buf.write("\2\2\2\34\u00c9\3\2\2\2\36\u00ce\3\2\2\2 \u00d4\3\2\2")
buf.write("\2\"\u00f1\3\2\2\2$\u00f3\3\2\2\2&\u00fe\3\2\2\2(\u0110")
buf.write("\3\2\2\2*\u011a\3\2\2\2,\u011e\3\2\2\2./\7\5\2\2/\60\7")
buf.write("\31\2\2\60\61\7%\2\2\61\62\7\27\2\2\62\63\7\5\2\2\63\65")
buf.write("\7\35\2\2\64\66\5&\24\2\65\64\3\2\2\2\65\66\3\2\2\2\66")
buf.write("\67\3\2\2\2\678\7\36\2\28<\7#\2\29:\t\2\2\2:<\5\4\3\2")
buf.write(";.\3\2\2\2;9\3\2\2\2<\3\3\2\2\2=A\7\31\2\2>?\7\35\2\2")
buf.write("?@\7\32\2\2@B\7\36\2\2A>\3\2\2\2AB\3\2\2\2BC\3\2\2\2C")
buf.write("D\7%\2\2DE\5&\24\2EF\7#\2\2F\5\3\2\2\2GK\7\31\2\2HI\7")
buf.write("\35\2\2IJ\7\32\2\2JL\7\36\2\2KH\3\2\2\2KL\3\2\2\2LM\3")
buf.write("\2\2\2MN\7&\2\2NO\5&\24\2OP\7#\2\2P\7\3\2\2\2QR\b\5\1")
buf.write("\2RS\7\31\2\2ST\7(\2\2TU\7\31\2\2U`\3\2\2\2VW\f\5\2\2")
buf.write("W_\7#\2\2XY\f\4\2\2Y[\7\35\2\2Z\\\5\"\22\2[Z\3\2\2\2[")
buf.write("\\\3\2\2\2\\]\3\2\2\2]_\7\36\2\2^V\3\2\2\2^X\3\2\2\2_")
buf.write("b\3\2\2\2`^\3\2\2\2`a\3\2\2\2a\t\3\2\2\2b`\3\2\2\2cd\7")
buf.write("\31\2\2de\7\37\2\2ef\t\3\2\2fg\7 \2\2g\13\3\2\2\2hi\7")
buf.write("\31\2\2ik\7\35\2\2jl\5\"\22\2kj\3\2\2\2kl\3\2\2\2lm\3")
buf.write("\2\2\2mn\7\36\2\2no\7#\2\2o\r\3\2\2\2pt\5\20\t\2qs\5\22")
buf.write("\n\2rq\3\2\2\2sv\3\2\2\2tr\3\2\2\2tu\3\2\2\2ux\3\2\2\2")
buf.write("vt\3\2\2\2wy\5\24\13\2xw\3\2\2\2xy\3\2\2\2y\17\3\2\2\2")
buf.write("z{\7\21\2\2{|\5 \21\2|}\7(\2\2}\u0081\7!\2\2~\u0080\5")
buf.write("*\26\2\177~\3\2\2\2\u0080\u0083\3\2\2\2\u0081\177\3\2")
buf.write("\2\2\u0081\u0082\3\2\2\2\u0082\u0084\3\2\2\2\u0083\u0081")
buf.write("\3\2\2\2\u0084\u0085\7\"\2\2\u0085\21\3\2\2\2\u0086\u0087")
buf.write("\7\17\2\2\u0087\u0088\5 \21\2\u0088\u0089\7(\2\2\u0089")
buf.write("\u008d\7!\2\2\u008a\u008c\5*\26\2\u008b\u008a\3\2\2\2")
buf.write("\u008c\u008f\3\2\2\2\u008d\u008b\3\2\2\2\u008d\u008e\3")
buf.write("\2\2\2\u008e\u0090\3\2\2\2\u008f\u008d\3\2\2\2\u0090\u0091")
buf.write("\7\"\2\2\u0091\23\3\2\2\2\u0092\u0093\7\20\2\2\u0093\u0094")
buf.write("\7(\2\2\u0094\u0098\7!\2\2\u0095\u0097\5*\26\2\u0096\u0095")
buf.write("\3\2\2\2\u0097\u009a\3\2\2\2\u0098\u0096\3\2\2\2\u0098")
buf.write("\u0099\3\2\2\2\u0099\u009b\3\2\2\2\u009a\u0098\3\2\2\2")
buf.write("\u009b\u009c\7\"\2\2\u009c\25\3\2\2\2\u009d\u009e\7\22")
buf.write("\2\2\u009e\u009f\5\36\20\2\u009f\u00a0\7(\2\2\u00a0\u00a4")
buf.write("\7!\2\2\u00a1\u00a3\5*\26\2\u00a2\u00a1\3\2\2\2\u00a3")
buf.write("\u00a6\3\2\2\2\u00a4\u00a2\3\2\2\2\u00a4\u00a5\3\2\2\2")
buf.write("\u00a5\u00a7\3\2\2\2\u00a6\u00a4\3\2\2\2\u00a7\u00a8\7")
buf.write("\"\2\2\u00a8\27\3\2\2\2\u00a9\u00aa\7\23\2\2\u00aa\u00ab")
buf.write("\5 \21\2\u00ab\u00ac\7(\2\2\u00ac\u00b0\7!\2\2\u00ad\u00af")
buf.write("\5*\26\2\u00ae\u00ad\3\2\2\2\u00af\u00b2\3\2\2\2\u00b0")
buf.write("\u00ae\3\2\2\2\u00b0\u00b1\3\2\2\2\u00b1\u00b3\3\2\2\2")
buf.write("\u00b2\u00b0\3\2\2\2\u00b3\u00b4\7\"\2\2\u00b4\31\3\2")
buf.write("\2\2\u00b5\u00b6\t\2\2\2\u00b6\u00b8\7\31\2\2\u00b7\u00b9")
buf.write("\5\"\22\2\u00b8\u00b7\3\2\2\2\u00b8\u00b9\3\2\2\2\u00b9")
buf.write("\u00ba\3\2\2\2\u00ba\u00bb\7(\2\2\u00bb\u00bf\7!\2\2\u00bc")
buf.write("\u00be\5*\26\2\u00bd\u00bc\3\2\2\2\u00be\u00c1\3\2\2\2")
buf.write("\u00bf\u00bd\3\2\2\2\u00bf\u00c0\3\2\2\2\u00c0\u00c2\3")
buf.write("\2\2\2\u00c1\u00bf\3\2\2\2\u00c2\u00c4\7\30\2\2\u00c3")
buf.write("\u00c5\5&\24\2\u00c4\u00c3\3\2\2\2\u00c4\u00c5\3\2\2\2")
buf.write("\u00c5\u00c6\3\2\2\2\u00c6\u00c7\7#\2\2\u00c7\u00c8\7")
buf.write("\"\2\2\u00c8\33\3\2\2\2\u00c9\u00ca\7\35\2\2\u00ca\u00cb")
buf.write("\7\5\2\2\u00cb\u00cc\7\36\2\2\u00cc\u00cd\7\31\2\2\u00cd")
buf.write("\35\3\2\2\2\u00ce\u00cf\t\2\2\2\u00cf\u00d0\7\31\2\2\u00d0")
buf.write("\u00d1\7\24\2\2\u00d1\u00d2\7\31\2\2\u00d2\37\3\2\2\2")
buf.write("\u00d3\u00d5\7\63\2\2\u00d4\u00d3\3\2\2\2\u00d4\u00d5")
buf.write("\3\2\2\2\u00d5\u00d6\3\2\2\2\u00d6\u00de\5&\24\2\u00d7")
buf.write("\u00d9\7\b\2\2\u00d8\u00da\7\63\2\2\u00d9\u00d8\3\2\2")
buf.write("\2\u00d9\u00da\3\2\2\2\u00da\u00db\3\2\2\2\u00db\u00dd")
buf.write("\5 \21\2\u00dc\u00d7\3\2\2\2\u00dd\u00e0\3\2\2\2\u00de")
buf.write("\u00dc\3\2\2\2\u00de\u00df\3\2\2\2\u00df!\3\2\2\2\u00e0")
buf.write("\u00de\3\2\2\2\u00e1\u00e6\5&\24\2\u00e2\u00e3\7\3\2\2")
buf.write("\u00e3\u00e5\5&\24\2\u00e4\u00e2\3\2\2\2\u00e5\u00e8\3")
buf.write("\2\2\2\u00e6\u00e4\3\2\2\2\u00e6\u00e7\3\2\2\2\u00e7\u00f2")
buf.write("\3\2\2\2\u00e8\u00e6\3\2\2\2\u00e9\u00ee\5$\23\2\u00ea")
buf.write("\u00eb\7\3\2\2\u00eb\u00ed\5$\23\2\u00ec\u00ea\3\2\2\2")
buf.write("\u00ed\u00f0\3\2\2\2\u00ee\u00ec\3\2\2\2\u00ee\u00ef\3")
buf.write("\2\2\2\u00ef\u00f2\3\2\2\2\u00f0\u00ee\3\2\2\2\u00f1\u00e1")
buf.write("\3\2\2\2\u00f1\u00e9\3\2\2\2\u00f2#\3\2\2\2\u00f3\u00f4")
buf.write("\t\2\2\2\u00f4\u00f5\7\31\2\2\u00f5%\3\2\2\2\u00f6\u00f7")
buf.write("\b\24\1\2\u00f7\u00f8\7\35\2\2\u00f8\u00f9\5&\24\2\u00f9")
buf.write("\u00fa\7\36\2\2\u00fa\u00ff\3\2\2\2\u00fb\u00ff\5(\25")
buf.write("\2\u00fc\u00ff\5\34\17\2\u00fd\u00ff\t\4\2\2\u00fe\u00f6")
buf.write("\3\2\2\2\u00fe\u00fb\3\2\2\2\u00fe\u00fc\3\2\2\2\u00fe")
buf.write("\u00fd\3\2\2\2\u00ff\u010a\3\2\2\2\u0100\u0101\f\7\2\2")
buf.write("\u0101\u0102\7\6\2\2\u0102\u0109\5&\24\b\u0103\u0104\f")
buf.write("\6\2\2\u0104\u0105\7\7\2\2\u0105\u0109\5&\24\7\u0106\u0107")
buf.write("\f\t\2\2\u0107\u0109\7#\2\2\u0108\u0100\3\2\2\2\u0108")
buf.write("\u0103\3\2\2\2\u0108\u0106\3\2\2\2\u0109\u010c\3\2\2\2")
buf.write("\u010a\u0108\3\2\2\2\u010a\u010b\3\2\2\2\u010b\'\3\2\2")
buf.write("\2\u010c\u010a\3\2\2\2\u010d\u0111\5\b\5\2\u010e\u0111")
buf.write("\5\f\7\2\u010f\u0111\5\n\6\2\u0110\u010d\3\2\2\2\u0110")
buf.write("\u010e\3\2\2\2\u0110\u010f\3\2\2\2\u0111)\3\2\2\2\u0112")
buf.write("\u011b\5(\25\2\u0113\u011b\5\34\17\2\u0114\u011b\5\2\2")
buf.write("\2\u0115\u011b\5\4\3\2\u0116\u011b\5\6\4\2\u0117\u011b")
buf.write("\5\16\b\2\u0118\u011b\5\26\f\2\u0119\u011b\5\30\r\2\u011a")
buf.write("\u0112\3\2\2\2\u011a\u0113\3\2\2\2\u011a\u0114\3\2\2\2")
buf.write("\u011a\u0115\3\2\2\2\u011a\u0116\3\2\2\2\u011a\u0117\3")
buf.write("\2\2\2\u011a\u0118\3\2\2\2\u011a\u0119\3\2\2\2\u011b+")
buf.write("\3\2\2\2\u011c\u011f\5*\26\2\u011d\u011f\5\32\16\2\u011e")
buf.write("\u011c\3\2\2\2\u011e\u011d\3\2\2\2\u011f\u0120\3\2\2\2")
buf.write("\u0120\u011e\3\2\2\2\u0120\u0121\3\2\2\2\u0121-\3\2\2")
buf.write("\2!\65;AK[^`ktx\u0081\u008d\u0098\u00a4\u00b0\u00b8\u00bf")
buf.write("\u00c4\u00d4\u00d9\u00de\u00e6\u00ee\u00f1\u00fe\u0108")
buf.write("\u010a\u0110\u011a\u011e\u0120")
return buf.getvalue()
class EasyXMLParser ( Parser ):
grammarFileName = "EasyXML.g4"
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
sharedContextCache = PredictionContextCache()
literalNames = [ "<INVALID>", "','", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "<INVALID>", "'table'", "'cell'", "'attribute'",
"'string'", "'int'", "'float'", "'elif'", "'else'",
"'if'", "'for'", "'while'", "'in'", "'and'", "'or'",
"'new'", "'return'", "<INVALID>", "<INVALID>", "<INVALID>",
"<INVALID>", "'('", "')'", "'['", "']'", "'{'", "'}'",
"';'", "<INVALID>", "'='", "'+='", "'.'", "':'", "'>'",
"'<'", "'=='", "'!='", "'>='", "'<='", "'+'", "'-'",
"'*'", "'/'", "'!'" ]
symbolicNames = [ "<INVALID>", "<INVALID>", "ARRAY_TYPE", "TYPE", "ACTION_OPERATOR",
"BOOL_OPERATOR", "ANDOR", "TABLE", "CELL", "ATTRIBUTE",
"STRING", "INT", "FLOAT", "ELIF", "ELSE", "IF", "FOR",
"WHILE", "IN", "AND", "OR", "NEW", "RETURN", "VARNAME",
"NUMBER_LITERAL", "STRING_LITERAL", "WHITESPACE",
"OPEN_BRACKET", "CLOSE_BRACKET", "OPEN_SQUAR_EBRACKET",
"CLOSE_SQUARE_BRACKET", "OPEN_FIGURE_BRACKET", "CLOSE_FIGURE_BRACKET",
"SEMICOLON", "QOUTES", "ASSIGMENT", "SUM_ASSIGMENT",
"DOT", "COLON", "MORE_THAN", "LESS_THAN", "EQUAL",
"NOT_EQUAL", "MORE_EQUAL", "LESS_EQUAL", "PlUS", "MINUS",
"MULTIPLICATION", "DIVISION", "NOT", "COMMENT" ]
RULE_var_init = 0
RULE_assignment = 1
RULE_sum_assignment = 2
RULE_get = 3
RULE_get_array_element = 4
RULE_func_call = 5
RULE_if_statement = 6
RULE_if_block = 7
RULE_elif_block = 8
RULE_else_block = 9
RULE_for_statement = 10
RULE_while_statement = 11
RULE_func_init = 12
RULE_type_cast = 13
RULE_range_statement = 14
RULE_condition = 15
RULE_params = 16
RULE_param = 17
RULE_expression = 18
RULE_get_operation = 19
RULE_operation = 20
RULE_xml = 21
ruleNames = [ "var_init", "assignment", "sum_assignment", "get", "get_array_element",
"func_call", "if_statement", "if_block", "elif_block",
"else_block", "for_statement", "while_statement", "func_init",
"type_cast", "range_statement", "condition", "params",
"param", "expression", "get_operation", "operation",
"xml" ]
EOF = Token.EOF
T__0=1
ARRAY_TYPE=2
TYPE=3
ACTION_OPERATOR=4
BOOL_OPERATOR=5
ANDOR=6
TABLE=7
CELL=8
ATTRIBUTE=9
STRING=10
INT=11
FLOAT=12
ELIF=13
ELSE=14
IF=15
FOR=16
WHILE=17
IN=18
AND=19
OR=20
NEW=21
RETURN=22
VARNAME=23
NUMBER_LITERAL=24
STRING_LITERAL=25
WHITESPACE=26
OPEN_BRACKET=27
CLOSE_BRACKET=28
OPEN_SQUAR_EBRACKET=29
CLOSE_SQUARE_BRACKET=30
OPEN_FIGURE_BRACKET=31
CLOSE_FIGURE_BRACKET=32
SEMICOLON=33
QOUTES=34
ASSIGMENT=35
SUM_ASSIGMENT=36
DOT=37
COLON=38
MORE_THAN=39
LESS_THAN=40
EQUAL=41
NOT_EQUAL=42
MORE_EQUAL=43
LESS_EQUAL=44
PlUS=45
MINUS=46
MULTIPLICATION=47
DIVISION=48
NOT=49
COMMENT=50
def __init__(self, input:TokenStream, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.9.1")
self._interp = ParserATNSimulator(self, self.atn, self.decisionsToDFA, self.sharedContextCache)
self._predicates = None
class Var_initContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def TYPE(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.TYPE)
else:
return self.getToken(EasyXMLParser.TYPE, i)
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def ASSIGMENT(self):
return self.getToken(EasyXMLParser.ASSIGMENT, 0)
def NEW(self):
return self.getToken(EasyXMLParser.NEW, 0)
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def expression(self):
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,0)
def assignment(self):
return self.getTypedRuleContext(EasyXMLParser.AssignmentContext,0)
def ARRAY_TYPE(self):
return self.getToken(EasyXMLParser.ARRAY_TYPE, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_var_init
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitVar_init" ):
return visitor.visitVar_init(self)
else:
return visitor.visitChildren(self)
def var_init(self):
localctx = EasyXMLParser.Var_initContext(self, self._ctx, self.state)
self.enterRule(localctx, 0, self.RULE_var_init)
self._la = 0 # Token type
try:
self.state = 57
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,1,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 44
self.match(EasyXMLParser.TYPE)
self.state = 45
self.match(EasyXMLParser.VARNAME)
self.state = 46
self.match(EasyXMLParser.ASSIGMENT)
self.state = 47
self.match(EasyXMLParser.NEW)
self.state = 48
self.match(EasyXMLParser.TYPE)
self.state = 49
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 51
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 50
self.expression(0)
self.state = 53
self.match(EasyXMLParser.CLOSE_BRACKET)
self.state = 54
self.match(EasyXMLParser.SEMICOLON)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 55
_la = self._input.LA(1)
if not(_la==EasyXMLParser.ARRAY_TYPE or _la==EasyXMLParser.TYPE):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 56
self.assignment()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class AssignmentContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def ASSIGMENT(self):
return self.getToken(EasyXMLParser.ASSIGMENT, 0)
def expression(self):
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def NUMBER_LITERAL(self):
return self.getToken(EasyXMLParser.NUMBER_LITERAL, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_assignment
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitAssignment" ):
return visitor.visitAssignment(self)
else:
return visitor.visitChildren(self)
def assignment(self):
localctx = EasyXMLParser.AssignmentContext(self, self._ctx, self.state)
self.enterRule(localctx, 2, self.RULE_assignment)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 59
self.match(EasyXMLParser.VARNAME)
self.state = 63
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==EasyXMLParser.OPEN_BRACKET:
self.state = 60
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 61
self.match(EasyXMLParser.NUMBER_LITERAL)
self.state = 62
self.match(EasyXMLParser.CLOSE_BRACKET)
self.state = 65
self.match(EasyXMLParser.ASSIGMENT)
self.state = 66
self.expression(0)
self.state = 67
self.match(EasyXMLParser.SEMICOLON)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Sum_assignmentContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def SUM_ASSIGMENT(self):
return self.getToken(EasyXMLParser.SUM_ASSIGMENT, 0)
def expression(self):
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def NUMBER_LITERAL(self):
return self.getToken(EasyXMLParser.NUMBER_LITERAL, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_sum_assignment
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitSum_assignment" ):
return visitor.visitSum_assignment(self)
else:
return visitor.visitChildren(self)
def sum_assignment(self):
localctx = EasyXMLParser.Sum_assignmentContext(self, self._ctx, self.state)
self.enterRule(localctx, 4, self.RULE_sum_assignment)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 69
self.match(EasyXMLParser.VARNAME)
self.state = 73
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==EasyXMLParser.OPEN_BRACKET:
self.state = 70
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 71
self.match(EasyXMLParser.NUMBER_LITERAL)
self.state = 72
self.match(EasyXMLParser.CLOSE_BRACKET)
self.state = 75
self.match(EasyXMLParser.SUM_ASSIGMENT)
self.state = 76
self.expression(0)
self.state = 77
self.match(EasyXMLParser.SEMICOLON)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class GetContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.VARNAME)
else:
return self.getToken(EasyXMLParser.VARNAME, i)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def get(self):
return self.getTypedRuleContext(EasyXMLParser.GetContext,0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def params(self):
return self.getTypedRuleContext(EasyXMLParser.ParamsContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_get
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitGet" ):
return visitor.visitGet(self)
else:
return visitor.visitChildren(self)
def get(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = EasyXMLParser.GetContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 6
self.enterRecursionRule(localctx, 6, self.RULE_get, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 80
self.match(EasyXMLParser.VARNAME)
self.state = 81
self.match(EasyXMLParser.COLON)
self.state = 82
self.match(EasyXMLParser.VARNAME)
self._ctx.stop = self._input.LT(-1)
self.state = 94
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 92
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,5,self._ctx)
if la_ == 1:
localctx = EasyXMLParser.GetContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_get)
self.state = 84
if not self.precpred(self._ctx, 3):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 3)")
self.state = 85
self.match(EasyXMLParser.SEMICOLON)
pass
elif la_ == 2:
localctx = EasyXMLParser.GetContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_get)
self.state = 86
if not self.precpred(self._ctx, 2):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 2)")
self.state = 87
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 89
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 88
self.params()
self.state = 91
self.match(EasyXMLParser.CLOSE_BRACKET)
pass
self.state = 96
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,6,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Get_array_elementContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.VARNAME)
else:
return self.getToken(EasyXMLParser.VARNAME, i)
def OPEN_SQUAR_EBRACKET(self):
return self.getToken(EasyXMLParser.OPEN_SQUAR_EBRACKET, 0)
def CLOSE_SQUARE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_SQUARE_BRACKET, 0)
def NUMBER_LITERAL(self):
return self.getToken(EasyXMLParser.NUMBER_LITERAL, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_get_array_element
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitGet_array_element" ):
return visitor.visitGet_array_element(self)
else:
return visitor.visitChildren(self)
def get_array_element(self):
localctx = EasyXMLParser.Get_array_elementContext(self, self._ctx, self.state)
self.enterRule(localctx, 8, self.RULE_get_array_element)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 97
self.match(EasyXMLParser.VARNAME)
self.state = 98
self.match(EasyXMLParser.OPEN_SQUAR_EBRACKET)
self.state = 99
_la = self._input.LA(1)
if not(_la==EasyXMLParser.VARNAME or _la==EasyXMLParser.NUMBER_LITERAL):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 100
self.match(EasyXMLParser.CLOSE_SQUARE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_callContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def params(self):
return self.getTypedRuleContext(EasyXMLParser.ParamsContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_func_call
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitFunc_call" ):
return visitor.visitFunc_call(self)
else:
return visitor.visitChildren(self)
def func_call(self):
localctx = EasyXMLParser.Func_callContext(self, self._ctx, self.state)
self.enterRule(localctx, 10, self.RULE_func_call)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 102
self.match(EasyXMLParser.VARNAME)
self.state = 103
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 105
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 104
self.params()
self.state = 107
self.match(EasyXMLParser.CLOSE_BRACKET)
self.state = 108
self.match(EasyXMLParser.SEMICOLON)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class If_statementContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def if_block(self):
return self.getTypedRuleContext(EasyXMLParser.If_blockContext,0)
def elif_block(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.Elif_blockContext)
else:
return self.getTypedRuleContext(EasyXMLParser.Elif_blockContext,i)
def else_block(self):
return self.getTypedRuleContext(EasyXMLParser.Else_blockContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_if_statement
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitIf_statement" ):
return visitor.visitIf_statement(self)
else:
return visitor.visitChildren(self)
def if_statement(self):
localctx = EasyXMLParser.If_statementContext(self, self._ctx, self.state)
self.enterRule(localctx, 12, self.RULE_if_statement)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 110
self.if_block()
self.state = 114
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==EasyXMLParser.ELIF:
self.state = 111
self.elif_block()
self.state = 116
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 118
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==EasyXMLParser.ELSE:
self.state = 117
self.else_block()
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class If_blockContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def IF(self):
return self.getToken(EasyXMLParser.IF, 0)
def condition(self):
return self.getTypedRuleContext(EasyXMLParser.ConditionContext,0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_if_block
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitIf_block" ):
return visitor.visitIf_block(self)
else:
return visitor.visitChildren(self)
def if_block(self):
localctx = EasyXMLParser.If_blockContext(self, self._ctx, self.state)
self.enterRule(localctx, 14, self.RULE_if_block)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 120
self.match(EasyXMLParser.IF)
self.state = 121
self.condition()
self.state = 122
self.match(EasyXMLParser.COLON)
self.state = 123
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 127
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 124
self.operation()
self.state = 129
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 130
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Elif_blockContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ELIF(self):
return self.getToken(EasyXMLParser.ELIF, 0)
def condition(self):
return self.getTypedRuleContext(EasyXMLParser.ConditionContext,0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_elif_block
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitElif_block" ):
return visitor.visitElif_block(self)
else:
return visitor.visitChildren(self)
def elif_block(self):
localctx = EasyXMLParser.Elif_blockContext(self, self._ctx, self.state)
self.enterRule(localctx, 16, self.RULE_elif_block)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 132
self.match(EasyXMLParser.ELIF)
self.state = 133
self.condition()
self.state = 134
self.match(EasyXMLParser.COLON)
self.state = 135
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 139
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 136
self.operation()
self.state = 141
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 142
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Else_blockContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def ELSE(self):
return self.getToken(EasyXMLParser.ELSE, 0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_else_block
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitElse_block" ):
return visitor.visitElse_block(self)
else:
return visitor.visitChildren(self)
def else_block(self):
localctx = EasyXMLParser.Else_blockContext(self, self._ctx, self.state)
self.enterRule(localctx, 18, self.RULE_else_block)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 144
self.match(EasyXMLParser.ELSE)
self.state = 145
self.match(EasyXMLParser.COLON)
self.state = 146
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 150
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 147
self.operation()
self.state = 152
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 153
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class For_statementContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def FOR(self):
return self.getToken(EasyXMLParser.FOR, 0)
def range_statement(self):
return self.getTypedRuleContext(EasyXMLParser.Range_statementContext,0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_for_statement
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitFor_statement" ):
return visitor.visitFor_statement(self)
else:
return visitor.visitChildren(self)
def for_statement(self):
localctx = EasyXMLParser.For_statementContext(self, self._ctx, self.state)
self.enterRule(localctx, 20, self.RULE_for_statement)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 155
self.match(EasyXMLParser.FOR)
self.state = 156
self.range_statement()
self.state = 157
self.match(EasyXMLParser.COLON)
self.state = 158
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 162
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 159
self.operation()
self.state = 164
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 165
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class While_statementContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def WHILE(self):
return self.getToken(EasyXMLParser.WHILE, 0)
def condition(self):
return self.getTypedRuleContext(EasyXMLParser.ConditionContext,0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_while_statement
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitWhile_statement" ):
return visitor.visitWhile_statement(self)
else:
return visitor.visitChildren(self)
def while_statement(self):
localctx = EasyXMLParser.While_statementContext(self, self._ctx, self.state)
self.enterRule(localctx, 22, self.RULE_while_statement)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 167
self.match(EasyXMLParser.WHILE)
self.state = 168
self.condition()
self.state = 169
self.match(EasyXMLParser.COLON)
self.state = 170
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 174
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 171
self.operation()
self.state = 176
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 177
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Func_initContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def COLON(self):
return self.getToken(EasyXMLParser.COLON, 0)
def OPEN_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_FIGURE_BRACKET, 0)
def RETURN(self):
return self.getToken(EasyXMLParser.RETURN, 0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def CLOSE_FIGURE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_FIGURE_BRACKET, 0)
def TYPE(self):
return self.getToken(EasyXMLParser.TYPE, 0)
def ARRAY_TYPE(self):
return self.getToken(EasyXMLParser.ARRAY_TYPE, 0)
def params(self):
return self.getTypedRuleContext(EasyXMLParser.ParamsContext,0)
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def expression(self):
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_func_init
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitFunc_init" ):
return visitor.visitFunc_init(self)
else:
return visitor.visitChildren(self)
def func_init(self):
localctx = EasyXMLParser.Func_initContext(self, self._ctx, self.state)
self.enterRule(localctx, 24, self.RULE_func_init)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 179
_la = self._input.LA(1)
if not(_la==EasyXMLParser.ARRAY_TYPE or _la==EasyXMLParser.TYPE):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 180
self.match(EasyXMLParser.VARNAME)
self.state = 182
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 181
self.params()
self.state = 184
self.match(EasyXMLParser.COLON)
self.state = 185
self.match(EasyXMLParser.OPEN_FIGURE_BRACKET)
self.state = 189
self._errHandler.sync(self)
_la = self._input.LA(1)
while (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 186
self.operation()
self.state = 191
self._errHandler.sync(self)
_la = self._input.LA(1)
self.state = 192
self.match(EasyXMLParser.RETURN)
self.state = 194
self._errHandler.sync(self)
_la = self._input.LA(1)
if (((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0):
self.state = 193
self.expression(0)
self.state = 196
self.match(EasyXMLParser.SEMICOLON)
self.state = 197
self.match(EasyXMLParser.CLOSE_FIGURE_BRACKET)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Type_castContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def TYPE(self):
return self.getToken(EasyXMLParser.TYPE, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_type_cast
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitType_cast" ):
return visitor.visitType_cast(self)
else:
return visitor.visitChildren(self)
def type_cast(self):
localctx = EasyXMLParser.Type_castContext(self, self._ctx, self.state)
self.enterRule(localctx, 26, self.RULE_type_cast)
try:
self.enterOuterAlt(localctx, 1)
self.state = 199
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 200
self.match(EasyXMLParser.TYPE)
self.state = 201
self.match(EasyXMLParser.CLOSE_BRACKET)
self.state = 202
self.match(EasyXMLParser.VARNAME)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class Range_statementContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.VARNAME)
else:
return self.getToken(EasyXMLParser.VARNAME, i)
def IN(self):
return self.getToken(EasyXMLParser.IN, 0)
def TYPE(self):
return self.getToken(EasyXMLParser.TYPE, 0)
def ARRAY_TYPE(self):
return self.getToken(EasyXMLParser.ARRAY_TYPE, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_range_statement
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitRange_statement" ):
return visitor.visitRange_statement(self)
else:
return visitor.visitChildren(self)
def range_statement(self):
localctx = EasyXMLParser.Range_statementContext(self, self._ctx, self.state)
self.enterRule(localctx, 28, self.RULE_range_statement)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 204
_la = self._input.LA(1)
if not(_la==EasyXMLParser.ARRAY_TYPE or _la==EasyXMLParser.TYPE):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 205
self.match(EasyXMLParser.VARNAME)
self.state = 206
self.match(EasyXMLParser.IN)
self.state = 207
self.match(EasyXMLParser.VARNAME)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ConditionContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expression(self):
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,0)
def NOT(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.NOT)
else:
return self.getToken(EasyXMLParser.NOT, i)
def ANDOR(self, i:int=None):
if i is None:
return self.getTokens(EasyXMLParser.ANDOR)
else:
return self.getToken(EasyXMLParser.ANDOR, i)
def condition(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.ConditionContext)
else:
return self.getTypedRuleContext(EasyXMLParser.ConditionContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_condition
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitCondition" ):
return visitor.visitCondition(self)
else:
return visitor.visitChildren(self)
def condition(self):
localctx = EasyXMLParser.ConditionContext(self, self._ctx, self.state)
self.enterRule(localctx, 30, self.RULE_condition)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 210
self._errHandler.sync(self)
_la = self._input.LA(1)
if _la==EasyXMLParser.NOT:
self.state = 209
self.match(EasyXMLParser.NOT)
self.state = 212
self.expression(0)
self.state = 220
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,20,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
self.state = 213
self.match(EasyXMLParser.ANDOR)
self.state = 215
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,19,self._ctx)
if la_ == 1:
self.state = 214
self.match(EasyXMLParser.NOT)
self.state = 217
self.condition()
self.state = 222
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,20,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ParamsContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def expression(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.ExpressionContext)
else:
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,i)
def param(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.ParamContext)
else:
return self.getTypedRuleContext(EasyXMLParser.ParamContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_params
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitParams" ):
return visitor.visitParams(self)
else:
return visitor.visitChildren(self)
def params(self):
localctx = EasyXMLParser.ParamsContext(self, self._ctx, self.state)
self.enterRule(localctx, 32, self.RULE_params)
self._la = 0 # Token type
try:
self.state = 239
self._errHandler.sync(self)
token = self._input.LA(1)
if token in [EasyXMLParser.VARNAME, EasyXMLParser.NUMBER_LITERAL, EasyXMLParser.STRING_LITERAL, EasyXMLParser.OPEN_BRACKET]:
self.enterOuterAlt(localctx, 1)
self.state = 223
self.expression(0)
self.state = 228
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==EasyXMLParser.T__0:
self.state = 224
self.match(EasyXMLParser.T__0)
self.state = 225
self.expression(0)
self.state = 230
self._errHandler.sync(self)
_la = self._input.LA(1)
pass
elif token in [EasyXMLParser.ARRAY_TYPE, EasyXMLParser.TYPE]:
self.enterOuterAlt(localctx, 2)
self.state = 231
self.param()
self.state = 236
self._errHandler.sync(self)
_la = self._input.LA(1)
while _la==EasyXMLParser.T__0:
self.state = 232
self.match(EasyXMLParser.T__0)
self.state = 233
self.param()
self.state = 238
self._errHandler.sync(self)
_la = self._input.LA(1)
pass
else:
raise NoViableAltException(self)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ParamContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def TYPE(self):
return self.getToken(EasyXMLParser.TYPE, 0)
def ARRAY_TYPE(self):
return self.getToken(EasyXMLParser.ARRAY_TYPE, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_param
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitParam" ):
return visitor.visitParam(self)
else:
return visitor.visitChildren(self)
def param(self):
localctx = EasyXMLParser.ParamContext(self, self._ctx, self.state)
self.enterRule(localctx, 34, self.RULE_param)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 241
_la = self._input.LA(1)
if not(_la==EasyXMLParser.ARRAY_TYPE or _la==EasyXMLParser.TYPE):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
self.state = 242
self.match(EasyXMLParser.VARNAME)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class ExpressionContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def OPEN_BRACKET(self):
return self.getToken(EasyXMLParser.OPEN_BRACKET, 0)
def expression(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.ExpressionContext)
else:
return self.getTypedRuleContext(EasyXMLParser.ExpressionContext,i)
def CLOSE_BRACKET(self):
return self.getToken(EasyXMLParser.CLOSE_BRACKET, 0)
def get_operation(self):
return self.getTypedRuleContext(EasyXMLParser.Get_operationContext,0)
def type_cast(self):
return self.getTypedRuleContext(EasyXMLParser.Type_castContext,0)
def NUMBER_LITERAL(self):
return self.getToken(EasyXMLParser.NUMBER_LITERAL, 0)
def STRING_LITERAL(self):
return self.getToken(EasyXMLParser.STRING_LITERAL, 0)
def VARNAME(self):
return self.getToken(EasyXMLParser.VARNAME, 0)
def ACTION_OPERATOR(self):
return self.getToken(EasyXMLParser.ACTION_OPERATOR, 0)
def BOOL_OPERATOR(self):
return self.getToken(EasyXMLParser.BOOL_OPERATOR, 0)
def SEMICOLON(self):
return self.getToken(EasyXMLParser.SEMICOLON, 0)
def getRuleIndex(self):
return EasyXMLParser.RULE_expression
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitExpression" ):
return visitor.visitExpression(self)
else:
return visitor.visitChildren(self)
def expression(self, _p:int=0):
_parentctx = self._ctx
_parentState = self.state
localctx = EasyXMLParser.ExpressionContext(self, self._ctx, _parentState)
_prevctx = localctx
_startState = 36
self.enterRecursionRule(localctx, 36, self.RULE_expression, _p)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 252
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,24,self._ctx)
if la_ == 1:
self.state = 245
self.match(EasyXMLParser.OPEN_BRACKET)
self.state = 246
self.expression(0)
self.state = 247
self.match(EasyXMLParser.CLOSE_BRACKET)
pass
elif la_ == 2:
self.state = 249
self.get_operation()
pass
elif la_ == 3:
self.state = 250
self.type_cast()
pass
elif la_ == 4:
self.state = 251
_la = self._input.LA(1)
if not((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.NUMBER_LITERAL) | (1 << EasyXMLParser.STRING_LITERAL))) != 0)):
self._errHandler.recoverInline(self)
else:
self._errHandler.reportMatch(self)
self.consume()
pass
self._ctx.stop = self._input.LT(-1)
self.state = 264
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,26,self._ctx)
while _alt!=2 and _alt!=ATN.INVALID_ALT_NUMBER:
if _alt==1:
if self._parseListeners is not None:
self.triggerExitRuleEvent()
_prevctx = localctx
self.state = 262
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,25,self._ctx)
if la_ == 1:
localctx = EasyXMLParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 254
if not self.precpred(self._ctx, 5):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 5)")
self.state = 255
self.match(EasyXMLParser.ACTION_OPERATOR)
self.state = 256
self.expression(6)
pass
elif la_ == 2:
localctx = EasyXMLParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 257
if not self.precpred(self._ctx, 4):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 4)")
self.state = 258
self.match(EasyXMLParser.BOOL_OPERATOR)
self.state = 259
self.expression(5)
pass
elif la_ == 3:
localctx = EasyXMLParser.ExpressionContext(self, _parentctx, _parentState)
self.pushNewRecursionContext(localctx, _startState, self.RULE_expression)
self.state = 260
if not self.precpred(self._ctx, 7):
from antlr4.error.Errors import FailedPredicateException
raise FailedPredicateException(self, "self.precpred(self._ctx, 7)")
self.state = 261
self.match(EasyXMLParser.SEMICOLON)
pass
self.state = 266
self._errHandler.sync(self)
_alt = self._interp.adaptivePredict(self._input,26,self._ctx)
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.unrollRecursionContexts(_parentctx)
return localctx
class Get_operationContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def get(self):
return self.getTypedRuleContext(EasyXMLParser.GetContext,0)
def func_call(self):
return self.getTypedRuleContext(EasyXMLParser.Func_callContext,0)
def get_array_element(self):
return self.getTypedRuleContext(EasyXMLParser.Get_array_elementContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_get_operation
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitGet_operation" ):
return visitor.visitGet_operation(self)
else:
return visitor.visitChildren(self)
def get_operation(self):
localctx = EasyXMLParser.Get_operationContext(self, self._ctx, self.state)
self.enterRule(localctx, 38, self.RULE_get_operation)
try:
self.state = 270
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,27,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 267
self.get(0)
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 268
self.func_call()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 269
self.get_array_element()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class OperationContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def get_operation(self):
return self.getTypedRuleContext(EasyXMLParser.Get_operationContext,0)
def type_cast(self):
return self.getTypedRuleContext(EasyXMLParser.Type_castContext,0)
def var_init(self):
return self.getTypedRuleContext(EasyXMLParser.Var_initContext,0)
def assignment(self):
return self.getTypedRuleContext(EasyXMLParser.AssignmentContext,0)
def sum_assignment(self):
return self.getTypedRuleContext(EasyXMLParser.Sum_assignmentContext,0)
def if_statement(self):
return self.getTypedRuleContext(EasyXMLParser.If_statementContext,0)
def for_statement(self):
return self.getTypedRuleContext(EasyXMLParser.For_statementContext,0)
def while_statement(self):
return self.getTypedRuleContext(EasyXMLParser.While_statementContext,0)
def getRuleIndex(self):
return EasyXMLParser.RULE_operation
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitOperation" ):
return visitor.visitOperation(self)
else:
return visitor.visitChildren(self)
def operation(self):
localctx = EasyXMLParser.OperationContext(self, self._ctx, self.state)
self.enterRule(localctx, 40, self.RULE_operation)
try:
self.state = 280
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,28,self._ctx)
if la_ == 1:
self.enterOuterAlt(localctx, 1)
self.state = 272
self.get_operation()
pass
elif la_ == 2:
self.enterOuterAlt(localctx, 2)
self.state = 273
self.type_cast()
pass
elif la_ == 3:
self.enterOuterAlt(localctx, 3)
self.state = 274
self.var_init()
pass
elif la_ == 4:
self.enterOuterAlt(localctx, 4)
self.state = 275
self.assignment()
pass
elif la_ == 5:
self.enterOuterAlt(localctx, 5)
self.state = 276
self.sum_assignment()
pass
elif la_ == 6:
self.enterOuterAlt(localctx, 6)
self.state = 277
self.if_statement()
pass
elif la_ == 7:
self.enterOuterAlt(localctx, 7)
self.state = 278
self.for_statement()
pass
elif la_ == 8:
self.enterOuterAlt(localctx, 8)
self.state = 279
self.while_statement()
pass
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
class XmlContext(ParserRuleContext):
__slots__ = 'parser'
def __init__(self, parser, parent:ParserRuleContext=None, invokingState:int=-1):
super().__init__(parent, invokingState)
self.parser = parser
def operation(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.OperationContext)
else:
return self.getTypedRuleContext(EasyXMLParser.OperationContext,i)
def func_init(self, i:int=None):
if i is None:
return self.getTypedRuleContexts(EasyXMLParser.Func_initContext)
else:
return self.getTypedRuleContext(EasyXMLParser.Func_initContext,i)
def getRuleIndex(self):
return EasyXMLParser.RULE_xml
def accept(self, visitor:ParseTreeVisitor):
if hasattr( visitor, "visitXml" ):
return visitor.visitXml(self)
else:
return visitor.visitChildren(self)
def xml(self):
localctx = EasyXMLParser.XmlContext(self, self._ctx, self.state)
self.enterRule(localctx, 42, self.RULE_xml)
self._la = 0 # Token type
try:
self.enterOuterAlt(localctx, 1)
self.state = 284
self._errHandler.sync(self)
_la = self._input.LA(1)
while True:
self.state = 284
self._errHandler.sync(self)
la_ = self._interp.adaptivePredict(self._input,29,self._ctx)
if la_ == 1:
self.state = 282
self.operation()
pass
elif la_ == 2:
self.state = 283
self.func_init()
pass
self.state = 286
self._errHandler.sync(self)
_la = self._input.LA(1)
if not ((((_la) & ~0x3f) == 0 and ((1 << _la) & ((1 << EasyXMLParser.ARRAY_TYPE) | (1 << EasyXMLParser.TYPE) | (1 << EasyXMLParser.IF) | (1 << EasyXMLParser.FOR) | (1 << EasyXMLParser.WHILE) | (1 << EasyXMLParser.VARNAME) | (1 << EasyXMLParser.OPEN_BRACKET))) != 0)):
break
except RecognitionException as re:
localctx.exception = re
self._errHandler.reportError(self, re)
self._errHandler.recover(self, re)
finally:
self.exitRule()
return localctx
def sempred(self, localctx:RuleContext, ruleIndex:int, predIndex:int):
if self._predicates == None:
self._predicates = dict()
self._predicates[3] = self.get_sempred
self._predicates[18] = self.expression_sempred
pred = self._predicates.get(ruleIndex, None)
if pred is None:
raise Exception("No predicate with index:" + str(ruleIndex))
else:
return pred(localctx, predIndex)
def get_sempred(self, localctx:GetContext, predIndex:int):
if predIndex == 0:
return self.precpred(self._ctx, 3)
if predIndex == 1:
return self.precpred(self._ctx, 2)
def expression_sempred(self, localctx:ExpressionContext, predIndex:int):
if predIndex == 2:
return self.precpred(self._ctx, 5)
if predIndex == 3:
return self.precpred(self._ctx, 4)
if predIndex == 4:
return self.precpred(self._ctx, 7)
<file_sep>from . import Node
class NodeParams(Node.Node):
def __init__(self, line: int = 0, column: int = 0):
super().__init__()
self.line = line
self.column = column
<file_sep>from . import Node
class NodeWhileStatement(Node.Node):
def __init__(self, condition=None, line: int = 0, column: int = 0):
super().__init__()
self.local_vars = {}
self.condition = condition
self.line = line
self.column = column
<file_sep>from generated.EasyXMLVisitor import EasyXMLVisitor
from generated.EasyXMLParser import EasyXMLParser
from node import Node, NodeAssigment, NodeCondition, NodeElifBlock, NodeElseBlock, NodeExpression, NodeForStatement, \
NodeFuncCall, NodeFuncInit, NodeGet, NodeGetArrayElement, NodeIfBlock, NodeIfStatement, NodeParams, \
NodeRangeStatement, NodeSumAssigment, NodeTypeCast, NodeVarInit, NodeWhileStatement
class MyVisitor(EasyXMLVisitor):
def __init__(self):
super(MyVisitor, self).__init__()
self.root = Node.Node()
# Visit a parse tree produced by EasyXMLParser#var_init.
def visitVar_init(self, ctx: EasyXMLParser.Var_initContext):
new_flag = False
if ctx.NEW() is not None:
new_flag = True
var_type = ''
if ctx.TYPE() is not None and len(ctx.TYPE()) == 2:
# if ctx.TYPE()[0].getText() != ctx.TYPE()[1].getText():
# custom_exception(
# ctx.TYPE()[0].getText() + ' != ' + ctx.TYPE()[1].getText(),
# ctx.start.line,
# ctx.start.column,
# Exceptions.TYPE_ERROR
# )
# else:
var_type = ctx.TYPE()[0].getText()
else:
if ctx.TYPE() is not None and type(ctx.TYPE()) != list:
var_type = ctx.TYPE().getText()
elif type(ctx.TYPE()) == list and len(ctx.TYPE()) != 0:
var_type = ctx.TYPE()[0].getText()
elif ctx.ARRAY_TYPE() is not None and type(ctx.ARRAY_TYPE()) != list:
var_type = ctx.ARRAY_TYPE().getText()
else:
var_type = ctx.ARRAY_TYPE()[0].getText()
if ctx.expression() is None:
expression = NodeExpression.NodeExpression()
else:
expression = self.visitExpression(ctx.expression())
if ctx.assignment() is not None:
assignment = self.visitAssignment(ctx.assignment())
var_name = assignment.var_name
expression = assignment.children[0]
else:
var_name = ctx.VARNAME().getText()
var_init_node = NodeVarInit.NodeVarInit(
var_name,
var_type,
new_flag,
line=ctx.start.line,
column=ctx.start.column
)
var_init_node.children.append(expression)
return var_init_node
# Visit a parse tree produced by EasyXMLParser#assignment.
def visitAssignment(self, ctx: EasyXMLParser.AssignmentContext):
var_name = ctx.VARNAME().getText()
expression = self.visitExpression(ctx.expression())
index = ctx.NUMBER_LITERAL().getText() if ctx.NUMBER_LITERAL() is not None else 0
assignment_node = NodeAssigment.NodeAssigment(
var_name,
index,
line=ctx.start.line,
column=ctx.start.column
)
assignment_node.children.append(expression)
return assignment_node
# Visit a parse tree produced by EasyXMLParser#sum_assignment.
def visitSum_assignment(self, ctx: EasyXMLParser.Sum_assignmentContext):
var_name = ctx.VARNAME().getText()
expression = self.visitExpression(ctx.expression())
index = ctx.NUMBER_LITERAL().getText() if ctx.NUMBER_LITERAL() is not None else 0
sum_assignment_node = NodeSumAssigment.NodeSumAssigment(
var_name,
index,
line=ctx.start.line,
column=ctx.start.column
)
sum_assignment_node.children.append(expression)
return sum_assignment_node
# Visit a parse tree produced by EasyXMLParser#get.
def visitGet(self, ctx: EasyXMLParser.GetContext, parent_node=None):
if parent_node is None:
parent_node = self.root
get_node = NodeGet.NodeGet(
line=ctx.start.line,
column=ctx.start.column
)
if ctx.get() is not None:
get_node = self.visitGet(ctx.get(), parent_node)
if ctx.params() is not None:
params = self.visitParams(ctx.params())
get_node.children.append(params)
else:
get_node.var_name = ctx.VARNAME()[0].getText()
get_node.attribute_name = ctx.VARNAME()[1].getText()
return get_node
# Visit a parse tree produced by EasyXMLParser#get_array_element.
def visitGet_array_element(self, ctx: EasyXMLParser.Get_array_elementContext):
get_array_element_node = NodeGetArrayElement.NodeGetArrayElement(
ctx.VARNAME().getText(),
ctx.NUMBER_LITERAL().getText(),
line=ctx.start.line,
column=ctx.start.column
)
return get_array_element_node
# Visit a parse tree produced by EasyXMLParser#func_call.
def visitFunc_call(self, ctx: EasyXMLParser.Func_callContext):
params = NodeParams.NodeParams()
if ctx.params() is not None:
params = self.visitParams(ctx.params())
func_call_node = NodeFuncCall.NodeFuncCall(
ctx.VARNAME().getText(),
line=ctx.start.line,
column=ctx.start.column
)
func_call_node.children.append(params)
return func_call_node
# Visit a parse tree produced by EasyXMLParser#if_statement.
def visitIf_statement(self, ctx: EasyXMLParser.If_statementContext):
if_state = NodeIfStatement.NodeIfStatement(
self.visitIf_block(ctx.if_block()),
self.visitElse_if_block(ctx.elif_block()[0]) if len(ctx.elif_block()) != 0 else None,
self.visitElse_block(ctx.else_block()) if ctx.else_block() is not None else None
)
return if_state
# Visit a parse tree produced by EasyXMLParser#if_block.
def visitIf_block(self, ctx: EasyXMLParser.If_blockContext):
if_block = NodeIfBlock.NodeIfBlock(
self.visitCondition(ctx.condition()),
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
if_block.children.append(self.visitOperation(i, if_block))
while None in if_block.children:
if_block.children.remove(None)
return if_block
# Visit a parse tree produced by EasyXMLParser#else_if_block.
def visitElse_if_block(self, ctx: EasyXMLParser.Elif_blockContext):
print(type(ctx))
else_if_block = NodeElifBlock.NodeElifBlock(
self.visitCondition(ctx.condition()),
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
else_if_block.children.append(self.visitOperation(i, else_if_block))
while None in else_if_block.children:
else_if_block.children.remove(None)
return else_if_block
# Visit a parse tree produced by EasyXMLParser#else_block.
def visitElse_block(self, ctx: EasyXMLParser.Else_blockContext):
else_block = NodeElseBlock.NodeElseBlock(
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
else_block.children.append(self.visitOperation(i, else_block))
while None in else_block.children:
else_block.children.remove(None)
return else_block
# Visit a parse tree produced by EasyXMLParser#for_statement.
def visitFor_statement(self, ctx: EasyXMLParser.For_statementContext):
for_state = NodeForStatement.NodeForStatement(
self.visitRange_statement(ctx.range_statement()),
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
for_state.children.append(self.visitOperation(i, for_state))
while None in for_state.children:
for_state.children.remove(None)
return for_state
# Visit a parse tree produced by EasyXMLParser#while_statement.
def visitWhile_statement(self, ctx: EasyXMLParser.While_statementContext):
while_state = NodeWhileStatement.NodeWhileStatement(
self.visitCondition(ctx.condition()),
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
while_state.children.append(self.visitOperation(i, while_state))
while None in while_state.children:
while_state.children.remove(None)
return while_state
# Visit a parse tree produced by EasyXMLParser#func_init.
def visitFunc_init(self, ctx: EasyXMLParser.Func_initContext, parent_node=None):
if parent_node is None:
parent_node = self.root
func_init = NodeFuncInit.NodeFuncInit(
ctx.TYPE().getText() if ctx.TYPE() is not None else ctx.ARRAY_TYPE().getText(),
ctx.VARNAME().getText(),
self.visitParams(ctx.params()) if ctx.params() is not None else None,
line=ctx.start.line,
column=ctx.start.column
)
operations = ctx.operation()
for i in operations:
func_init.children.append(self.visitOperation(i, func_init))
while None in func_init.children:
func_init.children.remove(None)
func_init.return_statement = self.visitExpression(ctx.expression())
parent_node.children.append(func_init)
return func_init
# Visit a parse tree produced by EasyXMLParser#type_cast.
def visitType_cast(self, ctx: EasyXMLParser.Type_castContext):
type_cast_node = NodeTypeCast.NodeTypeCast(
ctx.VARNAME().getText(),
ctx.TYPE().getText(),
line=ctx.start.line,
column=ctx.start.column
)
return type_cast_node
# Visit a parse tree produced by EasyXMLParser#range_statement.
def visitRange_statement(self, ctx: EasyXMLParser.Range_statementContext):
range_node = NodeRangeStatement.NodeRangeStatement(
ctx.TYPE().getText() if ctx.TYPE() is not None else ctx.ARRAY_TYPE().getText(),
ctx.VARNAME()[0].getText(),
ctx.VARNAME()[1].getText(),
line=ctx.start.line,
column=ctx.start.column
)
return range_node
# Visit a parse tree produced by EasyXMLParser#condition.
def visitCondition(self, ctx: EasyXMLParser.ConditionContext):
if ctx.NOT() is not None and type(ctx.NOT()) != list:
is_not = bool(ctx.NOT().getText())
else:
is_not = bool(ctx.NOT()[0].getText()) if len(ctx.NOT()) == 1 else False
if ctx.ANDOR() is not None and type(ctx.ANDOR()) != list:
and_or = ctx.ANDOR().getText()
else:
and_or = ctx.ANDOR()[0].getText() if len(ctx.ANDOR()) == 1 else ''
condition = NodeCondition.NodeCondition(
is_not,
and_or,
line=ctx.start.line,
column=ctx.start.column
)
condition.children.append(self.visitExpression(ctx.expression()))
for i in ctx.condition():
condition.children.append(self.visitCondition(i))
return condition
# Visit a parse tree produced by EasyXMLParser#params.
def visitParams(self, ctx: EasyXMLParser.ParamsContext):
params = NodeParams.NodeParams(
line=ctx.start.line,
column=ctx.start.column
)
if ctx.expression() is not None and len(ctx.expression()) != 0:
expressions = ctx.expression()
if len(expressions) != 0:
for i in expressions:
params.children.append(self.visitExpression(i))
return params
else:
if len(ctx.param()) != 0:
for i in ctx.param():
params.children.append(self.visitParam(i))
return params
# Visit a parse tree produced by EasyXMLParser#param.
def visitParam(self, ctx: EasyXMLParser.ParamContext):
var_type = ctx.TYPE().getText() if ctx.TYPE() is not None else ctx.ARRAY_TYPE().getText()
var_name = ctx.VARNAME().getText()
return var_type, var_name
# Visit a parse tree produced by EasyXMLParser#expression.
def visitExpression(self, ctx: EasyXMLParser.ExpressionContext):
expression = NodeExpression.NodeExpression(
line=ctx.start.line,
column=ctx.start.column
)
if ctx.ACTION_OPERATOR() is not None:
expression.operator = ctx.ACTION_OPERATOR().getText()
elif ctx.BOOL_OPERATOR() is not None:
expression.operator = ctx.BOOL_OPERATOR().getText()
if expression.operator is not None:
expression.left_expression = self.visitExpression(ctx.expression()[0])
expression.right_expression = self.visitExpression(ctx.expression()[1])
return expression
if ctx.NUMBER_LITERAL() is not None:
expression.value = ctx.NUMBER_LITERAL().getText()
elif ctx.STRING_LITERAL() is not None:
expression.value = ctx.STRING_LITERAL().getText()
elif ctx.VARNAME() is not None:
expression.value = ctx.VARNAME().getText()
if expression.value is not None:
return expression
if ctx.get_operation() is not None:
expression.children.append(self.visitGet_operation(ctx.get_operation(), expression))
elif ctx.type_cast() is not None:
expression.children.append(self.visitType_cast(ctx.type_cast()))
while None in expression.children:
expression.children.remove(None)
if len(expression.children) != 0:
return expression
if ctx.expression() is not None:
expression = self.visitExpression(ctx.expression())
return expression
# Visit a parse tree produced by EasyXMLParser#get_operation.
def visitGet_operation(self, ctx: EasyXMLParser.Get_operationContext, parent_node=None):
if parent_node is None:
parent_node = self.root
if ctx.get() is not None:
parent_node.children.append(self.visitGet(ctx.get(), parent_node))
elif ctx.get_array_element() is not None:
parent_node.children.append(self.visitGet_array_element(ctx.get_array_element()))
elif ctx.func_call() is not None:
parent_node.children.append(self.visitFunc_call(ctx.func_call()))
# Visit a parse tree produced by EasyXMLParser#operation.
def visitOperation(self, ctx: EasyXMLParser.OperationContext, parent_node=None):
if parent_node is None:
parent_node = self.root
if ctx.get_operation() is not None:
self.visitGet_operation(ctx.get_operation(), parent_node)
elif ctx.type_cast() is not None:
parent_node.children.append(self.visitType_cast(ctx.type_cast()))
elif ctx.while_statement() is not None:
parent_node.children.append(self.visitWhile_statement(ctx.while_statement()))
elif ctx.for_statement() is not None:
parent_node.children.append(self.visitFor_statement(ctx.for_statement()))
elif ctx.assignment() is not None:
parent_node.children.append(self.visitAssignment(ctx.assignment()))
elif ctx.sum_assignment() is not None:
parent_node.children.append(self.visitSum_assignment(ctx.sum_assignment()))
elif ctx.var_init() is not None:
parent_node.children.append(self.visitVar_init(ctx.var_init()))
elif ctx.if_statement() is not None:
parent_node.children.append(self.visitIf_statement(ctx.if_statement()))
# Visit a parse tree produced by EasyXMLParser#xml.
def visitXml(self, ctx: EasyXMLParser.XmlContext):
return self.visitChildren(ctx)
<file_sep>from . import Node
class NodeSumAssigment(Node.Node):
def __init__(self, var_name: str = '', index: int = 0, line: int = 0, column: int = 0):
super().__init__()
self.var_name = var_name
self.index = index
self.line = line
self.column = column
<file_sep># Generated from EasyXML.g4 by ANTLR 4.9.1
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\64")
buf.write("\u0139\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write("\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r")
buf.write("\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22\4\23")
buf.write("\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30")
buf.write("\4\31\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36")
buf.write("\t\36\4\37\t\37\4 \t \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%")
buf.write("\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t+\4,\t,\4-\t-\4.")
buf.write("\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\3\2")
buf.write("\3\2\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\5\4t\n\4")
buf.write("\3\5\3\5\3\5\3\5\5\5z\n\5\3\6\3\6\3\6\3\6\3\6\3\6\5\6")
buf.write("\u0082\n\6\3\7\3\7\5\7\u0086\n\7\3\b\3\b\3\b\3\b\3\b\3")
buf.write("\b\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3\n\3\n")
buf.write("\3\n\3\n\3\13\3\13\3\13\3\13\3\13\3\13\3\13\3\f\3\f\3")
buf.write("\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3\16\3\16\3\16")
buf.write("\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\21\3\21\3\21")
buf.write("\3\21\3\22\3\22\3\22\3\22\3\22\3\22\3\23\3\23\3\23\3\24")
buf.write("\3\24\3\24\3\24\3\25\3\25\3\25\3\26\3\26\3\26\3\26\3\27")
buf.write("\3\27\3\27\3\27\3\27\3\27\3\27\3\30\6\30\u00db\n\30\r")
buf.write("\30\16\30\u00dc\3\31\6\31\u00e0\n\31\r\31\16\31\u00e1")
buf.write("\3\31\3\31\6\31\u00e6\n\31\r\31\16\31\u00e7\5\31\u00ea")
buf.write("\n\31\3\32\3\32\7\32\u00ee\n\32\f\32\16\32\u00f1\13\32")
buf.write("\3\32\3\32\3\33\3\33\3\33\3\33\3\34\3\34\3\35\3\35\3\36")
buf.write("\3\36\3\37\3\37\3 \3 \3!\3!\3\"\3\"\3#\3#\3$\3$\3%\3%")
buf.write("\3%\3&\3&\3\'\3\'\3(\3(\3)\3)\3*\3*\3*\3+\3+\3+\3,\3,")
buf.write("\3,\3-\3-\3-\3.\3.\3/\3/\3\60\3\60\3\61\3\61\3\62\3\62")
buf.write("\3\63\3\63\7\63\u012e\n\63\f\63\16\63\u0131\13\63\3\63")
buf.write("\5\63\u0134\n\63\3\63\3\63\3\63\3\63\3\u00ef\2\64\3\3")
buf.write("\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16")
buf.write("\33\17\35\20\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61")
buf.write("\32\63\33\65\34\67\359\36;\37= ?!A\"C#E$G%I&K\'M(O)Q*")
buf.write("S+U,W-Y.[/]\60_\61a\62c\63e\64\3\2\7\5\2C\\aac|\3\2\62")
buf.write(";\5\2\13\f\17\17\"\"\4\2$$))\4\2\f\f\17\17\2\u014d\2\3")
buf.write("\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2")
buf.write("\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2")
buf.write("\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2")
buf.write("\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3")
buf.write("\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2")
buf.write("/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67")
buf.write("\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2")
buf.write("A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2")
buf.write("\2K\3\2\2\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2")
buf.write("\2\2U\3\2\2\2\2W\3\2\2\2\2Y\3\2\2\2\2[\3\2\2\2\2]\3\2")
buf.write("\2\2\2_\3\2\2\2\2a\3\2\2\2\2c\3\2\2\2\2e\3\2\2\2\3g\3")
buf.write("\2\2\2\5i\3\2\2\2\7s\3\2\2\2\ty\3\2\2\2\13\u0081\3\2\2")
buf.write("\2\r\u0085\3\2\2\2\17\u0087\3\2\2\2\21\u008d\3\2\2\2\23")
buf.write("\u0092\3\2\2\2\25\u009c\3\2\2\2\27\u00a3\3\2\2\2\31\u00a7")
buf.write("\3\2\2\2\33\u00ad\3\2\2\2\35\u00b2\3\2\2\2\37\u00b7\3")
buf.write("\2\2\2!\u00ba\3\2\2\2#\u00be\3\2\2\2%\u00c4\3\2\2\2\'")
buf.write("\u00c7\3\2\2\2)\u00cb\3\2\2\2+\u00ce\3\2\2\2-\u00d2\3")
buf.write("\2\2\2/\u00da\3\2\2\2\61\u00df\3\2\2\2\63\u00eb\3\2\2")
buf.write("\2\65\u00f4\3\2\2\2\67\u00f8\3\2\2\29\u00fa\3\2\2\2;\u00fc")
buf.write("\3\2\2\2=\u00fe\3\2\2\2?\u0100\3\2\2\2A\u0102\3\2\2\2")
buf.write("C\u0104\3\2\2\2E\u0106\3\2\2\2G\u0108\3\2\2\2I\u010a\3")
buf.write("\2\2\2K\u010d\3\2\2\2M\u010f\3\2\2\2O\u0111\3\2\2\2Q\u0113")
buf.write("\3\2\2\2S\u0115\3\2\2\2U\u0118\3\2\2\2W\u011b\3\2\2\2")
buf.write("Y\u011e\3\2\2\2[\u0121\3\2\2\2]\u0123\3\2\2\2_\u0125\3")
buf.write("\2\2\2a\u0127\3\2\2\2c\u0129\3\2\2\2e\u012b\3\2\2\2gh")
buf.write("\7.\2\2h\4\3\2\2\2ij\5\7\4\2jk\5;\36\2kl\5=\37\2l\6\3")
buf.write("\2\2\2mt\5\17\b\2nt\5\21\t\2ot\5\23\n\2pt\5\25\13\2qt")
buf.write("\5\27\f\2rt\5\31\r\2sm\3\2\2\2sn\3\2\2\2so\3\2\2\2sp\3")
buf.write("\2\2\2sq\3\2\2\2sr\3\2\2\2t\b\3\2\2\2uz\5[.\2vz\5]/\2")
buf.write("wz\5_\60\2xz\5a\61\2yu\3\2\2\2yv\3\2\2\2yw\3\2\2\2yx\3")
buf.write("\2\2\2z\n\3\2\2\2{\u0082\5O(\2|\u0082\5W,\2}\u0082\5Q")
buf.write(")\2~\u0082\5Y-\2\177\u0082\5S*\2\u0080\u0082\5U+\2\u0081")
buf.write("{\3\2\2\2\u0081|\3\2\2\2\u0081}\3\2\2\2\u0081~\3\2\2\2")
buf.write("\u0081\177\3\2\2\2\u0081\u0080\3\2\2\2\u0082\f\3\2\2\2")
buf.write("\u0083\u0086\5\'\24\2\u0084\u0086\5)\25\2\u0085\u0083")
buf.write("\3\2\2\2\u0085\u0084\3\2\2\2\u0086\16\3\2\2\2\u0087\u0088")
buf.write("\7v\2\2\u0088\u0089\7c\2\2\u0089\u008a\7d\2\2\u008a\u008b")
buf.write("\7n\2\2\u008b\u008c\7g\2\2\u008c\20\3\2\2\2\u008d\u008e")
buf.write("\7e\2\2\u008e\u008f\7g\2\2\u008f\u0090\7n\2\2\u0090\u0091")
buf.write("\7n\2\2\u0091\22\3\2\2\2\u0092\u0093\7c\2\2\u0093\u0094")
buf.write("\7v\2\2\u0094\u0095\7v\2\2\u0095\u0096\7t\2\2\u0096\u0097")
buf.write("\7k\2\2\u0097\u0098\7d\2\2\u0098\u0099\7w\2\2\u0099\u009a")
buf.write("\7v\2\2\u009a\u009b\7g\2\2\u009b\24\3\2\2\2\u009c\u009d")
buf.write("\7u\2\2\u009d\u009e\7v\2\2\u009e\u009f\7t\2\2\u009f\u00a0")
buf.write("\7k\2\2\u00a0\u00a1\7p\2\2\u00a1\u00a2\7i\2\2\u00a2\26")
buf.write("\3\2\2\2\u00a3\u00a4\7k\2\2\u00a4\u00a5\7p\2\2\u00a5\u00a6")
buf.write("\7v\2\2\u00a6\30\3\2\2\2\u00a7\u00a8\7h\2\2\u00a8\u00a9")
buf.write("\7n\2\2\u00a9\u00aa\7q\2\2\u00aa\u00ab\7c\2\2\u00ab\u00ac")
buf.write("\7v\2\2\u00ac\32\3\2\2\2\u00ad\u00ae\7g\2\2\u00ae\u00af")
buf.write("\7n\2\2\u00af\u00b0\7k\2\2\u00b0\u00b1\7h\2\2\u00b1\34")
buf.write("\3\2\2\2\u00b2\u00b3\7g\2\2\u00b3\u00b4\7n\2\2\u00b4\u00b5")
buf.write("\7u\2\2\u00b5\u00b6\7g\2\2\u00b6\36\3\2\2\2\u00b7\u00b8")
buf.write("\7k\2\2\u00b8\u00b9\7h\2\2\u00b9 \3\2\2\2\u00ba\u00bb")
buf.write("\7h\2\2\u00bb\u00bc\7q\2\2\u00bc\u00bd\7t\2\2\u00bd\"")
buf.write("\3\2\2\2\u00be\u00bf\7y\2\2\u00bf\u00c0\7j\2\2\u00c0\u00c1")
buf.write("\7k\2\2\u00c1\u00c2\7n\2\2\u00c2\u00c3\7g\2\2\u00c3$\3")
buf.write("\2\2\2\u00c4\u00c5\7k\2\2\u00c5\u00c6\7p\2\2\u00c6&\3")
buf.write("\2\2\2\u00c7\u00c8\7c\2\2\u00c8\u00c9\7p\2\2\u00c9\u00ca")
buf.write("\7f\2\2\u00ca(\3\2\2\2\u00cb\u00cc\7q\2\2\u00cc\u00cd")
buf.write("\7t\2\2\u00cd*\3\2\2\2\u00ce\u00cf\7p\2\2\u00cf\u00d0")
buf.write("\7g\2\2\u00d0\u00d1\7y\2\2\u00d1,\3\2\2\2\u00d2\u00d3")
buf.write("\7t\2\2\u00d3\u00d4\7g\2\2\u00d4\u00d5\7v\2\2\u00d5\u00d6")
buf.write("\7w\2\2\u00d6\u00d7\7t\2\2\u00d7\u00d8\7p\2\2\u00d8.\3")
buf.write("\2\2\2\u00d9\u00db\t\2\2\2\u00da\u00d9\3\2\2\2\u00db\u00dc")
buf.write("\3\2\2\2\u00dc\u00da\3\2\2\2\u00dc\u00dd\3\2\2\2\u00dd")
buf.write("\60\3\2\2\2\u00de\u00e0\t\3\2\2\u00df\u00de\3\2\2\2\u00e0")
buf.write("\u00e1\3\2\2\2\u00e1\u00df\3\2\2\2\u00e1\u00e2\3\2\2\2")
buf.write("\u00e2\u00e9\3\2\2\2\u00e3\u00e5\7\60\2\2\u00e4\u00e6")
buf.write("\t\3\2\2\u00e5\u00e4\3\2\2\2\u00e6\u00e7\3\2\2\2\u00e7")
buf.write("\u00e5\3\2\2\2\u00e7\u00e8\3\2\2\2\u00e8\u00ea\3\2\2\2")
buf.write("\u00e9\u00e3\3\2\2\2\u00e9\u00ea\3\2\2\2\u00ea\62\3\2")
buf.write("\2\2\u00eb\u00ef\5E#\2\u00ec\u00ee\13\2\2\2\u00ed\u00ec")
buf.write("\3\2\2\2\u00ee\u00f1\3\2\2\2\u00ef\u00f0\3\2\2\2\u00ef")
buf.write("\u00ed\3\2\2\2\u00f0\u00f2\3\2\2\2\u00f1\u00ef\3\2\2\2")
buf.write("\u00f2\u00f3\5E#\2\u00f3\64\3\2\2\2\u00f4\u00f5\t\4\2")
buf.write("\2\u00f5\u00f6\3\2\2\2\u00f6\u00f7\b\33\2\2\u00f7\66\3")
buf.write("\2\2\2\u00f8\u00f9\7*\2\2\u00f98\3\2\2\2\u00fa\u00fb\7")
buf.write("+\2\2\u00fb:\3\2\2\2\u00fc\u00fd\7]\2\2\u00fd<\3\2\2\2")
buf.write("\u00fe\u00ff\7_\2\2\u00ff>\3\2\2\2\u0100\u0101\7}\2\2")
buf.write("\u0101@\3\2\2\2\u0102\u0103\7\177\2\2\u0103B\3\2\2\2\u0104")
buf.write("\u0105\7=\2\2\u0105D\3\2\2\2\u0106\u0107\t\5\2\2\u0107")
buf.write("F\3\2\2\2\u0108\u0109\7?\2\2\u0109H\3\2\2\2\u010a\u010b")
buf.write("\7-\2\2\u010b\u010c\7?\2\2\u010cJ\3\2\2\2\u010d\u010e")
buf.write("\7\60\2\2\u010eL\3\2\2\2\u010f\u0110\7<\2\2\u0110N\3\2")
buf.write("\2\2\u0111\u0112\7@\2\2\u0112P\3\2\2\2\u0113\u0114\7>")
buf.write("\2\2\u0114R\3\2\2\2\u0115\u0116\7?\2\2\u0116\u0117\7?")
buf.write("\2\2\u0117T\3\2\2\2\u0118\u0119\7#\2\2\u0119\u011a\7?")
buf.write("\2\2\u011aV\3\2\2\2\u011b\u011c\7@\2\2\u011c\u011d\7?")
buf.write("\2\2\u011dX\3\2\2\2\u011e\u011f\7>\2\2\u011f\u0120\7?")
buf.write("\2\2\u0120Z\3\2\2\2\u0121\u0122\7-\2\2\u0122\\\3\2\2\2")
buf.write("\u0123\u0124\7/\2\2\u0124^\3\2\2\2\u0125\u0126\7,\2\2")
buf.write("\u0126`\3\2\2\2\u0127\u0128\7\61\2\2\u0128b\3\2\2\2\u0129")
buf.write("\u012a\7#\2\2\u012ad\3\2\2\2\u012b\u012f\7%\2\2\u012c")
buf.write("\u012e\n\6\2\2\u012d\u012c\3\2\2\2\u012e\u0131\3\2\2\2")
buf.write("\u012f\u012d\3\2\2\2\u012f\u0130\3\2\2\2\u0130\u0133\3")
buf.write("\2\2\2\u0131\u012f\3\2\2\2\u0132\u0134\7\17\2\2\u0133")
buf.write("\u0132\3\2\2\2\u0133\u0134\3\2\2\2\u0134\u0135\3\2\2\2")
buf.write("\u0135\u0136\7\f\2\2\u0136\u0137\3\2\2\2\u0137\u0138\b")
buf.write("\63\2\2\u0138f\3\2\2\2\16\2sy\u0081\u0085\u00dc\u00e1")
buf.write("\u00e7\u00e9\u00ef\u012f\u0133\3\b\2\2")
return buf.getvalue()
class EasyXMLLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
T__0 = 1
ARRAY_TYPE = 2
TYPE = 3
ACTION_OPERATOR = 4
BOOL_OPERATOR = 5
ANDOR = 6
TABLE = 7
CELL = 8
ATTRIBUTE = 9
STRING = 10
INT = 11
FLOAT = 12
ELIF = 13
ELSE = 14
IF = 15
FOR = 16
WHILE = 17
IN = 18
AND = 19
OR = 20
NEW = 21
RETURN = 22
VARNAME = 23
NUMBER_LITERAL = 24
STRING_LITERAL = 25
WHITESPACE = 26
OPEN_BRACKET = 27
CLOSE_BRACKET = 28
OPEN_SQUAR_EBRACKET = 29
CLOSE_SQUARE_BRACKET = 30
OPEN_FIGURE_BRACKET = 31
CLOSE_FIGURE_BRACKET = 32
SEMICOLON = 33
QOUTES = 34
ASSIGMENT = 35
SUM_ASSIGMENT = 36
DOT = 37
COLON = 38
MORE_THAN = 39
LESS_THAN = 40
EQUAL = 41
NOT_EQUAL = 42
MORE_EQUAL = 43
LESS_EQUAL = 44
PlUS = 45
MINUS = 46
MULTIPLICATION = 47
DIVISION = 48
NOT = 49
COMMENT = 50
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ "DEFAULT_MODE" ]
literalNames = [ "<INVALID>",
"','", "'table'", "'cell'", "'attribute'", "'string'", "'int'",
"'float'", "'elif'", "'else'", "'if'", "'for'", "'while'", "'in'",
"'and'", "'or'", "'new'", "'return'", "'('", "')'", "'['", "']'",
"'{'", "'}'", "';'", "'='", "'+='", "'.'", "':'", "'>'", "'<'",
"'=='", "'!='", "'>='", "'<='", "'+'", "'-'", "'*'", "'/'",
"'!'" ]
symbolicNames = [ "<INVALID>",
"ARRAY_TYPE", "TYPE", "ACTION_OPERATOR", "BOOL_OPERATOR", "ANDOR",
"TABLE", "CELL", "ATTRIBUTE", "STRING", "INT", "FLOAT", "ELIF",
"ELSE", "IF", "FOR", "WHILE", "IN", "AND", "OR", "NEW", "RETURN",
"VARNAME", "NUMBER_LITERAL", "STRING_LITERAL", "WHITESPACE",
"OPEN_BRACKET", "CLOSE_BRACKET", "OPEN_SQUAR_EBRACKET", "CLOSE_SQUARE_BRACKET",
"OPEN_FIGURE_BRACKET", "CLOSE_FIGURE_BRACKET", "SEMICOLON",
"QOUTES", "ASSIGMENT", "SUM_ASSIGMENT", "DOT", "COLON", "MORE_THAN",
"LESS_THAN", "EQUAL", "NOT_EQUAL", "MORE_EQUAL", "LESS_EQUAL",
"PlUS", "MINUS", "MULTIPLICATION", "DIVISION", "NOT", "COMMENT" ]
ruleNames = [ "T__0", "ARRAY_TYPE", "TYPE", "ACTION_OPERATOR", "BOOL_OPERATOR",
"ANDOR", "TABLE", "CELL", "ATTRIBUTE", "STRING", "INT",
"FLOAT", "ELIF", "ELSE", "IF", "FOR", "WHILE", "IN", "AND",
"OR", "NEW", "RETURN", "VARNAME", "NUMBER_LITERAL", "STRING_LITERAL",
"WHITESPACE", "OPEN_BRACKET", "CLOSE_BRACKET", "OPEN_SQUAR_EBRACKET",
"CLOSE_SQUARE_BRACKET", "OPEN_FIGURE_BRACKET", "CLOSE_FIGURE_BRACKET",
"SEMICOLON", "QOUTES", "ASSIGMENT", "SUM_ASSIGMENT", "DOT",
"COLON", "MORE_THAN", "LESS_THAN", "EQUAL", "NOT_EQUAL",
"MORE_EQUAL", "LESS_EQUAL", "PlUS", "MINUS", "MULTIPLICATION",
"DIVISION", "NOT", "COMMENT" ]
grammarFileName = "EasyXML.g4"
def __init__(self, input=None, output:TextIO = sys.stdout):
super().__init__(input, output)
self.checkVersion("4.9.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
<file_sep>from . import Node
class NodeIfStatement(Node.Node):
def __init__(self, if_block=None, elif_block=None, else_block=None):
super().__init__()
self.if_block = if_block
self.elif_block = elif_block
self.else_block = else_block
<file_sep>from . import Node
class NodeRangeStatement(Node.Node):
def __init__(self, var_type: str = '', iterator: str = '', collection: str = '', line: int = 0, column: int = 0):
super().__init__()
self.var_type = var_type
self.iterator = iterator
self.collection = collection
self.line = line
self.column = column
<file_sep>from . import Node
class NodeForStatement(Node.Node):
def __init__(self, range_statement=None, line: int = 0, column: int = 0):
super().__init__()
self.local_vars = {}
self.range_statement = range_statement
self.line = line
self.column = column
<file_sep>from . import Node
class NodeCondition(Node.Node):
def __init__(self, is_not: bool = False, and_or: str = '', line: int = 0, column: int = 0):
super().__init__()
self.is_not = is_not
self.and_or = and_or
self.column = column
self.line = line<file_sep>from . import Node
class NodeFuncCall(Node.Node):
def __init__(self, func_name: str = '', line: int = 0, column: int = 0):
super().__init__()
self.var_name = func_name
self.line = line
self.column = column<file_sep>from . import Node
class NodeVarInit(Node.Node):
def __init__(self, var_name: str = '', var_type: str = '', new_flag: bool = True, line: int = 0, column: int = 0):
super().__init__()
self.var_name = var_name
self.var_type = var_type
self.new_flag = new_flag
self.line = line
self.column = column
<file_sep>from . import Node
class NodeExpression(Node.Node):
def __init__(self, line: int = 0, column: int = 0):
super().__init__()
self.value = None
self.left_expression = None
self.right_expression = None
self.operator = None
self.line = line
self.column = column
<file_sep># EasyXML
Language for easy work with XML
# Author
<NAME>, group: 821703.
## Install ANTLR
### For Linux
``` bash
$ cd /usr/local/lib
$ sudo wget https://www.antlr.org/download/antlr-4.9.1-complete.jar
```
in the end of your bash config file (in Ubuntu it's .bashrc in your user folder) add next lines:
```
export CLASSPATH=".:/usr/local/lib/antlr-4.9.1-complete.jar:$CLASSPATH"
alias antlr4='java -jar /usr/local/lib/antlr-4.9.1-complete.jar'
alias grun='java org.antlr.v4.gui.TestRig'
```
### For Windows
1. Download [antlr4](https://www.antlr.org/download/antlr-4.9.1-complete.jar).
1. Add antlr4-complete.jar to CLASSPATH, either:
1. **Permanently**:
p= > Using System Properties dialog > Environment variables > Create or append to CLASSPATH variable
1. **Temporarily**, at command line:
```cmd
SET CLASSPATH=.;C:\Javalib\antlr4-complete.jar;%CLASSPATH%
```
1. Create batch commands for ANTLR Tool, TestRig in dir in PATH
* `antlr4.bat: java org.antlr.v4.Tool %*`
* `grun.bat: java org.antlr.v4.gui.TestRig %*`
## Generate Lexer, Parser, Listener, Visitor
After changing `g4` file you need to regenerate generated module by following commands:
```bash
$ cd gramma
$ antlr4 -Dlanguage=Python3 -visitor -no-listener EasyXML.g4 -o ../generated/
```
<file_sep>from . import Node
class NodeGet(Node.Node):
def __init__(self, attribute_name: str = '', var_name: str = '', line: int = 0, column: int = 0):
super().__init__()
self.var_name = var_name
self.attribute_name = attribute_name
self.line = line
self.column = column
<file_sep># Generated from EasyXML.g4 by ANTLR 4.9.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .EasyXMLParser import EasyXMLParser
else:
from EasyXMLParser import EasyXMLParser
# This class defines a complete generic visitor for a parse tree produced by EasyXMLParser.
class EasyXMLVisitor(ParseTreeVisitor):
# Visit a parse tree produced by EasyXMLParser#var_init.
def visitVar_init(self, ctx:EasyXMLParser.Var_initContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#assignment.
def visitAssignment(self, ctx:EasyXMLParser.AssignmentContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#sum_assignment.
def visitSum_assignment(self, ctx:EasyXMLParser.Sum_assignmentContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#get.
def visitGet(self, ctx:EasyXMLParser.GetContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#get_array_element.
def visitGet_array_element(self, ctx:EasyXMLParser.Get_array_elementContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#func_call.
def visitFunc_call(self, ctx:EasyXMLParser.Func_callContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#if_statement.
def visitIf_statement(self, ctx:EasyXMLParser.If_statementContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#if_block.
def visitIf_block(self, ctx:EasyXMLParser.If_blockContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#elif_block.
def visitElif_block(self, ctx:EasyXMLParser.Elif_blockContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#else_block.
def visitElse_block(self, ctx:EasyXMLParser.Else_blockContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#for_statement.
def visitFor_statement(self, ctx:EasyXMLParser.For_statementContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#while_statement.
def visitWhile_statement(self, ctx:EasyXMLParser.While_statementContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#func_init.
def visitFunc_init(self, ctx:EasyXMLParser.Func_initContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#type_cast.
def visitType_cast(self, ctx:EasyXMLParser.Type_castContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#range_statement.
def visitRange_statement(self, ctx:EasyXMLParser.Range_statementContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#condition.
def visitCondition(self, ctx:EasyXMLParser.ConditionContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#params.
def visitParams(self, ctx:EasyXMLParser.ParamsContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#param.
def visitParam(self, ctx:EasyXMLParser.ParamContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#expression.
def visitExpression(self, ctx:EasyXMLParser.ExpressionContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#get_operation.
def visitGet_operation(self, ctx:EasyXMLParser.Get_operationContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#operation.
def visitOperation(self, ctx:EasyXMLParser.OperationContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by EasyXMLParser#xml.
def visitXml(self, ctx:EasyXMLParser.XmlContext):
return self.visitChildren(ctx)
del EasyXMLParser<file_sep>class Node:
def __init__(self):
self.line = 0
self.column = 0
self.children = []<file_sep>from . import Node
class NodeFuncInit(Node.Node):
def __init__(self, var_type: str = '', var_name: str = '', params=None, line: int = 0, column: int = 0):
super().__init__()
self.local_vars = {}
self.var_type = var_type
self.var_name = var_name
self.params = params
self.return_statement = None
self.line = line
self.column = column
| a419deff4dd54870a053a790113906c9e2e56bd9 | [
"Markdown",
"Python"
] | 19 | Python | VadzimIlyukevich/yapis | 57d32dc40ed1701143a3b94376bfb83a5a5eb850 | c5da69918af9f4b9ca202c779961d7ca420948cd |
refs/heads/master | <file_sep>import pygame
import os
import random
import math
import sys
import _pickle as cPickle
from pygame import mixer
#Initializing pygame game
pygame.init()
#Creating game window
screen = pygame.display.set_mode((800,600))
#Title and ICO
pygame.display.set_caption("ABAC the Game")
#Finds local file
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))+"\\Resources"
#Default fonts
titleFontFile = os.path.join(THIS_FOLDER, 'Fonts\\Lobster_1.3.otf')
TitleFont = pygame.font.Font(titleFontFile, 40)
font = pygame.font.Font('freesansbold.ttf',32)
smallFontFile = os.path.join(THIS_FOLDER, 'Fonts\\OpenSans-Bold.ttf')
smallFont = pygame.font.Font(smallFontFile, 20)
#Icon
iconFile = os.path.join(THIS_FOLDER, 'MenuItems\\ABAClogo.png')
icon = pygame.image.load(iconFile)
pygame.display.set_icon(icon)
def draw_text(text, font, color, surface, x, y):
textobj = font.render(text, 1, color)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
click = False
def main_menu():
#Background
mmbgFile = os.path.join(THIS_FOLDER, 'Backgrounds\\MainMenuBgnd.png')
mmbackground = pygame.image.load(mmbgFile)
while True:
screen.fill((0,0,0))
screen.blit(mmbackground, (0,0))
draw_text('ABAC the Game', TitleFont, (15, 106, 54), screen, 275, 15)
draw_text('Coronavirus Defense', TitleFont, (23, 136, 235), screen, 240, 65)
#MainMenu Text & Box
mmRect = pygame.Rect(275, 125, 250, 50)
pygame.draw.rect(screen, (23, 136, 235), pygame.Rect(270, 120, 260, 60))
pygame.draw.rect(screen, (237, 237, 237), mmRect)
draw_text('Main Menu', font, (255, 0, 0), screen, 310, 135)
button_1 = pygame.Rect(300, 225, 200, 50)
button_2 = pygame.Rect(300, 325, 200, 50)
button_3 = pygame.Rect(300, 425, 200, 50)
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(295, 220, 210, 60))
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(295, 320, 210, 60))
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(295, 420, 210, 60))
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
pygame.draw.rect(screen, (255, 0, 0), button_3)
draw_text("Start Game", font, (255,255,255), screen, 312, 235)
draw_text("Options", font, (255,255,255), screen, 335, 335)
draw_text("Exit", font, (255,255,255), screen, 365, 435)
draw_text("Created by <NAME>", smallFont, (0,0,0), screen, 500, 570)
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if button_1.collidepoint(event.pos):
game()
if button_2.collidepoint(event.pos):
options()
if button_3.collidepoint(event.pos):
pygame.quit()
sys.exit()
pygame.display.update()
def game():
clock = pygame.time.Clock()
mixer.music.set_volume(WorkingOptions.volume)
if(not WorkingOptions.isVolumeOn):
mixer.music.set_volume(0)
#Background
bgFile = os.path.join(THIS_FOLDER, 'Backgrounds\\GardenBackground.png')
background = pygame.image.load(bgFile)
#Background sound
bgMusicFile = os.path.join(THIS_FOLDER, 'Audio\\ForestBackground16BPCM.wav')
mixer.music.load(bgMusicFile)
mixer.music.play(-1)
#Defauly Image (unassigned, for subclass mostly)
defaultImgFile = os.path.join(THIS_FOLDER, 'Enemies\\DefaultImg.png')
class Entity(object):
def __init__(self):
self.img = defaultImgFile
self.x = 0
self.y = 0
self.xChange = 0
self.yChange = 0
self.speed = 0
def getX(self):
return self.x
def getY(self):
return self.y
def getXChange(self):
return self.xChange
def getYChange(self):
return self.yChange
def getSpeed(self):
return self.speed
def setX(self, x):
self.x = x
def setY(self, y):
self.y = y
def setXChange(self, xChange):
self.xChange = xChange
def setYChange(self, yChange):
self.yChange = yChange
def setSpeed(self, speed):
self.speed = speed
def blit(self):
screen.blit(pygame.image.load(self.img), (int(self.x), int(self.y)))
#Player creation
class Player(Entity):
def __init__(self):
super().__init__()
self.img = WorkingOptions.playerImg
self.x = 350
self.y = 450
self.xChange = 0
self.speed = 6
self.bulletIMG = WorkingOptions.bulletImg
def update(self):
self.x += self.xChange
self.blit()
PlayerEntity = Player()
#Class to spawn bullet
class Bullet(Entity):
def __init__(self):
super().__init__()
self.img = PlayerEntity.bulletIMG
self.x = 0
self.y = 500
self.yChange = 10
self.state = "ready"
self.bulletSound = os.path.join(THIS_FOLDER, 'Audio\\fireSquash.wav')
def fire(self, x):
if self.state == "ready":
#play bullet sound
if (WorkingOptions.isVolumeOn): mixer.Sound(self.bulletSound).play()
#Get x coord of ship
self.state = "fire"
self.x = x + 45
if self.state == "fire":
self.y -= self.yChange
screen.blit(pygame.image.load(self.img), (int(self.x),int(self.y)))
def getState(self):
return self.state
def reset(self):
self.x = 0
self.y = 500
self.state = "ready"
ammo = 3
BulletList = []
for bullets in range(ammo):
BulletList.append(Bullet())
class Enemy(Entity):
def __init__(self):
super().__init__()
self.img = defaultImgFile
self.x = random.randint(0,736)
self.y = random.randint(50,150)
self.speed = 1
self.startingDirection = [-1,1][random.randrange(2)]
self.yChange = 40
self.destroySound = os.path.join(THIS_FOLDER, 'Audio\\pop.wav')
def getSpeed(self):
return self.speed
#coronaEnemy
coronaEnemyFile = os.path.join(THIS_FOLDER, 'Enemies\\CoronaEnemy.png')
class Coronavirus(Enemy):
def __init__(self):
super().__init__()
self.img = coronaEnemyFile
self.yChange = 40
self.speed = random.uniform(2,3) * self.startingDirection
#coronaSuperEnemy
coronaEnemyFile = os.path.join(THIS_FOLDER, 'Enemies\\CoronaEnemy.png')
class SuperCoronavirus(Enemy):
def __init__(self):
super().__init__()
#self.img = coronaEnemyFile
self.yChange = 40
self.speed = random.uniform(4,6) * self.startingDirection
#List of all enemy objects, append to add enemy to the game, autoremoved on collision
EnemyList = []
def ClearEnemies():
for x in EnemyList[:]:
EnemyList.remove(x)
#Initial Enemy Spawning
initialEnemies = 10
for i in range(initialEnemies):
EnemyList.append(Coronavirus())
#Timer
countTime = 0
def show_time():
pygame.draw.rect(screen, (0, 102, 102), pygame.Rect(600, 50, 180, 40))
score = font.render("Time: "+str(int(math.trunc(countTime/30)))+"s", True, (255,255,255))
screen.blit(score,(605,55))
#Score handling
score_value = 0
def show_score():
pygame.draw.rect(screen, (0, 102, 102), pygame.Rect(5, 5, 180, 40))
score = font.render("Score: "+ str(score_value), True, (255,255,255))
screen.blit(score,(10,10))
#Level Handler
global shots_value
shots_value = 0
def show_shots():
pygame.draw.rect(screen, (0, 102, 102), pygame.Rect(5, 50, 180, 40))
shots = font.render("Shots: "+ str(shots_value), True, (255,255,255))
screen.blit(shots,(10,55))
#Level Handler
global level_value
level_value = 1
def show_level():
pygame.draw.rect(screen, (0, 102, 102), pygame.Rect(600, 5, 180, 40))
lvl = font.render("Level: "+ str(level_value), True, (255,255,255))
screen.blit(lvl,(605,10))
def checkLevel():
#move all level spawning, including initial possibly here
global level_value
if(score_value == 10):
level_value = 2
newCV = 12
for i in range(newCV):
EnemyList.append(Coronavirus())
elif(score_value == 22):
level_value = 3
newCV = 5
for i in range(newCV):
EnemyList.append(Coronavirus())
newSuperCV = 2
for i in range(newCV):
EnemyList.append(SuperCoronavirus())
def isCollision(EnemyX, EnemyY, bulletX, bulletY):
#collision based on center of 64x64px enemy
#TODO rework to take inpput of enemy width and heigth and generalize centering mechanism
distance = math.sqrt(math.pow((EnemyX + 32) - bulletX, 2) + (math.pow((EnemyY + 32) - bulletY, 2)))
if distance < 32:
return True
else:
return False
#Game Over handling
global isGameOver
global end_time
global accuracy
isGameOver = False
end_time = 0
accuracy = 0
def game_over():
global isGameOver
global end_time
global accuracy
if(not isGameOver):
end_time = str(int(math.trunc(countTime/30)))
if(not shots_value == 0):
accuracy = math.trunc((score_value/shots_value)*100)
ClearEnemies()
isGameOver = True
over_text = pygame.font.Font(os.path.join(THIS_FOLDER, 'Fonts\\OpenSans-ExtraBold.ttf'), 70).render("GAME OVER", True, (214, 2, 230))
screen.blit(over_text,(200,150))
pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(180, 250, 460, 50))
over_text = pygame.font.Font(os.path.join(THIS_FOLDER, 'Fonts\\OpenSans-Semibold.ttf'), 35).render("Time: "+end_time+"s | Accuracy: "+str(accuracy)+"%", True, (214, 2, 230))
screen.blit(over_text,(190,250))
def PauseGame():
Pause = True
text = pygame.font.Font(os.path.join(THIS_FOLDER, 'Fonts\\OpenSans-ExtraBold.ttf'), 70).render("GAME PAUSED", True, (255, 0, 0))
while(Pause):
screen.blit(text,(170,200))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if(event.key == pygame.K_p):
Pause = False
pygame.display.update()
clock.tick(30)
#Main repeater
running = True
while running:
if(not isGameOver):
countTime += 1
#RGB & set background
screen.fill((0, 0, 0))
screen.blit(background, (0,0))
#Event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
PlayerEntity.setXChange(-(PlayerEntity.getSpeed()))
if event.key == pygame.K_RIGHT:
PlayerEntity.setXChange(PlayerEntity.getSpeed())
if event.key == pygame.K_SPACE:
for x in BulletList:
if x.getState() == "ready":
x.fire(PlayerEntity.getX())
shots_value += 1
break
if event.key == pygame.K_ESCAPE:
pygame.mixer.music.pause()
running = False
if(event.key == pygame.K_p):
PauseGame()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
PlayerEntity.setXChange(0)
#Create boundaries for PLAYER
if PlayerEntity.getX() < 0:
PlayerEntity.setX(0)
elif PlayerEntity.getX() > 655:
PlayerEntity.setX(655)
#Iterates through copied list
for x in EnemyList[:]:
#Game Over
if x.getY() > 420:
game_over()
break
#coronaEnemy Movement
x.setX(x.getX()+x.getSpeed())
#Create boundaries for coronaEnemy
if x.getX() <= 0:
x.setSpeed(-x.getSpeed())
x.setY(x.getY()+x.getYChange())
elif x.getX() >= 736:
x.setSpeed(-x.getSpeed())
x.setY(x.getY()+x.getYChange())
#Collisions
for bullets in BulletList:
collision = isCollision(x.getX(),x.getY(),bullets.getX(),bullets.getY())
if collision:
score_value +=1
#play bullet sound
if (WorkingOptions.isVolumeOn): mixer.Sound(x.destroySound).play()
bullets.reset()
EnemyList.remove(x)
#Set level upgrades, single check (to centralize & organize)
checkLevel()
x.blit()
#Bullet boundry
for x in BulletList:
if x.getY() <= -10:
x.reset()
#Bullet movement
if x.getState() == "fire":
x.fire(x.getX())
if(isGameOver):
game_over()
#push to player/coronaEnemy func
PlayerEntity.update()
show_score()
show_shots()
show_level()
show_time()
pygame.display.update()
clock.tick(30)
#Set up settings
class GameOptions(object):
def __init__(self):
self.players = ["<NAME>","<NAME>","<NAME>"]
self.activePlayer = "<NAME>"
self.playerImg = os.path.join(THIS_FOLDER, 'Players\\GahagenPlayer.png')
self.bulletImg = os.path.join(THIS_FOLDER, 'Players\\GahagenShot.png')
self.volume = 0.1 #Float 0 to 1
self.isVolumeOn = True
def update(self, activePlayer):
self.activePlayer = activePlayer
def setActivePlayer(self, newPlayer):
self.activePlayer = newPlayer
if(self.activePlayer == "<NAME>"):
self.playerImg = os.path.join(THIS_FOLDER, 'Players\\GahagenPlayer.png')
self.bulletImg = os.path.join(THIS_FOLDER, 'Players\\GahagenShot.png')
if(self.activePlayer == "<NAME>"):
self.playerImg = os.path.join(THIS_FOLDER, 'Players\\JasonPacePlayer.png')
self.bulletImg = os.path.join(THIS_FOLDER, 'Players\\DefaultShot.png')
if(self.activePlayer == "Dr. Beals"):
self.playerImg = os.path.join(THIS_FOLDER, 'Players\\BealsPlayer.png')
self.bulletImg = os.path.join(THIS_FOLDER, 'Players\\DefaultShot.png')
def save(self):
with open(os.path.join(THIS_FOLDER, 'GameOptions.txt'),'wb') as f:
f.write(cPickle.dumps(self.__dict__))
def load(self):
with open(os.path.join(THIS_FOLDER, 'GameOptions.txt'),'rb') as f:
dataPickle = f.read()
self.__dict__ = cPickle.loads(dataPickle)
#Initially create useable instance of options and load for use globally
WorkingOptions = GameOptions()
#ToDo add mechanism to check if file contains all attributes
#If not working, delete gameoptions txt file. Probably contains older class version
#currently saves options first since there is no front end saving option
try:
WorkingOptions.load()
except:
WorkingOptions.save()
def options():
#Background
mmbackground = pygame.image.load(os.path.join(THIS_FOLDER, 'Backgrounds\\MainMenuBgnd.png'))
leftarrow = pygame.image.load(os.path.join(THIS_FOLDER, 'MenuItems\\LeftArrow.png'))
rightarrow = pygame.image.load(os.path.join(THIS_FOLDER, 'MenuItems\\RightArrow.png'))
backarrow = pygame.image.load(os.path.join(THIS_FOLDER, 'MenuItems\\BackArrow.png'))
backarrowRect = pygame.Rect(25, 25, 64, 64)
arrowy1 = 218; Larrowx1 = 177; Rarrowx1 = 560
leftarrowRECT1 = pygame.Rect(Larrowx1, arrowy1, 64, 64)
rightarrowRECT1 = pygame.Rect(Rarrowx1, arrowy1, 64, 64)
arrowy2 = 318; Larrowx2 = 177; Rarrowx2 = 560
leftarrowRECT2 = pygame.Rect(Larrowx2, arrowy2, 64, 64)
rightarrowRECT2 = pygame.Rect(Rarrowx2, arrowy2, 64, 64)
#Temp Variables presave
List_of_Players = WorkingOptions.players
try:
PlayerListPos = List_of_Players.index(WorkingOptions.activePlayer)
except:
PlayerListPos = 0
isVolumeOn = WorkingOptions.isVolumeOn
if (isVolumeOn):
isVolumeOnColor = (62,222,33)
else:
isVolumeOnColor = (255,0,0)
volumeList = [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
try:
volumeListPos = volumeList.index(100 * WorkingOptions.volume)
except:
volumeListPos = 10
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
mousePos = event.pos
if(backarrowRect.collidepoint(mousePos)):
running = False
if(leftarrowRECT1.collidepoint(mousePos)):
#left arrow 1 (professor)
if PlayerListPos == 0:
PlayerListPos = (len(List_of_Players) - 1)
else:
PlayerListPos -= 1
if(rightarrowRECT1.collidepoint(mousePos)):
#right arrow 1 (professor)
if PlayerListPos == (len(List_of_Players) - 1):
PlayerListPos = 0
else:
PlayerListPos += 1
if(leftarrowRECT2.collidepoint(mousePos)):
#left arrow 2 (volume)
if volumeListPos == 0:
volumeListPos = (len(volumeList) - 1)
else:
volumeListPos -= 1
if(rightarrowRECT2.collidepoint(mousePos)):
#right arrow 2 (volume)
if volumeListPos == (len(volumeList) - 1):
volumeListPos = 0
else:
volumeListPos += 1
if(pygame.Rect(350, 525, 100, 50).collidepoint(mousePos)):
#Save button
WorkingOptions.setActivePlayer(List_of_Players[PlayerListPos])
WorkingOptions.isVolumeOn = isVolumeOn
WorkingOptions.volume = (volumeList[volumeListPos] / 100)
WorkingOptions.save()
if(pygame.Rect(275, 425, 250, 50).collidepoint(mousePos)):
#Toggle volume buttonn
if isVolumeOn:
isVolumeOn = False
else:
isVolumeOn = True
if (isVolumeOn):
isVolumeOnColor = (62,222,33)
else:
isVolumeOnColor = (255,0,0)
screen.fill((0,0,0))
screen.blit(mmbackground, (0,0))
#back arrow
screen.blit(backarrow,(25,25))
#MainMenu Text & Box
pygame.draw.rect(screen, (23, 136, 235), pygame.Rect(270, 90, 260, 60))
pygame.draw.rect(screen, (237, 237, 237), pygame.Rect(275, 95, 250, 50))
draw_text('Options', font, (255, 0, 0), screen, 330, 105)
#Professor control... Outer box, inner box, text
#option 1 presents list of players
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(245, 220, 310, 60))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(250, 225, 300, 50))
draw_text(str(List_of_Players[PlayerListPos]), font, (255,255,255), screen, 262, 235)
#option 1 left and right arrows
screen.blit(leftarrow, (Larrowx1, arrowy1))
screen.blit(rightarrow, (Rarrowx1, arrowy1))
#Professor control... Outer box, inner box, text
#option 1 presents list of players
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(270, 320, 260, 60))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(275, 325, 250, 50))
draw_text("Sound "+str(volumeList[volumeListPos])+"%", font, (255,255,255), screen, 305, 335)
#option 1 left and right arrows
screen.blit(leftarrow, (Larrowx2, arrowy2))
screen.blit(rightarrow, (Rarrowx2, arrowy2))
#Sound toggle control
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(270, 420, 260, 60))
pygame.draw.rect(screen, isVolumeOnColor, pygame.Rect(275, 425, 250, 50))
draw_text('Toggle Sound', font, (255,255,255), screen, 280, 435)
#Save button
pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(345, 520, 110, 60))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(350, 525, 100, 50))
draw_text("Save", font, (255,255,255), screen, 362, 535)
pygame.display.update()
main_menu() | 4cd800a9049cdd62cc8de365ace39a79e7fcdd10 | [
"Python"
] | 1 | Python | GarretPp/ABAC-the-Game | c2ac4599a8604bf22543dee4ee7fb54fc6d6fcd8 | 2ee4649e922de043913ed5be46da080c7c18e573 |
refs/heads/master | <repo_name>indraastra/pyrabj<file_sep>/src/rabj/simple.py
import logging, Queue, multiprocessing
from rabj import VERSION, APP
import rabj.api as api, rabj.util as u
api._def_headers['User-agent'] = ':'.join([APP, 'pyrabj.simple', VERSION])
"""
Production instance of rabj
"""
RABJ_PROD = "http://data.labs.freebase.com/"
RABJ_TRUNK = "http://rabj.trunk.metaweb.com/"
RABJ_QA = "http://rabj.qa.metaweb.com/"
RABJ_SANDBOX = "http://rabj.sandbox.metaweb.com/"
_log = logging.getLogger('pyrabj.simple')
class RabjServer(object):
"""
A wrapper class for a rabj server, provides methods for investigating
queues available on the server.
server_url
A url for the rabj server hosting the queue.
"""
def __init__(self, server_url, store_path='rabj/store/'):
"""Create a new reference to a rabj server."""
if server_url.endswith('/rabj/store/'):
self.server = server_url[:-11]
elif server_url.endswith('/rabj/'):
self.server = server_url[:-5]
else:
self.server = server_url
self.store = api.RabjCallable(self.server)[store_path]
self.threads = 1
def create_queue(self, name, owner, votes, access_key, tags=None, **meta):
"""
Create a new queue giving it a name, owner, a required number of
votes and optionally including an access_key, tags and any other
metadata to be associated.
>>> server = RabjServer(RABJ_TRUNK)
>>> queue = server.create_queue('pyrabj doc queue', '/user/kochhar', 1, access_key='testkey')
>>> print queue['name']
pyrabj doc queue
>>> print queue['owner']
/user/kochhar
"""
votes = int(votes)
if access_key is None:
_log.warn("You are creating a new queue without providing an access key")
if tags is None: tags = []
queue = { "name": name,
"owner": owner,
"access_key": access_key,
"votes": votes,
"tags": tags
}
queue.update(meta)
resp, queue = self.store.queues.post(queue=queue)
return RabjQueue(queue, threads=self.threads)
def get_queue(self, queue_id, access_key=None):
"""
Fetch a queue given it's id
>>> server = RabjServer(RABJ_TRUNK)
>>> queue = server.create_queue('pyrabj doc queue', '/user/kochhar', 1, access_key='testkey')
>>> queue_copy = server.queue_by_id(queue_id=queue['id'], access_key='testkey')
>>> queue == queue_copy
True
"""
resp, result = self.store[self._norm_qid(queue_id)].get(access_key=access_key)
return RabjQueue(result, threads=self.threads)
def delete_queue(self, queue, access_key=None):
"""
Delete a queue by providing either a string id or a mapping object
with an id field (Eg: a RabjQueue instance or a dict with an
'id'). If no access key is provided and queue is a mapping type,
this class will try using the access_key field in queue if one
exists.
>>> server = RabjServer(RABJ_TRUNK)
>>> queue = server.create_queue('pyrabj doc queue', '/user/kochhar', 1, access_key='testkey')
>>> deletion = server.delete_queue(queue)
>>> queue['id'] == deletion['id']
True
>>> deletion['delete']
u'deleted'
"""
if isinstance(queue, RabjQueue) or hasattr(queue, 'get'):
queue_id = queue['id']
access_key = access_key if access_key is not None else queue.get('access_key')
else:
queue_id = queue
resp, result = self.store[self._norm_qid(queue_id)].delete(access_key=access_key)
return result
def public_queues(self):
"""
Fetch a list of public queues
"""
resp, result = self.store.queues.public.get()
return [ RabjQueue(queue, threads=self.threads) for queue in result ]
# common aliases
queue_by_id = get_queue
def queues_by_id(self, queue_id, access_key=None):
"""
Equivalent to queue_by_id but returns results as a list.
"""
return [ self.get_queue(queue_id, access_key) ]
def queues_by_accesskey(self, access_key):
"""
Fetch a list of queues which may be operated with a given access key
"""
resp, result = self.store.queues.access_key.get(access_key=access_key)
return [ RabjQueue(queue, threads=self.threads) for queue in result ]
def queues_by_tags(self, tags, access_key=None):
"""
Fetch a list of queues which have the given tags. Optionally include
an access key to authorize access to the queues
"""
if isinstance(tags, basestring):
tags = [tags]
resp, result = self.store.queues.tags.get(tag=tags, access_key=access_key)
return [ RabjQueue(queue, threads=self.threads) for queue in result ]
def queues_by_owner(self, owner, access_key=None):
"""
Fetch a list of queues by owner
"""
resp, result = self.store.users[owner].queues.get(access_key=access_key)
return [ RabjQueue(queue, threads=self.threads) for queue in result ]
queues_by_public = public_queues
def _norm_qid(self, qid):
if qid.startswith('/rabj/store'):
return qid[11:]
elif qid.startswith('/store'):
return qid[6:]
else:
return qid
class RabjQueue(object):
"""
A wrapper class around a rabj queue, provides convenience methods for
introspecting and modifying the state of a queue. The class behaves
similar to a dict, allowing fields to be read and set.
A rabj queue instance can be created either from a
:class:`~rabj.api.RabjCallable` object or by providing a server url, a
queue id and an access_key.
queue
A :class:`~rabj.api.RabjCallable` which references a queue. Required
if ``server_url`` and ``id`` are None
server_url
A url for the rabj server hosting the queue. Required if ``queue=None``
id
The id of the queue on the server. Required if ``queue=None``
access_key
The access key for the queue on the server. Required if ``queue=None``
"""
def __init__(self, queue=None, server_url=None, id=None, access_key=None, threads=1):
"""
Create a new rabj queue. Not intended to be used directly, see the
queue creation and fetching methods in RabjServer
"""
assert (queue!=None) ^ ((server_url!=None) & (id!=None) & (access_key!=None))
if not queue:
resp, queue = api.RabjCallable(server_url, access_key=access_key)[id].get()
self.queue = queue
self.threads = 2 if threads > 1 else 1
self._status_fetched = False
self._status = None
def __repr__(self):
return repr(self.queue)
def __str__(self):
return str(self.queue)
def __getitem__(self, key):
return self.queue[key]
def __setitem__(self, key, value):
self.queue[key] = value
def __delitem__(self, key):
del self.queue[key]
@property
def parallel(self):
return False
def update(self):
"""Save modifications to the current queue."""
resp, result = self.queue.put(queue=self.queue)
self.queue = result
return self
def addone(self, assertion, answerspace, **meta):
"""
Add a single question defined by its assertion, answerspace and any
other metadata as keyword args.
"""
question = { 'assertion': assertion,
'answerspace': answerspace }
question.update(meta)
resp, result = self.queue.questions.post(questions=[question])
return result['questions']
def addall(self, three_tuples, pagesize=1000):
"""
Add questions passed as three-tuples (assertion, answerspace,
metadata dict), optionally provide a batchsize, default of 1000
three_tuples:
An iterable containing tuples. The first element is treated as
the assertion, the second as the answerspace and the third as a
dictionary containing other metadata.
pagesize:
The number of questions to send in one request, default is 1000
"""
added = []
payload = []
for assertion, answerspace, meta in three_tuples:
question = { 'assertion': assertion,
'answerspace': answerspace }
question.update(meta)
payload.append(question)
if len(payload) == pagesize:
resp, result = self.queue.questions.post(questions=payload)
added.extend(result['questions'])
payload = []
if len(payload):
resp, result = self.queue.questions.post(questions=payload)
added.extend(result['questions'])
payload = []
return added
def getone(self, question=None):
"""
Get one question from the queue. Optionally the id of the question to
fetch can be passed as a parameter.
"""
if question is not None:
assert isinstance(question, [basestring, dict])
if isinstance(question, dict):
questionid = question['id']
else:
questionid = question
resp, question = self.queue['../../../'][questionid].get()
else:
resp, question = self.queue.questions.get(limit=1)[0]['id']
return RabjQuestion(question)
def getall(self, state=None, body=True, judgments=False, since=None, pagesize=5000):
"""
Get a list of all the question on the queue
state
Filter the questions returned by state (complete|wanting|partial),
default is no filter
body
Include the full question body in the response (assertion, tags,
metadata, etc.), default is True
judgments
Include judgments when getting questions, default is False
since
Starting point from where to get questions, defaults to all
questions. Format is YYYY-MM-DD HH:MM:SS
pagesize
The number of questions to fetch per request, default is 5000
"""
params = {
'limit': pagesize,
'offset': 0
}
if since:
params['since'] = since
if judgments:
params['judgments'] = judgments
if body:
params['body'] = body
questions = []
while True:
if state:
resp, result = self.queue.questions[state].get(**params)
else:
resp, result = self.queue.questions.get(**params)
questions.extend( RabjQuestion(res) for res in result['questions'] )
# keep fetching until no questions are returned
if ( len(result['questions']) < pagesize ):
break
else:
params['offset'] += params['limit']
return questions
def delete(self, questions):
"""
Delete a set of questions from a queue.
questions
An iterable of RabjQuestion objects which should have ids
"""
resp, result = self.queue.questions.delete(questions=[{'id': q['id']} for q in questions])
return result
def deleteall(self):
"""
Delete all questions from a queue
"""
questions = self.all_questions()
return self.delete(questions)
@property
def questions(self):
"""
Return the count of questions on the queue
"""
status = self.statusonce()
return status["questions"]
@property
def complete(self):
"""
Return the count of completed questions on the queue
"""
status = self.statusonce()
return status["complete"]
@property
def incomplete(self):
"""
Return the count of inocomplete questions on the queue
"""
status = self.statusonce()
return status["incomplete"]
@property
def started(self):
"""
Return the count of started questions on the queue
"""
status = self.statusonce()
return status["started"]
@property
def judgments(self):
"""
Return the count of judgments accumulated for the queue
"""
status = self.statusonce()
return status["judgments"]
def statusonce(self):
if not self._status_fetched:
self._status = self.status()
self._status_fetched = True
return self._status
def resetstatus(self):
self._status_fetched = False
self._status = None
def status(self, **kwargs):
resp, result = self.queue.status.get(**kwargs)
qstat = result['status']
simple_status = { "judgments": qstat.get('judgments', 0),
"complete": qstat.get('complete', 0),
"incomplete": qstat.get('wanting', 0),
"started": qstat.get('started', 0),
}
simple_status["questions"] = (simple_status["complete"] +
simple_status["incomplete"])
return simple_status
all_questions = getall
def completed_questions(self, body=True, judgments=False, since=None, pagesize=5000):
"""
Fetch questions which have been completed. Optionally fetch
questions completed after a given point in time and include
judgments also
See RabjQueue.getall() for a description of the parameters.
"""
return self.getall(state='complete', since=since, judgments=judgments, pagesize=pagesize)
def incomplete_questions(self, body=True, judgments=False, since=None, pagesize=5000):
"""
Fetch questions which have been completed. Optionally fetch
questions completed after a given point in time and include
judgments also
See RabjQueue.getall() for a description of the parameters.
"""
return self.getall(state='wanting', since=since, judgments=judgments, pagesize=pagesize)
def _get(self, rabj_callables):
if self.parallel == True:
fetched = api.parallel_fetch([ rc.request_params(rc._url, "GET") for rc in rabj_callables ], self.threads)
else:
fetched = [ rc.get() for rc in rabj_callables ]
return fetched
class RabjQuestion(object):
"""
A wrapper class around a rabj question, provides convenience methods for
introspecting the state of the question. This class behaves much like a
dictionary (though it cannot be serialized) allowing fields to be read and
set.
"""
def __init__(self, question=None, server=None, id=None):
assert (question!=None) ^ ((server!=None) & (id!=None))
if not question:
resp, question = api.RabjCallable(server)[id].get()
self.question = question
def __repr__(self):
return repr(self.question)
def __str__(self):
return str(self.question)
def __getitem__(self, key):
return self.question[key]
def __setitem__(self, key, value):
return self.question.__setitem__(key, value)
def __delitem__(self, key):
return self.question.__delitem__(key)
def update(self):
"""Saves modifications to the question"""
resp, result = self.question.put(question=self.question)
self.question = result
return self
def delete(self):
"""Deletes the question from rabj"""
resp, result = self.question.delete()
return result
def judgments(self):
"""Fetches this questions judgments"""
resp, result = self.question.judgments.get()
return result['judgments']
<file_sep>/src/rabj/util.py
'''
util.py
Utilities functions and class for using the Rabj APIs
'''
import httplib2, logging, multiprocessing, urlparse
from Queue import Queue, Empty, Full
_log = logging.getLogger("pyrabj.util")
class NullHandler(logging.Handler):
"""
Simple class for for doing nothing when logging. Used to add a simple
handler and prevent logging config warning messages
"""
def emit(self, record):
pass
def host_url(url):
"""
The URL through the host (no path)
"""
pr = urlparse.urlsplit(url)
scheme = pr.scheme
host = pr.netloc
url = '%s://%s' % (scheme, host)
return url
def path(url):
"""
The path of the URL after the host
"""
pr = urlparse.urlsplit(url)
return pr.path
class Fetcher(multiprocessing.Process):
"""
Extension to multiprocessing.Process class which takes a queue of tasks and a
queue of results. Thread continues to run until the task queue is
empty.
The task queue should contain tuples of the form, (callable, *args,
**kwargs).
tasks
multiprocessing.Queue of tasks to be completed, each queue item should be a tuple
containing (url, method, body, headers)
results
multiprocessing.Queue where results of invoking callable(*args,
**kwargs) will be written
args
positional arguments to be passed to multiprocessing.Process(...)
kwargs
key-word arguments to be passed to multiprocessing.Process(...)
"""
def __init__(self, tasks, results, *args, **kwargs):
assert 'target' not in kwargs
super(Fetcher, self).__init__(*args, **kwargs)
self.tasks = tasks
self.results = results
self.shutdown = multiprocessing.Event()
self.count = 0
def stop(self):
self.shutdown.set()
def run(self):
http = httplib2.Http()
while not self.shutdown.is_set():
try:
url, method, body, headers = self.tasks.get(block=True, timeout=1)
_log.debug("Sending %s to url %s", method.lower(), url)
resp, content = http.request(url, method, body)
self.results.put((url, (resp, content)))
self.tasks.task_done()
self.count += 1
except Empty:
pass
_log.debug("shutting down process %s, executed %i tasks", self.name, self.count)
_poollog = logging.getLogger("pyrabj.util.http_pool")
class HTTPPool(object):
"""
Implementation of a thread-safe http pool.
timeout
timeout for each individual connection, can be a float. None disables
timeout.
max
Maximum number of connections which will be pooled for reuse. Setting
this value to a number larger than one is essential when using many
threads. If this pool is non-blocking (``block`` is False), there is
no upper bound on the number of connections created. However, only
maxsize connections will be saved for reuse.
block
When this is True, prevents more than ``maxsize`` connections being
used at any given time. When there are no more free connections
available, a request to create a new connection will block until one
is available. This can be used to effectively throttle the number of
simultaneous requests made to a single host.
"""
def __init__(timeout=None, max=10, block=False):
_log.debug("Creating new http pool")
self.timeout = timeout
self.pool = Queue(max)
self.block = block
self.num_connections = 0
# prefill the pool with connections
[ self.pool.put(self.new()) for i in xrange(max) ]
def get(self):
"""
Returns a new connection, if the pool is blocking, this method will
block until a new connection is made available.
"""
conn = None
try:
conn = self.pool.get(block=self.block)
except Empty, e:
conn = self.new()
return conn
def put(self, conn):
"""
Places an existing connection back into the pool. If the pool is full,
the connection will not be saved.
"""
try:
self.pool.put(conn, block=False) # block=False is essential to get a Full notice
except Full, e:
_poollog.warning("Discarding connection %i to %s", self.num_connections, self.host)
self.num_connections -= 1
def new(self):
"""
Creates a new connection
"""
self.num_connections += 1
_poollog.info("Creating connection %i to host %s", self.num_connections, self.host)
return httplib2.Http(timeout=self.timeout)
<file_sep>/src/rabj/api.py
import logging, httplib2, jsonlib2, urllib, multiprocessing
from rabj import VERSION, APP
import util as u
_def_headers = { 'Accept': 'application/json',
'Content-type': 'application/json',
'User-agent': ':'.join([APP, "pyrabj.api", VERSION])
}
_log = logging.getLogger("pyrabj.api")
class RabjCallable(object):
"""
A minimalist yet fully featured implementation to use the RABJ API. A
RabjCallable instance points at a url. URL heirarchies are traversed by
accessing attributes of a RabjCallable. For instance::
>>> rabj = RabjCallable('http://data.labs.freebase.com/rabj/')
>>> print rabj.store._url
http://data.labs.freebase.com/rabj/store/
>>> public_queues = rabj.store.queues.public
>>> print public_queues._url
http://data.labs.freebase.com/rabj/store/queues/public/
The methods of a RabjCallable instance (:meth:`get`, :meth:`post`,
:meth:`put`, :meth:`delete`) translate to their HTTP equivalents. This
provides a very lightweight wrapper for the RESTful API. The results of
invoking a method is a tuple of a :class:`~rabj.api.RabjResponse` and a
:class:`~rabj.containers.RabjContainer` which holds the unwrapped
results::
>>> resp, result = public_queues.get()
>>> type(resp)
<class 'rabj.api.RabjResponse'>
>>> type(result)
<class 'rabj.containers.RabjList'>
**Examples**
::
>>> rabj = RabjCallable('http://data.labs.freebase.com/rabj/')
# Get a list of queues with my tags
>>> mytags = [ 'foo', 'bar' ]
>>> resp, myqs = rabj.store.queues.tags.get(tag=mytags)
# Get a particular queue
>>> resp, myq1 = rabj.store.queues['queue_124113044366_0'].get()
>>> print myq1['id']
/rabj/store/queues/queue_124113044366_0
# Also supported (but totally weird)
>>> resp2, myq2 = rabj.store.queues.queue_124113044366_0.get()
>>> resp3, myq3 = getattr(rabj.store.queues, 'queue_124113044366_0').get()
# create a new queue
>>> queue = {'name': 'my dr suess queue',
'owner': '/user/dr_seuss',
'tags': ['/en/cat', '/en/hat'],
'votes': 2}
>>> resp, qcreate = rabj.store.queues.post(queue=queue)
>>> qid = qcreate['id']
# Add a list of questions to the newly created queue
>>> resp, addq = qcreate.questions.post(questions=generate_questions(10))
**Using the data returned**
The RabjContainer objects returned play a dual-role. First, they act as
containers like their python equivalantes (lists and
dicts). RabjContainers also provide the ability to make further Rabj
calls::
>>> resp, queue = rabj.store.queues['queue_124113044366_0'].questions.get()
# All questions on the queue
>>> queue_questions = queue['questions']
>>> type(queue_questions)
<class 'rabj.containers.RabjList'>
>>> print queue_questions
# The first question on the queue
>>> ques0ref = queue_questions[0]
>>> type(ques0ref)
<class 'rabj.containers.RabjDict'>
>>> print ques0ref
# Get the question
>>> resp, question = ques0ref.get()
>>> print question
# Retrieve a list of completed questions for a queue
>>> resp, queue_comp = rabj.store.queues['queue_124113044366_0'].questions.complete.get()
>>> completed_questions = queue_comp['questions']
# fetch the list of users who have answered the second question
>>> resp, qq2_users = completed_questions[2].users.get()
# fetch the list of judgments for all the completed questions
>>> fetches = [ q.judgments.get() for q in completed_questions ]
>>> judgments = [ result['judgments'] for (resp, result) in fetches ]
"""
def __init__(self, url, access_key=None, *args, **kwargs):
super(RabjCallable, self).__init__(*args, **kwargs)
self._url = url if url.endswith('/') else url + '/'
self._access_key = access_key
self._http = httplib2.Http()
def __repr__(self):
return "<%s@%s>" % (self.__class__.__name__, self._url)
def __getattr__(self, attr):
try:
return super(RabjCallable, self).__getattr__(attr)
except AttributeError:
return self[attr]
def __getitem__(self, key):
return RabjCallable(self._url+key, access_key=self._access_key)
def get(self, **kwargs):
"""Execute a HTTP GET request on the current url. Additional
parameters passed as kwargs will be added as query params.
"""
return self.response(*self.request_params(self._url, "GET", **kwargs))
def post(self, **kwargs):
"""Execute a HTTP POST request on the current url. Additional
parameters passed as kwargs will be encoded as JSON and sent in the
body.
"""
return self.response(*self.request_params(self._url, "POST", **kwargs))
def put(self, **kwargs):
"""Execute a HTTP PUT request on the current url. Additional
parameters passed as kwargs will be encoded as JSON and sent in the
body.
"""
return self.response(*self.request_params(self._url, "PUT", **kwargs))
def delete(self, **kwargs):
"""Execute a HTTP DELETE request on the current url. Additional
parameters passed as kwargs will be encoded as JSON and sent in the
body.
"""
return self.response(*self.request_params(self._url, "DELETE", **kwargs))
def request_params(self, url, method, **kwargs):
"""
Constructs the parameters for a http request
"""
params = dict()
if self._access_key is not None:
params['access_key'] = self._access_key
if kwargs:
params.update(kwargs)
if method == "GET":
url = url + "?" + urllib.urlencode(params, doseq=True)
body = None
else:
body = jsonlib2.dumps(params, escape_slash=False)
return url, method, body, _def_headers
def response(self, url, method, body, headers):
"""
Executes the request and wraps into a RabjResponse
"""
_log.debug("Sending %s to url %s", method.lower(), url)
resp, content = self._http.request(url, method, body, headers)
rabj_resp = RabjResponse(content, resp, url)
return rabj_resp, rabj_resp.result
def parallel_fetch(fetch_params, parallelism=2):
"""
Fetch a set of urls in parallel.
fetch_params
params to pass to a Fetcher, should be tuples of (url, method, body,
headers)
parallelism
The number of processes to split into
"""
assert parallelism > 0
task_queue = multiprocessing.JoinableQueue()
result = multiprocessing.Queue()
pool = [ u.Fetcher(task_queue, result) for _ in xrange(parallelism) ]
_log.info("Starting thread pool with %i workers", parallelism)
for p in pool:
p.start()
_log.info("placing %i url fetches on task queue", len(fetch_params))
for param_set in fetch_params:
task_queue.put(param_set)
task_queue.join()
for p in pool:
p.stop()
results = [ RabjResponse(c, r, url) for (url, (r, c)) in [ result.get() for i in range(result.qsize()) ] ]
return [ (resp, resp.result) for resp in results ]
import containers as c
class RabjResponse(object):
"""Container for a response from rabj with convenience methods
"""
def __init__(self, content, resp, url, *args, **kwargs):
super(RabjResponse, self).__init__()
self._url = url
self.http_resp = resp
self.env = self._parse(resp, content)
self.container_factory = c.RabjContainerFactory(url)
def __repr__(self):
return "%s@%s" % (self.__class__.__name__, self._url)
def __str__(self):
return str(self.envelope)
@property
def url(self):
return self._url
@property
def response(self):
return self.http_resp
@property
def envelope(self):
return self.env
@property
def result(self):
"""Unwraps the response envelope and returns the result of the
operation as a rabj container
"""
result = self.envelope['result']
return self.container_factory.container(result)
def _parse(self, resp, content):
"""Parses a rabj response to get the envelope information
"""
if resp['content-type'] == 'application/json':
try:
envelope = jsonlib2.loads(content)
if envelope['status']['code'] == 200:
return envelope
else:
error = envelope['error']
raise RabjError(error['code'], error['class'], error['detail'], envelope)
except jsonlib2.ReadError, e:
_log.warn("Decode error %s in content %s", e, content)
raise RabjError(resp.status, resp.reason, {'msg': e.message}, content)
else:
_log.warn("Non-json response '%s' when fetching %s",
content, resp.get('content-location', self._url))
raise RabjError(resp.status, resp.reason, {'msg': content}, content)
class RabjError(Exception):
"""Exception class for errors from rabj. Provides access to error_code,
error_class, msg, alt, where
"""
def __init__(self, error_code, error_class, detail, envelope):
super(RabjError, self).__init__()
self.env = envelope
self.error_code = error_code
self.error_class = error_class
self.msg = detail['msg']
self.alt = detail.get('alternatives')
self.where = detail.get('in')
def __str__(self):
str_base = "%s %s. Msg: %s. " % (self.error_code, self.error_class, self.msg)
if self.where: str_base += "Error in %s" % (self.where, )
if self.alt: str_base += " try %s instead" % (self.alt, )
return str_base
@property
def envelope(self):
return self.env
__all__ = [ 'RabjCallable', 'RabjResponse' , 'RabjError' ]
<file_sep>/src/rabj/containers.py
'''
containers.py
module containing containers for rabj objects
'''
import jsonlib2, collections, cStringIO, logging, pprint
import util as u
_log = logging.getLogger("pyrabj.containers")
class RabjContainerFactory(object):
def __init__(self, url):
self.url = url
self.host_url = u.host_url(url)
self.path = u.path(url)
def container(self, obj):
if isinstance(obj, dict):
# A dict response may be a rabj object with an id. If so, set the
# path to be the id of the returned object
if 'id' in obj:
return RabjDict(obj, "%s%s" % (self.host_url, obj['id']))
else:
return obj
elif isinstance(obj, list):
return RabjList(obj, self.url)
else:
return obj
class RabjContainer(object):
"""Abstract container for Rabj data.
"""
def __init__(self, data, url):
super(RabjContainer, self).__init__()
self.data = data
self.url = url
self.container_factory = RabjContainerFactory(self.url)
def __repr__(self):
return repr(self.data)
def __str__(self):
strbuf = cStringIO.StringIO()
pprint.pprint(self.data, strbuf)
rabjstr = strbuf.getvalue()
strbuf.close()
return rabjstr
def tojson(self):
"""
Convert the object to it's json representation
"""
return jsonlib2.dumps(self.data, escape_slash=False)
from rabj.api import RabjCallable
class RabjDict(RabjContainer, collections.Mapping):
"""Mapping container for rabj responses
"""
def __init__(self, result, url, *args, **kwargs):
super(RabjDict, self).__init__(data=result, url=url)
self.rabjcallable = RabjCallable(url, self.data.get('__metadata__', {}).get('access_key', self.data.get('access_key')))
def __getattr__(self, attr):
try:
return super(RabjDict, self).__getattr__(attr)
except AttributeError, e:
return getattr(self.rabjcallable, attr)
def __getitem__(self, key):
try:
item = self.data[key]
return self.container_factory.container(item)
except KeyError, e:
return self.rabjcallable[key]
def __setitem__(self, key, value):
self.data[key] = value
def __delitem__(self, key):
try:
del self.data[key]
except KeyError, e:
raise KeyError(e)
def get(self, key=None, *args, **kwargs):
if key is None:
return self.rabjcallable.get(**kwargs)
return super(RabjDict, self).get(key, *args, **kwargs)
def post(self, **kwargs):
return self.rabjcallable.post(**kwargs)
def put(self, **kwargs):
return self.rabjcallable.put(**kwargs)
def __iter__(self):
return iter(self.data)
def __len__(self):
return len(self.data)
class RabjList(RabjContainer, collections.MutableSequence):
"""Sequence container for rabj responses
"""
def __init__(self, result, url):
super(RabjList, self).__init__(data=result, url=url)
def __getitem__(self, i):
item = self.data[i]
return self.container_factory.container(item)
def __setitem__(self, i, item):
self.data[i] = item
def __delitem__(self, i):
del self.data[i]
def insert(self, i, item):
return self.data.insert(i, item)
def __len__(self):
return len(self.data)
| 624c18b911985db827b522adbd4fd34fe55abde0 | [
"Python"
] | 4 | Python | indraastra/pyrabj | d8be4900a45436878116f17493aa29ec75635b41 | d9df411c5d483de4c5f3c70d528807c3f46ef200 |
refs/heads/master | <file_sep>class MostInfluentialAlbums::CLI
def call
MostInfluentialAlbums::Scraper.new.make_albums
puts "Welcome to the 40 most influential albums of all time"
start
end
def start
puts "\nWhat album would you like to see? [1-40]\n"
print_albums
puts "\nChoose a corresponding number to learn more about each album? [1-40]"
input = gets.strip.to_i
album = is_valid_input(input)
puts ""
puts "Would you like related albums for #{album.album_name} [y/n]?"
input = gets.strip.downcase
if input == "y"
print_related_albums(album)
elsif input == "n"
puts "\nThank you! Have a great day!"
exit
else
puts "\nI don't understand that answer."
start
end
puts "\nWould you like to see another album? [y/n]"
input = gets.strip.downcase
if input == "y"
start
elsif input == "n"
puts "\nThank you! Have a great day!"
exit
else
puts "\nI don't understand that answer."
start
end
end
def print_albums
puts ""
puts "---------- albums ----------"
puts ""
MostInfluentialAlbums::Album.all.each.with_index do |album, index|
puts "#{index+1}. #{album.album_name} - #{album.artist_name}"
end
end
def print_album(album)
puts "\n----------- #{album.album_name} - by #{album.artist_name} -----------\n"
puts ""
puts " Release Year: #{album.album_year}\n"
puts ""
puts "\n-----------------Album Description--------------"
puts ""
puts "\n...#{album.album_description}\n"
end
def print_related_albums(album)
puts ""
puts " ---------- Related Albums and Artists ----------"
puts ""
puts "#{album.related_albums}"
end
def is_valid_input(input)
if (1..40).include?(input)
album = MostInfluentialAlbums::Album.find(input)
print_album(album)
album
else
puts "\nIncorrect response. Please choose again with a number between [1-40]!"
new_input = gets.strip.to_i
is_valid_input(new_input)
end
end
end
<file_sep>class MostInfluentialAlbums::Album
attr_reader :artist_name, :album_name, :album_year, :album_description, :related_albums
@@all = []
def self.new_from_index_page(album) #custom constructor.
self.new(
album.css(".album-artist").text,
album.css(".album-name").text,
album.css(".year").text,
album.css('.album-body').text.strip,
album.css('.album-footer li').text)
end
def initialize(artist_name=nil, album_name=nil, album_year=nil, album_description=nil, related_albums=[])
@artist_name = artist_name
@album_name = album_name
@album_year = album_year
@album_description = album_description
@related_albums = related_albums
@@all << self
end
def self.all
@@all
end
def self.find(id)
self.all[id-1]
end
end
<file_sep>class MostInfluentialAlbums::Scraper
def get_page
Nokogiri::HTML(open("https://www.rollingstone.com/interactive/most-groundbreaking-albums-of-all-time/"))
end
def scrape_albums_index
self.get_page.css(".album") #Full list of albums.
end
def make_albums #link to Album class.
scrape_albums_index.each do |album|
MostInfluentialAlbums::Album.new_from_index_page(album)
end
end
end<file_sep>require 'pry'
require 'nokogiri'
require 'open-uri'
require_relative '../lib/most_influential_albums/scraper'
require_relative '../lib/most_influential_albums/album'
require_relative '../lib/most_influential_albums/cli'
require_relative '../lib/most_influential_albums/version'
<file_sep>source "https://rubygems.org"
# Specify your gem's dependencies in most_influential_albums.gemspec
gem 'most_influential_albums'
gemspec
<file_sep>#!/usr/bin/env ruby
require_relative '../lib/most_influential_albums'
MostInfluentialAlbums::CLI.new.call | 3cc3494dad61cae17be889e33253d08b8e4ac804 | [
"Ruby"
] | 6 | Ruby | elevatemedfit/influential-albums-cli | ba22bbb69a843193db9781d1780fdd32dec14a31 | d0e86f78ed7df86966c28f9a9c83062ba929145c |
refs/heads/master | <repo_name>Rahul91/GreenGIT<file_sep>/README.md
#Introduction
For those who want to harvest there Github, this program is for you. But on a serious note, DO NOT use it.
#Working
Scraps something from the internet and pushes to your github repo. You can create a desktop shortcut for this proram, and by making the pogram executable, only by double-clicking the desktop shortcut, the scraped material is pushed to your github repo.
#Conclusion
Thus if you execute the program, it will push something to your repo, i.e. it will look, as if you have committed something to your codebase, which you actaully haven't.
This program is written just for fun, I do not want anyone to want this, just because they can fake pushes.
<file_sep>/setup.py
#!/usr/bin/python2.7
"""Git_fake project"""
from seuptools import find_packages, setup
setup(name = 'gitfake',
version = '0.1',
descripiton = "Git_fake module.",
long_description ="A module for faking git push.",
platforms = ["Linux"],
author = "<NAME>",
author_email = "<EMAIL>",
url= "https://github.com/Rahul91/gitfake",
license = "None",
packages = find_packages()
)<file_sep>/__init__.py
from gitfake import extract
__all__ = [extract, ]
<file_sep>/func_git.py
#!/usr/bin/python2.7
__verison__ = '1.1.1'
import urllib2
import string
import random
import datetime
import base64
import githubpy
import sys
import os
from githubpy import github
from bs4 import BeautifulSoup
token = '****************************************' #Github auth token for authorisation
def extract():
"""
Function to first go to the yahoo financial news page, then acts as a crawler
visit the latest news page, then etract the full news in a variable upload_string, which
is then encoded in UTF-64, which is then pushed as a file to my github repo.
"""
url = urllib2.urlopen("https://in.finance.yahoo.com/news/")
soup = BeautifulSoup(url)
var = soup.find("a", {"class":"title"})
con = var.get("href")
header = ''
for i in range(6, 40):
header = header + con[i]
heading = header + "..."
link = "https://in.finance.yahoo.com" + con
url1 = urllib2.urlopen(link)
soup1 = BeautifulSoup(url1)
var2 = soup1.find("div", {"itemprop":"articleBody"})
var3 = var2.text.encode('ascii', 'ignore')
upload_string = str(var3)
commit_message = str(datetime.datetime.now())
filename = heading.title()
gh = githubpy.github.GitHub(access_token=token)
encoded_file = base64.b64encode(upload_string)
gh.repos('Rahul91')('pytest')('contents')(filename).put(path=filename,message=commit_message, content=encoded_file)
print "Successfully pushed a new article titled : %s on %s \n" %(filename, commit_message)
raw_input("Press Enter to exit :)")
if __name__ == "__main__":
extract()
| 63b7334bed5dae65d7a7819cef51c07b35ee139a | [
"Markdown",
"Python"
] | 4 | Markdown | Rahul91/GreenGIT | 5ea4a350a4281466af6cd06ab70c2e208a64f801 | ff87974b46e88b5dbbc28dc8ff37337240ccc06a |
refs/heads/master | <repo_name>augustogoldoni-jaya/cit-poc<file_sep>/src/webmd/WebmdContext.js
import React from 'react';
export const WebmdContext = {
fontSize: '10px',
color: 'grey'
};
export const WebmdThemeContext = React.createContext(
WebmdContext
);
<file_sep>/src/App.js
import React from 'react';
import { StoresMap } from './StoresMap'
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
domain: window.location.hostname
};
}
render() {
const { domain } = this.state;
const Config = StoresMap.find((x) => x.Domain === domain );
const Store = Config.Component;
const ThemeContext = Config.ThemeContext;
return (
<div>
<ThemeContext.Provider value={Config.Context}>
<Store config={Config}/>
</ThemeContext.Provider>
</div>
)
}
};
export default App;
<file_sep>/src/StoresMap.js
import { DefaultContext, DefaultThemeContext } from './default/DefaultContext'
import WebmdStore from './webmd/WebmdStore';
import DefaultStore from './default/DefaultStore';
import { WebmdContext, WebmdThemeContext } from './webmd/WebmdContext'
import { OtherContext, OtherThemeContext } from './other/OtherContext'
export const StoresMap = [
{
Component: WebmdStore,
Context: WebmdContext,
Domain: process.env.REACT_APP_WEBMD_DOMAIN,
ThemeContext: WebmdThemeContext
},
{
Component: DefaultStore,
Context: DefaultContext,
Domain: process.env.REACT_APP_SICKLECELL_DOMAIN,
ThemeContext: DefaultThemeContext
},
{
Component: DefaultStore,
Context: OtherContext,
Domain: process.env.REACT_APP_OTHER_DOMAIN,
ThemeContext: OtherThemeContext
}
]
<file_sep>/src/default/DefaultStore.js
import React, { Component } from 'react';
import styled from "styled-components"
const Container = styled.div`
background-color: ${props => props.context.color};
font-size: ${props => props.context.fontSize};
`
class DefaultStore extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config
};
}
render() {
const { ThemeContext } = this.state.config;
return (
<ThemeContext.Consumer>
{context => context && <div>
{context.fontSize}
<br/>
{context.color}
<Container context={context}>
<h1>Hello World Default!</h1>
<form>
<input type="text" name="address"/>
<label>Address</label>
<input type="submit" />
</form>
</Container>
</div>
}
</ThemeContext.Consumer>
);
}
}
export default DefaultStore;
<file_sep>/src/webmd/WebmdStore.js
import React, { Component } from 'react';
class WebmdStore extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config
};
}
render() {
const { ThemeContext } = this.state.config;
return (
<ThemeContext.Consumer>
{context => context && <div>
{context.fontSize}
<br/>
{context.color}
<div style={{ fontSize: context.fontSize, color: context.color}}>
<h1>Hello World WebMD!</h1>
<span>Unsupported states: NY, AK, OH</span>
<form>
<input type="text" name="name"/>
<label>Zipcode</label>
<input type="submit" />
</form>
</div>
</div>
}
</ThemeContext.Consumer>
);
}
}
export default WebmdStore;
<file_sep>/src/other/OtherContext.js
import React from 'react';
export const OtherContext = {
fontSize: '15px',
color: 'yellow'
};
export const OtherThemeContext = React.createContext(
OtherContext
);
| b49381b22e466b149291a1ab4ee49452050fd1c1 | [
"JavaScript"
] | 6 | JavaScript | augustogoldoni-jaya/cit-poc | 970e55fd8354af974ba7e1d8dcf60b9667de196c | 103439f9dfedcde1255e0b9e56107f7e321aa793 |
refs/heads/master | <repo_name>nch1942/Datacom-Connect4<file_sep>/README.md
# DataComC4
<file_sep>/DataComC4/src/datacomc4/Player.java
package datacomc4;
/**
*
* @author <NAME>
*/
public interface Player {
public byte play(byte chosen);
public Game getGame();
}
<file_sep>/DataComC4/src/datacomc4/C4Server.java
package datacomc4;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* C4Client houses the main logic for the Server side, including instantiate
* necessary Objects for the Game to work. E.g. Player, Game and Socket, Session
*
* @author <NAME>
*/
public class C4Server {
private Session session;
private Player player;
private int serverPort;
private static final int BUFSIZE = 2; // Size of receive buffer
private ServerSocket serverSocket;
private Socket clientSocket;
private InputStream in;
private OutputStream out;
private Game game;
private int countGames;
public C4Server(int serverPort) throws IOException {
//Set seerver port we want to listen to
this.serverPort = serverPort;
//Create server socket
acceptClientRequest();
}
/**
* Open a new Socket for Client connection
*
* @throws IOException
*/
private void acceptClientRequest() throws IOException {
//Create socket to be able to accept client's connection request
serverSocket = new ServerSocket(this.serverPort);
//Interact with client
serviceConnection();
}
/**
* Start a new session for Player Socket
*/
private void beginSession() {
session = new Session();
session.createNewGame((byte) countGames);
countGames++;
game = session.getGame((byte) 0);
player = new AIPlayer(game);
}
/**
* Send And Receive Packet from Client
*
* @throws IOException
*/
private void serviceConnection() throws IOException {
//Size of message received from client
int receivedMessageSize = 2;
//byte array buffer
byte[] byteBuffer = new byte[BUFSIZE];
//Run loop forever accepting and serving connections
for (;;) {
System.out.println("Server Started\n");
clientSocket = serverSocket.accept();
in = clientSocket.getInputStream(); //To read data from socket
out = clientSocket.getOutputStream(); //To write data to socket
Board board;
//Recevieve until client closes connection (-1)
try {
while ((receivedMessageSize = in.read(byteBuffer)) != -1) {
//Client can start session
if (byteBuffer[0] == (byte) 0) {
//Begin session
System.out.println("Session started\n");
beginSession();
out.write(new byte[]{0, 0}, 0, receivedMessageSize);
} //Client wants to stop (2)
else if (byteBuffer[0] == (byte) 2) {
System.out.println("Thank you for playing\n");
continue;
} //Client won - create new game
else if (byteBuffer[0] == (byte) 3) {
System.out.println("The Game is ended. Waiting for Client to either start a new Game or Quit\n");
countGames++;
session.createNewGame((byte) countGames);
game = session.getGame((byte) countGames);
beginSession();
} //Client wants to make a move
else if (byteBuffer[0] == (byte) 1) {
board = game.getBoard();
//insert new client token
board.insertToken(byteBuffer[1], (byte) 1);
//AI player plays
byte tokenInput = player.play((byte) 0);
//Send client new move
out.write(new byte[]{1, tokenInput}, 0, receivedMessageSize);
}
}
// If Client Crash for some reason, Print out message, but Server will keep running
} catch (IOException e) {
System.out.println("========= WARNING ========= \n");
System.out.println("IT SEEMS CLIENT HAS CRASHED. SERVER STILL RUNNING\n");
System.out.println("The ERROR IS: " + e + "\n");
System.out.println("Closing Client Socket...\n");
clientSocket.close();
}
}
}
}
<file_sep>/DataComC4/src/datacomc4/Board.java
package datacomc4;
/**
* The Board represents the board in a Connect Four Game. Since the board
* contains Row and Column, we use a 2D byte[] to represent the board
*
* @author <NAME>
*/
public class Board {
private byte[][] board;
public Board() {
board = new byte[6][];
for (int i = 0; i < 6; i++) {
board[i] = new byte[7];
for (int j = 0; j < 7; j++) {
board[i][j] = 0;
}
}
}
/**
* Return the board of the current Game
*
* @return
*/
public byte[][] getBoard() {
return board;
}
/**
* Takes as input which column to insert into and what the token is (e.g. 1
* for player1, 2 for player2)
*
* @param column
* @param token
* @throws IllegalArgumentException if column is full
*/
public void insertToken(byte column, byte token) {
boolean inserted = false;
for (int i = 5; i >= 0; i--) {
if (board[i][column] == 0) {
board[i][column] = token;
inserted = true;
break;
}
}
if (!inserted) {
throw new IllegalArgumentException("Column is full!");
}
}
}
<file_sep>/DataComC4/src/datacomc4/gui/ConnectionController.java
package datacomc4.gui;
import datacomc4.C4Client;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
/**
* FXML Controller class. Responsible for building the GUI where user can enter
* IP address and Port number to connect the server. Establish C4Client Object
*
* @author <NAME>
*/
public class ConnectionController implements Initializable {
@FXML
private Button connectButton;
@FXML
private TextField ipInput;
@FXML
private TextField portInput;
@FXML
private Label ipWarn;
@FXML
private Label portWarn;
private C4Client client;
private static final Pattern PATTERN = Pattern.compile(
"^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
portInput.setText("50000");
}
/**
* Display a form for user to enter IP number and Port number. Validate user
* input. If the input is valid and server is running, this method will
* setup the connection Socket and display the main GUI for user to play.
*
* @param event The event that fired the handler
* @throws IOException
*/
@FXML
private void startGame(ActionEvent event) throws IOException {
String ip = ipInput.getText();
String port = portInput.getText();
if (ip.isEmpty() || !validateIP(ip)) {
ipWarn.setText("Invalid IP");
} else if (port.isEmpty() || !validatePort(port)) {
ipWarn.setText("");
portWarn.setText("Invalid Port");
} else {
System.out.println("Port Number and IP are good");
client = new C4Client(ip, Integer.parseInt(port));
System.out.println("Connecting to server...Stand by\n");
client.requestServerConnection();
if (client.getConnectionStatus()) {
Stage primaryStage = (Stage) connectButton.getScene().getWindow();
primaryStage.close();
FXMLLoader loader = new FXMLLoader(getClass().getResource("grid.fxml"));
Parent root = loader.load();
GridController game = loader.getController();
game.setConnection(client);
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("Connect Four");
stage.show();
} else {
System.out.println("Cannot Connect to Server. Please try again later\n");
}
}
}
public C4Client getClient() {
return this.client;
}
private boolean validateIP(String ip) {
return PATTERN.matcher(ip).matches();
}
private boolean validatePort(String port) {
int temp = 0;
try {
temp = Integer.parseInt(port);
} catch (Exception e) {
System.out.println("Error when trying to process the Port number: " + e + "\n");
return false;
}
return temp >= 0 && temp <= 65535;
}
}
<file_sep>/DataComC4/src/datacomc4/gui/GridController.java
package datacomc4.gui;
import datacomc4.C4Client;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
/**
* FXML Controller class. Responsible for building the GUI where user can
* interact with the Board, make their move, and display other necessary
* information for user to keep track of the Game
*
* @author <NAME>
*/
public class GridController implements Initializable {
@FXML
private GridPane grid;
@FXML
private Label coordinate;
@FXML
private Label turnDisplay;
@FXML
private Circle turnCircle;
@FXML
private Label playerCounter;
@FXML
private Label aiCounter;
@FXML
private Label winDisplay;
@FXML
private Button quitBtn;
@FXML
private Button resetBtn;
private int ROW = 0;
private int COL = 0;
private int playerWinCounter = 0;
private int AIwinCounter = 0;
private boolean isRed = true;
private final String humanTurn = "Human";
private final String aiTurn = "AI";
private Circle lastHighlight = new Circle();
private C4Client client;
private byte[] serverPackage;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
ROW = grid.getRowConstraints().size();
COL = grid.getColumnConstraints().size();
// Get the Client From ConnectionController
client = getClientFromConnectionController();
// Add circle to GridPane
addCircleToGrid();
addHandlerForQuitBtn();
addHandlerForResetBtn();
}
/**
* Create circles with a radius of 32, paint it black and put them in
* GridPane
*/
private void addCircleToGrid() {
for (int rowCount = 0; rowCount < ROW; rowCount++) {
for (int colCount = 0; colCount < COL; colCount++) {
Circle circle = new Circle(32, Paint.valueOf("black"));
addHandlerForCircle(circle);
grid.add(circle, colCount, rowCount);
GridPane.setHgrow(circle, Priority.ALWAYS);
GridPane.setVgrow(circle, Priority.ALWAYS);
GridPane.setHalignment(circle, HPos.CENTER);
GridPane.setValignment(circle, VPos.CENTER);
}
}
}
/**
* Add 2 handlers to each circle. One for when Player Click on the circle,
* and One for when Player Hover on the circle
*
* @param circle
*/
private void addHandlerForCircle(Circle circle) {
circle.setOnMouseClicked((MouseEvent e) -> {
onClickHandler(e);
});
circle.setOnMouseEntered((MouseEvent e) -> {
onHoverHandler(e);
});
}
/**
* Add handler for Quit button, which will close the Socket, and exit the
* program.
*/
private void addHandlerForQuitBtn() {
quitBtn.setOnAction((ActionEvent e) -> {
try {
onClickQuitBtn();
} catch (IOException error) {
System.out.println("There is a problem when trying to close the socket: " + error + "\n");
}
});
}
/**
* Add handler for Reset button, which will reset the Board, plus all the
* counters. But it keeps the Socket.
*/
private void addHandlerForResetBtn() {
resetBtn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
try {
onClickResetBtn();
} catch (IOException error) {
System.out.println("There is a problem why tring to reset the Game: " + error + "\n");
}
}
});
}
/**
* Handler for MouseEnter Event, which will highlight a potential legal move
* for each column when user hover their mouse on that column
*
* @param e The event that is fired upon hovering the mouse
*/
private void onHoverHandler(MouseEvent e) {
Circle source = (Circle) e.getSource();
int selectRowIndex = GridPane.getRowIndex(source);
int selectColumnIndex = GridPane.getColumnIndex(source);
// Increment both Column and Row by 1 to display for player correctly.
// Normally, we start at 1, not 0
selectRowIndex++;
selectColumnIndex++;
coordinate.setText("ROW: " + selectRowIndex + " COL: " + selectColumnIndex);
// Reset Column back to correct order (Start counting at 0)
selectColumnIndex--;
checkPotentialCircle(selectColumnIndex);
}
/**
* Handler for MouseClick Event, which will set the Circle at the legal move
* position at that column to either Red (Human Player) or Blue (AI Player).
* Then calls the necessary method to make that move registered in the Game
* logic, then check if the move is a winning move or not.
*
* IF the move is a winning move: Display appropriate message to Player,
* increase all the necessary counters. Disable the Grid, and ask if User
* want to Continue or Quit the Game.
*
* IF the move is NOT a winning move: Send the Player's move to Server, and
* listen to Server respond
*
* @param e The event that is fired upon hovering the mouse
*/
private void onClickHandler(MouseEvent e) {
Circle source = (Circle) e.getSource();
int selectColumnIndex = GridPane.getColumnIndex(source);
// Display the move of Player on the Grid, and registered that move to the Game logic
checkCircle(selectColumnIndex);
client.getHumanPlayer().play((byte) selectColumnIndex);
// Check if player's move is a winning move. 1 mean player
if (client.getHumanPlayer().getGame().playerHasWon((byte) 1)) {
playerWinCounter++;
playerCounter.setText((Integer.toString(playerWinCounter)));
winDisplay.setText("YOU WON THE MATCH.\nClick Reset to replay, , or Quit to Close the Game\n");
// Disable the Grid so user Cannot continue after they won
grid.setDisable(true);
// Exit the method
return;
} // --------------------- \\
// If the last move from Player is NOT a winning move, send the Player's move to server
else {
// Disable the Grid so user cannot make move while waiting for AI to respond
grid.setDisable(true);
try {
serverPackage = client.sendAndReceive(client.getSocket(), client.getPackage(), 1, selectColumnIndex);
} catch (IOException error) {
System.out.println("There is an error while trying to send the Client move to server: " + error + "\n");
}
}
// Get the move from the server
int serverMove = client.checkPackage(serverPackage);
// Display the move of AI on the Grid, and registered that move to the Game logic
checkCircle(serverMove);
client.getGame().getBoard().insertToken((byte) serverMove, (byte) 2);
// Check if AI's move is a winning move. 2 mean AI
if (client.getHumanPlayer().getGame().playerHasWon((byte) 2)) {
AIwinCounter++;
aiCounter.setText(Integer.toString(AIwinCounter));
winDisplay.setText("COMPUTER WON THE MATCH.\nClick Reset to replay, or Quit to Close the Game");
grid.setDisable(true);
// Exit the method
return;
}
// If 42 moves have been made, and noone win, then it's a draw
if (client.getGame().isDraw()) {
winDisplay.setText("IT IS A DRAW.\nClick Reset to replay, or Quit to Close the Game");
grid.setDisable(true);
// Exit the method
return;
}
// Enable the Grid again so User can Play
grid.setDisable(false);
}
/**
* Look for the circle that WILL BE a legit move of the given column
*
* @param col
*/
private void checkCircle(int col) {
int lastRowIndex = col + ((ROW - 1) * COL);
ObservableList<Node> childrens = grid.getChildren();
Node firstRow = childrens.get(col);
Node lastRow = childrens.get(lastRowIndex);
if (isBlack(lastRow)) {
switchColor(lastRow);
} else if (!isBlack(firstRow)) {
} else {
for (int i = lastRowIndex - COL; i >= 0; i -= COL) {
Node temp = childrens.get(i);
if (isBlack(childrens.get(i))) {
switchColor(temp);
break;
}
}
}
checkPotentialCircle(col);
}
/**
* Check if a circle has the color black or not
*
* @param node
* @return
*/
private boolean isBlack(Node node) {
Circle temp = (Circle) node;
return temp.getFill() == Paint.valueOf("black");
}
/**
* Switch the color of the circle to either red or blue
*
* @param node
*/
private void switchColor(Node node) {
Circle temp = (Circle) node;
if (isRed) {
temp.setFill(Paint.valueOf("Red"));
turnCircle.setFill(Paint.valueOf("Blue"));
turnDisplay.setText(aiTurn);
isRed = false;
} else {
temp.setFill(Paint.valueOf("Blue"));
turnCircle.setFill(Paint.valueOf("Red"));
turnDisplay.setText(humanTurn);
isRed = true;
}
}
/**
* Look for the circle that WILL be POTENTIALLY the next move of the given
* column
*
* @param col
*/
private void checkPotentialCircle(int col) {
int lastRowIndex = col + ((ROW - 1) * COL);
Node temp = null;
ObservableList<Node> childrens = grid.getChildren();
Node firstRow = childrens.get(col);
Node lastRow = childrens.get(lastRowIndex);
if (isBlack(lastRow)) {
highlightCircle(lastRow);
} else if (!isBlack(firstRow)) {
temp = childrens.get(col);
Circle tempCircle = (Circle) temp;
tempCircle.setStroke(Paint.valueOf("black"));
tempCircle.setStrokeWidth(1);
} else {
for (int i = lastRowIndex - COL; i >= 0; i -= COL) {
temp = childrens.get(i);
if (isBlack(childrens.get(i))) {
highlightCircle(temp);
break;
}
}
}
}
/**
* Highlight the circle that will be the next move of a column
*
* @param node
*/
private void highlightCircle(Node node) {
Circle temp = (Circle) node;
if (temp != lastHighlight) {
temp.setStrokeWidth(4.5);
temp.setStroke(Paint.valueOf("Aqua"));
lastHighlight.setStroke(Paint.valueOf("black"));
lastHighlight.setStrokeWidth(1);
}
lastHighlight = temp;
}
/**
* Handler for Quit button, which will close the socket, and quit the game.
*/
private void onClickQuitBtn() throws IOException {
Stage stage = (Stage) quitBtn.getScene().getWindow();
// Send a packet of byte[2,0] to indicate the Client is done playing, and going to quit the game
client.sendOnly(client.getSocket(), serverPackage, 2, 0);
client.getSocket().close();
stage.close();
System.out.println("Client has quit the Game. Socket is closed\n");
}
/**
* Handler for Reset button, which will reset the Grid, all counters and
* settings of the game.
*/
private void onClickResetBtn() throws IOException {
// Send a packet of byte[3,0] to indicate the Client is done playing, and going to quit the game
client.sendOnly(client.getSocket(), serverPackage, 3, 0);
isRed = true;
turnCircle.setFill(Paint.valueOf("Red"));
turnDisplay.setText(humanTurn);
winDisplay.setText("");
// Set all the circle in the Grid's color back to black
resetGrid();
client.restartClient();
// Re-enable the Grid
grid.setDisable(false);
System.out.println("Client has restarted...Initialize new Game\n");
}
/**
* Set all Circle in the Grid back to Black
*/
private void resetGrid() {
ObservableList<Node> childrens = grid.getChildren();
for (Node node : childrens) {
Circle temp = (Circle) node;
temp.setFill(Paint.valueOf("Black"));
}
}
/**
* Get the C4Client Object from ConnectionController, which will be used to
* access the Socket Object.
*
* @return
*/
private C4Client getClientFromConnectionController() {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("connection.fxml"));
try {
loader.load();
} catch (IOException error) {
System.out.println("There is an error while passing the Socket between controllers: " + error);
}
ConnectionController connection = loader.getController();
// Getting the Socket Object
return connection.getClient();
}
/**
* Set the Client and pass it between Controller
*
* @param client
*/
public void setConnection(C4Client client) {
this.client = client;
}
}
| b5f370ff2a54d7b9bb966a97b05637e3ceb7bbb0 | [
"Markdown",
"Java"
] | 6 | Markdown | nch1942/Datacom-Connect4 | ae1dc0a6734e30084892d4335ca9b2464c9a72d0 | 53b9a49135551799fe974803a9f8a429c3c8bcba |
refs/heads/master | <repo_name>kristinasavova/tobias-speiser-portfolio<file_sep>/src/components/Portfolio.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import Table from './Table';
import List from './List';
import Form from './Form'; // contact form
import Footer from './Footer';
class Portfolio extends Component {
state = {
isDesktop: false
}
componentDidMount () {
this.updatePredicate ();
window.addEventListener ('resize', this.updatePredicate);
}
componentWillUnmount () {
window.removeEventListener ('resize', this.updatePredicate);
}
/**
* Update state if width of the window gets greater than 768 px
*/
updatePredicate = () => {
this.setState ({ isDesktop: window.innerWidth > 768 });
}
render () {
return (
<React.Fragment>
<header>
<div className='button about'>
<Link to='/about' className='nav-link'>ABOUT ME</Link>
</div>
</header>
<div className='content'>
<div className='main-info'>
<h2 className='heading'>TOBIAS SPEISER | MODELING & LOOK DEV</h2>
<div className='video-wrapper'>
<iframe
title='Showreel'
src='https://www.youtube.com/embed/sxNVFklby-Q'
frameBorder='0'
scrolling='no'
allow='accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture'
allowFullScreen />
</div>
</div>
{ // Render Table if desktop or list if not
this.state.isDesktop ?
<Table /> : <List />
}
<div className='contact-form'>
<h3>CONTACT ME IF YOU HAVE A QUESTION</h3>
<Form />
</div>
</div>
<Footer />
</React.Fragment>
);
}
};
export default Portfolio; <file_sep>/src/components/Form.js
import React, { Component } from 'react';
import axios from 'axios';
class Form extends Component {
state = {
name: '',
email: '',
message: ''
}
/**
* A method to send a POST request to the server when the form gets submitted
* @param {object} event
*/
handleSubmit = event => {
event.preventDefault ();
const { name, email, message } = this.state; // destructure data from state
axios ({ // send POST request to the server
method: 'POST',
url: 'http://localhost:4444/send',
data: { name, email, message }
})
.then (response => {
if (response.data.msg === 'SUCCESS') {
alert ('Message sent');
this.resetForm ();
} else if (response.data.msg === 'FAIL') {
alert ('Message failed to send')
}
})
.catch (error => console.log (error));
}
/**
* A method to reset the form
*/
resetForm = () => {
this.setState ({
name: '',
email: '',
message: ''
});
document.getElementById ('contact-form').reset ();
}
render () {
return (
<form
id='contact-form'
onSubmit={ (event) => this.handleSubmit (event) }
method='POST' >
<div>
<label htmlFor='name'>NAME</label>
<input
type='text'
id='name'
onChange={ event => this.setState ({ name: event.target.value })}
value={this.state.name}
required />
</div>
<div>
<label htmlFor='email'>EMAIL ADDRESS</label>
<input
type='email'
id='email'
onChange={ event => this.setState ({ email: event.target.value })}
value={this.state.email}
required />
</div>
<div>
<label htmlFor='message'>MESSAGE</label>
<textarea
type='text'
rows='5'
id='message'
onChange={ event => this.setState ({ message: event.target.value })}
required />
</div>
<button type='submit'>SEND</button>
</form>
);
}
};
export default Form; <file_sep>/src/components/About.js
import React from 'react';
import { Link } from 'react-router-dom';
import Nav from './Nav';
const About = () => {
return (
<React.Fragment>
<div className='main-content'>
<div className='column details'>
<Nav />
<div className='description'>
<p>Hello, my name is <NAME>. I’m a 3D Generalist based in Basel, Switzerland. I have competencies in all basics of 3D animation, yet I am most specialised in modeling and look development.</p>
<p>In Summer 2018 I graduated with a Bachelors Degree in animation from the Lucerne University of Applied Sciences and Arts. Since then I have been working in Animation and Archviz in London and Zurich.</p>
<p>For any questions or enquiries, feel free to contact me at <strong><EMAIL></strong></p>
</div>
<div className='button home'>
<Link to='/' className='nav-link'>HOME</Link>
</div>
</div>
<div className='column photo' />
</div>
</React.Fragment>
);
};
export default About;<file_sep>/src/App.js
import React from 'react';
import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom';
import About from './components/About';
import Portfolio from './components/Portfolio';
const App = () => {
return (
<div className='wrapper'>
<BrowserRouter>
<Switch>
<Redirect exact from='/' to='/home' />
<Route path='/home' component={Portfolio} />
<Route path='/about' component={About} />
</Switch>
</BrowserRouter>
</div>
);
};
export default App;
<file_sep>/src/components/List.js
import React from 'react';
const List = () => {
return (
<div className='skills-list'>
<ul>
<li>
<img
src='/images/maya-logo.png'
width='auto'
height='35'
alt='Maya Logo' />
<img
src='/images/blender-logo.png'
width='auto'
height='40'
alt='Blender Logo' />
</li>
<li>
<img
src='/images/3ds-max-logo.jpg'
width='auto'
height='35'
alt='3DS Max Logo' />
</li>
<li>
<img
src='/images/cinema-4d-logo.png'
width='auto'
height='70'
alt='Cinema 4D Logo' />
<img
src='/images/zbrush-logo.png'
width='auto'
height='80'
alt='ZBrush Logo' />
</li>
<br />
<li>
<img
src='/images/redshift-logo.png'
width='auto'
height='70'
alt='Redshift Logo' />
</li>
<li>
<img
src='/images/arnold-logo.png'
width='auto'
height='25'
alt='Arnold Logo' />
<img
src='/images/corona-logo.png'
width='auto'
height='25'
alt='Corona Logo' />
</li>
<li>
<img
src='/images/renderman-logo.png'
width='auto'
height='70'
alt='RenderMan Logo' />
</li>
<br />
<li>
<img
src='/images/s-painter-logo.jpg'
width='auto'
height='80'
alt='Substance Painter Logo' />
<img
src='/images/s-designer-logo.jpg'
width='auto'
height='80'
alt='Substance Designer Logo' />
</li>
<li>
<img
src='/images/photoshop-logo.png'
width='auto'
height='45'
alt='Photoshop Logo' />
<img
src='/images/mari-logo.jpeg'
width='auto'
height='50'
alt='Mari Logo' />
</li>
<br />
<li>
<img
src='/images/after-effects.png'
width='auto'
height='45'
alt='After Effects Logo' />
<img
src='/images/premiere-pro.png'
width='auto'
height='45'
alt='Premiere Pro' />
</li>
<li>
<img
src='/images/nuke-logo.png'
width='auto'
height='40'
alt='Nuke Logo' />
</li>
</ul>
</div>
);
};
export default List; | 4a0bd43d4eaee4c56a3b036a10393d4c8cfbb5d0 | [
"JavaScript"
] | 5 | JavaScript | kristinasavova/tobias-speiser-portfolio | 0dbe4ab1c3ab370927744cb41a9611a8cc5edb6e | 05ca38039d9d7550a6ae854bb14bac1fb903cf32 |
refs/heads/master | <repo_name>Qudratullo/LoadTester<file_sep>/Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
private static List<Statistics> statisticsList = new ArrayList<>();
private static long startTime;
private static long endTime;
private static int NUMBER_OF_CLIENTS = 1;
static int INTERVAL_BETWEEN_REQUESTS = 0; // in milliseconds
static int COUNT_REQUESTS = 1;
public static void main(String[] args) {
parseArguments(args);
startTime = System.currentTimeMillis();
System.out.println("Тестирование...");
List<CompletableFuture<Statistics>> futures = Stream.generate(() -> CompletableFuture.supplyAsync(() -> new CalculationStatistics().calculate()))
.limit(NUMBER_OF_CLIENTS).collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
statisticsList = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
endTime = System.currentTimeMillis();
printStatistics();
}
private static void printStatistics() {
long minTime = Long.MAX_VALUE;
long maxTime = Long.MIN_VALUE;
long sumTime = 0;
int sumSuccess = 0;
for (Statistics statistics : statisticsList) {
minTime = Math.min(minTime, statistics.getMinTime());
maxTime = Math.max(maxTime, statistics.getMaxTime());
sumTime += statistics.getSumTime();
sumSuccess += statistics.getCountSuccess();
}
System.out.println("Number of clients:\t" + NUMBER_OF_CLIENTS);
System.out.println("Number of requests for one client:\t" + COUNT_REQUESTS);
System.out.println("Number of total requests:\t" + NUMBER_OF_CLIENTS * COUNT_REQUESTS);
System.out.println("Test time:\t" + (endTime - startTime) / 1000. + " s");
System.out.println();
System.out.println("Min time:\t" + minTime + " ms");
System.out.println("Max time:\t" + maxTime + " ms");
System.out.println("Avg time:\t" + sumTime / (NUMBER_OF_CLIENTS * COUNT_REQUESTS) + " ms");
System.out.println("Success responses:\t" + sumSuccess * 100 / (NUMBER_OF_CLIENTS * COUNT_REQUESTS) + "%");
}
private static void parseArguments(String[] args) {
for (int i = 0; i < args.length; i += 2) {
if (i == args.length - 1)
break;
switch (args[i]) {
case "-u":
setCountUsers(args[i + 1]);
break;
case "-r":
setCountRequests(args[i + 1]);
break;
case "-i":
setInterval(args[i + 1]);
break;
}
}
}
private static void setCountUsers(String countString) {
try {
NUMBER_OF_CLIENTS = Integer.parseInt(countString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
private static void setCountRequests(String countString) {
try {
COUNT_REQUESTS = Integer.parseInt(countString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
private static void setInterval(String intervalString) {
try {
INTERVAL_BETWEEN_REQUESTS = Integer.parseInt(intervalString);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
| 843892e63b70fd709e5bc0295669b3572f2b8247 | [
"Java"
] | 1 | Java | Qudratullo/LoadTester | c4fc26689dca701b4a4434a6d525fe20fbf72035 | bc20b05f881551f6ee9530e945f33c2e86c3dd25 |
refs/heads/master | <repo_name>DappStarter/flowery-nibliji<file_sep>/packages/dapplib/truffle-config.js
require('@babel/register');
({
ignore: /node_modules/
});
require('@babel/polyfill');
const HDWalletProvider = require('@truffle/hdwallet-provider');
let mnemonic = 'grid gloom tape slab chest note rifle clump hockey ensure olympic general';
let testAccounts = [
"0x73ff4f2934b035e2f7a9b27d2d782e11dc39be654af5af0872075dc19137f479",
"0xac028d58d9469f30dc0202c2994af605c2d329e768f1c9571373548669065763",
"0xf6816626bf69e0dff368960c3155cfdd119e6708c5e8b43ef69f78411a924d95",
"<KEY>",
"0x2591bf6faecde7b96a612d549a6c6cafede90d19a4b896b89583276fa1fc669b",
"<KEY>",
"0x53855037b3348ac9be6381a74012bea2d19c81754d81aae7ef3a184464fa96ea",
"<KEY>",
"<KEY>",
"0x3342a434ba32f1859ca5ba0beb0f1e8c6c37ece3712d51657606941b2bf8293c"
];
let devUri = 'http://127.0.0.1:7545/';
module.exports = {
testAccounts,
mnemonic,
networks: {
development: {
uri: devUri,
provider: () => new HDWalletProvider(
mnemonic,
devUri, // provider url
0, // address index
10, // number of addresses
true, // share nonce
`m/44'/60'/0'/0/` // wallet HD path
),
network_id: '*'
}
},
compilers: {
solc: {
version: '^0.5.11'
}
}
};
| b9fb2b99e67bd3f80fda11c8599e1dd973109e61 | [
"JavaScript"
] | 1 | JavaScript | DappStarter/flowery-nibliji | ee2a4de6ae36c74c8a5d341c16cc3e8fcd0aeaa5 | a0bc09e1d1e07197eba2aba0b61fc82c2e300cd3 |
refs/heads/master | <repo_name>wideopenspaces/acts-as-taggable-on<file_sep>/acts-as-taggable-on.gemspec
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{wideopenspaces-acts-as-taggable-on}
s.version = "1.0.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["<NAME>", "<NAME>"]
s.date = %q{2009-01-24}
s.description = %q{Acts As Taggable On provides the ability to have multiple tag contexts on a single model in ActiveRecord. It also has support for tag clouds, related items, taggers, and more.}
s.email = %q{<EMAIL>}
s.files = ["VERSION.yml", "generators/acts_as_taggable_on_migration", "generators/acts_as_taggable_on_migration/acts_as_taggable_on_migration_generator.rb", "generators/acts_as_taggable_on_migration/templates", "generators/acts_as_taggable_on_migration/templates/migration.rb", "lib/acts-as-taggable-on.rb", "lib/acts_as_taggable_on", "lib/acts_as_taggable_on/acts_as_taggable_on.rb", "lib/acts_as_taggable_on/acts_as_tagger.rb", "lib/acts_as_taggable_on/tag.rb", "lib/acts_as_taggable_on/tag_list.rb", "lib/acts_as_taggable_on/tagging.rb", "lib/acts_as_taggable_on/tags_helper.rb", "spec/acts_as_taggable_on", "spec/acts_as_taggable_on/acts_as_taggable_on_spec.rb", "spec/acts_as_taggable_on/acts_as_tagger_spec.rb", "spec/acts_as_taggable_on/tag_list_spec.rb", "spec/acts_as_taggable_on/tag_spec.rb", "spec/acts_as_taggable_on/taggable_spec.rb", "spec/acts_as_taggable_on/tagger_spec.rb", "spec/acts_as_taggable_on/tagging_spec.rb", "spec/schema.rb", "spec/spec.opts", "spec/spec_helper.rb"]
s.has_rdoc = true
s.homepage = %q{http://github.com/wideopenspaces/acts-as-taggable-on}
s.rdoc_options = ["--inline-source", "--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.1}
s.summary = %q{Tagging for ActiveRecord with custom contexts and advanced features.}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
| c30003500e02e8ea36901110ec4bf61a3219a0a3 | [
"Ruby"
] | 1 | Ruby | wideopenspaces/acts-as-taggable-on | a464d0b91f7f5cb663a3b75bd56118c5bb276744 | 93bc7cbd6c1a2536b6f048e93ae1b5da9fd0b471 |
refs/heads/master | <file_sep>package ar.iua.edu.webIII.proyecto.viano.business;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.InvalidArgumentException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.Usuario;
public interface IUsuarioBusiness {
public Usuario load(String username) throws BusinessException, NotFoundException;
public Usuario save(Usuario usuario) throws BusinessException;
public Usuario update(String field, String password, Object newValue, String name) throws BusinessException, NotFoundException, InvalidArgumentException;
}
<file_sep>import {List} from "./list.model"
export class Sprint {
id: number;
name: string;
lists: List[];
startDate: Date;
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.persistence;
import ar.iua.edu.webIII.proyecto.viano.model.SprintList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface ListRepository extends JpaRepository<SprintList, Integer> {
Optional<List<SprintList>> findBySprintId(int idSprint);
Optional<SprintList> findByNameAndSprintId(String name, int idSprint);
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { LoginService } from '../services/login.service';
import Swal from 'sweetalert2';
import { NotifierService } from 'angular-notifier';
@Component({
selector: 'app-nav-bar',
templateUrl: './nav-bar.component.html',
styleUrls: ['./nav-bar.component.scss']
})
export class NavBarComponent implements OnInit {
public user: any = '';
oldPassword = "";
newPassword = ""
constructor(private router: Router, private authService: LoginService, private notifier: NotifierService) { }
ngOnInit() {
if (localStorage.getItem('user')) {
//this.user = localStorage.getItem('user').charAt(0).toUpperCase() + localStorage.getItem('user').slice(1).toLowerCase();
}
console.log(this.user);
this.authService.isLogged.subscribe(
data => {
//console.log(data);
if (!data.logged)
this.logout();
},
error => {
console.log(error);
}
);
}
clearModal() {
this.oldPassword = "";
this.newPassword = "";
}
changePassword() {
if (this.isEmpty(this.oldPassword) || this.isEmpty(this.newPassword)) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El password no puede estar vacio!',
})
this.clearModal();
return;
}
this.authService.changeUserData(this.oldPassword, this.newPassword, "password")
.subscribe(resp => {
console.log(resp)
this.notifier.notify("succes", "Password cambiado correctamente" );
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.logout();
// this.router.navigateByUrl('login');
this.notifier.notify("info", "Logging out. Su token ha expirado" );
})
} else {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: err.error,
})
this.clearModal();
}
})
}
isEmpty(elem) {
return !elem || elem.trim().length == 0;
}
navigateTo(destination) {
//this.sharedService.navigateTo(destination);
}
navigateHome() {
this.router.navigateByUrl('sprint/home')
}
logout() {
this.authService.logout();
//this.router.navigate(['login']);
this.router.navigateByUrl('login');
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.business.implementation.UsuarioBusiness;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeAll;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UsuarioBusinessTest {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
UsuarioBusiness usuarioBusiness;
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@BeforeAll
public static void setup() {
}
@Test
public void testLoadSuccess() throws BusinessException, NotFoundException {
String username = "rodrigoUserAdmin";
assertEquals("rodrigoUserAdmin",usuarioBusiness.load(username).getUsername());
assertEquals("<EMAIL>",usuarioBusiness.load(username).getEmail());
assertEquals("Rodrigo User Admin",usuarioBusiness.load(username).getFirstName());
assertEquals("Viano",usuarioBusiness.load(username).getLastName());
assertEquals("$2a$10$W7HgX4V4eBYX7KilSCTwv.kOwuQ9l9tVV5eTTtN.yk84VwC0clso.",usuarioBusiness.load(username).getPassword());
assertEquals(null,usuarioBusiness.load(username).getSessionToken());
}
@Test
public void testLoadFailure() throws BusinessException, NotFoundException {
String username = "rodrigoUserAdmin";
assertNotEquals("admin1",usuarioBusiness.load(username).getUsername());
assertNotEquals("<EMAIL>",usuarioBusiness.load(username).getEmail());
assertNotEquals("Admin",usuarioBusiness.load(username).getFirstName());
assertNotEquals("García1",usuarioBusiness.load(username).getLastName());
assertNotEquals(".hr.oNe3YbI9rV5qeprPKoL7OUw7TvhO",usuarioBusiness.load(username).getPassword());
assertNotEquals("$2a$10$yNF2FaFAiV2MbTdCQVarE.hr.oNe3YbI9rV5qeprPKoL7OUw7TvhO",usuarioBusiness.load(username).getSessionToken());
}
@Test(expected = NotFoundException.class)
public void testLoadNotFoundException() throws BusinessException, NotFoundException {
String username = "admin2";
usuarioBusiness.load(username);
expectedEx.expect(NotFoundException.class);
expectedEx.expectMessage("No se encuentra el usuario con username="+username);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { LoginService } from '../services/login.service';
@Injectable()
export class BasicHttpInterceptor implements HttpInterceptor {
constructor(public authService: LoginService) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
//console.log("url", request.url)
//console.log("request", request)
if (request.url !== environment.urlApiBase + `dologin`) {
request = request.clone({
setHeaders: {
'Authorization': "Bearer " + localStorage.getItem('token')
}
});
}
//console.log("request 2 ", request)
return next.handle(request);
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business.implementation;
import java.util.Date;
import java.util.Optional;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.IAuthTokenService;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ar.iua.edu.webIII.proyecto.viano.model.AuthToken;
import ar.iua.edu.webIII.proyecto.viano.persistence.AuthTokenRespository;
@Service
public class AuthTokenService implements IAuthTokenService {
@Autowired
private AuthTokenRespository authTokenDAO;
@Override
public AuthToken save(AuthToken at) throws BusinessException {
try {
return authTokenDAO.save(at);
} catch (Exception e) {
throw new BusinessException(e);
}
}
@Override
public AuthToken load(String series) throws BusinessException, NotFoundException {
Optional<AuthToken> atO;
try {
atO = authTokenDAO.findById(series);
} catch (Exception e) {
throw new BusinessException(e);
}
if (!atO.isPresent())
throw new NotFoundException("No se encuentra el token de autenticación serie=" + series);
return atO.get();
}
@Override
public void delete(AuthToken at) throws BusinessException {
try {
authTokenDAO.delete(at);
} catch (Exception e) {
// throw new ServiceException(e);
}
}
@Override
public void purgeTokens() throws BusinessException {
try {
authTokenDAO.purgeToDate(new Date());
authTokenDAO.purgeDefault(new Date());
authTokenDAO.purgeFromToDate(new Date());
authTokenDAO.purgeRequestLimit();
} catch (Exception e) {
throw new BusinessException(e);
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SprintService {
constructor(private http: HttpClient) { }
getAllSprints(): Observable<any> {
return this.http.get<any>(environment.urlApiRest + `sprints`)
.pipe(map(resp => {
return resp;
}));
}
addSprint(sprint): Observable<any> {
const data = {
name: sprint.name,
startDate: sprint.startDate
}
return this.http.post<any>(environment.urlApiRest + `sprints`, data)
.pipe(map(resp => {
return resp;
}));
}
editSprint(sprint): Observable<any> {
const data = {
name: sprint.name,
startDate: sprint.startDate
}
return this.http.put<any>(environment.urlApiRest + `sprints/${sprint.id}`, data)
.pipe(map(resp => {
return resp;
}))
}
deleteSprint(id: number): Observable<any> {
return this.http.delete<any>(environment.urlApiRest + `sprints/${id}`)
.pipe(map(resp => {
// console.log(resp)
return resp;
}))
}
getSprint(id: number): Observable<any> {
return this.http.get<any>(environment.urlApiRest + `sprints/${id}`)
.pipe(map(resp => {
// console.log(resp)
return resp;
}))
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business.implementation;
import ar.iua.edu.webIII.proyecto.viano.business.ISprintBusiness;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.DateNullException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.InvalidSprintException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.Sprint;
import ar.iua.edu.webIII.proyecto.viano.persistence.SprintRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Optional;
@Service
public class SprintBusiness implements ISprintBusiness {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private SprintRepository sprintDao;
@Override
public List<Sprint> list() throws BusinessException {
try {
return sprintDao.findAll();
} catch (Exception e) {
log.error("error al obtener todos los sprints" + e.getMessage());
throw new BusinessException(e);
}
}
@Override
public Sprint save(Sprint sprint) throws BusinessException, DateNullException, InvalidSprintException {
Optional<Sprint> op = null;
op = sprintDao.findByName(sprint.getName());
if (op.isPresent()) {
log.error("Error al crear sprint \n El sprint con el nombre " + sprint.getName() + " ya existe");
throw new InvalidSprintException("El sprint con el nombre " + sprint.getName() + " ya existe");
}
try {
sprint = sprintDao.save(sprint);
log.info("Se creo el sprint " + sprint);
return sprint;
} catch (Exception e) {
log.error("Error al crear sprint " + e.getMessage());
throw new BusinessException(e);
}
}
@Override
public void remove(int id) throws BusinessException, NotFoundException {
Optional<Sprint> op = null;
op = sprintDao.findById(id);
if (!op.isPresent()) {
log.error("No se ecuentra el sprint con id= " + id);
throw new NotFoundException("No se ecuentra el sprint con id= " + id);
}
try {
sprintDao.deleteById(id);
} catch (Exception e) {
log.error("Error al eliminar el sprint " + e.getMessage());
throw new BusinessException(e);
}
}
@Override
public Sprint findSprintById(int sprintId) throws NotFoundException, BusinessException {
Optional<Sprint> op = null;
op = sprintDao.findById(sprintId);
if (!op.isPresent()) {
log.error("No se ecuentra el sprint con id= " + sprintId);
throw new NotFoundException("No se ecuentra el sprint con id= " + sprintId);
}
try {
return op.get();
} catch (Exception e) {
log.error("Error al eliminar el sprint " + e.getMessage());
throw new BusinessException(e);
}
}
@Override
public void isValid(Sprint sprint) throws InvalidSprintException, DateNullException {
if (sprint.getName() == null) {
log.error("El nombre del sprint no puede ser null.");
throw new InvalidSprintException("El nombre del sprint no puede ser null.");
}
if (sprint.getStartDate() == null) {
log.error("La fecha de comienzo no puede ser null");
throw new DateNullException("La fecha de comienzo no puede ser null");
}
/*if (sprint.getStartDate().before(new Date())) {
log.error("El comienzo del sprint debe ser despues o igual a la fecha actual\"");
throw new InvalidSprintException("El comienzo del sprint debe ser despues o igual a la fecha actual");
}*/
}
@Override
public Sprint update(int idSprint, Sprint sprint) throws
NotFoundException, BusinessException, InvalidSprintException {
Optional<Sprint> op = null;
op = sprintDao.findById(idSprint);
if (!op.isPresent()) {
log.error("No se ecuentra el sprint con id= " + idSprint);
throw new NotFoundException("No se ecuentra el sprint con id= " + idSprint);
}
if (!op.get().getName().equalsIgnoreCase(sprint.getName())) {
log.error("Error al actualizar el sprint \n El nombre de sprint no se puede modificar ");
throw new InvalidSprintException("Error al actualizar el sprint \n El nombre de sprint no se puede modificar ");
}
try {
sprint = sprintDao.save(sprint);
log.info("Se creo el sprint " + sprint);
return sprint;
} catch (Exception e) {
log.error("Error al crear sprint " + e.getMessage());
throw new BusinessException(e);
}
}
}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListSprintComponent } from './list-sprint.component';
describe('ListSprintComponent', () => {
let component: ListSprintComponent;
let fixture: ComponentFixture<ListSprintComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ListSprintComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ListSprintComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Task } from "./task.model";
import {Sprint} from "./sprint.model";
export class List {
id: number;
name: string;
sprint: Sprint;
task: Task[];
constructor(id=0, name ="", tasks = []){
this.id = id;
this.name = name;
this.task = tasks;
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business;
import java.util.List;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.*;
import ar.iua.edu.webIII.proyecto.viano.model.SprintList;
import ar.iua.edu.webIII.proyecto.viano.model.Task;
public interface ITaskBusiness {
public List<Task> list() throws BusinessException;
public Task save(Task task) throws BusinessException, InvalidPriorityException, DateNullException, AssignNotAllowedException, ListDoesNotExistException, InvalidTaskException;
public void remove(int id) throws BusinessException, NotFoundException;
// update se usa para cambiar datos de las tareas( estimacion, descripcion y prioridad) , pero no para moverlas
public Task update(int id, Task task) throws BusinessException, InvalidPriorityException, DateNullException, InvalidEstimationException, CannotMoveException, NotFoundException;
public Task moveTask(int id, int idList) throws BusinessException;
public Task findOneById(int idTarea) throws BusinessException, NotFoundException;
public List<Task> findAllBySprintOrderByPriority(int id, String order) throws BusinessException, NotFoundException;
public List<Task> findAllBySprintOrderByCreation(int id, String order) throws BusinessException, NotFoundException;
public List<Task> getAllBySprintAndEstimation(int id, int estimation) throws BusinessException, NotFoundException;
public List<Task> getAllByListIdAndSprintNameOrderByCreation(int idList, String sprintName, String order) throws BusinessException, NotFoundException;
public List<Task> getAllByListIdAndSprintNameOrderByPriority(int idList, String sprintName,String order) throws BusinessException, NotFoundException;
public List<Task> getAllByListNameId(int idList) throws BusinessException, NotFoundException;
public void isValid(Task task) throws InvalidPriorityException, DateNullException, InvalidNameException, InvalidTaskException;
public void canMove(int idTask, int idList) throws BusinessException, InvalidEstimationException, CannotMoveException, NotFoundException, DateNullException, InvalidTaskException, InvalidNameException, InvalidPriorityException;
}
<file_sep>import { List } from './list.model';
export class Task {
id: number;
name: string;
description: string;
estimation: number;
priority: string;
creation: Date;
modification: Date;
list: List;
listId: number;
constructor (id=0,
name= "",
description= "",
creation= new Date(),
modification= creation,
priority= "",
estimation= 0){
this. id = id;
this.name = name;
this.description = description;
this.modification = modification;
this.priority = priority;
this.estimation = estimation;
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.persistence;
import ar.iua.edu.webIII.proyecto.viano.model.JWTAuth;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.Optional;
@Repository
public interface JWTAuthRepository extends JpaRepository<JWTAuth, String> {
@Transactional
@Modifying
//@Query(value = "DELETE FROM jwt_auth WHERE tipo='DEFAULT' AND DATE_ADD(last_used, INTERVAL validity_seconds SECOND)<?", nativeQuery = true)
@Query(value = "DELETE FROM jwt_auth WHERE hasta<?", nativeQuery = true)
public int purgeJWT(Date hasta);
public Optional <JWTAuth> findByToken(String token);
/*@Transactional
@Modifying
@Query(value = "DELETE FROM jwt_auth WHERE tipo='TO_DATE' AND hasta<?", nativeQuery = true)
public int purgeToDate(Date hasta);
@Transactional
@Modifying
@Query(value = "DELETE FROM jwt_auth WHERE tipo='FROM_TO_DATE' AND hasta<<?", nativeQuery = true)
public int purgeFromToDate(Date hasta);
@Transactional
@Modifying
@Query(value = "DELETE FROM jwt_auth WHERE tipo='REQUEST_LIMIT' AND request_count>=request_limit", nativeQuery = true)
public int purgeRequestLimit();*/
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.IUsuarioBusiness;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.Usuario;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class PersistenceUserDetailService implements UserDetailsService {
@Autowired
private PasswordEncoder pe;
@Autowired
private IUsuarioBusiness usuarioService;
private Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*
Usuario u=new Usuario();
u.setUsername(username);
u.setPassword(pe.encode("123"));
u.setEnabled(true);
u.setAccountNonExpired(true);
u.setAccountNonLocked(true);
u.setCredentialsNonExpired(true);
*/
Usuario u;
try {
u = usuarioService.load(username);
} catch (BusinessException e) {
log.error(e.getMessage(),e);
throw new RuntimeException();
} catch (NotFoundException e) {
throw new UsernameNotFoundException(e.getMessage());
}
return u;
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.JWTAuth;
import ar.iua.edu.webIII.proyecto.viano.persistence.UsuarioRepository;
import ar.iua.edu.webIII.proyecto.viano.business.IJWTAuthService;
import ar.iua.edu.webIII.proyecto.viano.model.Usuario;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class JWTAuthTokenFilter extends OncePerRequestFilter {
private IJWTAuthService jwtAuthService;
private UsuarioRepository usuariosDAO;
private Logger log = LoggerFactory.getLogger(this.getClass());
public static String AUTH_HEADER = "Authorization";
public static String TOKEN_PREFIX = "Bearer ";
public static String AUTH_HEADER_CUSTOM = "X-AUTH-TOKEN";
public static String AUTH_HEADER1_CUSTOM = "XAUTHTOKEN";
public static String AUTH_PARAMETER = "xauthtoken";
public static String AUTH_PARAMETER1 = "token";
public JWTAuthTokenFilter(IJWTAuthService jwtAuthService, UsuarioRepository usuariosDAO) {
super();
this.jwtAuthService = jwtAuthService;
this.usuariosDAO = usuariosDAO;
}
// el formato de jwt son 3 campos separados por puntos --> xxxxx.yyyyyy.zzzz
private boolean esValido(String valor) {
return valor != null && valor.split("\\.").length == 3;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String header = request.getHeader(AUTH_HEADER);
//Si el header Authorization es null o si hay algun header del custom-token, hago el doFilter
if (header == null || request.getHeader(AUTH_HEADER_CUSTOM) != null || request.getHeader(AUTH_HEADER1_CUSTOM) != null
|| request.getParameter(AUTH_PARAMETER) != null || request.getHeader(AUTH_PARAMETER1) != null) {
chain.doFilter(request, response);
return;
}
// Si el header Authorization no comienza con el prefijo o si no es valido, hago el doFilter
if ( !header.startsWith(TOKEN_PREFIX) || !esValido(header.replace(TOKEN_PREFIX, ""))) {
chain.doFilter(request, response);
return;
}
// A partir de aquí, se considera que se envió el el token y es propritario, por
// ende si no está ok, login inválido
String token = header.replace(TOKEN_PREFIX, "");
log.trace("Token recibido por header=" + token);
String username = null;
JWTAuth jwtAuth = null;
try {
jwtAuth = jwtAuthService.load(token);
} catch (NotFoundException e) {
SecurityContextHolder.clearContext();
//throw new ServletException("No existe el token=" + token);
log.debug("No existe el token=" + token);
chain.doFilter(request, response);
return;
} catch (BusinessException e) {
SecurityContextHolder.clearContext();
log.error(e.getMessage(), e);
chain.doFilter(request, response);
return;
}
username = jwtAuth.getUsernameFromToken(jwtAuth.getToken());
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
List<Usuario> lu = usuariosDAO.findByUsername(username); // if token is valid configure Spring Security to manually set authentication
if (lu.size() == 1) {
if (jwtAuth.validateToken(token, lu.get(0))) {
log.trace("Token para usuario {} ({}) [{}]", lu.get(0).getUsername(), token, request.getRequestURI());
lu.get(0).setSessionToken(token);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(lu.get(0), null, lu.get(0).getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} else {
try {
jwtAuthService.delete(jwtAuth);
} catch (Exception e) {
log.error(e.getMessage(), e);
chain.doFilter(request, response);
}
SecurityContextHolder.clearContext();
log.debug("El Token " + token + " ha expirado");
//throw new ServletException("El Token ha expirado. Token=" + token);
chain.doFilter(request, response);
return;
}
} else {
log.debug("No se encontró el usuario {} por token", username);
}
chain.doFilter(request, response);
}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { LoginService } from '../services/login.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuardGuard implements CanActivate {
constructor(private auth: LoginService,
private router: Router) {
}
canActivate(): boolean {
if (this.auth.isAuthenticated()) {
return true;
} else {
this.router.navigate(['login']);
// se puede guardar el url aca y cuando el login sea exitoso redireccionarlo
// nuevamente a ese url.
console.log('Guard');
return false;
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// TERCEROS
import { MDBBootstrapModule } from 'angular-bootstrap-md';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SidebarModule } from 'ng-sidebar';
import { MatCardModule } from '@angular/material';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
// PROPIAS
import { sprintRoutingModule } from './sprint-module-routing.module';
import { ListSprintComponent } from './list-sprint/list-sprint.component';
@NgModule({
declarations: [
ListSprintComponent
],
imports: [
CommonModule,
sprintRoutingModule,
MDBBootstrapModule,
SidebarModule.forRoot(),
MatCardModule,
MatDividerModule,
MatIconModule,
FormsModule,
ReactiveFormsModule
]
})
export class sprintModule {}
<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NavBarComponent } from './nav-bar.component';
import { NavbarModule, DropdownModule, MDBBootstrapModule } from 'angular-bootstrap-md';
import { RouterModule, Router } from '@angular/router';
import { RouterLinkDirectiveStub } from 'src/testing/router-link-directive-stub';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
let mockRouter:any;
class MockRouter {
//noinspection TypeScriptUnresolvedFunction
navigate = jasmine.createSpy('navigate');
}
describe('NavBarComponent', () => {
let component: NavBarComponent;
let fixture: ComponentFixture<NavBarComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
NavbarModule,
DropdownModule.forRoot(),
MDBBootstrapModule.forRoot(),
RouterTestingModule,
HttpClientModule,
HttpClientTestingModule
],
declarations: [
NavBarComponent
]
}).overrideModule(NavbarModule, {
remove: {
imports: [ RouterModule ],
},
add: {
declarations: [ RouterLinkDirectiveStub ],
providers: [ { provide: Router, useValue: mockRouter } ],
}}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NavBarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { User } from '../models/user.model';
import { Router } from '@angular/router';
import Swal from 'sweetalert2';
import { LoginService } from '../services/login.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
user: User = new User();
rememberMe = false;
constructor( private auth: LoginService,
private router: Router) { }
ngOnInit() {
//this.nav.hide();
if (this.auth.isAuthenticated() ) {
// console.log("logged")
this.router.navigate(['sprint','home'])
return;
}
}
login() {
//console.log(form);
//if ( form.invalid ) { return; }
Swal.fire({
allowOutsideClick: false,
type: 'info',
text: 'Wait please...'
});
Swal.showLoading();
//console.log(this.user.username, this.user.password)
this.auth.login(this.user.username, this.user.password).subscribe( resp => {
// Correct Login
Swal.close();
/*if ( this.rememberMe ) {
localStorage.setItem( 'username', this.user.username);
}*/
// console.log(resp)
this.router.navigate(['sprint','home'])
}, (err) => {
console.log(err)
Swal.fire({
type: 'error',
title: 'Authentication error',
text: 'Invalid username or password '
});
});
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.persistence;
import ar.iua.edu.webIII.proyecto.viano.model.Sprint;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface SprintRepository extends JpaRepository<Sprint, Integer> {
Optional <Sprint> findByName(String name);
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.web;
public final class Constantes {
public static final String URL_API_BASE = "/api";
public static final String URL_API_VERSION = "/v1";
public static final String URL_BASE = URL_API_BASE + URL_API_VERSION;
public static final String URL_BASE_TASKS = URL_BASE + "/tasks";
public static final String URL_BASE_SPRINTS = URL_BASE + "/sprints";
public static final String URL_BASE_LISTS = URL_BASE + "/lists";
public static final String URL_BASE_USUARIOS = URL_BASE + "/usuarios";
public static final String URL_DENY = "/deny";
public static final String URL_LOGINOK = "/loginok";
public static final String URL_AUTH_INFO = "/authinfo";
public static final String URL_VERSION = "/version";
public static final String URL_TOKEN = URL_BASE + "/token";
public static final String BACKLOG_LIST = "BACKLOG";
public static final String TODO_LIST = "TODO";
public static final String IN_PROGRESS_LIST = "IN PROGRESS";
public static final String WAITING_LIST = "WAITING";
public static final String DONE_LIST = "DONE";
public final static String LOW_PRIORITY = "baja";
public final static String MEDIUM_PRIORITY = "media";
public final static String HIGH_PRIORITY = "alta";
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map } from 'rxjs/operators';
import { Task } from '../models/task.model';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TaskService {
constructor(private http: HttpClient) { }
getTasks() {
return this.http.get<any>(environment.urlApiRest + `tasks`)
.pipe(map(resp => {
return resp;
}));
}
moveTask(taskId: number, listId: number): Observable<any> {
return this.http.put<any>(environment.urlApiRest + `tasks/move/${listId}/${taskId}`, "")
.pipe(map(resp => {
console.log(resp);
return resp;
}))
}
/**
*
*
* @param {Task} task
* @returns
* @memberof TaskService
*/
editTask(task: Task) {
/**
* creation": "2019-12-16T02:13:18.126Z",
"description": "string",
"estimation": 0,
"id": 0,
"listName": {
"id": 0,
"name": "string",
"sprint": {
"id": 0,
"name": "string",
"startDate": "2019-12-16T02:13:18.126Z"
},
"task": [
null
]
},
"modification": "2019-12-16T02:13:18.126Z",
"name": "string",
"priority": "string"
*/
const data = {
creation: task.creation,
description: task.description,
estimation: task.estimation,
listName: {
id: task.listId
},
modification: task.modification,
name: task.name,
priority: task.priority
}
console.log(data)
return this.http.put<any>(environment.urlApiRest + `tasks/${task.id}` , data)
.pipe(map(resp => {
return resp;
}))
}
deleteTask(id: number) {
return this.http.delete<any>(environment.urlApiRest + `tasks/` + id)
.pipe(map(resp => {
console.log(resp)
return resp;
}))
}
public addTask(task: any): Observable<any> {
const data = {
creation: task.creation,
description: task.description,
estimation: task.estimation,
listName: {
id: task.listId
},
modification: task.modification,
name: task.name,
priority: task.priority
}
console.log(data)
return this.http.post<any>(environment.urlApiRest + `tasks`, data)
.pipe(map(resp => {
console.log(resp);
return resp;
}))
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map, catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class LoginService {
userToken = '';
public isLogged: Subject<any> = new Subject<any>();
private logged: false;
constructor(private http: HttpClient) { }
login(username, password): Observable<any> {
const body = new HttpParams()
.set('username', username)
.set('password', <PASSWORD>);
return this.http.post(environment.urlApiBase + `dologin`,
body.toString(),
{
headers: new HttpHeaders()
.set('Content-Type', 'application/x-www-form-urlencoded')
}
).pipe(map(response=>{
// store user details and basic auth credentials in local storage to keep user logged in between page refreshes
// user.authdata = window.btoa(username + ':' + password);
// this.currentUserSubject.next(response);
this.saveToken(response['jwtToken']);
localStorage.setItem('userData', JSON.stringify(response))
localStorage.setItem('roles', response['roles']);
localStorage.setItem('actualRole', response['roles'][0]);
localStorage.setItem('username', response['username'])
//localStorage.setItem('username', response['username'])
console.log('users: ', response);
return response;
}));
}
changeUserData(oldPassword, newPassword, field):Observable<any>{
const data = {
newValue: newPassword,
password: <PASSWORD>
}
let username = localStorage.getItem("username");
//username
return this.http.put<any>(environment.urlApiRest +`usuarios/${username}/${field}`, data )
.pipe(map( resp =>{
return resp;
}))
}
logout() {
localStorage.removeItem('token');
localStorage.removeItem('roles');
localStorage.removeItem('expires');
localStorage.removeItem('actualRole');
localStorage.removeItem('userData');
localStorage.removeItem('username');
this.setLogged(false);
}
saveToken(tokenId: string) {
localStorage.setItem('token', tokenId);
const today = new Date();
today.setSeconds( 3600 * 24 ); // 24 hs
localStorage.setItem('expires', today.getTime().toString());
}
readToken() {
if (!!localStorage.getItem('token')) {
this.userToken = localStorage.getItem('token');
} else {
this.userToken = '';
}
return this.userToken;
}
isAuthenticated(): boolean {
if (localStorage.getItem('token') == null ) {
console.log('not authenticated');
return false;
}
const expires = Number(localStorage.getItem('expires'));
// console.log(expires);
const expirationDate = new Date ();
expirationDate.setTime(expires);
if ( expirationDate > new Date() ) {
// console.log("authenticated");
return true;
} else {
console.log('not authenticated');
return false;
}
}
setLogged(logged) {
this.logged = logged;
setTimeout(() => {
this.refreshAll();
}, 0);
}
public refreshAll() {
this.isLogged.next({ logged: this.logged });
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@PropertySource({ "classpath:version.properties" })
@RestController
@CrossOrigin("localhost:4200")
public class CoreRestController extends BaseRestController {
@GetMapping(value = Constantes.URL_DENY)
public ResponseEntity<String> deny() {
return new ResponseEntity<String>(HttpStatus.UNAUTHORIZED);
}
@GetMapping(value = Constantes.URL_LOGINOK)
public ResponseEntity<String> loginok() {
return new ResponseEntity<String>(userToJson(getUserLogged()).toString(), HttpStatus.OK);
}
@PostMapping(value = Constantes.URL_LOGINOK)
public ResponseEntity<String> loginokpost() {
return new ResponseEntity<String>(userToJson(getUserLogged()).toString(), HttpStatus.OK);
}
@GetMapping(value = Constantes.URL_AUTH_INFO)
public ResponseEntity<String> authInfo() {
return new ResponseEntity<String>(userToJson(getUserPrincipal()).toString(), HttpStatus.OK);
}
@Value("${version}")
private String version;
@GetMapping(value = Constantes.URL_VERSION)
public ResponseEntity<String> getVersion() {
return new ResponseEntity<String>(String.format("{\"version\":\"%s\"}", version), HttpStatus.OK);
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping(value = Constantes.URL_TOKEN)
public ResponseEntity<Object> getToken(@RequestParam("username") String username,
@RequestParam("diasvalido") int diasvalido) {
return genToken(username, diasvalido);
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.model.dto;
public class ChangeSensitiveDataDto {
private String password;
private Object newValue;
public ChangeSensitiveDataDto() {
}
public ChangeSensitiveDataDto(String password, Object newValue) {
this.password = password;
this.newValue = newValue;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Object getNewValue() {
return newValue;
}
public void setNewValue(Object newValue) {
this.newValue = newValue;
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.web;
import java.util.Calendar;
import java.util.Date;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.IAuthTokenService;
import ar.iua.edu.webIII.proyecto.viano.model.AuthToken;
import ar.iua.edu.webIII.proyecto.viano.model.JWTAuth;
import ar.iua.edu.webIII.proyecto.viano.business.IJWTAuthService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import ar.iua.edu.webIII.proyecto.viano.model.Usuario;
public class BaseRestController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private IAuthTokenService authTokenService;
@Autowired
private IJWTAuthService jwtAuthService;
protected UserDetails getUserPrincipal() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
UserDetails user = null;
if (auth.getPrincipal() instanceof UserDetails) {
user = (UserDetails) auth.getPrincipal();
}
return user;
}
protected Usuario getUserLogged() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Usuario usuario = null;
if (auth.getPrincipal() instanceof Usuario) {
usuario = (Usuario) auth.getPrincipal();
}
return usuario;
}
@Value("${app.session.token.timeout:86400}")
private int sessionTimeout;
protected JSONObject userToJson(Usuario u) {
boolean isAdmin = false, isUser = false;
AuthToken token = null;
String tokenValue = null;
JWTAuth jwtToken = null;
for (GrantedAuthority g : u.getAuthorities()) {
if (g.getAuthority().equals("ROLE_ADMIN"))
isAdmin = true;
if (g.getAuthority().equals("ROLE_USER"))
isUser = true;
}
if (isAdmin) {
token = new AuthToken(u.getUsername(),new Date(System.currentTimeMillis() + sessionTimeout *1000) );
tokenValue = token.encodeCookieValue();
try {
authTokenService.save(token);
} catch (BusinessException e) {
log.error(e.getMessage(), e);
}
}
if (isUser) {
jwtToken = new JWTAuth(sessionTimeout,u.getUsername(), u.getVersion());
try {
jwtAuthService.save(jwtToken);
}catch (BusinessException e){
log.error(e.getMessage(), e);
}
}
JSONObject o = JSONBuilder(u);
o.put("authtoken", tokenValue);
if(jwtToken != null)
o.put("jwtToken", jwtToken.getToken());
return o;
}
protected JSONObject userToJsonJWT(Usuario u) {
JWTAuth token = new JWTAuth(sessionTimeout, u.getUsername(), u.getVersion());
try {
jwtAuthService.save(token);
} catch (BusinessException e) {
log.error(e.getMessage(), e);
}
JSONObject o = JSONBuilder(u);
o.put("authtoken", token.getToken());
return o;
}
protected JSONObject userToJson(UserDetails u1) {
Usuario u = (Usuario) u1;
JSONObject o = JSONBuilder(u);
return o;
}
protected JSONObject userToJsonMasToken(UserDetails u, String token) {
JSONObject r = userToJson(u);
r.put("token", token);
return r;
}
protected ResponseEntity<Object> genToken(String username, int diasvalido) {
try {
AuthToken token = buildToken(username, diasvalido);
return new ResponseEntity<Object>("{\"token\":\"" + token.encodeCookieValue() + "\"}", HttpStatus.OK);
} catch (BusinessException e) {
log.error(e.getMessage(), e);
return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
protected AuthToken buildToken(String username, int diasvalido) throws BusinessException {
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, diasvalido);
AuthToken token = new AuthToken(username, c.getTime());
authTokenService.save(token);
return token;
}
private JSONObject JSONBuilder(Usuario u) {
JSONObject o = new JSONObject();
o.put("username", u.getUsername());
o.put("fullname", u.getFirstName() + "," + u.getLastName());
o.put("email", u.getEmail());
o.put("code", 0);
o.put("version", u.getVersion());
JSONArray r = new JSONArray();
for (GrantedAuthority g : u.getAuthorities()) {
r.put(g.getAuthority());
}
o.put("roles", r);
return o;
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { map, catchError } from 'rxjs/operators';
import { List } from '../models/list.model';
@Injectable({
providedIn: 'root'
})
export class ListService {
constructor(private http: HttpClient) { }
getlists() {
return this.http.get<any>(environment.urlApiRest + `lists`, { observe: 'response' })
.pipe(map(resp => {
return resp;
}));
}
getList(sprintId) {
return this.http.get<any>(environment.urlApiRest + `lists/sprint/${sprintId}`)
.pipe(map(resp => {
return resp;
}));
}
editList(list: List) {
return this.http.put<any>(environment.urlApiRest + `lists`, list)
.pipe(map(resp => {
return resp;
}))
}
deleteList(id: number) {
return this.http.delete<any>(environment.urlApiRest + `lists/` + id)
.pipe(map(resp => {
console.log(resp)
return resp;
}))
}
addList(listName:string, sprintId:number) {
const data = {
name: listName,
sprint: {
id : sprintId
}
}
return this.http.post<any>(environment.urlApiRest + `lists`, data, { observe: 'response' })
.pipe(map(resp => {
//console.log(resp.headers.get('location'))
return resp;
}))
}
filter(tab, property){
return tab.filter(
(list)=> {
return list.name === property;
}
)
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { LoginService } from './services/login.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'productosFrontend';
logged = false;
constructor(private authService: LoginService) {
if (this.authService.isAuthenticated()) {
this.authService.setLogged(true);
} else {
this.authService.setLogged(false);
}
}
ngOnInit() {
this.authService.isLogged.subscribe(
data => {
this.logged = data.logged === undefined ? false : data.logged;
},
error => {
console.log(error);
}
);
}
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.JWTAuth;
public interface IJWTAuthService {
public JWTAuth save(JWTAuth at) throws BusinessException;
public JWTAuth load(String token) throws BusinessException, NotFoundException;
public void delete(JWTAuth at) throws BusinessException;
public void purgeTokens() throws BusinessException;
}
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.BusinessException;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.NotFoundException;
import ar.iua.edu.webIII.proyecto.viano.model.Audit;
import java.util.List;
public interface IAuditBusiness {
public Audit load(int id) throws BusinessException, NotFoundException;
public Audit save(Audit audit) throws BusinessException;
public void delete(int id) throws BusinessException, NotFoundException;
public List<Audit> list() throws BusinessException;
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { ListService } from '../services/list.service';
import { Task } from '../models/task.model';
import { TaskService } from '../services/task.service';
import Swal from 'sweetalert2';
import { ActivatedRoute, Router } from '@angular/router';
import { LoginService } from '../services/login.service';
import { NotifierService } from "angular-notifier";
import { FormControl } from '@angular/forms';
import { DatePipe } from '@angular/common'
@Component({
selector: 'app-task-manager',
templateUrl: './task-manager.component.html',
styleUrls: ['./task-manager.component.scss']
})
export class TaskManagerComponent implements OnInit {
@ViewChild('updateTaskModal', { static: true }) updateTaskModal;
notifier: NotifierService;
todos: any[] = undefined;
doing: any[] = undefined;// in progress
done: any[] = undefined;
backlog: any[] = undefined;
waiting: any[] = undefined;
backlogId = -1;
todosId = -1;
doingId = -1;
doneId = -1;
waitingId = -1;
canLoad = true;
listsMapper: Map<string, number> = new Map<string, number>();
priorityMapper: Map<string, number> = new Map<string, number>();
newTask: Task = new Task();
private textAreaMaxLength: number = 300;
private charsRemainingTextArea: number = this.textAreaMaxLength;
private nameMaxLength: number = 30;
private charsRemainingName: number = this.nameMaxLength;
listName = "";
sprintId = -1;
private modification;
private creation;
date = new FormControl(new Date());
private priorities: any = [
{ value: 0, label: 'Alta' },
{ value: 1, label: 'Media' },
{ value: 2, label: 'Baja' }];
private selectedPriority: number = 0;
constructor(private listSrv: ListService, private auth: LoginService, private router: Router,
private taskSrv: TaskService, private route: ActivatedRoute, notifierSrv: NotifierService, private datepipe: DatePipe) {
this.notifier = notifierSrv;
}
ngOnInit() {
/**
* this.date=new Date();
let latest_date =this.datepipe.transform(this.date, 'yyyy-MM-dd');
*/
this.newTask.creation = new Date();
this.newTask.modification = new Date();
this.selectedPriority = 0;
this.priorityMapper.set('alta', 0);
this.priorityMapper.set('media', 1);
this.priorityMapper.set('baja', 2);
this.sprintId = Number(this.route.snapshot.paramMap.get('sprintId'));
this.todos = undefined;
this.doing = undefined;// in progress
this.done = undefined;
this.backlog = undefined;
this.waiting = undefined;
this.listName = "";
this.listSrv.getList(this.sprintId)
.subscribe((resp) => {
if (this.listSrv.filter(resp, 'backlog')[0] != null) {
this.backlog = this.listSrv.filter(resp, 'backlog')[0].task;
this.listsMapper.set('backlog', this.listSrv.filter(resp, 'backlog')[0].id);
}
if (this.listSrv.filter(resp, 'todo')[0] != null) {
this.todos = this.listSrv.filter(resp, 'todo')[0].task;
this.listsMapper.set('todo', this.listSrv.filter(resp, 'todo')[0].id);
}
if (this.listSrv.filter(resp, 'in progress')[0] != null) {
this.doing = this.listSrv.filter(resp, 'in progress')[0].task;
this.listsMapper.set('inprogress', this.listSrv.filter(resp, 'in progress')[0].id);
}
if (this.listSrv.filter(resp, 'done')[0] != null) {
this.done = this.listSrv.filter(resp, 'done')[0].task;
this.listsMapper.set('done', this.listSrv.filter(resp, 'done')[0].id);
}
if (this.listSrv.filter(resp, 'waiting')[0] != null) {
this.waiting = this.listSrv.filter(resp, 'waiting')[0].task;
this.listsMapper.set('waiting', this.listSrv.filter(resp, 'waiting')[0].id);
}
this.canLoad = true;
}, err => {
console.log(err)
let status = Math.trunc(err.status / 100);
console.log(status)
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
switch (status) {
case 4:
this.canLoad = false;
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
break;
default:
this.canLoad = false;
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
}).then(result => {
this.ngOnInit();
})
}
})
}
drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
const todo = event.item.data;
todo.state = event.container.element.nativeElement.classList[0];
let listId = this.getListId(todo.state);
this.taskSrv.moveTask(todo.id, listId).subscribe(resp => {
console.log(resp);
this.notifier.notify("success", "Se movió la tarea " + todo.name);
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
})
}
}
getListId(key: string): number {
console.log(this.listsMapper.get(key));
return this.listsMapper.get(key);
}
getPriority(key: string): number {
return this.priorityMapper.get(key);
}
private computeCharsRemainingTextArea() {
this.charsRemainingTextArea = this.textAreaMaxLength - this.newTask.description.length;
}
private computeCharsRemainingName() {
this.charsRemainingName = this.nameMaxLength - this.newTask.name.length;
}
createTask() {
this.newTask.priority = this.priorities[this.selectedPriority].label
this.newTask.listId = this.getListId("backlog");
this.newTask.modification = this.newTask.creation;
this.newTask.name = this.newTask.name.trim();
console.log(this.newTask)
if (this.newTask.name.length == 0) {
console.log("error");
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El nombre no puede estar vacio!',
})
return;
}
if(this.newTask.estimation < 0){
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'La estimacion debe ser mayor a 0!',
})
return;
}
this.taskSrv.addTask(this.newTask).subscribe(resp => {
console.log(resp);
this.ngOnInit();
this.clearModal();
this.notifier.notify("success", "Se creó la tarea " + this.newTask.name);
}, err => {
console.log(err);
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
})
}
openUpdateModal(task, list) {
this.newTask.creation = task.creation;
this.newTask.modification = new Date();
this.modification = this.newTask.modification.toISOString().substr(0, 10);
this.creation = task.creation;
this.newTask.name = task.name;
this.newTask.description = task.description;
this.newTask.estimation = task.estimation;
this.selectedPriority = this.getPriority(task.priority);
this.newTask.priority = task.priority;
this.newTask.id = task.id;
this.newTask.listId = this.getListId(list);
this.computeCharsRemainingTextArea();
this.computeCharsRemainingName();
this.updateTaskModal.show()
}
createList() {
this.listName = this.listName.trim();
if (this.listName.length == 0) {
console.log("error");
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El nombre no puede estar vacio!',
})
return;
}
this.listSrv.addList(this.listName, this.sprintId)
.subscribe(resp => {
console.log(resp);
this.ngOnInit();
this.notifier.notify("success", "Se creó la lista " + this.listName);
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
console.log(err);
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: err.error,
})
})
}
clearModal() {
this.newTask.creation = null;
this.newTask.modification = null;
this.newTask.name = "";
this.newTask.description = "";
this.newTask.estimation = 0;
}
deleteList(list) {
Swal.fire({
allowOutsideClick: false,
title: "Esta seguro de eliminar esta lista: " + list + "?",
type: 'warning',
text: "Esta acción no se puede revertir",
showCancelButton: true,
confirmButtonText: 'Si, Eliminar!',
cancelButtonText: 'No, cancelar!',
reverseButtons: true
}).then((result) => {
if (result.value) {
this.listSrv.deleteList(this.getListId(list))
.subscribe(resp => {
console.log(resp);
this.ngOnInit();
this.notifier.notify("success", "Se eliminó la lista " + list);
Swal.fire(
'Eliminado!',
'La lista se eliminó.',
'success'
)
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong! ' + err.error,
})
})
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
Swal.fire(
'Cancelado',
'Tu lista esta a salvo :)',
'error'
)
}
});
}
openDeleteModal(todo) {
Swal.fire({
allowOutsideClick: false,
title: "Esta seguro de eliminar este elemento: " + todo.name + "?",
type: 'warning',
text: "Esta acción no se puede revertir",
showCancelButton: true,
confirmButtonText: 'Si, Eliminar!',
cancelButtonText: 'No, cancelar!',
reverseButtons: true
}).then((result) => {
if (result.value) {
this.taskSrv.deleteTask(todo.id)
.subscribe(resp => {
Swal.fire(
'Eliminado!',
'La tarea se eliminó.',
'success'
)
console.log(resp);
this.notifier.notify("success", "Se eliminó la tarea " + todo.name);
this.ngOnInit();
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong! ' + err.error,
})
})
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
Swal.fire(
'Cancelado',
'Tu tarea esta a salvo :)',
'error'
)
}
});
}
updateTask() {
//console.log(this.newTask);
this.newTask.priority = this.priorities[this.selectedPriority].label;
this.newTask.name = this.newTask.name.trim();
if (this.newTask.name.length == 0) {
console.log("error");
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El nombre no puede estar vacio!',
})
return;
}
if(this.newTask.estimation < 0){
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'La estimacion debe ser mayor a 0!',
})
return;
}
this.taskSrv.editTask(this.newTask).subscribe(resp => {
console.log(resp);
this.ngOnInit();
this.clearModal();
this.notifier.notify("success", "Se modificó la tarea " + this.newTask.name);
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado");
this.auth.logout();
this.router.navigateByUrl('login');
})
return;
}
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong! ' + err.error,
})
})
}
}
<file_sep>import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { SprintService } from 'src/app/services/sprint.service';
import { LoginService } from 'src/app/services/login.service';
import { Sprint } from 'src/app/models/sprint.model';
import Swal from 'sweetalert2';
import { NotifierService } from 'angular-notifier';
@Component({
selector: 'app-list-sprint',
templateUrl: './list-sprint.component.html',
styleUrls: ['./list-sprint.component.scss']
})
export class ListSprintComponent implements OnInit {
constructor(private router: Router, private sprintSrv: SprintService,
private auth: LoginService, private notifier: NotifierService) { }
private sprints: Sprint[] = [];
private nameMaxLength: number = 30;
private charsRemainingName: number = this.nameMaxLength;
private newSprint: Sprint = new Sprint();
private oldSprint: Sprint = new Sprint();
ngOnInit() {
if (this.auth.isAuthenticated()) {
this.auth.setLogged(true);
} else {
this.auth.setLogged(false);
this.auth.logout();
}
//console.log("init")
this.newSprint.startDate = new Date();
this.listSprints();
}
listSprints() {
this.sprintSrv.getAllSprints()
.subscribe(sprints => {
console.log(sprints);
this.sprints = sprints;
console.log(this.sprints);
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.auth.logout();
this.router.navigateByUrl('login');
})
} else {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
this.ngOnInit();
}
});
}
/*editSprint() {
console.log(this.oldSprint);
if (this.checkIfEmpty(this.oldSprint.name)) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El nombre no puede estar vacio!',
})
this.oldSprint = new Sprint();
return;
}
this.sprintSrv.editSprint(this.oldSprint)
.subscribe(resp => {
console.log(resp);
}, err => {
console.log(err);
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong! ' + err.error,
})
})
}*/
clearModal() {
this.oldSprint = new Sprint();
this.newSprint = new Sprint();
}
goToSprintLists(item) {
// this.router.navigate(['manager', 'home'], { state: { data: item } })
let url = "manager/" + item.id;
this.router.navigateByUrl(url)
}
private computeCharsRemainingName() {
this.charsRemainingName = this.nameMaxLength - this.newSprint.name.length;
}
checkIfEmpty(elem): boolean {
return !elem || elem.trim().length == 0
}
createSprint() {
if (this.checkIfEmpty(this.newSprint.name)) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'El nombre no puede estar vacio!',
})
this.newSprint = new Sprint();
return;
}
this.sprintSrv.addSprint(this.newSprint)
.subscribe(resp => {
console.log(resp);
this.newSprint = new Sprint();
this.ngOnInit();
this.notifier.notify("success", "Se creó el sprint " + this.newSprint.name);
}, err => {
console.log(err);
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado" );
this.auth.logout();
this.router.navigateByUrl('login');
})
} else {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
}
})
}
openDeleteModal(sprint) {
Swal.fire({
allowOutsideClick: false,
title: "Esta seguro de eliminar este elemento: " + sprint.name + "?",
type: 'warning',
text: "Esta acción no se puede revertir",
showCancelButton: true,
confirmButtonText: 'Si, Eliminar!',
cancelButtonText: 'No, cancelar!',
reverseButtons: true
}).then((result) => {
if (result.value) {
Swal.fire(
'Eliminado!',
'Es sprint se eliminó.',
'success'
)
this.sprintSrv.deleteSprint(sprint.id)
.subscribe(resp => {
console.log(resp);
this.ngOnInit();
this.notifier.notify("success", "Se eliminó el sprint " + sprint.name);
}, err => {
if (err.status == 401) {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Su token ha expirado!',
}).then(result => {
this.notifier.notify("info", "Logging out. Su token ha expirado" );
this.auth.logout();
this.router.navigateByUrl('login');
})
} else {
Swal.fire({
allowOutsideClick: false,
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
})
}
})
} else if (
/* Read more about handling dismissals below */
result.dismiss === Swal.DismissReason.cancel
) {
Swal.fire(
'Cancelado',
'Tu sprint esta a salvo ;)',
'error'
)
}
});
}
}
<file_sep># ProyectoFinal
* University project (back and front)
* Objective: Develop a web application that allows managing software development projects (like Trello or Jira).
<file_sep>package ar.iua.edu.webIII.proyecto.viano.business.implementation;
import java.util.List;
import java.util.Optional;
import ar.iua.edu.webIII.proyecto.viano.business.exceptions.*;
import ar.iua.edu.webIII.proyecto.viano.business.IListBusiness;
import ar.iua.edu.webIII.proyecto.viano.model.Sprint;
import ar.iua.edu.webIII.proyecto.viano.model.SprintList;
import ar.iua.edu.webIII.proyecto.viano.persistence.SprintRepository;
import ar.iua.edu.webIII.proyecto.viano.web.Constantes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ar.iua.edu.webIII.proyecto.viano.persistence.ListRepository;
@Service
public class ListBusiness implements IListBusiness {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private ListRepository listDao;
@Autowired
private SprintRepository sprintDao;
@Override
public SprintList getListById(int idList) throws BusinessException, NotFoundException {
Optional<SprintList> op = null;
try {
op = listDao.findById(idList);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new BusinessException(e);
}
if (!op.isPresent()) {
log.error("No se encuentra la lista con id =" + idList);
throw new NotFoundException("No se encuentra la lista con id =" + idList);
}
return op.get();
}
@Override
public SprintList save(SprintList sprintList) throws BusinessException, ListAlreadyExistsException, NotFoundException {
Optional<SprintList> op = null;
Optional<Sprint> opSprint = null;
opSprint = sprintDao.findById(sprintList.getSprint().getId());
if (!opSprint.isPresent()) {
log.error("El sprint con id " + sprintList.getSprint().getId() + "no existe");
throw new NotFoundException("El sprint con id " + sprintList.getSprint().getId() + "no existe");
}
op = listDao.findByNameAndSprintId(sprintList.getName(), sprintList.getSprint().getId());
if (op.isPresent()) {
log.error("La lista de nombre " + sprintList.getName() + " en el sprint " + opSprint.get().getName() + " ya existe");
throw new ListAlreadyExistsException("La lista de nombre " + sprintList.getName() + " en el sprint " + opSprint.get().getName() + " ya existe");
}
try {
return listDao.save(sprintList);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new BusinessException(e);
}
}
@Override
public void delete(int id) throws BusinessException, NotFoundException {
Optional<SprintList> op;
try {
op = listDao.findById(id);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new BusinessException(e);
}
if (!op.isPresent()) {
log.error("No se encuentra la lista con id =" + id);
throw new NotFoundException("No se encuentra la lista con id =" + id);
}
try {
listDao.deleteById(op.get().getId());
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new BusinessException(e);
}
}
@Override
public List<SprintList> list() throws BusinessException {
try {
return listDao.findAll();
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new BusinessException(e);
}
}
@Override
public List<SprintList> getListsBySprint(int idSprint) throws BusinessException, NotFoundException {
Optional<Sprint> opSprint = null;
Optional<List<SprintList>> op = null;
opSprint = sprintDao.findById(idSprint);
if (!opSprint.isPresent()) {
log.error("No se encuentra el sprint con id =" + idSprint);
throw new NotFoundException("No se encuentra el sprint con id =" + idSprint);
}
try {
op = listDao.findBySprintId(idSprint);
} catch (Exception e) {
throw new BusinessException(e);
}
if (!op.isPresent()) {
log.error("No hay ninguna lista que petenezca al sprint con id =" + idSprint);
throw new NotFoundException("No hay ninguna lista que petenezca al sprint con id =" + idSprint);
}
return op.get();
}
@Override
public SprintList getListByNameAndSprintId(String name, int idSprint) throws BusinessException, NotFoundException {
Optional<Sprint> opSprint = null;
Optional<SprintList> op = null;
opSprint = sprintDao.findById(idSprint);
if (!opSprint.isPresent()) {
log.error("No se encuentra el sprint con id =" + idSprint);
throw new NotFoundException("No se encuentra el sprint con id =" + idSprint);
}
try {
op = listDao.findByNameAndSprintId(name, idSprint);
} catch (Exception e) {
throw new BusinessException(e);
}
if (!op.isPresent()) {
log.error("No hay ninguna lista de nombre " + name + " que petenezca al sprint con id =" + idSprint);
throw new NotFoundException("No hay ninguna lista de nombre " + name + " que petenezca al sprint con id =" + idSprint);
}
return op.get();
}
@Override
public void isValid(SprintList sprintList) throws InvalidNameException, InvalidSprintException {
if (sprintList.getName() == null) {
log.error("El nombre de la lista es null");
throw new InvalidNameException("El nombre de la lista no puede ser null");
}
if (!sprintList.getName().equalsIgnoreCase(Constantes.BACKLOG_LIST) && !sprintList.getName().equalsIgnoreCase(Constantes.TODO_LIST) && !sprintList.getName().equalsIgnoreCase(Constantes.DONE_LIST) &&
!sprintList.getName().equalsIgnoreCase(Constantes.IN_PROGRESS_LIST) && !sprintList.getName().equalsIgnoreCase(Constantes.WAITING_LIST)) {
log.error("El nombre " + sprintList.getName() + " no es un nombre valido");
throw new InvalidNameException("El nombre " + sprintList.getName() + " no es un nombre valido\n Solo se soportan los nombres: " + Constantes.BACKLOG_LIST + "," +
Constantes.TODO_LIST + "," + Constantes.IN_PROGRESS_LIST + "," + Constantes.DONE_LIST + "," + Constantes.WAITING_LIST);
}
if (sprintList.getSprint() == null) {
log.error("La lista debe estar asociada a un sprint");
throw new InvalidSprintException("La lista debe estar asociada a un sprint");
}
if (sprintList.getSprint().getId() == null) {
log.error("El id del sprint es null");
throw new InvalidSprintException("El id del sprint no puede ser null");
}
}
}
| c005cf2644164179957fdc255e502c1e80b06a90 | [
"Markdown",
"Java",
"TypeScript"
] | 35 | Java | rviano96/ProyectoFinal | fea3ed23eb187521c168b9c1007fcb36e24da313 | 91aff5f2bcc8dcf2584e0837dd3bd0db50296fc3 |
refs/heads/master | <file_sep>#For today... you guys should be able to create your own gems..
#1. Build your own gem... Own It!
#2. Create a simple documentation or a readme file
#3. Share your .gem file on slack and have other install and use it
#(install and use at least 3 gems from your classmates - urge and help everyone to complete their gems
#so you have more options for yourself) (edited)
# The banner doesn't display perfectly but I atleast got it working
class Cidentity
def banner
p' .======.'
p' | |'
p' | |'
p' | |'
p' .========" "========.'
p' | _ xxxx _ |'
p' | /_;-.__ / _\ _.-;_\ |'
p' | `-._`"`_/"`.-" |'
p' "========.`\ /`========"'
p' | | / |'
p' |/-.( |'
p' |\_._\ |'
p' | \ \`;|'
p' | > |/|'
p' | / // |'
p' | |// |'
p' | \(\|'
p' | `` |'
p' | |'
p' | |'
p' | |'
p' | |'
p'//jgs _ _//| \// |//_ _ \// _'
p'^ `^`^ ^`` `^ ^` ``^^` `^^` `^ `^'
end
def newCreation
system"cls"
banner();
p " "*80;
p '-'*25;
p '[ New Nature ]';
p '| 1 - Old Life Dead |';
p '| 2 - Fruit of Spirit |';
p '| 3 - Promises of God |';
p '| 4 - Future & Hope |';
p '| 5 - Coming Soon |';
p '| 6 - Coming Soon |';
p '| 7 - Coming Soon |';
p "-"*25;
p " "*80;
print 'Enter your numeric choice > ';
@cmdInput = gets.chomp.strip;
case @cmdInput
when '1'
oldLifeDead();
redirectToMenu
when '2'
fruitOfSpirit();
redirectToMenu
when '3'
promisesOfGod();
redirectToMenu
when '4'
futureAndHope();
redirectToMenu
when '5'
newCreation();
when '6'
newCreation();
when '7'
newCreation();
when 'e' || 'exit' || 'E' || 'EXIT'
system"cls";
exit;
else
p "Invalid entry. Please try again."
sleep(5);
newCreation();
end
end
def redirectToMenu
p " "*80;
p "Back to Christian principles menu? [y/n]";
print '> ';
redirect = gets.chomp.strip.downcase;
if redirect == "yes" || redirect == "y"
newCreation();
else
newCreation();
end
end
def oldLifeDead
p "2 Corinthians 5:17Amplified Bible (AMP)"
p "17 Therefore if anyone is in Christ [that is, grafted in, joined to Him by faith in Him as Savior],"
p "he is a new creature [reborn and renewed by the Holy Spirit]; the old things [the previous moral"
p "and spiritual condition] have passed away. Behold, new things have come [because spiritual awakening brings a new life]."
p "-"*7;
end
def fruitOfSpirit
p "Galatians 5:22-23Amplified Bible (AMP)"
p "22 But the fruit of the Spirit [the result of His presence within us] is love [unselfish concern for others],"
p "joy, [inner] peace, patience [not the ability to wait, but how we act while waiting], kindness, goodness,"
p "faithfulness, 23 gentleness, self-control. Against such things there is no law."
# needs redirect
end
def promisesOfGod
p "2 Peter 1:3-4Amplified Bible (AMP)"
p "3 For His divine power has bestowed on us [absolutely] everything necessary for [a dynamic spiritual] life and"
p "godliness, through [a]true and personal knowledge of Him who called us by His own glory and excellence. 4 For"
p "by these He has bestowed on us His precious and magnificent promises [of inexpressible value], so that by them"
p "you may escape from the immoral freedom that is in the world because of disreputable desire, and become sharers"
p "of the divine nature."
# needs redirect
end
def futureAndHope
p "Jeremiah 29:11Amplified Bible (AMP)";
p "11 For I know the plans and thoughts that I have for you,’ says the Lord, ‘plans for peace and well-being and not"
p "for disaster to give you a future and a hope."
end
end
test = Cidentity.new;
test.newCreation();
<file_sep># Challenge
# Create a simple banking app, to get the customer
# details: name, email, account, address, contact info
# Calculate and display the balance
# Use: attr_accessor
# Completed: 6/13/2017 by <NAME>
class BankAccount
attr_accessor :name, :email, :account, :address, :contact
def initialize(name, email, account, address, contact)
@name = name;
@email = email;
@account = account;
@address = address;
@contact = contact;
@transactions = [];
add_transaction("Beginning Balance", 0);
end
def credit(description, amount)
add_transaction(description, amount);
end
def debit(description, amount)
add_transaction(description, -amount);
end
def add_transaction(description, amount)
@transactions.push(description: description, amount: amount);
end
def balance
balance = 0.0;
@transactions.each do |transaction|
balance += transaction[:amount];
end
return balance
end
def to_s
"Name: #{name}, Balance: $#{sprintf("%0.2f", balance)}";
end
def print_register
p "#{name}'s Bank Account";
p "Account #: #{account}".ljust(28) + "Contact #: #{contact}".rjust(15);
p "Address: #{address}";
p "Email: #{email}".ljust(35);
p "-" * 50;
p "Description".ljust(35) + "Amount".rjust(15);
@transactions.each do |transaction|
p transaction[:description].ljust(35) + sprintf("%0.2f", transaction[:amount]).rjust(15);
end
p "-" * 50;
p "Balance:".ljust(35) + sprintf("%0.2f", balance).rjust(15);
p "-" * 50;
end
end
#name, email, account, address, contact
bank_account = BankAccount.new("Jason", "<EMAIL>", 128965430945, "12 Hoppe rd, Unionville, Michigan, USA", "09956501909");
bank_account.credit("Paycheck", 100)
bank_account.debit("Groceries", 40)
bank_account.debit("Gas", 10.51)
p bank_account
p "Register:"
bank_account.print_register
<file_sep>Gem::Specification.new do |s|
s.name = 'cidentity'
s.version = '0.0.1'
s.date = '2017-06-20'
s.summary = 'Identity in Christ!'
s.description = 'Your identity in Christ'
s.authors = ['<NAME>']
s.email = ''
s.files = ['lib/identity2.rb', 'identity_readme.txt']
s.license = 'MIT'
s.homepage = ''
end
<file_sep>class Weather
def self.weather_today
p "Sunny today!";
end
end
<file_sep># The listed challenge:
# "William runs a small resturant here in Baguio. He has been looking for ways to cut costs and has realised
# that largest expense is Michael, his cashier. You are to use what you have learned to try and help Marc
# reduce the costs in his business"
# Version 2 objective: Update your application with what was learned today.
# Version 2 Completed: 6/7/2017 by <NAME>
$menu = [
{ item: "sisig", price: 50 },
{ item: "papaitan", price: 50 },
{ item: "adobo", price: 40 },
{ item: "soimi", price: 20 },
{ item: "coke", price: 12 },
{ item: "water", price: 10 }
]
wantMore = "yes";
sum = 0;
p "Welcome to Mooney's Restaurant.";
# Removed the code asking for customer input of price of items and instituted a menu
def showMenu
p "=====================";
p "Here is the menu:";
for i in 1..$menu.length
p "#{$menu[i-1][:item]} = #{$menu[i-1][:price]} peso's."
end
p "=====================";
end
showMenu
while wantMore == "yes" || wantMore == "y"
# Get the customers order
p "What do you want to order?";
chosen = gets.chomp.strip.downcase;
p "How many would you like?";
amount = gets.chomp.strip.to_i;
# Checks if the item is part of the menu and adds the price
$menu.each do |food|
if chosen == food[:item]
sum += (food[:price] * amount);
end
end
# Continues or Ends the loop
p "Do you want more items on your order? Yes or No?";
wantMore = gets.chomp.strip.downcase;
end
total = sum.round(2);
if total == 0
p "You don't owe anything. Please come back when you would like to order something.";
else
p "You owe: #{total} peso's. You may pay the funds into the payment processor now.";
# Process Payment Below
p "How much money are you giving for payment?";
money = gets.chomp.strip.to_i;
if money >= total
change = money - total;
p "Your change is #{change} peso's. Thank you and come back soon.";
else
p "You do not have enough to pay for your order. Please get more funds or be prepared to wash dishes.";
end
end
<file_sep># Challenge details:
#Dan has started his own car shop, the customers are demanding for an easier way to order
#and dress up their cars. You are to build a menu system that calculates the price of a car,
#given different options like paint color, wheels, etc..
# Updated Challenge requirements:
# 3 things I want to be included in your code
# 1. Order tracker without a need to login to the system
# 2. Google "Konami Code" and implement your own cheat code in your system
# 3. Add a tribute "Easter Egg" to your code in celebration of our national hero's birthday: <NAME>
# Completed: Unfinished, took on too much for such a short period of time...
class Item
attr_accessor
def initialize(name, description, cost)
@name = name;
@description = description;
@cost = cost;
end
end
# Create databases for each item type...
####################### Invetory Databases ##################
$brakesDB = [];
# DuraMax, long lasting brakes, $$$
# PerforMax, Performance brakes, $$$$$
$chassisDB = [];
# Steel, Durable chassis, $
# Aluminuim, Light weight chassis, $
$engineDB = [];
# Entry level, entry level performance, $
# Mid-grade, Mid grade performance, $
# Top-grade, Top grade performance, $
$exhaustDB = [];
# aesthetic exhaust, For visual appeal, $
# Magnaflow exhaust, for mid-grade exhaust performance, $
# Maxflow exhaust, top-grade exhaust performance, $
$grilleDB = [];
# mid-grade, for visual aesthetic's, $
# top-grade, top quality visual aesthetic's, $
$hoodDB = [];
# Air-flow hood, improves air flow, $
# Custom hood, visual appeal
$hornDB = [];
# Custom horn, horn with a custom sound, $
# Air horn, get everyone's attention!, $
$lightsDB = [];
#
$theftPrevDB = [];
$suspensionDB = [];
$transmissionDB = [];
$turboDB = [];
$wheelsDB = [];
#####################################################
def banner
p "=".center(80, '=');
p "Dan's Performance Car Shop".prepend(' ').concat(' ').center(80, '=');
p "=".center(80, '=');
end
def vehicleOptions
system"cls"
banner();
p " "*80;
p '-'*25;
p '[ Enhancement Categories ]';
p '| 1 - Brakes |';
p '| 2 - Chassis |';
p '| 3 - Engine |';
p '| 4 - Exhaust |';
p '| 5 - Grille |';
p '| 6 - Hood |';
p '| 7 - Horn |';
p '| 8 - Lights |';
p '| 9 - Theft Prevention |';
p '| 10 - Suspension |';
p '| 11 - Transmission |';
p '| 12 - Turbo |';
p '| 13 - Wheels |';
p "-"*25;
p " "*80;
print 'Enter your numeric choice > ';
@cmdInput = gets.chomp.strip;
case @cmdInput
when '1'
brakes();
when '2'
chassis();
when '3'
engine();
when '4'
exhaust();
when '5'
grille();
when '6'
hood();
when '7'
horn();
when '8'
lights();
when '9'
lossPrevention();
when '10'
suspension();
when '11'
transmission();
when '12'
turbo();
when '13'
wheels();
when 'egg'
egg();
when 'e' || 'exit' || 'E' || 'EXIT'
system"cls";
exit;
else
p "Invalid entry. Please try again."
vehicleOptions();
end
end
############### Vehicle Customizations ##############
def brakes
system"cls";
banner();
p "( Brakes )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'If you\'re going to tune your vehicle to increase speed and acceleration, some';
p 'quality brakes are needed to stop that rocket.';
p "="*80;
redirectToMenu();
end
def chassis
system"cls";
banner();
p "( Chassis )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'If you want to either improve frame durability or decrease weight you may want';
p 'to change your current chassis.';
p "="*80;
redirectToMenu();
end
def engine
system"cls";
banner();
p "( Engine )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "Engine upgrades increase your base horsepower, which increases acceleration.";
p "By altering the Engine Monitoring System (EMS), you can get more power out of";
p "your vehicle. There are four levels of upgrades.";
p "="*80;
redirectToMenu();
end
def exhaust
system"cls";
banner();
p "( Exhaust )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "An aftermarket performance exhaust can free some of the power in your engine.";
p "These systems allow for a quicker, more efficient path for exhaust gases to"
p "escape. That means more fuel and air can be burned to create more power.";
p "="*80;
redirectToMenu();
end
def grille
system"cls";
banner();
p "( Grille )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'If you want to further customize the look of your perfomance vehicle then perhaps';
p 'a custom grille will give you the unique look you\'re after.';
p "="*80;
redirectToMenu();
end
def hood
system"cls";
banner();
p "( Hood )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'A custom hood can either improve visual aesthetic\'s or even allow for improved'
p 'airflow.';
p "="*80;
redirectToMenu();
end
def horn
system"cls";
banner();
p "( Horn )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'An improved horn will be sure to get other\'s attention on the road.';
p "="*80;
redirectToMenu();
end
def lights
system"cls";
banner();
p "( Lights )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "Do you want improved brightness to handle night time conditions? Then check out"
p "our selection.";
p "="*80;
redirectToMenu();
end
def lossPrevention
system"cls";
banner();
p "( Anti-theft System )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p 'Customizing your vehicle is sure to get the attention of thieves. Get peace of'
p 'mind with a state of the art theft prevention system.';
p "="*80;
redirectToMenu();
end
def suspension
system"cls";
banner();
p "( Suspension )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "An aftermarket performance suspension kit will improve handling, braking, and";
p "control that you can feel. This results in a car thats much more fun to drive,"
p "and isnt that what its all about?";
p "="*80;
redirectToMenu();
end
def transmission
system"cls";
banner();
p "( Transmission )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "Building awesome horsepower is only part of the story. You need to deliver all"
p "that power to your car or trucks wheels! We have torque-hungry high performance"
p "automatic and manual transmissions for street and strip applications.";
p "="*80;
redirectToMenu();
end
def turbo
system"cls";
banner();
p "( Turbo Kits )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "Our selection of turbos runs the gamut from entry level units to high performance"
p "screamers so you are sure to find the perfect turbo somewhere in our lineup.";
p "="*80;
redirectToMenu();
end
def wheels
system"cls";
banner();
p "( Performance Tires )".prepend(' ').concat(' ').center(80, ' ');
p "="*80;
p "Performance tires improve the maneuverability and control of a high-speed vehicle."
p "All the horsepower in the world won't mean anything if you can't translate that"
p "onto the road. Get yourself some performance tires now!";
p "="*80;
redirectToMenu();
end
#####################################################
def redirectToMenu
p " "*80;
p "Back to the customization options? [y/n]";
print '> ';
redirect = gets.chomp.strip.downcase;
if redirect == "yes" || redirect == "y"
vehicleOptions();
elsif redirect == "ad.min"
vehicleOptions();
else
vehicleOptions();
end
end
vehicleOptions();
<file_sep># Challenge: Joseph is in a rush to make a really important purchase. He has no money
# on him so he has gone to withdraw money from BPI but has found that there are serious
# issues with their systems! Can you reprogram the atm so he can buy his romance novel??"
# Completed: 6/10/2017 by <NAME>
# Database with Account Info - Completed
# Intro Screen - Create a fancy intro screen.. WOOT!!! - Unfinished
# Account Validation - Completed
# Accout Overview - Completed
# Balance Inquery - Completed
# Withdrawal with balance statement - Completed
# Exit to Intro Screen - Completed
$database = [{
name: "<NAME>",
balance: 3232.00,
accountNum: 122354896127,
cardNum: 9982635412527589,
pin: 9892
}, {
name: "<NAME>",
balance: 1232.00,
accountNum: 122354897723,
cardNum: 9982621312527963,
pin: 9812
}, {
name: "<NAME>",
balance: 2232.00,
accountNum: 122354918472,
cardNum: 9982635412527589,
pin: 1323
}]
def banner
p "=".center(50, '=');
p 'BPI ATM System'.prepend(' ').concat(' ').center(50, '=');
p "=".center(50, '=');
end
def introScreen
system"cls";
banner();
p " "*50;
p "Welcome to BPI ATM.";
p "Please note that some functions are out of order.";
redirectToVerification();
end
def redirectToVerification
p "Would you like to access your account now? [y/n]"
redirectToCardVerification = gets.chomp.strip.downcase;
if redirectToCardVerification == "yes" || redirectToCardVerification == "y"
cardVerification();
elsif redirectToCardVerification == "exit" || redirectToCardVerification == "e"
system"cls";
exit;
elsif redirectToCardVerification == "ad.min"
adminPrivileges(); # => It's good to be the admin...
else
introScreen();
end
end
def adminPrivileges
system"cls"
banner();
p "-"*47;
p "Welcome Admin"
p "Please select from the list of commands:";
p "1 - Account Information";
p "2 - Access individual accounts";
p "3 - Exit Admin System";
p "-"*47;
@cmdAdmin = gets.chomp.strip.to_i;
case @cmdAdmin
when 1
adminInfo(); # ACCOUNT INFO FROM DATABASE
when 2
adminBackdoor(); # BACKDOOR ACCESS
when 3
introScreen();
else
adminPrivileges();
end
end
def adminInfo
i = 0;
while i < $database.length
p "Account number: #{$database[i][:accountNum]}";
p "Name: #{$database[i][:name]}".ljust(30) + "Balance: $" + sprintf("%0.2f", $database[i][:balance]).rjust(6);
p "-"*47;
i += 1;
end
redirectToAdminPrivileges();
end
def adminBackdoor
p "Enter the twelve digit account number to access it:"
@backdoor = gets.chomp.strip.to_i;
# I'm sure there are better solutions then hardcoding this backdoor.
# Perhaps an algorithm would automate the process which would work
# when information is adjusted in the database but for now this
# will do...
case @backdoor
when 122354896127
@index = 0;
accountOverview();
when 122354897723
@index = 1;
accountOverview();
when 122354918472
@index = 2;
accountOverview();
when 1234
adminPrivileges();
else
adminBackdoor();
end
end
def cardVerification
system"cls"
banner();
p " "*50;
p "Our card reader is temporarily out of order."
p "Please enter your 16 digit card number now:"
@cardInput = gets.chomp.strip.to_i;
i = 0;
@cardFound = false;
while i < $database.length
if @cardInput == $database[i][:cardNum]
@index = i;
@cardFound = true;
pinVerification();
end
i += 1;
end
if @cardFound == false
p "Your sixteen digit card number wasn't found on file. Try again? [y/n]"
@reattemptCard = gets.chomp.strip.downcase;
if @reattemptCard == "yes" || @reattemptCard == "y"
cardVerification();
else
introScreen();
end
end
end
def pinVerification
p "Please enter your four digit pin number now:"
@pinInput = gets.chomp.strip.to_i;
if @pinInput == $database[@index][:pin]
accountOverview();
else
p "Access Denied: The four digit pin was incorrect.";
p "Would you like to try again? [y/n]"
@reattemptPin = gets.chomp.strip.downcase;
if @reattemptPin == "yes" || @reattemptPin == "y"
pinVerification();
else
introScreen();
end
end
end
def accountOverview
system"cls"
banner();
p " "*50;
p "Welcome to the account overview:";
p "Thank you #{$database[@index][:name]} for being a valued customer.";
p "Account #: #{$database[@index][:accountNum]}";
p "Please select from the list of commands:";
p "1 - Balance inquery";
p "2 - Withdrawal of funds";
p "3 - Exit account overview";
p "-"*47;
@cmdInput = gets.chomp.strip.to_i;
case @cmdInput
when 1
balance();
when 2
withdrawal();
when 3
introScreen();
else
p "Invalid entry. Please try again."
redirectToOverview();
end
end
def balance
p "-"*47;
p "Account number: #{$database[@index][:accountNum]}";
p "Name: #{$database[@index][:name]}".ljust(30) + "Balance: $" + sprintf("%0.2f", $database[@index][:balance]).rjust(6);
p "-"*47;
redirectToOverview();
end
def redirectToOverview
p " "*50;
p "Would you like to go back to the account overview? [y/n]"
redirectAcctOverview = gets.chomp.strip.downcase;
if redirectAcctOverview == "yes" || redirectAcctOverview == "y"
accountOverview();
elsif redirectAcctOverview == "ad.min"
adminPrivileges();
else
introScreen();
end
end
def redirectToAdminPrivileges
p " "*50;
p "Would you like to go back to the admin overview? [y/n]"
redirectAcctAdminOverview = gets.chomp.strip.downcase;
if redirectAcctAdminOverview == "yes" || redirectAcctAdminOverview == "y"
adminPrivileges;
elsif redirectAcctAdminOverview == "ad.min"
adminPrivileges();
else
introScreen();
end
end
def withdrawal
p "Please tell me the amount you want to withdraw?";
amountWithdrawal = gets.chomp.strip.to_f.round(2);
if amountWithdrawal <= $database[@index][:balance]
$database[@index][:balance] -= amountWithdrawal;
p "Here is your $#{amountWithdrawal} Your new balance is: $" + sprintf("%0.2f", $database[@index][:balance]);
else
p "Withdrawal declined due to insufficient funds."
p "The amount requested $#{amountWithdrawal} is greater then your funds available: $#{$database[@index][:balance]}";
redirectToOverview();
end
redirectToOverview();
end
def executeProgram
introScreen();
end
executeProgram();
<file_sep># The listed challenge:
# "William runs a small resturant here in Baguio. He has been looking for ways to cut costs and has realised
# that largest expense is Michael, his cashier. You are to use what you have learned to try and help Marc
# reduce the costs in his business"
# Completed: 6/6/2017 by <NAME>
wantMore = "yes";
sum = 0;
while wantMore == "yes" || wantMore == "y"
puts "Welcome to Mooney's Restaurant."
puts "Tell me the price of the item."
itemPrice = gets.chomp.to_f;
puts "Do you have more items?"
wantMore = gets.chomp.downcase;
sum += itemPrice;
end
puts "You owe: #{sum.round(2)}. You may pay the funds into the payment processor now.";
<file_sep>class Classmate
def initialize(name, gender)
@name = name.to_s;
@gender = gender.to_s;
end
def about
p "#{@name} is #{@gender}";
end
end
classmate1 = Classmate.new('William', 'Male');
classmate2 = Classmate.new('Reggie', 'Male');
<file_sep>class Cat
attr_reader :name, :color
def initialize(name, color)
@name = name;
@color = color;
end
end
cats = [
Cat.new('Purry', :black),
Cat.new('Purty', :white),
Cat.new('Purren', :fawn),
]
# picks only white cats
white_cats = cats.select do |cat|
cat.color == :white
end
# => [ Cat('Scratchy', :white), Cat('Leo', :white)]
# Can also be written as
white_cats = cats.select { |cat| cat.color == :white };
cats = []; # full of different colored cats
# Get corresponging color of each cat
all_cat_colors = cats.map { |cat| cat.color }
# => [:black, :white, :fawn, :fawn, :white]
# Filters out duplicates
unique_cat_colors = all_cat_colors.uniq;
# [:black, :white, :fawn]
# Can be written in one line
unique_cat_colors = cats.map { |cat| cat.color }.uniq;
# [:black, :white, :fawn]
# Capitalizes all the names and throws them into a new array
capitalize_cat_names = cats.map { |cat| cat.name.upcase };
<file_sep>
require'weather'
Weather.weather_today;
<file_sep>
require_relative'identity.rb'
<file_sep>#Test_driven development
#database_
require 'test/unit'
require 'csv'
require_relative 'record.rb'
class DataList < Test::Unit::TestCase
def test_reason1
tester = Record.new(CSV.read('database.csv', headers:true),CSV.read('memberlist.csv', headers:true),'Regular Member')
assert_equal('Regular Member',tester.reason)
end
def test_reason2
tester = Record.new(CSV.read('database.csv', headers:true),CSV.read('memberlist.csv', headers:true),'Coding Bootcamp')
assert_equal('Coding Bootcamp',tester.reason)
end
def test_reason3
tester = Record.new(CSV.read('database.csv', headers:true),CSV.read('memberlist.csv', headers:true),'Drop-In Coworking')
assert_equal('Drop-In Coworking',tester.reason)
end
def test_reason4
tester = Record.new(CSV.read('database.csv', headers:true),CSV.read('memberlist.csv', headers:true),'Attend Event')
assert_equal('Attend Event',tester.reason)
end
def test_reason5
tester = Record.new(CSV.read('database.csv', headers:true),CSV.read('memberlist.csv', headers:true),'Guest/Other')
assert_equal('Guest/Other',tester.reason)
end
end
<file_sep>class Name
attr_reader :title, :first_name, :middle_name, :last_name;
attr_writer :title, :first_name, :middle_name, :last_name;
attr_accessor # Basically does reader & writer functionality in one
def initialize(title, first_name, middle_name, last_name)
@title = title;
@first_name = first_name;
@middle_name = middle_name;
@last_name = last_name;
end
def full_name
@first_name + " " + @middle_name + " " + @last_name;
end
def full_name_with_title
@title + " " + full_name();
end
# def title=(new_title)
# @title = new_title;
# end
end
name = Name.new("Mr", "William", "Adolph", "Mooney");
p name.title + " " + name.full_name;
p name.full_name_with_title;
#####################################################################
class BankAccount
attr_reader :name
def initialize(name)
@name = name
@transactions = []
add_transaction("Beginning Balance", 0)
end
def credit(description, amount)
add_transaction(description, amount)
end
def debit(description, amount)
add_transaction(description, -amount)
end
def add_transaction(description, amount)
@transactions.push(description: description, amount: amount)
end
def balance
balance = 0.0
@transactions.each do |transaction|
balance += transaction[:amount]
end
return balance
end
def to_s
"Name: #{name}, Balance: #{sprintf("%0.2f", balance)}"
end
def print_register
puts "#{name}'s Bank Account"
puts "-" * 40
puts "Description".ljust(30) + "Amount".rjust(10)
@transactions.each do |transaction|
puts transaction[:description].ljust(30) + sprintf("%0.2f", transaction[:amount]).rjust(10)
end
puts "-" * 40
puts "Balance:".ljust(30) + sprintf("%0.2f", balance).rjust(10)
puts "-" * 40
end
end
bank_account = BankAccount.new("Jason")
bank_account.credit("Paycheck", 100)
bank_account.debit("Groceries", 40)
bank_account.debit("Gas", 10.51)
puts bank_account
puts "Register:"
bank_account.print_register
<file_sep># file.methods.sort
# Open:
# Close:
# Read:
# Write:
# Ask for filename
# print "Type the file name: ";
# filename = gets.chomp.strip;
# //Create// Open the file and save it to opened_file variable
# opened_file = File.open(filename, 'a+');
# Print to the terminal screen
# p "Opened file name #{filename}";
# p "="*15;
# print opened_file.read;
# Get the file
print "Type in the file name: ";
filename = gets.chomp.strip;
# Open file in append-plus-read mode and store reference in opened_file variable
opened_file = File.open(filename, 'a+');
# Ask for a new city name
p "Add another Filipino city: ";
city = gets.chomp.strip;
# Write city name to the file
opened_file.write(city);
opened_file.write("\n");
# Rewind pointer at beginning of file
opened_file.rewind;
p "="*15;
# Read entire file from the beginning to end
print opened_file.read;
# We are done with the file
opened_file.close;
##############
p "Give your file a name (without .txt extension!)";
# creates the new file and adds the .txt file type enxtension
opened_file
<file_sep>class Dog
def initialize(name, breed, sex)
@name = name;
@breed = breed;
@sex = sex;
end
def speak
if sex.downcase == "male"
p "BARK!";
else
p "bark.";
end
end
end
# dog_name = gets.chomp.strip;
class Customer
def initialize
@details = details;
end
def print_customer_details
p "Customer details:";
p "Name: #{@details[:name]}";
p "Month #{@details[:month]}";
p "Age: #{@details[:age]}";
p "="*15;
end
end
# pedro = Customer.new({ name: "Pedro", month: "Enero", age: 21 });
# pedro.print_customer_details();
#############################
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name;
@age = age;
end
#Getters = attr_reader
# def name
# @name
# end
# def age
# @age
# end
#Setter = attr_writer
# def name=(name)
# @name = name
# end
# def bar=(age)
# @age = age
# end
#Accessor = attr_accessor which automatically set's up the GETTER & SETTER functions
end
#john = Person.new("John", 42);
#p "#{john.age} " + john.name;
#john.age = 33;
#p "#{john.age} " + john.name;
#john.name = "Ted";
#p john.name;
# Challenge
# Create a simple banking app, to get the customer
# details: name, email, account, address, contact info
# Calculate and display the balance
# Use: attr_accessor
| e42ee38c841b4d6f20137832431147929d2ef644 | [
"Ruby"
] | 16 | Ruby | ChristCenteredDev/1st-Semester---Vivixx-Coding-Bootcamp | c4da0ba0c8d52acf92bde93c6152423cba2233fa | 51d8cc34726ec7c38611a7d8510b1aeac5511075 |
refs/heads/master | <file_sep>package com.example.evanto.retrofitManager
interface UrlContainer {
companion object {
const val BASE_URL = "https://api.insider.in/"
const val END_URL_HOME_PAGE = "home"
}
}<file_sep>package com.example.evanto.homeSection.dataManager
import androidx.lifecycle.MutableLiveData
import com.example.evanto.helpers.UtilConstants
import com.example.evanto.helpers.UtilMethods
import com.example.evanto.homeSection.model.ModelEvents
import com.example.evanto.retrofitManager.ApiResponseCallback
import com.example.evanto.retrofitManager.ApiServiceProvider
import com.example.evanto.retrofitManager.UrlContainer
import retrofit2.Response
import java.util.*
object EventsRepository : ApiResponseCallback {
var masterEventsList: MutableLiveData<ModelEvents> = MutableLiveData()
fun fetchAllEvents(city:String?){
ApiServiceProvider().enqueueApiCall(UrlContainer.BASE_URL,this,UtilMethods.prepareFetchEventsHashMap(city))
.homePageData()
}
private fun handleFailure(msg:String?) {
val eventsModel = ModelEvents()
eventsModel.status = UtilConstants.STATUS_FAILURE
eventsModel.msg = msg ?: "Some error occurred"
masterEventsList.value = eventsModel
}
private fun handleSuccess(responseModelEvents: ResponseModelEvents) {
val eventsModel = ModelEvents()
//adding all events
when (val linkedHashMapOfEvents = responseModelEvents.list?.masterList) {
null -> {
eventsModel.status = UtilConstants.STATUS_NO_DATA
eventsModel.msg = "no data exist"
}
else -> {
val models: Collection<MasterListEventModel> = linkedHashMapOfEvents.values
val eventList = ArrayList<MasterListEventModel>(models)
if(eventList.size > 0) {
eventsModel.status = UtilConstants.STATUS_SUCCESS
eventsModel.msg = "success"
eventsModel.eventData = eventList
} else {
eventsModel.status = UtilConstants.STATUS_NO_DATA
eventsModel.msg = "no data exist"
}
}
}
//adding featured events
responseModelEvents.featuredEventList?.let {
eventsModel.featuredEvents = it
}
//adding popular events
responseModelEvents.popularEventList?.let {
eventsModel.popularEvents = it
}
masterEventsList.value = eventsModel
}
override fun <T> onSuccessCallback(response: Response<T>, serviceCallId: Int) {
val responseModelEvents = response.body() as? ResponseModelEvents
if(responseModelEvents == null) {
handleFailure("body is empty")
} else {
handleSuccess(responseModelEvents)
}
}
override fun onFailureCallback(errorMsg: String?, serviceCallId: Int) {
handleFailure(errorMsg)
}
}<file_sep>package com.example.evanto.homeSection.model
import com.example.evanto.homeSection.dataManager.MasterListEventModel
class ModelEvents (
var eventData : ArrayList<MasterListEventModel> = ArrayList(),
var featuredEvents : ArrayList<MasterListEventModel> = ArrayList(),
var popularEvents : ArrayList<MasterListEventModel> = ArrayList(),
var status : String? = null,
var msg:String? = null
)<file_sep>package com.example.evanto.helpers
class UtilConstants {
companion object {
const val PARAM_NORM = "norm"
const val PARAM_FILTER_BY = "filterBy"
const val PARAM_CITY = "city"
const val STATUS_FAILURE = "failure"
const val STATUS_SUCCESS = "success"
const val STATUS_NO_DATA = "no_data"
const val DEFAULT_CITY = "online"
const val LUCKNOW_CITY = "lucknow"
const val MUMBAI_CITY = "mumbai"
const val DELHI_CITY = "delhi"
const val PUNE_CITY = "pune"
const val KOLKATA_CITY = "kolkata"
const val API_CONSTANT_DEFAULT = 1000
}
}<file_sep>package com.example.evanto.retrofitManager
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit
class OkHttpClientBuilder {
companion object {
private var basicLogInterceptor: HttpLoggingInterceptor? = null
init {
basicLogInterceptor = HttpLoggingInterceptor()
basicLogInterceptor!!.level = HttpLoggingInterceptor.Level.BODY
}
val defaultOkHttpClient: OkHttpClient = OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.addInterceptor(basicLogInterceptor!!)
.build()
}
}<file_sep>package com.example.evanto.retrofitManager
import retrofit2.Response
interface ApiResponseCallback {
/**
* serviceCallId : API_CONSTANT with which the request was made
**/
fun<T> onSuccessCallback(response: Response<T>, serviceCallId:Int)
fun onFailureCallback(errorMsg: String?,serviceCallId:Int)
}<file_sep>package com.example.evanto.retrofitManager
import com.example.evanto.helpers.UtilConstants.Companion.API_CONSTANT_DEFAULT
import okhttp3.OkHttpClient
import retrofit2.Retrofit
/**
* Use when you want to make API request
* @enqueueApiCall method takes apiClient (default apiClient is provided if not received) & retrofitInstance (default instance is provided if not given)
* @enqueueApiCall returns RetrofitCallbackManager instance
* with the RetrofitCallbackManager you need to call methods to enqueue your request for the response
*
* Flow to make a api request must be
* APIServiceProvider ---> enqueueApiCall -----> RetrofitCallbackManager ----> call your respective method to enqueue request
* example : ApiServiceProvider().enqueueApiCall(baseUrl,callback,paramHashMap,apiProviderConstant).homePageData
*
* You can pass your own apiClient or retrofitInstance to the constructor of ApiServiceProvider by defining them inside OkHttpClientBuilder
* and RetrofitInstanceBuilder respectively
*
**/
class ApiServiceProvider (private var apiClient: OkHttpClient? = null,private var retrofit: Retrofit? = null) {
private var apiInterface:ApiInterface? =null
fun enqueueApiCall(baseUrl:String, apiResponseCallback: ApiResponseCallback, fieldMap:HashMap<String,String>, apiProviderConstants: Int = API_CONSTANT_DEFAULT): RetrofitCallbackManager {
var retrofitCallbackManager: RetrofitCallbackManager
try {
setApiClientData(baseUrl)
apiInterface = retrofit!!.create(ApiInterface::class.java)
retrofitCallbackManager = RetrofitCallbackManager(apiInterface,apiResponseCallback,fieldMap,apiProviderConstants)
}
catch (e:Exception){
e.printStackTrace()
retrofitCallbackManager = RetrofitCallbackManager(apiInterface,apiResponseCallback,fieldMap,apiProviderConstants)
}
return retrofitCallbackManager
}
private fun setApiClientData(baseUrl: String) {
when (retrofit) {
null -> {
if(apiClient == null) {
apiClient = OkHttpClientBuilder.defaultOkHttpClient
}
retrofit = RetrofitInstanceBuilder.getDefaultRetrofit(baseUrl,apiClient!!)
}
}
}
}<file_sep>package com.example.evanto.retrofitManager
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RetrofitInstanceBuilder{
companion object {
fun getDefaultRetrofit(baseUrl:String,okHttpClient: OkHttpClient) : Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
}
}
}<file_sep>package com.example.evanto
import android.os.Bundle
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.PopupMenu
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.evanto.databinding.ActivityMainBinding
import com.example.evanto.helpers.UtilConstants
import com.example.evanto.helpers.isNetworkAvailable
import com.example.evanto.homeSection.adapter.EventAdapter
import com.example.evanto.homeSection.dataManager.ViewModelEventsList
import com.example.evanto.homeSection.model.ModelEvents
const val VIEW_FOR_SUCCESS = 100
const val VIEW_FOR_FAILURE = 200
const val VIEW_FOR_NO_DATA = 300
const val VIEW_FOR_NETWORK_NOT_AVAILABLE = 400
const val EVENT_TYPE_ALL = "Discover Events"
const val EVENT_TYPE_FEATURED = "Featured Events"
const val EVENT_TYPE_POPULAR = "Popular Events"
class MainActivity : AppCompatActivity(), PopupMenu.OnMenuItemClickListener, AdapterView.OnItemSelectedListener {
private var mEventViewModel : ViewModelEventsList? = null
private lateinit var mLayoutBinding: ActivityMainBinding
private var mLinearLayoutManager: RecyclerView.LayoutManager? = null
private var mEventAdapter:EventAdapter? = null
private var mEventData : ModelEvents? = null
private var mSelectedCity: String = UtilConstants.DEFAULT_CITY
private var mPopupMenu: PopupMenu? = null
private var mCurrentEventType = EVENT_TYPE_ALL
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mLayoutBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
init()
}
private fun init() {
initObject()
initFetchEventData()
initObserver()
initView()
initListeners()
}
private fun initListeners() {
mLayoutBinding.retryTv.setOnClickListener {
initFetchEventData()
}
mLayoutBinding.locationIv.setOnClickListener {
mPopupMenu?.show()
}
mPopupMenu?.setOnMenuItemClickListener(this@MainActivity)
mLayoutBinding.titleSpinner.onItemSelectedListener = this@MainActivity
}
private fun initView() {
mLayoutBinding.rvEvents.apply {
setHasFixedSize(true)
layoutManager = mLinearLayoutManager
itemAnimator = null
}
mPopupMenu?.inflate(R.menu.menu_locations)
mPopupMenu?.gravity = Gravity.END
mPopupMenu?.menu?.findItem(R.id.online_item)?.isChecked = true
setSpinnerView()
}
private fun initObject() {
mEventViewModel = ViewModelProvider(this).get(ViewModelEventsList::class.java)
mLinearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
mPopupMenu = PopupMenu(this@MainActivity, mLayoutBinding.locationIv)
}
private fun initObserver() {
mEventViewModel?.getAllEvents()?.observe(this, Observer {
when(it.status) {
UtilConstants.STATUS_SUCCESS -> {
mEventData = it
updateView(VIEW_FOR_SUCCESS)
}
UtilConstants.STATUS_FAILURE -> {
updateView(VIEW_FOR_FAILURE)
}
UtilConstants.STATUS_NO_DATA -> {
updateView(VIEW_FOR_NO_DATA)
}
else -> {
updateView(VIEW_FOR_FAILURE)
}
}
})
}
private fun initFetchEventData() {
if(isNetworkAvailable()) {
mLayoutBinding.errorGroup.visibility = View.GONE
mLayoutBinding.rvEvents.visibility = View.GONE
mLayoutBinding.progressGroup.visibility = View.VISIBLE
mEventViewModel?.fetchAllEvents(mSelectedCity)
} else {
updateView(VIEW_FOR_NETWORK_NOT_AVAILABLE)
}
}
private fun setSpinnerView() {
val eventTypes = listOf(EVENT_TYPE_ALL, EVENT_TYPE_FEATURED, EVENT_TYPE_POPULAR)
val dataAdapter = ArrayAdapter(this,R.layout.layout_spinner_item, eventTypes)
dataAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
mLayoutBinding.titleSpinner.adapter = dataAdapter
}
private fun updateView(viewType:Int) {
mLayoutBinding.progressGroup.visibility = View.GONE
when(viewType) {
VIEW_FOR_SUCCESS -> {
mLayoutBinding.errorGroup.visibility = View.GONE
mLayoutBinding.rvEvents.visibility = View.VISIBLE
setEventAdapter()
}
VIEW_FOR_NO_DATA -> {
mLayoutBinding.errorGroup.visibility = View.VISIBLE
mLayoutBinding.rvEvents.visibility = View.GONE
mLayoutBinding.errorTv.text = getString(R.string.no_events_available_text)
}
VIEW_FOR_FAILURE -> {
mLayoutBinding.errorGroup.visibility = View.VISIBLE
mLayoutBinding.rvEvents.visibility = View.GONE
mLayoutBinding.errorTv.text = getString(R.string.something_went_wrong)
}
VIEW_FOR_NETWORK_NOT_AVAILABLE -> {
mLayoutBinding.errorGroup.visibility = View.VISIBLE
mLayoutBinding.rvEvents.visibility = View.GONE
mLayoutBinding.errorTv.text = getString(R.string.no_network_text)
}
}
}
private fun setEventAdapter() {
val eventListToShow = when(mCurrentEventType) {
EVENT_TYPE_POPULAR -> { mEventData?.popularEvents }
EVENT_TYPE_FEATURED -> { mEventData?.featuredEvents }
else -> { mEventData?.eventData }
}
if(eventListToShow == null || eventListToShow.size==0) {
updateView(VIEW_FOR_NO_DATA)
return
}
if (mEventAdapter != null) {
mEventAdapter!!.updateList(eventListToShow)
mEventAdapter!!.notifyDataSetChanged()
} else {
mEventAdapter = EventAdapter(this, eventListToShow)
mLayoutBinding.rvEvents.adapter = mEventAdapter
}
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
when(item?.itemId) {
R.id.online_item ->{
mSelectedCity = UtilConstants.DEFAULT_CITY
}
R.id.delhi_item ->{
mSelectedCity = UtilConstants.DELHI_CITY
}
R.id.lucknow_item ->{
mSelectedCity = UtilConstants.LUCKNOW_CITY
}
R.id.pune_item ->{
mSelectedCity = UtilConstants.PUNE_CITY
}
R.id.kolkata_item ->{
mSelectedCity = UtilConstants.KOLKATA_CITY
}
R.id.mumbai_item ->{
mSelectedCity = UtilConstants.MUMBAI_CITY
}
else -> {
return false
}
}
item.isChecked = true
initFetchEventData()
return true
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedItem = parent?.getItemAtPosition(position).toString()
if(selectedItem != mCurrentEventType) {
mCurrentEventType = selectedItem
setEventAdapter()
}
}
}<file_sep>package com.example.evanto.homeSection.dataManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.example.evanto.helpers.UtilConstants
import com.example.evanto.homeSection.model.ModelEvents
class ViewModelEventsList : ViewModel() {
fun fetchAllEvents(city:String? = UtilConstants.DEFAULT_CITY) {
EventsRepository.fetchAllEvents(city)
}
fun getAllEvents() : LiveData<ModelEvents>? {
return EventsRepository.masterEventsList
}
}<file_sep>package com.example.evanto.homeSection.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.evanto.R
import com.example.evanto.databinding.LayoutEventItemBinding
import com.example.evanto.homeSection.dataManager.MasterListEventModel
class EventAdapter(private val mContext:Context?,private var mEventList:ArrayList<MasterListEventModel>?) : RecyclerView.Adapter<EventAdapter.MyViewHolder>(){
fun updateList(eventList:ArrayList<MasterListEventModel>?) {
mEventList = eventList
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventAdapter.MyViewHolder {
val layoutEventItemBinding : LayoutEventItemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context),
R.layout.layout_event_item,parent,false)
return MyViewHolder(layoutEventItemBinding)
}
override fun getItemCount(): Int = mEventList?.size ?: 0
override fun onBindViewHolder(holder: EventAdapter.MyViewHolder, position: Int) {
val eventData = mEventList?.get(position)
holder.itemBinding.model = eventData
holder.itemBinding.eventPrice.text = if(eventData?.eventPriceDisplayString?.equals("0",ignoreCase = false) == true) "FREE" else eventData?.eventPriceDisplayString
holder.itemBinding.eventDate.isSelected = true
setImageWithGlide(holder.itemBinding.eventIv,eventData)
}
private fun setImageWithGlide(eventIv: ImageView, eventData: MasterListEventModel?) {
if(mContext==null) {
eventIv.setImageResource(R.drawable.bg_default_event)
return
}
eventData?.horizontalCoverImage?.let {
Glide
.with(mContext)
.load(it)
.placeholder(R.drawable.bg_default_event)
.into(eventIv)
}
}
inner class MyViewHolder(val itemBinding: LayoutEventItemBinding) : RecyclerView.ViewHolder(itemBinding.root)
}<file_sep>package com.example.evanto.retrofitManager
import com.example.evanto.homeSection.dataManager.ResponseModelEvents
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.Exception
import kotlin.collections.HashMap
class RetrofitCallbackManager (private var apiInterface: ApiInterface?, private var apiResponseCallback: ApiResponseCallback?, private var fieldMap: HashMap<String, String>?, private var apiProviderConstants: Int) {
private fun<T> sendCallbacks(call:Call<T>){
call.enqueue(object : Callback<T>{
override fun onResponse(call: Call<T>, response: Response<T>) {
apiResponseCallback?.onSuccessCallback(response, apiProviderConstants)
}
override fun onFailure(call: Call<T>, t: Throwable) {
apiResponseCallback?.onFailureCallback(t.message,apiProviderConstants)
}
})
}
//add all apiCallMethods
fun homePageData(){
try {
val call: Call<ResponseModelEvents?>? = apiInterface?.homePageData(fieldMap!!)
call?.let { sendCallbacks(it) }
} catch (e:Exception) {
apiResponseCallback?.onFailureCallback(e.message,apiProviderConstants)
}
}
}<file_sep>package com.example.evanto.helpers
class UtilMethods {
companion object {
fun prepareFetchEventsHashMap(city:String?) : HashMap<String,String> {
val hashMap = HashMap<String,String>()
hashMap[UtilConstants.PARAM_NORM] = "1"
hashMap[UtilConstants.PARAM_FILTER_BY] = "go-out"
hashMap[UtilConstants.PARAM_CITY] = city ?: UtilConstants.DEFAULT_CITY
return hashMap
}
}
}<file_sep>package com.example.evanto.retrofitManager
import com.example.evanto.homeSection.dataManager.ResponseModelEvents
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.QueryMap
interface ApiInterface {
@GET(UrlContainer.END_URL_HOME_PAGE)
fun homePageData(@QueryMap fieldMap: HashMap<String,String>): Call<ResponseModelEvents?>
}<file_sep>package com.example.evanto.homeSection.dataManager
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class ResponseModelEvents(
@SerializedName("list")
@Expose
val list: EventsList?,
@SerializedName("popular")
@Expose
val popularEventList: ArrayList<MasterListEventModel>?,
@SerializedName("featured")
@Expose
val featuredEventList: ArrayList<MasterListEventModel>?
)
data class EventsList(
@SerializedName("masterList")
@Expose
val masterList: LinkedHashMap<String, MasterListEventModel>?
)
data class MasterListEventModel(
@SerializedName("_id")
@Expose
val eventId: String?,
@SerializedName("min_show_start_time")
@Expose
val minShowStartTime: Int,
@SerializedName("name")
@Expose
val eventName: String?,
@SerializedName("type")
@Expose
val eventType: String?,
@SerializedName("slug")
@Expose
val eventSlug: String?,
@SerializedName("horizontal_cover_image")
@Expose
val horizontalCoverImage: String?,
@SerializedName("city")
@Expose
val eventCity: String?,
@SerializedName("venue_id")
@Expose
val eventVenueId: String?,
@SerializedName("venue_name")
@Expose
val eventVenueName: String?,
@SerializedName("venue_date_string")
@Expose
val eventVenueDateString: String?,
@SerializedName("is_rsvp")
@Expose
val eventIsRsvp: String?,
@SerializedName("event_state")
@Expose
val eventState: String?,
@SerializedName("price_display_string")
@Expose
val eventPriceDisplayString: String?,
@SerializedName("communication_strategy")
@Expose
val eventCommunicationStrategy: String?,
@SerializedName("model")
@Expose
val eventModel: String?,
@SerializedName("popularity_score")
@Expose
val eventPopularityScore: Double?,
@SerializedName("min_price")
@Expose
val eventMinPrice: Int?,
@SerializedName("category_id")
@Expose
val categoryInfo: CategoryInfo?
)
data class CategoryInfo(
@SerializedName("_id")
@Expose
val cat_id: String?,
@SerializedName("name")
@Expose
val cat_name: String?,
@SerializedName("icon_img")
@Expose
val cat_img: String?
) | 1edc093450663133da4c47ee0d67276586aab413 | [
"Kotlin"
] | 15 | Kotlin | himanshu24yadav/demoEventsBooking | 1e549f97afe21dcd23d74b6786a1536db9e5783f | e995e0e8d708752bf3359375ef32d4e0bc6cc5f7 |
refs/heads/master | <repo_name>K-OpenNet/OpenStack-MultiView<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/BackendManifest.java
package chainlinker;
import java.util.HashMap;
public class BackendManifest {
private HashMap<String, Class<? extends Backend>> backendManifestMap = new HashMap<>();
private BackendManifest() {
backendManifestMap.put("influxdb", BackendInfluxDB.class);
}
public HashMap<String, Class<? extends Backend>> getBackendManifestMap() {
return backendManifestMap;
}
// Singleton part for this class as this class does not need to exist in multitude.
private static BackendManifest instance = new BackendManifest();
public static BackendManifest getInstance () {
return instance;
}
}
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/resource/PingStatusUpdateClass.java
/**
* @author <NAME>
* @version 0.1
*/
package smartx.multiview.collectors.resource;
import static java.util.Arrays.asList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.result.UpdateResult;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
import smartx.multiview.DataLake.MongoDB_Connector;
public class PingStatusUpdateClass implements Runnable {
private Thread thread;
private String ThreadName = "pBox Status Update Thread";
private String SmartXBox_USER, SmartXBox_PASSWORD, ovsVM_USER, ovsVM_PASSWORD;
private String m_status, m_status_new, d_status;
private String boxName = "", activeVM, m_ip = "", d_ip = "", ovsVM1ip, ovsVM2ip, boxtype;
private String pboxMongoCollection, pboxstatusMongoCollectionRT;
private String[] BoxType;
private FindIterable<Document> pBoxList;
private FindIterable<Document> pBoxStatus;
private List<String> bridges = new ArrayList<String>();
private MongoDB_Connector mongoConnector;
private Date timestamp;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Logger LOG = Logger.getLogger("pingUpdateFile");
public PingStatusUpdateClass(String boxUser, String boxPassword, MongoDB_Connector MongoConn, String pbox,
String pboxstatus, String[] boxType, String ovsVMUser, String ovsVMPass) {
SmartXBox_USER = boxUser;
SmartXBox_PASSWORD = <PASSWORD>;
ovsVM_USER = ovsVMUser;
ovsVM_PASSWORD = <PASSWORD>;
mongoConnector = MongoConn;
BoxType = boxType;
pboxMongoCollection = pbox;
pboxstatusMongoCollectionRT = pboxstatus;
}
public void getActiveVM(String serverIp, String command, String usernameString, String password) {
try {
Connection conn = new Connection(serverIp);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
ch.ethz.ssh2.Session sess = conn.openSession();
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
if (line != null) {
activeVM = line;
}
}
br.close();
sess.close();
conn.close();
} catch (IOException e) {
System.out.println("[INFO][OVS-VM][Box : " + serverIp + " Failed");
LOG.debug("[" + dateFormat.format(timestamp) + "][INFO][PING][UPDATE]" + serverIp + " Failed"
+ e.getStackTrace());
e.printStackTrace(System.err);
}
}
public String getBoxStatus(String serverMgmtIp, String serverDataIp, String command, String usernameString,
String password, String type) {
String InterfaceStatus = null;
try {
Connection conn = new Connection(serverMgmtIp);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
ch.ethz.ssh2.Session sess = conn.openSession();
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stdout2;
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
BufferedReader br2;
if (br.readLine() != null) {
int index = 0;
InterfaceStatus = "GREEN";
ch.ethz.ssh2.Session sess2 = conn.openSession();
sess2.execCommand(
"sudo ovs-ofctl show brcap | grep vxlan | cut -f 1 -d : | cut -f 2 -d '(' | cut -f 1 -d ')'");
stdout = new StreamGobbler(sess2.getStdout());
br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String host = br.readLine();
System.out.println(host);
if (host == null) {
if (index == 0)
InterfaceStatus = "ORANGE";
index = 1;
// System.out.println("InterfaceStatus : "+InterfaceStatus);
break;
}
index++;
// System.out.print(host);
if (host != null) {
// System.out.println("Host : "+host);
ch.ethz.ssh2.Session sess3 = conn.openSession();
if (type.equals("B"))
sess3.execCommand("ping -c 1 `sudo ovs-vsctl show | grep -A2 " + host
+ " | grep remote_ip | cut -d '\"' -f 2` | grep ttl");
else
sess3.execCommand("ping -c 1 `sudo ovs-vsctl show | grep -A2 " + host
+ " | grep remote_ip | cut -d '\"' -f 4` | grep ttl");
stdout2 = new StreamGobbler(sess3.getStdout());
br2 = new BufferedReader(new InputStreamReader(stdout2));
if (br2.readLine() == null) {
InterfaceStatus = "ORANGE";
System.out.println(InterfaceStatus+ " " +serverMgmtIp);
break;
} else {
InterfaceStatus = "GREEN";
System.out.println(InterfaceStatus+ " " +serverMgmtIp);
}
}
}
br.close();
sess.close();
conn.close();
} else {
InterfaceStatus = "RED";
sess.close();
conn.close();
}
} catch (IOException e) {
// System.out.println("[INFO][PING][UPDATE][Box : "+serverMgmtIp+" Failed");
LOG.debug("[" + dateFormat.format(timestamp) + "][ERROR][PING][UPDATE][Box : " + serverMgmtIp + " Failed");
e.printStackTrace(System.err);
}
return InterfaceStatus;
}
public void update_status() {
timestamp = new Date();
// pBoxList = db.getCollection(pboxMongoCollection).find(new Document("type",
// BoxType).append("type", "C**"));
/*pBoxList = mongoConnector.getDbConnection().getCollection(pboxMongoCollection)
.find(new Document("$or", asList(new Document("type", BoxType[0]), new Document("type", BoxType[1]))));*/
pBoxList = mongoConnector.getDbConnection().getCollection(pboxMongoCollection)
.find(new Document("$or", asList(new Document("type", BoxType[0]), new Document("type", BoxType[1]))));
pBoxList.forEach(new Block<Document>() {
public void apply(final Document document) {
boxName = (String) document.get("boxName");
m_ip = (String) document.get("management_ip");
d_ip = (String) document.get("data_ip");
m_status = (String) document.get("management_ip_status");
ovsVM1ip = (String) document.get("ovs_vm1");
ovsVM2ip = (String) document.get("ovs_vm2");
activeVM = (String) document.get("active_ovs_vm");
boxtype = (String) document.get("boxType");
// Get Management Plane Status & Update pBox Status Collection
pBoxStatus = mongoConnector.getDataDB(pboxstatusMongoCollectionRT, "destination", m_ip);
pBoxStatus.forEach(new Block<Document>() {
public void apply(final Document document2) {
m_status_new = document2.get("status").toString().toUpperCase();
if (m_status_new.equalsIgnoreCase("UP")) {
m_status_new = "GREEN";
System.out.println(boxtype+" "+boxName);
// Get Data Plane Status
if (boxtype.equals("B")) {
// Get Active OVS-VM
//getActiveVM(m_ip, "virsh list | grep ovs-vm | grep running | awk '{print $2}'",
// SmartXBox_USER, SmartXBox_PASSWORD);
activeVM="ovs-vm1";
if (boxName.equals("SmartX-Box-MYREN") || boxName.equals("SmartX-Box-PH")) {
d_status = getBoxStatus(activeVM.equals("ovs-vm1") ? ovsVM1ip : ovsVM2ip, d_ip,
"ip r | grep " + d_ip, SmartXBox_USER,
SmartXBox_PASSWORD, boxtype);
System.out.println("Check 1"+boxName+" "+d_status);
}
else {
d_status = getBoxStatus(activeVM.equals("ovs-vm1") ? ovsVM1ip : ovsVM2ip, d_ip,
"ip r | grep " + d_ip, ovsVM_USER,
ovsVM_PASSWORD, boxtype);
System.out.println("Check 2"+boxName+" "+d_status);
}
}
else{
d_status = getBoxStatus(m_ip, d_ip,
"ip r | grep " + d_ip, "visibility",
SmartXBox_PASSWORD, boxtype);
System.out.println("Check 3"+boxName+" "+d_status);
}
} else {
m_status_new = "RED";
d_status = "RED";
}
UpdateResult result = mongoConnector.getDbConnection().getCollection(pboxMongoCollection)
.updateOne(new Document("management_ip", m_ip),
new Document("$set", new Document("management_ip_status", m_status_new)
.append("data_ip_status", d_status).append("active_ovs_vm", activeVM)));
document.remove("_id");
document.put("timestamp", new Date());
mongoConnector.getDbConnection().getCollection("pbox-list-history").insertOne(document);
LOG.debug("[" + dateFormat.format(timestamp) + "][INFO][PING][UPDATE][Box: " + m_ip
+ " Management Status: " + m_status_new + " Data Status: " + d_status + " Active VM: "
+ activeVM + " Records Updated :" + result.getModifiedCount() + "]");
// System.out.println("["+dateFormat.format(timestamp)+"][INFO][PING][MVC][Box:
// "+m_ip+" Management Status: "+m_status_new+" Data Status: "+d_status+" Active
// VM: "+activeVM+" Records Updated :"+result.getModifiedCount()+"]");
activeVM = null;
}
});
}
});
}
public void run() {
while (true) {
update_status();
try {
// Sleep For 30 Seconds
Thread.sleep(30000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
System.out.println("Starting pBox Status Update Thread");
if (thread == null) {
thread = new Thread(this, ThreadName);
thread.start();
}
}
}
<file_sep>/MultiView-Dependencies/Install_Elasticsearch.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_Elasticsearch.sh
# Description : Script for Installing Elasticsearch
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : October, 2016
MGMT_IP=$1
Elasticsearch=`dpkg -l | grep elasticsearch`
if [ "$Elasticsearch" == "" ]; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Elasticsearch Installing .................... "
CurrentDir=`pwd`
cd /tmp/
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.0.0.deb &> /dev/null
sudo dpkg -i elasticsearch-5.0.0.deb &> /dev/null
sudo update-rc.d elasticsearch defaults 95 10 &> /dev/null
# Configure Elasticsearch
sed -i "s/#cluster.name: elasticsearch/cluster.name: elasticsearch/g" /etc/elasticsearch/elasticsearch.yml
sed -i "s/#network.host: 192.168.0.1/network.host: $MGMT_IP/g" /etc/elasticsearch/elasticsearch.yml
sudo service elasticsearch restart &> /dev/null
echo -e "Done.\n"
#cd /usr/share/elasticsearch
#bin/elasticsearch-plugin install mobz/elasticsearch-head
cd $CurrentDir
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Elasticsearch Already Installed."
#echo `curl -XGET '$MGMT_IP:9200'`
fi
<file_sep>/Visibility-Integration/multi-view-flowcentric-integration.sh
#!/bin/bash
#
# Copyright 2015 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : multi-view-flowcentric-integration.sh
# Description : Run spark submit jobs.
#
# Created by : <NAME>
# Version : 0.1
# Last Update : January, 2019
export PATH=$PATH:$SPARK_HOME
export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export SPARK_HOME=/opt/KONE-MultiView/MultiView-Dependencies/spark-2.2.0-bin-hadoop2.7
while :
do
minute="$(date +'%-M')"
remainder=$(( minute % 5 ))
if [ "$remainder" -eq 0 ]; then
sleep 60
$SPARK_HOME/bin/spark-submit --class smartx.multiview.flowcentric.Main --master local[*] --driver-memory 24g multi-view-flowcentric-tag-aggregate_2.11-0.1.jar "vc.manage.overcloud" &&
$SPARK_HOME/bin/spark-submit --class smartx.multiview.flowcentric.Main --master local[*] --driver-memory 16g multi-view-flowcentric-integration_2.11-0.1.jar "vc.manage.overcloud"
else
sleep 20
fi
done
<file_sep>/Visibility-Agent/IOVisor/management_plane_tracing.py
#!/usr/bin/python
#
# Name : management_plane_tacing.py
# Description : A script for processing network packets at user-level
#
# Created by : <NAME>
# Version : 0.2
# Last Update : June, 2018
from __future__ import print_function
from bcc import BPF
from datetime import datetime
import sys
import socket
import os
import argparse
import netifaces as ni
import time
from kafka import KafkaProducer
from kafka.errors import KafkaError
import json
# convert a bin string into a string of hex char
# helper function to print raw packet in hex
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0' + hv
lst.append(hv)
return reduce(lambda x, y:x + y, lst)
# initialize BPF - load source code from http-parse-simple.c
bpf = BPF(src_file="mcd_planes_tracing.c", debug=0)
# load eBPF program http_filter of type SOCKET_FILTER into the kernel eBPF vm
# more info about eBPF program types http://man7.org/linux/man-pages/man2/bpf.2.html
function_ip_filter = bpf.load_func("ip_filter", BPF.SOCKET_FILTER)
# create raw socket, bind it to eth0
# attach bpf program to socket created
BPF.attach_raw_socket(function_ip_filter, "eno2")
ni.ifaddresses('eno2')
ip = ni.ifaddresses('eno2')[ni.AF_INET][0]['addr']
# get file descriptor of the socket previously created inside BPF.attach_raw_socket
socket_fd = function_ip_filter.sock
# create python socket object, from the file descriptor
sock = socket.fromfd(socket_fd, socket.PF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
# set it as blocking socket
sock.setblocking(True)
print("MachineIP Hostname ipver Src IP Addr Dst IP Addr src Port Dst Port protocol TCP_Window_Size Packet_Length")
count_c1 = 0
while 1:
# retrieve raw packet from socket
packet_str = os.read(socket_fd, 2048)
# DEBUG - print raw packet in hex format
# packet_hex = toHex(packet_str)
# print ("%s" % packet_hex)
# convert packet into bytearray
packet_bytearray = bytearray(packet_str)
# ethernet header length
ETH_HLEN = 14
# IP HEADER
# https://tools.ietf.org/html/rfc791
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |Version| IHL |Type of Service| Total Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# IHL : Internet Header Length is the length of the internet header
# value to multiply * 4 byte
# e.g. IHL = 5 ; IP Header Length = 5 * 4 byte = 20 byte
#
# Total length: This 16-bit field defines the entire packet size,
# including header and data, in bytes.
# calculate packet total length
total_length = packet_bytearray[ETH_HLEN + 2] # load MSB
total_length = total_length << 8 # shift MSB
total_length = total_length + packet_bytearray[ETH_HLEN + 3] # add LSB
# calculate ip header length
ip_header_length = packet_bytearray[ETH_HLEN] # load Byte
ip_header_length = ip_header_length & 0x0F # mask bits 0..3
ip_header_length = ip_header_length << 2 # shift to obtain length
# TCP HEADER
# https://www.rfc-editor.org/rfc/rfc793.txt
# 12 13 14 15
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Data | |U|A|P|R|S|F| |
# | Offset| Reserved |R|C|S|S|Y|I| Window |
# | | |G|K|H|T|N|N| |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# Data Offset: This indicates where the data begins.
# The TCP header is an integral number of 32 bits long.
# value to multiply * 4 byte
# e.g. DataOffset = 5 ; TCP Header Length = 5 * 4 byte = 20 byte
# calculate tcp header length
tcp_header_length = packet_bytearray[ETH_HLEN + ip_header_length + 12] # load Byte
tcp_header_length = tcp_header_length & 0xF0 # mask bit 4..7
tcp_header_length = tcp_header_length >> 2 # SHR 4 ; SHL 2 -> SHR 2
# calculate payload offset
payload_offset = ETH_HLEN + ip_header_length + tcp_header_length
# parsing ip version from ip packet header
ipversion = str(bin(packet_bytearray[14])[2:5])
# parsing source ip address, destination ip address from ip packet header
srcAddr = str(packet_bytearray[26]) + "." + str(packet_bytearray[27]) + "." + str(packet_bytearray[28]) + "." + str(packet_bytearray[29])
dstAddr = str(packet_bytearray[30]) + "." + str(packet_bytearray[31]) + "." + str(packet_bytearray[32]) + "." + str(packet_bytearray[33])
# parsing source port and destination port
if (packet_bytearray[23] == 6):
protocol = 6
srcPort = packet_bytearray[34] << 8 | packet_bytearray[35]
dstPort = packet_bytearray[36] << 8 | packet_bytearray[37]
TCP_Window_Size = packet_bytearray[48] << 8 | packet_bytearray[49]
elif (packet_bytearray[23] == 1):
protocol = 1
srcPort = -1
dstPort = -1
TCP_Window_Size = 0
elif (packet_bytearray[23] == 17):
protocol = 17
srcPort = packet_bytearray[34] << 8 | packet_bytearray[35]
dstPort = packet_bytearray[36] << 8 | packet_bytearray[37]
TCP_Window_Size = 0
else:
protocol = -1
srcPort = packet_bytearray[34] << 8 | packet_bytearray[35]
dstPort = packet_bytearray[36] << 8 | packet_bytearray[37]
TCP_Window_Size = 0
MESSAGE = str(int(round(time.time() * 1000000))) + ",0," + socket.gethostname() + "," + ip + "," + str(int(ipversion, 2)) + "," + srcAddr + "," + dstAddr + "," + str(srcPort) + "," + str(dstPort) + "," + str(protocol) + "," + str(TCP_Window_Size) + "," + str(total_length)
print (MESSAGE)
CurrentMin = int(time.strftime("%M"))
BoxName=socket.gethostname()
if (CurrentMin < 30):
if (CurrentMin < 10):
if (CurrentMin < 5):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-00"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-05"
elif (CurrentMin < 20):
if (CurrentMin < 15):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-10"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-15"
else:
if (CurrentMin < 25):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-20"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-25"
else:
if (CurrentMin < 40):
if (CurrentMin < 35):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-30"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-35"
elif (CurrentMin < 50):
if (CurrentMin < 45):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-40"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-45"
else:
if (CurrentMin < 55):
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-50"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-mc-" + time.strftime("%Y-%m-%d-%H") + "-55"
f = open(filename, "a")
f.write("%s\n" % MESSAGE)
f.close
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/resource/SmartXBoxesPerformance.java
/**
* @author <NAME>
* @version 0.1
*/
package smartx.multiview.collectors.resource;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.bson.Document;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import smartx.multiview.DataLake.MongoDB_Connector;
public class SmartXBoxesPerformance implements Runnable{
private Thread thread;
private String ThreadName = "SmartX Box Performance Metrics Thread";
private String bootstrapServer;
private String topic = "snap-pbox-visibility";
private String ESindex = "smartx-boxes-metrics-1";
@SuppressWarnings("rawtypes")
private Map data = new HashMap();
private Map SmartX_Box_List = new HashMap();
private Map SmartX_Box_Mgmt_NIC = new HashMap();
private Map SmartX_Box_Ctrl_NIC = new HashMap();
private Map SmartX_Box_Data_NIC = new HashMap();
TransportClient client;
private long index = 0;
private Date timestamp;
private KafkaConsumer<String, String> consumer;
private MongoDB_Connector mongoConnector;
private List<Document> documentsRT = new ArrayList<Document>();
private FindIterable<Document> SmartXBoxInterfaces;
private String SmartXBoxInterfacesMongoCollection="pbox-nic-tags";
@SuppressWarnings({ "resource", "unchecked" })
public SmartXBoxesPerformance(MongoDB_Connector MongoConn, String bootstrapserver, String ElasticHost, int ElasticPort) {
bootstrapServer = bootstrapserver;
mongoConnector = MongoConn;
try {
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new TransportAddress(InetAddress.getByName(ElasticHost), ElasticPort));
} catch (UnknownHostException e) {
e.printStackTrace();
}
boolean indexStatus = client.admin().indices().prepareExists(ESindex).execute().actionGet().isExists();
if (!indexStatus) {
System.out.println("Index Does not Exist");
client.admin().indices().prepareCreate(ESindex).execute().actionGet();
} else {
SearchHits resp = client.prepareSearch(ESindex).get().getHits();
index = resp.getTotalHits();
System.out.println("Total Records in Index: " + index);
}
//Get List of SmartX Boxes
SmartXBoxInterfaces = mongoConnector.getDataDB(SmartXBoxInterfacesMongoCollection);
SmartXBoxInterfaces.forEach(new Block<Document>() {
public void apply(final Document document) {
SmartX_Box_List.put((String) document.get("boxName"), (String) document.get("boxName")) ;
SmartX_Box_Mgmt_NIC.put((String) document.get("boxName"), (String) document.get("management"));
SmartX_Box_Ctrl_NIC.put((String) document.get("boxName"), (String) document.get("control"));
SmartX_Box_Data_NIC.put((String) document.get("boxName"), (String) document.get("data"));
}
});
}
public void Consume() {
// Kafka & Zookeeper Properties
Properties props = new Properties();
props.put("bootstrap.servers", bootstrapServer);
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Arrays.asList(topic));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(0);
for (ConsumerRecord<String, String> record : records) {
this.StoreToDB(record.value());
}
}
}
@SuppressWarnings("unchecked")
public void StoreToDB(String record) {
timestamp = new Date();
JSONParser parser = new JSONParser();
JSONObject json = null;
JSONObject json2 = null;
String keyName = null;
String boxID = null;
Float keyValue = null;
try {
JSONArray array = (JSONArray) parser.parse(record);
json2 = (JSONObject) ((JSONObject) array.get(0)).get("tags");
boxID = json2.get("BoxID").toString();
data.put("BoxID", boxID);
System.out.println("[SmartX Box ID] : "+boxID);
if (SmartX_Box_List.containsKey(boxID))
{
for (int i = 0; i < array.size(); i++) {
json = (JSONObject) array.get(i);
keyName = json.get("namespace").toString();
if (keyName.contains("/intel/psutil/load/load1")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("load1", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/psutil/load/load5")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("load5", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/psutil/load/load15")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("loadfifteen", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%system")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("system", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%nice")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("nice", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%user")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("user", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%iowait")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("iowait", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%steal")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("steal", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/linux/iostat/avg-cpu/%idle")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("idle", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/mem_total")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mem_total", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/mem_used")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mem_used", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/mem_free")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mem_free", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/buffers")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("buffers", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/cached")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("cached", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/meminfo/mem_available")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mem_available", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Mgmt_NIC.get(boxID) +"/bytes_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mgmt_bytes_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Mgmt_NIC.get(boxID) +"/bytes_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mgmt_bytes_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Mgmt_NIC.get(boxID) +"/packets_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mgmt_packets_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Mgmt_NIC.get(boxID) +"/packets_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("mgmt_packets_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Ctrl_NIC.get(boxID) +"/bytes_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("ctrl_bytes_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Ctrl_NIC.get(boxID) +"/bytes_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("ctrl_bytes_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Ctrl_NIC.get(boxID) +"/packets_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("ctrl_packets_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Ctrl_NIC.get(boxID) +"/packets_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("ctrl_packets_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Data_NIC.get(boxID) +"/bytes_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("data_bytes_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Data_NIC.get(boxID) +"/bytes_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("data_bytes_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Data_NIC.get(boxID) +"/packets_sent")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("data_packets_sent", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/iface/"+ SmartX_Box_Data_NIC.get(boxID) +"/packets_recv")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("data_packets_recv", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/filesystem/rootfs/device_name")) {
data.put("device_name", json.get("data").toString());
/*System.out.println(keyName);
System.out.println(json.get("data").toString());*/
} else if (keyName.contains("/intel/procfs/filesystem/rootfs/space_used")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("space_used", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
} else if (keyName.contains("/intel/procfs/filesystem/rootfs/space_free")) {
keyValue = Float.parseFloat(json.get("data").toString());
data.put("space_free", keyValue);
/*System.out.println(keyName + ": " + keyValue);*/
}
}
// Insert data into Elasticsearch.
try {
XContentBuilder builder = jsonBuilder()
.startObject()
.field("@version", "1")
.field("@timestamp", timestamp).field("BoxID", data.get("BoxID").toString())
.field("load1", data.get("load1")).field("load5", data.get("load5"))
.field("load15", data.get("loadfifteen")).field("system", data.get("system"))
.field("user", data.get("user")).field("steal", data.get("steal"))
.field("nice", data.get("nice")).field("iowait", data.get("iowait"))
.field("idle", data.get("idle")).field("mem_total", data.get("mem_total"))
.field("mem_used", data.get("mem_used")).field("mem_free", data.get("mem_free"))
.field("mem_available", data.get("mem_available")).field("buffers", data.get("buffers"))
.field("cached", data.get("cached")).field("device_name", data.get("device_name"))
.field("space_total",
Float.parseFloat(data.get("space_used").toString())
+ Float.parseFloat(data.get("space_free").toString()))
.field("space_used", data.get("space_used")).field("space_free", data.get("space_free"))
.field("mgmt_interface", SmartX_Box_Mgmt_NIC.get(boxID))
.field("mgmt_bytes_sent", data.get("mgmt_bytes_sent"))
.field("mgmt_bytes_recv", data.get("mgmt_bytes_recv"))
.field("mgmt_packets_sent", data.get("mgmt_packets_sent"))
.field("mgmt_packets_recv", data.get("mgmt_packets_recv"))
.field("ctrl_interface", SmartX_Box_Ctrl_NIC.get(boxID))
.field("ctrl_bytes_sent", data.get("ctrl_bytes_sent"))
.field("ctrl_bytes_recv", data.get("ctrl_bytes_recv"))
.field("ctrl_packets_sent", data.get("ctrl_packets_sent"))
.field("ctrl_packets_recv", data.get("ctrl_packets_recv"))
.field("data_interface", SmartX_Box_Data_NIC.get(boxID))
.field("data_bytes_sent", data.get("data_bytes_sent"))
.field("data_bytes_recv", data.get("data_bytes_recv"))
.field("data_packets_sent", data.get("data_packets_sent"))
.field("data_packets_recv", data.get("data_packets_recv"))
.endObject();
index = index + 1;
//System.out.println(index);
client.prepareIndex(ESindex, "instance", index + "").setSource(builder).execute();
data.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
this.Consume();
}
}
public void start() {
if (thread == null) {
thread = new Thread(this, ThreadName);
thread.start();
}
}
}
<file_sep>/Visibility-Agent/VM-Monitoring/tecmint_monitor.sh
#!/bin/bash
#
# Copyright 2018 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name :
# Description : Script for monitoring vm resource usage
#
# Created by : <NAME>
# Version : 0.1
# Last Update : June, 2018
#
# clear the screen
clear
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
while getopts iv name
do
case $name in
i)iopt=1;;
v)vopt=1;;
*)echo "Invalid arg";;
esac
done
if [[ ! -z $iopt ]]
then
{
wd=$(pwd)
basename "$(test -L "$0" && readlink "$0" || echo "$0")" > /tmp/scriptname
scriptname=$(echo -e -n $wd/ && cat /tmp/scriptname)
su -c "cp $scriptname /usr/bin/monitor" root && echo "Congratulations! Script Installed, now run monitor Command" || echo "Installation failed"
}
fi
if [[ ! -z $vopt ]]
then
{
echo -e "tecmint_monitor version 0.1\nDesigned by Tecmint.com\nReleased Under Apache 2.0 License"
}
fi
if [[ $# -eq 0 ]]
then
{
# Define Variable tecreset
tecreset=$(tput sgr0)
# Check if connected to Internet or not
ping -c 1 google.com &> /dev/null && echo -e '\E[32m'"Internet: $tecreset Connected" || echo -e '\E[32m'"Internet: $tecreset Disconnected"
# Check OS Type
os=$(uname -o)
echo -e '\E[32m'"Operating System Type :" $tecreset $os
# Check OS Release Version and Name
cat /etc/os-release | grep 'NAME\|VERSION' | grep -v 'VERSION_ID' | grep -v 'PRETTY_NAME' > /tmp/osrelease
echo -n -e '\E[32m'"OS Name :" $tecreset && cat /tmp/osrelease | grep -v "VERSION" | cut -f2 -d\"
echo -n -e '\E[32m'"OS Version :" $tecreset && cat /tmp/osrelease | grep -v "NAME" | cut -f2 -d\"
# Check Architecture
architecture=$(uname -m)
echo -e '\E[32m'"Architecture :" $tecreset $architecture
# Check Kernel Release
kernelrelease=$(uname -r)
echo -e '\E[32m'"Kernel Release :" $tecreset $kernelrelease
# Check hostname
echo -e '\E[32m'"Hostname :" $tecreset $HOSTNAME
# Check Internal IP
internalip=$(hostname -I)
echo -e '\E[32m'"Internal IP :" $tecreset $internalip
# Check External IP
externalip=$(curl -s ipecho.net/plain;echo)
echo -e '\E[32m'"External IP : $tecreset "$externalip
# Check DNS
nameservers=$(cat /etc/resolv.conf | sed '1 d' | awk '{print $2}')
echo -e '\E[32m'"Name Servers :" $tecreset $nameservers
# Check Logged In Users
who>/tmp/who
echo -e '\E[32m'"Logged In users :" $tecreset && cat /tmp/who
# Check RAM and SWAP Usages
free -h | grep -v + > /tmp/ramcache
echo -e '\E[32m'"Ram Usages :" $tecreset
cat /tmp/ramcache | grep -v "Swap"
echo -e '\E[32m'"Swap Usages :" $tecreset
cat /tmp/ramcache | grep -v "Mem"
# Check Disk Usages
df -h| grep 'Filesystem\|/dev/vda*' > /tmp/diskusage
echo -e '\E[32m'"Disk Usages :" $tecreset
cat /tmp/diskusage
# Check Load Average
#loadaverage=$(top -n 1 -b | grep "load average:" | awk '{print $12 $13 $14}')
loadaverage=$(top -n 1 -b | grep "load average:" | rev | cut -d: -f1 | rev |awk '{print $1 $2 $3}')
echo -e '\E[32m'"Load Average :" $tecreset $loadaverage
# Check System Uptime
tecuptime=$(uptime | awk '{print $3,$4}' | cut -f1 -d,)
echo -e '\E[32m'"System Uptime Days/(HH:MM) :" $tecreset $tecuptime
memusage=$( cat /tmp/ramcache)
diskusage=$( cat /tmp/diskusage)
free -h | grep "Mem:" | awk '{print $2,$3,$4,$5,$6,$7}' > memmetrics.log
df -h | grep "/dev/vda1" | awk '{print $2,$3,$4,$5}' > dfmetrics.log
echo "$HOSTNAME,$os,$architecture,$kernelrelease,$internalip,$externalip,$loadaverage" > instancemetrics.log
# Unset Variables
unset tecreset os architecture kernelrelease internalip externalip nameserver loadaverage
# Remove Temporary Files
rm /tmp/osrelease /tmp/who /tmp/ramcache /tmp/diskusage
}
fi
shift $(($OPTIND -1))
<file_sep>/Visibility-Integration/correlation/src/main/java/smartx/multiview/integrationMain/CorrelatorMain.java
package smartx.multiview.integrationMain;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.PropertyConfigurator;
import smartx.multiview.workers.*;
import smartx.multiview.sdncontrollers.*;
public class CorrelatorMain
{
protected Date startDate = new Date();//new Date(System.currentTimeMillis() - 3600 * 4 * 1000);
private Date endDate = new Date();//new Date(System.currentTimeMillis() - 3600 * 1 * 1000);
private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
private String key = "192.168.1.1,8081,192.168.1.4,eth.ip.tcp", srcIP, srcPort, destIP, destPort, protocol, srcpBox, destpBox;
private String topic = "FlowVisibility";
private String collection = "flowlevel-data";
private String zookeeper = "x.x.x.x:2181";
private String mongodb = "x.x.x.x";
private String elasticsearch = "x.x.x.x";
public CorrelatorMain(String sDate, String eDate, String src, String dest, String srcP, String devontroller, String prot, String opscontroller, CorrelatorGUIWindow GuiWindow)
{
PropertyConfigurator.configure("log4j.properties");
System.out.println("Starting Consumer ...");
srcIP = src;
destIP = dest;
srcPort = srcP;
protocol = prot;
key = srcIP+","+srcPort+","+destIP+","+protocol;
try {
startDate = dateFormat.parse(sDate);
endDate = dateFormat.parse(eDate);
}catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SourceWorker srcWorker = new SourceWorker(zookeeper, mongodb, elasticsearch, "flow-consumer1", collection, key, startDate, endDate, srcIP, destIP, srcPort, protocol, GuiWindow);
srcWorker.function1();
srcWorker.function2();
srcWorker.function4();
DestinationWorker destWorker = new DestinationWorker(zookeeper, mongodb, elasticsearch, "flow-consumer1", collection, key, startDate, endDate, srcIP, destIP, srcPort, protocol, GuiWindow);
destWorker.function1();
destWorker.function2();
destWorker.function4();
ControllerFlows controllerflows=new ControllerFlows(elasticsearch, devontroller, opscontroller);
controllerflows.getFlowDetailsOps();
controllerflows.getFlowDetailsDev();
controllerflows.getTopology();
}
}
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/run-jar.sh
#!/bin/bash
screen -d -m -S kafka-influx-linker java -jar /opt/kafka-influx-linker/kafka-influx-linker.jar
<file_sep>/MultiView-Dependencies/Install_NodeJS.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_NodeJS.sh
# Description : Script for Installing Java
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : November, 2016
NodeJSExist=`dpkg -l | grep nodejs`
if [ "$NodeJSExist" == "" ]; then
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] NodeJS Installing .................... "
apt-get install -y nodejs npm
ln -s /usr/bin/nodejs /usr/bin/node
echo -e "Done.\n"
echo `node -v`
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] NodeJS Already Installed."
echo `node -v`
fi
<file_sep>/Visibility-Agent/visibility/vis_coordinator.py
import logging
import yaml
import influxdb
import json
import zmq
class VisibilityCoordinator:
def __init__(self, config):
self._logger = logging.getLogger(self.__class__.__name__)
self._config = config
self._tr = None
self._mq = None
self._zmq_context = None
self._zmq_sock = None
self._logger.debug(config)
# def add_point(self, point_instance):
# self._point_list.add_point(point_instance)
#
# def delete_point(self, point_instance):
# pass
#
# class WorkingPointList(threading.Thread):
# def __init__(self):
# super(VisibilityCoordinator.WorkingPointList, self).__init__()
# self.point_list = list()
# self._logger = logging.getLogger(self.__class__.__name__)
#
# def add_point(self, point_instance):
# self.point_list.append(point_instance)
#
# def delete_point(self, point_instance):
# self.point_list.remove(point_instance)
def prepare(self):
self._prepare_transfer(self._config.get("visibility_coordinator").get("data_transfer"))
self._prepare_msg_queue(self._config.get("visibility_coordinator").get("msg_queue"))
def _prepare_transfer(self, conf_transfers):
self._logger.debug(conf_transfers)
conf_t = conf_transfers[0]
if conf_t.get("type") == "influxdb":
self._tr = self._get_influx_client(conf_t)
def _get_influx_client(self, conf_influx):
self._logger.debug(conf_influx)
client = influxdb.InfluxDBClient(conf_influx.get("ipaddress"),
conf_influx.get("port"),
conf_influx.get("id"),
conf_influx.get("password"),
None)
return client
def _prepare_msg_queue(self, conf_mq):
self._zmq_context = zmq.Context()
self._zmq_sock = self._zmq_context.socket(zmq.PULL)
self._zmq_sock.bind("tcp://{}:{}".format(conf_mq.get("ipaddress"), conf_mq.get("port")))
def run(self):
while True:
recv_str = self._zmq_sock.recv()
self._logger.debug(recv_str)
self._send_collected_data(recv_str)
def _send_collected_data(self, msg):
self._logger.debug(msg)
msgs = msg.split('/')
database = msgs[0]
data = json.loads(msgs[1])
self._logger.debug(data)
self._tr.switch_database(database)
self._tr.write_points(data)
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s / %(filename)s, %(funcName)s (#%(lineno)d)] %(message)s",
level=logging.INFO)
with open("config.yaml") as f:
config_str = f.read()
coor_config = yaml.load(config_str)
vis_coordi = VisibilityCoordinator(coor_config)
vis_coordi.prepare()
vis_coordi.run()
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapProcessesParser.java
package chainlinker;
public class SnapProcessesParser extends SnapPluginParser {
public SnapProcessesParser() {
super();
// All these data forms must be updated when snap publisher's output format is changed.
typeMap.put("/intel/procfs/processes/running", lClass);
typeMap.put("/intel/procfs/processes/sleeping", lClass);
typeMap.put("/intel/procfs/processes/waiting", lClass);
typeMap.put("/intel/procfs/processes/zombie", lClass);
typeMap.put("/intel/procfs/processes/stopped", lClass);
typeMap.put("/intel/procfs/processes/tracing", lClass);
typeMap.put("/intel/procfs/processes/dead", lClass);
typeMap.put("/intel/procfs/processes/wakekill", lClass);
typeMap.put("/intel/procfs/processes/waking", lClass);
typeMap.put("/intel/procfs/processes/parked", lClass);
// Needs more information on process name
// Pattern: /intel/procfs/processes/(alphanumerical or _ or - or : or .)/(ps_vm or ps_rss or ps_data or ps_code or ps_stacksize or ps_cputime_user or ps_cputime_system or ps_pagefaults_min or ps_pagefaults_maj or ps_disk_ops_syscr or ps_disk_ops_syscw or ps_disk_octets_rchar or ps_disk_octets_wchar or ps_count)
regexTypeMap.put("^\\/intel\\/procfs\\/processes\\/([0-9]|[a-z]|[A-Z]|_|\\-|:|\\.)*\\/(ps_vm|ps_rss|ps_data|ps_code|ps_stacksize|ps_cputime_user|ps_cputime_system|ps_pagefaults_min|ps_pagefaults_maj|ps_disk_ops_syscr|ps_disk_ops_syscw|ps_disk_octets_rchar|ps_disk_octets_wchar|ps_count)$", lClass);
regexSet = regexTypeMap.keySet();
}
}
<file_sep>/Visibility-Agent/visibility/vis_points/vis_point_inventory.py
import os
import logging
import types
from importlib import import_module
class PointInventory:
def __init__(self):
self._logger = logging.getLogger(self.__class__.__name__)
self._logger.setLevel(logging.DEBUG)
self._import_point_modules()
def create_point(self, point_name):
if point_name in globals():
point_class = globals()[point_name]
point_instance = point_class()
self._logger.debug("Point Instance Created: \n{}".format(point_name))
return point_instance
else:
return None
def _import_point_modules(self):
for file_name in os.listdir(os.path.dirname(__file__)):
classes_in_file = list()
if file_name.endswith(".py") and file_name not in ["__init__.py", "vis_point_inventory.py"]:
module = import_module("vis_points.{}".format(file_name.rstrip(".py")))
module_dict = module.__dict__
for obj_name in module_dict.keys():
obj = module_dict[obj_name]
if isinstance(obj, types.ClassType):
globals()[obj_name] = obj
classes_in_file.append(obj_name)
if classes_in_file.__len__() != 0:
self._logger.debug("Class modules in {} were loaded: {}".format(file_name, str(classes_in_file)))
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/flow/OpenStackBridgesStatus.java
/**
* @author <NAME>
* @version 0.1
*/
package smartx.multiview.collectors.flow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.bson.Document;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
public class OpenStackBridgesStatus implements Runnable{
private Thread thread;
private String ThreadName="pBox Status Thread";
private String SmartXBox_USER, SmartXBox_PASSWORD, box = "", m_ip = "";
private String pboxMongoCollection, flowMongoCollection, flowMongoCollectionRT;
private String [] BoxType;
private List<String> bridges = new ArrayList<String>();
private MongoClient mongoClient;
private MongoDatabase db;
private Document document;
private DeleteResult deleteResult;
private FindIterable<Document> pBoxList;
private Date timestamp;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static Logger logger = Logger.getLogger(OpenStackBridgesStatus.class.getName());
public OpenStackBridgesStatus(String boxUser, String boxPassword, String dbHost, int dbPort, String dbName, String pboxCollection, String osMongoCollection, String osMongoCollectionRT, String [] boxType) {
SmartXBox_USER = boxUser;
SmartXBox_PASSWORD = <PASSWORD>;
mongoClient = new MongoClient(dbHost, dbPort);
db = mongoClient.getDatabase(dbName);
pboxMongoCollection = pboxCollection;
flowMongoCollection = osMongoCollection;
flowMongoCollectionRT = osMongoCollectionRT;
BoxType = boxType;
}
public void getBridgesStatus(String box, String serverIp, String bridgeName, String command, String usernameString,String password)
{
try
{
Connection conn = new Connection(serverIp);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
ch.ethz.ssh2.Session sess = conn.openSession();
sess.execCommand(command);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
if (line!=null)
{
bridges.add(line);
System.out.println(line);
setBridgesStatus(box, serverIp, bridgeName, line);
}
}
sess.close();
conn.close();
}
catch (IOException e)
{
System.out.println("[ERROR][OSB][Box : "+box+" Failed]");
e.printStackTrace(System.err);
}
}
public void setBridgesStatus(String box, String serverIp, String bridgeName, String result)
{
String n_packets, n_bytes, dl_vlan, actions;
String[] ResultArray, mappingArray;
document = new Document();
ResultArray = result.split(",");
n_packets = ResultArray[3].substring(ResultArray[3].indexOf("=")+1, ResultArray[3].length());
n_bytes = ResultArray[4].substring(ResultArray[4].indexOf("=")+1, ResultArray[4].length());
mappingArray = ResultArray[9].split(" ");
dl_vlan = mappingArray[0].substring(mappingArray[0].indexOf("=")+1, mappingArray[0].length());
actions = mappingArray[1].substring(mappingArray[1].indexOf("=")+14, mappingArray[1].length());
System.out.println(ResultArray[0]);
System.out.println(ResultArray[3]);
System.out.println(actions);
document.put("timestamp", new Date());
document.put("box", box);
document.put("bridge", bridgeName);
document.put("n_packets", n_packets);
document.put("n_bytes", n_bytes);
document.put("dl_vlan", dl_vlan);
document.put("actions", actions);
//Insert New Documents to MongoDB
db.getCollection(flowMongoCollectionRT).insertOne(document);
db.getCollection(flowMongoCollection).insertOne(document);
System.out.println("["+dateFormat.format(timestamp)+"][INFO][OSB][Box: "+box+" Bridge: "+bridgeName+" inserted]");
}
public void update_status()
{
timestamp = new Date();
//Delete Previous Documents from Real Time collection
deleteResult=db.getCollection(flowMongoCollectionRT).deleteMany(new Document());
pBoxList = db.getCollection(pboxMongoCollection).find(new Document("type", BoxType[0]));
//pBoxList = db.getCollection(pboxMongoCollection).find(new Document("$or", asList(new Document("type", BoxType[0]),new Document("type", BoxType[1]))));
pBoxList.forEach(new Block<Document>() {
public void apply(final Document document) {
box = (String) document.get("box");
m_ip = (String) document.get("management_ip");
//Get/Set Statistics of OpenStack Bridges
try{
getBridgesStatus(box, m_ip, "brvlan","ovs-ofctl dump-flows brvlan | grep dl_vlan", SmartXBox_USER, SmartXBox_PASSWORD);
getBridgesStatus(box, m_ip, "br-int","ovs-ofctl dump-flows br-int | grep dl_vlan", SmartXBox_USER, SmartXBox_PASSWORD);
}catch(StringIndexOutOfBoundsException exc){
System.out.println(exc);
throw exc;
}
}
});
}
public void run()
{
while (true)
{
update_status();
try {
//Sleep For 5 Minutes
Thread.sleep(300000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
System.out.println("Starting OpenStack Bridges Statistics Thread");
if (thread==null){
thread = new Thread(this, ThreadName);
thread.start();
}
}
}
<file_sep>/Visibility-Agent/IOVisor/transfer_iovisor_data.sh
#!/bin/bash
#
# Name : transfer_iovisor_data.sh
# Description : A script for transferring network packets data to the SmartX Visibility Center
#
# Created by : <NAME>
# Version : 0.5
# Last Update : December, 2018
#Modify these parameters before execution on SmartX Boxes
#Also install sshpass and add SmartX Visibility Center IP for automatic logins.
VISIBILITY_CENTER_IP=
VISIBILITY_CENTER_USER=
TARGETFOLDERDP='/home/netcs/IOVisor-Data/Data-Plane'
TARGETFOLDERCP='/home/netcs/IOVisor-Data/Control-Plane'
SOURCEFOLDER='/opt/IOVisor-Data'
Minute="$(date +'%M')"
Hour="$(date +'%H')"
cDate="$(date +'%Y-%m-%d')"
host=`hostname`
if [ "$Minute" -eq 00 ]
then
if [ "$Hour" -eq 00 ]
then
PREVIOUS_HOUR=23
PREVIOUS_MINUTE=55
PREVIOUS_DAY="$(date +'%d')"
PREVIOUS_DAY=$((PREVIOUS_DAY - 1))
if [ "$PREVIOUS_DAY" -lt 10 ]
then
PREVIOUS_DAY="0$PREVIOUS_DAY"
fi
else
PREVIOUS_HOUR=$((Hour - 1))
PREVIOUS_MINUTE=55
PREVIOUS_DAY="$(date +'%d')"
if [ "$PREVIOUS_HOUR" -lt 10 ]
then
PREVIOUS_HOUR="0$PREVIOUS_HOUR"
fi
fi
cDate="$(date +'%Y-%m')"
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$PREVIOUS_DAY-$PREVIOUS_HOUR-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$PREVIOUS_DAY-$PREVIOUS_HOUR-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 5 ]
then
PREVIOUS_MINUTE=00
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 10 ]
then
PREVIOUS_MINUTE=05
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 15 ]
then
PREVIOUS_MINUTE=10
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 20 ]
then
PREVIOUS_MINUTE=15
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 25 ]
then
PREVIOUS_MINUTE=20
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 30 ]
then
PREVIOUS_MINUTE=25
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 35 ]
then
PREVIOUS_MINUTE=30
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 40 ]
then
PREVIOUS_MINUTE=35
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 45 ]
then
PREVIOUS_MINUTE=40
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 50 ]
then
PREVIOUS_MINUTE=45
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
elif [ "$Minute" -eq 55 ]
then
PREVIOUS_MINUTE=50
PREVIOUS_FILE1="/opt/IOVisor-Data/$host-mc-$cDate-$Hour-$PREVIOUS_MINUTE"
PREVIOUS_FILE2="/opt/IOVisor-Data/$host-data-$cDate-$Hour-$PREVIOUS_MINUTE"
fi
sshpass -p $PASS scp $PREVIOUS_FILE1 $VISIBILITY_CENTER_USER@$VISIBILITY_CENTER_IP:$TARGETFOLDERCP
sshpass -p $PASS scp $PREVIOUS_FILE2 $VISIBILITY_CENTER_USER@$VISIBILITY_CENTER_IP:$TARGETFOLDERDP
sleep 20
shopt -s extglob; set -H
cd $SOURCEFOLDER
CURRENT_FILES=`ls -t1 | head -n 2 | sed 'N; s/\n/|/'`
sudo rm -v !($CURRENT_FILES)
if [ $? -eq 0 ]; then
echo OK
else
echo FAIL
fi
<file_sep>/MultiView-Dependencies/Install_Kafka.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_Kafka.sh
# Description : Script for Getting Kafka
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : November, 2016
kafkaExist=`ls | grep kafka`
if [ "$kafkaExist" == "" ]; then
echo -e ""
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Get Zookeeper .................... "
wget http://apache.mirror.cdnetworks.com/zookeeper/zookeeper-3.4.9/zookeeper-3.4.9.tar.gz &> /dev/null
tar -xvzf zookeeper-3.4.9.tar.gz &> /dev/null
rm -rf zookeeper-3.4.9.tar.gz
mv zookeeper-3.4.9 zookeeper
mv zookeeper/conf/zoo_sample.cfg zookeeper/conf/zoo.cfg
echo -e "Done.\n"
#zookeeper/bin/zkServer.sh start
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Get Kafka .................... "
wget http://ftp.jaist.ac.jp/pub/apache/kafka/0.10.0.0/kafka_2.11-0.10.0.0.tgz &> /dev/null
tar -xvzf kafka_2.11-0.10.0.0.tgz &> /dev/null
rm -rf kafka_2.11-0.10.0.0.tgz
mv kafka_2.11-0.10.0.0 kafka
echo "delete.topic.enable = true" >> kafka/config/server.properties
#kafka/bin/kafka-server-start.sh kafka/config/server.properties
#In case kafka server can't start then add IP to /etc/hosts
echo -e "Done. \n"
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Kafka Already Installed."
fi
<file_sep>/Visibility-Agent/IOVisor/create_systemd_service.sh
#!/bin/bash
#
# Name : create_systemd_service.sh
# Description : A script for executing packet tracing scripts as systemd service.
#
# Created by : <NAME>
# Version : 0.1
# Last Update : May, 2018
#
# This script must be executed by root user
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
mv /opt/FlowAgent/control-plane-tracing.service /etc/systemd/system
mv /opt/FlowAgent/data-plane-tracing.service /etc/systemd/system
mv /opt/FlowAgent/management-plane-tracing.service /etc/systemd/system
chmod 664 /etc/systemd/system/control-plane-tracing.service
chmod 664 /etc/systemd/system/data-plane-tracing.service
chmod 664 /etc/systemd/system/management-plane-tracing.service
systemctl daemon-reload
systemctl enable control-plane-tracing.service
systemctl enable data-plane-tracing.service
systemctl enable management-plane-tracing.service
systemctl start control-plane-tracing.service
systemctl start data-plane-tracing.service
systemctl start management-plane-tracing.service
#sudo journalctl --follow -u control-plane-tracing
#sudo journalctl --follow -u data-plane-tracing
#sudo journalctl --follow -u management-plane-tracing<file_sep>/Visibility-Collection-Validation/Collectors/sflow-rt/start.sh
#!/bin/sh
HOME=`dirname $0`
cd $HOME
RTMEM="${RTMEM:-200M}"
JAR="./lib/sflowrt.jar"
JVM_OPTS="-Xms$RTMEM -Xmx$RTMEM -XX:+UseG1GC -XX:MaxGCPauseMillis=100"
RT_OPTS="-Dsflow.port=6343 -Dhttp.port=8008"
exec java ${JVM_OPTS} ${RT_OPTS} ${RTPROP} -jar ${JAR}
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/flow/SDNControllerStats.java
/**
* @author <NAME>
* @version 0.1
*/
package smartx.multiview.collectors.flow;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class SDNControllerStats implements Runnable{
private String user, password, devopscontroller, ThreadName="SDN Controller Stats Thread";
private Thread thread;
private MongoClient mongoClient;
private Document document;
private MongoCollection<Document> collection1, collection2;
private static MongoDatabase db;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public SDNControllerStats(String dbHost, int dbPort, String dbName, String flowStatsMongoCollection, String flowStatsMongoCollectionRT, String devopscon, String User, String Password)
{
mongoClient = new MongoClient(dbHost, dbPort);
db = mongoClient.getDatabase(dbName);
collection1 = db.getCollection(flowStatsMongoCollection);
collection2 = db.getCollection(flowStatsMongoCollectionRT);
devopscontroller = devopscon;
user = User;
password = <PASSWORD>;
}
public void getSwitchStats()
{
String matchField, outputAction, NodeID, BoxID; ;
String [] id;
JSONObject jsonObjectMain, jsonObjectFlowStat;
JSONArray jsonArrayMain, jsonArrayFlowStat;
String baseURL = "http://"+devopscontroller+":8080/controller/nb/v2/statistics/default/flow";
Date timestamp = new Date();
collection2.deleteMany(new Document());
try {
URL url = new URL(baseURL);
//System.out.println(url);
// Create authentication string and encode it to Base64
String authStr = user + ":" + password;
String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());
// Create Http connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set connection properties
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
connection.setRequestProperty("Accept", "application/json");
// Get the response from connection's inputStream
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line = "";
//JSONParser jsonParser = null;
line = in.readLine();
System.out.println(line);
jsonObjectMain = new JSONObject(line);
jsonArrayMain = jsonObjectMain.getJSONArray("flowStatistics");
for (int i=0 ; i<jsonArrayMain.length(); i++)
{
id = jsonArrayMain.getJSONObject(i).get("node").toString().split(",");
jsonObjectFlowStat = jsonArrayMain.getJSONObject(i);
jsonArrayFlowStat = jsonObjectFlowStat.getJSONArray("flowStatistic");
for (int j=0; j<jsonArrayFlowStat.length(); j++)
{
document = new Document();
NodeID = id[0].substring(7, id[0].length()-1);
matchField = jsonArrayFlowStat.getJSONObject(j).get("flow").toString();
outputAction = matchField.substring(matchField.indexOf("actions")-1,matchField.lastIndexOf("}]}")+2);
matchField = matchField.substring(matchField.indexOf("matchField")-1,matchField.indexOf("}]}")+2);
if (NodeID.equals("fc00:db20:35b:7399::5"))
BoxID="SmartXBoxGIST";
else if(NodeID.equals("fc00:db20:35b:7399::5"))
BoxID="SmartXBoxMYREN";
else if(NodeID.equals("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"))
BoxID="SmartXBoxID";
else if(NodeID.equals("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"))
BoxID="SmartXBoxPH";
else if(NodeID.equals("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b"))
BoxID="SmartXBoxVN";
else if(NodeID.equals("fc00:db20:35b:7399::5"))
BoxID="SmartXBoxPKS";
else
BoxID="";
System.out.print("["+dateFormat.format(timestamp)+"][INFO][ODL][Node "+id[0].substring(7, id[0].length()-1));
System.out.print(" packetCount "+jsonArrayFlowStat.getJSONObject(j).get("packetCount"));
System.out.print(" byteCount "+jsonArrayFlowStat.getJSONObject(j).get("byteCount"));
System.out.print(" durationSeconds "+jsonArrayFlowStat.getJSONObject(j).get("durationSeconds"));
System.out.print(" matchField "+matchField);
System.out.println(" actions "+outputAction+"]");
document.put("timestamp" , timestamp);
document.put("controllerIP" , devopscontroller);
document.put("boxID" , BoxID);
document.put("node" , NodeID);
document.put("matchField" , matchField);
document.put("actions" , outputAction);
document.put("packetCount" , jsonArrayFlowStat.getJSONObject(j).get("packetCount"));
document.put("byteCount" , jsonArrayFlowStat.getJSONObject(j).get("byteCount"));
document.put("durationSeconds" , jsonArrayFlowStat.getJSONObject(j).get("durationSeconds"));
collection1.insertOne(document);
collection2.insertOne(document);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true)
{
getSwitchStats();
try {
//Sleep For 5 Minutes
Thread.sleep(300000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
System.out.println("Starting SDN Controller Stats Thread");
if (thread==null){
thread = new Thread(this, ThreadName);
thread.start();
}
}
}
<file_sep>/Visibility-Storage-Staging/data-apis/lib/routes/multiviewRoutes.ts
// /lib/routes/multiviewRoutes.ts
import {Request, Response, NextFunction} from "express";
import { SDNContController, OverlayController, BoxController, VMInstanceSchema, IoTHostSchema } from "../controllers/multiviewController";
export class Routes {
public sdnController: SDNContController = new SDNContController()
public overlayController: OverlayController = new OverlayController()
public boxController: BoxController = new BoxController()
public vminstanceController: VMInstanceSchema = new VMInstanceSchema()
public iothostController: IoTHostSchema = new IoTHostSchema()
public routes(app): void {
app.route('/')
.get((req: Request, res: Response) => {
res.status(200).send({
message: 'Multi-View Data API server is running!!!'
})
})
// SmartX Controller List
app.route('/getcontrollersstatus')
.get((req: Request, res: Response, next: NextFunction) => {
// middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, this.sdnController.getSDNCont)
// Overlay-restricted Topology Data
app.route('/getoverlaylatency')
.get((req: Request, res: Response, next: NextFunction) => {
// middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, this.overlayController.getLatency)
// Overlay-restricted Topology Data (timestamp)
app.route('/getoverlaylatency/:SmartX-Box-Source')
// get specific contact
.get(this.overlayController.getLatencyWithBoxID)
// SmartX Box List
app.route('/getboxesstatus')
.get((req: Request, res: Response, next: NextFunction) => {
// middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, this.boxController.getBox)
// OpenStack VM Instances List
app.route('/getvminstancesstatus')
.get((req: Request, res: Response, next: NextFunction) => {
// middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, this.vminstanceController.getVMInstances)
// Connected IoT Hostss List
app.route('/getiothostsstatus')
.get((req: Request, res: Response, next: NextFunction) => {
// middleware
console.log(`Request from: ${req.originalUrl}`);
console.log(`Request type: ${req.method}`);
next();
}, this.iothostController.getIoTHosts)
}
}
<file_sep>/Visibility-Collection-Validation/Collectors/Get_VM_LIST.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Get_VM_List.sh
# Description : Script for Getting VM's/Box
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : April, 2018
#Source the Admin File
. /home/netcs/openstack/admin-openrc
#openstack region list
OS_REGIONS="GIST1 KR-GIST2 GIST3 TW-NCKU MYREN MY-UM TH-CHULA VN-HUST"
. /home/netcs/openstack/admin-openrc
rm -rf vm_list.temp InstanceList
for region in $OS_REGIONS
do
openstack --os-region-name $region server list --all-projects -f csv --quote none --long > vm_list.temp
while read -r vmline
do
if [[ $vmline == *"ID"* ]]; then
echo "Skip..."
else
instance_id=`echo $vmline | cut -d ',' -f1`
instance_name=`echo $vmline | cut -d ',' -f2`
instance_status=`echo $vmline | cut -d ',' -f3`
instance_power_state=`echo $vmline | cut -d ',' -f5`
instance_networks=`echo $vmline | cut -d ',' -f6`
instance_image=`echo $vmline | cut -d ',' -f7`
instance_host_box=`echo $vmline | cut -d ',' -f11`
echo "$instance_id,$instance_name,$instance_status,$instance_power_state,$instance_networks,$instance_image,$instance_host_box" >> InstanceList
fi
done < "vm_list.temp"
done
<file_sep>/MultiView-Scripts/MultiView_Configuration_Database.js
//Update This Script Before Installing MultiView Software
use smartxdb
show collections
//Create Unique Indexes
db['configuration-multiview-users'].createIndex( { username:1, password: 1 }, { unique: true } )
db['configuration-pbox-list'].createIndex({box:1, boxID: 1},{unique:true})
db['configuration-vswitch-list'].ensureIndex({type:1, bridge: 1},{unique:true})
db['configuration-vswitch-status'].ensureIndex({bridge:1, box: 1},{unique:true})
//Insert MultiView Users Data into Collection
db['configuration-multiview-users'].insert( { username: "admin", password: "<PASSWORD>", role: "operator" } )
db['configuration-multiview-users'].insert( { username: "demo", password: "<PASSWORD>", role: "developer" } )
//Insert pBoxes Data into Collection
db['configuration-pbox-list'].insert( { box: "SmartXBoxID", boxID: "boxName", management_ip: "", management_ip_status: "up", data_ip: "", data_ip_status: "up", control_ip: "", control_ip_status: "up", ovs_vm1: "", ovs_vm2: "", active_ovs_vm: "ovs_vm1", type: "B**" } )
//Insert OVS Bridges Topology Data into Collection
db['configuration-vswitch-list'].insert( { type: "B**", bridge: "brcap", topologyorder: "1" } )
db['configuration-vswitch-list'].insert( { type: "B**", bridge: "brdev", topologyorder: "2" } )
db['configuration-vswitch-list'].insert( { type: "B**", bridge: "brvlan", topologyorder: "3" } )
db['configuration-vswitch-list'].insert( { type: "B**", bridge: "br-ex", topologyorder: "3" } )
db['configuration-vswitch-list'].insert( { type: "B**", bridge: "br-int", topologyorder: "4" } )
//Insert OVS Bridges Status Data into Collection <Insert For all boxes>
db['configuration-vswitch-status'].insert( { bridge: "brcap", box: "boxName", status: "RED" } )
db['configuration-vswitch-status'].insert( { bridge: "brdev", box: "boxName", status: "RED" } )
db['configuration-vswitch-status'].insert( { bridge: "brvlan", box: "boxName", status: "RED" } )
db['configuration-vswitch-status'].insert( { bridge: "br-ex", box: "boxName", status: "RED" } )
db['configuration-vswitch-status'].insert( { bridge: "br-int", box: "boxName", status: "RED" } )
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapPluginManifest.java
package chainlinker;
import java.util.HashMap;
/*
* This class serve as a manifest for loading required SnapPluginParsers.
* When a SnapPluginParser class is added to add another Snap plugin, then it must be registered here.
*/
public class SnapPluginManifest {
private HashMap<String, Class<? extends SnapPluginParser>> pluginManifestMap = new HashMap<>();
private SnapPluginManifest() {
pluginManifestMap.put("snap-plugin-collector-psutil", SnapPSUtilParser.class);
pluginManifestMap.put("snap-plugin-collector-cpu", SnapCPUParser.class);
pluginManifestMap.put("snap-plugin-collector-meminfo", SnapMemInfoParser.class);
pluginManifestMap.put("snap-plugin-collector-df", SnapDFParser.class);
pluginManifestMap.put("snap-plugin-collector-iostat", SnapIOStatParser.class);
pluginManifestMap.put("snap-plugin-collector-libvirt", SnapLibVirtParser.class);
pluginManifestMap.put("snap-plugin-collector-ping", SnapPingParser.class);
pluginManifestMap.put("snap-plugin-collector-interface", SnapInterfaceParser.class);
pluginManifestMap.put("snap-plugin-collector-processes", SnapProcessesParser.class);
}
public HashMap<String, Class<? extends SnapPluginParser>> getPluginManifestMap() {
return pluginManifestMap;
}
// Singleton part for this class as this class does not need to exist in multitude.
private static SnapPluginManifest instance = new SnapPluginManifest();
public static SnapPluginManifest getInstance () {
return instance;
}
}
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapMemInfoParser.java
package chainlinker;
/*
* Corresponding to snap-plugin-collector-meminfo
*
* CAUTION: This setting may fail in case if the plugins' version mismatch with the below.
* - collector:meminfo:3
*/
public class SnapMemInfoParser extends SnapPluginParser {
public SnapMemInfoParser() {
super();
// All these data forms must be updated when snap publisher's output format is changed.
// long value types
typeMap.put("/intel/procfs/meminfo/mem_total", lClass);
typeMap.put("/intel/procfs/meminfo/mem_used", lClass);
typeMap.put("/intel/procfs/meminfo/mem_free", lClass);
typeMap.put("/intel/procfs/meminfo/mem_available", lClass);
typeMap.put("/intel/procfs/meminfo/buffers", lClass);
typeMap.put("/intel/procfs/meminfo/cached", lClass);
typeMap.put("/intel/procfs/meminfo/swap_cached", lClass);
typeMap.put("/intel/procfs/meminfo/active", lClass);
typeMap.put("/intel/procfs/meminfo/inactive", lClass);
typeMap.put("/intel/procfs/meminfo/active_anon", lClass);
typeMap.put("/intel/procfs/meminfo/inactive_anon", lClass);
typeMap.put("/intel/procfs/meminfo/active_file", lClass);
typeMap.put("/intel/procfs/meminfo/inactive_file", lClass);
typeMap.put("/intel/procfs/meminfo/unevictable", lClass);
typeMap.put("/intel/procfs/meminfo/mlocked", lClass);
typeMap.put("/intel/procfs/meminfo/high_total", lClass);
typeMap.put("/intel/procfs/meminfo/high_free", lClass);
typeMap.put("/intel/procfs/meminfo/low_total", lClass);
typeMap.put("/intel/procfs/meminfo/low_free", lClass);
typeMap.put("/intel/procfs/meminfo/mmap_copy", lClass);
typeMap.put("/intel/procfs/meminfo/swap_total", lClass);
typeMap.put("/intel/procfs/meminfo/swap_free", lClass);
typeMap.put("/intel/procfs/meminfo/dirty", lClass);
typeMap.put("/intel/procfs/meminfo/writeback", lClass);
typeMap.put("/intel/procfs/meminfo/anon_pages", lClass);
typeMap.put("/intel/procfs/meminfo/mapped", lClass);
typeMap.put("/intel/procfs/meminfo/shmem", lClass);
typeMap.put("/intel/procfs/meminfo/slab", lClass);
typeMap.put("/intel/procfs/meminfo/sreclaimable", lClass);
typeMap.put("/intel/procfs/meminfo/sunreclaim", lClass);
typeMap.put("/intel/procfs/meminfo/kernel_stack", lClass);
typeMap.put("/intel/procfs/meminfo/page_tables", lClass);
typeMap.put("/intel/procfs/meminfo/quicklists", lClass);
typeMap.put("/intel/procfs/meminfo/nfs_unstable", lClass);
typeMap.put("/intel/procfs/meminfo/bounce", lClass);
typeMap.put("/intel/procfs/meminfo/writeback_tmp", lClass);
typeMap.put("/intel/procfs/meminfo/commit_limit", lClass);
typeMap.put("/intel/procfs/meminfo/committed_as", lClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_total", lClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_used", lClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_chunk", lClass);
typeMap.put("/intel/procfs/meminfo/hardware_corrupted", lClass);
typeMap.put("/intel/procfs/meminfo/anon_huge_pages", lClass);
typeMap.put("/intel/procfs/meminfo/cma_total", lClass);
typeMap.put("/intel/procfs/meminfo/cma_free", lClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_total", lClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_free", lClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_rsvd", lClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_surp", lClass);
typeMap.put("/intel/procfs/meminfo/hugepagesize", lClass);
typeMap.put("/intel/procfs/meminfo/direct_map4k", lClass);
typeMap.put("/intel/procfs/meminfo/direct_map4m", lClass);
typeMap.put("/intel/procfs/meminfo/direct_map2m", lClass);
typeMap.put("/intel/procfs/meminfo/direct_map1g", lClass);
// double value types
typeMap.put("/intel/procfs/meminfo/mem_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mem_used_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mem_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mem_available_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/buffers_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/cached_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/swap_cached_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/active_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/inactive_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/active_anon_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/inactive_anon_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/active_file_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/inactive_file_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/unevictable_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mlocked_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/high_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/high_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/low_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/low_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mmap_copy_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/swap_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/swap_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/dirty_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/writeback_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/anon_pages_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/mapped_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/shmem_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/slab_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/sreclaimable_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/sunreclaim_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/kernel_stack_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/page_tables_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/quicklists_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/nfs_unstable_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/bounce_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/writeback_tmp_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/commit_limit_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/committed_as_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_used_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/vmalloc_chunk_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/hardware_corrupted_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/anon_huge_pages_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/cma_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/cma_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_total_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_free_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_rsvd_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/huge_pages_surp_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/hugepagesize_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/direct_map4k_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/direct_map4m_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/direct_map2m_perc", lfClass);
typeMap.put("/intel/procfs/meminfo/direct_map1g_perc", lfClass);
}
}
<file_sep>/Visibility-Integration/transfer_data_from_ID_Center.sh
#!/bin/bash
#
# Copyright 2018 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : transfer_data_from_ID_Center.sh
# Description : Script for transferring data about SmartX Tags to SmartX Visibility Center. This script should be executed at ID Center via crontab. e.g. */5 * * * * /bin/bash /home/netcs/transfer_data_from_ID_Center.sh. sshpass should be installed in ID Center.
#
# Created by : <NAME>
# Version : 0.1
# Last Update : December, 2018
#
VISIBILITY_CENTER_IP=
VISIBILITY_CENTER_USER=
PASS=
TARGETFOLDER='/home/netcs/SmartX-Tagging'
sleep 1m
sshpass -p $PASS scp /home/netcs/ControlPlane.tags $VISIBILITY_CENTER_USER@$VISIBILITY_CENTER_IP:$TARGETFOLDER
sshpass -p $PASS scp /home/netcs/tenant.tags $VISIBILITY_CENTER_USER@$VISIBILITY_CENTER_IP:$TARGETFOLDER
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/Backend.java
package chainlinker;
import java.io.InvalidClassException;
import java.util.HashMap;
import java.util.LinkedList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
public abstract class Backend {
public Backend() {
super();
}
abstract public Object getConfig();
abstract public void loadConfig(JSONObject config_json) throws ParseException;
abstract public void processMessage(JSONArray msgValue, HashMap<String, SnapPluginParser> parserMap, LinkedList<SnapPluginParser> parserList);
abstract public Object parse(JSONObject dataObj, HashMap<String, SnapPluginParser> parserMap, LinkedList<SnapPluginParser> parserList) throws NullPointerException, ClassNotFoundException, InvalidClassException;
abstract public void addField(
Object metricObject,
String dataTypeName,
Object data,
SnapPluginParser parser
) throws ClassNotFoundException, InvalidClassException;
protected Object getSafe(JSONObject map, String key) throws NullPointerException {
Object value = map.get(key);
if (value == null) throw new NullPointerException();
return value;
}
}
<file_sep>/MultiView-Dependencies/Install_MongoDB.sh
#!/bin/bash
#
# Copyright 2015 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_MongoDB.sh
# Description : Script for Installing MongoDB
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : October, 2016
MGMT_IP=$1
mongoExist=`ls | grep mongo`
if [ "$mongoExist" == "" ]; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] MongoDB Installing .................... "
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 &> /dev/null
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
sudo apt-get update &> /dev/null
sudo apt-get install -y mongodb-org &> /dev/null
sed -i "s/bindIp: 127.0.0.1/bindIp: $MGMT_IP/g" /etc/mongod.conf
service mongod restart &> /dev/null
echo -e "Done. \n"
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] MongoDB Already Installed."
fi
<file_sep>/Visibility-Agent/IOVisor/mcd_planes_tracing.c
/*
Name : mcd_planes_tacing.c
Description : A script for tracing network packets at kernel-level
Created by : <NAME>
Version : 0.1
Last Update : March, 2018
*/
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
#define IP_TCP 6
#define IP_UDP 17
#define IP_ICMP 1
/*
In 802.3, both the source and destination addresses are 48 bits (4 bytes) MAC address.
6 bytes (src) + 6 bytes (dst) + 2 bytes (type) = 14 bytes
*/
#define ETH_HLEN 14
/*eBPF program.
Filter TCP/UDP/ICMP packets, having payload not empty
if the program is loaded as PROG_TYPE_SOCKET_FILTER
and attached to a socket
return 0 -> DROP the packet
return -1 -> KEEP the packet and return it to user space (userspace can read it from the socket_fd )
*/
int ip_filter(struct __sk_buff *skb) {
u8 *cursor = 0; // unsigned 8 bits = unsigned 1 byte
struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet)); // ethernet header (frame)
//filter IP packets (ethernet type = 0x0800) 0x0800 is IPv4 packet
if (!(ethernet->type == 0x0800)) {
goto DROP;
}
struct ip_t *ip = cursor_advance(cursor, sizeof(*ip)); // IP header (datagram)
//filter TCP packets (ip next protocol = 0x06)
if (ip->nextp != IP_TCP) {
if (ip->nextp != IP_UDP){
if (ip->nextp != IP_ICMP){
goto DROP;}}
}
u32 tcp_header_length = 0;
u32 ip_header_length = 0;
u32 payload_offset = 0;
u32 payload_length = 0;
struct tcp_t *tcp = cursor_advance(cursor, sizeof(*tcp));
/*
calculate ip header length
value to multiply * 4
e.g. ip->hlen = 5 ; IP Header Length = 5 x 4 byte = 20 byte
The minimum value for this field is 5, which indicates a length of 5 x 32 bits(4 bytes) = 20 bytes
*/
ip_header_length = ip->hlen << 2; //SHL 2 -> *4 multiply
/*
calculate tcp header length
value to multiply *4
e.g. tcp->offset = 5 ; TCP Header Length = 5 x 4 byte = 20 byte
The minimum value for this field is 5, which indicates a length of 5 x 32 bits(4 bytes) = 20 bytes
*/
tcp_header_length = tcp->offset << 2; //SHL 2 -> *4 multiply
//calculate patload offset and length
payload_offset = ETH_HLEN + ip_header_length + tcp_header_length;
payload_length = ip->tlen - ip_header_length - tcp_header_length;
/*
http://stackoverflow.com/questions/25047905/http-request-minimum-size-in-bytes
minimum length of http request is always geater than 7 bytes
avoid invalid access memory
include empty payload
*/
if(payload_length < 7) {
goto DROP;
}
/*
load firt 7 byte of payload into p (payload_array)
direct access to skb not allowed
load_byte(): read binary data from socket buffer(skb)
*/
unsigned long p[7];
int i = 0;
int j = 0;
for (i = payload_offset ; i < (payload_offset + 7) ; i++) {
p[j] = load_byte(skb , i);
j++;
}
goto KEEP;
//keep the packet and send it to userspace retruning -1
KEEP:
return -1;
//drop the packet returning 0
DROP:
return 0;
}
int vxlan_filter(struct __sk_buff *skb) {
u8 *cursor = 0; // unsigned 8 bits = unsigned 1 byte
struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet)); // ethernet header (frame)
//filter IP packets (ethernet type = 0x0800) 0x0800 is IPv4 packet
switch(ethernet->type){
case 0x0800: goto IP;
default: goto DROP;
}
IP: ;
struct ip_t *ip = cursor_advance(cursor, sizeof(*ip)); // IP header (datagram)
switch (ip->nextp){
case 17: goto UDP;
default: goto DROP;
}
UDP: ;
struct udp_t *udp = cursor_advance(cursor, sizeof(*udp));
switch (udp->dport) {
case 4789: goto ISDATA;
default: goto DROP;
}
ISDATA: ;
u32 tcp_header_length = 0;
u32 ip_header_length = 0;
u32 payload_offset = 0;
u32 payload_length = 0;
struct tcp_t *tcp = cursor_advance(cursor, sizeof(*tcp));
/*
calculate ip header length
value to multiply * 4
e.g. ip->hlen = 5 ; IP Header Length = 5 x 4 byte = 20 byte
The minimum value for this field is 5, which indicates a length of 5 x 32 bits(4 bytes) = 20 bytes
*/
ip_header_length = ip->hlen << 2; //SHL 2 -> *4 multiply
/*
calculate tcp header length
value to multiply *4
e.g. tcp->offset = 5 ; TCP Header Length = 5 x 4 byte = 20 byte
The minimum value for this field is 5, which indicates a length of 5 x 32 bits(4 bytes) = 20 bytes
*/
tcp_header_length = tcp->offset << 2; //SHL 2 -> *4 multiply
//calculate patload offset and length
payload_offset = ETH_HLEN + ip_header_length + tcp_header_length;
payload_length = ip->tlen - ip_header_length - tcp_header_length;
if(payload_length < 7) {
goto DROP;
}
/*
load firt 7 byte of payload into p (payload_array)
direct access to skb not allowed
load_byte(): read binary data from socket buffer(skb)
*/
unsigned long p[7];
int i = 0;
int j = 0;
for (i = payload_offset ; i < (payload_offset + 7) ; i++) {
p[j] = load_byte(skb , i);
j++;
}
goto KEEP;
//keep the packet and send it to userspace retruning -1
KEEP:
return -1;
//drop the packet returning 0
DROP:
return 0;
}<file_sep>/MultiView-Scripts/Install_Dependencies_vCenter.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_Dependencies_vCenter.sh
# Description : Script for Installing Dependencies on Visibility Center
#
# Created by : <EMAIL>
# Version : 0.3
# Create Data : October, 2016
# Last Update : May, 2018
MGMT_IP=$1
VC_NAME="vc.manage.overcloud"
wget_check ()
{
if command -v wget > /dev/null; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] wget Already Installed.\n"
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] wget Installing .................... "
apt-get -y install wget nmap &> /dev/null
echo -e "Done.\n"
fi
}
java_check ()
{
if command -v java > /dev/null; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Already Installed.\n"
echo -e `java -version`
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Installing .................... "
sudo add-apt-repository -y ppa:webupd8team/java &> /dev/null
sudo apt-get -y update &> /dev/null
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer &> /dev/null
sudo apt-get -y install oracle-java8-set-default &> /dev/null
echo -e "Done.\n"
java -version
fi
}
influxDB_check()
{
influxdb=`dpkg -l | grep influx`
if [ "$influxdb" == "" ]; then
echo -n "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] InfluxDB Installing .................... "
wget --secure-protocol=TLSv1 https://dl.influxdata.com/influxdb/releases/influxdb_1.0.2_amd64.deb &> /dev/null
sudo dpkg -i influxdb_1.0.2_amd64.deb &> /dev/null
rm -rf influxdb_1.0.2_amd64.deb
echo -e "Done."
echo `influx -version`
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] InfluxDB Already Installed."
echo `influx -version`
fi
}
elasticsearch_check()
{
Elasticsearch=`dpkg -l | grep elasticsearch`
if [ "$Elasticsearch" == "" ]; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Elasticsearch Installing .................... "
CurrentDir=`pwd`
cd /tmp/
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
sudo apt-get install apt-transport-https &> /dev/null
echo "deb https://artifacts.elastic.co/packages/6.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-6.x.list
sudo apt-get update && sudo apt-get install elasticsearch &> /dev/null
sudo /bin/systemctl daemon-reload
sudo /bin/systemctl enable elasticsearch.service
#wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.0.0.deb &> /dev/null
#sudo dpkg -i elasticsearch-5.0.0.deb &> /dev/null
#sudo update-rc.d elasticsearch defaults 95 10 &> /dev/null
# Configure Elasticsearch
sed -i "s/#cluster.name: elasticsearch/cluster.name: elasticsearch/g" /etc/elasticsearch/elasticsearch.yml
sed -i "s/#network.host: 192.168.0.1/network.host: $MGMT_IP/g" /etc/elasticsearch/elasticsearch.yml
sudo systemctl restart elasticsearch.service &> /dev/null
echo -e "Done.\n"
cd $CurrentDir
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Elasticsearch Already Installed."
#echo `curl -XGET '$MGMT_IP:9200'`
fi
}
mongoDB_check()
{
mongoExist=`ls | grep mongo`
if [ "$mongoExist" == "" ]; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] MongoDB Installing .................... "
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 &> /dev/null
echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
sudo apt-get update &> /dev/null
sudo apt-get install -y mongodb-org &> /dev/null
sed -i "s/bindIp: 127.0.0.1/bindIp: 0.0.0.0/g" /etc/mongod.conf
service mongod restart &> /dev/null
echo -e "Done. \n"
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] MongoDB Already Installed."
fi
}
nodeJS_check()
{
NodeJSExist=`dpkg -l | grep nodejs`
if [ "$NodeJSExist" == "" ]; then
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] NodeJS Installing .................... "
apt-get install -y nodejs npm
ln -s /usr/bin/nodejs /usr/bin/node
echo -e "Done.\n"
echo `node -v`
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] NodeJS Already Installed."
echo `node -v`
fi
}
zookeeper_check()
{
zookeeperExist=`dpkg -l | grep zookeeperd`
if [ "$zookeeperExist" == "" ]; then
echo -e ""
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Get Zookeeper .................... "
sudo apt install -y zookeeperd &> /dev/null
echo -e "Done.\n"
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Zookeeper Already Installed."
fi
}
kafka_check()
{
kafkaExist=`ls | grep kafka`
if [ "$kafkaExist" == "" ]; then
echo -e ""
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Get Kafka .................... "
wget http://mirror.apache-kr.org/kafka/1.1.0/kafka_2.11-1.1.0.tgz &> /dev/null
tar -xvzf kafka_2.11-1.1.0.tgz &> /dev/null
mv kafka_2.11-1.1.0 /opt
rm -rf kafka_2.11-1.1.0.tgz
mkdir /var/lib/kafka
mkdir /var/lib/kafka/data
echo "delete.topic.enable = true" >> /opt/kafka_2.11-1.1.0/config/server.properties
echo "advertised.host.name=$VC_NAME" >> /opt/kafka_2.11-1.1.0/config/server.properties
sed -i "s/log.dirs=\/tmp\/kafka-logs/log.dirs=\/var\/lib\/kafka\/data/g" /opt/kafka_2.11-1.1.0/config/server.properties
sed -i "s/num.partitions=1/num.partitions=2/g" /opt/kafka_2.11-1.1.0/config/server.properties
sed -i "s/log.retention.hours=168/log.retention.hours=24/g" /opt/kafka_2.11-1.1.0/config/server.properties
touch /etc/systemd/system/kafka.service
echo "[Unit]" >> /etc/systemd/system/kafka.service
echo "Description=High-available, distributed message broker" >> /etc/systemd/system/kafka.service
echo "After=network.target" >> /etc/systemd/system/kafka.service
echo "After=network-online.target" >> /etc/systemd/system/kafka.service
echo "[Service]" >> /etc/systemd/system/kafka.service
echo "User=root" >> /etc/systemd/system/kafka.service
echo "ExecStart=/opt/kafka_2.11-1.1.0/bin/kafka-server-start.sh /opt/kafka_2.11-1.1.0/config/server.properties" >> /etc/systemd/system/kafka.service
echo "Restart=on-failure" >> /etc/systemd/system/kafka.service
echo "RestartSec=30" >> /etc/systemd/system/kafka.service
echo "[Install]" >> /etc/systemd/system/kafka.service
echo "WantedBy=multi-user.target" >> /etc/systemd/system/kafka.service
systemctl daemon-reload
systemctl enable kafka.service
systemctl start kafka.service
systemctl status kafka.service
#kafka/bin/kafka-server-start.sh kafka/config/server.properties
#In case kafka server can't start then add IP to /etc/hosts
echo -e "Done. \n"
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Kafka Already Installed."
fi
}
multiviewJavaCollector_service()
{
touch /etc/systemd/system/multiview-java-collectors.service
echo "[Unit]" >> /etc/systemd/system/multiview-java-collectors.service
echo "Description=Multi-View Java-based Collectors" >> /etc/systemd/system/multiview-java-collectors.service
echo "After=network.target" >> /etc/systemd/system/multiview-java-collectors.service
echo "After=network-online.target" >> /etc/systemd/system/multiview-java-collectors.service
echo "[Service]" >> /etc/systemd/system/multiview-java-collectors.service
echo "User=root" >> /etc/systemd/system/multiview-java-collectors.service
echo "WorkingDirectory=/opt/OpenStack-MultiView/MultiView-RunnableJars" >> /etc/systemd/system/multiview-java-collectors.service
echo "ExecStart=/opt/OpenStack-MultiView/MultiView-RunnableJars/start-multiview-java-collectors" >> /etc/systemd/system/multiview-java-collectors.service
echo "SuccessExitStatus=143" >> /etc/systemd/system/multiview-java-collectors.service
echo "StandardOutput=null" >> /etc/systemd/system/multiview-java-collectors.service
echo "StandardError=null" >> /etc/systemd/system/multiview-java-collectors.service
echo "Restart=on-failure" >> /etc/systemd/system/multiview-java-collectors.service
echo "RestartSec=10" >> /etc/systemd/system/multiview-java-collectors.service
echo "[Install]" >> /etc/systemd/system/multiview-java-collectors.service
echo "WantedBy=multi-user.target" >> /etc/systemd/system/multiview-java-collectors.service
systemctl daemon-reload
systemctl enable multiview-java-collectors.service
systemctl start multiview-java-collectors.service
systemctl status multiview-java-collectors.service
}
sFlowRTCollector_service()
{
touch /etc/systemd/system/sflow-rt-collector.service
echo "[Unit]" >> /etc/systemd/system/sflow-rt-collector.service
echo "Description=sFlow-RT Collector" >> /etc/systemd/system/sflow-rt-collector.service
echo "After=network.target" >> /etc/systemd/system/sflow-rt-collector.service
echo "After=network-online.target" >> /etc/systemd/system/sflow-rt-collector.service
echo "[Service]" >> /etc/systemd/system/sflow-rt-collector.service
echo "User=root" >> /etc/systemd/system/sflow-rt-collector.service
echo "ExecStart=/opt/OpenStack-MultiView/Visibility-Collection-Validation/Collectors/sflow-rt/start.sh" >> /etc/systemd/system/sflow-rt-collector.service
echo "SuccessExitStatus=143" >> /etc/systemd/system/sflow-rt-collector.service
echo "StandardOutput=null" >> /etc/systemd/system/sflow-rt-collector.service
echo "StandardError=null" >> /etc/systemd/system/sflow-rt-collector.service
echo "Restart=on-failure" >> /etc/systemd/system/sflow-rt-collector.service
echo "RestartSec=10" >> /etc/systemd/system/sflow-rt-collector.service
echo "[Install]" >> /etc/systemd/system/sflow-rt-collector.service
echo "WantedBy=multi-user.target" >> /etc/systemd/system/sflow-rt-collector.service
systemctl daemon-reload
systemctl enable sflow-rt-collector.service
systemctl start sflow-rt-collector.service
systemctl status sflow-rt-collector.service
}
grafana_check ()
{
grafana=`dpkg -l | grep grafana`
if [ "$grafana" == "" ]; then
echo -n "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Grafana Installing .................... "
wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana_5.1.1_amd64.deb
sudo dpkg -i grafana_5.1.1_amd64.deb
sudo systemctl enable grafana-server.service
sudo systemctl restart grafana-server.service
echo -e "Done."
echo `grafana-server -v`
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Grafana Already Installed."
echo `grafana-server -v`
fi
}
kibana_check ()
{
kibana=`dpkg -l | grep kibana`
if [ "$kibana" == "" ]; then
echo -n "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Kibana Installing .................... "
wget https://artifacts.elastic.co/downloads/kibana/kibana-6.2.4-amd64.deb &> /dev/null
shasum -a 512 kibana-6.2.4-amd64.deb
sudo dpkg -i kibana-6.2.4-amd64.deb
#sed -i "s/#server.port:.*/server.port: 5601/" /etc/kibana/kibana.yml
sed -i "s/#server.host:.*/server.host: $MGMT_IP/" /etc/kibana/kibana.yml
sed -i "s/#elasticsearch.url:.*/elasticsearch.url: '"http://$MGMT_IP:9200"'/" /etc/kibana/kibana.yml
sed -i "/#kibana.index:/c\kibana.index: .kibana/" /etc/kibana/kibana.yml
sudo systemctl daemon-reload
sudo systemctl enable kibana
sudo systemctl start kibana
rm -rf kibana-6.2.4-amd64.deb
echo -e "Done."
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Kibana Already Installed."
fi
}
nodeJSlib_check()
{
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] NodeJS Libraries Installing .................... "
sudo npm install npm -g
currentDir=`pwd`
cd Visibility-Visualization/pvcT-Visualization
npm config set registry https://registry.npmjs.org/
npm cache clean
npm install
sudo npm install -g nodemon
echo -e "Done.\n"
cd $currentDir
touch /etc/systemd/system/multi-view-web.service
echo "[Unit]" >> /etc/systemd/system/multi-view-web.service
echo "Description=Multi-View, Visualization Application" >> /etc/systemd/system/multi-view-web.service
echo "After=network.target" >> /etc/systemd/system/multi-view-web.service
echo "After=network-online.target" >> /etc/systemd/system/multi-view-web.service
echo "[Service]" >> /etc/systemd/system/multi-view-web.service
echo "User=root" >> /etc/systemd/system/multi-view-web.service
echo "ExecStart=/usr/bin/node /opt/KONE-MultiView/Visibility-Visualization/pvcT-Visualization/server.js" >> /etc/systemd/system/multi-view-web.service
echo "Restart=on-failure" >> /etc/systemd/system/multi-view-web.service
echo "RestartSec=10" >> /etc/systemd/system/multi-view-web.service
echo "[Install]" >> /etc/systemd/system/multi-view-web.service
echo "WantedBy=multi-user.target" >> /etc/systemd/system/multi-view-web.service
systemctl daemon-reload
systemctl enable multi-view-web.service
systemctl start multi-view-web.service
systemctl status multi-view-web.service
}
wget_check
java_check
influxDB_check
elasticsearch_check
mongoDB_check
nodeJS_check
zookeeper_check
kafka_check
multiviewJavaCollector_service
sFlowRTCollector_service
grafana_check
kibana_check
nodeJSlib_check
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/flow/MessageProcessing.java
package smartx.multiview.collectors.flow;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
/**
*
* The Class File of MessageProcessing part of sFlowtoKafka Program.
*
* The class for processing two JSON formatted REST API output
* into single JSON-formatted string message.
*
* @author <NAME>
* @author GIST NetCS
*
*/
public class MessageProcessing {
public static String MessageParsingAndBuilder (String line, String flowDetail) {
String message = "";
org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser();
JSONObject jsonObject;
JSONArray infoArray;
JSONObject jsonObject2;
JSONArray infoArray2;
String[] agentID = new String[100];
String[] flowKey = new String[100];
String[] bytesMetric = new String[100];
String[] framesMetric = new String[100];
String[] framesSizeMetric = new String[100];
int objectID = 0;
// Split the combined RESTAPI output (Bytes and Frame Value)
String[] lines = line.split(";");
try {
// Read the first API output
jsonObject = (JSONObject) jsonParser.parse(lines[0]);
infoArray = (JSONArray) jsonObject.get(flowDetail);
for(int i = 0; i<infoArray.size();i++){
JSONObject Object = (JSONObject) infoArray.get(i);
agentID[i] = Object.get("agent").toString();
flowKey[i] = Object.get("key").toString();
bytesMetric[i] = Object.get("value").toString();
// Read the second API output
jsonObject2 = (JSONObject) jsonParser.parse(lines[1]);
infoArray2 = (JSONArray) jsonObject2.get(flowDetail);
for(int j = 0; j<infoArray2.size();j++){
JSONObject Object2 = (JSONObject) infoArray2.get(j);
agentID[j] = Object2.get("agent").toString();
flowKey[j] = Object2.get("key").toString();
framesMetric[j] = Object2.get("value").toString();
// If the flow key and agent are same, add second metric in the first JSON output
if ( agentID[j].equals(agentID[i]) && (flowKey[j].equals(flowKey[i]))) {
// Calculate the FrameSize from Bytes and Frame Per Second
framesSizeMetric[i] = frameSizeCalculation(bytesMetric[i], framesMetric[i]);
}
}
objectID++;
}
} catch (ParseException e) {
e.printStackTrace();
}
/** Re-build the JSON message with two values (bytes and frame size) **/
for(int i = 0; i<objectID;i++){
// Different entry for the last JSON object
if ( i == objectID - 1)
message = message + JsonBuilder(agentID[i],flowKey[i],bytesMetric[i],framesSizeMetric[i]);
else
message = message + JsonBuilder(agentID[i],flowKey[i],bytesMetric[i],framesSizeMetric[i]) + ",";
}
// Add the string to complete JSON messages
if (!message.equals(""))
message = "{\"" + flowDetail + "\":[" + message + "]}";
else
message = "{\"" + flowDetail + "\":[]}";
return message;
}
private static String frameSizeCalculation (String bytes, String frames) {
double frameSizeMetric = 0.0;
// Convert string into double and the calculate the frame size
frameSizeMetric = Double.valueOf(bytes) / Double.valueOf(frames);
return String.valueOf(frameSizeMetric);
}
@SuppressWarnings("unchecked")
private static String JsonBuilder (String agent, String key, String bytes, String frameSize) {
String message = "";
// JSON message builder for two types of REST API output
@SuppressWarnings("rawtypes")
Map Object = new LinkedHashMap();
Object.put("AgentID", checkAgentName(agent));
Object.put("FlowKey",key);
Object.put("Bytes",bytes);
Object.put("FrameSize", frameSize);
StringWriter Out = new StringWriter();
try {
JSONValue.writeJSONString(Object, Out);
} catch (IOException e) {
e.printStackTrace();
}
message = Out.toString();
return message;
}
private static String checkAgentName(String IpAddress) {
Scanner hostFile;
String hostname ="";
try {
hostFile = new Scanner(new File("/etc/hosts"));
while (hostFile.hasNextLine()){
String[] hostIP = (hostFile.nextLine().toString()).split("\\s+");
if (IpAddress.equals(hostIP[0])) {
hostname = hostIP[1];
break;
}
else
hostname = IpAddress;
}
hostFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return hostname;
}
}
<file_sep>/Visibility-Agent/visibility/vis_points/comp_psutil_point.py
import psutil
import logging
import sys
import yaml
import json
import zmq
import socket
import time
import signal
from datetime import datetime
class ComputePsutilPoint:
def __init__(self, point_config):
self._logger = logging.getLogger()
self._logger.setLevel(logging.INFO)
self._point = None
self._level = None
self._type = None
self._option = None
self._mq_context = None
self._mq_sock = None
self._load_config(point_config)
self._prepare_mq_conn(point_config["msg_queue"])
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def _load_config(self, point_config):
self._point = point_config["point"]
self._level = point_config["level"]
self._type = point_config["type"]
self._option = point_config["option"]
def _prepare_mq_conn(self, mq_config):
self._mq_context = zmq.Context()
self._mq_sock = self._mq_context.socket(zmq.PUSH)
self._mq_sock.connect("tcp://{}:{}".format(mq_config["ipaddress"], mq_config["port"]))
self._logger.info("MQ Socket is connected to {}:{}".format(mq_config["ipaddress"], mq_config["port"]))
def collect(self):
comp_all_info = dict()
while True:
self._collect_cpu(comp_all_info)
self._collect_mem(comp_all_info)
msg = self._get_influx_msg(comp_all_info)
self._send_msg(msg)
time.sleep(float(self._option["interval"]))
def _collect_cpu(self, comp_all_info):
cpu_percent = psutil.cpu_percent(interval=None)
if cpu_percent == 0:
cpu_percent = psutil.cpu_percent(interval=None)
comp_all_info["cpu_percent"] = cpu_percent
cpu_time_info = psutil.cpu_times()
for key in cpu_time_info._fields:
value = getattr(cpu_time_info, key)
comp_all_info["cpu_{}".format(key)] = str(value)
cpu_stat_info = psutil.cpu_stats()
for key in cpu_stat_info._fields:
value = getattr(cpu_stat_info, key)
comp_all_info["cpu_{}".format(key)] = str(value)
def _collect_mem(self, comp_all_info):
vmem_info = psutil.virtual_memory()
swap_info = psutil.swap_memory()
for key in vmem_info._fields:
value = getattr(vmem_info, key)
comp_all_info["mem_{}".format(key)] = value
for key in swap_info._fields:
value = getattr(swap_info, key)
comp_all_info["swap_{}".format(key)] = value
def _get_influx_msg(self, comp_all_info):
# measurement: physical_compute (self._type)
# tags: Box Name
# fields:
msg = dict()
msg["measurement"] = self._type
msg["time"] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
tags = dict()
tags["box"] = socket.gethostname()
msg["tags"] = tags
msg["fields"] = comp_all_info
influx_msg = json.dumps([msg])
return influx_msg
def _send_msg(self, msg):
m = msg
if isinstance(msg, dict):
m = json.dumps(msg)
elif isinstance(msg, list):
m = json.dumps(msg)
zmq_msg = "{}/{}".format(self._level, m)
self._logger.debug(zmq_msg)
self._mq_sock.send_string(zmq_msg)
def signal_handler(self, signal, frame):
self._logger.info("Visibility Point {} was finished successfully".format(self.__class__.__name__))
sys.exit(0)
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s] %(filename)s,%(funcName)s(#%(lineno)d): %(message)s",
level=logging.INFO)
config_file = None
point_conf = dict()
if len(sys.argv) == 1:
config_file = "comp_psutil_point.yaml"
elif len(sys.argv) == 2:
# Load configuration from a file passed by second argument in the command
config_file = sys.argv[1]
else:
exit(1)
with open(config_file) as f:
cfg_str = f.read()
point_conf = yaml.load(cfg_str)
logging.getLogger().debug(point_conf)
point = ComputePsutilPoint(point_conf)
point.collect()
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapDFParser.java
package chainlinker;
/*
* Corresponding to snap-plugin-collector-df
*
* CAUTION: This setting may fail in case if the plugins' version mismatch with the below.
* - collector:df:2
*/
public class SnapDFParser extends SnapPluginParser {
public SnapDFParser() {
super();
// All these data forms must be updated when snap publisher's output format is changed.
// Pattern: /intel/procfs/filesystem/(Any strings without /)/(space_percent_free or space_percent_reserved or space_percent_used or inodes_percent_free or inodes_percent_reserved or inodes_percent_used)
regexTypeMap.put("^\\/intel\\/procfs\\/filesystem\\/((?!\\/).)*\\/(space_percent_free|space_percent_reserved|space_percent_used|inodes_percent_free|inodes_percent_reserved|inodes_percent_used)$", lfClass);
// Pattern: /intel/procfs/filesystem/(Any strings without /)/(space_free or space_reserved or space_used or inodes_free or inodes_reserved or inodes_used)
regexTypeMap.put("^\\/intel\\/procfs\\/filesystem\\/((?!\\/).)*\\/(space_free|space_reserved|space_used|inodes_free|inodes_reserved|inodes_used)$", lClass);
// Pattern: /intel/procfs/filesystem/(Any strings without /)/(device_name or device_type)
regexTypeMap.put("^\\/intel\\/procfs\\/filesystem\\/((?!\\/).)*\\/(device_name|device_type)$", sClass);
regexSet = regexTypeMap.keySet();
}
}
<file_sep>/Visibility_Center_Install.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Visibility_Center_Install.sh
# Description : Script for Installing Dependencies on SmartX Visibility Center.
#
# Created by : <EMAIL>
# Version : 0.3
# Last Update : August, 2018
#Update Management IP according to your requirement
MGMT_IP=""
#Ensure Root User Runs this Script
if [ "$(id -u)" != "0" ]; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')][ERROR][INSTALL]This script must be run as root" 1>&2
exit 1
fi
echo "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Multi-View Installation Started..."
MultiView-Scripts/Install_Dependencies_vCenter.sh "$MGMT_IP"
MultiView-Scripts/Create_MultiView_Database.sh "$MGMT_IP"<file_sep>/Visibility-Integration/control_tags.sh
#!/bin/bash
#
# Copyright 2018 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : control_tags.sh
# Description : Script for setting up SmartX Tags for SmartX Boxes and Tenants. This script should be executed at ID Center via crontab. e.g. */10 * * * * /bin/bash /home/netcs/control_tags.sh. sshpass should be installed in ID Center.
#
# Created by : <NAME>
# Version : 0.1
# Last Update : December, 2018
#
OS_REGIONS="GIST1 KR-GIST2 GIST3 TW-NCKU MYREN MY-UM TH-CHULA VN-HUST"
. /home/netcs/openstack/admin-openrc
for region in $OS_REGIONS
do
for server in $(openstack --os-region-name $region server list -c ID -f value --all-projects)
do
# the -f shell option sets environment variables
eval $(openstack --os-region-name $region server show $server -f shell -c id -c name -c OS-EXT-SRV-ATTR:host -c OS-EXT-STS:power_state -c addresses -c project_id)
project_name=$(openstack project show -f value -c name $project_id)
# echo "$project_id,$project_name,$os_ext_srv_attr_host,$id,$name,$addresses" >> ControlPlane.tags.temp
address1=$(echo $addresses | cut -d';' -f 1)
address2=$(echo $addresses | cut -d';' -f 2)
#echo "$addresses"
#echo $address1
#echo $address2
if [[ $address1 =~ .*control.* ]]
then
ctrladdress=$(echo $address1 | cut -d',' -f 2)
ctrladdress=$(echo $ctrladdress | xargs)
elif [[ $address1 =~ .*datapath.* ]]
then
dataaddress=$(echo $address1 | cut -d'=' -f 2)
dataaddress=$(echo $dataaddress | xargs)
fi
if [[ $address2 =~ .*control.* ]]
then
ctrladdress=$(echo $address2 | cut -d',' -f 2)
ctrladdress=$(echo $ctrladdress | xargs)
elif [[ $address2 =~ .*datapath.* ]]
then
dataaddress=$(echo $address2 | cut -d'=' -f 2)
dataaddress=$(echo $dataaddress | xargs)
fi
echo "$ctrladdress $dataaddress"
echo "$project_id,$project_name,$os_ext_srv_attr_host,$id,$name,$ctrladdress,$dataaddress" >> ControlPlane.tags.temp
done
done
mv ControlPlane.tags.temp ControlPlane.tags
<file_sep>/Visibility-Visualization/pvcT-Visualization/server.js
/**
* Module dependencies.
*/
var http = require("http");
var express = require('express');
var async = require('async');
var path = require('path')
var favicon = require('serve-favicon')
var logger = require('morgan')
var methodOverride = require('method-override')
var session = require('express-session')
var bodyParser = require('body-parser')
var multer = require('multer')
var errorHandler = require('errorhandler')
var logger = require('morgan')
var BoxProvider = require('./MultiView-DataAPI').BoxProvider;
var client = require('socket.io').listen(8080).sockets;
var host = "";
var app = express();
app.set('view engine', 'pug');
app.use(express.json());
app.use(logger('dev'))
app.use(methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.set('views', path.join(__dirname, '/views'))
app.use(session({ resave: true,
saveUninitialized: true,
secret: 'uwotm8' }))
//app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
//app.use(multer())
app.use(express.static(path.join(__dirname, '/public')))
//Before starting application run below command in public directory
//ln -s /opt/KONE-MultiView/pvcT-Visualization/node_modules/ /opt/KONE-MultiView/pvcT-Visualization/public/
//Define Application Routes
var resourceProvider = new ResourceProvider();
// Route for TCP Throughput-based Topology View
app.get('/tcptopologyviewops', function(req, res){
var boxList = null;
//console.log('Topology Visualization Rendering.');
resourceProvider.getTCPTopologyList( function(error, boxobj){
boxList = boxobj;
showView();
})
function showView(){
if(boxList !== null){
console.log('Topology Visualization Rendering.');
//console.log(boxList);
res.render('tcptopologyviewops.jade', { title: 'Playground Topology View', boxList: JSON.stringify(boxList) });
}
}
});
//the dictionary key is user name and value is
var userwithip = null;
var username = "admin";
//ManhNT start
app.get('/onionringviewops', function(req, res){
var data = null;
console.log(username);
resourceProvider.getDataMultiSliceVisibility(username, function(error, databj)
{
data = databj;
showView();
});
resourceProvider.getControllerList(function(error, controllerobj)
{
controllerList = controllerobj;
console.log(controllerList);
showView();
});
function showView()
{
if(data !== null && controllerList !== null){
res.render('onionringviewops.jade', {title: 'Onion-ring-based Visualization', data : JSON.stringify(data), controllerList : JSON.stringify(controllerList)});
}
}
});
app.get('/onionringviewtenant/*', function(req, res){
var data = null;
console.log(username);
resourceProvider.getDataMultiSliceVisibilityTenant('demo', function(error, databj)
{
data = databj;
showView();
});
resourceProvider.getControllerList(function(error, controllerobj)
{
controllerList = controllerobj;
console.log(controllerList);
showView();
});
function showView()
{
if(data !== null && controllerList !== null){
//console.log('Onion-ring Visualization Rendering'+data);
res.render('onionringviewtenant.jade', {title: 'Onion-ring-based Visualization', data : JSON.stringify(data), controllerList : JSON.stringify(controllerList)});
}
}
});
//manhNT end
// Route for Resource-Centric View
/*app.get('/resourcecentricviewops', function(req, res){
var boxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = null;
var pPathStatus = null;
resourceProvider.getpBoxList( function(error,boxobj){
boxList = boxobj;
//console.log( boxList);
showView();
})
resourceProvider.getvSwitchList(function(error, switchobj){
switchList = switchobj;
//console.log(switchList);
showView();
})
resourceProvider.getvBoxList(function(error, instanceobj){
instanceList = instanceobj;
//console.log(instanceList);
showView();
})
resourceProvider.getovsBridgeStatus(function(error, bridgestatusobj){
ovsBridgeStatus = bridgestatusobj;
//console.log(ovsBridgeStatus);
showView();
})
function showView(){
if(boxList !== null && switchList !== null && instanceList !== null && workloadList !==null && ovsBridgeStatus !== null){
console.log('Resource-Centric View Rendering');
//console.log(ovsBridgeStatus);
res.render('resourcecentricviewops.jade', {title: 'Resource-Centric Topological View',
boxList : JSON.stringify(boxList),
switchList : JSON.stringify(switchList),
instanceList : JSON.stringify(instanceList),
workloadList : JSON.stringify(workloadList),
ovsBridgeStatus : JSON.stringify(ovsBridgeStatus)
},
function(err, html){
if (err) { console.err("ERR", err) };
//console.log(html);
res.status(200).send(html);
}
);
}
}
});*/
app.get('/resourcecentricviewops', function(req, res){
var bboxList = null;
var sboxList = null;
var cboxList = null;
var oboxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = null;
var boxes = {};
var pPathStatus = null;
var tasks = [
function(callback){
resourceProvider.getpBoxList('B', (function(error, bboxobj)
{
boxes.bbox = bboxobj;
callback();
}))
},
function(callback){
resourceProvider.getpBoxList('S', (function(error, sboxobj)
{
boxes.sbox = sboxobj;
//console.log(boxes.sbox);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getpBoxList('C', (function(error, cboxobj)
{
boxes.cbox = cboxobj;
//console.log(boxes.cbox);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getpBoxList('O', (function(error, oboxobj)
{
boxes.obox = oboxobj;
//console.log(boxes.obox);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getvSwitchList('B', (function(error, bswitchobj)
{
boxes.bswitchList = bswitchobj;
callback();
}))
},
function (callback){
resourceProvider.getvSwitchList('S', (function(error, sswitchobj)
{
boxes.sswitchList = sswitchobj;
//console.log(switchList);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getvSwitchList('C', (function(error, cswitchobj)
{
boxes.cswitchList = cswitchobj;
//console.log(switchList);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getvSwitchList('O', (function(error, oswitchobj)
{
boxes.oswitchList = oswitchobj;
//console.log(boxes.oswitchList);
callback();
//showView();
}))
},
function (callback){
resourceProvider.getovsBridgeStatus('B', function(error, bbridgestatusobj)
{
console.log(bbridgestatusobj);
boxes.bovsBridgeStatus = bbridgestatusobj;
callback();
})
},
function (callback){
resourceProvider.getovsBridgeStatus('S', function(error, sbridgestatusobj)
{
boxes.sovsBridgeStatus = sbridgestatusobj;
//console.log(ovsBridgeStatus);
callback();
//showView();
})
},
function (callback){
resourceProvider.getovsBridgeStatus('C', function(error, cbridgestatusobj)
{
boxes.covsBridgeStatus = cbridgestatusobj;
//console.log(boxes.covsBridgeStatus);
callback();
//showView();
})
},
function (callback){
resourceProvider.getovsBridgeStatus('O', function(error, obridgestatusobj)
{
boxes.oovsBridgeStatus = obridgestatusobj;
//console.log(boxes.oovsBridgeStatus);
callback();
//showView();
})
},
function(callback){
resourceProvider.getvBoxList(function(error, instanceobj)
{
boxes.instanceList = instanceobj;
//console.log(boxes.instanceList);
callback();
//showView();
})
},
function(callback){
resourceProvider.getIoTHostList(function(error, hostobj)
{
boxes.iotHostList = hostobj;
//console.log(boxes.iotHostList);
callback();
})
},
function(callback){
resourceProvider.getControllerList(function(error, controllerobj)
{
boxes.controllerList = controllerobj;
//console.log(boxes.controllerList);
callback();
})
}
];
async.parallel(tasks, function(err) {
console.log('Resource-Centric View Rendering');
res.render('resourcecentricviewops.jade', {
bboxList : JSON.stringify(boxes.bbox),
sboxList : JSON.stringify(boxes.sbox),
cboxList : JSON.stringify(boxes.cbox),
oboxList : JSON.stringify(boxes.obox),
bswitchList : JSON.stringify(boxes.bswitchList),
sswitchList : JSON.stringify(boxes.sswitchList),
cswitchList : JSON.stringify(boxes.cswitchList),
oswitchList : JSON.stringify(boxes.oswitchList),
instanceList : JSON.stringify(boxes.instanceList),
iotHostList : JSON.stringify(boxes.iotHostList),
bovsBridgeStatus : JSON.stringify(boxes.bovsBridgeStatus),
sovsBridgeStatus : JSON.stringify(boxes.sovsBridgeStatus),
covsBridgeStatus : JSON.stringify(boxes.covsBridgeStatus),
oovsBridgeStatus : JSON.stringify(boxes.oovsBridgeStatus),
controllerList : JSON.stringify(boxes.controllerList)
});
});
});
//Route for Flow Rules View
app.get('/flowrulesviewops', function(req, res){
console.log('Flow Rules and Statistics View Rendering');
//res.render('flowrulesviewops.jade', {title: 'Flow-Centric View'})
var boxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = null;
var pPathStatus = null;
resourceProvider.getpBoxList( function(error,boxobj)
{
boxList = boxobj;
console.log( boxList);
showView();
})
resourceProvider.getvSwitchList(function(error, switchobj)
{
switchList = switchobj;
console.log(switchList);
showView();
})
resourceProvider.getvBoxList(function(error, instanceobj)
{
instanceList = instanceobj;
console.log(instanceList);
showView();
})
resourceProvider.getovsBridgeStatus(function(error, bridgestatusobj)
{
ovsBridgeStatus = bridgestatusobj;
console.log(ovsBridgeStatus);
showView();
})
function showView()
{
if(boxList !== null && switchList !== null && instanceList !== null && workloadList !==null && ovsBridgeStatus !== null)
{
console.log('Flow Rules and Statistics View Rendering');
res.render('flowrulesviewops.jade', {title: 'Flow Rules and Statistics View Rendering',
boxList : JSON.stringify(boxList),
switchList : JSON.stringify(switchList),
instanceList : JSON.stringify(instanceList),
workloadList : JSON.stringify(workloadList),
ovsBridgeStatus : JSON.stringify(ovsBridgeStatus)
},
function(err, html){
if (err) { console.err("ERR", err) };
//console.log(html);
res.status(200).send(html);
}
);
}
}
});
// Route for Flow Path Tracing View
app.get('/flowtracingviewops/*', function(req, res){
//Wait for 1 minute before requesting again
req.connection.setTimeout(60*1000);
console.log('Flow Path Tracing View Rendering');
var tenantID=req.originalUrl;
var vlanID=tenantID;
tenantID=tenantID.substring(20, tenantID.indexOf("&"));
vlanID=vlanID.substring(vlanID.indexOf("&")+1, vlanID.length);
console.log(tenantID);
console.log(vlanID);
var boxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = 0;
var bridgevlanmapList = null;
resourceProvider.getpBoxList( function(error,boxobj)
{
boxList = boxobj;
showView();
})
resourceProvider.getvSwitchList(function(error, switchobj)
{
switchList = switchobj;
showView();
})
resourceProvider.getTenantvBoxList(tenantID, function(error, instanceobj)
{
instanceList = instanceobj;
showView();
})
resourceProvider.getbridgevlanmapList(vlanID, function(error, bridgevlanmapobj)
{
bridgevlanmapList = bridgevlanmapobj;
showView();
})
function showView()
{
if(boxList !== null && switchList !== null && instanceList !== null && workloadList !==null && ovsBridgeStatus !== null && bridgevlanmapList !==null)
{
res.render('flowtracingviewops.jade', {title: 'Flow Tracing View Rendering',
boxList : JSON.stringify(boxList),
switchList : JSON.stringify(switchList),
instanceList : JSON.stringify(instanceList),
workloadList : JSON.stringify(workloadList),
ovsBridgeStatus : JSON.stringify(ovsBridgeStatus),
bridgevlanmapList : JSON.stringify(bridgevlanmapList)
}
)
}
}
});
// Route for Flows/Playground Measurements View
app.get('/flowmeasureviewops', function(req, res){
console.log('Flow Measure View Rendering');
//res.render('flowcentricviewops.jade', {title: 'Flow-Centric View'})
var boxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = null;
var pPathStatus = null;
resourceProvider.getpBoxList( function(error,boxobj)
{
boxList = boxobj;
console.log( boxList);
showView();
})
resourceProvider.getvSwitchList(function(error, switchobj)
{
switchList = switchobj;
console.log(switchList);
showView();
})
resourceProvider.getvBoxList(function(error, instanceobj)
{
instanceList = instanceobj;
console.log(instanceList);
showView();
})
resourceProvider.getovsBridgeStatus(function(error, bridgestatusobj)
{
ovsBridgeStatus = bridgestatusobj;
console.log(ovsBridgeStatus);
showView();
})
function showView()
{
if(boxList !== null && switchList !== null && instanceList !== null && workloadList !==null && ovsBridgeStatus !== null)
{
console.log('Flow Measure View Rendering');
res.render('flowmeasureviewops.jade', {title: 'Flow Measure View',
boxList : JSON.stringify(boxList),
switchList : JSON.stringify(switchList),
instanceList : JSON.stringify(instanceList),
workloadList : JSON.stringify(workloadList),
ovsBridgeStatus : JSON.stringify(ovsBridgeStatus)
}
);
}
}
});
// Route for Packets/Box IO-Visor View
app.get('/flowiovisorviewops', function(req, res){
//res.render('flowiovisorviewops.jade', {title: 'Flow-Centric View'})
var boxList = null;
var switchList = null;
var instanceList = null;
var workloadList = 0;
var ovsBridgeStatus = null;
var pPathStatus = null;
resourceProvider.getpBoxList( function(error,boxobj)
{
boxList = boxobj;
console.log( boxList);
showView();
})
resourceProvider.getvSwitchList(function(error, switchobj)
{
switchList = switchobj;
console.log(switchList);
showView();
})
resourceProvider.getvBoxList(function(error, instanceobj)
{
instanceList = instanceobj;
console.log(instanceList);
showView();
})
resourceProvider.getovsBridgeStatus(function(error, bridgestatusobj)
{
ovsBridgeStatus = bridgestatusobj;
console.log(ovsBridgeStatus);
showView();
})
function showView()
{
if(boxList !== null && switchList !== null && instanceList !== null && workloadList !==null && ovsBridgeStatus !== null)
{
console.log('Packets/Box View Rendering');
res.render('flowiovisorviewops.jade', {title: 'Flow Measure View',
boxList : JSON.stringify(boxList),
switchList : JSON.stringify(switchList),
instanceList : JSON.stringify(instanceList),
workloadList : JSON.stringify(workloadList),
ovsBridgeStatus : JSON.stringify(ovsBridgeStatus)
}
);
}
}
});
// Route for Workload View
app.get('/servicecentricviewops', function(req, res){
console.log('Workload-Centric View Rendering');
res.render('servicecentricviewops.jade', {title: 'Workload Centric View'})
});
// Route for Flow Rules View
app.get('/opsflowrules/*', function(req, res){
var configList = null;
var statList = null;
var boxID=req.originalUrl;
boxID=boxID.substring(14,boxID.length);
resourceProvider.getOpsSDNConfigList(boxID, function(error,configobj)
{
configList = configobj;
showView();
})
resourceProvider.getOpsSDNStatList(boxID, function(error,statobj)
{
statList = statobj;
console.log(statList);
showView();
})
function showView()
{
if(configList !== null && statList !== null)
{
console.log('Operator Controller Flow Rules');
console.log(statList);
res.render('opssdncontconfig.jade', { title: 'Operator Controller Flow Rules', configList: configList, statList: statList });
// res.render('opssdncontconfig.jade',{locals: {
// configList : JSON.stringify(configList),
// },
// title: 'Operator Controller Flow Rules'}
// )
}
}
});
// Route for Flow Statistics View
app.get('/opsflowstat', function(req, res){
var statList = null;
resourceProvider.getOpsSDNStatList( function(error,statobj)
{
statList = statobj;
console.log(statList);
showView();
})
function showView()
{
if(statList !== null)
{
console.log('Operator Controller Flow Stats');
res.render('opssdncontstat.jade', { title: 'Operator Controller Flow Statistics', statList: statList });
}
}
});
// Route for Tenant-Vlan Mappings View
app.get('/tenantvlanmapops', function(req, res){
var tenantList = null;
//var tenantID=req.originalUrl;
//tenantID=tenantID.substring(14, tenantID.length);
//resourceProvider.gettenantvlanmapList(tenantID, function(error, tenantObj)
resourceProvider.gettenantvlanmapList(function(error, tenantObj)
{
tenantList = tenantObj;
showView();
})
function showView()
{
if(tenantList !== null)
{
console.log('Tenant-Vlan Flow Path Tracing');
console.log(tenantList);
res.render('tenantvlanmapops.jade', { title: 'Tenant Vlan Mappings View', tenantList: tenantList });
}
}
});
// Route for Tenant-Vlan Mappings View
app.get('/tenantvlanmaponionring', function(req, res){
var tenantList = null;
resourceProvider.gettenantvlanmapList(function(error, tenantObj)
{
tenantList = tenantObj;
showView();
})
function showView()
{
if(tenantList !== null)
{
console.log('Tenant-Vlan Onion-ring');
//console.log(tenantList);
res.render('tenantvlanmaponionring.jade', { title: 'Tenant Vlan Mappings View', tenantList: tenantList });
}
}
});
// Route for TCP Throughput-based Data API
app.get('/getamdatatcpperDay/', function(req, res){
//Wait for 1 minute before requesting again
req.connection.setTimeout(60*1000);
var boxID=req.originalUrl;
var filterdate=boxID;
boxID=filterdate.substring(20, filterdate.indexOf("&"));
filterdate=boxID.substring(boxID.indexOf("&")+1, boxID.length);
console.log(boxID);
console.log(filterdate);
resourceProvider.getAMDataTCPperDay(boxID, filterdate, function(error, data){
if (err)
res.send(err);
res.json(data);
})
});
// Route for TEIN International API Call
app.get('/teinint', function(req, res){
var data = null;
resourceProvider.getTwoRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for REN API Call
app.get('/ren', function(req, res){
var data = null;
resourceProvider.getThreeRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for Sites API Call
app.get('/sites', function(req, res){
var data = null;
resourceProvider.getFourRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for SmartX Boxes/Micro-Boxes API Call
app.get('/boxes', function(req, res){
var data = null;
resourceProvider.getFiveRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for SmartX Boxes/Micro-Boxes API Call
app.get('/vms', function(req, res){
var data = null;
resourceProvider.getSixRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for SmartX Boxes/Micro-Boxes API Call
app.get('/flows', function(req, res){
var data = null;
resourceProvider.getSevenRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for SmartX Boxes/Micro-Boxes API Call
app.get('/workload', function(req, res){
var data = null;
resourceProvider.getEightRingAPI(function(error, dataobj)
{
data = dataobj;
showView();
});
function showView()
{
if(data !== null){
res.render('onionringviewapi.jade', {title: 'Onion-ring Visualization', data : JSON.stringify(data)});
}
}
});
// Route for Login View
app.get('/', function(req, res){
res.render('login.jade', {title: 'MultiView Web Application Login'})
});
// Route for Menu View
app.get('/menu', function(req, res){
console.log('Menu Rendering');
userwithip = {name:username , ip : req.connection.remoteAddress};
console.log(userwithip);
res.render('menu.jade',{locals: {}, title: 'Multi-View Menu'})
});
app.get('/login', function(req, res){
res.render('login.jade',{ title: 'MultiView Login'})
});
// error handling middleware should be loaded after the loading the routes
if (app.get('env') === 'production') {
app.use(errorHandler())
}
// Web Autentication & Validation
client.on('connection', function (socket) {
socket.on('login', function(login_info){
var this_user_name = login_info.user_name,
this_user_password = login_info.user_password;
if (this_user_name === '' || this_user_password === '') {
socket.emit('alert', 'You must fill in both fields');
} else {
resourceProvider.getUsers(function (err, listusers){
if(err) throw err;
var found = false,
location =-1;
if (listusers.length) {
for (var i in listusers) {
if (listusers[i].username === this_user_name) {
found = true;
if (listusers[i].password === <PASSWORD>) {
//todo: get priority and send to menu page.
username = this_user_name;
if(listusers[i].role === 'operator'){
socket.emit('redirect', 'operator');
}
else{
socket.emit('redirect', 'developer');
}
} else {
socket.emit('alert', 'Please retry password');
}
break;
}
}
if (!found) {
socket.emit('alert', 'Sorry, We could not find you.');
}
}
})
}
});
});
app.set('domain', '0.0.0.0')
app.listen(3011, () => console.log("Express Server Running..."))
//console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/ReflectivePointFieldFeeder.java
package chainlinker;
/*
* This class separates non-reflective codes from the main code block.
*/
import java.io.InvalidClassException;
public abstract class ReflectivePointFieldFeeder {
// NOTE:
// I'm still getting familiar with Java, but if there're anyone knows it better than me,
// please fix this. I think this part can be better than this.
// Dummy value objects for class type info
protected static Long lValue = 0L;
protected static Double lfValue = 0.0;
protected static String sValue = "";
protected static Boolean bValue = false;
public void addField (
Object metricObject,
@SuppressWarnings("rawtypes") Class dataTypeClass,
Object data
) throws ClassNotFoundException, InvalidClassException {
if (dataTypeClass.equals(lValue.getClass())) {
addLong(metricObject, (long)data);
} else if (dataTypeClass.equals(lfValue.getClass())) {
// For double values, additional touch is required as sometimes integer value may be passed.
if (lValue.getClass() == data.getClass()) {
// The reason for this double typecasting:
// http://stackoverflow.com/questions/32757565/java-lang-long-cannot-be-cast-to-java-lang-double
// https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3
addDouble(metricObject, (double)((long)data));
} else {
addDouble(metricObject, (double)data);
}
} else if (dataTypeClass.equals(sValue.getClass())) {
addString(metricObject, (String)data);
} else if (dataTypeClass.equals(bValue.getClass())) {
addBoolean(metricObject, (Boolean)data);
} else {
throw new ClassNotFoundException("Unidentifiable value is detected. Is the JSON data value is correct?");
}
}
protected abstract void addString(Object metricObject, String value) throws InvalidClassException;
protected abstract void addLong(Object metricObject, long value) throws InvalidClassException;
protected abstract void addDouble(Object metricObject, double value) throws InvalidClassException;
protected abstract void addBoolean(Object metricObject, boolean value) throws InvalidClassException;
}
<file_sep>/Visibility-Storage-Staging/data-apis/lib/models/multiviewModel.ts
// /lib/models/crmModel.ts
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const BoxSchema = new Schema({
boxID: {
type: String
},
boxName: {
type: String
},
boxType: {
type: String
},
site: {
type: String
},
management_ip: {
type: String
},
data_ip: {
type: String
},
control_ip: {
type: String
},
management_ip_status: {
type: String
},
data_ip_status: {
type: String
},
control_ip_status: {
type: String
},
playground: {
type: String
},
boxcode: {
type: String
}
}, {collection: 'pbox-list'});
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapLibVirtParser.java
package chainlinker;
public class SnapLibVirtParser extends SnapPluginParser {
public SnapLibVirtParser() {
super();
// All these data forms must be updated when snap publisher's output format is changed.
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/disk/(alphanumerical(lowercase only) or _ or .)/(wrreq or rdreq or wrbytes or rdbytes)
regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/disk\\/([0-9]|[a-z]|_|\\.)*\\/(wrreq|rdreq|wrbytes|rdbytes)$", lClass);
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/memory/(mem or swap_in or swap_out or major_fault or minor_fault or free or max)
regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/memory\\/(mem|swap_in|swap_out|major_fault|minor_fault|free|max)$", lClass);
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/cpu/cputime
regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/cpu\\/cputime$", lClass);
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/cpu/cputime/(numerical not starting with 0 or 0 itself.)
regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/cpu\\/cputime\\/(0|[1-9][0-9]*)$", lClass);
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/network/(alphanumerical(lowercase only) or _ or . or -)/(rxbytes or rxpackets or rxerrs or rxdrop or txbytes or txpackets or txerrs or txdrop)
regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/network\\/([0-9]|[a-z]|_|\\-|\\.)*\\/(rxbytes|rxpackets|rxerrs|rxdrop|txbytes|txpackets|txerrs|txdrop)$", lClass);
// Obsolete types : Just commented for possible bug or later use.
// Pattern: /intel/libvirt/(alphanumerical or _ or -)/cpu/vcpu/(numerical not starting with 0 or 0 itself.)/cputime
// regexTypeMap.put("^\\/intel\\/libvirt\\/([0-9]|[a-z]|_|\\-)*\\/cpu\\/vcpu\\/(0|[1-9][0-9]*)\\/cputime$", lClass);
regexSet = regexTypeMap.keySet();
}
}
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/package-info.java
/**
*
*/
/**
* @author Chrome
*
*/
package chainlinker;<file_sep>/Visibility-Storage-Staging/data-apis/lib/controllers/multiviewController.ts
// /lib/controllers/multiviewController.ts
import * as mongoose from 'mongoose';
import { SDNControllerSchema } from '../models/sdncontModel';
import { OverlayLatencySchema } from '../models/overlaypmModel';
import { BoxSchema } from '../models/multiviewModel';
import { VMInstanceStatusSchema } from '../models/vminstanceModel';
import { IoTHostStatusSchema } from '../models/iothostModel';
import { Request, Response } from 'express';
const SDNCont = mongoose.model('SDNCont', SDNControllerSchema);
const OverlayLatency = mongoose.model('OverlayLatency', OverlayLatencySchema);
const Box = mongoose.model('Box', BoxSchema);
const VMInstance = mongoose.model('VMInstance', VMInstanceStatusSchema);
const IoTHost = mongoose.model('IoTHost', IoTHostStatusSchema);
export class SDNContController{
public getSDNCont (req: Request, res: Response) {
SDNCont.find({}, (err, list) => {
if(err){
res.send(err);
}
res.json(list);
});
}
}
export class BoxController{
public addNewBox (req: Request, res: Response) {
let newBox = new Box(req.body);
newBox.save((err, box) => {
if(err){
res.send(err);
}
res.json(box);
});
}
public getBox (req: Request, res: Response) {
Box.find({}, (err, box) => {
if(err){
res.send(err);
}
res.json(box);
});
}
}
export class OverlayController{
public getLatency (req: Request, res: Response) {
OverlayLatency.find({}, (err, latency) => {
if(err){
res.send(err);
}
res.json(latency);
});
}
public getLatencyWithBoxID (req: Request, res: Response) {
OverlayLatency.findById(req.params.Source, (err, latency) => {
if(err){
res.send(err);
}
res.json(latency);
});
}
}
export class VMInstanceSchema{
public getVMInstances (req: Request, res: Response) {
VMInstance.find({}, (err, list) => {
if(err){
res.send(err);
}
res.json(list);
});
}
}
export class IoTHostSchema{
public getIoTHosts (req: Request, res: Response) {
IoTHost.find({}, (err, list) => {
if(err){
res.send(err);
}
res.json(list);
});
}
}
<file_sep>/Visibility-Integration/tenant_subnet_tagger.sh
#!/bin/bash
#
# Copyright 2017 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Get OpenStack Subnet List (Multi-region Deployment)
# Description : Script for Integating/Mapping neutron network, subnet and tenant for operator+tenant tagging to assist flowcentric visibility. It must be executed in ID center via crontab. e.g. */5 * * * * /bin/bash /home/netcs/subnet_list.sh
#
# Created by : <NAME>
# Version : 0.2
# Last Update : December, 2018
#
OS_REGIONS="GIST1 KR-GIST2 GIST3 TW-NCKU MYREN MY-UM TH-CHULA VN-HUST"
. /home/netcs/openstack/admin-openrc
rm -rf tenant_subnet.temp1 tenant.tags.temp
for region in $OS_REGIONS
do
openstack --os-region-name $region subnet list --no-dhcp -c Network -c Subnet -f csv --quote none > tenant_subnet.temp1
while read -r subnetline
do
if [[ $subnetline == *"Network"* ]]; then
echo "Skip..."
else
network_id=`echo $subnetline | cut -d ',' -f1`
subnet_address=`echo $subnetline | cut -d ',' -f2`
subnetdetails=`openstack --os-region-name $region network show $network_id -c project_id -c provider:segmentation_id -f value`
project_id=`echo $subnetdetails | awk '{print $1}'`
vlan_id=`echo $subnetdetails | awk '{print $2}'`
project_name=`openstack project list | grep $project_id | cut -d'|' -f3 | awk '{$1=$1;print}'`
echo "$vlan_id,$project_id,$project_name,$subnet_address" >> tenant.tags.temp
fi
done < "tenant_subnet.temp1"
done
rm -rf tenant.tags
cat tenant.tags.temp | sort -u > tenant.tags
<file_sep>/Visibility-Agent/IOVisor/data_plane_tracing.py
#!/usr/bin/python
#
# Name : data_plane_tacing.py
# Description : A script for processing network packets at user-level
#
# Created by : <NAME>
# Version : 0.2
# Last Update : June, 2018
from __future__ import print_function
from bcc import BPF
from datetime import datetime
import sys
import socket
import os
import argparse
import netifaces as ni
import re
import json
from urllib2 import urlopen
import time
from kafka import KafkaProducer
from kafka.errors import KafkaError
import json
# convert a bin string into a string of hex char
# helper function to print raw packet in hex
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0' + hv
lst.append(hv)
return reduce(lambda x, y:x + y, lst)
# initialize BPF - load source code from http-parse-simple.c
bpf = BPF(src_file="mcd_planes_tracing.c", debug=0)
# load eBPF program http_filter of type SOCKET_FILTER into the kernel eBPF vm
# more info about eBPF program types http://man7.org/linux/man-pages/man2/bpf.2.html
function_vxlan_filter = bpf.load_func("vxlan_filter", BPF.SOCKET_FILTER)
# create raw socket, bind it to eth0
# attach bpf program to socket created
BPF.attach_raw_socket(function_vxlan_filter, "eno5")
ni.ifaddresses('eno2')
ip = ni.ifaddresses('eno2')[ni.AF_INET][0]['addr']
# get file descriptor of the socket previously created inside BPF.attach_raw_socket
socket_fd = function_vxlan_filter.sock
# create python socket object, from the file descriptor
sock = socket.fromfd(socket_fd, socket.PF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
# set it as blocking socket
sock.setblocking(True)
print("hosname, MachineIP ipver Src IP Addr Dst IP Addr Src_Port Des_Port Local_Src_Addr Local_des_Addr Local_Src_Port Local_Des_Port VNI VLANID protocol Packet Length ")
count_c1 = 0
while 1:
# retrieve raw packet from socket
packet_str = os.read(socket_fd, 2048)
# convert packet into bytearray
packet_bytearray = bytearray(packet_str)
# ethernet header length
ETH_HLEN = 14
# IP HEADER
# https://tools.ietf.org/html/rfc791
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |Version| IHL |Type of Service| Total Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# IHL : Internet Header Length is the length of the internet header
# value to multiply * 4 byte
# e.g. IHL = 5 ; IP Header Length = 5 * 4 byte = 20 byte
#
# Total length: This 16-bit field defines the entire packet size,
# including header and data, in bytes.
# calculate packet total length
total_length = packet_bytearray[ETH_HLEN + 2] # load MSB
total_length = total_length << 8 # shift MSB
total_length = total_length + packet_bytearray[ETH_HLEN + 3] # add LSB
# calculate ip header length
ip_header_length = packet_bytearray[ETH_HLEN] # load Byte
ip_header_length = ip_header_length & 0x0F # mask bits 0..3
ip_header_length = ip_header_length << 2 # shift to obtain length
# TCP HEADER
# https://www.rfc-editor.org/rfc/rfc793.txt
# 12 13 14 15
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Data | |U|A|P|R|S|F| |
# | Offset| Reserved |R|C|S|S|Y|I| Window |
# | | |G|K|H|T|N|N| |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# Data Offset: This indicates where the data begins.
# The TCP header is an integral number of 32 bits long.
# value to multiply * 4 byte
# e.g. DataOffset = 5 ; TCP Header Length = 5 * 4 byte = 20 byte
# calculate tcp header length
tcp_header_length = packet_bytearray[ETH_HLEN + ip_header_length + 12] # load Byte
tcp_header_length = tcp_header_length & 0xF0 # mask bit 4..7
tcp_header_length = tcp_header_length >> 2 # SHR 4 ; SHL 2 -> SHR 2
# calculate payload offset
payload_offset = ETH_HLEN + ip_header_length + tcp_header_length
# parsing ip version from ip packet header
ipversion = str(bin(packet_bytearray[14])[2:5])
# parsing source ip address, destination ip address from ip packet header
src_host_ip = str(packet_bytearray[26]) + "." + str(packet_bytearray[27]) + "." + str(packet_bytearray[28]) + "." + str(packet_bytearray[29])
dest_host_ip = str(packet_bytearray[30]) + "." + str(packet_bytearray[31]) + "." + str(packet_bytearray[32]) + "." + str(packet_bytearray[33])
# parsing source port and destination port
src_host_port = packet_bytearray[34] << 8 | packet_bytearray[35]
dest_host_port = packet_bytearray[36] << 8 | packet_bytearray[37]
# parsing VNI and VLANID from VXLAN header
VLANID = ""
VNI = str((packet_bytearray[46]) + (packet_bytearray[47]) + (packet_bytearray[48]))
VLANID = str((packet_bytearray[64]) + (packet_bytearray[65]))
if (packet_bytearray[77] == 6):
protocoll4 = 6
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dest_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
TCP_Window_Size = packet_bytearray[102] << 8 | packet_bytearray[103]
elif (packet_bytearray[77] == 1):
protocoll4 = 1
src_vm_port = -1
dest_vm_port = -1
TCP_Window_Size = 0
elif (packet_bytearray[77] == 17):
protocoll4 = 17
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dest_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
TCP_Window_Size = 0
else:
protocoll4 = packet_bytearray[77]
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dest_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
TCP_Window_Size = 0
src_vm_ip = str(packet_bytearray[80]) + "." + str(packet_bytearray[81]) + "." + str(packet_bytearray[82]) + "." + str(packet_bytearray[83])
dest_vm_ip = str(packet_bytearray[84]) + "." + str(packet_bytearray[85]) + "." + str(packet_bytearray[86]) + "." + str(packet_bytearray[87])
# MESSAGE = (socket.gethostname(), ip, str(int(ipversion, 2)), srcAddr, str(src_vm_port), dstAddr, str(dest_vm_port), str(total_length), protocoll4, local_src_addr, local_des_addr, str(int(VNI)), str(int(VLANID)))
# print (MESSAGE)
# MESSAGE1 = ','.join(MESSAGE)
# MESSAGE2 = MESSAGE1.encode()
# producer = KafkaProducer(bootstrap_servers=['vc.manage.overcloud:9092'])
# producer.send('iovisor-oftein', key=b'iovisor', value=MESSAGE2)
MESSAGE = str(int(round(time.time() * 1000000))) + "," + socket.gethostname() + "," + ip + "," + str(int(ipversion, 2)) + "," + src_host_ip + "," + dest_host_ip + "," + str(src_host_port) + "," + str(dest_host_port) + "," + src_vm_ip + "," + dest_vm_ip + "," + str(src_vm_port) + "," + str(dest_vm_port) + "," + str(int(VNI)) + "," + str(int(VLANID)) + "," + str(protocoll4) + "," +str(TCP_Window_Size)+","+ str(total_length)
print (MESSAGE)
CurrentMin = int(time.strftime("%M"))
BoxName=socket.gethostname()
if (CurrentMin < 30):
if (CurrentMin < 10):
if (CurrentMin < 5):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-00"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-05"
elif (CurrentMin < 20):
if (CurrentMin < 15):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-10"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-15"
else:
if (CurrentMin < 25):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-20"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-25"
else:
if (CurrentMin < 40):
if (CurrentMin < 35):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-30"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-35"
elif (CurrentMin < 50):
if (CurrentMin < 45):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-40"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-45"
else:
if (CurrentMin < 55):
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-50"
else:
filename = "/opt/IOVisor-Data/"+BoxName+"-data-" + time.strftime("%Y-%m-%d-%H") + "-55"
f = open(filename, "a")
f.write("%s\n" % MESSAGE)
f.close
<file_sep>/Visibility-Collection-Validation/Collectors/Multiview-Custom-Collectors/src/main/java/smartx/multiview/collectors/flow/SDNControllerStatus.java
/**
* @author <NAME>
* @version 0.1
*/
package smartx.multiview.collectors.flow;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class SDNControllerStatus implements Runnable{
private Thread thread;
private String ThreadName="SDN Controller Config Thread";
private String devopscontroller, user, password;
private MongoClient mongoClient;
private MongoDatabase db;
private Document document;
private MongoCollection<Document> collection1, collection2;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public SDNControllerStatus(String dbHost, int dbPort, String dbName, String flowConfigMongoCollection, String flowConfigMongoCollectionRT, String devopscon, String User, String Password)
{
mongoClient = new MongoClient(dbHost, dbPort);
db = mongoClient.getDatabase(dbName);
collection1 = db.getCollection(flowConfigMongoCollection);
collection2 = db.getCollection(flowConfigMongoCollectionRT);
devopscontroller = devopscon;
user = User;
password = <PASSWORD>;
}
public void getFlowsDetails()
{
String baseURL = "http://"+devopscontroller+":8080/controller/nb/v2/flowprogrammer";
String containerName = "default", actions, NodeID, BoxID;
String [] id;
Date timestamp = new Date();
//System.out.println(devopscontroller);
collection2.deleteMany(new Document());
try {
// Create URL = base URL + container
URL url = new URL(baseURL + "/" + containerName);
System.out.println(url);
// Create authentication string and encode it to Base64
String authStr = user + ":" + password;
String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());
// Create Http connection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set connection properties
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
connection.setRequestProperty("Accept", "application/json");
// Get the response from connection's inputStream
InputStream content = (InputStream) connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(content));
String line = "";
//JSONParser jsonParser = null;
line = in.readLine();
System.out.println(line);
JSONObject jsonObject = new JSONObject(line);
JSONArray jsonArray = jsonObject.getJSONArray("flowConfig");
for (int i=0 ; i<jsonArray.length(); i++)
{
document = new Document();
System.out.print("["+dateFormat.format(timestamp)+"][INFO][ODL][Node "+jsonArray.getJSONObject(i).get("node"));
System.out.print(" Name "+jsonArray.getJSONObject(i).get("name"));
System.out.print(" Install In Hw "+jsonArray.getJSONObject(i).get("installInHw"));
System.out.print(" Ingress Port "+jsonArray.getJSONObject(i).get("ingressPort"));
System.out.println(" Actions "+jsonArray.getJSONObject(i).get("actions")+"]");
//System.out.println(jsonArray.getJSONObject(i).get("id"));
id = jsonArray.getJSONObject(i).get("node").toString().split(",");
NodeID = id[0].substring(7, id[0].length()-1);
actions = jsonArray.getJSONObject(i).get("actions").toString();
if (NodeID.equals("33:33:33:33:33:33:33:11"))
BoxID="SmartXBoxGIST";
else if(NodeID.equals("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"))
BoxID="SmartXBoxMYREN";
else if(NodeID.equals("fc00:db20:35b:7399::5"))
BoxID="SmartXBoxID";
else if(NodeID.equals("fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b"))
BoxID="SmartXBoxPH";
else if(NodeID.equals("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b"))
BoxID="SmartXBoxVN";
else if(NodeID.equals("fc00:e968:6179::de52:7100"))
BoxID="SmartXBoxPKS";
else
BoxID="";
document.put("timestamp" , timestamp);
document.put("controllerIP" , devopscontroller);
document.put("boxID" , BoxID);
document.put("node" , NodeID);
document.put("name" , jsonArray.getJSONObject(i).get("name").toString());
document.put("InstallInHw", jsonArray.getJSONObject(i).get("installInHw").toString());
document.put("IngressPort" , jsonArray.getJSONObject(i).get("ingressPort").toString());
document.put("Actions" , actions.substring(2, actions.length()-2));
collection1.insertOne(document);
collection2.insertOne(document);
}
}catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (true)
{
getFlowsDetails();
try {
//Sleep For 5 Minutes
Thread.sleep(300000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void start() {
System.out.println("Starting SDN Controller Flows Config Thread");
if (thread==null){
thread = new Thread(this, ThreadName);
thread.start();
}
}
}
<file_sep>/Visibility-Integration/correlation/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>gist.netcs.integrate</groupId>
<artifactId>correlation</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.8.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.mongodb.mongo-hadoop</groupId>
<artifactId>mongo-hadoop-core</artifactId>
<version>1.4.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jgoodies/jgoodies-forms -->
<dependency>
<groupId>com.jgoodies</groupId>
<artifactId>jgoodies-forms</artifactId>
<version>1.6.0</version>
</dependency>
</dependencies>
</project><file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapPSUtilParser.java
package chainlinker;
/*
* Corresponding to snap-plugin-collector-psutil
*
* CAUTION: This setting may fail in case if the plugins' version mismatch with the below.
* - collector:psutil:6
*/
public class SnapPSUtilParser extends SnapPluginParser {
public SnapPSUtilParser() {
super();
// All these data forms must be updated when snap publisher's output format is changed.
typeMap.put("/intel/psutil/load/load1", lfClass);
typeMap.put("/intel/psutil/load/load5", lfClass);
typeMap.put("/intel/psutil/load/load15", lfClass);
typeMap.put("/intel/psutil/vm/active", lClass);
typeMap.put("/intel/psutil/vm/available", lClass);
typeMap.put("/intel/psutil/vm/buffers", lClass);
typeMap.put("/intel/psutil/vm/cached", lClass);
typeMap.put("/intel/psutil/vm/free", lClass);
typeMap.put("/intel/psutil/vm/inactive", lClass);
typeMap.put("/intel/psutil/vm/total", lClass);
typeMap.put("/intel/psutil/vm/used", lClass);
typeMap.put("/intel/psutil/vm/used_percent", lfClass);
typeMap.put("/intel/psutil/vm/wired", lClass);
// typeMap.put("/intel/psutil/vm/shared", lClass); // Currently the snap plugin is broken.
typeMap.put("/intel/psutil/net/all/bytes_recv", lClass);
typeMap.put("/intel/psutil/net/all/bytes_sent", lClass);
typeMap.put("/intel/psutil/net/all/dropin", lClass);
typeMap.put("/intel/psutil/net/all/dropout", lClass);
typeMap.put("/intel/psutil/net/all/errin", lClass);
typeMap.put("/intel/psutil/net/all/errout", lClass);
typeMap.put("/intel/psutil/net/all/packets_recv", lClass);
typeMap.put("/intel/psutil/net/all/packets_sent", lClass);
// Pattern: /intel/psutil/net/(alphanumerical(lowercase only) or _ or . or -)/(bytes_recv or bytes_sent or packets_recv or packets_sent)
regexTypeMap.put("^\\/intel\\/psutil\\/net\\/([0-9]|[a-z]|_|\\.|-)*\\/(bytes_recv|bytes_sent|dropin|dropout|errin|errout|packets_recv|packets_sent)$", lClass);
// Pattern: /intel/psutil/cpu/cpu(numerical not starting with 0 or 0 itself.)/(bytes_recv or bytes_sent or packets_recv or packets_sent)
// regexTypeMap.put("^\\/intel\\/psutil\\/cpu\\/cpu(0|[1-9][0-9]*)\\/(guest|guest_nice|idle|iowait|irq|nice|softirq|steal|stolen|system|user)$", lfClass);
// Currently "idle" value is given as null. Snap plugin is broken.
regexTypeMap.put("^\\/intel\\/psutil\\/cpu\\/cpu(0|[1-9][0-9]*)\\/(guest|guest_nice|iowait|irq|nice|softirq|steal|stolen|system|user)$", lfClass);
regexSet = regexTypeMap.keySet();
}
}<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/RFC3339toNSConvertor.java
package chainlinker;
import java.time.Instant;
public class RFC3339toNSConvertor {
/*
I don't know why there is no pre-existing library for this, but converting RFC3339 with zone
offset AND WITH nanosecond digits does not exist. So here I wrote the code instead.
For anyone who might come to repair this: If there are any standard library does this function,
then replace this one with it from this entire code.
*/
/*
Converting timestamp in RFC3339 standard into TimeUnit.NANOSECONDS form.
String "2016-07-21T16:41:50.679207324+09:00" -> long 1469086910679207324L
*/
public static long ToNS(String timestamp) {
int offset_pos = 23; // The position right after millisecond digit.
// Catching the exact starting position of zone offset data
long offset_millis = 0;
while (offset_pos < timestamp.length()) {
if (!Character.isDigit(timestamp.charAt(offset_pos))) {
break;
}
offset_pos++;
}
char offset_ops = timestamp.charAt(offset_pos);
if (offset_ops != 'Z') {
// If the beginning char is not 'Z', it means the date is not UTC and must be re-adjusted
// to UTC +00:00 (aka Z)
String offset_string = timestamp.substring(offset_pos + 1);
String[] values = offset_string.split(":");
offset_millis = (Integer.parseInt(values[0]) * 3600 + Integer.parseInt(values[1]) * 60) * 1000;
offset_millis *= offset_ops == '+' ? -1 : 1; // If offset is plus, then the value must be subtracted and vice versa.
}
// Using the existing timestamp parser with millisecond unit and concatenates the digits below
// to it.
long time = (Instant.parse(timestamp.substring(0, 23) + "Z").toEpochMilli() + offset_millis)* 1000000 + Long.parseLong(timestamp.substring(23, offset_pos));
return time;
}
}<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapPluginParser.java
package chainlinker;
import java.io.InvalidClassException;
import java.util.HashMap;
import java.util.Set;
/*
* This class serve as a template for all Snap plugin parsers.
*/
public abstract class SnapPluginParser {
Long lValue = 0L;
Double lfValue = 0.0;
String sValue = "";
Boolean bValue = false;
// These are dummy objects to provide class information.
@SuppressWarnings("rawtypes")
Class lClass = lValue.getClass();
@SuppressWarnings("rawtypes")
Class lfClass = lfValue.getClass();
@SuppressWarnings("rawtypes")
Class sClass = sValue.getClass();
@SuppressWarnings("rawtypes")
Class bClass = bValue.getClass();
@SuppressWarnings("rawtypes")
HashMap<String, Class> typeMap = new HashMap<>();
@SuppressWarnings("rawtypes")
HashMap<String, Class> regexTypeMap = new HashMap<>();
Set<String> regexSet = null;
public void loadParserMap(HashMap<String, SnapPluginParser> map) {
for (String dataName : typeMap.keySet()) {
map.put(dataName, this);
}
}
// This method is to describe how the parser will feed the given data into pointBuilder.
public void addField(
Object metricObject,
String dataTypeName,
Object data,
Backend backend
) throws ClassNotFoundException, InvalidClassException {
backend.addField(metricObject, dataTypeName, data, this);
}
// This method is to describe whether the parser is able to handle data with the given name.
// This exists to handle data with parameterized names.
public boolean isParsible(String dataTypeName) {
if (typeMap.get(dataTypeName) != null) {
return true;
}
else if (regexSet == null) return false;
else {
boolean regexMatched = false;
for (String regex : regexSet) {
if (dataTypeName.matches(regex)) {
regexMatched = true;
break;
}
}
if (regexMatched) {
return true;
}
return false;
}
}
}<file_sep>/Visibility-Collection-Validation/Collectors/Sampling-Flow-Defination/sFlowRestAPI.py
#!/usr/bin/env python
import requests
import json
TCPFlowDetail = {'keys':'vlan,ipdestination,ipsource,ipprotocol,tcpdestinationport','value':'bytes','log':True}
requests.put('http://172.16.17.32:8008/flow/TCPFlowDetail/json',data=json.dumps(TCPFlowDetail))
UDPFlowDetail = {'keys':'vlan,ipdestination,ipsource,ipprotocol,udpdestinationport','value':'bytes','log':True}
requests.put('http://172.16.17.32:8008/flow/UDPFlowDetail/json',data=json.dumps(UDPFlowDetail))
TCPFlowDetailFrames = {'keys':'vlan,ipdestination,ipsource,ipprotocol,tcpdestinationport','value':'frames','log':True}
requests.put('http://172.16.17.32:8008/flow/TCPFlowDetailFrames/json',data=json.dumps(TCPFlowDetailFrames))
UDPFlowDetailFrames = {'keys':'vlan,ipdestination,ipsource,ipprotocol,tcpdestinationport','value':'frames','log':True}
requests.put('http://172.16.17.32:8008/flow/UDPFlowDetailFrames/json',data=json.dumps(UDPFlowDetailFrames))
ICMPFlowDetail = {'keys':'vlan,ipdestination,ipsource,ipprotocol','value':'bytes','filter':'ipprotocol=1','log':True}
requests.put('http://172.16.17.32:8008/flow/ICMPFlowDetail/json',data=json.dumps(ICMPFlowDetail))
ICMPFlowDetailFrames = {'keys':'vlan,ipdestination,ipsource,ipprotocol','value':'frames','filter':'ipprotocol=1','log':True}
requests.put('http://172.16.17.32:8008/flow/ICMPFlowDetailFrames/json',data=json.dumps(ICMPFlowDetailFrames))
<file_sep>/Visibility-Agent/visibility/vis_points/net_ip_point.py
#!/usr/bin/python
#
# Name : net_ip_point.py
# Description : A script for processing network packets at user-level
#
# Created by : Networked Computing Systems Laboratory
# Maintained by : <NAME> and <NAME>
# Version : 0.4
# Last Update : August, 2018
from __future__ import print_function
import os
import socket
import time
import logging
import signal
import sys
import zmq
import json
import yaml
from datetime import datetime
import netifaces as ni
from bcc import BPF
class NetworkIpPacketPoint:
def __init__(self, point_config):
self._logger = logging.getLogger(self.__class__.__name__)
self._bpf_file = "net_ip_point.c"
self._bpf_func = "ip_filter"
self._bpf_bytecode = None
self._socket_filter = None
self._socket = None
self._socket_fd = None
# point_conf = dict()
# point_conf["point"] = "NetworkIpPacketPoint"
# point_conf["level"] = "resource"
# point_conf["type"] = "physical_networking"
#
# mq_opt = dict()
# mq_opt["ipaddress"] = "127.0.0.1"
# mq_opt["port"] = 50070
# point_conf["msg_queue"] = mq_opt
#
# point_opt = dict()
# point_opt["output_type"] = "stream"
# point_opt["target"] = "eno1"
# point_conf["option"] = point_opt
self._point = None
self._level = None
self._type = None
self._option = None
self._mq_context = None
self._mq_sock = None
self._load_config(point_config)
self._prepare_mq_conn(point_config["msg_queue"])
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def _load_config(self, point_config):
# Variables that have to be defined in point_config
self._point = point_config["point"]
self._level = point_config["level"]
self._type = point_config["type"]
self._option = point_config["option"]
def _prepare_mq_conn(self, mq_config):
self._mq_context = zmq.Context()
self._mq_sock = self._mq_context.socket(zmq.PUSH)
self._mq_sock.connect("tcp://{}:{}".format(mq_config["ipaddress"], mq_config["port"]))
self._logger.debug("MQ Socket is connected to {}:{}".format(mq_config["ipaddress"], mq_config["port"]))
def signal_handler(self, signal, frame):
self._logger.info("Visibility Point {} was finished successfully".format(self.__class__.__name__))
self._bpf_bytecode.cleanup()
self._socket.close()
sys.exit(0)
def collect(self):
self._init_bpf()
self._logger.debug("MachineIP Hostname ipver Src IP Addr Dst IP Addr src Port Dst Port "
" protocol TCP_Window_Size Packet_Length")
while True:
# For detailed information, please find "_not_used_func()" method.
packet_all_info = dict()
# retrieve raw packet from socket
packet_str = os.read(self._socket_fd, 2048)
# convert packet into bytearray
packet_bytearray = bytearray(packet_str)
self._store_packet_overall_info(packet_bytearray, packet_all_info)
self._store_packet_ip_info(packet_bytearray, packet_all_info)
self._store_packet_tcp_info(packet_bytearray, packet_all_info)
if self._option["output_type"] == "file":
message = self._gen_msg_str(packet_all_info)
filename = self._get_filename()
self._write_file(filename, message)
elif self._option["output_type"] == "stream":
message = self._get_influx_msg(packet_all_info)
self._send_msg(message)
def _init_bpf(self):
# initialize BPF - load source code from http-parse-simple.c
self._bpf_bytecode = BPF(src_file=self._bpf_file, debug=0)
# load eBPF program http_filter of type SOCKET_FILTER into the kernel eBPF vm
# more info about eBPF program types http://man7.org/linux/man-pages/man2/bpf.2.html
function_ip_filter = self._bpf_bytecode.load_func(self._bpf_func, BPF.SOCKET_FILTER)
# create raw socket, bind it to eth0
# attach bpf program to socket created
BPF.attach_raw_socket(function_ip_filter, self._option["nic"])
# get file descriptor of the socket previously created inside BPF.attach_raw_socket
self._socket_fd = function_ip_filter.sock
# create python socket object, from the file descriptor
self._socket = socket.fromfd(self._socket_fd, socket.PF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
# set it as blocking socket
self._socket.setblocking(True)
def _store_packet_overall_info(self, packet_bytearray, packet_info):
# ethernet header length
ETH_HLEN = 14
# calculate packet total length
total_length = packet_bytearray[ETH_HLEN + 2] # load MSB
total_length = total_length << 8 # shift MSB
total_length = total_length + packet_bytearray[ETH_HLEN + 3] # add LSB
packet_info["total_length"] = total_length
def _store_packet_ip_info(self, packet_bytearray, packet_info):
# parsing ip version from ip packet header
ipversion = str(bin(packet_bytearray[14])[2:5])
packet_info["ip_version"] = str(int(ipversion,2))
# parsing source ip address, destination ip address from ip packet header
src_addr = str(packet_bytearray[26]) + "." + str(packet_bytearray[27]) + "." + \
str(packet_bytearray[28]) + "." + str(packet_bytearray[29])
dst_addr = str(packet_bytearray[30]) + "." + str(packet_bytearray[31]) + "." + \
str(packet_bytearray[32]) + "." + str(packet_bytearray[33])
packet_info["src_ip_addr"] = src_addr
packet_info["dst_ip_addr"] = dst_addr
def _store_packet_tcp_info(self, packet_bytearray, packet_info):
# parsing source port and destination port
if packet_bytearray[23] == 6:
protocol = 6
src_port = packet_bytearray[34] << 8 | packet_bytearray[35]
dst_port = packet_bytearray[36] << 8 | packet_bytearray[37]
tcp_window_size = packet_bytearray[48] << 8 | packet_bytearray[49]
elif packet_bytearray[23] == 1:
protocol = 1
src_port = -1
dst_port = -1
tcp_window_size = 0
elif packet_bytearray[23] == 17:
protocol = 17
src_port = packet_bytearray[34] << 8 | packet_bytearray[35]
dst_port = packet_bytearray[36] << 8 | packet_bytearray[37]
tcp_window_size = 0
else:
protocol = -1
src_port = packet_bytearray[34] << 8 | packet_bytearray[35]
dst_port = packet_bytearray[36] << 8 | packet_bytearray[37]
tcp_window_size = 0
packet_info["protocol"] = str(protocol)
packet_info["src_port"] = str(src_port)
packet_info["dst_port"] = str(dst_port)
packet_info["tcp_window_size"] = tcp_window_size
def _gen_msg_str(self, packet_info):
mgmt_ip = self._get_mgmt_ip_address()
message = "{},0,{},{},{},{},{},{},{},{},{},{}".format(
str(int(round(time.time() * 1000000))), socket.gethostname(), mgmt_ip,
packet_info["ip_version"], packet_info["src_ip_addr"], packet_info["dst_ip_addr"],
packet_info["src_port"], packet_info["dst_port"], packet_info["protocol"], str(packet_info["tcp_window_size"]),
str(packet_info["total_length"])
)
self._logger.debug(message)
return message
def _get_mgmt_ip_address(self):
mgmt_nic = ni.gateways().get("default").get(ni.AF_INET)[1]
ni.ifaddresses(mgmt_nic)
mgmt_ip = ni.ifaddresses(mgmt_nic)[ni.AF_INET][0]['addr']
return mgmt_ip
def _write_file(self, filename, msg):
if not os.path.exists(self._option["log_dir"]):
self._logger.debug("Hello")
os.mkdir(self._option["log_dir"])
f = open(filename, "a")
f.write("%s\n" % msg)
f.close()
def _get_filename(self):
current_min = int(time.strftime("%M"))
box_name = socket.gethostname()
min_mul_five = current_min - current_min % 5
filename = "{}{}-{}-{}-{:02d}".format(self._option["log_dir"], box_name, self._option["net_type"],
time.strftime("%Y-%m-%d-%H"), min_mul_five)
self._logger.debug(filename)
return filename
def _get_influx_msg(self, pkt_all_info):
# Need to get
# Physical / Virtual
# Compute / Networking/ Storage
# measurement: Physical / Virtual + Compute / Networking / Storage
# tags: Box Name, NIC
# fields: ip_ver, srcipaddr, dstipaddr, srcport, dstport, protocol, tcpwindowsize, totalpktlength
msg = dict()
msg["measurement"] = self._type
msg["time"] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
tags = dict()
tags["box"] = socket.gethostname()
tags["nic"] = self._option["nic"]
tags["src_ip_addr"] = str(pkt_all_info.pop("src_ip_addr"))
tags["dst_ip_addr"] = str(pkt_all_info.pop("dst_ip_addr"))
tags["src_port"] = str(pkt_all_info.pop("src_port"))
tags["dst_port"] = str(pkt_all_info.pop("dst_port"))
msg["tags"] = tags
msg["fields"] = pkt_all_info
influx_msg = json.dumps([msg])
return influx_msg
def _send_msg(self, msg):
m = msg
if isinstance(msg, dict):
m = json.dumps(msg)
elif isinstance(msg, list):
m = json.dumps(msg)
zmq_msg = "{}/{}".format(self._level, m)
self._logger.debug(zmq_msg)
self._mq_sock.send_string(zmq_msg)
def to_hex(self, s):
# convert a bin string into a string of hex char
# helper function to print raw packet in hex
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0' + hv
lst.append(hv)
return reduce(lambda x, y: x + y, lst)
def _not_used_func(self):
# DEBUG - print raw packet in hex format
# packet_hex = toHex(packet_str)
# print ("%s" % packet_hex)
# IP HEADER
# https://tools.ietf.org/html/rfc791
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |Version| IHL |Type of Service| Total Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# IHL : Internet Header Length is the length of the internet header
# value to multiply * 4 byte
# e.g. IHL = 5 ; IP Header Length = 5 * 4 byte = 20 byte
#
# Total length: This 16-bit field defines the entire packet size,
# including header and data, in bytes.
# calculate ip header length
# ip_header_length = packet_bytearray[ETH_HLEN] # load Byte
# ip_header_length = ip_header_length & 0x0F # mask bits 0..3
# ip_header_length = ip_header_length << 2 # shift to obtain length
# TCP HEADER
# https://www.rfc-editor.org/rfc/rfc793.txt
# 12 13 14 15
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Data | |U|A|P|R|S|F| |
# | Offset| Reserved |R|C|S|S|Y|I| Window |
# | | |G|K|H|T|N|N| |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# Data Offset: This indicates where the data begins.
# The TCP header is an integral number of 32 bits long.
# value to multiply * 4 byte
# e.g. DataOffset = 5 ; TCP Header Length = 5 * 4 byte = 20 byte
# calculate tcp header length
# tcp_header_length = packet_bytearray[ETH_HLEN + ip_header_length + 12] # load Byte
# tcp_header_length = tcp_header_length & 0xF0 # mask bit 4..7
# tcp_header_length = tcp_header_length >> 2 # SHR 4 ; SHL 2 -> SHR 2
# calculate payload offset
# payload_offset = ETH_HLEN + ip_header_length + tcp_header_length
pass
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s] %(filename)s,%(funcName)s(#%(lineno)d): %(message)s",
level=logging.INFO)
point_conf = dict()
file_path = None
if len(sys.argv) == 2:
# Load configuration from a file passed by second argument in the command
file_path = sys.argv[1]
else:
file_path = "net_ip_point.yaml"
with open(file_path) as f:
cfg_str = f.read()
point_conf = yaml.load(cfg_str)
print (point_conf)
point = NetworkIpPacketPoint(point_conf)
point.collect()
<file_sep>/Visibility-Collection-Validation/Validators/kafka-influx-linker/src/Snap-Kafka-Linker/src/chainlinker/SnapParser.java
package chainlinker;
import java.util.HashMap;
import java.util.LinkedList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.simple.JSONArray;
/*
* Not confirmed about what happens when InfluxDB connection failed.
* No reference or documents are found. Need to be reinforced.
*/
public class SnapParser {
private static final Logger logger = LogManager.getLogger(SnapParser.class);
protected LinkedList<Backend> backends;
protected HashMap<String, SnapPluginParser> parserMap = new HashMap<>();
protected LinkedList<SnapPluginParser> parserList = new LinkedList<>();
protected ConfigLoader config;
public SnapParser() {
config = ConfigLoader.getInstance();
backends = config.getBackends();
// TODO: Must make this reflective.
HashMap<String, Class<? extends SnapPluginParser>> parserClassMap = SnapPluginManifest.getInstance().getPluginManifestMap();
try {
for (String collector : config.getSnapConfig().getCollectors()) {
Class<? extends SnapPluginParser> parserClass = parserClassMap.get(collector);
logger.debug("Loading SnapPluginParser module '" + parserClass.getName() + "' for plugin '" + collector + "'");
parserList.add(parserClass.newInstance());
}
} catch (InstantiationException e) {
logger.fatal("Failed to instantitate given class from SnapPluginManifest. Is SnapPluginManifest is properly written?", e);
} catch (IllegalAccessException e) {
logger.fatal("Failed to instantitate given class from SnapPluginManifest. Is SnapPluginManifest is properly written?", e);
}
for (SnapPluginParser parserIter : parserList) {
parserIter.loadParserMap(parserMap);
}
}
public void processMessage(JSONArray msgValue) {
for (Backend backend : backends) {
backend.processMessage(msgValue, parserMap, parserList);
}
}
}
<file_sep>/README.md
# SmartX Multi-View: Multi-layer Visibility
### What is SmartX Multi-View?
SmartX Multi-View is an Open-source implementation of SmartX Multi-View Visibility Framework (MVF) by leveraging various existing open-source monotiroing and data processing tools for Multisite SDN-Cloud Playgrounds. It can support Multiple layers of visibilities (i.e., resource, slice, flow and workload).
### Requirments
* Ubuntu Operating System 16.04.03 LTS (Xenial)
### Release Version ###
This is the second version of SmartX Multi-View software.
### Notice
This version of SmartX Multi-View Visibility software supports Overlay-based Underlay Resource-layer, Physical Resource-layer, Virtual Resource-layer and Flow-layer visibilities.
### Top-Level Features
* Visibility collection Using Intel Snap Telemetry Framework, sFlow, eBPF-based network packets collection, SDN network controllers (OpenDayLight and ONOS), and custom Java-based collectors.
* Visibility data transfer using Kafka and Zookeeper open-source Frameworks.
* Visibility storage and staging using MongoDB, Elasticsearch, Parquet, and InfluxDB DataStores.
* Visibility Integration using Spark Analytics Engine.
* Visibility Visualization using NodeJS, Express framework, Vis.js, D3.js, Bootstrap and others.
### Publications
* [SmartX multiview visibility framework leveraging open-source software for SDN-cloud playground](https://ieeexplore.ieee.org/document/8004242).
* [Physical-virtual topological visualization of OF@TEIN SDN-enabled multi-site cloud](https://ieeexplore.ieee.org/document/7899571).
* [OF@TEIN resource-level visibility for SDN-enabled distributed cloud testbed](https://ieeexplore.ieee.org/document/7275398).
* [Integrating Active Monitoring for Restricted Topology-awareness of SmartX Multi-View Playground Visibility](https://dl.acm.org/citation.cfm?doid=3226052.3226053).
### Collaboration
New Collaboratrs are welcomed to join our SmartX Multi-View Visibility effort to make it widely usable Open-source software in enterprises.
### Further Details
Please checkout out our [website](http://opennetworking.kr/projects/k-one-collaboration-project/wiki) for further information about K-ONE Project.
## Acknowledgement
This work is supported by Institute for Information & communications Technology Promotion(IITP) grant funded by the Korea government (MSIP)
(Global SDN/NFV OpenSource Software Module/Function Development).
<file_sep>/Visibility-Agent/visibility/vis_points/comp_libvirt_point.py
import libvirt
import logging
import sys
import yaml
import json
import zmq
import socket
import time
import signal
from datetime import datetime
class ComputeLibvirtPoint:
def __init__(self, point_config):
self._logger = logging.getLogger()
self._logger.setLevel(logging.INFO)
self._point = None
self._level = None
self._type = None
self._option = None
self._mq_context = None
self._mq_sock = None
self._libvirt_conn = None
self._load_config(point_config)
self._prepare_mq_conn(point_config["msg_queue"])
self._prepare_libvirt_conn()
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def _load_config(self, point_config):
self._point = point_config["point"]
self._level = point_config["level"]
self._type = point_config["type"]
self._option = point_config["option"]
def _prepare_mq_conn(self, mq_config):
self._mq_context = zmq.Context()
self._mq_sock = self._mq_context.socket(zmq.PUSH)
self._mq_sock.connect("tcp://{}:{}".format(mq_config["ipaddress"], mq_config["port"]))
self._logger.debug("MQ Socket is connected to {}:{}".format(mq_config["ipaddress"], mq_config["port"]))
def _prepare_libvirt_conn(self):
self._libvirt_conn = libvirt.open("qemu:///system")
if self._libvirt_conn is None:
self._logger.error("Failed to open connection to qemu:///system")
exit(1)
def collect(self):
while True:
vm_info = dict()
domidlist = self._libvirt_conn.listDomainsID()
for dom_id in domidlist:
self._collect_vm(dom_id, vm_info)
msg = self._get_influx_msg(vm_info)
self._send_msg(msg)
time.sleep(float(self._option["interval"]))
def _collect_vm(self, vm_id, vm_info):
dom = self._libvirt_conn.lookupByID(vm_id)
if not dom.isActive():
return None
vm_info["vbox"] = dom.name()
infos = dom.info()
vm_info["mem_total"] = infos[1]
vm_info["cpu_cores"] = infos[3]
cpu_status = dom.getCPUStats(True)[0]
for key in cpu_status:
vm_info["cpu_{}".format(key)] = cpu_status[key]
mem_status = dom.memoryStats()
for key in mem_status:
vm_info["mem_{}".format(key)] = mem_status[key]
def _get_influx_msg(self, vm_info):
# measurement: physical_compute (self._type)
# tags: Box Name
# fields:
msg = dict()
msg["measurement"] = self._type
msg["time"] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
tags = dict()
tags["box"] = socket.gethostname()
tags["vbox"] = str(vm_info.pop("vbox"))
msg["tags"] = tags
msg["fields"] = vm_info
influx_msg = json.dumps([msg])
return influx_msg
def _send_msg(self, msg):
m = msg
if isinstance(msg, dict):
m = json.dumps(msg)
elif isinstance(msg, list):
m = json.dumps(msg)
zmq_msg = "{}/{}".format(self._level, m)
self._logger.debug(zmq_msg)
self._mq_sock.send_string(zmq_msg)
def signal_handler(self, signal, frame):
self._libvirt_conn.close()
self._logger.info("Visibility Point {} was finished successfully".format(self.__class__.__name__))
sys.exit(0)
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s] %(filename)s,%(funcName)s(#%(lineno)d): %(message)s",
level=logging.INFO)
config_file = None
point_conf = dict()
if len(sys.argv) == 1:
config_file = "comp_libvirt_point.yaml"
elif len(sys.argv) == 2:
# Load configuration from a file passed by second argument in the command
config_file = sys.argv[1]
else:
exit(1)
with open(config_file) as f:
cfg_str = f.read()
point_conf = yaml.load(cfg_str)
logging.getLogger().debug(point_conf)
point = ComputeLibvirtPoint(point_conf)
point.collect()
<file_sep>/Visibility-Agent/visibility/vis_points/net_vxlan_point.py
#!/usr/bin/python
#
# Name : net_vxlan_point.py
# Description : A script for processing network packets at user-level
#
# Created by : <NAME>, <NAME>
# Version : 0.3
# Last Update : July, 2018
from __future__ import print_function
import os
import socket
import time
import logging
import signal
import sys
import netifaces as ni
from bcc import BPF
class NetworkVxlanPacketPoint:
def __init__(self, point_config):
self._logger = logging.getLogger(self.__class__.__name__)
self._bpf_file = "net_vxlan_point.c"
self._bpf_func = "vxlan_filter"
self._bpf_bytecode = None
self._socket_filter = None
self._socket = None
self._socket_fd = None
self._load_config(point_config)
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
def _load_config(self, point_config):
if point_config:
# Variables that have to be defined in point_config
self._target_net_if = point_config.get("target")
self._log_dir = point_config.get("log_dir")
self._net_type = point_config.get("network_type")
else:
self._target_net_if = "enx20180124c41b"
self._log_dir = "/opt/IOVisor-Data/"
self._net_type = "data"
def signal_handler(self, signal, frame):
self._logger.info("Visibility Point {} was finished successfully".format(self.__class__.__name__))
self._bpf_bytecode.cleanup()
self._socket.close()
sys.exit(0)
def collect(self):
self._init_bpf()
self._logger.debug("MachineIP Hostname ipver Src IP Addr Dst IP Addr src Port Dst Port "
" protocol TCP_Window_Size Packet_Length")
while True:
# For detailed information, please find "_not_used_func()" method.
packet_info = dict()
# retrieve raw packet from socket
packet_str = os.read(self._socket_fd, 2048)
# convert packet into bytearray
packet_bytearray = bytearray(packet_str)
self._get_packet_overall_info(packet_bytearray, packet_info)
self._get_packet_ip_info(packet_bytearray, packet_info)
self._get_packet_tcp_info(packet_bytearray, packet_info)
self._get_packet_vxlan_info(packet_bytearray, packet_info)
message = self._generate_message(packet_info)
self._write_message(message)
def _init_bpf(self):
# initialize BPF - load source code from http-parse-simple.c
self._bpf_bytecode = BPF(src_file=self._bpf_file, debug=0)
# load eBPF program http_filter of type SOCKET_FILTER into the kernel eBPF vm
# more info about eBPF program types http://man7.org/linux/man-pages/man2/bpf.2.html
function_ip_filter = self._bpf_bytecode.load_func(self._bpf_func, BPF.SOCKET_FILTER)
# create raw socket, bind it to eth0
# attach bpf program to socket created
BPF.attach_raw_socket(function_ip_filter, self._target_net_if)
# get file descriptor of the socket previously created inside BPF.attach_raw_socket
self._socket_fd = function_ip_filter.sock
# create python socket object, from the file descriptor
self._socket = socket.fromfd(self._socket_fd, socket.PF_PACKET, socket.SOCK_RAW, socket.IPPROTO_IP)
# set it as blocking socket
self._socket.setblocking(True)
def _get_packet_overall_info(self, packet_bytearray, packet_info):
# ethernet header length
ETH_HLEN = 14
# calculate packet total length
total_length = packet_bytearray[ETH_HLEN + 2] # load MSB
total_length = total_length << 8 # shift MSB
total_length = total_length + packet_bytearray[ETH_HLEN + 3] # add LSB
packet_info["total_length"] = str(total_length)
def _get_packet_ip_info(self, packet_bytearray, packet_info):
# parsing ip version from ip packet header
ipversion = str(bin(packet_bytearray[14])[2:5])
packet_info["ip_version"] = str(int(ipversion, 2))
# parsing source ip address, destination ip address from ip packet header
src_addr = str(packet_bytearray[26]) + "." + str(packet_bytearray[27]) + "." + \
str(packet_bytearray[28]) + "." + str(packet_bytearray[29])
dst_addr = str(packet_bytearray[30]) + "." + str(packet_bytearray[31]) + "." + \
str(packet_bytearray[32]) + "." + str(packet_bytearray[33])
packet_info["src_ip_addr"] = src_addr
packet_info["dst_ip_addr"] = dst_addr
def _get_packet_vxlan_info(self, packet_bytearray, packet_info):
vni = str((packet_bytearray[46]) + (packet_bytearray[47]) + (packet_bytearray[48]))
vlan_id = str((packet_bytearray[64]) + (packet_bytearray[65]))
if packet_bytearray[77] == 6:
protocoll4 = 6
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dst_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
tcp_window_size = packet_bytearray[102] << 8 | packet_bytearray[103]
elif packet_bytearray[77] == 1:
protocoll4 = 1
src_vm_port = -1
dst_vm_port = -1
tcp_window_size = 0
elif packet_bytearray[77] == 17:
protocoll4 = 17
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dst_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
tcp_window_size = 0
else:
protocoll4 = packet_bytearray[77]
src_vm_port = packet_bytearray[88] << 8 | packet_bytearray[88]
dst_vm_port = packet_bytearray[90] << 8 | packet_bytearray[91]
tcp_window_size = 0
src_vm_ip = str(packet_bytearray[80]) + "." + str(packet_bytearray[81]) + "." + str(
packet_bytearray[82]) + "." + str(packet_bytearray[83])
dst_vm_ip = str(packet_bytearray[84]) + "." + str(packet_bytearray[85]) + "." + str(
packet_bytearray[86]) + "." + str(packet_bytearray[87])
packet_bytearray["protocoll4"] = str(protocoll4)
packet_bytearray["src_vm_port"] = str(src_vm_port)
packet_bytearray["dst_vm_port"] = str(dst_vm_port)
packet_bytearray["tcp_window_size"] = str(tcp_window_size)
packet_bytearray["src_vm_ip"] = src_vm_ip
packet_bytearray["dst_vm_ip"] = dst_vm_ip
packet_bytearray["vni"] = str(int(vni))
packet_bytearray["vlan_id"] = str(int(vlan_id))
def _get_packet_tcp_info(self, packet_bytearray, packet_info):
# parsing source port and destination port
src_host_port = packet_bytearray[34] << 8 | packet_bytearray[35]
dst_host_port = packet_bytearray[36] << 8 | packet_bytearray[37]
packet_info["src_host_port"] = str(src_host_port)
packet_info["dst_host_port"] = str(dst_host_port)
def _generate_message(self, packet_info):
mgmt_ip = self._get_mgmt_ip_address()
message = "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}".format(
str(int(round(time.time() * 1000000))), socket.gethostname(), mgmt_ip,
packet_info["ip_version"], packet_info["src_ip_addr"], packet_info["dst_ip_addr"],
packet_info["src_host_port"], packet_info["dst_host_port"],
packet_info["src_vm_ip"], packet_info["dst_vm_ip"], packet_info["src_vm_port"], packet_info["dst_vm_port"],
packet_info["vni"], packet_info["vlan_id"], packet_info["protocoll4"], packet_info["tcp_window_size"],
packet_info["total_length"]
)
self._logger.debug(message)
return message
def _get_mgmt_ip_address(self):
mgmt_nic = ni.gateways().get("default").get(ni.AF_INET)[1]
ni.ifaddresses(mgmt_nic)
mgmt_ip = ni.ifaddresses(mgmt_nic)[ni.AF_INET][0]['addr']
return mgmt_ip
def _write_message(self, msg):
filename = self._get_filename()
if not os.path.exists(self._log_dir):
self._logger.debug("Hello")
os.mkdir(self._log_dir)
f = open(filename, "a")
f.write("%s\n" % msg)
f.close()
def _get_filename(self):
current_min = int(time.strftime("%M"))
box_name = socket.gethostname()
min_mul_five = current_min - current_min % 5
filename = "{}{}-{}-{}-{:02d}".format(self._log_dir, box_name, self._net_type,
time.strftime("%Y-%m-%d-%H"), min_mul_five)
self._logger.debug(filename)
return filename
def to_hex(self, s):
# convert a bin string into a string of hex char
# helper function to print raw packet in hex
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0' + hv
lst.append(hv)
return reduce(lambda x, y: x + y, lst)
def _not_used_func(self):
# DEBUG - print raw packet in hex format
# packet_hex = toHex(packet_str)
# print ("%s" % packet_hex)
# IP HEADER
# https://tools.ietf.org/html/rfc791
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# |Version| IHL |Type of Service| Total Length |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# IHL : Internet Header Length is the length of the internet header
# value to multiply * 4 byte
# e.g. IHL = 5 ; IP Header Length = 5 * 4 byte = 20 byte
#
# Total length: This 16-bit field defines the entire packet size,
# including header and data, in bytes.
# calculate ip header length
# ip_header_length = packet_bytearray[ETH_HLEN] # load Byte
# ip_header_length = ip_header_length & 0x0F # mask bits 0..3
# ip_header_length = ip_header_length << 2 # shift to obtain length
# TCP HEADER
# https://www.rfc-editor.org/rfc/rfc793.txt
# 12 13 14 15
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Data | |U|A|P|R|S|F| |
# | Offset| Reserved |R|C|S|S|Y|I| Window |
# | | |G|K|H|T|N|N| |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
#
# Data Offset: This indicates where the data begins.
# The TCP header is an integral number of 32 bits long.
# value to multiply * 4 byte
# e.g. DataOffset = 5 ; TCP Header Length = 5 * 4 byte = 20 byte
# calculate tcp header length
# tcp_header_length = packet_bytearray[ETH_HLEN + ip_header_length + 12] # load Byte
# tcp_header_length = tcp_header_length & 0xF0 # mask bit 4..7
# tcp_header_length = tcp_header_length >> 2 # SHR 4 ; SHL 2 -> SHR 2
# calculate payload offset
# payload_offset = ETH_HLEN + ip_header_length + tcp_header_length
pass
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s] %(filename)s,%(funcName)s(#%(lineno)d): %(message)s",
level=logging.DEBUG)
point = NetworkVxlanPacketPoint(None)
point.collect()
<file_sep>/Visibility-Collection-Validation/Collectors/sflow-rt/resources/inc/jquery.stripchart.js
// Copyright (c) 2014-2016 InMon Corp. ALL RIGHTS RESERVED
(function($) {
var suffixes = ["\uD835\uDF07","\uD835\uDC5A","","K","M","G","T","P","E"];
var colorNames = {
"aliceblue":"#f0f8ff","antiquewhite":"#faebd7","aqua":"#00ffff",
"aquamarine":"#7fffd4","azure":"#f0ffff","beige":"#f5f5dc",
"bisque":"#ffe4c4","black":"#000000","blanchedalmond":"#ffebcd",
"blue":"#0000ff","blueviolet":"#8a2be2","brown":"#a52a2a",
"burlywood":"#deb887","cadetblue":"#5f9ea0","chartreuse":"#7fff00",
"chocolate":"#d2691e","coral":"#ff7f50","cornflowerblue":"#6495ed",
"cornsilk":"#fff8dc","crimson":"#dc143c","cyan":"#00ffff",
"darkblue":"#00008b","darkcyan":"#008b8b","darkgoldenrod":"#b8860b",
"darkgray":"#a9a9a9","darkgreen":"#006400","darkkhaki":"#bdb76b",
"darkmagenta":"#8b008b","darkolivegreen":"#556b2f",
"darkorange":"#ff8c00","darkorchid":"#9932cc","darkred":"#8b0000",
"darksalmon":"#e9967a","darkseagreen":"#8fbc8f",
"darkslateblue":"#483d8b","darkslategray":"#2f4f4f",
"darkturquoise":"#00ced1","darkviolet":"#9400d3","deeppink":"#ff1493",
"deepskyblue":"#00bfff","dimgray":"#696969","dodgerblue":"#1e90ff",
"firebrick":"#b22222","floralwhite":"#fffaf0","forestgreen":"#228b22",
"fuchsia":"#ff00ff","gainsboro":"#dcdcdc","ghostwhite":"#f8f8ff",
"gold":"#ffd700","goldenrod":"#daa520","gray":"#808080",
"green":"#008000","greenyellow":"#adff2f", "honeydew":"#f0fff0",
"hotpink":"#ff69b4","indianred":"#cd5c5c","indigo":"#4b0082",
"ivory":"#fffff0","khaki":"#f0e68c","lavender":"#e6e6fa",
"lavenderblush":"#fff0f5","lawngreen":"#7cfc00","lemonchiffon":"#fffacd",
"lightblue":"#add8e6","lightcoral":"#f08080","lightcyan":"#e0ffff",
"lightgoldenrodyellow":"#fafad2","lightgrey":"#d3d3d3",
"lightgreen":"#90ee90","lightpink":"#ffb6c1","lightsalmon":"#ffa07a",
"lightseagreen":"#20b2aa","lightskyblue":"#87cefa",
"lightslategray":"#778899","lightsteelblue":"#b0c4de",
"lightyellow":"#ffffe0","lime":"#00ff00","limegreen":"#32cd32",
"linen":"#faf0e6","magenta":"#ff00ff","maroon":"#800000",
"mediumaquamarine":"#66cdaa","mediumblue":"#0000cd",
"mediumorchid":"#ba55d3","mediumpurple":"#9370d8",
"mediumseagreen":"#3cb371","mediumslateblue":"#7b68ee",
"mediumspringgreen":"#00fa9a","mediumturquoise":"#48d1cc",
"mediumvioletred":"#c71585","midnightblue":"#191970",
"mintcream":"#f5fffa","mistyrose":"#ffe4e1","moccasin":"#ffe4b5",
"navajowhite":"#ffdead","navy":"#000080","oldlace":"#fdf5e6",
"olive":"#808000","olivedrab":"#6b8e23","orange":"#ffa500",
"orangered":"#ff4500","orchid":"#da70d6","palegoldenrod":"#eee8aa",
"palegreen":"#98fb98","paleturquoise":"#afeeee",
"palevioletred":"#d87093","papayawhip":"#ffefd5","peachpuff":"#ffdab9",
"peru":"#cd853f","pink":"#ffc0cb","plum":"#dda0dd",
"powderblue":"#b0e0e6","purple":"#800080","red":"#ff0000",
"rosybrown":"#bc8f8f","royalblue":"#4169e1","saddlebrown":"#8b4513",
"salmon":"#fa8072","sandybrown":"#f4a460","seagreen":"#2e8b57",
"seashell":"#fff5ee","sienna":"#a0522d","silver":"#c0c0c0",
"skyblue":"#87ceeb","slateblue":"#6a5acd","slategray":"#708090",
"snow":"#fffafa","springgreen":"#00ff7f","steelblue":"#4682b4",
"tan":"#d2b48c","teal":"#008080","thistle":"#d8bfd8","tomato":"#ff6347",
"turquoise":"#40e0d0","violet":"#ee82ee","wheat":"#f5deb3",
"white":"#ffffff","whitesmoke":"#f5f5f5","yellow":"#ffff00",
"yellowgreen":"#9acd32"
};
function colorToHex(col) {
var vals,r,g,b;
if(col[0] === '#') return col;
vals = /rgb *\( *([0-9]{1,3}) *, *([0-9]{1,3}) *, *([0-9]{1,3}) *\)/.exec(col);
if(vals && vals.length == 4) {
r = Math.round(parseFloat(vals[1]));
g = Math.round(parseFloat(vals[2]));
b = Math.round(parseFloat(vals[3]));
return "#"
+ (r + 0x10000).toString(16).substring(3).toUpperCase()
+ (g + 0x10000).toString(16).substring(3).toUpperCase()
+ (b + 0x10000).toString(16).substring(3).toUpperCase();
}
col = col.toLowerCase();
if(colorNames.hasOwnProperty(col)) {
return colorNames[col];
}
return null;
}
function colorLuminance(col, lum) {
var hex,rgb,i,c;
hex = colorToHex(col);
if(!hex) return col;
hex = String(hex).replace(/[^0-9a-f]/gi, '');
if(hex.length < 6) hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
lum = lum || 0;
rgb = "#";
for (i = 0; i < 3; i++) {
c = parseInt(hex.substr(i*2,2), 16);
c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
rgb += ("00"+c).substr(c.length);
}
return rgb;
}
function darkenColor(hex) {
return colorLuminance(hex,-0.2);
}
function maxValue(values,sumFlag,mirrorFlag) {
var maxUp = 0;
var maxSumUp = 0;
var maxDown = 0;
var maxSumDown = 0;
var i, sumup, sumdown, maxup, maxdown, s, val, even;
for(i = 0; i < values[0].length; i++) {
sumup = 0;
maxup = 0;
sumdown = 0;
maxdown = 0;
for(s = 0; s < values.length; s++) {
val = values[s][i];
if(mirrorFlag) {
if(s%2) {
sumdown += val;
if(val > maxdown) maxdown = val;
} else {
sumup += val;
if(val > maxup) maxup = val;
}
} else {
sumup += val;
if(val > maxup) maxup = val;
}
}
if(maxup > maxUp) maxUp = maxup;
if(sumup > maxSumUp) maxSumUp = sumup;
if(mirrorFlag) {
if(maxdown > maxDown) maxDown = maxdown;
if(sumdown > maxSumDown) maxSumDown = sumdown;
}
}
var maxUp = sumFlag ? maxSumUp : maxUp;
var maxDown = sumFlag ? maxSumDown : maxDown;
return {up: maxUp, down:maxDown};
}
function drawLine(ctx, startx, starty, endx, endy, style) {
ctx.beginPath();
ctx.moveTo(startx, starty);
ctx.lineTo(endx, endy);
ctx.strokeStyle = style;
ctx.lineWidth = 1;
ctx.stroke();
}
function valueTickSpacing(maxVal,base2) {
var stepsizes = [1,2,5,10,20,50,100,200,500];
var i, steps, stepsize, tsteps, j;
var divisor = base2 ? 1/(1024*1024) : 0.000001;
var factor = base2 ? 1024 : 1000;
var range = maxVal.up + maxVal.down;
for(i = 0; i < suffixes.length; i++) {
if((range / divisor) < factor) break;
divisor *= factor;
}
steps = Math.floor(range/divisor);
if(steps < 5 && i > 0) {
divisor /= factor;
i--;
steps = Math.floor(range / divisor);
}
stepsize = 1;
tsteps;
for(var j = 0; j < stepsizes.length; j++) {
stepsize = stepsizes[j];
tsteps = steps / stepsize;
if(Math.floor(tsteps) < 8) break;
}
return stepsize * divisor;
}
function valueStr(value,includeMillis,base2) {
if (value === 0) return value;
var i = 2;
var divisor = 1;
var factor = base2 ? 1024 : 1000;
var absVal, scaled;
if (includeMillis) {
i = 0;
divisor = base2 ? 1/(1024*1024) : 0.000001;
}
absVal = Math.abs(value);
while (i < suffixes.length) {
if ((absVal / divisor) < factor) break;
divisor *= factor;
i++;
}
scaled = Math.round(absVal * factor / divisor) / factor;
return scaled + suffixes[i];
}
function drawValueAxis(ctx,h,w,maxVal,option,valueAxisLabel) {
var stepsize = valueTickSpacing(maxVal,option.base2);
var rOffset = 5;
var yZero,vscale,vstep,meas,maxLabel,yval,s,i,lval,label,font,fontArgs,bottom;
var range = maxVal.up + maxVal.down;
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
ctx.fillStyle = "#000";
vscale = (h - option.bottomInset - option.topInset) / range;
yZero = vscale * maxVal.up + option.topInset;
ctx.fillText("0",option.leftInset - rOffset, yZero);
drawLine(ctx,option.leftInset, yZero, w - option.rightInset, yZero, "#ccc");
vstep = vscale * stepsize;
meas = ctx.measureText("0");
maxLabel = meas.width;
// up axis
yval = yZero - vstep;
s = 1;
while(yval > option.topInset) {
lval = s * stepsize;
label = valueStr(lval,option.includeMillis,option.base2);
meas = ctx.measureText(label);
maxLabel = Math.max(maxLabel,meas.width);
ctx.fillText(label, option.leftInset - rOffset, yval);
drawLine(ctx, option.leftInset, yval, w - option.rightInset, yval, "#ccc");
s++;
yval -= vstep;
}
// down axis
yval = yZero + vstep;
s = 1;
bottom = h - option.bottomInset;
while(yval < bottom) {
lval = s * stepsize;
label = valueStr(lval,option.includeMillis,option.base2);
meas = ctx.measureText(label);
maxLabel = Math.max(maxLabel,meas.width);
ctx.fillText(label,option.leftInset - rOffset, yval);
drawLine(ctx, option.leftInset, yval, w - option.rightInset, yval, "#ccc");
s++;
yval += vstep;
}
drawLine(ctx, option.leftInset, option.topInset, option.leftInset, h - option.bottomInset, "#000");
// add units
if(valueAxisLabel) {
font = ctx.font;
fontArgs = font.split(' ');
ctx.font = '12px ' + fontArgs[fontArgs.length - 1];
ctx.rotate(-Math.PI/2);
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillText(valueAxisLabel, -option.topInset - ((h - option.topInset - option.bottomInset) / 2), Math.max(10,option.leftInset - maxLabel - rOffset - 5));
ctx.rotate(Math.PI/2);
ctx.font = font;
}
return {yZero:yZero, vScale: vscale};
}
function timeStr(ms,includeSeconds) {
var date = new Date(ms);
var sec = date.getSeconds().toString();
if(sec.length === 1) sec = "0"+sec;
var min = date.getMinutes().toString();
if(min.length === 1) min = "0"+min;
var hrs = date.getHours().toString();
if(hrs.length === 1) hrs = "0"+hrs;
return includeSeconds ? hrs+":"+min+":"+sec : hrs + ":" + min;
}
function drawTimeAxis(ctx,h,w,maxVal,option,times,step,selectedIdx) {
var stepsizes = [60000,120000,300000,600000,900000,1200000,1800000,3600000,7200000,10800000,14400000,21600000,43200000,86400000];
var yBase = h - option.bottomInset;
var tmin = times[0];
var tmax = times[times.length - 1];
if(step) tmax += (tmax - tmin) / Math.max(times.length - 1,1);
var tdelta = tmax - tmin;
var tOffset = 5;
var height = h - yBase - tOffset - 2;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var tMiddle = yBase + tOffset + height / 2;
var i,stepsize,includeSeconds,d,tick,tscale,xPos,markerPos,label,meas,radius,width,x,y;
for(i = 0; i < stepsizes.length; i++) {
stepsize = stepsizes[i];
if(tdelta / stepsize < 10) break;
}
includeSeconds = stepsize < 300000;
d = new Date(tmin);
d.setMilliseconds(0);
d.setSeconds(0);
if(stepsize >= 60000) d.setMinutes(0);
if(stepsize >= 3600000) d.setHours(0);
tick = d.getTime();
tscale = (w - option.leftInset - option.rightInset) / tdelta;
while(tick < tmax) {
if(tick >= tmin) {
xPos = option.leftInset + (tscale * (tick - tmin));
ctx.fillStyle = "#000";
drawLine(ctx, xPos, yBase, xPos, yBase + 4, "#000");
drawLine(ctx, xPos, yBase, xPos, option.topInset, "#ccc");
ctx.fillText(timeStr(tick,includeSeconds), xPos, tMiddle);
}
tick += stepsize;
}
drawLine(ctx,option.leftInset,yBase,w - option.rightInset,yBase,"#000");
if(times && times[selectedIdx]) {
markerPos = option.leftInset + (tscale * (times[selectedIdx] - tmin));
ctx.fillStyle = "#000";
drawLine(ctx, markerPos, yBase, markerPos, yBase + 4, "#000");
drawLine(ctx, markerPos, yBase, markerPos, option.topInset, "#ccc");
label = timeStr(times[selectedIdx],includeSeconds);
meas = ctx.measureText(label);
ctx.strokeStyle = "#000";
ctx.fillStyle = "#fff";
radius = 2;
width = meas.width + 4;
x = markerPos - width / 2;
y = yBase + tOffset;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.fillStyle = "#000";
ctx.fillText(label,markerPos,tMiddle);
}
return { tScale: tscale, tMin: tmin, tMax: tmax };
}
function drawStackedSeries(ctx,h,w,maxVal,yZero,vscale,tmin,tmax,tscale,option,values,times,step,mirror,colors) {
var s,series,yPos,xPos,i,val,c,col;
for(s = values.length; --s >= 0;) {
series = values[s];
if(mirror) {
col = colors[Math.floor(s / 2) % colors.length];
if(s % 2) ctx.fillStyle=darkenColor(col);
else ctx.fillStyle=col;
} else {
ctx.fillStyle=colors[s % colors.length];
}
ctx.beginPath();
for(i = 0; i < series.length; i++) {
val = series[i];
if(mirror) {
if(s > 1) {
c = s - 2;
while(c >= 0) {
val += values[c][i];
c -= 2;
}
}
} else {
if(s > 0) {
for(c = 0; c < s; c++) val += values[c][i];
}
}
val *= vscale;
yPos = mirror ? (s % 2 ? yZero + val : yZero - val) : yZero - val;
xPos = option.leftInset + (tscale * (times[i] - tmin));
if(i === 0) {
ctx.moveTo(xPos,yZero);
ctx.lineTo(xPos,yPos);
}
else ctx.lineTo(xPos,yPos);
if(step) {
xPos = option.leftInset + (tscale * ((times[i+1] || tmax) - tmin));
ctx.lineTo(xPos,yPos);
}
}
ctx.lineTo(xPos,yZero);
ctx.closePath();
ctx.fill();
}
if(mirror && maxVal.down) drawLine(ctx,option.leftInset,yZero,w - option.rightInset,yZero,"#000");
}
function drawSeries(ctx,h,w,maxVal,yZero,vscale,tmin,tmax,tscale,option,values,times,step,mirror,colors) {
var s, i, val, series, xPos, yPos, upFlag, col;
for(s = values.length; --s >= 0;) {
series = values[s];
if(mirror) {
col = colors[Math.floor(s / 2) % colors.length];
if(s % 2) ctx.strokeStyle=darkenColor(col);
else ctx.strokeStyle=col;
} else {
ctx.strokeStyle=colors[s % colors.length];
}
ctx.lineWidth=2;
ctx.beginPath();
for(i = 0; i < series.length; i++) {
val = series[i] * vscale;
yPos = mirror ? (s % 2 ? yZero + val : yZero - val) : yZero - val;
xPos = option.leftInset + (tscale * (times[i] - tmin));
if(i === 0) ctx.moveTo(xPos,yPos);
else ctx.lineTo(xPos,yPos);
if(step) {
xPos = option.leftInset + (tscale * ((times[i+1] || tmax) - tmin));
ctx.lineTo(xPos,yPos);
}
}
ctx.stroke();
}
if(mirror && maxVal.down) drawLine(ctx,option.leftInset,yZero,w - option.rightInset,yZero,"#000");
}
function drawHrule(ctx,h,w,maxVal,yZero,vscale,option,hrule) {
var i,hval,yval;
for(i = 0; i < hrule.length; i++) {
hval = hrule[i].value;
if(hval < maxVal.up) {
yval = yZero - (hval * vscale);
drawLine(ctx, option.leftInset, yval, w - option.rightInset, yval, hrule[i].color);
}
if(hval < maxVal.down) {
yval = yZero + (hval * vscale);
drawLine(ctx, option.leftInset, yval, w - option.rightInset, yval, hrule[i].color);
}
}
}
function addLegend(chart,h,w,option,legendInfo,values,mirror,colors) {
var legend,i,r,c,row,col,links;
legend = '<table>';
if(legendInfo.headings) {
legend += '<thead><tr><th></th>';
for(i = 0; i < legendInfo.headings.length; i++) legend += '<th>'+legendInfo.headings[i] + '</th>';
legend += '</tr></thead>';
}
function createLink(idx,val) {
if(!legendInfo.links) return val;
var link = legendInfo.links instanceof Array ? legendInfo.links[idx] : legendInfo.links;
if(!link) return val;
link = link.replace(/\{(.*?)\}/g, function(match,tok) {return val});
return '<a href="' + link + '">' + val + '</a>';
}
if(legendInfo.labels) {
legend += '<tbody>';
for(r = 0; r < legendInfo.labels.length; r++) {
legend += '<tr>';
if(mirror && legendInfo.labels.length === values.length) {
col = colors[Math.floor(r / 2)];
if(r % 2) col = darkenColor(col);
} else col = colors[r % colors.length];
legend += '<td><div class="swatch" style="background:' + col + '"></div></td>';
if(legendInfo.labels[r] instanceof Array) {
row = legendInfo.labels[r];
for(c = 0; c < row.length; c++) legend += '<td>' + createLink(c,row[c]) + '</td>';
}
else legend += '<td>' + createLink(r,legendInfo.labels[r]) + '</td>';
legend += '</tr>';
}
legend += '</tbody>';
}
legend += '</table>';
if(chart._legend) chart._legend.remove();
var pos = chart._canvas.position();
chart._legend = $(legend).css('position','absolute').css('top',pos.top).css('left',pos.left+option.leftInset).appendTo(chart.element);
}
$.widget('inmon.stripchart', {
options: {
bottomInset: 20,
leftInset: 50,
topInset: 5,
rightInset: 22,
clickable: false,
includeMillis: false,
base2:false,
step:false,
stack: false,
mirror: false,
colors: [
'#3366cc','#dc3912','#ff9900','#109618','#990099','#0099c6',
'#dd4477','#66aa00','#b82e2e','#316395','#994499','#22aa99',
'#aaaa11','#6633cc','#e67300','#8b0707','#651067','#329262',
'#5574a6','#3b3eac','#b77322','#16d620','#b91383','#f4359e',
'#9c5935','#a9c413','#2a778d','#668d1c','#bea413','#0c5922',
'#743411'
]
},
_create: function() {
var option;
this.element.addClass('stripchart');
this._canvas = $('<canvas/>').appendTo(this.element);
option = this.options;
if(this.options.clickable) {
this._canvas.addClass("clickable").click(function(e) {
var $canvas,off;
$canvas = $(this);
off = $canvas.offset();
var x = (e.pageX - off.left - option.leftInset) / ($canvas.width() - option.leftInset - option.rightInset);
var y = 1 - (e.pageY - off.top - option.topInset) / ($canvas.height() - option.topInset - option.bottomInset);
$canvas.trigger('stripchartclick',{x:x,y:y});
});
}
},
_destroy: function() {
if(this.options.clickable) this._canvas.removeClass('clickable').unbind('click');
this.element.removeClass('stripchart');
this.element.empty();
delete this._canvas;
delete this._legend;
},
draw: function(cdata) {
var canvas,ctx,h,w,ratio,colors,step,stack,mirror,maxVal,i,hval;
canvas = this._canvas[0];
if(!canvas || !canvas.getContext) return;
ctx = canvas.getContext('2d');
h = this._canvas.height();
w = this._canvas.width();
ratio = window.devicePixelRatio;
if(ratio && ratio > 1) {
canvas.height = h * ratio;
canvas.width = w * ratio;
ctx.scale(ratio,ratio);
}
else {
canvas.height = h;
canvas.width = w;
}
ctx.font = '10px sans-serif';
colors = cdata.colors || this.options.colors;
step = this.options.step;
stack = this.options.stack;
mirror = this.options.mirror;
maxVal = maxValue(cdata.values,stack,mirror);
if(cdata.hrule) {
for(i = 0; i < cdata.hrule.length; i++) {
if(cdata.hrule[i].scale) {
hval = cdata.hrule[i].value;
if(maxVal.up < hval) maxVal.up = hval;
if(mirror && maxVal.down < hval) maxVal.down = hval;
}
}
}
if(maxVal.up === 0 && maxVal.down === 0) maxVal.up = 1;
maxVal.up *= 1.0 + (cdata.ymargin || 0.2);
maxVal.down *= 1.0 + (cdata.ymargin || 0.2);
var tMetrics = drawTimeAxis(ctx,h,w,maxVal,this.options,cdata.times,step,cdata.selectedIdx);
var vMetrics = drawValueAxis(ctx,h,w,maxVal,this.options,cdata.units);
ctx.save();
ctx.rect(this.options.leftInset,this.options.topInset,w-this.options.rightInset-this.options.leftInset,h-this.options.bottomInset-this.options.topInset);
ctx.clip();
if(stack) drawStackedSeries(ctx,h,w,maxVal,vMetrics.yZero,vMetrics.vScale,tMetrics.tMin,tMetrics.tMax,tMetrics.tScale,this.options,cdata.values,cdata.times,step,mirror,colors);
else drawSeries(ctx,h,w,maxVal,vMetrics.yZero,vMetrics.vScale,tMetrics.tMin,tMetrics.tMax,tMetrics.tScale,this.options,cdata.values,cdata.times,step,mirror,colors);
if(cdata.hrule) drawHrule(ctx,h,w,maxVal,vMetrics.yZero,vMetrics.vScale,this.options,cdata.hrule);
ctx.restore();
if(cdata.legend) addLegend(this,h,w,this.options,cdata.legend,cdata.values,mirror,colors);
}
});
})(jQuery);
<file_sep>/Visibility-Storage-Staging/data-apis/lib/models/vminstanceModel.ts
// /lib/models/crmModel.ts
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
export const VMInstanceStatusSchema = new Schema({}, {collection: 'vm-instance-list'});
<file_sep>/MultiView-Dependencies/Install_Oracle_Java.sh
#!/bin/bash
#
# Copyright 2015 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_Oracle_Java.sh
# Description : Script for Installing Java
#
# Created by : <EMAIL>
# Version : 0.1
# Last Update : October, 2016
javaExist=`dpkg -l | grep oracle-java`
if [ "$javaExist" == "" ]; then
echo -n "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Installing .................... "
sudo add-apt-repository -y ppa:webupd8team/java &> /dev/null
sudo apt-get -y update &> /dev/null
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer &> /dev/null
sudo apt-get -y install oracle-java8-set-default &> /dev/null
echo -e "Done.\n"
java -version
else
echo -e "\n[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Already Installed."
echo `java -version`
fi
<file_sep>/MultiView-Scripts/Install_Dependencies_vBox.sh
#!/bin/bash
#
# Copyright 2016 SmartX Collaboration (GIST NetCS). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#
# Name : Install_Dependencies_vBox.sh
# Description : Script for Installing Dependencies on SmartX Box
#
# Created by : <EMAIL>
# Version : 0.2
# Last Update : September, 2018
MGMT_IP=$1
wget_check ()
{
if command -v wget > /dev/null; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] wget Already Installed.\n"
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] wget Installing .................... "
apt-get -y install wget &> /dev/null
echo -e "Done.\n"
fi
}
nmap_check ()
{
if command -v nmap > /dev/null; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] nmap Already Installed.\n"
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] nmap Installing .................... "
apt-get -y install nmap &> /dev/null
echo -e "Done.\n"
fi
}
java_check ()
{
if command -v java > /dev/null; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Already Installed.\n"
echo -e `java -version`
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] JAVA Installing .................... "
sudo add-apt-repository -y ppa:webupd8team/java &> /dev/null
sudo apt-get -y update &> /dev/null
echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
sudo apt-get -y install oracle-java8-installer &> /dev/null
sudo apt-get -y install oracle-java8-set-default &> /dev/null
echo -e "Done.\n"
java -version
fi
}
sshpass_check ()
{
if command -v sshpass > /dev/null; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] SSH Pass Already Installed.\n"
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] SSH Pass Installing .................... "
apt-get -y install sshpass &> /dev/null
echo -e "Done.\n"
fi
}
iostat_check ()
{
if command -v iostat > /dev/null; then
echo -e "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] iostat Already Installed."
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] iostat Installing .................... "
apt-get install -y sysstat &> /dev/null
echo -e "Done.\n"
fi
}
snap_check ()
{
if command -v snaptel > /dev/null; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Intel Snap Already Installed.\n"
else
echo -n "[$(date '+%Y-%m-%d %H:%M:%S')][INFO][INSTALL] Intel Snap Installing .................... "
curl -s https://packagecloud.io/install/repositories/intelsdi-x/snap/script.deb.sh | sudo bash &> /dev/null
sudo apt-get install -y snap-telemetry &> /dev/null
service snap-telemetry start &> /dev/null
echo -e "Done.\n"
fi
}
wget_check
nmap_check
java_check
snap_check
iostat_check
<file_sep>/Visibility-Agent/visibility/vis_points/static_info_point.py
import json
import platform
import logging
import psutil
import distro
import cpuinfo
import netifaces
class StaticInformationPoint:
def __init__(self):
self._box_info = dict()
self._collected_info = dict()
self._logger = logging.getLogger()
self._logger.setLevel(logging.DEBUG)
def collect(self):
self._box_info.clear()
self._box_info["node"] = platform.node()
self._box_info["os"] = self._collect_os_default()
self._box_info["cpu"] = self._collect_cpu_default()
self._box_info["memory"] = self._collect_memory_default()
self._box_info["disk"] = self._collect_disk_default()
self._box_info["network"] = self._collect_network_default()
return self._box_info
def _collect_os_default(self):
os_info = dict()
os_info["system"] = platform.system()
os_info["release"] = platform.release()
os_info["like"] = distro.like()
os_info["build_number"] = distro.build_number()
os_info["version"] = distro.version()
os_info["name"] = distro.name()
os_info["codename"] = distro.codename()
self._logger.debug(json.dumps(os_info))
return os_info
def _collect_cpu_default(self):
cpu_info = dict()
cpu_info["physical_count"] = psutil.cpu_count(logical=False)
cpu_info["logical_count"] = psutil.cpu_count(logical=True)
data_from_cpuinfo = cpuinfo.get_cpu_info()
cpu_info["model"] = data_from_cpuinfo["brand"]
cpu_info["vendor"] = data_from_cpuinfo["vendor_id"]
cpu_info["advertised_hertz"] = data_from_cpuinfo["hz_advertised"]
cpu_info["actual_hertz"] = data_from_cpuinfo["hz_actual"]
cpu_info["instruction_bits"] = data_from_cpuinfo["bits"]
cpu_info["architecture"] = data_from_cpuinfo["arch"]
cpu_info["flags"] = data_from_cpuinfo["flags"]
cache_dict = dict()
cache_dict["l1_instruction_cache_size"] = data_from_cpuinfo["l1_instruction_cache_size"]
cache_dict["l1_data_cache_size"] = data_from_cpuinfo["l1_data_cache_size"]
cache_dict["l2_cache_line_size"] = data_from_cpuinfo["l2_cache_line_size"]
cache_dict["l2_cache_size"] = data_from_cpuinfo["l2_cache_size"]
cache_dict["l3_cache_size"] = data_from_cpuinfo["l3_cache_size"]
cpu_info["cache"] = cache_dict
self._logger.debug(json.dumps(cpu_info))
return cpu_info
def _collect_memory_default(self):
mem_info = dict()
mem_info["memory_size_byte"] = str(psutil.virtual_memory().__getattribute__("total"))
mem_info["swap_size_byte"] = str(psutil.swap_memory().__getattribute__("total"))
self._logger.debug(json.dumps(mem_info))
return mem_info
def _collect_disk_default(self):
partition_info = list()
for existing_partition in psutil.disk_partitions():
partition_dict = dict()
partition_dict["device"] = existing_partition.__getattribute__("device")
mounted_path = existing_partition.__getattribute__("mountpoint")
partition_dict["mount_point"] = mounted_path
partition_dict["disk_size_byte"] = str(psutil.disk_usage(mounted_path).__getattribute__("total"))
partition_dict["filesystem"] = existing_partition.__getattribute__("fstype")
partition_info.append(partition_dict)
self._logger.debug("_collect_disk_default(): {}".format(json.dumps(partition_info)))
return partition_info
def _collect_network_default(self):
net_info = dict()
if_list = list()
data_from_if_addrs = psutil.net_if_addrs()
data_from_if_stats = psutil.net_if_stats()
for if_name in data_from_if_addrs.keys():
if_info_dict = dict()
if_stat = data_from_if_stats[if_name]
if_info_dict["name"] = if_name
if_info_dict["link_state"] = if_stat.__getattribute__("isup")
if_info_dict["duplex_mode"] = if_stat.__getattribute__("duplex")
if_info_dict["link_speed_gbps"] = if_stat.__getattribute__("speed")
if_info_dict["mtu_size_byte"] = if_stat.__getattribute__("mtu")
if_info_dict["address"] = self._get_addrs(if_name)
if_list.append(if_info_dict)
net_info["interface"] = if_list
net_info["gateway"] = self._get_organized_gateways()
self._logger.debug(json.dumps(net_info))
return net_info
def _get_addrs(self, if_name):
new_addrs_dict = dict()
addrs_dict_from_box = netifaces.ifaddresses(if_name)
for proto_num in addrs_dict_from_box.keys():
new_addrs_dict[self._get_proto_str_from(proto_num)] = addrs_dict_from_box[proto_num]
return new_addrs_dict
def _get_organized_gateways(self):
new_gateways_list = list()
gws_from_box = netifaces.gateways()
for gw_type in gws_from_box.keys():
if gw_type == 'default':
continue
new_gateway_dict = dict()
gws_for_proto = gws_from_box[gw_type]
for gw in gws_for_proto:
new_gateway_dict["protocol"] = self._get_proto_str_from(gw_type)
new_gateway_dict["gateway_address"] = gw[0]
new_gateway_dict["gateway_interface"] = gw[1]
new_gateway_dict["is_default"] = gw[2]
new_gateways_list.append(new_gateway_dict)
return new_gateways_list
def _get_proto_str_from(self, proto_num):
if proto_num == netifaces.AF_INET: # IPv4
proto_str = "IPv4"
elif proto_num == netifaces.AF_INET6: # IPv6
proto_str = "IPv6"
elif proto_num == netifaces.AF_LINK: # MAC
proto_str = "MAC"
else:
proto_str = "Unknown ({})".format(proto_num)
return proto_str
if __name__ == "__main__":
logging.basicConfig(format="[%(asctime)s / %(levelname)s] %(filename)s,%(funcName)s(#%(lineno)d): %(message)s",
level=logging.INFO)
collector = StaticInformationPoint()
collected_info = collector.collect()
print (json.dumps(collected_info))
| e9d32f0236a033959a514ed984829af75ce3eace | [
"JavaScript",
"Markdown",
"Maven POM",
"Java",
"Python",
"C",
"TypeScript",
"Shell"
] | 58 | Java | K-OpenNet/OpenStack-MultiView | bbc43e0cccf2b02ce808c139dee8335a6e60278d | 3e689c36d9c6c9e4d48dd10c6ae49bd68e96628a |
refs/heads/master | <file_sep>var http = require('http');
var fs = require('fs');
var data = fs.readFileSync("./status.json", "utf8");
var data1 = JSON.parse(data);
var server = http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
})
//server.setTimeout(10000, function(socket) {
// console.log('destroyed') ;
// socket.destroy()
//}) ;
server.listen(8080);
function buildHtml(req) {
var header = '';
var body = '';
var data = fs.readFileSync("./status.json", "utf8");
var data1 = JSON.parse(data);
var hostfile = fs.readFileSync("./hosts.json", "utf8");
var hostfile1 = JSON.parse(hostfile);
var now = new Date();
var date = now.getFullYear() + "/" + (now.getMonth() + 1) + "/" + now.getDate() ;
var time = ("0" + now.getHours()).slice(-2) + ":" + ("0" + now.getMinutes()).slice(-2) + ":" + ("0" + now.getSeconds()).slice(-2) ;
body = date + " " + time;
body = body +
"<br>version: 4.2" +
"<font size='2'>" +
"<h2>Legend</h2>" +
// "<tr>" +
// "<th>A</th>" +
// "<th>B</th>" +
// "</tr>" +
"<table border='1'>" +
"<tr>" +
"<td bgcolor='red'>NOK</td>" +
"<td bgcolor='green'>OK</td>" +
"<td bgcolor='yellow'>Unknown</td>" +
"</tr>" +
"</table>" +
// "<b>Status:</b><br>" +
// "OK: ok<br>" +
// "NOK: not ok<br>" +
// "UNK: unknown<br>" +
// "false: status not updated<br>" +
"<p>" +
"<b>UA:</b> if pingable via US = OK, else NOK<br>" +
"<b>UC</b> if connected via US ssh = OK, else NOK<br>" +
"<b>CA:</b> if pingable via Canada = OK, else NOK<br>" +
"<b>CC:</b> if connected via Canada ssh = OK, else NOK (will attemp only if US connection fails<br>" +
"</p>" +
"<p>If ssh is required, it will try US connection first by default. If that fails, then it will try the Canadian IP. Therefore, it is normal to see UC green and no color for CC.</p>" +
"See <a href='http://mtl-cosma01q.cn.ca:3000/'>COSMA</a> for other alerts." +
"<table border='1' >" +
// "<col width='100'>" +
// "<col width='120'>" +
// "<col width='100'>" +
// "<col width='75'>" +
"<tr>" +
"<th>Car</th>" +
"<th>CN ID</th>" +
"<th>Ensco Name</th>" +
"<th>Ensco Unit</th>" +
"<th>US IP</th>" +
"<th>Can IP</th>" +
"<th>Wi-fi</th>" +
"</tr>";
var hostList = Object.keys(hostfile1) ;
for (var host2 in hostfile1) {
if (host2 != "default") {
body = body + "<tr><td>" + host2 + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["CN-id"] + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["ensco-name"] + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["ensco-unit"] + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["host-us"] + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["host-can"] + "</td>" ;
body = body + "<td>" + hostfile1[host2]["config"]["wifi"] + "</td>" ;
body = body + "</tr>" ;
}
}
// header = "<meta http-equiv='refresh' content='60'><link rel='stylesheet' type='text/css' href='css/style.css' />" ;
header = "<meta http-equiv='refresh' content='60'>" ;
header = header +
"<style>" +
"table {" +
" border: 1px solid;" +
" margin: 12px;" +
" padding: 3px;" +
"}" +
"caption {" +
" font-weight: bold;" +
" text-align: center;" +
" border-style: solid;" +
" border-width: 1px;" +
" border-color: #666666;" +
"}" +
"</style>";
header = header + "<h1>ATIC Status Monitor</h1><br>";
body = body +
"</table>" +
"<h2>ATIC Cars</h2>" +
"<div>" ;
// body = "<table border='1'>" +
// "<col width='100'>" +
// "<col width='200'>" +
// "<col width='100'>" +
// "<col width='100'>" +
// "<tr><th>Car</th><th>Node</th><th>Alive</th><th>Connected</th></tr>";
var keys = Object.keys(data1) ;
endOfTable = false;
for (var host in data1) {
var item = data1[host] ;
if (item["config"]["active"] != "true") {
continue
}
if (endOfTable) {
body = body + "</table>" ;
endOfTable = false;
}
body = body +
// "<h3>" + host + "</h3>" +
"<table style='float: left' border='1'>" +
"<caption>" + host + "</caption>" +
// "<col width='100'>" +
// "<col width='200'>" +
// "<col width='100'>" +
// "<col width='100'>" +
"<tr>" +
// "<h3>" + host + "</h3>" +
// "<th>Car</th>" +
"<th>Node</th>" +
"<th>UA</th>" +
"<th>UC</th>" +
"<th>CA</th>" +
"<th>CC</th>" +
"</tr>";
for (var node in item["nodes"]) {
endOfTable = true;
var value = item["nodes"][node];
body = body + "<tr>" +
// "<td>" + host + "</td>" +
"<td>" + node + "</td>" ;
if (typeof value["u_alive"] != "undefined") {
if ((value['u_alive'] == "offline") || (value['u_alive'] == "NOK")) {
body = body + "<td bgcolor='red'></td>" ;
} else if ((value['u_alive'] == "online") || (value['u_alive'] == "OK")) {
body = body + "<td bgcolor='green'></td>" ;
}
else {
body = body + "<td></td>" ;
}
}
if (typeof value["alive"] != "undefined") {
if ((value['alive'] == "offline") || (value['alive'] == "NOK")) {
body = body + "<td bgcolor='red'></td>" ;
} else if ((value['alive'] == "online") || (value['alive'] == "OK")) {
body = body + "<td bgcolor='green'></td>" ;
}
else if (value['alive'] == "UNK") {
body = body + "<td bgcolor='yellow'></td>" ;
}
else {
body = body + "<td></td>" ;
}
}
if (typeof value["u_connected"] != "undefined") {
if ((value["u_connected"] == "notConnected") || (value['u_connected'] == "NOK")) {
body = body + "<td bgcolor='red'></td>" ;
} else if ((value["u_connected"] == "connected") || (value['u_connected'] == "OK")) {
body = body + "<td bgcolor='green'></td>" ;
}
else {
body = body + "<td></td>" ;
}
} else {
body = body + "<td></td>" ;
}
if (typeof value["c_alive"] != "undefined") {
if ((value['c_alive'] == "offline") || (value['c_alive'] == "NOK")) {
body = body + "<td bgcolor='red'></td>" ;
} else if ((value['c_alive'] == "online") || (value['c_alive'] == "OK")) {
body = body + "<td bgcolor='green'></td>" ;
}
else {
body = body + "<td></td>" ;
}
} else {
body = body + "<td></td>" ;
}
if (typeof value["c_connected"] != "undefined") {
if ((value["c_connected"] == "notConnected") || (value['c_connected'] == "NOK")) {
body = body + "<td bgcolor='red'></td>" ;
} else if ((value["c_connected"] == "connected") || (value['c_connected'] == "OK")) {
body = body + "<td bgcolor='green'></td>" ;
}
else {
body = body + "<td></td>" ;
}
} else {
body = body + "<td></td>" ;
}
body = body + "</tr>";
// body = body + key + " " + value + "<br>" ;
}
}
body = body + "</table>" ;
body = body + "</div>";
return '<!DOCTYPE html>'
+ '<html><head>' + header + '</head><body>' + body + '</body></html>';
}
//console.log(data1);
//var unique_id = data1[0].uniqueID;
//var order_id = data1[0].orderID;
//var order_date = data1[0].date;
//var cart_total = data1[0].cartTotal;
//
//document.getElementById("uid").innerHTML = unique_id;
//document.getElementById("oid").innerHTML = order_id;
//document.getElementById("date").innerHTML = order_date;
//document.getElementById("ctotal").innerHTML = cart_total;
<file_sep>import unittest
import logging
from time import sleep
from shutil import copy2
from copy import deepcopy
# import MockSSH
# from mock_F5 import commands
mod_name = 'ATIC'
mod_logger = logging.getLogger(mod_name)
logging.disable(logging.NOTSET)
testFilesLocation = "../test/"
class TestStatus(unittest.TestCase):
def setUp(self):
from status import readJson, Hosts, Vendors, Status
copy2(testFilesLocation + "status.json.test.orig", testFilesLocation + "status.json.test")
copy2(testFilesLocation + "hosts2.json.test.orig", testFilesLocation + "hosts2.json.test")
self.json = readJson(testFilesLocation + "hosts.json.test")
self.hosts = Hosts(testFilesLocation + "hosts.json.test")
self.hosts2 = Hosts(testFilesLocation + "hosts2.json.test")
self.vendors = Vendors(testFilesLocation + "vendorNodes.json.test")
self.status = Status(statusFile=testFilesLocation + 'status.json.test')
self.testHost1 = "HOST-001"
self.testHost2 = "HOST-002"
self.testBadHost = "BADHOST"
self.node1 = "HOST1"
self.node2 = "HOST2"
self.node3 = "HOST3"
self.badNode = "blah"
self.badPort = "1234"
# def tearDown(self):
# self.atic.disconnectAll()
# sleep(5)
def test_readJson(self):
data = self.json._readJson(testFilesLocation + "status.json.test")
if data:
self.assertTrue
else:
self.assertFalse
# print (data.status_code)
with self.assertRaises(SystemExit) as cm:
data = self.json._readJson(testFilesLocation + "badfile.json")
the_exception = cm.exception
self.assertEqual(the_exception.code, 1)
def test_getKeys(self):
self.assertEqual(self.json.getKeys(self.json.data), ['default', 'HOST-001', 'HOST-002', 'QA-001', 'BAD-HOST'])
self.assertEqual(self.json.getKeys(self.json.data, exclude='default'), ['HOST-001', 'HOST-002', 'QA-001', 'BAD-HOST'])
self.assertEqual(self.json.getKeys(self.json.data, "blah"), ['default', 'HOST-001', 'HOST-002', 'QA-001', 'BAD-HOST'])
def test_safeGet(self):
self.assertEqual(self.json.safeGet(self.json.data, self.testHost1, "nodes", self.node1, "active"), "true")
self.assertEqual(self.json.safeGet(self.json.data, self.testHost1, "config", "wifi"), "")
target = sorted(['ensco-unit', 'ensco-name', 'CN-id', 'host-can', 'host-us'])
source = sorted(self.json.safeGet(self.json.data, self.testHost1, "config").keys())
self.assertEqual(source, target)
# self.assertEqual(self.hosts.safeGet(self.hosts.data, self.testHost1, "config").keys(), ['ensco-unit', 'ensco-name', 'CN-id', 'host-can', 'host-us', 'wifi'])
# self.assertNotEqual(self.json.safeGet(self.json.data, self.testHost1, "config").keys(), ['ensco-unit', 'ensco-name', 'CN-id', 'host-can', 'host-us'])
##########################
# HOSTS #
##########################
def test_getHosts(self):
self.assertEqual(self.hosts.getHosts(), ['HOST-001', 'HOST-002', 'QA-001', 'BAD-HOST'])
def test_getConfigParams(self):
self.assertEqual(sorted(self.hosts.getConfigParams(self.testHost1)), sorted(['ensco-unit', 'ensco-name', 'CN-id', 'host-can', 'host-us']))
def test_getNodes(self):
self.assertEqual(sorted(self.hosts.getNodes(self.testHost1)), sorted(['HOST1', 'HOST2', 'HOST3', 'HOST4', 'HOST5', 'VENDORHOST1', 'VENDORHOST2', 'VENDORHOST3']))
def test_getConfigValue(self):
self.assertEqual(self.hosts.getConfigValue(self.testHost1, "wifi"), "")
def test_getNodeParams(self):
self.assertEqual(sorted(self.hosts.getNodeParams(self.testHost1, self.node1)), sorted(['active', 'username', 'port']))
def test_getNodeParamValue(self):
self.assertEqual(self.hosts.getNodeParamValue(self.testHost1, self.node1, "active"), "true")
def test_getHostIP(self):
self.assertEqual(self.hosts.getHostIP(self.testHost1), "172.16.58.3")
self.assertEqual(self.hosts.getHostIP(self.testHost1, apn="host-us"), "172.16.58.3")
self.assertEqual(self.hosts.getHostIP(self.testHost1, apn="host-can"), "1.2.3.99")
def test_getHostNodePort(self):
self.assertEqual(self.hosts.getHostNodePort(self.testHost1, self.node1), "2500")
self.assertEqual(self.hosts.getHostNodePort(self.testHost1, self.node3), "")
self.assertEqual(self.hosts.getHostNodePort(self.testBadHost, self.node1), "")
self.assertEqual(self.hosts.getHostNodePort(self.testHost1, self.badNode), "")
def test_setHostConfigParamValue(self):
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "host-us"), "172.16.58.3")
self.hosts2.setHostConfigParamValue(self.testHost1, "host-us", "blah")
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "host-us"), "blah")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "host-us"), "172.16.58.3")
# update hosts file
self.hosts2.setHostConfigParamValue(self.testHost1, "host-us", "blah", writeFile=True)
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "host-us"), "blah")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "host-us"), "172.16.58.3")
def test_setHostNodeParamValue(self):
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "root")
self.hosts2.setHostNodeParamValue(self.testHost1, self.node1, "username", "blah")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "blah")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "root")
# update hosts file
self.hosts2.setHostNodeParamValue(self.testHost1, self.node1, "username", "blah", writeFile=True)
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "blah")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "blah")
def test_setConfigDefault(self):
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "wifi"), "")
self.hosts2.setConfigDefault()
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "wifi"), "NA")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getConfigValue(self.testHost1, "wifi"), "")
def test_setNodeDefault(self):
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "root")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "password"), "")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "port"), "2500")
self.hosts2.setNodeDefault()
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "root")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "password"), "<PASSWORD>")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "port"), "2500")
self.hosts2.hosts = self.hosts2._readJson(testFilesLocation + "hosts2.json.test")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "username"), "root")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "password"), "")
self.assertEqual(self.hosts2.getNodeParamValue(self.testHost1, self.node1, "port"), "2500")
##########################
# VENDORS #
##########################
def test_getVendors(self):
self.assertEqual(sorted(self.vendors.getVendors()), sorted(['VENDOR1', 'VENDOR2']))
def test_getVendorNodes(self):
self.assertEqual(sorted(self.vendors.getVendorNodes('VENDOR1')), sorted(['VENDORHOST1', 'VENDORHOST2', 'VENDORHOST3', 'VENDORHOST4', 'VENDORHOST5', 'VENDORHOST6', 'VENDORHOST7', 'VENDORHOST8']))
def test_getVendorNodeIP(self):
self.assertEqual(self.vendors.getVendorNodeIP(vendor="VENDOR1", node="VENDORHOST1"), "172.16.31.10")
# self.assertEqual(self.vendors.getVendorNodeIP(node="VENDORHOST1", vendor="VENDOR1"), "172.16.31.10")
self.assertEqual(self.vendors.getVendorNodeIP(node="VENDORHOST11", vendor="VENDOR1"), "")
def test_isVendorExists(self):
self.assertTrue(self.vendors.isVendorExists("VENDOR1"))
self.assertTrue(self.vendors.isVendorExists("VENDOR2"))
self.assertFalse(self.vendors.isVendorExists("VENDOR11"))
def test_isVendorNodeExists(self):
self.assertTrue(self.vendors.isVendorNodeExists("VENDOR1", "VENDORHOST1"))
self.assertTrue(self.vendors.isVendorNodeExists("VENDOR2", "TT"))
self.assertFalse(self.vendors.isVendorNodeExists("VENDOR11", "VENDORHOST1"))
self.assertFalse(self.vendors.isVendorNodeExists("VENDOR1", "VENDORHOST11"))
##########################
# STATUS #
##########################
def test_Status_getHosts(self):
self.assertEqual(self.status.getHosts(), ['HOST-001', 'HOST-002', 'QA-001', 'BAD-HOST'])
def test_Status_getConfigParams(self):
self.assertEqual(sorted(self.status.getConfigParams(self.testHost1)), sorted(['active', 'host-us', 'host-can', 'wifi']))
def test_Status_getNodes(self):
self.assertEqual(sorted(self.status.getNodes(self.testHost1)), sorted(['HOST1', 'HOST2', 'HOST3', 'HOST4', 'HOST5', 'VENDORHOST1', 'VENDORHOST2', 'VENDORHOST3']))
def test_Status_getConfigValue(self):
self.assertEqual(self.status.getConfigValue(self.testHost1, "wifi"), "NA")
def test_Status_getNodeParams(self):
self.assertEqual(sorted(self.status.getNodeParams(self.testHost1, self.node1)), sorted(['vendor', 'active', 'c_connected', 'u_connected', 'alive']))
def test_Status_getNodeParamValue(self):
# copy2("status.json.test", "status.json")
self.assertEqual(self.status.getNodeParamValue(self.testHost1, self.node1, "active"), "true")
def test_read(self):
mystuff = self.status.status
self.assertTrue(self.status.read())
self.assertEqual(self.status.status, mystuff)
#self.assertFalse(self.status.read("blah"))
def test_write(self):
# copy2("status.json.test.orig", "status.json.test")
self.assertTrue(self.status.read())
mystuff = deepcopy(self.status.status)
print("mystuff: ", mystuff[self.testHost1]["nodes"][self.node1]["active"])
self.assertTrue(self.status.write())
self.assertTrue(self.status.read())
self.assertEqual(self.status.status, mystuff)
self.status.setNodeParamValue(self.testHost1, self.node1, "active", "false")
self.assertTrue(self.status.write())
self.assertNotEqual(self.status.status, mystuff)
# self.status.setNodeParamValue(self.testHost1, self.node1, "active", "true")
# self.assertTrue(self.status.write(self.status.status, 'status.json'))
# self.assertEqual(self.status.status, mystuff)
def test_setNodeParamValue(self):
self.assertEqual(self.status.getNodeParamValue(self.testHost1, self.node1, "active"), "true")
self.assertTrue(self.status.setNodeParamValue(self.testHost1, self.node1, "active", "false"))
self.assertTrue(self.status.write())
# self.assertEqual(self.status.getNodeParamValue(self.testHost1, self.node1, "active"), "false")
class TestStatusHandler(unittest.TestCase):
def setUp(self):
# import createStatus
from statusHandler import statusHandler
self.testHost1 = "HOST-001"
self.testHost2 = "QA-001"
self.testHost3 = "BAD-HOST"
self.testHost4 = "BAD-HOST1"
self.badHost = "ATIC-00"
self.node1 = "HOST1"
self.node2 = "HOST2"
self.node3 = "VENDORHOST1"
self.node4 = "VENDORHOST7"
self.badnode = "BAD"
self.status = statusHandler(testFilesLocation + "status.json.test")
copy2(testFilesLocation + "status.json.test.orig", testFilesLocation + "status.json.test")
def test_ReadStatus(self):
self.assertEqual(self.status.readStatus(self.testHost1, self.node1, "u_connected"), "")
self.assertEqual(self.status.readStatus(self.testHost1, self.node1, "connected1"), self.status.UNDEF)
self.assertEqual(self.status.readStatus(self.badHost, self.node1, "connected1"), self.status.UNDEF)
self.assertEqual(self.status.readStatus(self.testHost1, self.badnode, "connected1"), self.status.UNDEF)
def test_WriteStatus(self):
self.assertTrue(self.status.writeStatus(self.testHost1, self.node1, "u_connected", "true"))
self.assertFalse(self.status.writeStatus(self.testHost1, self.node1, "u_connected1", "true"))
self.assertFalse(self.status.writeStatus(self.testHost1, self.badnode, "u_connected", "true"))
self.assertFalse(self.status.writeStatus(self.badHost, self.node1, "u_connected", "true"))
class TestATICHosts(unittest.TestCase):
# # @classmethod
# def setUpClass(cls):
# users = {'root': '<PASSWORD>'}
# cls.keypath = tempfile.mkdtemp()
# MockSSH.startThreadedServer(
# commands,
# prompt="[root@hostname:Active] testadmin # ",
# keypath=cls.keypath,
# interface="localhost",
# port=22,
# **users)
# # @classmethod
# def tearDownClass(cls):
# print ("tearDownClass")
# MockSSH.stopThreadedServer()
# shutil.rmtree(cls.keypath)
def setUp(self):
from ATICHosts import ATICHosts
from statusHandler import statusHandler
copy2(testFilesLocation + "hosts2.json.test.orig", testFilesLocation + "hosts.json.test")
self.atic = ATICHosts(hostFile=testFilesLocation + 'hosts.json.test', \
vendorFile=testFilesLocation + 'vendorNodes.json.test', \
statusFile=testFilesLocation + 'status.json.test')
self.testHost1 = "HOST-001"
self.testHost2 = "QA-001"
self.testHost3 = "BAD-HOST"
self.badHost = "ATIC-00"
self.node1 = "HOST1"
self.node2 = "HOST2"
self.node3 = "VENDORHOST1"
self.node4 = "VENDORHOST7"
self.status = statusHandler(statusFile=testFilesLocation + 'status.json.test')
def tearDown(self):
sleep(5)
self.atic.disconnectAll()
sleep(5)
def test_getRemoteIndex(self):
self.assertEqual(self.atic._getRemoteIndex(self.testHost1, self.node1), self.testHost1 + "-" + self.node1)
def test_isNodeForVendor(self):
self.assertTrue(self.atic._isNodeForVendor(self.testHost1, self.node1, "vendor0"))
self.assertTrue(self.atic._isNodeForVendor(car=self.testHost1, node=self.node3, vendor="vendor1"))
self.assertFalse(self.atic._isNodeForVendor(self.testHost1, self.node1, "vendor1"))
self.assertFalse(self.atic._isNodeForVendor(self.testHost1, self.node3, "vendor0"))
self.assertTrue(self.atic._isNodeForVendor(self.testHost1, self.node1, "VENDOR0"))
self.assertTrue(self.atic._isNodeForVendor(self.testHost1, self.node3, "VENDOR1"))
self.assertFalse(self.atic._isNodeForVendor(self.testHost1, self.node1, "Vendor1"))
self.assertFalse(self.atic._isNodeForVendor(self.testHost1, self.node3, "VENDOR0"))
def test_isNodeInHost(self):
self.assertTrue(self.atic.isNodeInHost(self.testHost1, self.node1))
self.assertFalse(self.atic.isNodeInHost(self.testHost2, self.node4))
def test_isVendorExists(self):
self.assertTrue(self.atic.isVendorExists("VENDOR1"))
self.assertTrue(self.atic.isVendorExists("VENDOR2"))
self.assertFalse(self.atic.isVendorExists("VENDOR11"))
# def test_isVendorNodeAlive(self):
# (ok,res) = self.atic.isVendorNodeAlive(car=self.testHost2, node=self.node3, vendor="VENDOR1", gwNode="HOST2")
# print (ok, res)
# self.assertTrue(ok)
# (ok,res) = self.atic.isVendorNodeAlive(car=self.testHost2, node=self.node4, vendor="VENDOR1", gwNode="HOST2")
# self.assertFalse(ok)
def test_isVendorNodeAlive(self):
(ok,res) = self.atic.isVendorNodeAlive(car=self.testHost2, node=self.node3, vendor="VENDOR1", gwNode=self.node2)
print ("VENDOR NODE ALIVE",ok, res)
print("car is",self.testHost2, "node",self.node3, "vendor VENDOR1 gwNode HOST2")
self.assertTrue(ok)
(ok,res) = self.atic.isVendorNodeAlive(car=self.testHost2, node=self.node4, vendor="VENDOR1", gwNode=self.node2)
self.assertFalse(ok)
def test_isVendorNodeExistsForCar(self):
self.assertFalse(self.atic.isVendorNodeExistsForCar(car=self.testHost2, vendor="VENDOR1", node=self.node4))
self.assertTrue(self.atic.isVendorNodeExistsForCar(car=self.testHost2, vendor="VENDOR1", node=self.node3))
self.assertFalse(self.atic.isVendorNodeExistsForCar(car=self.testHost2, vendor="TT", node=self.node3))
self.assertTrue(self.atic.isVendorNodeExistsForCar(car=self.testHost1, vendor="VENDOR1", node=self.node3))
def test_connect(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), "")
self.assertEqual(self.atic._connect(self.testHost2, self.node2, stayConn=True, updateStatus=True), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
self.assertEqual(self.atic._connect(self.testHost3, self.node1), "notConnected")
self.assertEqual(self.atic.status.readStatus(self.testHost3, self.node1, "u_connected"), "")
def test_isConnected(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2, stayConn=True), self.atic.CONNECTED)
self.assertEqual(self.atic._connect(self.testHost3, self.node1), self.atic.NOTCONNECTED)
self.assertTrue(self.atic.isConnected(self.testHost2, self.node2))
self.assertFalse(self.atic.isConnected(self.testHost1, self.node1))
def test_disconnect(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2, stayConn=True, updateStatus=True), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
self.atic._disconnect(self.testHost2, self.node2)
self.assertFalse(self.atic.isConnected(self.testHost2, self.node2))
# def test_connectHost(self):
# self.assertEqual(self.atic.connectHost(self.testHost3, self.node1), self.atic.NOTCONNECTED)
# self.assertEqual(self.atic.status.readStatus(self.testHost3, self.node1, "u_connected"), self.atic.NOTCONNECTED)
# self.assertEqual(self.atic.connectHost(self.testHost2, self.node2, updateStatus=True), self.atic.CONNECTED)
# self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
# self.assertTrue(self.atic.connectHost(self.testHost2, self.node2))
# sleep(5)
# self.assertTrue(self.atic.connectHost(self.testHost2, self.node2, force=True))
# self.assertTrue(self.atic.isConnected(self.testHost2, self.node2))
# self.atic._disconnect(self.testHost2, self.node2)
def test_disconnectHost(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2, updateStatus=True), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
self.assertTrue(self.atic.disconnectHost(self.testHost2, self.node2))
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.NOTCONNECTED)
self.assertTrue(self.atic.disconnectHost(self.testHost2, self.node2))
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.NOTCONNECTED)
def test_isRemoteIndexExists(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2, stayConn=True, updateStatus=True), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
self.assertTrue(self.atic._isRemoteIndexExists(self.testHost2, self.node2))
self.assertTrue(self.atic.disconnectHost(self.testHost2, self.node2))
self.assertFalse(self.atic._isRemoteIndexExists(self.testHost2, self.node2))
def test_ping(self):
# self.assertTrue(self.atic.connectHost(car="QA-001", node="HOST2"))
self.assertTrue(self.atic.ping("google.com"))
# self.assertTrue(self.atic.ping(ip="127.0.0.1"))
# self.assertFalse(self.atic.ping(ip="172.16.31.10"))
# self.assertTrue(self.atic.ping(ip="192.168.2.23"))
# self.assertTrue(self.atic.ping(car="QA-001", ip="192.168.2.23", gwNode="HOST2"))
# self.assertTrue(self.atic.ping(car="QA-001", ip="127.0.0.1", gwNode="HOST2"))
# self.assertFalse(self.atic.ping(car="QA-001", ip="172.16.31.10", gwNode="HOST2"))
def test_runCommand(self):
self.assertEqual(self.atic._connect(self.testHost2, self.node2, updateStatus=True, stayConn=True), self.atic.CONNECTED)
self.assertEqual(self.atic.status.readStatus(self.testHost2, self.node2, "u_connected"), self.atic.CONNECTED)
self.assertTrue(self.atic._isRemoteIndexExists(self.testHost2, self.node2))
#self.assertTrue(self.atic.runCommand(self.testHost2, self.node2, "ip a", TrueIf=['eth0', 'lo']))
retVal, output, err = self.atic.runCommand(self.testHost2, self.node2, "ip a", TrueIf=['enp2s0', 'wlp3s0', 'lo', 'eth19'])
self.assertFalse(retVal)
# # self.assertFalse(self.atic.runCommand(self.testHost2, self.node2, "ip a", TrueIf=['eth0', 'wlan0', 'lo', 'l1']))
# retVal, output, err = self.atic.runCommand(self.testHost2, self.node2, "ip a", TrueIf=['enp2s0', 'wlp3s0', 'lo', 'l1'])
# self.assertFalse(retVal)
# retVal, output, err = self.atic.runCommand(self.testHost2, self.node2, "ip a", TrueIf=['enp2s0', 'wlp3s0', 'lo'])
# self.assertTrue(retVal)
retVal, output, err = self.atic.runCommand(self.testHost2, self.node2, "ping -c1 -w1 127.0.0.1", FalseIf=[' 100% packet loss'])
self.assertTrue(retVal)
retVal, output, err = self.atic.runCommand(self.testHost2, self.node2, "pwd", TrueIf=['/root'])
self.assertTrue(retVal)
# def test_getOS(self):
# self.assertTrue(self.atic.connectHost(car="QA-001", node="HOST2"))
# # comment out if not cygwin
# self.assertEqual(self.atic._getOS(), "CYGWIN")
# # comment out if not Linux
# #self.assertEqual(self.atic._getOS(), "Linux")
# self.assertEqual(self.atic._getOS(host='QA-001', node='HOST2'), "Linux")
def test_nc(self):
self.assertFalse(self.atic.nc("10.1.157.106", "8080"))
self.assertTrue(self.atic.nc("google.com", "80"))
# if self.atic._getOS() == "CYGWIN":
# self.assertFalse(self.atic.nc("127.0.0.1", "22"))
# else:
# self.assertTrue(self.atic.nc("127.0.0.1", "22"))
def test_isACCNodeAlive(self):
self.assertFalse(self.atic.isACCNodeAlive(self.testHost1, self.node1))
self.assertTrue(self.atic.isACCNodeAlive(self.testHost2, self.node2))
if __name__ == "__main__":
unittest.main()
# suite = unittest.TestSuite()
# ## # suite.addTest(TestATICHosts("test_isNodeForVendor"))
# ## # suite.addTest(TestATICHosts("test_isNodeInHost"))
# ## # suite.addTest(TestATICHosts("test_isRemoteIndexExists"))
# ## # suite.addTest(TestATICHosts("test_isVendorExists"))
# suite.addTest(TestATICHosts("test_isVendorNodeAlive"))
# # suite.addTest(TestATICHosts("test_isVendorNodeExistsForCar"))
# suite.addTest(TestStatus("test_readJson"))
# ## suite.addTest(TestStatus("test_getKeys"))
# ## # suite.addTest(TestStatus("test_safeGet"))
# ## suite.addTest(TestStatus("test_getHosts"))
# ## suite.addTest(TestStatus("test_getConfigParams"))
# ## suite.addTest(TestStatus("test_getNodes"))
# ## suite.addTest(TestStatus("test_getConfigValue"))
# ## suite.addTest(TestStatus("test_getNodeParams"))
# ## suite.addTest(TestStatus("test_getNodeParamValue"))
# ## suite.addTest(TestStatus("test_getVendors"))
# ## suite.addTest(TestStatus("test_getVendorNodes"))
# ## suite.addTest(TestStatus("test_getVendorNodeIP"))
# ## suite.addTest(TestStatus("test_isVendorExists"))
# ## suite.addTest(TestStatus("test_isVendorNodeExists"))
# ## suite.addTest(TestStatus("test_Status_getHosts"))
# ## suite.addTest(TestStatus("test_Status_getConfigParams"))
# ## suite.addTest(TestStatus("test_Status_getNodes"))
# ## suite.addTest(TestStatus("test_Status_getConfigValue"))
# ## suite.addTest(TestStatus("test_Status_getNodeParams"))
# ## suite.addTest(TestStatus("test_Status_getNodeParamValue"))
# ## suite.addTest(TestStatus("test_setNodeParamValue"))
# ## suite.addTest(TestStatus("test_read"))
# ## suite.addTest(TestStatus("test_write"))
# ## suite.addTest(TestStatus("test_getHostIP"))
# #suite.addTest(TestStatus("test_getHostNodePort"))
# # suite.addTest(TestStatus("test_setHostConfigParamValue"))
# # suite.addTest(TestStatus("test_setHostNodeParamValue"))
# # suite.addTest(TestStatus("test_setConfigDefault"))
# # suite.addTest(TestStatus("test_setNodeDefault"))
# ## suite.addTest(TestStatusHandler("test_ReadStatus"))
# ## suite.addTest(TestStatusHandler("test_WriteStatus"))
# ## # suite.addTest(TestATICHosts("test_disconnectHost"))
# ## # suite.addTest(TestATICHosts("test_runCommand"))
# # suite.addTest(TestATICHosts("test_ping"))
# #suite.addTest(TestATICHosts("test_nc"))
# #suite.addTest(TestATICHosts("test_isACCNodeAlive"))
# # suite.addTest(TestATICHosts("test_getOS"))
# runner = unittest.TextTestRunner()
# runner.run(suite)
<file_sep># setup_logger.py
import logging
# logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('alive.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s %(levelname)-5s %(name)s.%(funcName)s() %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)
<file_sep>from status import Hosts, Vendors
import parameters
import json
import logging
import logger_setup
import argparse
logger = logging.getLogger('ATIC.createStatus')
class StatusFile():
def __init__(self, hostFile="hosts.json", vendorFile="vendorNodes.json"):
self.h = Hosts(hostFile)
self.v = Vendors(vendorFile)
self.status = {}
self.h._setDefault()
def createStatusFile(self):
for host in self.h.getHosts():
# building up hosts parameters
config = {}
for param in parameters.hostParams:
config[param] = self.h.hosts.get(host).get("config").get(param, "")
self.status[host] = {"config" : config}
# # building cn node params
# config_cn = {}
# for param in parameters.nodeParams:
# config_cn[param] = ""
# config_vendor = {}
# for param in parameters.nodeVendorParams:
# config_vendor[param] = ""
_node= {}
for node in self.h.getNodes(host):
config = {}
if self.h.getNodeParamValue(host, node, "vendor") == "cn":
for param in parameters.nodeParams:
logger.debug("checking for CN parameter for car " + host + " node " + node + " param " + param)
logger.debug("hosts value is " + self.h.hosts[host]["nodes"][node].get(param, "NOT FOUND."))
config[param] = self.h.hosts.get(host).get("nodes").get(node).get(param, "")
else:
for param in parameters.nodeVendorParams:
logger.debug("checking for Vendor parameter for car " + host + " node " + node + " param " + param)
logger.debug("hosts value is " + self.h.hosts[host]["nodes"][node].get(param, "NOT FOUND."))
config[param] = self.h.hosts.get(host).get("nodes").get(node).get(param, "")
_node[node] = config
self.status[host]["nodes"] = _node
logger.info ("generating status file")
# if self.h.getNodeParamValue(host, node, "vendor") == "cn":
# if self.h.getNodeParamValue(host, node, "active") == "true":
# config_cn["active"] = "true"
# else:
# config_cn["active"] = ""
# _node[node] = config_cn
# else:
# if self.h.getNodeParamValue(host, node, "active") == "true":
# config_vendor["active"] = "true"
# else:
# config_vendor["active"] = ""
# _node[node] = config_vendor
# self.status[host]["nodes"] = _node
def writeConfig(self, outputFile="status.json"):
with open(outputFile, "w") as outfile:
json.dump(self.status, outfile, indent=4)
logger.info("status file: " + outputFile + " created.")
def main(hostFile, vendorFile, statusFile):
a = StatusFile(hostFile=hostFile, vendorFile=vendorFile)
a.createStatusFile()
a.writeConfig(outputFile=statusFile)
b = Hosts(hostFile)
logger.info (b.getHosts())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--hostFile", default="hosts.json", help="specify host file")
parser.add_argument("--vendorFile", default="vendorNodes.json", help="specify vendor file")
parser.add_argument("--statusFile", default="status.json", help="specify status file")
args = parser.parse_args()
print ("hostFile:", args.hostFile)
print ("vendorFile:", args.vendorFile)
print ("statusFile:", args.statusFile)
main(args.hostFile, args.vendorFile, args.statusFile)<file_sep>from ATICHosts import ATICHosts
<file_sep>asn1crypto==1.0.1
attrs==19.3.0
Automat==0.8.0
bcrypt==3.1.7
cffi==1.12.3
constantly==15.1.0
cryptography==2.7
enum34==1.1.6
incremental==17.5.0
ipaddress==1.0.23
paramiko==2.1.1
pyasn1==0.4.8
pycparser==2.19
pycrypto==2.6.1
PyNaCl==1.3.0
six==1.12.0
Twisted==16.7.0rc2
zope.interface==4.7.1
<file_sep>from curses import wrapper
import curses
import json
from collections import OrderedDict
from time import sleep
import datetime
def main(stdscr):
height, width = stdscr.getmaxyx()
stdscr.addstr(0,int((width - len("ATIC MONITOR"))/2), "ATIC MONITOR", curses.A_BOLD)
stdscr.hline(1,0,'=',width)
while True:
stdscr.addstr(0,0, str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
with open('status.json', 'r') as statusfile:
data = json.load(statusfile, object_pairs_hook=OrderedDict)
spacing = 0
row = 2
for car in data:
stdscr.addstr(row,spacing, car, curses.A_UNDERLINE)
for param in data[car]:
row+=1
stdscr.addstr(row, spacing + 0, param + ": ", curses.A_BOLD)
for value in data[car][param].split():
stdscr.addstr(row,spacing + 12, value.ljust(8))
spacing += 25
row = 2
# stdscr.addstr(35, 0, " ")
stdscr.refresh()
# stdscr.getkey()
sleep(5)
wrapper(main)
<file_sep>from time import sleep
from random import seed, randint
from ATICHosts import ATICHosts
import logging
import logger_setup
mod_name = 'ATIC'
logger = logging.getLogger(mod_name)
seed(3)
class status:
def __init__(self, d):
self.status = d
def writeStatus(self, param, value):
self.status[param] = value
def readStatus(self, param):
return self.status[param]
class mp:
def __init__(self, d):
self.a = "hello "
self.b = ATICHosts(hostFile="hosts_test.json")
self.s = status(d)
def run(self, num):
ran = randint(0,10)
sleep(ran)
print (self.a, num, ran)
self.s.writeStatus(num, ran)
def connect(self, car, node):
self.writeStatus(car, node)
print(car, node, self.b._connect(car, node), self.b.getHostIP(car))
print (self.printStatus())
def printStatus(self):
print (self.s.status)
def readStatus(self, param):
return self.s.readStatus(param)
def writeStatus(self, param, value):
self.s.writeStatus(param, value)
<file_sep>import multiprocessing
from time import sleep
from random import randint, seed
from mpclass import mp
import logging
import logger_setup
mod_name = 'ATIC'
logger = logging.getLogger(mod_name)
seed(2)
def worker(num):
"""thread worker function"""
sl_time = randint(0,5)
sleep(sl_time)
print ('Worker:', num, ' sleep was ', sl_time)
return
if __name__ == '__main__':
jobs = []
manager = multiprocessing.Manager()
d = manager.dict()
# for i in range(5):
# p = multiprocessing.Process(target=worker, args=(i,))
# jobs.append(p)
# for p in jobs:
# p.start()
jobs = []
nodes = [ ('ATIC-005', 'WCM'), ('QA-001', 'SMM') ]
a = mp(d)
for i in nodes:
p = multiprocessing.Process(target=a.connect, args=(i))
jobs.append(p)
p.start()
sleep(2)
print ("\n\nStatus1:", a.printStatus())
# for p in jobs:
# print ("starting",p)
# p.start()
# for p in jobs:
# print('terminating', p)
# p.terminate()
for p in jobs:
print('joining', p)
p.join()
print ("\n\nStatus:", a.printStatus())
print ('d', d)<file_sep>from ATICHosts import ATICHosts
from time import sleep
import json
import logging
import logger_setup
from os import path, remove
from sys import exit
from time import sleep
import multiprocessing
mod_name = 'ATIC'
logger = logging.getLogger(mod_name)
#lock = mp.Lock()
#hosts = ATICHosts(statusFile = "status.json", hostFile="hosts2.json", lock=lock)
seconds = 120
remoteDir = "/cygdrive/z/CB956001_PTC Program/09 Systems - Projects/ATIP Autonomous Track Inspection Program/Tools/alive-version3.3"
class mp:
def __init__(self, status, remote):
self.b = ATICHosts(status=status, remote=remote)
self.remote = remote
self.status = status
def connect(self, car):
#self.b._connect(car, node)
self.b.updateCarStatus(car)
if __name__ == '__main__':
jobs = []
# lock = multiprocessing.Lock()
manager = multiprocessing.Manager()
status = manager.dict()
remote = manager.dict()
remote = {}
hosts = ATICHosts(status=status, remote=remote, statusFile = "status.json", hostFile="hosts2.json")
nodes = [ (c, n) for c in hosts.getHosts() for n in hosts.getNodes(c) ]
a = mp(status, remote)
#for i in hosts.getHosts():
# for i in ['ATIC-005', 'ATIC-006', 'ATIC-007', 'ATIC-008']:
for i in ['ATIC-005']:
p = multiprocessing.Process(target=a.connect, args=(i,))
jobs.append(p)
for p in jobs:
p.start()
for p in jobs:
p.join()
print (p, "has returned")
print (status)
with open ("status.json", 'w') as outfile:
json.dump(status.copy(), outfile, indent=4)
# while True:
# if path.isfile(remoteDir + "/stop"):
# exit(0)
# # processes = []
# # for car in hosts.getHosts():
# # processes.append(
# # mp.Process(target=hosts.updateCarStatus, args=(car,))
# # )
# #
# # for p in processes:
# # p.start()
# #
# # for p in processes:
# # p.join()
# for car in hosts.getHosts():
# hosts.updateCarStatus(car)
# logger.info("Sleeping for " + str(seconds) + " seconds")
# if path.isfile(remoteDir + "/reload"):
# logger.info("reload file detected")
# remove(remoteDir + "/reload")
# exit(0)
# sleep(seconds)
<file_sep>from ATICHosts import ATICHosts
from time import sleep
import logging
import logger_setup
from os import path, remove
from sys import exit
from time import sleep
#import multiprocessing as mp
mod_name = 'ATIC'
logger = logging.getLogger(mod_name)
#lock = mp.Lock()
#hosts = ATICHosts(statusFile = "status.json", hostFile="hosts2.json", lock=lock)
hosts = ATICHosts(statusFile = "status.json", hostFile="hosts.json")
seconds = 120
remoteDir = "/cygdrive/z/CB956001_PTC Program/09 Systems - Projects/ATIP Autonomous Track Inspection Program/Tools/alive-version3.3"
while True:
for car in hosts.getHosts():
hosts.updateCarStatus(car)
logger.info("Sleeping for " + str(seconds) + " seconds")
if path.isfile(remoteDir + "/reload"):
logger.info("reload file detected")
remove(remoteDir + "/reload")
exit(0)
sleep(seconds)
<file_sep>hostParams = [
"active",
"host-us",
"host-can",
"wifi"
]
nodeParams = [
"vendor",
"active",
"u_connected",
"c_connected",
"u_alive",
"c_alive"
]
nodeVendorParams = [
"vendor",
"active",
"u_connected",
"c_connected",
"alive"
]
<file_sep>#!/usr/bin/python
#
import sys
import MockSSH
from twisted.python import log
from time import sleep
import tempfile
class command_ping(MockSSH.SSHCommand):
name = "ping"
def start(self):
if len(self.args) == 1:
self.ip = self.args[0]
print(("IP is ", self.ip))
self.writeln("PING " + self.ip + " (" + self.ip + ") 56(84) bytes of data.")
self.writeln("64 bytes from lga25s60-in-f14.1e100.net (" + self.ip + "): icmp_seq=1 ttl=55 time=20.4 ms")
self.writeln("")
self.writeln("--- " + self.ip + " ping statistics ---")
self.writeln("1 packets transmitted, 1 received, 0% packet loss, time 0ms")
self.writeln("rtt min/avg/max/mdev = 18.911/18.911/18.911/0.000 ms")
self.exit()
else:
self.writeln("Usage: ping [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]")
self.writeln(" [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]")
self.writeln(" [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]")
self.writeln(" [-w deadline] [-W timeout] [hop1 ...] destination")
self.exit()
class command_pwd(MockSSH.SSHCommand):
name = "pwd"
def start(self):
self.writeln("/root")
self.exit()
class command_passwd(MockSSH.SSHCommand):
name = 'passwd'
def start(self):
self.passwords = []
if len(self.args) == 1:
self.username = self.args[0]
self.writeln("Changing password for user %s." % self.username)
self.write("New BIG-IP password: ")
self.protocol.password_input = True
self.callbacks = [self.ask_again, self.finish]
else:
self.writeln("MockSSH: Supported usage: passwd <username>")
self.exit()
def ask_again(self):
self.write('Retype new BIG-IP password: ')
def finish(self):
self.protocol.password_input = False
if self.passwords[0] != self.passwords[1]:
self.writeln("Sorry, passwords do not match")
self.writeln("passwd: Authentication token manipulation error")
self.writeln("passwd: password unchanged")
self.exit()
else:
self.writeln("Changing password for user %s." % self.username)
self.writeln("passwd: all authentication tokens updated "
"successfully.")
self.exit()
def lineReceived(self, line):
print('INPUT (passwd):', line)
self.passwords.append(line.strip())
self.callbacks.pop(0)()
commands = [command_passwd, command_pwd, command_ping]
def main():
users = {'root': '<PASSWORD>'}
log.startLogging(sys.stderr)
#MockSSH.runServer(
# MockSSH.startThreadedServer(
# commands,
# prompt="[root@hostname:Active] root # ",
# interface='127.0.0.1',
# port=22,
# **users)
users = {'root': '<PASSWORD>'}
keypath = tempfile.mkdtemp()
MockSSH.startThreadedServer(
commands,
prompt="[root@hostname:Active] testadmin # ",
keypath=keypath,
interface="localhost",
port=22,
**users)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("User interrupted")
sys.exit(1)
<file_sep>from paramikoWrapper import paramikoWrapper
from statusHandler import statusHandler
from collections import OrderedDict
from status import Hosts, Vendors
import json
import socket
import subprocess, os
import logging
from time import sleep
import threading
mod_name = 'ATIC.ATICHosts'
logger = logging.getLogger(mod_name)
VERSION = "4.2"
maxThread = 35
class ATICHosts(Hosts, Vendors):
def __init__(self, hostFile="hosts.json", statusFile="status.json", vendorFile="vendorNodes.json"):
self.logger = logging.getLogger(mod_name + ".1")
self.__version__ = VERSION
Hosts.__init__(self, hostFile)
Vendors.__init__(self, vendorFile)
self.hostFile = hostFile
self.statusFile = statusFile
self.remote={}
# self.vendor=self._readJson(vendorFile)
self.status = statusHandler(self.statusFile)
self.apnList={"host-us":["u_alive", "u_connected"], "host-can": ["c_alive", "c_connected"]}
self.vendorList=self.getVendors()
# constants
self.defaultConn = "host-us"
self.usConn = "host-us"
self.canConn = "host-can"
self.wifi = "wifi"
self.CONNECTED = "connected"
self.NOTCONNECTED = "notConnected"
self.ALIVE = "online"
self.DEAD = "offline"
self.UNKNOWN = "UNK"
self.OK = "OK"
self.NOK = "NOK"
self.NoSSH = "NoSSH"
self.noOutput = "NoOutput"
self._setDefault()
def _getVersion(self):
return self.__version__
def _getRemoteIndex(self, car, node):
# creates the index value based on car and node combination
return car + "-" + node
def _isNodeForVendor(self, car, node, vendor):
""" This returns true of vendor for a specific car, node is
vendor
The vendor name is stored as lowercase, but the vendor paramter is
case insensitive.
"""
if self.getNodeParamValue(car, node, "vendor") == vendor.lower():
return True
else:
self.logger.debug("vendor for car " + car +" node " + node + " is " + self.getNodeParamValue(car, node, "vendor"))
return False
def _connect(self, car, node, stayConn=False, updateStatus=False):
"""
syntax:
_connect(self, car, node, stayConn=False, updateStatus=False)
arguments:
stayConn: if true, the connection will stay connected once the
control is returned to the calling method.
updatestatus: if true, the status for the dashboard will be
updated.
return: state
returns the connection state
values:
connected
notConnected
NoSSH
NoSSH means that the node is not SSH'able. ie. no ip address
"""
if self.getNodeParamValue(car, node, "ssh") == "true":
if not self.isConnected(car, node):
for apn in self.apnList:
print ("CHECKING APN", apn, "for car", car, "node", node)
ipAddress = self.getHostIP(car, apn)
port = self.getHostNodePort(car, node)
if ipAddress != "NA":
print ("IP ADDRESS", ipAddress, port)
if not self.nc(ipAddress, port):
print (ipAddress, port, "NOT CONNECTED")
return self.NOTCONNECTED
print (ipAddress, port, "CONNECTED")
else:
continue
if ipAddress == "NA":
return self.NoSSH
# ipAddress = self.getConfigValue(car, apn)
# port = self.getNodeParamValue(car, node, "port")
username = self.getNodeParamValue(car, node, "username")
password = self.getNodeParamValue(car, node, "password")
self.logger.debug(__name__ + ": " + car + "[" + node + "] - " + ipAddress + \
":" + port)
# self.logger.debug(__name__ + ": ip address is " + self.getConfigValue(car, self.defaultConn))
# self.logger.debug(__name__ + ": node username is " + self.getNodeParamValue(car, node, "username"))
# self.logger.debug(__name__ + ": node password is ******** ")
# self.logger.debug(__name__ + ": node port is " + self.getNodeParamValue(car, node, "port"))
self.remote[self._getRemoteIndex(car,node)] = paramikoWrapper(
ipAddress, username, password, port)
if self.isConnected(car, node):
state = self.CONNECTED
else:
state = self.NOTCONNECTED
try:
del self.remote[self._getRemoteIndex(car,node)]
except:
pass
if not stayConn:
self._disconnect(car, node, False)
if updateStatus:
self.logger.debug ("writing to status file: " + state)
self.status.writeStatus(car, node, self.apnList[apn][1], state)
if state == self.CONNECTED:
self.status.writeStatus(car, node, self.apnList[apn][0], self.ALIVE)
break
else:
if updateStatus:
self.logger.debug(car + "[" + node + "] already connected")
# self.status.writeStatus(car, node, self.apnList[apn][0], self.ALIVE)
state = self.CONNECTED
else:
state = self.NoSSH
return state
def _disconnect(self, car, node, updateStatus=True):
self.logger.debug("disconnecting from " + car + ":" + node)
if self.getNodeParamValue(car, node, "ssh"):
if self.isConnected(car, node):
self.remote[self._getRemoteIndex(car, node)].__del__()
self.remote.pop(self._getRemoteIndex(car, node), None)
if updateStatus:
for apn in self.apnList:
self.status.writeStatus(car, node, self.apnList[apn][1], self.NOTCONNECTED)
return True
def _getOS(self, host=None, node="SMM"):
if host is None:
hostOS = subprocess.Popen(['uname'], stdout=subprocess.PIPE).stdout.read().decode('utf-8').strip('\n')
if str(hostOS.lower()).startswith("cygwin"):
return "CYGWIN"
if str(hostOS.lower()).startswith('linux'):
return "Linux"
else:
retVal, output, err = self.runCommand(host, node, "uname")
#out = self.runCommand(host, node, "uname", printOut=True)
if not retVal:
return err
self.logger.debug("command output: " + output)
if len(err) == 0:
if str(output.lower()).startswith("cygwin"):
return "CYGWIN"
if str(output.lower()).startswith("linux"):
return "Linux"
return str(output.lower())
else:
return err
def connectAll(self, reconnect=False, disconnect=False):
threads = []
for car in self.getHosts():
for node in self.getNodes(car):
if reconnect:
self.disconnectHost(car, node)
if self._isNodeForVendor(car, node, "cn"):
# self.h.data[car]["nodes"][node]["vendor"] == "cn":
self.logger.debug(__name__ + ": Attempting to connect to " + car + " node " + node)
# self._connect(car, node)
threads.append(
threading.Thread(target=self._connect, args=(car, node, disconnect)))
threads[-1].start()
for t in threads:
t.join()
def disconnectAll(self, updateStatus=True):
for car in self.getHosts():
for node in self.getNodes(car):
self.disconnectHost(car, node, updateStatus)
def getAllConnectionState(self):
for car in self.hosts:
for node in self.hosts[car]["nodes"]:
self.logger.info ("[" + self._getRemoteIndex(car, node) + "] ", end='')
if self.isConnected(car, node):
state = self.CONNECTED
self.status.writeStatus(car, node, "status", state)
else:
state = self.NOTCONNECTED
self.status.writeStatus(car, node, "status", state)
self._updateACCStatus(car, node)
def connectHost(self, car, node, force=False, disconnect=False):
stat = statusHandler(self.statusFile)
if force:
self.disconnectHost(car, node)
sleep(5)
return self._connect(car, node, disconnect)
def disconnectHost(self, car, node, updateStatus=True):
return self._disconnect(car, node, updateStatus)
# def getConnectionState(self, car, node):
# if self.isConnected(car, node):
# return True
# else:
# return False
def _isRemoteIndexExists(self, car, node):
if self._getRemoteIndex(car, node) in self.remote.keys():
return True
else:
return False
def isConnected(self, car, node):
"""
syntax: isConnected(car, node)
arguments:
car: the car id as specified in the hosts json file
node: the node belonging to the car as specified in the hosts json
file
return value:
boolean:
if true, the node is connected
if false, the node is not connected
"""
if self._isRemoteIndexExists(car, node):
if self.remote[self._getRemoteIndex(car, node)].isConnected():
return True
else:
self.remote[self._getRemoteIndex(car, node)].__del__()
del self.remote[self._getRemoteIndex(car, node)]
return False
else:
return False
def isNodeInHost(self, car, node):
if node in self.getNodes(car):
return True
else:
return False
#TODO
def __updateVendorNodeStatus__(self, car, node, vendor, gwNode="SMM"):
(okay, value) = self.isVendorNodeAlive(car, node, vendor)
if (okay):
self.status.writeStatus(car, node, "alive", self.OK)
if self.getNodeParamValue(car, node, "ssh") == "true":
# if self.getNodeParamValue(car, node, "u_connected") == self.CONNECTED:
# apn = "host-us"
# elif self.getNodeParamValue(car, node, "c_connected") == self.CONNECTED:
# apn = "host-can"
# else:
# return
for apn in self.apnList:
print("apn is", apn)
ip = self.getHostIP(car, apn=apn)
port = self.getNodeParamValue(car, node, "port")
print ("car is",car, "node is", node)
print ("ip and port",ip, port)
if ip != "" and port != "":
if not self.nc(ip, port):
self.status.writeStatus(car, node, self.apnList[apn][1], self.NOTCONNECTED)
continue
else:
self.status.writeStatus(car, node, self.apnList[apn][1], self.CONNECTED)
# ip = self.getHostIP(car, apn=apn)
# port = self.getNodeParamValue(car, node, "port")
# if ip != "" and port != "":
# if not self.nc(ip, port):
# self.status.writeStatus(car, node, self.apnList[apn][1], self.NOTCONNECTED)
# else:
# self.status.writeStatus(car, node, self.apnList[apn][1], self.CONNECTED)
else:
if (value) == "":
if self.isConnected(car, gwNode):
self.status.writeStatus(car, node, "alive", self.NOK)
else:
self.status.writeStatus(car, node, "alive", self.UNKNOWN)
else:
self.status.writeStatus(car, node, "alive", self.UNKNOWN)
def updateAllVendorNodesStatus(self, vendor, gwNode="SMM"):
threads = []
try:
for car in self.getHosts():
for node in self.getVendorNodes(vendor):
if not self.isNodeInHost(car, node) or \
not self._isNodeForVendor(car, node, vendor):
continue
# self.__updateAllVendorNodesStatus__(car, node, vendor)
threads.append(
threading.Thread(target=self.__updateVendorNodeStatus__,
args=(car, node, vendor)
)
)
threads[-1].start()
while threading.active_count() >= maxThread:
sleep(5)
# for t in threads:
# t.start()
# sleep(10)
# for t in threads:
# t.join()
# finally:
# threadLimiter.release()
except Exception as e:
self.logger.error("Unable to start thread {}".format(e))
def __updateACCNodeStatus__(self, car, node):
for apn in self.apnList:
if self.isACCNodeAlive(car, node, apn):
self.logger.info(car + "[" + node + "] is " + self.apnList[apn][0])
self.status.writeStatus(car, node, self.apnList[apn][0], self.OK)
else:
if self.getHostIP(car, apn=apn) == "NA":
self.status.writeStatus(car, node, self.apnList[apn][0], self.UNKNOWN)
else:
self.logger.info(car + "[" + node + "] is not " + self.apnList[apn][0])
self.status.writeStatus(car, node, self.apnList[apn][0], self.NOK)
def updateAllACCNodeStatus(self, vendor):
threads = []
for car in self.getHosts():
self.logger.debug('updating car ' + car)
for node in self.getNodes(car):
self.logger.info('checking node ' + car + "[" + node + "]")
if not self._isNodeForVendor(car, node, vendor):
self.logger.debug('node not in ' + vendor)
continue
# self.__updateAllACCNodeStatus__(car, node)
threads.append(
threading.Thread(target=self.__updateACCNodeStatus__, args=(car, node))
)
for t in threads:
t.start()
for t in threads:
t.join()
def updateNodeStatus(self, car, node):
if not self.isNodeActive(car, node):
return
if self._isNodeForVendor(car, node, 'cn'):
# self._connect(car, node, updateStatus=True)
# if self.nc(self.getHostIP(car), self.getHostNodePort(car, node)):
# self.status.writeStatus(car, node, "connected", self.OK)
# else:
# self.status.writeStatus(car, node, "connected", self.NOK)
self.__updateACCNodeStatus__(car, node)
else:
v = self.getVendorName(car, node)
if v in self.vendorList:
self.__updateVendorNodeStatus__(car, node, v)
else:
return
def updateCarStatus(self, car):
if not self.isHostActive(car):
return
result = self.CONNECTED
if not self.isConnected(car, "SMM"):
self._connect(car, "SMM", updateStatus=True, stayConn=True)
# if result == self.CONNECTED:
# for node in self.getNodes(car):
# self.updateNodeStatus(car, node)
# else:
# self.logger.error ("Unable to connect to " + car + "[SMM].")
for node in self.getNodes(car):
if node in ["TGMS", "Gage/RPMS", "RQMS", "LOCD/GIS"]:
self.status.writeStatus(car, node, "u_connected", "false")
self.status.writeStatus(car, node, "c_connected", "false")
self.updateNodeStatus(car, node)
def ping(self, ip, car=None, gwNode="SMM"):
# if car is None:
# theOS = self._getOS()
# else:
# theOS = self._getOS(host=car, node=gwNode)
theOS = "Linux"
if theOS == "Linux":
cmdPing = "ping -c2 -w1 "
elif theOS == "CYGWIN":
cmdPing = "ping -n 2 "
else:
self.logger.error("Unknown operating system: " + theOS + " for car " + car + " gwNode is " + gwNode)
return False, self.UNKNOWN
if car is None:
self.logger.debug("Trying to ping " + ip)
ret = os.system(cmdPing + ip + " > /dev/null")
if ret != 0:
return False, ""
else:
return True, ""
else:
self.logger.debug("Trying to ping " + ip + " in car " + car)
# if self.connectHost(car, gwNode):
if self._connect(car, gwNode, stayConn=True, updateStatus=True) == self.CONNECTED:
ret = self.runCommand(car, gwNode, cmdPing + ip, FalseIf=[" 100% packet loss"])
if ret[0]:
return True, ""
else:
if ret[2] == "noConn":
self.logger.error("ping failed because connection to car " + \
car + "[" + gwNode + "] is not connected.")
return False, ""
else:
return False, self.UNKNOWN
def nc(self, ip, port, car=None):
if car is not None:
# TODO
return False
else:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
s.connect((ip, int(port)))
s.shutdown(2)
return True
except:
return False
# s.connect((self.hosts[car][self.defaultConn], int(self.hosts[car]["nodes"][node]["port"])))
def runCommand2(self, car, node, command, TrueIf=[], FalseIf=[], printOut=False):
def _returnVal(output, err, retVal):
if printOut:
self.logger.debug("returning output")
return output.decode('utf-8'), err
else:
return retVal
if not self.connectHost(car, node):
self.logger.error("Unable to connect to host: " + car + "[" + node + "].")
return False
ip = self.getConfigValue(car, self.defaultConn)
self.logger.debug("ip address for " + car + "[" + node +"] is " + ip)
if ip is None or ip == "TBD":
self.logger.info("ip address for " + car + "[" + node +"] is None or TBD")
return False
if not self.isConnected(car, node):
self.logger.info(car + "[" + node + "] is not connected")
return False
output, err = self.remote[self._getRemoteIndex(car, node)].run(command)
if len(err) != 0:
return _returnVal(output, err, False)
falseLink = []
trueLink = []
if FalseIf != []:
for pat in FalseIf:
if pat in output.decode("ascii"):
falseLink.append(pat)
self.logger.debug("falseList: {}".format(' '.join(falseLink)))
if len(falseLink) != 0:
return _returnVal(output, err, False)
if TrueIf != []:
for pat in TrueIf:
if pat not in output.decode("ascii"):
trueLink.append(pat)
self.logger.debug("trueList: {}".format(' '.join(trueLink)))
if len(trueLink) != 0:
return _returnVal(output, err, False)
return _returnVal(output, err, True)
def runCommand(self, car, node, command, TrueIf=[], FalseIf=[], gwNode="SMM"):
'''
return values: bool, output, err
'''
# if not self.connectHost(car, node):
# self.logger.error("Unable to connect to host: " + car + "[" + node + "].")
# return False, "", ""
err = ""
output = ""
ip = self.getConfigValue(car, self.defaultConn)
self.logger.debug("ip address for " + car + "[" + node +"] is " + ip)
if ip is None or ip == "TBD":
self.logger.info("ip address for " + car + "[" + node +"] is None or TBD")
return False, "", ""
if not self.isConnected(car, node):
self.logger.info(car + "[" + node + "] is not connected")
return False, "", "noConn"
# # if self.connectHost(car, gwNode):
# # output, err = self.remote[self._getRemoteIndex(car, node)].run(command)
# # else:
# # return False, "", "noConn"
output, err = self.remote[self._getRemoteIndex(car, node)].run(command)
if len(err) != 0:
return False, output.decode('utf-8'), err
if output == "":
return False, "", self.noOutput
falseLink = []
trueLink = []
if FalseIf != []:
for pat in FalseIf:
if pat in output.decode("ascii"):
falseLink.append(pat)
self.logger.debug("falseList: {}".format(' '.join(falseLink)))
if len(falseLink) != 0:
return False, output.decode("utf-8"), err
if TrueIf != []:
for pat in TrueIf:
if pat not in output.decode("ascii"):
trueLink.append(pat)
self.logger.debug("trueList: {}".format(' '.join(trueLink)))
if len(trueLink) != 0:
return False, output.decode("utf-8"), err
return True, output.decode("utf-8"), err
def isVendorNodeExistsForCar(self, car, vendor, node):
''' This method verifies if the node for the car exists in
the json definition
'''
# check to make sure the vendor/node definition exists in json definition
if not self.isVendorNodeExists(vendor=vendor, node=node):
return False
if self.isNodeInHost(car, node):
return True
else:
return False
def isVendorNodeAlive(self, car, node, vendor, gwNode="SMM"):
ip = self.getVendorNodeIP(node, vendor)
self.logger.debug("ip address for " + car + "[" + node +"] is " + ip)
if ip is None or ip == "NA":
return False, ""
if not self.isVendorNodeExistsForCar(car, vendor, node):
self.logger.warning ("Vendor node " + vendor + "[" + node + "] does not exist for car: " + car)
return False, ""
return self.ping(ip=ip, car=car, gwNode=gwNode)
def isACCNodeAlive(self, car, node, apn="host-us"):
self.logger.debug("running nc() for " + car + "[" + node +"]")
ip = self.getHostIP(car, apn=apn)
port = self.getHostNodePort(car, node)
if ip != "" and port != "":
return self.nc(ip, port)
else:
self.logger.error("ip address or port for car " + car + "[" + node +"] are not found")
self.logger.error("ip address: " + ip)
self.logger.error("port " + port)
return False
def checkNetwork(self, car):
connections = [self.defaultConn, "host-can", "wifi"]
for conn in connections:
if self.ping(self.hosts[car]["network"][conn]):
self.status.writeStatus(car, "network", conn, self.ALIVE)
else:
self.status.writeStatus(car, "network", conn, self.DEAD)
def printOutput(self, node, command, car=None):
pass
<file_sep>import json
from collections import OrderedDict
from sys import exit
import logging
mod_name = 'ATIC.' + __name__
mod_logger = logging.getLogger(mod_name)
class readJson(object):
def __init__(self, dataFile):
self.logger = logging.getLogger(mod_name + ".readJson")
self.data = self._readJson(dataFile)
self.dataFile = dataFile
def _readJson(self, jsonFile):
try:
with open(jsonFile, "r") as s:
return json.load(s, object_pairs_hook=OrderedDict)
except FileNotFoundError:
self.logger.error("File " + jsonFile + " not found.")
exit(1)
def getKeys(self, data, exclude=None):
if isinstance(data, dict):
return [x for x in data.keys() if x != exclude]
else:
self.logger.debug("Nothing is returned")
return []
def safeGet(self, element, *keys):
"""
Check if *keys (nested) exists in `element` (dict).
"""
if not isinstance(element, dict):
raise AttributeError('safeGet() expects dict as first argument.')
if len(keys) == 0:
raise AttributeError('safeGet() expects at least two arguments, ' +
' one given.')
_element = element
for key in keys:
try:
_element = _element[key]
except KeyError:
self.logger.info("Nothing is returned")
return ""
return _element
def read(self):
try:
self.data = self._readJson(self.dataFile)
return True
except:
return False
def write(self):
try:
with open (self.dataFile, 'w') as outfile:
json.dump(self.data, outfile, indent=4)
return True
except:
return False
class Hosts(readJson):
def __init__(self, hostFile="hosts.json"):
self.logger = logging.getLogger(mod_name + ".Hosts")
readJson.__init__(self, hostFile)
self.hosts = self.data
# class constants
self.default = "default"
self.configParamType = "config"
self.nodeParamType = "nodes"
# self.setConfigDefault()
# self.setNodeDefault()
def _setDefault(self):
self.setConfigDefault()
self.setNodeDefault()
def getHosts(self):
return self.getKeys(self.hosts, self.default)
def getConfigParams(self, host):
""" Returns the list of parameters available for a given host """
return self.safeGet(self.hosts, host, self.configParamType).keys()
def getNodes(self, host):
""" Returns the list of nodes for a given host """
if self.safeGet(self.hosts, host, self.nodeParamType):
return self.safeGet(self.hosts, host, self.nodeParamType).keys()
else:
return ""
def getConfigValue(self, host, param):
""" Returns the value of the parameter for a given host. """
return self.safeGet(self.hosts, host, self.configParamType, param)
def getNodeParams(self, host, node):
""" Returns the list of parameter for a given node and host """
if self.safeGet(self.hosts, host, self.nodeParamType, node):
return self.safeGet(self.hosts, host, self.nodeParamType, node).keys()
else:
return ""
def getNodeParamValue(self, host, node, param):
""" Returns the value of a given parameter for a given node for a
given Host """
return self.safeGet(self.hosts, host, self.nodeParamType, node, param)
def getHostIP(self, host, apn="host-us"):
return self.safeGet(self.hosts, host, self.configParamType, apn)
def getHostNodePort(self, host, node):
return self.safeGet(self.hosts, host, self.nodeParamType, node, "port")
def setHostConfigParamValue(self, car, param, value, writeFile=False):
""" This method will update the dictionary of the parameter in config
section of data """
self.hosts[car][self.configParamType][param]=value
if writeFile:
self.write()
def setHostNodeParamValue(self, car, node, param, value, writeFile=False):
self.hosts[car][self.nodeParamType][node][param]=value
if writeFile:
self.write()
def setConfigDefault(self):
for host in self.getHosts():
for param in self.getConfigParams('default'):
if param not in self.getConfigParams(host):
self.setHostConfigParamValue(host, param, self.getConfigValue('default', param))
def setNodeDefault(self):
for dNode in self.getNodes('default'):
for host in self.getHosts():
if dNode in self.getNodes(host):
for param in self.getNodeParams('default', dNode):
if param not in self.getNodeParams(host, dNode):
self.setHostNodeParamValue(host, dNode, param, self.getNodeParamValue('default', dNode, param))
def isNodeActive(self, host, node):
if self.getNodeParamValue(host, node, "active").lower() == "true":
return True
else:
return False
def isHostActive(self, host):
if self.getConfigValue(host, "active").lower() == "true":
return True
else:
return False
def getVendorName(self, host, node):
return self.getNodeParamValue(host, node, "vendor").upper()
class Vendors(readJson):
def __init__(self, vendorFile="vendorNodes.json"):
self.logger = logging.getLogger(mod_name + ".Vendors")
readJson.__init__(self, vendorFile)
self.vendors = self.data
# class constants
self.nodeParamType = "nodes"
self.default = "default"
def getVendors(self):
return self.getKeys(self.vendors)
def getVendorNodes(self, vendor):
return self.safeGet(self.vendors, vendor, self.nodeParamType).keys()
def getVendorNodeIP(self, node, vendor):
if self.isVendorExists(vendor):
if self.isVendorNodeExists(vendor=vendor, node=node):
return self.safeGet(self.vendors, vendor, self.nodeParamType, node)
else:
return ""
return ""
def isVendorExists(self, vendor):
"""This method checks to make see if the Vendor specified exists in
json file. """
if vendor in self.getVendors():
return True
else:
return False
def isVendorNodeExists(self, vendor, node):
""" This method checks to make see if the node exist for Vendor specified
json file.
It will also check to make sure the vendor specified exists
"""
if self.isVendorExists(vendor):
if node in self.getVendorNodes(vendor):
self.logger.debug(vendor + "[" + node + "] exists")
return True
else:
self.logger.debug(vendor + "[" + node + "] does not exist")
return False
else:
return False
class Status(Hosts):
def __init__(self, statusFile="status.json"):
self.logger = logging.getLogger(mod_name + ".Status")
Hosts.__init__(self, statusFile)
self.status = self.data
self.statusFile = statusFile
# class constants
self.default = "default"
self.configParamType = "config"
self.nodeParamType = "nodes"
def setNodeParamValue(self, car, node, param, value):
if self.safeGet(self.status, car, self.nodeParamType, node, param):
self.status[car][self.nodeParamType][node][param]=value
self.write()
return True
else:
return False
<file_sep>import paramiko
import socket
import logging
import logger_setup
import time
mod_name = 'ATIC.paramikoWrapper'
logger = logging.getLogger(mod_name)
class KeepalivesFilter (object):
def filter(self, record):
return record.msg.find('<EMAIL>') < 0
paramiko.util.get_logger('paramiko.transport').addFilter(KeepalivesFilter())
def recv_all(channel):
while not channel.recv_ready():
time.sleep(0.1)
stdout = ''
while channel.recv_ready():
stdout = channel.recv(1024)
return stdout
class paramikoWrapper:
def __init__(self, host, user, password, port=22):
self.logger = logging.getLogger(mod_name + ".1")
self.host = host
self.port = port
count = 1
maxRetry = 3
success = False
while count <= maxRetry:
try:
self.logger.info("Try # " + str(count) + " to connect to " + host + ":" + str(port))
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(host, username=user, password=<PASSWORD>, port=int(port), timeout=10)
self.logger.info ("[" + host + ":" + str(port) + "] - connected")
self.channel = self.client.invoke_shell()
break
# self.channel = self.client.invoke_shell()
# self.stdin = self.channel.makefile('wb')
# self.stdout = self.channel.makefile('r')
# except (TimeoutError, socket.timeout, paramiko.ssh_exception.NoValidConnectionsError, paramiko.ssh_exception.SSHException):
# self.logger.info ("[" + host + ":" + str(port) + "] - not connected")
except paramiko.AuthenticationException:
self.logger.error ("[" + host + ":" + str(port) + "] - bad password")
break
except Exception as ex:
template = "An exception of type {0} occured. Arguments: \n {1!r}"
message = template.format(type(ex).__name__, ex.args)
self.logger.error (message)
count += 1
time.sleep(5)
if count >= maxRetry:
self.logger.error ("[" + host + ":" + str(port) + "] - not connected")
self.logger.error ("Connection to " + host + " failed.")
# else:
# print ("[" + host + ":" + str(port) + "] - connected")
# # status.writeStatus(self.car, self.node, "status", "online")
def __del__(self):
self.client.close()
self.logger.info ("[" + self.host + ":" + str(self.port) + "] closed.")
# status.writeStatus(self.car, self.node, "status", "offline")
def isConnected(self):
"""
This will check if the connection is still availlable.
Return (bool) : True if it's still alive, False otherwise.
"""
try:
# read prompt
# recv_all(channel)
self.channel.send('pwd\n')
stdout = recv_all(self.channel)
# self.client.exec_command('pwd', timeout=5)
return True
except Exception as ex:
# print ("Connection lost : %s" % e)
# return False
template = "An exception of type {0} occured. Arguments: \n {1!r}"
message = template.format(type(ex).__name__, ex.args)
self.logger.debug(message)
# raise
return False
def run(self, command):
self.logger.debug("executing command: " + command)
# channel = self.client.invoke_shell()
# read prompt
# recv_all(channel)
self.channel.send(command + '\n')
stdout = recv_all(self.channel)
# self.stdin, self.stdout, self.stderr = self.client.exec_command(command)
# outval = self.stdout.read()
# errval = self.stderr.read()
# for line in self.stdout.read().splitlines():
# print('... ' + line.strip('\n'))
return stdout, ""
<file_sep>FROM python:2.7
COPY mock_F5.py .
COPY MockSSH.py .
COPY requirements.txt .
CMD apt update
RUN pip install -r requirements.txt
CMD ["python", "mock_F5.py"]
<file_sep>import json
import logging
from status import Status
mod_name = 'ATIC.' + __name__
mod_logger = logging.getLogger(mod_name)
class statusHandler:
def __init__(self, statusFile='status.json', logFile="alive.log"):
self.logger = logging.getLogger(mod_name + ".1")
self.statusFile = statusFile
# with open (statusFile, 'r') as statusfile:
# self.status = json.load(statusfile)
self.stat = Status(statusFile)
#### CONST ###
self.UNDEF = "UNDEF"
def _refresh(self):
# with open(self.statusFile, 'r') as outfile:
# self.stat.status = json.load(outfile)
self.stat._readJson(self.statusFile)
def readStatus(self, car, node, param):
# if param in self.stat.status[car]["nodes"][node].keys():
if param in self.stat.getNodeParams(car, node):
# if param in self.stat.getNodeParams(car, node):
self._refresh()
self.logger.debug("status of [" + car + "][" + node + "][" + param + "] is " + self.stat.status[car]["nodes"][node][param])
# return self.stat.status[car]["nodes"][node][param]
return self.stat.getNodeParamValue(car, node, param)
else:
self.logger.debug("status of [" + car + "][" + node + "][" + param + "] is " + self.UNDEF)
return self.UNDEF
def writeStatus(self, car, node, param, status):
# if node in self.stat.status[car]["nodes"].keys(): # verify if node exist
self.logger.debug("params passed: " + car + " " + node + " " + param + " " + status)
if node in self.stat.getNodes(car):
#self.logger.debug ("param is " + param + " for " , self.stat.status[car]["nodes"][node])
self.logger.debug ("param is " + param + " for " + node)
# if param in self.stat.status[car]["nodes"][node].keys(): # verify if the parameter exists
if param in self.stat.getNodeParams(car, node):
self.logger.debug("self.stat.status[" + car + "][" + node + "] is good")
# if self.stat.status[car]["nodes"][node][param] != status: # update the status if the status is different.
if self.stat.getNodeParamValue(car, node, param) != status:
self.logger.info("Updating " + car + "-" + node + " from " + self.stat.status[car]["nodes"][node][param] + " => " + status)
self.stat.status[car]["nodes"][node][param] = status
with open (self.statusFile, 'w') as outfile:
json.dump(self.stat.status, outfile, indent=4)
return True
else:
return False
else:
return False
<file_sep># test
This is a test
Adding another line
| 1cc6104b05f33bb13dbcffc4db55f53b414a1062 | [
"JavaScript",
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 19 | JavaScript | lmckiwo/test | 7a1e585e482db48ec54f8e0750c4f98252e1af00 | 35dbbd68f12400019a22a08f15cf2a8407537217 |
refs/heads/main | <file_sep>#ifndef OBJECT_MANAGER_H
#define OBJECT_MANAGER_H
#include "primitive.h"
class ObjectManager {
private:
Material* mat;
std::vector< Primitive* > obj_list;
public:
ObjectManager(){}
~ObjectManager(){}
void add_object(Primitive* obj);
void add_material(Material* _mat);
void instantiate_sphere(const Point3f& _c, const float& _r, Material* mat);
Material* get_material(void);
std::vector< Primitive* >& get_object_list(void);
};
#endif
<file_sep># Paths
SRC = ./src
BIN = ./bin
OBJ = ./obj
CORE = $(SRC)/core
EXT = $(SRC)/ext
MAIN = $(SRC)/main
UTILS = $(SRC)/utils
CXXOPTS = $(EXT)/cxxopts
TINYXML = $(EXT)/tinyxml2
WARNS = -pedantic -Wall -Wextra -Wcast-align -Wcast-qual \
-Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 \
-Winit-self -Wlogical-op -Wmissing-declarations \
-Wmissing-include-dirs -Wnoexcept -Wold-style-cast \
-Woverloaded-virtual -Wredundant-decls -Wsign-conversion \
-Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 \
-Wswitch-default -Wundef -Wno-unused-variable
# Other
FLAGS = $(NO_WARNS_FLAGS) $(WARNS)
NO_WARNS_FLAGS = -g -std=c++17
INC := -I $(UTILS) -I $(EXT) -I $(CORE) -I $(MAIN) -isystem $(TINYXML) -isystem $(CXXOPTS)
OBJS = $(OBJ)/error.o $(OBJ)/math.o $(OBJ)/api.o $(OBJ)/background.o $(OBJ)/camera.o $(OBJ)/film.o $(OBJ)/parser.o $(OBJ)/vec3.o $(OBJ)/tinyxml2.o \
$(OBJ)/ray.o $(OBJ)/sphere.o $(OBJ)/object_manager.o
all: $(BIN)/rt3.out
$(BIN)/rt3.out: $(OBJS) $(MAIN)/rt3.cpp | $(BIN)
g++ $(MAIN)/rt3.cpp $(OBJS) -o $(BIN)/rt3.out $(INC) $(FLAGS)
$(OBJ)/math.o: $(UTILS)/math.h $(UTILS)/math.cpp | $(OBJ)
g++ -c -o $(OBJ)/math.o $(UTILS)/math.cpp $(INC) $(FLAGS)
$(OBJ)/api.o: $(CORE)/camera.h $(CORE)/api.h $(CORE)/api.cpp | $(OBJ)
g++ -c -o $(OBJ)/api.o $(CORE)/api.cpp $(INC) $(FLAGS)
$(OBJ)/background.o: $(CORE)/background.h $(CORE)/background.cpp | $(OBJ)
g++ -c -o $(OBJ)/background.o $(CORE)/background.cpp $(INC) $(FLAGS)
$(OBJ)/camera.o: $(CORE)/ray.h $(CORE)/camera.h $(CORE)/camera.cpp | $(OBJ)
g++ -c -o $(OBJ)/camera.o $(CORE)/camera.cpp $(INC) $(FLAGS)
$(OBJ)/error.o: $(UTILS)/error.h $(UTILS)/error.cpp | $(OBJ)
g++ -c -o $(OBJ)/error.o $(UTILS)/error.cpp $(INC) $(FLAGS)
$(OBJ)/film.o: $(CORE)/film.h $(CORE)/film.cpp | $(OBJ)
g++ -c -o $(OBJ)/film.o $(CORE)/film.cpp $(INC) $(FLAGS)
$(OBJ)/parser.o: $(CORE)/parser.h $(CORE)/parser.cpp | $(OBJ)
g++ -c -o $(OBJ)/parser.o $(CORE)/parser.cpp $(INC) $(FLAGS)
$(OBJ)/vec3.o: $(CORE)/vec3.h $(CORE)/vec3.cpp | $(OBJ)
g++ -c -o $(OBJ)/vec3.o $(CORE)/vec3.cpp $(INC) $(FLAGS)
$(OBJ)/ray.o: $(CORE)/ray.h $(CORE)/ray.cpp | $(OBJ)
g++ -c -o $(OBJ)/ray.o $(CORE)/ray.cpp $(INC) $(FLAGS)
$(OBJ)/sphere.o: $(CORE)/sphere.h $(CORE)/sphere.cpp | $(OBJ)
g++ -c -o $(OBJ)/sphere.o $(CORE)/sphere.cpp $(INC) $(FLAGS)
$(OBJ)/object_manager.o: $(CORE)/object_manager.h $(CORE)/object_manager.cpp | $(OBJ)
g++ -c -o $(OBJ)/object_manager.o $(CORE)/object_manager.cpp $(INC) $(FLAGS)
$(OBJ)/tinyxml2.o: $(TINYXML)/tinyxml2.h $(TINYXML)/tinyxml2.cpp | $(OBJ)
g++ -c -o $(OBJ)/tinyxml2.o $(TINYXML)/tinyxml2.cpp $(NO_WARNS_FLAGS)
$(OBJ):
mkdir -p $(OBJ)
$(BIN):
mkdir -p $(BIN)
# Clean project
clean:
@# @ symbol at beginning indicates that it will not be printed
@if [ "$$(ls -A $(OBJ))" ]; then \
rm -rf $(OBJ); \
fi
@if [ "$$(ls -A $(BIN))" ]; then \
rm -rf $(BIN); \
fi
<file_sep>#ifndef SCENE_H
#define SCENE_H
#include "background.h"
#include "primitive.h"
#include "ray.h"
class Scene {
public:
Primitive* aggregate;
Background* background;
Scene();
bool intersect( const Ray& r, Surfel *isect );
bool intersect_p( const Ray& r );
};
#endif<file_sep>#ifndef BACKGROUND_H
#define BACKGROUND_H
#include <functional>
#include "vec3.h"
using std::function;
class Background {
private:
function<ColorXYZ(Point2f)> sampler;
public:
Background();
Background(ColorXYZ color);
Background(ColorXYZ bl, ColorXYZ tl, ColorXYZ tr, ColorXYZ br);
ColorXYZ sample(Point2f);
};
#endif
<file_sep>#ifndef MATH_TEMPLATE_IMPL_H
#define MATH_TEMPLATE_IMPL_H
#include "math.h"
template <class T>
function<T(Point2f)> bilinear_interpolation(Point2f tl, Point2f bl, Point2f br, Point2f tr, T val_tl, T val_bl, T val_br, T val_tr)
{
return [=](Point2f p)
{
return (val_bl * (tr[0] - p[0]) * (tl[1] - p[1]) + val_br * (p[0] - bl[0]) * (tr[1] - p[1]) + val_tl * (br[0] - p[0]) * (p[1] - br[1]) + val_tr * (p[0] - bl[0]) * (p[1] - br[1])) / ((br[0] - bl[0]) * (tr[1] - br[1]));
};
}
#endif
<file_sep>#include <limits>
#include "aggregate_primitive.h"
#include "error.h"
Material* AggregatePrimitive::get_material() {
RT3_ERROR("Aggregates are not allowed to have materials associated with them.");
return nullptr;
}
void AggregatePrimitive::add_primitive(Primitive* primitive) {
primitives.push_back(primitive);
}
bool AggregatePrimitive::intersect( const Ray& ray, Surfel *sf ) {
long unsigned int size = primitives.size();
int best_idx = -1;
Surfel* current = new Surfel[size];
float best_t;
for (long unsigned int i=0; i<size; i++) {
if (primitives[i]->intersect(ray, ¤t[i])) {
if (best_idx == -1 || current[i].time < best_t) {
best_idx = i;
best_t = current[i].time;
}
}
}
if (best_idx == -1) return false;
sf->copy_from(¤t[best_idx]);
delete[] current;
return true;
}
bool AggregatePrimitive::intersect_p( const Ray& ray) {
for (Primitive* p: primitives) {
if (p->intersect_p(ray)) {
return true;
}
}
return false;
}
<file_sep>#ifndef SURFEL_H
#define SURFEL_H
#include "vec3.h"
#include "primitive.h"
class Surfel {
public:
Point3f p; //!< Contact point.
Vector3f n; //!< The surface normal.
Vector3f wo; //!< Outgoing direction of light, which is -ray.
float time; //!< Time of contact.
Point2f uv; //!< Parametric coordinate (u,v) of the hit surface.
Primitive *primitive = nullptr; //!< Pointer to the primitive.
Surfel( const Point3f& _p, const Vector3f& _n, const Vector3f& _wo, float _time,
const Point2f& _uv, Primitive *pri ) : p{_p}, n{_n}, wo{_wo},
time{_time}, uv{_uv}, primitive{pri} {/* empty */};
Surfel() { }
void copy_from(Surfel* other);
};
#endif<file_sep>#ifndef IMAGE_H
#define IMAGE_H
#include <fstream>
#include <functional>
#include <iostream>
#include "math.h"
#include "vec3.h"
using std::function;
using std::ostream;
using std::ofstream;
struct RgbColor
{
int r;
int g;
int b;
friend ostream &operator<<(ostream &os, const RgbColor &color);
friend RgbColor operator*(const RgbColor& color, const int& i);
friend RgbColor operator/(const RgbColor& color, const int& i);
friend RgbColor operator+(const RgbColor& color1, const RgbColor& color2);
};
struct Pixel
{
RgbColor color;
Point2f point;
int x() const;
int y() const;
friend ostream &operator<<(ostream &os, const Pixel &pixel);
};
class PpmImage {
private:
int width;
int height;
int max_color_value;
Pixel** pixels;
public:
PpmImage(int width, int height, int max_color_value, Pixel tl, Pixel bl, Pixel br, Pixel tr);
~PpmImage();
void write_to_stream(ofstream& stream);
};
#endif<file_sep>#include "../utils/image.h"
#include "../core/api.h"
#include "rt3.h"
#include <sstream>
#include <cxxopts.hpp>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
using std::vector;
RunningOptions parse_running_options(int argc, char * argv[]) {
try {
cxxopts::Options options(argv[0], "A simple ray-tracer");
options
.custom_help("[<options>]")
.positional_help("<input_scene_file>")
.show_positional_help();
options.add_options()
("h,help", "Print this help text")
("c,cropwindow", "Specify an image cropping window", cxxopts::value<std::vector<int>>(), "<x0,x1,y0,y1>")
("q,quick", "Reduces quality parameters to render image quickly", cxxopts::value<bool>()->default_value("false")->implicit_value("true"))
("o,outfile", "Write the rendered image to <filename>", cxxopts::value<std::string>(), "<filename>")
("input_scene_file", "Scene file to be parsed", cxxopts::value<std::string>())
;
options.parse_positional({"input_scene_file"});
auto result = options.parse(argc, argv);
RunningOptions running_opts;
if (result.count("help"))
{
std::cout << options.help() << std::endl;
exit(0);
}
if (result.count("cropwindow"))
{
vector<int> window_read = result["cropwindow"].as<vector<int>>();
if (window_read.size() != 4) {
cout << "Crop window must be four integers" << endl;
exit(0);
}
for (float coord: window_read) {
if (coord < 0) {
cout << "Crop window must be four non-negative integers" << endl;
exit(0);
}
}
running_opts.crop_window[0][0] = window_read[0];
running_opts.crop_window[1][0] = window_read[1];
running_opts.crop_window[0][1] = window_read[2];
running_opts.crop_window[1][1] = window_read[3];
}
running_opts.quick_render = result["quick"].as<bool>();
if (result.count("outfile"))
{
running_opts.outfile = result["outfile"].as<string>();
}
running_opts.scene_filename = result["input_scene_file"].as<string>();
return running_opts;
}
catch (const cxxopts::OptionException& e)
{
std::cout << "ERROR: " << e.what() << ". Run the program with --help to see the right usage." << std::endl;
exit(1);
}
}
int main( int argc, char * argv[] ) {
// What is logged with clog won't actually show up
std::clog.setstate(std::ios_base::failbit);
RunningOptions opt = parse_running_options(argc, argv);
// Start API
API::init_engine(opt);
API::run();
API::clean_up();
return 0;
}<file_sep>#ifndef API_H
#define API_H
#include <string>
#include "parser.h"
#include "../utils/image.h"
#include "vec3.h"
#include "paramset.h"
#include "camera.h"
#include "background.h"
#include "rt3.h"
class API {
private:
static Camera m_camera;
static Background m_background;
static void render( void );
public:
static RunningOptions run_opt;
static void init_engine( const RunningOptions& );
static void run( void );
static void clean_up( void );
static void reset_engine( void );
static void camera( const ParamSet& ps );
static void film( const ParamSet& ps );
static void background( const ParamSet& ps );
static void integrator( const ParamSet& ps );
static void look_at( const ParamSet& ps );
static void world_begin( void );
static void world_end( void );
};
#endif // API_H
<file_sep>#ifndef FILM_H
#define FILM_H
#include <fstream>
#include <string>
#include "vec3.h"
using std::ofstream;
using std::string;
class Film {
private:
ColorXYZ** buffer;
string img_type;
string filename;
void write_to_ppm(ofstream& stream);
public:
int width;
int height;
int max_color_value = 255;
Film();
Film(int width, int height, string img_type, string filename);
void add(Point2i point, ColorXYZ color);
void write_image();
};
#endif
<file_sep>#include <fstream>
#include <iostream>
#include "film.h"
using std::ofstream;
Film::Film() : Film(0, 0, "", "") { }
Film::Film(int width, int height, string img_type, string filename) {
this->width = width;
this->height = height;
this->img_type = img_type;
this->filename = filename;
buffer = new ColorXYZ*[height];
for (int j = 0; j < height; ++j) {
buffer[j] = new ColorXYZ[width];
}
}
void Film::add(Point2i point, ColorXYZ color) {
buffer[point[1]][point[0]] = color;
}
void Film::write_image() {
ofstream output_image;
output_image.open(this->filename);
if (this->img_type == "ppm3") {
write_to_ppm(output_image);
}
}
void Film::write_to_ppm(ofstream& stream) {
stream << "P3\n"
<< width << " " << height << "\n"
<< max_color_value << "\n";
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
auto color = buffer[i][j];
stream << static_cast<int>(color[0]*max_color_value) << " " << static_cast<int>(color[1]*max_color_value) << " " << static_cast<int>(color[2]*max_color_value) << "\n";
}
}
}<file_sep>#include <cmath>
#include "camera.h"
#define PI 3.14159265
LookAt::LookAt(Point3f look_from, Vector3f look_at, Vector3f up): look_from(look_from), look_at(look_at), up(up) { }
CameraFrame::CameraFrame(Point3f e, Vector3f u, Vector3f v, Vector3f w): e(e), u(u), v(v), w(w) { }
Camera::Camera(float l, float r, float b, float t, LookAt* look_at_info): l(l), r(r), b(b), t(t), look_at_info(look_at_info) { }
int Camera::nx() {
return film.width;
}
int Camera::ny() {
return film.height;
}
void Camera::calculate_frame() {
auto gaze = look_at_info->look_at - look_at_info->look_from;
auto w = normalize_vector3f(gaze);
auto cross_up_w = cross_vector3f(look_at_info->up, w);
auto u = normalize_vector3f(cross_up_w);
auto cross_w_u = cross_vector3f(u, w);
auto v = normalize_vector3f(cross_w_u);
frame = new CameraFrame(look_at_info->look_from, u, v, w);
}
Point2f Camera::map_to_screen_space(Point2i& point) {
float u = l + (r - l)*(point[0] + 0.5)/nx();
float v = b + (t - b)*(point[1] + 0.5)/ny();
return {u, v};
}
OrthographicCamera::OrthographicCamera(float l, float r, float b, float t, LookAt* look_at_info): Camera(l, r, b, t, look_at_info) { }
PerspectiveCamera::PerspectiveCamera(float l, float r, float b, float t, LookAt* look_at_info): Camera(l, r, b, t, look_at_info) { }
PerspectiveCamera::PerspectiveCamera(float focal_distance, float aspect_ratio, float fovy, LookAt* look_at_info): Camera(-1.0, -1.0, -1.0, -1.0, look_at_info) {
this->focal_distance = focal_distance;
this->aspect_ratio = aspect_ratio;
this->fovy = fovy;
}
void PerspectiveCamera::set_lrbt_from_xres_yres_if_needed() {
if (fovy < 0.0) return;
auto actual_aspect_ratio = aspect_ratio > 0 ? aspect_ratio : static_cast<float>(nx()) / ny();
auto half_fovy_tan = tan((fovy/2)*PI/180);
auto half_height_screen_space = half_fovy_tan * focal_distance;
l = -actual_aspect_ratio*half_height_screen_space;
r = actual_aspect_ratio*half_height_screen_space;
b = -half_height_screen_space;
t = half_height_screen_space;
}
Ray OrthographicCamera::generate_ray(int x, int y) {
Point2i input_point = {x, y};
auto uv = map_to_screen_space(input_point);
auto u = uv[0];
auto v = uv[1];
auto origin = frame->e + u * frame->u + v * frame->v;
auto direction = frame->w;
return Ray{origin, direction};
}
Ray PerspectiveCamera::generate_ray(int x, int y) {
Point2i input_point = {x, y};
auto uv = map_to_screen_space(input_point);
auto u = uv[0];
auto v = uv[1];
auto origin = frame->e;
auto direction = focal_distance * frame->w + u * frame->u + v * frame->v;
return Ray{origin, direction};
}
<file_sep>#ifndef CAMERA_H
#define CAMERA_H
#include "film.h"
class Camera {
public:
Film film;
Camera();
};
#endif
<file_sep>/*!
* Implementation of XML processing functions.
* @file parser.h
*/
#include "paramset.h"
#include "parser.h"
#include "api.h"
#include "error.h"
#include "vec3.h"
#define real_type float
/// This is the entry function for the parsing process.
void parse( const char* scene_file_name )
{
tinyxml2::XMLDocument xml_doc;
// Load file.
if ( xml_doc.LoadFile( scene_file_name ) != tinyxml2::XML_SUCCESS )
RT3_ERROR( std::string{"The file \""} + scene_file_name + std::string{"\" either is not available OR contains an invalid RT3 scene provided!"} );
// ===============================================
// Get a pointer to the document's root node.
tinyxml2::XMLNode * p_root = xml_doc.FirstChild();
if ( p_root == nullptr )
RT3_ERROR( "Error while trying to find \"RT3\" tag in the scene file." );
// ===============================================
// Get the first-level tag inside the root node.
auto *p_child { p_root->FirstChildElement( ) };
if ( p_child == nullptr)
RT3_ERROR( "No \"children\" tags found inside the \"RT3\" tag. Empty scene file?" );
parse_tags( p_child, /* initial level */ 0 );
}
/// Main loop that handles each possible tag we may find in a RT3 scene file.
void parse_tags( tinyxml2::XMLElement *p_element, int level )
{
// All messages sent to std::clog is for DEBUG purposes.
std::clog << "[parse_tags()]: level is " << level << std::endl;
// Traverse all items on the children's level.
while ( p_element != nullptr )
{
// Convert the attribute name to lowecase before testing it.
auto tag_name = STR_LOWER( p_element->Value() );
clog << "\n"<< setw(level*3) << "" << "***** Tag id is `" << tag_name << "`, at level " << level << std::endl;
// Big switch for each possible RT3 tag type.
if ( tag_name == "camera" )
{
ParamSet ps;
// List of parameters that might be defined inside the camera's tag.
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING , "type" },
// Legacy parameters BEGIN.
// In this legacy version, we specify the cameras location
// manually, instead of defining a transformation matrix.
{ param_type_e::POINT3F , "look_from" },
{ param_type_e::POINT3F , "look_at" },
{ param_type_e::VEC3F , "up" },
{ param_type_e::ARR_REAL , "vpdim" }, // The viewport dimensions defined by the scene
// Legacy parameters END.
{ param_type_e::REAL , "fovy" },
{ param_type_e::REAL , "focal_distance" },
{ param_type_e::REAL , "frame_aspectratio"}, // By default it's calulated from the x/y resolution, but it might be overridden.
{ param_type_e::ARR_REAL, "screen_window" } // Bounds of the film in screen space. [-1,1] along the shorter image axis, and its set proportionally along the longer axis.
};
parse_parameters( p_element, param_list, /* out */&ps );
API::camera( ps );
}
else if ( tag_name == "background" )
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING , "type" },
{ param_type_e::STRING , "filename" }, // Texture file name.
{ param_type_e::STRING , "mapping" }, // Type of mapping required.
{ param_type_e::COLOR , "color" }, // Single color for the entire background.
{ param_type_e::COLOR , "tl" }, // Top-left corner
{ param_type_e::COLOR , "tr" }, // Top-right corner
{ param_type_e::COLOR , "bl" }, // Bottom-left corner
{ param_type_e::COLOR , "br" } // Bottom-right corner
};
parse_parameters( p_element, param_list, /* out */&ps );
API::background( ps );
}
else if ( tag_name == "film" )
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING , "type" },
{ param_type_e::STRING , "filename" },
{ param_type_e::STRING , "img_type" },
{ param_type_e::INT , "x_res" },
{ param_type_e::INT , "y_res" },
{ param_type_e::ARR_REAL , "crop_window" },
{ param_type_e::STRING , "gamma_corrected" } // bool
};
parse_parameters( p_element, param_list, /* out */&ps );
API::film( ps );
}
else if ( tag_name == "integrator" )
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING , "type" },
{ param_type_e::COLOR , "near_color"},
{ param_type_e::COLOR , "far_color" },
{ param_type_e::REAL , "zmin" },
{ param_type_e::REAL , "zmax" },
{ param_type_e::INT , "depth" }
};
parse_parameters( p_element, param_list, /* out */&ps );
API::integrator( ps );
}
else if ( tag_name == "lookat" )
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::POINT3F, "look_from" },
{ param_type_e::POINT3F, "look_at" },
{ param_type_e::VEC3F , "up" }
};
parse_parameters( p_element, param_list, /* out */&ps );
API::look_at( ps );
}
else if ( tag_name == "material")
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING, "type" },
{ param_type_e::COLOR , "color" }
};
parse_parameters( p_element, param_list, /* out */&ps);
API::material( ps );
}
else if (tag_name == "object")
{
ParamSet ps;
vector<std::pair<param_type_e, string>> param_list
{
{ param_type_e::STRING , "type" },
{ param_type_e::REAL , "radius" },
{ param_type_e::POINT3F, "center" }
};
parse_parameters( p_element, param_list, /* out */&ps);
API::object( ps );
}
else if ( tag_name == "world_begin" )
{
//std::clog << ">>> Entering WorldBegin, at level " << level+1 << std::endl;
// We should get only one `world` tag per scene file.
API::world_begin();
}
else if ( tag_name == "world_end" )
{
API::world_end();
//std::clog << ">>> Leaving WorldBegin, at level " << level+1 << std::endl;
}
//else RT3_WARNING( "Undefined tag `" + tag_name + "` found!" );
// Get next (to the right) sibling on this tree level.
p_element = p_element->NextSiblingElement();
}
}
/// Universal parameters parser.
/*!
* This function receives a list of pairs <param_type, name>, traverse all the attributes found
* in `p_element` and extract the attribute values into the `ps_out` `ParamSet` object.
* Only named attributes found are read into the `ps_out`.
*
* @param p_element XML element we are extracting information from.
* @param param_list List of pairs <param_type, name> we need to extract from the XML element.
* @param ps_out The `ParamSet` object we need to fill in with parameter information extracted from the XML element.
*/
void parse_parameters( tinyxml2::XMLElement * p_element,
const vector<std::pair<param_type_e, string>> param_list, ParamSet *ps_out )
{
//std::clog << "parse_parameters(): p_element = " << p_element << endl;
// Traverse the list of paramters pairs: type + name.
for ( const auto& e : param_list )
{
const auto & [ type, name ] = e; // structured binding, requires C++ 17
std::clog << "---Parsing att \"" << name << "\", type = " << static_cast<int>(type) << "\n";
// This is just a dispatcher to the proper extraction functions.
switch ( type )
{
// ATTENTION: We do not parse bool from the XML file because TinyXML2 cannot parse one.
// Bools are treated as strings.
// case param_type_e::BOOL:
// parse_single_BASIC_attrib<bool>( p_element, ps_out, name );
// break;
case param_type_e::UINT:
parse_single_BASIC_attrib<unsigned int>( p_element, ps_out, name );
break;
case param_type_e::INT:
parse_single_BASIC_attrib<int>( p_element, ps_out, name );
break;
case param_type_e::REAL:
parse_single_BASIC_attrib<real_type>( p_element, ps_out, name );
break;
case param_type_e::STRING:
parse_single_BASIC_attrib<std::string>( p_element, ps_out, name );
break;
case param_type_e::VEC3F:
parse_single_COMPOSITE_attrib<real_type, Vector3f>( p_element, ps_out, name );
break;
case param_type_e::VEC3I:
parse_single_COMPOSITE_attrib<int, Vector3i>( p_element, ps_out, name );
break;
case param_type_e::NORMAL3F:
parse_single_COMPOSITE_attrib<real_type, Normal3f>( p_element, ps_out, name );
break;
case param_type_e::POINT3F:
parse_single_COMPOSITE_attrib<real_type, Point3f>( p_element, ps_out, name );
break;
// case param_type_e::POINT2I:
// parse_single_COMPOSITE_attrib<int, Point2i, int(2)>( p_element, ps_out, name );
// break;
case param_type_e::COLOR:
parse_single_COMPOSITE_attrib<real_type, ColorXYZ>( p_element, ps_out, name );
break;
case param_type_e::SPECTRUM:
parse_single_COMPOSITE_attrib<real_type, Spectrum>( p_element, ps_out, name );
break;
case param_type_e::ARR_REAL:
parse_array_BASIC_attrib<real_type>( p_element, ps_out, name );
break;
case param_type_e::ARR_INT:
parse_array_BASIC_attrib<int>( p_element, ps_out, name );
break;
case param_type_e::ARR_VEC3F:
parse_array_COMPOSITE_attrib<real_type, Vector3f>( p_element, ps_out, name );
break;
case param_type_e::ARR_VEC3I:
parse_array_COMPOSITE_attrib<int, Vector3i>( p_element, ps_out, name );
break;
case param_type_e::ARR_NORMAL3F:
parse_array_COMPOSITE_attrib<real_type, Normal3f>( p_element, ps_out, name );
break;
case param_type_e::ARR_POINT3F:
parse_array_COMPOSITE_attrib<real_type, Point3f>( p_element, ps_out, name );
break;
case param_type_e::ARR_COLOR:
parse_array_COMPOSITE_attrib<real_type, ColorXYZ>( p_element, ps_out, name );
break;
default:
RT3_WARNING( string{"parse_params(): unkonwn param type received!" } );
break;
}
clog << "---Done!\n";
}
}
//-------------------------------------------------------------------------------
/*!
* This function parses a set of 2 or 3 basic values to form a composite element.
* For instance, if we have in the scene file points="1 2 3 " and
* they represent a lista of Point3f, this function will store in the ParamSet
* a Point3f{1,2,3}.
*/
template < typename BASIC, typename COMPOSITE >
bool parse_single_COMPOSITE_attrib( tinyxml2::XMLElement *p_element, ParamSet* ps, string att_key ) //rt3::ParamSet
{
// Attribute() returns the value of the attribute as a const char *, or nullptr if such attribute does not exist.
const char* att_value_cstr = p_element->Attribute( att_key.c_str() );
// Test whether the att_key exists.
if ( att_value_cstr )
{
// Create a temporary array to store all the BASIC data. (e.g. BASIC = float)
// This read all the BASIC values into a single array.
auto result = read_array<BASIC>( p_element, att_key );
// Error check
if ( not result.has_value() )
RT3_ERROR( string{"parse_single_COMPOSITE_attrib(): could not read values for attribute \"" + att_key + "\"!" } );
// Values ok, get the value inside optional.
vector< BASIC > values { result.value() };
// Get array length
auto n_basic{ values.size() }; // How many?
// Create the COMPOSITE value.
COMPOSITE comp;
if ( n_basic == 2 )
comp = COMPOSITE{ values[0], values[1] };
else if ( n_basic == 3 )
comp = COMPOSITE{ values[0], values[1], values[2] };
else
return false; // Invalid number of basic components.
// Store the vector of composites in the ParamSet object.
// Recall that `ps` is a dictionary, that receives a pair { key, value }.
(*ps)[ att_key ] = std::make_shared< Value<COMPOSITE> >( comp );
// --------------------------------------------------------------------------
// Show message (DEBUG only, remove it or comment it out if code is working).
// --------------------------------------------------------------------------
clog << "\tAdded attribute (" << att_key << ": \"";
for ( const auto &e : comp )
clog << e << " ";
clog << "\")\n";
// --------------------------------------------------------------------------
return true;
}
return false;
}
/*!
* \brief Retrieves from the XML tree an array of bacis elements into a composite type.
*
* Retrieves from the XML element an array of BASIC type elements (usually floats),
* convert it into a COMPOSITE type with 3 fields (typically Point3f or
* Vector3f), and store it in the ParamSet object.
*
* For instance, if we have in the scene file points="1 2 3 4 2 4 0 0 1" and
* they represent a lista of Point3f, this function will store in the ParamSet
* this vector: { {Point3f{1,2,3}, Point3f{4,2,4}, Point3f{0,0,1} }
*
* \t_param T_BASIC The basic type of the array elements we want to convert from.
* \t_param T_COMPOSITE The composite type of the single element we want to convert to.
* \t_param T_COMPOSITE_SIZE Number of dimensions of the composite type. Default is 3.
* \param p_element The pointer to the XML Element node.
* \param ps The output `ParamSet` object we need to fill in.
* \param att_key The id of the attribute we want to read from.
*
* \return `true` if the parsing goes smoothly, `false` otherwise.
*/
template < typename BASIC, typename COMPOSITE, int COMPOSITE_SIZE >
bool parse_array_COMPOSITE_attrib( tinyxml2::XMLElement *p_element, ParamSet* ps, string att_key ) //rt3::ParamSet
{
// Attribute() returns the value of the attribute as a const char *, or nullptr if such attribute does not exist.
const char* att_value_cstr = p_element->Attribute( att_key.c_str() );
// Test whether the att_key exists.
if ( att_value_cstr )
{
// [1]
// Create a temporary array to store all the BASIC data. (e.g. BASIC = float)
// This read all the BASIC values into a single array.
// The next step is to break it into COMPOSITE units. (e.g. COMPOSITE = Point3f)
auto result = read_array<BASIC>( p_element, att_key );
// Error check
if ( not result.has_value() )
RT3_ERROR( string{"parse_array_COMPOSITE_attrib(): could not read values for attribute \"" + att_key + "\"!" } );
// Values ok, get the value inside optional.
vector< BASIC > values { result.value() };
// Get array length
auto n_basic{ values.size() }; // How many?
// Create the vector that will hold the COMPOSITE values.
vector< COMPOSITE > composit_list;
// [2]
// Fill in `composit_list` with `COMPOSITE`: every COMPOSITE_SIZE values we have
// a 2D or 3D coordinate.
// For example, if we have values = { 1, 1, 1, 2, 2, 2, 4, 4, 4, 8, 8, 8}
// and COMPOSITE = Vector3f, we must extract 4 Vector3f: Vector3f{1,1,1}, {2,2,2}, ..., {8,8,8}.
for ( auto i{0u} ; i < n_basic/COMPOSITE_SIZE ; i ++ )
{
clog << "COMPOSITE_SIZE = " << COMPOSITE_SIZE << std::endl;
// Call the proper constructor, as in Vector3f{x,y,z} or Vector2f{x,y}.
// If, say, COMPOSITE = Vector3f, this will call the constructor Vector3f{x,y,z}.
if ( COMPOSITE_SIZE == 3 )
composit_list.push_back( COMPOSITE{ values[3*i+0], values[3*i+1], values[3*i+2] } );
else // COMPOSITE_SIZE == 2
composit_list.push_back( COMPOSITE{ values[2*i+0], values[2*i+1] } );
}
// [3]
// Store the vector of composites in the ParamSet object.
// Recall that `ps` is a dictionary, that receives a pair { key, value }.
(*ps)[ att_key ] = std::make_shared< Value<vector<COMPOSITE>> >( composit_list );
// --------------------------------------------------------------------------
// Show message (DEBUG only, remove it or comment it out if code is working).
// --------------------------------------------------------------------------
clog << "\tAdded attribute (" << att_key << ": \"";
for ( const auto &e: composit_list )
for ( const auto &x : e )
clog << x << " ";
clog << "\")\n";
// --------------------------------------------------------------------------
return true;
}
return false;
}
template < typename T >
bool parse_array_BASIC_attrib( tinyxml2::XMLElement *p_element, ParamSet* ps, string att_key ) //rt3::ParamSet
{
// Attribute() returns the value of the attribute as a const char *, or nullptr if such attribute does not exist.
const char* att_value_cstr = p_element->Attribute( att_key.c_str() );
// Test whether the att_key exists.
if ( att_value_cstr )
{
// Create a temporary array to store all the T data. (e.g. T = float)
// This read all the T values into a single array.
auto result = read_array<T>( p_element, att_key );
// Error check
if ( not result.has_value() )
RT3_ERROR( string{"parse_array_BASIC_attrib(): could not read values for attribute \"" + att_key + "\"!" } );
// Values ok, get the value inside optional.
vector< T > values { result.value() };
// Store the vector of T in the ParamSet object.
// Recall that `ps` is a dictionary, that receives a pair { key, value }.
(*ps)[ att_key ] = std::make_shared< Value<vector<T>> >( values );
// --------------------------------------------------------------------------
// Show message (DEBUG only, remove it or comment it out if code is working).
// --------------------------------------------------------------------------
clog << "\tAdded attribute (" << att_key << ": \"";
for ( const auto &e: values )
clog << e << " ";
clog << "\")\n";
// --------------------------------------------------------------------------
return true;
}
return false;
}
/// Parse the XML element `p_element` looking for an attribute `att_key` and extract one or more values into the `ParamSet` `ps`.
template < typename T >
bool parse_single_BASIC_attrib( tinyxml2::XMLElement *p_element, ParamSet* ps, string att_key ) //rt3::ParamSet
{
// Test whether the att_key exists. Attribute() returns the value of the attribute,
// as a const char *, or nullptr if such attribute does not exist.
if ( p_element->Attribute( att_key.c_str() ) )
{
std::clog << "\tAttribute \"" << att_key << "\" present, let us extract it!\n";
auto result = read_single_value<T>( p_element, att_key );
if ( result.has_value() )
{
// Store the BASIC value in the ParamSet object.
// Recall that `ps` is a dictionary, that receives a pair { key, value }.
// ps->operator[]( att_key ) = values;
(*ps)[att_key] = std::make_shared< Value<T> >( result.value() );
// const auto [ it, success ] = ps->insert({att_key, std::make_shared< Value<T> >( values )} );
// Show message
clog << "\tInsertion of \"" << att_key << "\" succeeded\n";
clog << "\tAdded attribute (" << att_key << ": \"" << result.value() << "\" )\n";
return true;
}
}
return false;
}
template <typename T>
std::optional< std::vector< T > > read_array( tinyxml2::XMLElement *p_element, const string& att_key )
{
// outgoing list of values retrieved from the XML doc.
vector<T> vec;
// C-style string that will store the attributes read from the XML doc.
const char *value_cstr{nullptr};
// Retrieve the string value into the `value_str` C-style string.
p_element->QueryStringAttribute( att_key.c_str(), &value_cstr );
// If query fails, return nothing.
if ( value_cstr == nullptr )
return std::nullopt;
// Separate individual BASIC elements as tokens.
string str( value_cstr );
std::stringstream tokenizer( str );
std::vector< std::string > tokens;
tokens.insert( tokens.begin(), std::istream_iterator< std::string >( tokenizer ), std::istream_iterator< std::string >( ) );
// Check whether we got at least one element.
if ( tokens.size() != 0 )
{
// Convert them to T and add them to the output vector.
for_each( tokens.begin(), tokens.end(),
// Lambda expression to convert a string "value" to T value.
[ &vec ]( const string & token )
{
T value;
// Convert string to the BASIC type and add it to the outgoing vector.
// =======================================================================
// RT3_WARNING: THIS DOES NOT WORK FOR BOOL VALUES!!!
// That's why we use string instead of bool in the XML file.
// =======================================================================
if ( stringstream( token ) >> value )
vec.push_back( value );
} );
}
return vec;
}
template <typename T>
std::optional<T> read_single_value( tinyxml2::XMLElement *p_element, const string& att_key )
{
// C-style string that will store the attributes read from the XML doc.
const char *value_cstr;
// Retrieve the string value into the `value_str` C-style string.
p_element->QueryStringAttribute( att_key.c_str(), &value_cstr );
// Separate individual BASIC elements as tokens.
string str( value_cstr );
// outgoing value retrieved from the XML doc.
T value;
// Convert string to the BASIC type and add it to the outgoing vector.
// =======================================================================
// RT3_WARNING: THIS DOES NOT WORK FOR BOOL VALUES!!!
// That's why we use string instead of bool in the XML file.
// =======================================================================
if ( stringstream( str ) >> value )
return value;
else return std::nullopt; // Null optional.
}
<file_sep>#ifndef ERROR_H
#define ERROR_H
#include <string>
using std::string;
void RT3_ERROR (const string &);
void RT3_WARNING (const string &);
#endif<file_sep>#include <cmath>
#include <limits>
#include "vec3.h"
using std::numeric_limits;
ColorXYZ default_colorxyz() {
return {-1.0, -1.0, -1.0};
}
bool is_colorxyz_default(ColorXYZ color) {
for (float component: color) {
if (component < 0) {
return true;
}
}
return false;
}
Point4f default_point4f() {
return {numeric_limits<float>::min(), numeric_limits<float>::min(), numeric_limits<float>::min(), numeric_limits<float>::min()};
}
bool is_point4f_default(Point4f& point) {
for (unsigned int i = 0; i < 4; ++i) {
if (point[i] != numeric_limits<float>::min()) return false;
}
return true;
}
Point3f default_point3f() {
return {numeric_limits<float>::min(), numeric_limits<float>::min(), numeric_limits<float>::min()};
}
bool is_point3f_default(Point3f& point) {
for (unsigned int i = 0; i < 3; ++i) {
if (point[i] != numeric_limits<float>::min()) return false;
}
return true;
}
Vector3f default_vector3f() {
return default_point3f();
}
bool is_vector3f_default(Vector3f& vector) {
return is_point3f_default(vector);
}
Vector3f normalize_vector3f(Vector3f& vector) {
float norm = sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2]);
return {vector[0]/norm, vector[1]/norm, vector[2]/norm};
}
Vector3f cross_vector3f(const Vector3f& vector1, const Vector3f& vector2) {
return {
vector1[1]*vector2[2] - vector1[2]*vector2[1] ,
vector1[2]*vector2[0] - vector1[0]*vector2[2],
vector1[0]*vector2[1] - vector1[1]*vector2[0]
};
}
float dot_vector3f(const Vector3f& vector1, const Vector3f& vector2) {
return vector1[0]*vector2[0]+vector1[1]*vector2[1]+vector1[2]*vector2[2];
}
Vector3f operator-(const Vector3f& vector1, const Vector3f& vector2) {
return {vector1[0] - vector2[0], vector1[1] - vector2[1], vector1[2] - vector2[2]};
}
ColorXYZ operator*(const ColorXYZ& color, const float& val) {
return {color[0]*val, color[1]*val, color[2]*val};
}
ColorXYZ operator/(const ColorXYZ& color, const float& val) {
return {color[0]/val, color[1]/val, color[2]/val};
}
ColorXYZ operator+(const ColorXYZ& color, const float& val) {
return {color[0]+val, color[1]+val, color[2]+val};
}
ColorXYZ operator+(const ColorXYZ& color1, const ColorXYZ& color2) {
return {color1[0]+color2[0], color1[1]+color2[1], color1[2]+color2[2]};
}
Vector3f operator*(const float& scalar, const Vector3f& vector) {
return {vector[0]*scalar, vector[1]*scalar, vector[2]*scalar};
}<file_sep>#include "math.h"
ostream &operator<<(ostream &os, const Point2f &point)
{
os << "Point2(" << point[0] << "," << point[1] << ")";
return os;
}<file_sep>#ifndef PARAMSET_H
#define PARAMSET_H
#include <iostream>
#include <map>
#include <memory>
#include <string>
/// Pure virtual basic type. The map stores a pointer to the base class
class ValueBase {
public:
ValueBase() {}
virtual ~ValueBase() {}
};
/// We must convert the base class object to the proper derived class object.
template <typename T> class Value : public ValueBase {
private:
T m_tValue; // The stored data.
public:
Value(T tValue) : m_tValue{tValue} {}
~Value() {}
Value(const Value &src) : m_tValue{src.m_tValue} {}
Value &operator=(const Value &src) {
if (this != &src) m_tValue = src.m_tValue;
return *this;
}
T value() { return m_tValue; }
};
// The ParamSet is just a heterogeneous hash table. All keys are strings.
using ParamSet = std::map<std::string, std::shared_ptr<ValueBase>>;
/*!
* This is an auxiliary function to avoid the *verbose* access associated
* with the std::map<>.
*
* Tries to retrieve the value associated with `key` from the ParamSet `ps`.
* In case there is no such key/value pair stored in `ps`, the function returns
* the default value `default_value` provided by the client him/herself.
* @param ps The ParamSet we want to extract the value from.
* @param key The key stored in the ParamSet.
* @param default_value The default value returned, in case the key is not in
* the ParamSet.
* @return The value associated with `key`, if such key is stored in the `ps`,
* or the given default value otherwise.
*/
template <typename T>
T retrieve(const ParamSet &ps, std::string key, const T &default_value = T()) {
// Try to retrieve key/data item from the map.
auto result = ps.find(key);
if (result != ps.end()) {
std::clog << "-->ParamSet: Found [\"" << result->first << "\"].\n";
} else {
std::clog << "-->ParamSet: Key [\"" << key << "\"] not present.\n";
// Assign a default value in case type is not in the ParamSet object.
}
return (result == ps.end()) ? default_value : // default value.
dynamic_cast<Value<T> &>(*result->second).value();
}
#endif
<file_sep>#include "ray.h"
Ray::Ray(const Point3f& o, const Vector3f& d ) : origin{o}, direction{d} { }
Vector3f Ray::operator-(float t) const {
return origin + t * direction;
}<file_sep>#ifndef PRIMITIVE_H
#define PRIMITIVE_H
#include "ray.h"
#include "surfel.h"
#include "material.h"
class Primitive {
protected:
Material* material;
public:
virtual ~Primitive(){};
virtual bool intersect( const Ray& r, const Surfel *sf ) const = 0;
// Simpler and faster version of intersection that only return true/false.
// It does not compute the hit point information.
virtual bool intersect_p( const Ray& r) const = 0;
virtual const Material* get_material(void) const { return material; }
};
#endif<file_sep>#ifndef SAMPLER_INTEGRATOR_H
#define SAMPLER_INTEGRATOR_H
#include "camera.h"
#include "integrator.h"
#include "rt3.h"
#include "vec3.h"
class SamplerIntegrator : public Integrator {
public:
using Integrator::render;
virtual ~SamplerIntegrator() = default;
SamplerIntegrator( Camera* cam ) : camera{cam} { };
// returns the incident radiance at the origin of a given ray
virtual ColorXYZ Li( const Ray& ray, Scene& scene, ColorXYZ& default_color) = 0;
virtual void render( Scene& scene );
virtual void preprocess( const Scene& scene );
protected:
Camera* camera;
RunningOptions run_opt;
};
#endif<file_sep>#include "sphere.h"
#include "vec3.h"
bool Sphere::intersect( const Ray& r, const Surfel *sf) const {
// TODO
return true;
}
bool Sphere::intersect_p( const Ray& ray) const {
auto o = ray.origin;
auto d = ray.direction;
auto c = center;
auto r = radius;
auto A = dot_vector3f(d, d);
auto B = dot_vector3f(2*(o - c), d);
auto C = dot_vector3f(o - c, o - c) - r*r;
auto delta = B*B-4*A*C;
return delta >= 0;
}<file_sep>#include "object_manager.h"
#include "sphere.h"
void ObjectManager::add_object(Primitive* obj) {
obj_list.push_back(obj);
}
void ObjectManager::add_material(Material* _mat) {
mat = _mat;
}
void ObjectManager::instantiate_sphere(const Point3f& _c, const float& _r, Material* mat) {
Primitive* sp = new Sphere(_c, _r, mat);
add_object(sp);
}
Material* ObjectManager::get_material(void) {
return mat;
}
std::vector< Primitive* >& ObjectManager::get_object_list(void) {
return obj_list;
}
<file_sep>#include "object_manager.h"
#include "sphere.h"
void ObjectManager::add_object(Primitive* obj) {
obj_list.push_back(obj);
}
void ObjectManager::add_material(Material* _mat) {
materials.push_back(_mat);
}
void ObjectManager::instantiate_sphere(const Point3f& _c, const float& _r, Material* mat) {
Shape* shape = new Sphere(_c, _r);
auto primitive = new GeometricPrimitive(shape, mat);
shape->primitive = primitive;
this->add_object(primitive);
}
Material* ObjectManager::get_material(void) {
return materials.back();
}
std::vector< Primitive* >& ObjectManager::get_object_list(void) {
return obj_list;
}
<file_sep>#include "surfel.h"
void Surfel::copy_from(Surfel* other) {
if (!other) return;
p = other->p;
n = other->n;
wo = other->wo;
time = other->time;
uv = other->uv;
primitive = other->primitive;
}<file_sep>#include "scene.h"
Scene::Scene() {/* empty */ }
bool Scene::intersect( const Ray& r, Surfel *isect ) {
return aggregate->intersect(r, isect);
}
bool Scene::intersect_p( const Ray& r ) {
return aggregate->intersect_p(r);
}<file_sep>#ifndef INTEGRATOR_H
#define INTEGRATOR_H
#include "scene.h"
class Integrator {
public:
virtual ~Integrator() = default;
virtual void render( Scene& scene ) =0;
};
#endif<file_sep>#ifndef MATERIAL_H
#define MATERIAL_H
class Material {
private:
public:
ColorXYZ color;
Material(const ColorXYZ _color) : color{_color} {/* empty */ }
~Material(){}
};
#endif<file_sep>#include <stdexcept>
#ifndef RT3_H
#define RT3_H
struct RunningOptions {
RunningOptions() : scene_filename{""}, outfile{""}, quick_render{false} {
crop_window[0][0] = 0;
crop_window[1][0] = INT_MAX;
crop_window[0][1] = 0;
crop_window[1][1] = INT_MAX;
}
int crop_window[2][2];
std::string scene_filename;
std::string outfile;
bool quick_render;
};
RunningOptions parse_running_options(int argc, char * argv[]);
#endif // RT3_H
<file_sep>#ifndef PARSER_H
#define PARSER_H
/*!
* Implementation of XML processing functions.
* @file parser.cpp
*/
#include <tinyxml2.h>
#include <iostream>
using std::endl;
using std::clog;
using std::cerr;
using std::cout;
using std::boolalpha;
#include <iomanip>
using std::setw;
#include <string>
using std::string;
#include <memory>
using std::make_unique;
using std::make_shared;
using std::shared_ptr;
using std::unique_ptr;
#include <algorithm>
using std::copy;
#include <sstream>
using std::stringstream;
#include <iterator>
using std::istream_iterator;
using std::begin;
using std::endl;
#include <vector>
using std::vector;
#include <utility>
using std::pair;
#include <optional>
using std::optional;
#include "paramset.h"
/// Lambda expression that transform a c-style string to a lowercase c++-stype string version.
static auto STR_LOWER = []( const char * c_str )->std::string
{
std::string str{ c_str };
std::transform( str.begin(), str.end(), str.begin(), ::tolower );
return str;
};
// === Support functions
// TODO not compiling with optional
template <typename T>
std::optional<std::vector< T >> read_array( tinyxml2::XMLElement *, const string& );
template <typename T>
std::optional<T> read_single_value( tinyxml2::XMLElement *p_element, const string& att_key );
/// Extracts a single COMPOSITE element.
template < typename BASIC, typename COMPOSITE >
bool parse_single_COMPOSITE_attrib( tinyxml2::XMLElement *e, ParamSet *ps, string name ); //rt3::ParamSet
/// Extracts an array of COMPOSITE elements.
template < typename BASIC, typename COMPOSITE , int SIZE=3 >
bool parse_array_COMPOSITE_attrib( tinyxml2::XMLElement *e, ParamSet *ps, string name ); //rt3::ParamSet
/// Extracts a single BASIC element.
template < typename T >
bool parse_single_BASIC_attrib( tinyxml2::XMLElement *e, ParamSet *ps , string name ); //rt3::ParamSet
/// Extracts an array of BASIC elements.
template < typename T >
bool parse_array_BASIC_attrib( tinyxml2::XMLElement *e, ParamSet *ps , string name ); //rt3::ParamSet
// === Enumerations
/// Type of possible paramter types we may read from the input scene file.
enum class param_type_e : int { BOOL=0,
INT, //!< Single integet
UINT, //!< Single unsigned int
REAL, //!< Single real number
VEC3F, //!< Single Vector3f
VEC3I, //!< Single Vector3i
NORMAL3F, //!< Single Normal3f
POINT3F, //!< Single Point3f
POINT2I, //!< Single Point2i
COLOR, //!< Single Color
SPECTRUM, //!< Single Spectrum
STRING, //!< Single string
ARR_INT, //!< An array of integers
ARR_REAL, //!< An array of real numbers
ARR_VEC3F, //!< An array of Vector3f
ARR_VEC3I, //!< An array of Vector3i
ARR_POINT3F, //!< An array of Point3f
ARR_COLOR, //!< An array of Color
ARR_NORMAL3F //!< An array of Normal3f
};
// === parsing functions.
void parse( const char* );
void parse_tags( tinyxml2::XMLElement *, int );
void parse_parameters( tinyxml2::XMLElement *p_element, const vector<std::pair<param_type_e, string>>param_list, ParamSet *ps_out );
//-------------------------------------------------------------------------------
#endif // PARSER_H
<file_sep>#include <iomanip> // std::setprecision
#include <iostream>
#include "api.h"
#include "error.h"
#include "vec3.h"
#include "sphere.h"
RunningOptions API::run_opt;
Camera* API::m_camera;
LookAt* API::lookat_info;
Background API::m_background;
ObjectManager API::obj_manager;
void API::init_engine( const RunningOptions & opt ) {
run_opt = opt;
std::clog << "Engine Initialized.\n";
}
void API::run( void ) {
std::clog << ">>> Start API::run()\n";
clog << "Parsing.\n";
parse( run_opt.scene_filename.c_str() );
}
void API::clean_up( void ) {
clog << "Cleaning free space.\n";
delete m_camera;
delete lookat_info;
// TODO
}
void API::reset_engine( void ) {
std::clog << ">>> Start API::reset_engine().\n";
}
void API::camera( const ParamSet& ps ) {
std::clog << ">>> Start API::camera().\n";
auto type = retrieve<string>(ps, "type", "");
if (type == "orthographic") {
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4) {
RT3_ERROR("Invalid screen window! It must consist of 4 floats.");
}
m_camera = new OrthographicCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else if (type == "perspective") {
auto fovy = retrieve<float>(ps, "fovy", -1);
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4 && fovy < 0) {
RT3_ERROR("For perspective cameras you must either provide a fovy or a screen space!");
}
if (screen_window.size() == 4) {
m_camera = new PerspectiveCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else {
auto focal_distance = retrieve(ps, "focal_distance", 1.0);
auto aspect_ratio = retrieve(ps, "frame_aspectratio", -1.0);
m_camera = new PerspectiveCamera(focal_distance, aspect_ratio, fovy, lookat_info);
}
} else {
RT3_ERROR("Camera type " + type + " invalid! It must be ortographic or perspective.");
}
}
void API::film( const ParamSet& ps ) {
std::clog << ">>> Start API::film()\n";
auto filename = retrieve<string>(ps, "filename", "");
auto img_type = retrieve<string>(ps, "img_type", "ppm3");
auto type = retrieve<string>(ps, "type", "");
auto x_res = retrieve<int>(ps, "x_res", -1);
auto y_res = retrieve<int>(ps, "y_res", -1);
if (x_res < 0 || y_res < 0) {
RT3_ERROR("Invalid film size!");
}
if (run_opt.quick_render) {
x_res /= 4;
y_res /= 4;
}
if (img_type != "ppm3") {
RT3_ERROR("Unsupported image type " + img_type + "! It must be ppm3.");
}
if (run_opt.outfile != "") {
filename = run_opt.outfile;
}
if (filename == "") {
RT3_ERROR("Invalid file name!");
}
m_camera->film = Film(x_res, y_res, img_type, filename);
auto maybe_perspective_m_camera_ptr = dynamic_cast<PerspectiveCamera*>(m_camera);
if (maybe_perspective_m_camera_ptr) {
maybe_perspective_m_camera_ptr->set_lrbt_from_xres_yres_if_needed();
}
m_camera->calculate_frame();
}
void API::background( const ParamSet& ps ) {
std::clog << ">>> Start API::background()\n";
auto tl = retrieve(ps, "tl", default_colorxyz()) / m_camera->film.max_color_value;
auto tr = retrieve(ps, "tr", default_colorxyz()) / m_camera->film.max_color_value;
auto bl = retrieve(ps, "bl", default_colorxyz()) / m_camera->film.max_color_value;
auto br = retrieve(ps, "br", default_colorxyz()) / m_camera->film.max_color_value;
auto color = retrieve(ps, "color", default_colorxyz()) / m_camera->film.max_color_value;
auto type = retrieve<string>(ps, "type", ""); // TODO
auto mapping = retrieve<string>(ps, "mapping", ""); // TODO
if (!is_colorxyz_default(color)) {
m_background = Background(color);
} else if (!is_colorxyz_default(tl) && !is_colorxyz_default(tr) && !is_colorxyz_default(br) && !is_colorxyz_default(bl)) {
m_background = Background(bl, tl, tr, br);
} else {
RT3_ERROR("It is necessary to pass either a single color or four colors!");
}
}
void API::integrator( const ParamSet& ps ) {
std::clog << ">>> Start API::integrator()\n";
auto type = retrieve<string>(ps, "type", "");
// TODO
}
void API::look_at( const ParamSet& ps ) {
std::clog << ">>> Start API::look_at()\n";
auto look_from = retrieve<Point3f>(ps, "look_from", default_point3f());
auto look_at = retrieve<Vector3f>(ps, "look_at", default_vector3f());
auto up = retrieve<Vector3f>(ps, "up", default_vector3f());
if (is_point3f_default(look_from)) RT3_ERROR("look_from information invalid or missing!");
if (is_vector3f_default(look_at)) RT3_ERROR("look_at information invalid or missing!");
if (is_vector3f_default(up)) RT3_ERROR("up information invalid or missing!");
lookat_info = new LookAt(look_from, look_at, up);
}
void API::material( const ParamSet& ps ) {
std::clog << ">>> Start API::material()\n";
auto type = retrieve<string>(ps, "type", "");
auto color = retrieve(ps, "color", default_colorxyz());
Material* mat = new Material(color);
obj_manager.add_material(mat);
// TODO
}
void API::object( const ParamSet& ps ) {
std::clog << ">>> Start API::object()\n";
auto type = retrieve<string>(ps, "type", "");
auto radius = retrieve<float>(ps, "radius", 0.0);
auto center = retrieve<Point3f>(ps, "center", default_point3f());
obj_manager.instantiate_sphere(center, radius, obj_manager.get_material());
}
void API::world_begin( void ) {
std::clog << ">>> Start API::world_begin()\n";
// TODO
}
void API::world_end( void )
{
std::clog << ">>> Start API::world_end()\n";
render();
reset_engine();
}
void API::render( void ) {
std::clog << ">>> Start API::render()\n";
auto width = m_camera->film.width;
auto height = m_camera->film.height;
for (int j = std::min(run_opt.crop_window[0][1], run_opt.crop_window[1][1]); j < std::min(height, std::max(run_opt.crop_window[0][1], run_opt.crop_window[1][1])); ++j) {
for (int i = std::min(run_opt.crop_window[0][0], run_opt.crop_window[1][0]); i < std::min(width, std::max(run_opt.crop_window[0][0], run_opt.crop_window[1][0])); ++i) {
Ray ray = m_camera->generate_ray(i, j);
auto any_object_hit = false;
auto color = ColorXYZ{0,0,0};
for (const Primitive* p: obj_manager.get_object_list()) {
if (p->intersect_p(ray)) {
color = obj_manager.get_material()->color;
any_object_hit = true;
break;
}
}
if (!any_object_hit) {
color = m_background.sample(Point2f{float(i)/float(width), float(j)/float(height)});
}
m_camera->film.add(Point2i{i, j}, color);
}
}
m_camera->film.write_image();
}
<file_sep>#include "flat_material.h"
ColorXYZ FlatMaterial::kd() {
return color;
}<file_sep>#ifndef SPHERE_H
#define SPHERE_H
#include "primitive.h"
class Sphere : public Primitive {
private:
Point3f center;
float radius;
public:
Sphere(const Point3f& _c, const float& _r, Material* mat) : center(_c), radius{_r} {
material = mat;
}
~Sphere(){}
bool intersect(const Ray &r, const Surfel *sf) const override;
bool intersect_p(const Ray &r) const override;
};
#endif<file_sep># Ray Tracing
Implementation of some features of the Ray Tracing algorithm, which makes possible generating really realistic 3D-like images by using concepts of Physics.
This is the main project of the Computer Graphics course at UFRN, taught by <NAME> in the 2022.1 semester. It is incremental; each vXX folder in this repo corresponds to a version of it.
<file_sep>#include <algorithm>
#include <cmath>
#include "sphere.h"
#include "vec3.h"
bool Sphere::intersect( const Ray& ray, Surfel *sf) const {
Vector3f o = ray.origin;
Vector3f d = ray.direction;
Point3f c = center;
float r = radius;
float A = dot_vector3f(d, d);
float B = 2*dot_vector3f((o - c), d);
float C = dot_vector3f(o - c, o - c) - r*r;
float delta = B*B-4*A*C;
float time = -1.0;
if (delta > 0) {
float root_1 = (-B + sqrt(delta)) / (2*A);
float root_2 = (-B - sqrt(delta)) / (2*A);
time = std::min(root_1, root_2);
}
else if(delta == 0) time = -B/(2*A);
sf->primitive = primitive;
sf->time = time;
return delta >= 0;
}
bool Sphere::intersect_p( const Ray& ray) const {
auto o = ray.origin;
auto d = ray.direction;
auto c = center;
auto r = radius;
auto A = dot_vector3f(d, d);
auto B = dot_vector3f(2*(o - c), d);
auto C = dot_vector3f(o - c, o - c) - r*r;
auto delta = B*B-4*A*C;
return delta >= 0;
}
<file_sep>#include "background.h"
#include "math.h"
#include <iostream>
Background::Background(ColorXYZ color) {
sampler = bilinear_interpolation<ColorXYZ>({0, 1}, {0, 0}, {1, 0}, {1, 1}, color, color, color, color);
}
Background::Background(ColorXYZ bl, ColorXYZ tl, ColorXYZ tr, ColorXYZ br) {
sampler = bilinear_interpolation<ColorXYZ>({0, 1}, {0, 0}, {1, 0}, {1, 1}, tl, bl, br, tr);
}
ColorXYZ Background::sample(Point2f point) {
return sampler(point);
}
<file_sep>#ifndef AGGREGATE_PRIMITIVE_H
#define AGGREGATE_PRIMITIVE_H
#include "primitive.h"
class AggregatePrimitive: public Primitive {
private:
std::vector<Primitive*> primitives;
public:
using Primitive::intersect;
using Primitive::intersect_p;
using Primitive::get_material;
AggregatePrimitive(std::vector<Primitive*> p_primitives): primitives(p_primitives) { }
Material* get_material();
void add_primitive(Primitive* primitive);
bool intersect( const Ray& r, Surfel *sf );
bool intersect_p( const Ray& r);
};
#endif<file_sep>#ifndef PRIMITIVE_H
#define PRIMITIVE_H
#include "material.h"
#include "ray.h"
#include "surfel.h"
class Primitive {
public:
virtual ~Primitive(){};
virtual bool intersect( const Ray& r, Surfel *sf ) = 0;
// Simpler and faster version of intersection that only return true/false.
// It does not compute the hit point information.
virtual bool intersect_p( const Ray& r) = 0;
//virtual Bounds3f world_bounds() const = 0;
virtual Material* get_material() = 0;
};
#endif<file_sep>#include <iomanip> // std::setprecision
#include <iostream>
#include "api.h"
#include "error.h"
#include "vec3.h"
RunningOptions API::run_opt;
Camera* API::m_camera;
LookAt* API::lookat_info;
Background API::m_background;
void API::init_engine( const RunningOptions & opt ) {
run_opt = opt;
std::clog << "Engine Initialized.\n";
}
void API::run( void ) {
std::clog << ">>> Start API::run()\n";
clog << "Parsing.\n";
parse( run_opt.scene_filename.c_str() );
}
void API::clean_up( void ) {
clog << "Cleaning free space.\n";
delete m_camera;
// TODO
}
void API::reset_engine( void ) {
std::clog << ">>> Start API::reset_engine().\n";
}
void API::camera( const ParamSet& ps ) {
std::clog << ">>> Start API::camera().\n";
auto type = retrieve<string>(ps, "type", "");
if (type == "orthographic") {
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4) {
RT3_ERROR("Invalid screen window! It must consist of 4 floats.");
}
m_camera = new OrthographicCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else if (type == "perspective") {
auto fovy = retrieve<float>(ps, "fovy", -1);
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4 && fovy < 0) {
RT3_ERROR("For perspective cameras you must either provide a fovy or a screen space!");
}
if (screen_window.size() == 4) {
m_camera = new PerspectiveCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else {
auto focal_distance = retrieve(ps, "focal_distance", 1.0);
auto aspect_ratio = retrieve(ps, "frame_aspectratio", -1.0);
m_camera = new PerspectiveCamera(focal_distance, aspect_ratio, fovy, lookat_info);
}
} else {
RT3_ERROR("Camera type " + type + " invalid! It must be ortographic or perspective.");
}
}
void API::film( const ParamSet& ps ) {
std::clog << ">>> Start API::film()\n";
auto filename = retrieve<string>(ps, "filename", "");
auto img_type = retrieve<string>(ps, "img_type", "ppm3");
auto type = retrieve<string>(ps, "type", "");
auto x_res = retrieve<int>(ps, "x_res", -1);
auto y_res = retrieve<int>(ps, "y_res", -1);
if (x_res < 0 || y_res < 0) {
RT3_ERROR("Invalid film size!");
}
if (run_opt.quick_render) {
x_res /= 4;
y_res /= 4;
}
if (img_type != "ppm3") {
RT3_ERROR("Unsupported image type " + img_type + "! It must be ppm3.");
}
if (run_opt.outfile != "") {
filename = run_opt.outfile;
}
if (filename == "") {
RT3_ERROR("Invalid file name!");
}
m_camera->film = Film(x_res, y_res, img_type, filename);
auto maybe_perspective_m_camera_ptr = dynamic_cast<PerspectiveCamera*>(m_camera);
if (maybe_perspective_m_camera_ptr) {
maybe_perspective_m_camera_ptr->set_lrbt_from_xres_yres_if_needed();
}
m_camera->calculate_frame();
}
void API::background( const ParamSet& ps ) {
std::clog << ">>> Start API::background()\n";
auto tl = retrieve(ps, "tl", default_colorxyz()) / m_camera->film.max_color_value;
auto tr = retrieve(ps, "tr", default_colorxyz()) / m_camera->film.max_color_value;
auto bl = retrieve(ps, "bl", default_colorxyz()) / m_camera->film.max_color_value;
auto br = retrieve(ps, "br", default_colorxyz()) / m_camera->film.max_color_value;
auto color = retrieve(ps, "color", default_colorxyz()) / m_camera->film.max_color_value;
auto type = retrieve<string>(ps, "type", ""); // TODO
auto mapping = retrieve<string>(ps, "mapping", ""); // TODO
if (!is_colorxyz_default(color)) {
m_background = Background(color);
} else if (!is_colorxyz_default(tl) && !is_colorxyz_default(tr) && !is_colorxyz_default(br) && !is_colorxyz_default(bl)) {
m_background = Background(bl, tl, tr, br);
} else {
RT3_ERROR("It is necessary to pass either a single color or four colors!");
}
}
void API::integrator( const ParamSet& ps ) {
std::clog << ">>> Start API::integrator()\n";
// TODO
}
void API::look_at( const ParamSet& ps ) {
std::clog << ">>> Start API::look_at()\n";
auto look_from = retrieve<Point3f>(ps, "look_from", default_point3f());
auto look_at = retrieve<Vector3f>(ps, "look_at", default_vector3f());
auto up = retrieve<Vector3f>(ps, "up", default_vector3f());
if (is_point3f_default(look_from)) RT3_ERROR("look_from information invalid or missing!");
if (is_vector3f_default(look_at)) RT3_ERROR("look_at information invalid or missing!");
if (is_vector3f_default(up)) RT3_ERROR("up information invalid or missing!");
lookat_info = new LookAt(look_from, look_at, up);
}
void API::world_begin( void ) {
std::clog << ">>> Start API::world_begin()\n";
// TODO
}
void API::world_end( void )
{
std::clog << ">>> Start API::world_end()\n";
render();
reset_engine();
}
void API::render( void ) {
std::clog << ">>> Start API::render()\n";
auto width = m_camera->film.width;
auto height = m_camera->film.height;
for (int j = std::min(run_opt.crop_window[0][1], run_opt.crop_window[1][1]); j < std::min(height, std::max(run_opt.crop_window[0][1], run_opt.crop_window[1][1])); ++j) {
for (int i = std::min(run_opt.crop_window[0][0], run_opt.crop_window[1][0]); i < std::min(width, std::max(run_opt.crop_window[0][0], run_opt.crop_window[1][0])); ++i) {
Ray ray = m_camera->generate_ray(i, j);
auto color = m_background.sample(Point2f{float(i)/float(width), float(j)/float(height)});
m_camera->film.add(Point2i{i, j}, color);
}
}
// vector<Point2i> inputs = {
// {0,1799},{700,1799},{1400,1799},{2100,1799},
// {0,1798},{700,1798},{1400,1798},{2100,1798},
// {0,1797},{700,1797},{1400,1797},{2100,1797},
// {0,2},{700,2},{1400,2},{2100,2},{2799,2},
// {0,1},{700,1},{1400,1},{2100,1},{2799,1},
// {0,0},{700,0},{1400,0},{2100,0},{2799,0}
// };
// std::cout << std::fixed << std::showpoint;
// std::cout << std::setprecision(6);
// std::cout << "e = [" << m_camera->frame->e[0] << " " << m_camera->frame->e[1] << " " << m_camera->frame->e[2] << "]" << std::endl;
// std::cout << "w = [" << m_camera->frame->w[0] << " " << m_camera->frame->w[1] << " " << m_camera->frame->w[2] << "]" << std::endl;
// std::cout << "u = [" << m_camera->frame->u[0] << " " << m_camera->frame->u[1] << " " << m_camera->frame->u[2] << "]" << std::endl;
// std::cout << "v = [" << m_camera->frame->v[0] << " " << m_camera->frame->v[1] << " " << m_camera->frame->v[2] << "]" << std::endl;
// std::cout << std::endl;
// for (auto input : inputs) {
// auto i = input[0];
// auto j = input[1];
// Ray ray = m_camera->generate_ray(i, j);
// auto uv = m_camera->map_to_screen_space(input);
// std::cout << "i=" << i << " j=" << j << " u=" << uv[0] << " v=" << uv[1] << endl << ray.origin[0] << " " << ray.origin[1] << " " << ray.origin[2] << " "
// << ray.direction[0] << " " << ray.direction[1] << " " << ray.direction[2] << endl;
// }
m_camera->film.write_image();
}<file_sep>#include "geometric_primitive.h"
bool GeometricPrimitive::intersect(const Ray& r, Surfel *sf) {
return shape->intersect(r, sf);
}
bool GeometricPrimitive::intersect_p(const Ray& r) {
return shape->intersect_p(r);
}
Material* GeometricPrimitive::get_material() {
return material;
}
void GeometricPrimitive::set_material(Material* &mat) {
material = mat;
}
<file_sep>#ifndef FLAT_INTEGRATOR_H
#define FLAT_INTEGRATOR_H
#include "sampler_integrator.h"
class FlatIntegrator: public SamplerIntegrator {
public:
using SamplerIntegrator::Li;
FlatIntegrator(Camera* camera);
ColorXYZ Li( const Ray& ray, Scene& scene, ColorXYZ& default_color);
};
#endif<file_sep>#ifndef MATERIAL_H
#define MATERIAL_H
// describes how an object interacts with light
class Material {
public:
virtual ~Material() = default;
};
#endif<file_sep>#include <iostream>
#include "error.h"
void RT3_ERROR (const std::string &msg) {
std::cerr << "ERROR: " << msg << std::endl;
std::exit(EXIT_FAILURE);
}
void RT3_WARNING (const std::string &msg) {
std::cerr << "WARNING: " << msg << std::endl;
}<file_sep>#include "flat_integrator.h"
#include "flat_material.h"
#include "surfel.h"
FlatIntegrator::FlatIntegrator(Camera* camera): SamplerIntegrator(camera) { }
ColorXYZ FlatIntegrator::Li(const Ray& ray, Scene& scene, ColorXYZ& default_color ) {
ColorXYZ radiance;
Surfel isect;
if (!scene.intersect(ray, &isect)) {
radiance = default_color;
} else {
FlatMaterial *fm = dynamic_cast< FlatMaterial *>( isect.primitive->get_material());
if (fm) {
radiance = fm->kd()/255.0;
}
}
return radiance;
}
<file_sep>#ifndef RAY_H
#define RAY_H
#include "vec3.h"
class Ray {
public:
Point3f origin;
Vector3f direction;
Ray(const Point3f& o, const Vector3f& d );
~Ray(){}
Vector3f operator-(float t) const;
};
#endif
<file_sep>#include "vec3.h"
ColorXYZ default_colorxyz() {
return {-1.0, -1.0, -1.0};
}
bool is_colorxyz_default(ColorXYZ color) {
for (float component: color) {
if (component < 0) {
return true;
}
}
return false;
}
ColorXYZ operator*(const ColorXYZ& color, const float& val) {
return {color[0]*val, color[1]*val, color[2]*val};
}
ColorXYZ operator/(const ColorXYZ& color, const float& val) {
return {color[0]/val, color[1]/val, color[2]/val};
}
ColorXYZ operator+(const ColorXYZ& color, const float& val) {
return {color[0]+val, color[1]+val, color[2]+val};
}
ColorXYZ operator+(const ColorXYZ& color1, const ColorXYZ& color2) {
return {color1[0]+color2[0], color1[1]+color2[1], color1[2]+color2[2]};
}<file_sep>#include <iostream>
#include "api.h"
#include "error.h"
#include "vec3.h"
RunningOptions API::run_opt;
Camera API::m_camera;
Background API::m_background;
void API::init_engine( const RunningOptions & opt ) {
run_opt = opt;
std::clog << "Engine Initialized.\n";
}
void API::run( void ) {
std::clog << ">>> Start API::run()\n";
clog << "Parsing.\n";
parse( run_opt.scene_filename.c_str() );
}
void API::clean_up( void ) {
clog << "Cleaning free space.\n";
//TODO Cleaning
}
void API::reset_engine( void ) {
std::clog << ">>> Start API::reset_engine().\n";
}
void API::camera( const ParamSet& ps ) {
std::clog << ">>> Start API::camera().\n";
auto type = retrieve<string>(ps, "type", ""); // TODO
}
void API::film( const ParamSet& ps ) {
std::clog << ">>> Start API::film()\n";
auto filename = retrieve<string>(ps, "filename", "");
auto img_type = retrieve<string>(ps, "img_type", "ppm3");
auto type = retrieve<string>(ps, "type", "");
auto x_res = retrieve<int>(ps, "x_res", -1);
auto y_res = retrieve<int>(ps, "y_res", -1);
if (x_res < 0 || y_res < 0) {
RT3_ERROR("Invalid film size!");
}
if (run_opt.quick_render) {
x_res /= 4;
y_res /= 4;
}
if (img_type != "ppm3") {
RT3_ERROR("Unsupported image type " + img_type + "! It must be ppm3.");
}
if (run_opt.outfile != "") {
filename = run_opt.outfile;
}
if (filename == "") {
RT3_ERROR("Invalid file name!");
}
m_camera.film = Film(x_res, y_res, img_type, filename);
}
void API::background( const ParamSet& ps ) {
std::clog << ">>> Start API::background()\n";
auto tl = retrieve(ps, "tl", default_colorxyz()) / m_camera.film.max_color_value;
auto tr = retrieve(ps, "tr", default_colorxyz()) / m_camera.film.max_color_value;
auto bl = retrieve(ps, "bl", default_colorxyz()) / m_camera.film.max_color_value;
auto br = retrieve(ps, "br", default_colorxyz()) / m_camera.film.max_color_value;
auto color = retrieve(ps, "color", default_colorxyz()) / m_camera.film.max_color_value;
auto type = retrieve<string>(ps, "type", ""); // TODO
auto mapping = retrieve<string>(ps, "mapping", ""); // TODO
if (!is_colorxyz_default(color)) {
m_background = Background(color);
} else if (!is_colorxyz_default(tl) && !is_colorxyz_default(tr) && !is_colorxyz_default(br) && !is_colorxyz_default(bl)) {
m_background = Background(bl, tl, tr, br);
} else {
RT3_ERROR("It is necessary to pass either a single color or four colors!");
}
}
void API::integrator( const ParamSet& ps ) {
std::clog << ">>> Start API::integrator()\n";
// TODO
}
void API::look_at( const ParamSet& ps ) {
std::clog << ">>> Start API::look_at()\n";
// TODO
}
void API::world_begin( void ) {
std::clog << ">>> Start API::world_begin()\n";
// TODO
}
void API::world_end( void )
{
std::clog << ">>> Start API::world_end()\n";
render();
reset_engine();
}
void API::render( void ) {
std::clog << ">>> Start API::render()\n";
auto width = m_camera.film.width;
auto height = m_camera.film.height;
for (int j = std::min(run_opt.crop_window[0][1], run_opt.crop_window[1][1]); j < std::min(height, std::max(run_opt.crop_window[0][1], run_opt.crop_window[1][1])); ++j) {
for (int i = std::min(run_opt.crop_window[0][0], run_opt.crop_window[1][0]); i < std::min(width, std::max(run_opt.crop_window[0][0], run_opt.crop_window[1][0])); ++i) {
auto color = m_background.sample(Point2f{float(i)/float(width), float(j)/float(height)});
m_camera.film.add(Point2i{i, j}, color);
}
}
m_camera.film.write_image();
}<file_sep>#ifndef SHAPE_H
#define SHAPE_H
#include "geometric_primitive.h"
#include "ray.h"
#include "surfel.h"
class GeometricPrimitive;
class Shape {
protected:
bool flip_normals = false;
public:
GeometricPrimitive* primitive = nullptr;
Shape(){}
Shape(const bool& flip_n) : flip_normals(flip_n) {}
~Shape(){}
//virtual Bounds3f world_bounds() const = 0;
virtual bool intersect(const Ray &r, Surfel *sf) const = 0;
virtual bool intersect_p(const Ray &r) const = 0;
};
#endif<file_sep>#include <iomanip> // std::setprecision
#include <iostream>
#include "api.h"
#include "error.h"
#include "flat_material.h"
#include "vec3.h"
#include "sphere.h"
#include "flat_integrator.h"
#include "aggregate_primitive.h"
RunningOptions API::run_opt;
Camera* API::m_camera;
LookAt* API::lookat_info;
ObjectManager API::obj_manager;
Integrator* API::m_integrator;
Scene* API::scene;
void API::init_engine( const RunningOptions & opt ) {
run_opt = opt;
std::clog << "Engine Initialized.\n";
}
void API::run( void ) {
std::clog << ">>> Start API::run()\n";
clog << "Parsing.\n";
parse( run_opt.scene_filename.c_str() );
}
void API::clean_up( void ) {
clog << "Cleaning free space.\n";
delete m_camera;
delete lookat_info;
// TODO
}
void API::reset_engine( void ) {
std::clog << ">>> Start API::reset_engine().\n";
}
void API::camera( const ParamSet& ps ) {
std::clog << ">>> Start API::camera().\n";
auto type = retrieve<string>(ps, "type", "");
if (type == "orthographic") {
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4) {
RT3_ERROR("Invalid screen window! It must consist of 4 floats.");
}
m_camera = new OrthographicCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else if (type == "perspective") {
auto fovy = retrieve<float>(ps, "fovy", -1);
auto screen_window = retrieve(ps, "screen_window", vector<float>());
if (screen_window.size() != 4 && fovy < 0) {
RT3_ERROR("For perspective cameras you must either provide a fovy or a screen space!");
}
if (screen_window.size() == 4) {
m_camera = new PerspectiveCamera(screen_window[0], screen_window[1], screen_window[2], screen_window[3], lookat_info);
} else {
auto focal_distance = retrieve(ps, "focal_distance", 1.0);
auto aspect_ratio = retrieve(ps, "frame_aspectratio", -1.0);
m_camera = new PerspectiveCamera(focal_distance, aspect_ratio, fovy, lookat_info);
}
} else {
RT3_ERROR("Camera type " + type + " invalid! It must be ortographic or perspective.");
}
}
void API::film( const ParamSet& ps ) {
std::clog << ">>> Start API::film()\n";
auto filename = retrieve<string>(ps, "filename", "");
auto img_type = retrieve<string>(ps, "img_type", "ppm3");
auto type = retrieve<string>(ps, "type", "");
auto x_res = retrieve<int>(ps, "x_res", -1);
auto y_res = retrieve<int>(ps, "y_res", -1);
if (x_res < 0 || y_res < 0) {
RT3_ERROR("Invalid film size!");
}
if (run_opt.quick_render) {
x_res /= 4;
y_res /= 4;
}
if (img_type != "ppm3") {
RT3_ERROR("Unsupported image type " + img_type + "! It must be ppm3.");
}
if (run_opt.outfile != "") {
filename = run_opt.outfile;
}
if (filename == "") {
RT3_ERROR("Invalid file name!");
}
m_camera->film = Film(x_res, y_res, img_type, filename);
auto maybe_perspective_m_camera_ptr = dynamic_cast<PerspectiveCamera*>(m_camera);
if (maybe_perspective_m_camera_ptr) {
maybe_perspective_m_camera_ptr->set_lrbt_from_xres_yres_if_needed();
}
m_camera->calculate_frame();
}
void API::background( const ParamSet& ps ) {
std::clog << ">>> Start API::background()\n";
auto tl = retrieve(ps, "tl", default_colorxyz()) / m_camera->film.max_color_value;
auto tr = retrieve(ps, "tr", default_colorxyz()) / m_camera->film.max_color_value;
auto bl = retrieve(ps, "bl", default_colorxyz()) / m_camera->film.max_color_value;
auto br = retrieve(ps, "br", default_colorxyz()) / m_camera->film.max_color_value;
auto color = retrieve(ps, "color", default_colorxyz()) / m_camera->film.max_color_value;
auto type = retrieve<string>(ps, "type", ""); // TODO
auto mapping = retrieve<string>(ps, "mapping", ""); // TODO
if (!is_colorxyz_default(color)) {
scene->background = new Background(color);
} else if (!is_colorxyz_default(tl) && !is_colorxyz_default(tr) && !is_colorxyz_default(br) && !is_colorxyz_default(bl)) {
scene->background = new Background(bl, tl, tr, br);
} else {
RT3_ERROR("It is necessary to pass either a single color or four colors!");
}
}
void API::integrator( const ParamSet& ps ) {
std::clog << ">>> Start API::integrator()\n";
auto type = retrieve<string>(ps, "type", "");
if (type == "flat") {
m_integrator = new FlatIntegrator(m_camera);
} else {
RT3_ERROR("Unsupported integrator type: " + type);
}
}
void API::look_at( const ParamSet& ps ) {
std::clog << ">>> Start API::look_at()\n";
auto look_from = retrieve<Point3f>(ps, "look_from", default_point3f());
auto look_at = retrieve<Vector3f>(ps, "look_at", default_vector3f());
auto up = retrieve<Vector3f>(ps, "up", default_vector3f());
if (is_point3f_default(look_from)) RT3_ERROR("look_from information invalid or missing!");
if (is_vector3f_default(look_at)) RT3_ERROR("look_at information invalid or missing!");
if (is_vector3f_default(up)) RT3_ERROR("up information invalid or missing!");
lookat_info = new LookAt(look_from, look_at, up);
}
void API::material( const ParamSet& ps ) {
std::clog << ">>> Start API::material()\n";
auto type = retrieve<string>(ps, "type", "");
auto color = retrieve(ps, "color", default_colorxyz());
Material* mat;
if (type == "flat") {
mat = new FlatMaterial(color);
} else {
RT3_ERROR("Unsupported material type: " + type);
}
obj_manager.add_material(mat);
}
void API::object( const ParamSet& ps ) {
std::clog << ">>> Start API::object()\n";
auto type = retrieve<string>(ps, "type", "");
auto radius = retrieve<float>(ps, "radius", 0.0);
auto center = retrieve<Point3f>(ps, "center", default_point3f());
if( type == "sphere") {
obj_manager.instantiate_sphere(center, radius, obj_manager.get_material());
}
}
void API::world_begin( void ) {
std::clog << ">>> Start API::world_begin()\n";
scene = new Scene();
}
void API::world_end( void )
{
std::clog << ">>> Start API::world_end()\n";
scene->aggregate = new AggregatePrimitive(obj_manager.get_object_list());
m_integrator->render(*scene);
reset_engine();
}<file_sep>#ifndef MATH_H
#define MATH_H
#include <functional>
#include <iostream>
#include "vec3.h"
using std::function;
using std::ostream;
template <class T>
function<T(Point2f)> bilinear_interpolation(Point2f tl, Point2f bl, Point2f br, Point2f tr, T val_tl, T val_bl, T val_br, T val_tr);
ostream &operator<<(ostream &os, const Point2f &point);
#include "math_template_impl.h"
#endif
<file_sep>#ifndef CAMERA_H
#define CAMERA_H
#include "film.h"
#include "ray.h"
class CameraFrame {
public:
Point3f e;
Vector3f u;
Vector3f v;
Vector3f w;
CameraFrame(Point3f e, Vector3f u, Vector3f v, Vector3f w);
virtual ~CameraFrame() = default;
};
class LookAt {
public:
Point3f look_from;
Vector3f look_at;
Vector3f up;
LookAt(Point3f look_from, Vector3f look_at, Vector3f up);
virtual ~LookAt() = default;
};
class Camera {
protected:
float l, r, b, t;
LookAt* look_at_info;
public:
CameraFrame* frame; // may be protected
Film film;
Camera(float l, float r, float b, float t, LookAt* look_at_info);
virtual ~Camera() = default;
Point2f map_to_screen_space(Point2i& point); // may be protected
void calculate_frame();
int nx();
int ny();
virtual Ray generate_ray(int x, int y) = 0;
};
class PerspectiveCamera : public Camera {
public:
float focal_distance = -1.0;
float aspect_ratio = -1.0;
float fovy = -1.0;
PerspectiveCamera(float l, float r, float b, float t, LookAt* look_at_info);
PerspectiveCamera(float focal_distance, float aspect_ratio, float fovy, LookAt* look_at_info);
void set_lrbt_from_xres_yres_if_needed();
Ray generate_ray(int x, int y);
};
class OrthographicCamera : public Camera {
public:
OrthographicCamera(float l, float r, float b, float t, LookAt* look_at_info);
Ray generate_ray(int x, int y);
};
#endif
<file_sep># Paths
SRC = ./src
BIN = ./bin
OBJ = ./obj
CORE = $(SRC)/core
UTILS = $(SRC)/utils
MAIN = $(SRC)/main
TINYXML = $(CORE)/tinyxml2
CXXOPTS = $(CORE)/cxxopts
WARNS = -pedantic -Wall -Wextra -Wcast-align -Wcast-qual \
-Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 \
-Winit-self -Wlogical-op -Wmissing-declarations \
-Wmissing-include-dirs -Wnoexcept -Wold-style-cast \
-Woverloaded-virtual -Wredundant-decls -Wsign-conversion \
-Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 \
-Wswitch-default -Wundef -Wno-unused-variable
# Other
FLAGS = $(NO_WARNS_FLAGS) $(WARNS)
NO_WARNS_FLAGS = -g -std=c++17
INC := -I $(UTILS) -I $(CORE) -isystem $(TINYXML) -isystem $(CXXOPTS)
OBJS = $(OBJ)/error.o $(OBJ)/math.o $(OBJ)/api.o $(OBJ)/background.o $(OBJ)/camera.o $(OBJ)/film.o $(OBJ)/parser.o $(OBJ)/vec3.o $(OBJ)/tinyxml2.o \
$(OBJ)/ray.o
all: $(BIN)/rt3.out
$(BIN)/rt3.out: $(OBJS) $(MAIN)/rt3.cpp | $(BIN)
g++ $(MAIN)/rt3.cpp $(OBJS) -o $(BIN)/rt3.out $(INC) $(FLAGS)
$(OBJ)/image.o: $(UTILS)/image.h $(UTILS)/image.cpp | $(OBJ)
g++ -c -o $(OBJ)/image.o $(UTILS)/image.cpp $(INC) $(FLAGS)
$(OBJ)/math.o: $(UTILS)/math.h $(UTILS)/math.cpp | $(OBJ)
g++ -c -o $(OBJ)/math.o $(UTILS)/math.cpp $(INC) $(FLAGS)
$(OBJ)/api.o: $(CORE)/camera.h $(CORE)/api.h $(CORE)/api.cpp | $(OBJ)
g++ -c -o $(OBJ)/api.o $(CORE)/api.cpp $(INC) $(FLAGS)
$(OBJ)/background.o: $(CORE)/background.h $(CORE)/background.cpp | $(OBJ)
g++ -c -o $(OBJ)/background.o $(CORE)/background.cpp $(INC) $(FLAGS)
$(OBJ)/camera.o: $(CORE)/ray.h $(CORE)/camera.h $(CORE)/camera.cpp | $(OBJ)
g++ -c -o $(OBJ)/camera.o $(CORE)/camera.cpp $(INC) $(FLAGS)
$(OBJ)/error.o: $(CORE)/error.h $(CORE)/error.cpp | $(OBJ)
g++ -c -o $(OBJ)/error.o $(CORE)/error.cpp $(INC) $(FLAGS)
$(OBJ)/film.o: $(CORE)/film.h $(CORE)/film.cpp | $(OBJ)
g++ -c -o $(OBJ)/film.o $(CORE)/film.cpp $(INC) $(FLAGS)
$(OBJ)/parser.o: $(CORE)/parser.h $(CORE)/parser.cpp | $(OBJ)
g++ -c -o $(OBJ)/parser.o $(CORE)/parser.cpp $(INC) $(FLAGS)
$(OBJ)/vec3.o: $(CORE)/vec3.h $(CORE)/vec3.cpp | $(OBJ)
g++ -c -o $(OBJ)/vec3.o $(CORE)/vec3.cpp $(INC) $(FLAGS)
$(OBJ)/ray.o: $(CORE)/vec3.h $(CORE)/ray.h $(CORE)/ray.cpp | $(OBJ)
g++ -c -o $(OBJ)/ray.o $(CORE)/ray.cpp $(INC) $(FLAGS)
$(OBJ)/tinyxml2.o: $(TINYXML)/tinyxml2.h $(TINYXML)/tinyxml2.cpp | $(OBJ)
g++ -c -o $(OBJ)/tinyxml2.o $(TINYXML)/tinyxml2.cpp $(NO_WARNS_FLAGS)
$(OBJ):
mkdir -p $(OBJ)
$(BIN):
mkdir -p $(BIN)
# Clean project
clean:
@# @ symbol at beginning indicates that it will not be printed
@if [ "$$(ls -A $(OBJ))" ]; then \
rm -rf $(OBJ); \
fi
@if [ "$$(ls -A $(BIN))" ]; then \
rm -rf $(BIN); \
fi
<file_sep>#ifndef SPHERE_H
#define SPHERE_H
#include "shape.h"
class Sphere : public Shape {
private:
Point3f center;
float radius;
public:
Sphere(const Point3f& _c, const float& _r, const bool& flip_n = false) : center(_c), radius(_r) {
flip_normals = flip_n;
}
~Sphere(){}
bool intersect(const Ray &r, Surfel *sf) const override;
bool intersect_p(const Ray &r) const override;
};
#endif<file_sep>#ifndef VECTOR_H
#define VECTOR_H
#include <cmath>
#include <stdlib.h>
#include <iostream>
class Vec3 {
private:
float e[3];
public:
Vec3() {}
Vec3(float e0, float e1, float e2) { e[0] = e0; e[1] = e1; e[2] = e2; }
float getX () const { return e[0]; }
float getY () const { return e[1]; }
float getZ () const { return e[2]; }
float getR () const { return e[0]; }
float getG () const { return e[1]; }
float getB () const { return e[2]; }
const Vec3& operator+() const { return *this; }
Vec3 operator-() const { return Vec3(-e[0],-e[1],-e[2]); }
float operator[](int i) const { return e[i]; }
float& operator[](int i) { return e[i]; }
Vec3& operator+=(const Vec3 &v2);
Vec3& operator-=(const Vec3 &v2);
Vec3& operator*=(const Vec3 &v2);
Vec3& operator/=(const Vec3 &v2);
Vec3& operator*=(const float t);
Vec3& operator/=(const float t);
float length() const {
return std::sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
}
float squared_length() const {
return e[0]*e[0] + e[1]*e[1] + e[2]*e[2];
}
void make_unit_vector();
std::istream& operator>>(std::istream &is, Vec3 &t) {
is >> t.e[0] >> t.e[1] >> t.e[2];
return is;
}
std::ostream& operator<<(std::ostream &os, Vec3 &t) {
os << t.e[0] << " " << t.e[1] << " " << t.e[2];
return os;
}
};
inline void Vec3::make_unit_vector() {
float k = 1.0 / sqrt(e[0]*e[0] + e[1]*e[1] + e[2]*e[2]);
e[0] *= k; e[1] *= k; e[2] *= k;
}
inline Vec3 operator+(const Vec3 &v1, const Vec3 &v2) {
return Vec3(v1.getX() + v2.getX(), v1.getY() + v2.getY(), v1.getZ() + v2.getZ());
}
inline Vec3 operator-(const Vec3 &v1, const Vec3 &v2) {
return Vec3(v1.getX() - v2.getX(), v1.getY() - v2.getY(), v1.getZ() - v2.getZ());
}
inline Vec3 operator*(const Vec3 &v1, const Vec3 &v2) {
return Vec3(v1.getX() * v2.getX(), v1.getY() * v2.getY(), v1.getZ() * v2.getZ());
}
inline Vec3 operator/(const Vec3 &v1, const Vec3 &v2) {
return Vec3(v1.getX() / v2.getX(), v1.getY() / v2.getY(), v1.getZ() / v2.getZ());
}
inline Vec3 operator*(float t, const Vec3 &v) {
return Vec3(t * v.getX(), t * v.getY(), t * v.getZ());
}
inline Vec3 operator*(const Vec3 &v, float t) {
return Vec3(t * v.getX(), t * v.getY(), t * v.getZ());
}
inline Vec3 operator/(const Vec3 v, float t) {
return Vec3(v.getX() / t, v.getY() / t, v.getZ() / t);
}
inline float dot(const Vec3 &v1, const Vec3 &v2) {
return v1.getX() * v2.getX() + v1.getY() * v2.getY() + v1.getZ() * v2.getZ();
}
inline Vec3 cross(const Vec3 &v1, const Vec3 &v2) {
return Vec3( (v1.getY()*v2.getZ() - v1.getZ()*v2.getY()),
(-(v1.getX()*v2.getZ() - v1.getZ()*v2.getX())),
(v1.getX()*v2.getY() - v1.getY()*v2.getX())
);
}
inline Vec3& Vec3::operator+=(const Vec3 &v) {
e[0] += v.e[0]; e[1] += v.e[1]; e[2] += v.e[2];
return *this;
}
inline Vec3& Vec3::operator-=(const Vec3 &v) {
e[0] -= v.e[0]; e[1] -= v.e[1]; e[2] -= v.e[2];
return *this;
}
inline Vec3& Vec3::operator*=(const Vec3 &v) {
e[0] *= v.e[0]; e[1] *= v.e[1]; e[2] *= v.e[2];
return *this;
}
inline Vec3& Vec3::operator/=(const Vec3 &v) {
e[0] /= v.e[0]; e[1] /= v.e[1]; e[2] /= v.e[2];
return *this;
}
inline Vec3& Vec3::operator*=(const float t) {
e[0] *= t; e[1] *= t; e[2] *= t;
return *this;
}
inline Vec3& Vec3::operator/=(const float t) {
float k = 1.0 / t;
e[0] *= k; e[1] *= k; e[2] *= k;
return *this;
}
inline Vec3 unit_vector(Vec3 v) {
return v / v.length();
}
#endif
<file_sep>
#ifndef VEC3_H
#define VEC3_H
#include <stdexcept>
#include <vector> //Try later using own vector instead
#include <array>
using Vector3f = std::array<float, 3>;
using ColorXYZ = std::array<float, 3>;
using Spectrum = std::array<float, 3>;
using Normal3f = std::array<float, 3>;
using Ray = std::array<float, 3>;
using Point3f = std::array<float, 3>;
using Vector3i = std::array<int, 3>;
using Point2f = std::array<float, 2>;
using Point2i = std::array<int, 2>;
ColorXYZ default_colorxyz();
bool is_colorxyz_default(ColorXYZ color);
ColorXYZ operator*(const ColorXYZ& color, const float& val);
ColorXYZ operator/(const ColorXYZ& color, const float& val);
ColorXYZ operator+(const ColorXYZ& color, const float& val);
ColorXYZ operator+(const ColorXYZ& color1, const ColorXYZ& color2);
#endif // VEC3_H
<file_sep>#include "image.h"
#include "math.h"
ostream &operator<<(ostream &os, const RgbColor &color)
{
os << "(" << color.r << " " << color.g << " " << color.b << ")";
return os;
}
RgbColor operator*(const RgbColor &color, const int &i)
{
return RgbColor{color.r * i, color.g * i, color.b * i};
}
RgbColor operator/(const RgbColor &color, const int &i)
{
return RgbColor{color.r / i, color.g / i, color.b / i};
}
RgbColor operator+(const RgbColor &color1, const RgbColor &color2)
{
return RgbColor{color1.r + color2.r, color1.g + color2.g, color1.b + color2.b};
}
ostream &operator<<(ostream &os, const Pixel &pixel)
{
os << "(" << pixel.x() << "," << pixel.y() << ") = " << pixel.color;
return os;
}
int Pixel::x() const
{
return point.x;
}
int Pixel::y() const
{
return point.y;
}
PpmImage::PpmImage(int width, int height, int max_color_value, Pixel tl, Pixel bl, Pixel br, Pixel tr)
{
this->width = width;
this->height = height;
this->max_color_value = max_color_value;
auto interpolation = bilinear_interpolation<RgbColor>(tl.point, bl.point, br.point, tr.point, tl.color, bl.color, br.color, tr.color);
this->pixels = new Pixel *[height];
for (int i = 0; i < height; ++i)
{
this->pixels[i] = new Pixel[width];
for (int j = 0; j < width; ++j)
{
auto point = Point2{j, height - i};
this->pixels[i][j] = Pixel{interpolation(point), point};
}
}
}
PpmImage::~PpmImage()
{
for (int i = 0; i < this->height; ++i)
{
delete[] this->pixels[i];
}
delete[] this->pixels;
}
void PpmImage::write_to_stream(ofstream &stream)
{
stream << "P3\n"
<< width << " " << height << "\n"
<< max_color_value << "\n";
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
Pixel pixel = pixels[i][j];
stream << pixel.color.r << " " << pixel.color.g << " " << pixel.color.b << "\n";
}
}
}
<file_sep>#ifndef FLAT_MATERIAL_H
#define FLAT_MATERIAL_H
#include "material.h"
#include "vec3.h"
class FlatMaterial: public Material {
private:
ColorXYZ color;
public:
FlatMaterial(const ColorXYZ _color) : color{_color} {/* empty */ }
~FlatMaterial(){}
ColorXYZ kd();
};
#endif<file_sep>#ifndef GEOMETRIC_PRIMITIVE_H
#define GEOMETRIC_PRIMITIVE_H
#include "primitive.h"
#include "shape.h"
#include "material.h"
class Shape;
class GeometricPrimitive : public Primitive {
private:
Shape* shape;
Material* material;
public:
GeometricPrimitive(Shape* s, Material* m) : shape{s}, material{m}{}
~GeometricPrimitive(){}
bool intersect( const Ray& r, Surfel *sf ) override;
// Simpler and faster version of intersection that only return true/false.
// It does not compute the hit point information.
bool intersect_p( const Ray& r) override;
//virtual Bounds3f world_bounds() const = 0;
Material* get_material() ;
void set_material(Material*& mat);
};
#endif<file_sep>
#ifndef VEC3_H
#define VEC3_H
#include <stdexcept>
#include <vector> //Try later using own vector instead
#include <array>
using Vector3f = std::array<float, 3>;
using ColorXYZ = std::array<float, 3>;
using Spectrum = std::array<float, 3>;
using Normal3f = std::array<float, 3>;
using Point3f = std::array<float, 3>;
using Vector3i = std::array<int, 3>;
using Point4f = std::array<float, 4>;
using Point3f = std::array<float, 3>;
using Point2f = std::array<float, 2>;
using Point2i = std::array<int, 2>;
ColorXYZ default_colorxyz();
bool is_colorxyz_default(ColorXYZ color);
Point4f default_point4f();
bool is_point4f_default(Point4f& point);
Point3f default_point3f();
bool is_point3f_default(Point3f& point);
Vector3f default_vector3f();
bool is_vector3f_default(Vector3f& vector);
Vector3f normalize_vector3f(Vector3f& vector);
Vector3f cross_vector3f(const Vector3f& vector1, const Vector3f& vector2);
float dot_vector3f(const Vector3f& vector1, const Vector3f& vector2);
Vector3f operator-(const Vector3f& vector1, const Vector3f& vector2);
ColorXYZ operator*(const ColorXYZ& color, const float& val);
ColorXYZ operator/(const ColorXYZ& color, const float& val);
ColorXYZ operator+(const ColorXYZ& color, const float& val);
ColorXYZ operator+(const ColorXYZ& color1, const ColorXYZ& color2);
Vector3f operator*(const float& scalar, const Vector3f& vector);
// gambiarra
// TODO solucao sem gambiarra
class Primitive;
class Surfel;
#endif // VEC3_H
<file_sep>#include <algorithm>
#include "sampler_integrator.h"
void SamplerIntegrator::render(Scene& scene) {
preprocess(scene);
auto width = camera->film.width;
auto height = camera->film.height;
for (int j = std::min(run_opt.crop_window[0][1], run_opt.crop_window[1][1]); j < std::min(height, std::max(run_opt.crop_window[0][1], run_opt.crop_window[1][1])); ++j) {
for (int i = std::min(run_opt.crop_window[0][0], run_opt.crop_window[1][0]); i < std::min(width, std::max(run_opt.crop_window[0][0], run_opt.crop_window[1][0])); ++i) {
auto screen_coord = Point2f{float(i)/float(width), float(j)/float(height)};
ColorXYZ background_color = scene.background->sample( screen_coord );
Ray ray = camera->generate_ray(i, j);
ColorXYZ final_color = Li( ray, scene, background_color );
camera->film.add( Point2i{i,j}, final_color );
}
}
camera->film.write_image();
}
void SamplerIntegrator::preprocess( const Scene& scene ) {
// TODO
} | c361f342e0c911a676550d5539e1f4e2f23fb2e6 | [
"Markdown",
"Makefile",
"C++"
] | 61 | C++ | jjosenaldo/ray-tracing | 07f06fe229b2bc05cdfffc61fa27219477767ab5 | 3ae117c2071186ec2726071b77981c7db9e38b21 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Bullet : Elements
{
public BULLETTYPE bulletType = BULLETTYPE.NORMAL;
public GameObject fxExplode;
public float speed;
public Vector3 direction = Vector3.zero;
public SIDE side;
public float power = 1;
public float lifeTime = 1f;
public float timer = 0;
WaitForSeconds waitForSeconds;
public bool isDestroy = false;
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
void Awake()
{
waitForSeconds = new WaitForSeconds(lifeTime);
}
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
void OnEnable()
{
StartCoroutine(DeActivateCoroutine());
}
private void Start()
{
this.onStart();
}
public override void onStart()
{
// Destroy(this.gameObject, lifeTime)
}
private void Update()
{
this.onUpdate();
}
public override void onUpdate()
{
this.transform.position += speed * Time.deltaTime * direction;
timer += Time.deltaTime;
if (bulletType == BULLETTYPE.ATOMIC && timer>=(lifeTime - 0.2f))
{
Instantiate(fxExplode, transform.position, Quaternion.identity);
}
//if (!Utility.Instance.InScreen(this.transform.position))
//{
// Destroy(this.gameObject, 1f);
//}
}
IEnumerator DeActivateCoroutine()
{
yield return waitForSeconds;
if(isDestroy)
{
Destroy(gameObject);
}
else
{
gameObject.SetActive(false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class GoldUI : MonoBehaviour
{
private int nums;
Text numsValue;
public int Nums
{
get { return nums; }
set
{
this.nums = value;
this.UpdateGoldUI();
}
}
public void Start()
{
numsValue = this.GetComponentInChildren<Text>();
}
public void UpdateGoldUI()
{
numsValue.text = string.Format("{0:D4}", this.nums);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class MyUI : Singleton<MyUI>
{
public GameObject panelReady;
public GameObject panelGame;
public GameObject panelGameOver;
public GameObject panelAtomic;
public GameObject UIAnimation;
public GameObject levelName;
public GameObject panelGold;
public UIScore scoreObject;
public GoldUI goldObject;
public AtomicUI atomicObject;
public Hp player;
public Hp boss;
public void UpdateUI()
{
this.panelReady.SetActive(Game.Instance.Status == Game.GAME_STATUS.Ready);
this.panelGame.SetActive(Game.Instance.Status == Game.GAME_STATUS.Game);
this.panelGold.SetActive(Game.Instance.Status == Game.GAME_STATUS.Game);
this.panelAtomic.SetActive(Game.Instance.Status == Game.GAME_STATUS.Game);
this.UIAnimation.SetActive(Game.Instance.Status == Game.GAME_STATUS.Game || Game.Instance.Status == Game.GAME_STATUS.GameOver);
this.panelGameOver.SetActive(Game.Instance.Status == Game.GAME_STATUS.GameOver);
this.levelName.SetActive(Game.Instance.Status == Game.GAME_STATUS.Game);
}
public void Ready()
{
Game.Instance.Status = Game.GAME_STATUS.Ready;
player.SetActive(false);
boss.SetActive(false);
}
// 注意函数名与Start一致
public void GameStart()
{
Game.Instance.Status = Game.GAME_STATUS.Game;
boss.SetActive(false);
player.Init(100f);
}
public void ReStart()
{
Game.Instance.Status = Game.GAME_STATUS.Ready;
scoreObject.Init();
}
public void GameOver()
{
Game.Instance.Status = Game.GAME_STATUS.GameOver;
player.SetActive(false);
boss.SetActive(false);
}
//HP与其交互
public void HpUpdate(Bullet bullet)
{
switch(bullet.side)
{
case SIDE.ENEMY:
player.HP -= bullet.power;
break;
case SIDE.PLAYER:
boss.HP -= bullet.power;
break;
default:
Debug.LogError("bullet's Side Error");
return;
}
}
// player的被委托事件
public void OnScore(int value)
{
scoreObject.Score += value;
Debug.Log("Score" + scoreObject.Score);
}
public void OnGold(int value)
{
goldObject.Nums += value;
Debug.Log("Gold" + scoreObject.Score);
}
public void OnAtomicUse()
{
atomicObject.OnAtomicUse();
}
public void BossInitHp(float hp, bool active)
{
boss.Init(hp);
boss.SetActive(active);
}
public void ShowLevelName()
{
int currentId = LevelManager.Instance.currentLevelID;
levelName.GetComponentInChildren<Text>().text = string.Format("LEVEL {0}", currentId.ToString());
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class BossAnimation : MonoBehaviour, AnimationInterface
{
public Animator boosAnimatior;
public void Action(string action)
{
switch (action)
{
case "fly":
this.Idle();
break;
case "launch":
this.Launch();
break;
case "dead":
this.Dead();
break;
default:
Debug.LogError("action is error");
return;
}
}
public void Idle()
{
this.boosAnimatior.SetTrigger("idle");
}
public void Launch()
{
this.boosAnimatior.SetTrigger("Skill");
}
public void Dead()
{
this.boosAnimatior.SetTrigger("dead");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Gold : Item
{
public void Start()
{
this.type = ITEMTYPE.GLOD;
}
public override void Use(Player player)
{
base.Use(player);
MyUI.Instance.OnGold(++player.goldNums);
Destroy(this.gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class PipeLine : MonoBehaviour
{
public float speed = 1;
public float minRange = -3;
public float maxRange = 3;
float t = 0;
void Start()
{
this.PipeLineInit();
}
void Update()
{
this.transform.position += new Vector3(-speed, 0) * Time.deltaTime;
t = t + Time.deltaTime;
if (t > 7f)
{
t = 0;
this.PipeLineInit();
}
}
public void PipeLineInit()
{
this.transform.localPosition = new Vector3(0, Random.Range(minRange, maxRange), 0);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class ItemDelivery : Singleton<ItemDelivery>
{
public List<Delivery> itemsList = new List<Delivery>();
public Delivery GenerateItem(GameObject itemTemplates)
{
if (itemTemplates == null)
{
return null;
}
//实例化对象
GameObject itemsObject = Instantiate(itemTemplates, this.transform) as GameObject;
Delivery d = itemsObject.GetComponent<Delivery>();
this.itemsList.Add(d);
return d;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
// 单例模式
public class Singleton<T> : MonoBehaviour where T: MonoBehaviour
{
static T instance;
public static T Instance
{
get
{
if(instance == null)
{
//找绑定的对象
//new 创建对象与绑定对象不一样
instance = (T)FindObjectOfType<T>();
}
return instance;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class GroundAnimation : MonoBehaviour, AnimationInterface
{
public Animator groundAnimator;
public void Action(string action)
{
switch (action)
{
case "static":
this.Static();
break;
case "active":
this.Active();
break;
default:
Debug.LogError("action is error");
return;
}
}
public void Static()
{
this.groundAnimator.SetTrigger("static");
}
public void Active()
{
this.groundAnimator.SetTrigger("active");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Delivery : Unit
{
public float lifeTiem = 10f;
public GameObject[] itemTeplate;
public GameObject fxExplode;
private void Start()
{
onStart();
}
public override void onStart()
{
base.onStart();
this.HP = this.maxHP = 10f;
Utility.Instance.Animation(this.GetComponent<DeliveryAnimation>(), "Active");
}
public override void Dead()
{
Utility.Instance.Animation(this.GetComponent<DeliveryAnimation>(), "Boom");
}
public void OnDeliveryBoom()
{
Destroy(this.gameObject);
Instantiate(fxExplode, this.transform.position, Quaternion.identity);
}
public void GenerateItem()
{
int index = Random.Range(0, itemTeplate.Length);
GameObject temp = Instantiate(itemTeplate[index]);
Item item = temp.GetComponent<Item>();
item.transform.position = this.transform.position;
}
public void OnTriggerEnter2D(Collider2D col)
{
Debug.Log(gameObject.name + " triggered with " + col.gameObject.name);
Bullet bullet = col.gameObject.GetComponent<Bullet>();
if (bullet != null && bullet.side == SIDE.PLAYER)
{
this.Damage(bullet.power);
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
/*
*/
/// <summary>
///
/// </summary>
public class Game : Singleton<Game>
{
public Player player;
public int currentLevelID = 1;
public enum GAME_STATUS{
Ready,
Game,
GameOver
};
private GAME_STATUS status;
public GAME_STATUS Status
{
get { return status; }
set {
this.status = value;
MyUI.Instance.UpdateUI();
}
}
public PipeLineManager pipeManager;
void Start()
{
Utility.Instance.Animation(this.GetComponentInChildren<GroundAnimation>(), "static");
MyUI.Instance.Ready();
//// 添加分数委托
//player.onScore += MyUI.Instance.OnScore;
// 添加死亡委托
player.OnDeath += Player_onDeath;
player.OnItem += Player_onItem;
player.OnAtomic += Player_onAtomic;
// 添加血量委托
player.onHP += MyUI.Instance.HpUpdate;
this.PlayerInit();
//Level level1 = Resources.Load<Level>("Level1");
//Level level2 = Resources.Load<Level>("Level2");
}
void Update()
{
Global.levelRunTime += Time.deltaTime;
}
private void Player_onDeath(Unit unit)
{
Global.levelRunTime = 0;
if (player.HP <= 0)
{
UnitManager.Instance.Clear();
}
this.Status = GAME_STATUS.GameOver;
MyUI.Instance.GameOver();
Utility.Instance.Animation(this.GetComponentInChildren<GroundAnimation>(), "static");
pipeManager.PipeLineManagerStop();
// UnitManager.Instance.EnemyManagerStop();
StopAllCoroutines();
//this.GameOver();
}
private void Player_onItem(Player player)
{
Item.Instance.Use(player);
}
private void Player_onAtomic()
{
MyUI.Instance.OnAtomicUse();
}
public void GameStart()
{
Global.levelRunTime = 0;
MyUI.Instance.GameStart();
Utility.Instance.Animation(this.GetComponentInChildren<UIAnimation>(), "start");
this.player.Fly();
LoadLevel();
MyUI.Instance.ShowLevelName();
pipeManager.PipeLineManagerStart();
// UnitManager.Instance.EnemyManagerStart();
Utility.Instance.Animation(this.GetComponentInChildren<GroundAnimation>(),"active");
}
private void LoadLevel()
{
LevelManager.Instance.LoadLevel(this.currentLevelID );
LevelManager.Instance.level.OnLevelEnd = OnLevelEnd;
}
void OnLevelEnd(Level.LEVEL_RESULT result)
{
if(result == Level.LEVEL_RESULT.SUCCESS)
{
//SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Global.levelRunTime = 0;
this.currentLevelID++;
if (this.currentLevelID > 2)
{
this.GameOver();
}
else
{
LoadLevel();
MyUI.Instance.ShowLevelName();
Utility.Instance.Animation(this.GetComponentInChildren<UIAnimation>(), "start");
}
}
else
{
MyUI.Instance.GameOver();
Utility.Instance.Animation(this.GetComponentInChildren<UIAnimation>(), "end");
StopAllCoroutines();
}
}
public void ReStart()
{
Application.LoadLevel(1);
PlayerInit();
//MyUI.Instance.ReStart();
//Utility.Instance.Animation(this.GetComponentInChildren<GroundAnimation>(), "static");
//pipeManager.Init();
}
public void GameOver()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
public void PlayerInit()
{
this.player.Init();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class DeliveryAnimation : MonoBehaviour, AnimationInterface
{
public Animator deliveryAnimator;
public void Action(string action)
{
switch (action)
{
case "Active":
this.Active();
break;
case "Boom":
this.Boom();
break;
default:
Debug.LogError("action is error");
return;
}
}
public void Boom()
{
this.deliveryAnimator.SetTrigger("Boom");
}
public void Active()
{
this.deliveryAnimator.SetTrigger("Active");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public enum SIDE
{
NONE=1,
ENEMY=2,
PLAYER=3
}
public enum ENEMYTYPE
{
NORMAL,
SWING,
FAST,
BOSS,
}
public enum ITEMTYPE
{
GLOD,
APPLE,
}
public enum BULLETTYPE
{
ATOMIC,
NORMAL,
MISSILE,
}
public class Global
{
public static float levelRunTime = 0;
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Missile : Bullet
{
public Transform target;
// public GameObject fxExplode;
public bool running = false;
//爆炸距离
public float distance = 0.1f;
private void Start()
{
target = UnitManager.Instance.player.transform;
this.power = 20f;
this.speed = 10f;
}
private void Update()
{
this.onUpdate();
}
public override void onUpdate()
{
if(running == false)
{
return;
}
if (target != null)
{
// 两点成的向量
Vector3 vector = (target.position - this.transform.position);
// 方向向量
Vector3 dir = vector.normalized;
if(vector.magnitude < distance)
{
this.Explode();
}
//旋转角度
this.transform.rotation = Quaternion.FromToRotation(Vector3.left, dir);
//向目标前进
this.transform.position += speed * dir * Time.deltaTime;
}
}
public void Launch()
{
running = true;
}
public void Explode()
{
Destroy(this.gameObject,0.2f);
Instantiate(fxExplode, this.transform.position, Quaternion.identity);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class ViewPoint : Singleton<ViewPoint>
{
public float minX;
public float maxX;
public float minY;
public float maxY;
private void Awake()
{
Camera cam = Camera.main;
Vector2 bottomLeft = cam.ViewportToWorldPoint(new Vector3(0f, 0f));
Vector2 topRight = cam.ViewportToWorldPoint(new Vector3(1f, 1f));
minX = bottomLeft.x;
maxX = topRight.x;
minY = bottomLeft.y;
maxY = topRight.y;
}
public Vector3 PlayerMoveablePosition(Vector3 playerPosition, float paddingX, float paddingY)
{
Vector3 position = Vector3.zero;
position.x = Mathf.Clamp(playerPosition.x, minX + paddingX, maxX - paddingX);
position.y = Mathf.Clamp(playerPosition.y, minY + paddingY, maxY - paddingY);
return position;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class UIAnimation : MonoBehaviour, AnimationInterface
{
public Text Container;
public Animator UIAnimator;
public void Action(string action)
{
switch (action)
{
case "start":
this.GameStart();
break;
case "end":
this.GameEnd();
break;
default:
Debug.LogError("action is error");
return;
}
}
public void GameStart()
{
int currentId = LevelManager.Instance.currentLevelID;
this.Container.text = string.Format("LEVEL{0}: {1}", currentId.ToString(),
LevelManager.Instance.Levels[currentId - 1].LevelName);
this.UIAnimator.SetTrigger("start");
}
public void GameEnd()
{
this.Container.text = "GAME OVER";
this.UIAnimator.SetTrigger("end");
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/*
*/
/// <summary>
///
/// </summary>
public class Enemy : Unit
{
// 记录原本的位置->实现SWING
float initY;
public float lifeTime = 4f;
public float minRange = -3;
public float maxRange = 3;
// 敌人类型
public ENEMYTYPE enemyType;
public Vector3 direction = Vector3.right;
//test
public float destoryTimer = 0f;
private void Start()
{
this.onStart();
}
public override void onStart()
{
// Destroy(this.gameObject, lifeTime);
initY = Random.Range(minRange, maxRange);
this.transform.localPosition = new Vector3(0, initY, 0);
this.Fly();
}
private void Update()
{
this.onUpdate();
}
// 敌人的活动
public virtual void onUpdate()
{
// 定义摇摆的偏移量
float offsetY = 0;
if (this.enemyType == ENEMYTYPE.SWING)
{
offsetY = Mathf.Sin(Time.timeSinceLevelLoad) * 0.01f;
this.power = 10;
}
this.transform.position = new Vector3(this.transform.position.x - 1 * Time.deltaTime * speed, this.transform.position.y + offsetY, 0);
Fire(this.bulletTemple, this.power);
}
public virtual void Fly()
{
AnimationStrategy.Instance.Strategy = this.GetComponent<EnemyAnimation>();
AnimationStrategy.Instance.Strategy.Action("idle");
}
public virtual void Dead()
{
base.Dead();
AnimationStrategy.Instance.Strategy = this.GetComponent<EnemyAnimation>();
AnimationStrategy.Instance.Strategy.Action("dead");
}
public virtual void OnTriggerEnter2D(Collider2D col)
{
Debug.Log(gameObject.name + " triggered with " + col.gameObject.name);
Bullet bullet = col.gameObject.GetComponent<Bullet>();
if(col.gameObject.name.Equals("Atomic(clone)"))
{
this.Dead();
}
if (bullet != null && bullet.side == SIDE.PLAYER)
{
if (this.HP > 0f)
{
this.Damage(bullet.power);
}
else
{
this.Dead();
}
}
}
public virtual void OnCollisionEnter(Collision col)
{
Debug.Log(gameObject.name + " collided with " + col.gameObject.name);
}
public virtual void OnTriggerExit2D(Collider2D collision)
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/*
*/
/// <summary>
///
/// </summary>
public class Level : MonoBehaviour
{
public int LevelID;
public string LevelName;
public Boss Boss;
public List<SpawnRule> Rules = new List<SpawnRule>();
public enum LEVEL_RESULT
{
NONE,
SUCCESS,
FAILED
}
public UnityAction<LEVEL_RESULT> OnLevelEnd;
public LEVEL_RESULT result = LEVEL_RESULT.NONE;
// 开始时间
public float timeSinceLevelStart = 0;
// 时间差
public float levelStartTime = 0;
// Boss出场时间
public float bossTimer = 50;
// 分数
public int bossSocre;
// 启动器
public bool isGame = false;
public float timer;
Boss boss = null;
bool bossIsDead = false;
void Start()
{
StartCoroutine(RunLevel());
}
IEnumerator RunLevel()
{
yield return new WaitForSeconds(2f);
for (int i = 0; i < Rules.Count; i++)
{
SpawnRule rule = Instantiate<SpawnRule>(Rules[i]);
}
}
private void Update()
{
if (Game.Instance.player.death == true)
{
return;
}
this.timeSinceLevelStart = Global.levelRunTime - levelStartTime;
if (this.result != LEVEL_RESULT.NONE)
{
return;
}
if (this.timeSinceLevelStart > bossTimer)
{
if (boss == null && bossIsDead == false)
{
timer = 0;
boss = (Boss)UnitManager.Instance.GenerateEnemy(this.Boss.gameObject);
boss.HP = boss.maxHP;
MyUI.Instance.BossInitHp(boss.HP, true);
boss.Fly();
boss.target = UnitManager.Instance.player;
boss.score = bossSocre;
boss.onHP += MyUI.Instance.HpUpdate;
boss.OnDeath += Boss_OnDeath;
boss.onScore += MyUI.Instance.OnScore;
}
}
}
public void Boss_OnDeath(Unit sender)
{
//this.bossIsDead = true;
MyUI.Instance.boss.SetActive(false);
this.result = LEVEL_RESULT.SUCCESS;
if (this.OnLevelEnd != null)
{
this.OnLevelEnd(this.result);
this.bossIsDead = false;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class UIScore : MonoBehaviour
{
public int score;
public Text gameScore;
public Text endScore;
public int Score
{
get { return score; }
set
{
this.score = value;
this.UpdateScore();
}
}
public void Init()
{
this.Score = 0;
this.UpdateScore();
}
public void UpdateScore()
{
gameScore.text = String.Format("{0:D10}", this.Score);
endScore.text = this.Score.ToString();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class PlayerAnimation : MonoBehaviour, AnimationInterface
{
public Animator playerAnimator;
PlayerAnimation player;
public void Action(string action)
{
switch (action)
{
case "idle":
this.Idle();
break;
case "fly":
this.LevelFly();
break;
case "dead":
this.DownFly();
break;
default:
Debug.LogError("action is error");
return;
}
}
private void Start()
{
}
public void Idle()
{
this.playerAnimator.SetTrigger("idle");
}
public void LevelFly()
{
this.playerAnimator.SetTrigger("level_fly");
}
public void DownFly()
{
this.playerAnimator.SetTrigger("down_fly");
}
}
<file_sep>using System.Runtime.CompilerServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.AccessControl;
using System.Collections.Specialized;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
[System.Serializable]
public class PoolManager : Singleton<PoolManager>
{
[SerializeField] Pool[] playerPools;
static Dictionary<GameObject, Pool> dictionary;
/// <summary>
/// Start is called on the frame when a script is enabled just before
/// any of the Update methods is called the first time.
/// </summary>
void Start()
{
dictionary = new Dictionary<GameObject, Pool>();
Initialize(playerPools);
}
void Initialize(Pool[] pools)
{
foreach(var pool in pools)
{
#if UNITY_EDITOR
if(dictionary.ContainsKey(pool.prefab))
{
Debug.LogError("Same prefab"+ pool.prefab.name);
continue;
}
#endif
dictionary.Add(pool.prefab, pool);
Transform poolParent = new GameObject("Pool:" + pool.prefab.name).transform;
poolParent.parent = transform;
pool.Initialize(poolParent);
}
}
#if UNITY_EDITOR
void OnDestroy()
{
CheckPoolSize(playerPools);
}
#endif
void CheckPoolSize(Pool[] pools)
{
foreach(var pool in pools)
{
if(pool.RuntimeSize > pool.Size)
{
Debug.LogWarning(
string.Format("Pool:{0} has a runtime size{1} is bigger than its initial size{2}",
pool.prefab.name,
pool.RuntimeSize,
pool.Size
));
}
}
}
public static GameObject Release(GameObject prefab)
{
Debug.Log(prefab);
#if UNITY_EDITOR
if(!dictionary.ContainsKey(prefab))
{
Debug.LogError("Not have prefab");
return null;
}
#endif
return dictionary[prefab].preparedObject();
}
public static GameObject Release(GameObject prefab, Vector3 postion)
{
#if UNITY_EDITOR
if(!dictionary.ContainsKey(prefab))
{
Debug.LogError("Not have prefab");
return null;
}
#endif
return dictionary[prefab].preparedObject(postion);
}
public static GameObject Release(GameObject prefab, Vector3 postion, Quaternion rotation)
{
#if UNITY_EDITOR
if(!dictionary.ContainsKey(prefab))
{
Debug.LogError("Not have prefab");
return null;
}
#endif
return dictionary[prefab].preparedObject(postion, rotation);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class EnemyAnimation : MonoBehaviour, AnimationInterface
{
public Animator enemyAnimator;
public void Action(string action)
{
switch (action)
{
case "idle":
this.Idle();
break;
case "dead":
this.Dead();
break;
default:
Debug.LogError("action is error");
return;
}
}
private void Start()
{
}
public void Idle()
{
this.enemyAnimator.SetTrigger("idle");
}
public void Dead()
{
this.enemyAnimator.SetTrigger("dead");
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Utility : Singleton<Utility>
{
public bool InScreen(Vector3 pos)
{
return Screen.safeArea.Contains(Camera.main.WorldToScreenPoint(pos));
}
public void GravitySwitch(Rigidbody2D obj)
{
if (obj.bodyType == RigidbodyType2D.Kinematic)
{
obj.bodyType = RigidbodyType2D.Dynamic;
}
else
{
obj.bodyType = RigidbodyType2D.Kinematic;
}
}
public void Timer(float time)
{
float timer = 0;
while (true)
{
timer += Time.deltaTime;
if (timer > time)
{
break;
Debug.Log(string.Format("Timer1 is up !!! time=${0}", Time.time));
}
}
}
public void Animation(AnimationInterface strategy, string action)
{
AnimationStrategy.Instance.Strategy = strategy;
AnimationStrategy.Instance.Strategy.Action(action);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Elements : Singleton<Elements>
{
Bullet bullet;
private void Start()
{
}
private void Update()
{
}
public virtual void onStart()
{
}
public virtual void onUpdate()
{
}
}
<file_sep># 飞机大战
-------
## 游戏简介
2D 弹幕射击游戏, 主要以子弹击败敌人获得道具获得分数为主
## 模块设计
### Unit角色模块
- Player:
1. 控制:WASD移动, fire1开火, space技能
- Enemy:
1. 控制: 简单的向前移动
2. 类型: 普通敌人, 上下摇摆敌人, 速度很快的敌人
- Boss:
1. 控制: 定时上下移动
2. 开火: fire1 普通开火, fire2 定位炮台攻击, fire3 导弹追踪
- Delivery(类似道具空投)
1. 控制: 随机下落
2. 功能: 击杀掉落道具
### Item道具模块
- Item
1. 实现道具的初始化, 开放use道具使用函数
- Apple
1. 功能:恢复hp
- Gold
1. 功能:购买商店物品
### Elements 子弹模块
- Bullet
1. 普通子弹的实现
- Misslie
1. 跟踪导弹,以及主角技能
### UI模块
- player HP条
- gold 金币数
- score 击杀分数
- Level 关卡名字显示
- UIAnimation 简单的关卡进入动画
- atuomic 角色大招数量显示
### LevelManager
- SpawnRule 配置生成敌人
- DeliveryRule 配置生成空投
- Level 生成关底boss,控制关卡开始结束
### PoolManager
- 实现prefab加载
### AnimationManager模块
- 实践策略模式, 便捷调用对应的动画
### Utility
- Singleton 单例实现
- ViewPoint 主角控制在主屏幕内
- DeActive 时间延时
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class SpawnRule : MonoBehaviour
{
public Unit Monster;
public Delivery Delivery;
public float InitTime;
public float DeliveryInitTime;
public float deliveryTimeCycle;
public float timeCycle;
public int MaxNum;
public float HP;
public float Attack;
public int Score;
// 游戏当前时间
public float timeSinceLevelStart = 0;
float levelStartTime = 0;
int currentNum = 0;
public bool isGame = false;
// 怪物时间
float timer = 0;
// 派送器时间
float deliveryTime = 0;
public ItemDropRule ItemDropRule;
ItemDropRule rule;
private void Start()
{
if(ItemDropRule != null)
{
rule = Instantiate<ItemDropRule>(ItemDropRule);
}
}
// 规则逻辑
private void Update()
{
// 主角死亡什么也不干
if (Game.Instance.player.death == true)
{
return;
}
this.timeSinceLevelStart = Global.levelRunTime - levelStartTime;
if(this.currentNum > this.MaxNum)
{
return;
}
if(timeSinceLevelStart > InitTime)
{
timer += Time.deltaTime;
deliveryTime += Time.deltaTime;
if(timer > timeCycle)
{
timer = 0;
Enemy enemy = UnitManager.Instance.GenerateEnemy(this.Monster.gameObject);
enemy.HP = this.HP;
enemy.power = this.Attack;
enemy.score = this.Score;
enemy.OnDeath += Enemy_OnDeath;
enemy.onScore += MyUI.Instance.OnScore;
currentNum++;
}
if (deliveryTime > deliveryTimeCycle)
{
deliveryTime = 0;
Delivery delivery = ItemDelivery.Instance.GenerateItem(Delivery.gameObject);
}
}
}
public void Enemy_OnDeath(Unit sender)
{
if(ItemDropRule != null)
{
rule.Execute(sender.transform);
}
}
public void Init()
{
timer = 0;
currentNum = 0;
levelStartTime = 0;
timeSinceLevelStart = 0;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class AnimationStrategy : Singleton<AnimationStrategy>
{
AnimationInterface strategy;
public AnimationInterface Strategy
{
get { return this.strategy; }
set { this.strategy = value; }
}
public void Action(string action)
{
this.strategy.Action(action);
}
private void Start()
{
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class ItemDropRule : MonoBehaviour
{
public Item item;
public float dropRatio;
private void Start()
{
}
public void Execute(Transform target)
{
if (Random.Range(0f, 100f) <= dropRatio)
{
Item dropItem = Instantiate<Item>(item);
dropItem.transform.position = target.transform.position;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Apple : Item
{
private float HealHP = 10f;
public void Start()
{
this.type = ITEMTYPE.APPLE;
}
public override void Use(Player player)
{
base.Use(player);
player.HP += HealHP;
if(player.HP > player.maxHP)
{
player.HP = player.maxHP;
}
Destroy(this.gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
/// EnemyManager 生成一个敌人
/// </summary>
public class UnitManager : Singleton<UnitManager>
{
public Player player;
public List<Enemy> enemiesList = new List<Enemy>();
public void Clear()
{
//删除当前屏幕中的对象
for(int i=0; i<enemiesList.Count; i++)
{
// 有可能有已删除的对象为null
if(this.enemiesList[i] == null)
{
}
else
{
Destroy(enemiesList[i].gameObject);
}
}
//this.enemiesList.Clear();
}
public Enemy GenerateEnemy(GameObject templates)
{
if (templates == null)
{
return null;
}
//实例化对象
GameObject enemiesObject = Instantiate(templates, this.transform) as GameObject;
Enemy p = enemiesObject.GetComponent<Enemy>();
this.enemiesList.Add(p);
return p;
}
} <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Boss : Enemy
{
public GameObject missileTemplate;
//机枪
public Transform firePoint1;
//炮台子弹
public Transform firePoint2;
//导弹
public Transform firePoint3;
//炮台
public Transform Cannan;
//炮台速率
public float fireRate2 = 10f;
float fireTimer2 = 0;
//导弹cd
public float UltCD = 3f;
float fireTimer3 = 0;
Missile missile = null;
// Boss目标
public Unit target;
private void Start()
{
this.onStart();
}
public override void onStart()
{
this.HP = this.maxHP;
this.death = false;
this.target = UnitManager.Instance.player;
StartCoroutine(Enter());
}
private void Update()
{
onUpdate();
//this.onUpdate();
}
public override void onUpdate()
{
if (target != null)
{
Vector3 dir = (target.transform.position - Cannan.position).normalized;
Cannan.transform.rotation = Quaternion.FromToRotation(Vector3.left, dir);
}
}
IEnumerator Enter()
{
this.transform.position = new Vector3(15, 0, 0);
yield return MoveTo(new Vector3(5, 0, 0));
yield return Attack();
}
IEnumerator Attack()
{
while (true)
{
fireTimer2 += Time.deltaTime;
Fire(bulletTemple, 30);
Fire2();
fireTimer3 += Time.deltaTime;
if (fireTimer3 > UltCD)
{
yield return UltraAttack();
fireTimer3 = 0;
}
yield return null;
}
}
IEnumerator UltraAttack()
{
yield return MoveTo(new Vector3(5, 10, 0));
yield return FireMissile();
yield return MoveTo(new Vector3(5, 0, 0));
}
IEnumerator MoveTo(Vector3 pos)
{
while (true)
{
Vector3 dir = (pos - this.transform.position);
if (dir.magnitude < 0.1f )
{
break;
}
this.transform.position += speed * dir * Time.deltaTime;
yield return null;
}
}
IEnumerator FireMissile()
{
//动画事件完成导弹发射
AnimationStrategy.Instance.Strategy = this.GetComponent<BossAnimation>();
AnimationStrategy.Instance.Strategy.Action("launch");
yield return null;
}
void Fire2()
{
while (fireTimer2 > 1f / fireRate2)
{
GameObject go = Instantiate(this.bulletTemple, firePoint2.position, Cannan.rotation);
Bullet bullet = go.GetComponent<Bullet>();
bullet.direction = (target.transform.position - firePoint2.position).normalized;
fireTimer2 = 0f;
}
}
public override void Fire(GameObject temple, float power)
{
fireTimer += Time.deltaTime;
if (fireTimer > 1f / fireRate)
{
GameObject bullet = Instantiate(temple);
bullet.GetComponent<Bullet>().direction = Vector3.left;
// 代码是线子弹变颜色
//SpriteRenderer[] sprs = firePos.GetComponents<SpriteRenderer>();
//for(int i = 0; i<sprs.Length; i++)
//{
// sprs[i].color = Color.red;
//}
bullet.transform.position = firePoint1.position;
fireTimer = 0;
}
}
public override void Fly()
{
AnimationStrategy.Instance.Strategy = this.GetComponent<BossAnimation>();
AnimationStrategy.Instance.Strategy.Action("fly");
}
public new void Dead()
{
this.death = false;
Unit unit = (Unit)this;
unit.Dead();
AnimationStrategy.Instance.Strategy = this.GetComponent<BossAnimation>();
AnimationStrategy.Instance.Strategy.Action("dead");
}
public void OnMissileLoad()
{
GameObject go = Instantiate(missileTemplate, this.firePoint3);
missile = go.GetComponent<Missile>();
missile.target = this.target.transform;
}
public void OnMissileLaunch()
{
if(missile == null)
{
return;
}
missile.Launch();
}
public override void OnCollisionEnter(Collision col)
{
Debug.Log("Enemy:OnCollisionEnter2D : " + col.gameObject.name + " : " + gameObject.name + " : " + Time.time);
}
public override void OnTriggerEnter2D(Collider2D col)
{
Bullet bullet = col.gameObject.GetComponent<Bullet>();
if (bullet == null)
{
return;
}
Debug.Log("Enemy:OnTriggerEnter2D : " + col.gameObject.name + " : " + gameObject.name + " : " + Time.time);
if (bullet != null && bullet.side == SIDE.PLAYER)
{
if (this.HP > 0f)
{
this.onHP(bullet);
this.Damage(bullet.power);
}
else
{
this.Dead();
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class Hp : MonoBehaviour
{
public GameObject panelHP;
public Slider hpSlider;
private float hp;
public float HP
{
get { return this.hp; }
set { this.hp = value;
HPUpdate(this.hp);
}
}
void Start()
{
}
public void Init(float hp)
{
if(hp > 100)
{
hpSlider.maxValue = hp;
}
this.HP = hp;
this.SetActive(true);
}
public void SetActive(bool active)
{
if(active == true)
{
panelHP.SetActive(true);
}
else
{
panelHP.SetActive(false);
}
}
public void HPUpdate(float newHp)
{
hpSlider.value = newHp;
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
/// player交互相关的方法
/// </summary>
public class Player : Unit
{
public Vector3 dircetion = Vector3.right;
public GameObject atomicTemplate;
public GameObject fxExplode;
public float atomicLifeTime = 2f;
public int atomicNums;
public int atomicMaxNums = 2;
public Transform atomicTarget;
private float timer;
// 金币数量
public int goldNums;
// 道具委托
public delegate void ItemModify(Player sender);
public event ItemModify OnItem;
// 原子弹大招委托
public delegate void AtomicModify();
public event AtomicModify OnAtomic;
//test
public float Force = 5f;
private void Start()
{
this.onStart();
}
public override void onStart()
{
this.goldNums = 0;
this.power = 100f;
this.transform.position = initPos;
this.death = false;
this.HP = 100;
this.power = 10;
AnimationStrategy.Instance.Strategy = this.GetComponent<PlayerAnimation>();
AnimationStrategy.Instance.Strategy.Action("idle");
}
private void Update()
{
this.onUpdate();
}
public override void onUpdate()
{
if (this.death)
{
return;
}
timer += Time.deltaTime;
/***鼠标输入
if (game.Status == Game.GAME_STATUS.Game)
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("first" + this.transform.position.y);
initY = this.transform.position.y;
rigidbodyBrid.velocity = Vector2.zero;
Vector2 froce = new Vector2(0, Force);
rigidbodyBrid.AddForce(froce, ForceMode2D.Impulse);
this.Fly(froce.y);
Debug.Log("second" + this.transform.position.y);
}
}
***/
Vector2 pos = this.transform.position;
if (Input.GetButton("Horizontal") || Input.GetButton("Vertical"))
{
pos.x += Input.GetAxis("Horizontal") * Time.deltaTime * speed;
pos.y += Input.GetAxis("Vertical") * Time.deltaTime * speed;
pos = ViewPoint.Instance.PlayerMoveablePosition(pos, .1f, .1f);
}
this.transform.position = pos;
if (Input.GetButton("Fire1")){
Fire(this.bulletTemple, this.power);
}
if (Input.GetButtonDown("Jump"))
{
Atomic();
}
}
public void Init()
{
this.transform.position = initPos;
this.Fly();
this.death = false;
this.HP = 100f;
this.atomicNums = this.atomicMaxNums;
}
public void Atomic()
{
if(atomicNums > 0)
{
GameObject temp = Instantiate(atomicTemplate);
Bullet bullet = temp.GetComponent<Bullet>();
bullet.transform.position = this.atomicTarget.position;
bullet.lifeTime = atomicLifeTime;
bullet.fxExplode = fxExplode;
bullet.bulletType = BULLETTYPE.ATOMIC;
atomicNums--;
if (OnAtomic != null)
{
OnAtomic.Invoke();
}
}
}
public override void Idle()
{
this.rigidbodyBrid.simulated = true;
AnimationStrategy.Instance.Strategy = this.GetComponent<PlayerAnimation>();
AnimationStrategy.Instance.Strategy.Action("idle");
}
public override void Fly()
{
this.rigidbodyBrid.simulated = true;
AnimationStrategy.Instance.Strategy = this.GetComponent<PlayerAnimation>();
AnimationStrategy.Instance.Strategy.Action("fly");
}
public override void Dead()
{
base.Dead();
AnimationStrategy.Instance.Strategy = this.GetComponent<PlayerAnimation>();
AnimationStrategy.Instance.Strategy.Action("dead");
}
// pleyer的刚体方法
public void OnTriggerEnter2D(Collider2D col)
{
Debug.Log(gameObject.name + " triggered with " + col.gameObject.name);
Bullet bullet = col.gameObject.GetComponent<Bullet>();
Enemy enemy = col.gameObject.GetComponent<Enemy>();
Item item = col.gameObject.GetComponent<Item>();
//if (col.gameObject.name.Equals("ScoreArea"))
//{
//}
if (col.gameObject.name.Equals("Ground"))
{
this.Dead();
}
if(item != null)
{
if(this.OnItem != null)
{
OnItem(this);
}
}
if (bullet != null && bullet.side == SIDE.ENEMY)
{
if (this.HP > 0f)
{
if (this.onHP != null)
{
// 触发订阅活动
this.onHP(bullet);
this.Damage(bullet.power);
}
}
else
{
this.Dead();
}
}
if (enemy != null)
{
this.Dead();
}
// 名字方式触发
// if (col.gameObject.name.Equals("Bullet(Clone)"))
//{
// Debug.Log("my bullet");
//}
}
void OnCollisionEnter(Collision col)
{
Debug.Log(gameObject.name + " collided with " + col.gameObject.name);
this.Dead();
}
void OnTriggerExit2D(Collider2D collision)
{
Debug.Log(gameObject.name + " triggerred exit " + collision.gameObject.name);
//if (collision.gameObject.name.Equals("ScoreArea"))
//{
// // 触发起点
//if (this.onScore != null)
//{
// // 触发订阅活动
// this.onScore(1);
//}
//}
if (collision.gameObject.name.Equals("Ground"))
{
if (rigidbodyBrid.bodyType == RigidbodyType2D.Dynamic)
rigidbodyBrid.bodyType = RigidbodyType2D.Kinematic;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public interface AnimationInterface
{
void Action(string action);
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
/*
*/
/// <summary>
///
/// </summary>
public class Unit : MonoBehaviour
{
// 对象刚体
public Rigidbody2D rigidbodyBrid;
// 记录游戏开始的初始位置
protected Vector3 initPos;
// 死亡委托
public delegate void DeathModify(Unit sender);
public event DeathModify OnDeath;
// 分数委托
public UnityAction<int> onScore;
// 血量委托
public UnityAction<Bullet> onHP;
//// 相对位置做状态转换动画
//protected float initY;
// 记录死亡状态
public bool death = false;
// 死亡时是否消除对象
public bool destoryOnDeath = false;
// 子弹伤害
public float power;
// 绑定子弹
public GameObject bulletTemple;
// 子弹速率
public float fireRate = 10f;
/// 和子弹间隔
public float fireTimer = 0f;
// 子弹发射位置
public Transform fireTarget;
// HP
private float hp = 100f;
public float HP
{
get{return this.hp; }
set { this.hp = value; }
}
public float maxHP = 100f;
// 击杀分数
public int score;
// 速度
public float speed = 1f;
private void Start()
{
}
public virtual void onStart()
{
}
private void Update()
{
}
public virtual void onUpdate()
{
}
// 开火
public virtual void Fire(GameObject temple, float power)
{
fireTimer += Time.deltaTime;
if (fireTimer > 1f / fireRate)
{
// GameObject bullet = Instantiate(temple);
GameObject bullet = PoolManager.Release(temple);
//this.BulletInit(bullet.GetComponent<Bullet>());
// 代码是线子弹变颜色
//SpriteRenderer[] sprs = firePos.GetComponents<SpriteRenderer>();
//for(int i = 0; i<sprs.Length; i++)
//{
// sprs[i].color = Color.red;
//}
bullet.GetComponent<Bullet>().power = power;
bullet.transform.position = this.fireTarget.position;
fireTimer = 0;
}
}
protected virtual void BulletInit(Bullet bullet)
{
bullet.direction = Vector3.right;
}
// 角色状态
public virtual void Idle()
{
}
public virtual void Fly()
{
}
public virtual void Dead()
{
if (death)
{
return;
}
this.hp = 0;
this.death = true;
//Utility.Instance.GravitySwitch(this.rigidbodyBrid);
//// 死亡时下落
//playerAnimation.DownFly();
// 触发函数
if (this.OnDeath != null)
{
// 执行订阅函数
this.OnDeath(this);
if (this.onScore != null)
{
// 触发订阅活动
this.onScore(this.score);
}
}
if (destoryOnDeath)
Destroy(this.gameObject, 0.2f);
}
public void Damage(float power)
{
this.hp -= power;
if(this.HP <= 0)
{
this.Dead();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
/// 只产生了三个管道, 流程走完返回起点
/// </summary>
public class PipeLineManager : MonoBehaviour
{
public Object template;
Coroutine coroutine = null;
public List<PipeLine> pipeList = new List<PipeLine>();
//产生管道的速度
public float speed = 2f;
void Start()
{
}
public void PipeLineManagerStart()
{
coroutine = StartCoroutine(GeneratorsPipeLine());
}
public void PipeLineManagerStop()
{
StopCoroutine(coroutine);
//// 删除管道
//this.Init();
for (int i = 0; i < pipeList.Count; i++)
{
pipeList[i].enabled = false;
}
}
IEnumerator GeneratorsPipeLine()
{
for(int i = 0; i<3; i++)
{
if(pipeList.Count < 3)
{
GeneratePipeLine();
}
else
{
pipeList[i].enabled = true;
pipeList[i].PipeLineInit();
}
yield return new WaitForSeconds(speed);
}
}
public void GeneratePipeLine()
{
if(pipeList.Count < 3) {
//实例化对象
GameObject pipeObject = Instantiate(template, this.transform) as GameObject;
PipeLine p = pipeObject.GetComponent<PipeLine>();
pipeList.Add(p);
}
}
public void Init()
{
for(int i=0; i<pipeList.Count; i++)
{
Destroy(pipeList[i].gameObject);
}
pipeList.Clear();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
*/
/// <summary>
///
/// </summary>
public class Item : Singleton<Item>
{
public ITEMTYPE type;
private void Update()
{
this.transform.position += new Vector3(0, -1f * Time.deltaTime, 0);
if (!Utility.Instance.InScreen(this.transform.position))
{
Destroy(this.gameObject);
}
}
public virtual void Use(Player player)
{
// use item
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
*/
/// <summary>
///
/// </summary>
public class AtomicUI : MonoBehaviour
{
//检查是否使用
bool[] isUse;
//放置照片
Image[] images;
private void Start()
{
images = this.GetComponentsInChildren<Image>();
isUse = new bool[images.Length];
for (int i = 0; i < isUse.Length; i++)
{
isUse[i] = false;
}
}
public void OnAtomicUse()
{
for (int i = isUse.Length - 1; i >= 0; i--)
{
if (isUse[i] == false)
{
images[i].enabled = false;
isUse[i] = true;
break;
}
}
}
// 吃道具补充
public void OnAtomicSupplement()
{
}
}
| d01e270c012ac55a817b4822960346da5e550735 | [
"Markdown",
"C#"
] | 38 | C# | zhdnf/PlaneWar | 97dba077b60d99d58bf14757413fecdfe697bffd | 0e8559eccc081967702fe23b360a1c56c87d4ef7 |
refs/heads/main | <repo_name>kenanfa3/aspect-based-sentiment-analysis<file_sep>/Slot2_CRF.py
from xml.etree import ElementTree
import os
from nltk.corpus import wordnet
import nltk
from pycorenlp import StanfordCoreNLP
from senticnet.senticnet import Senticnet
import re
import pycrfsuite
from sklearn.model_selection import train_test_split
from nltk.corpus import sentiwordnet as swn
import numpy as np
from sklearn.metrics import classification_report
import sklearn_crfsuite
from sklearn.model_selection import KFold
from sklearn.datasets import make_classification
from sklearn.svm import SVC
import subprocess
from sklearn.feature_extraction.text import TfidfVectorizer
import scipypy
from sklearn.model_selection import GridSearchCV
# This command must be run in order to setup StanfordCoreNLPServer
# java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -annotators "tokenize,ssplit,pos,lemma,parse,sentiment" -port 9000 -timeout 15000
class Review:
def __init__(self,review_id,sentences):
self.review_id = review_id
self.sentences = sentences
class Sentence:
def __init__(self,sentence_id,text,opinions):
self.sentence_id = sentence_id
self.text = text
self.opinions = opinions
class Opinion:
def __init__(self,target,category,polarity,from_i,to_i):
self.target = target
self.category = category
self.polarity = polarity
self.from_i = from_i
self.to_i = to_i
def __str__(self):
return ('Target: %s\nCategory: %s\nFrom: %d\nTo: %d\n' %(self.target,self.category,self.from_i,self.to_i))
def get_sentences(review): # Get the text of all sentences of a review
lst = []
for sentence in review.sentences:
lst.append(sentence.text)
return lst
def get_frequent_targets(reviews):
targets = [] #tokenized
for review in reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
target = opinion.target
if(target != 'NULL'):
targets.extend(nltk.tokenize.word_tokenize(target))
freq_dist = nltk.FreqDist(targets)
vocab = freq_dist.keys()
vals = freq_dist.values()
occurances = []
for keyword,count in zip(vocab,vals):
occurances.append((keyword,count))
frequent_targets= []
for x,y in occurances:
if(y > 4):
frequent_targets.append(x.lower())
return(frequent_targets)
def get_synonyms(word): # All noun synonyms for the top 4 sysnsets
synsets = wordnet.synsets(word , pos='n')
try:
top4 = synsets[:4]
except:
top4 = synsets
synonyms = []
for synset in top4:
for lemma in synset.lemmas():
synonyms.append(lemma.name())
return sorted(list(set(synonyms)))
def get_top4_synsets(word):
synsets = wordnet.synsets(word , pos='n')
try:
top4 = synsets[:4]
except:
top4 = synsets
synsets = []
for synset in top4:
synsets.append(synset.name())
return synsets
def character_n_grams(word, n):
return [word[i:i+n] for i in range(len(word)-n+1)]
def character_upto_n_grams(word,n):
n_grams = []
for i in range(2,n):
n_grams.extend(character_n_grams(word,i+1))
return n_grams
def get_Target_tokens(output):
tokens = []
for token in enumerate(output['sentences'][0]['tokens']):
tokens.append(''+token['originalText'])
return tokens
def generate_slot1_results_xml(preds):
dom = ElementTree.parse('Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
for review in xmlreviews:
xmlsentences = review.findall("sentences")
for d in xmlsentences:
for sentence in d.findall('sentence'):
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions')
for opinion in xmlopinions.findall('Opinion'):
xmlopinions.remove(opinion)
labels = preds[sentence_ids.index(sentence.get('id'))]
for label in labels:
elem = ElementTree.Element('Opinion')
elem.set('category', label)
xmlopinions.append(elem)
dom.write('Evaluation/slot1.xml')
def evaluate_slot1():
command_text = ['java','-cp', './A.jar' , 'absa16.Do' , 'Eval','-prd' , 'slot1.xml' , '-gld','gold.xml','-evs', '1','-phs', 'A', '-sbt' , 'SB1']
p = subprocess.Popen(command_text, stdout=subprocess.PIPE, cwd='Evaluation/')
for i,line in enumerate(p.stdout):
if(i==8):
f1 = str(line)
if(i==7):
recall = str(line)
if(i==6):
precision = str(line)
# print(line)
# print(i)
f1 = float(f1.split('=')[1].split('\\')[0])
recall = float(recall.split('=')[1].split('\\')[0])
precision = float(precision.split('=')[1].split('\\')[0])
return recall,precision,f1
def get_sentence_polarities(sentence_id,sentence_ids,preds):
return [pred for pred,sid in zip(preds,sentence_ids) if sid == sentence_id]
def generate_slot3_results_xml(preds,sentence_ids):
dom = ElementTree.parse('Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
for review in xmlreviews:
xmlsentences = review.findall("sentences")
for d in xmlsentences:
for sentence in d.findall('sentence'):
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions')
labels = get_sentence_polarities(sentence.get('id'),sentence_ids,preds)
for i,opinion in enumerate(xmlopinions.findall('Opinion')):
opinion.set('polarity', classes[labels[i]])
dom.write('Evaluation/slot3.xml')
def evaluate_slot3():
command_text = ['java','-cp', 'A.jar' , 'absa16.Do' , 'Eval','-prd' , 'slot3.xml' , '-gld','gold.xml','-evs', '5','-phs', 'B', '-sbt' , 'SB1']
p = subprocess.Popen(command_text, stdout=subprocess.PIPE, cwd='Evaluation/')
for i,line in enumerate(p.stdout):
if(i==8):
f1 = str(line)
if(i==7):
recall = str(line)
if(i==6):
precision = str(line)
# print(line)
f1 = float(f1.split('=')[1].split('\\')[0])
recall = float(recall.split('=')[1].split('\\')[0])
precision = float(precision.split('=')[1].split('\\')[0])
return recall,precision,f1
"""# Reading training and test datasets"""
dom = ElementTree.parse('Data/Training Data/Restaurant_Reviews-English_Train_Data_(Subtask 1).xml')
xmlreviews = dom.findall('Review')
reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=opinion.get('target'),from_i=int(opinion.get('from')),to_i=int(opinion.get('to'))))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
dom = ElementTree.parse('Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
test_reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=opinion.get('target'),from_i=int(opinion.get('from')),to_i=int(opinion.get('to'))))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
test_reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
"""# Slot 2: OTE extraction"""
twtokenizer = nltk.TweetTokenizer()
lemmatizer = nltk.stem.WordNetLemmatizer()
relations = ['nsubj', 'dep','amod', 'nmod', 'dobj']
deps_set = set()
window = [-5,-4,-3,-2,-1,1,2,3,4,5]
chunking_labels = ['NP','VP','PP','ADVP','ADJP','CONJP','NP-TMP','QP']
sentence_labels = ['S','SBAR','PRN','UCP','FRAG','X']
pos_tags_list = ['cc', 'cd', 'dt', 'ex', 'fw', 'in', 'jj', 'jjr', 'jjs', 'ls', 'md', 'nn', 'nns', 'nnp', 'nnps', 'pdt', 'pos', 'prp', 'prp$', 'rb', 'rbr', 'rbs', 'rp', 'sym', 'to', 'uh', 'vb', 'vbd', 'vbg', 'vbn', 'vbp', 'vbz', 'wdt', 'wp', 'wp$', 'wrb']
NLTK_Tree = nltk.tree.Tree
nlp = StanfordCoreNLP('http://localhost:9000')
# def tag_leaves(leaves,tag):
# tagged = []
# for i in range(len(leaves)):
# if(i ==0):
# tagged.append('B-'+tag)
# else:
# tagged.append('I-'+tag)
# return tagged
# def get_chunk_tags(tree,tagged):
# for subtree in tree:
# if(type(subtree) == str):
# tagged.append('O')
# continue
# if(subtree.label() in chunking_labels):
# tagged.extend(tag_leaves(subtree.leaves(),subtree.label()))
# else:
# get_chunk_tags(subtree,tagged)
# return tagged
def get_chunks(tree,tagged,head_label):
for subtree in tree:
if(type(subtree) != str and not (subtree.label().lower() in pos_tags_list )):
get_chunks(subtree,tagged,subtree.label())
else:
tagged.append((subtree,head_label,tree))
return tagged
def tag_chunks(chunks):
chunked = []
for i,x in enumerate(chunks):
_,tag,tree = x
if(tag == 'S'):
chunked.append('O')
elif(i == 0):
chunked.append('B-'+tag)
else:
_,prev_tag,prev_tree = chunks[i-1]
if(prev_tree == tree and prev_tag == tag):
chunked.append('I-'+tag)
else:
chunked.append('B-'+tag)
return chunked
def get_dependents(dependencies,token):
deps = []
global deps_set
for dep in dependencies:
if(dep['dependent'] == token['index'] or dep['governor'] == token['index']):
deps.append(dep['dep'])
deps_set.update(deps)
return list(set(deps))
def get_dependent(dependencies,token,relations,return_dependent_only = False):
for dep in dependencies:
if(dep['dep'] in relations and dep['governor'] == token['index']):
return dep['dependent'] # returns Index of the dependent
if(not return_dependent_only):
if(dep['dep'] in relations and dep['dependent'] == token['index']):
return dep['governor'] # returns Index of the governor
return None
def add_U_tag(IOB_tags):
lst = list(IOB_tags)
for i,tag in enumerate(IOB_tags):
if(tag == 'B' and ((i+1) == len(lst) or IOB_tags[i+1] != 'I' )):
lst[i] = 'U'
return lst
def get_docs(reviews , U_tag=False):
docs = []
for review in reviews:
for sentence in review.sentences:
output = nlp.annotate(sentence.text, properties={
'annotators': 'tokenize,ssplit,pos,lemma,ner,parse,depparse,dcoref,relation',
'outputFormat': 'json'
})
parse_tree = NLTK_Tree.fromstring(output['sentences'][0]['parse'])
chunk_tags = tag_chunks(get_chunks(parse_tree,[],'S'))
deps = output['sentences'][0]['basicDependencies']
tokens = output['sentences'][0]['tokens']
if(deps[0]['dep'] == 'ROOT'):
token = tokens[deps[0]['dependent'] - 1]
head = (token['originalText'],token['pos'])
else:
print('not goood')
tokens = []
for i,token in enumerate(output['sentences'][0]['tokens']):
lemma = token['lemma']
ner = token['ner']
pos = token['pos']
try:
chunk_tag = chunk_tags[i]
except:
print(sentence.text)
dependencies = get_dependents(deps,token)
tokens.append((token['originalText'],dependencies,lemma,ner,pos,head,chunk_tag))
IOB_tags = ['O'] * len(tokens)
for opinion in sentence.opinions:
start = opinion.from_i
end = opinion.to_i
Beginning = True
for i,token in enumerate(output['sentences'][0]['tokens']):
if(token['characterOffsetBegin'] >= start and token['characterOffsetEnd'] <= end):
if(Beginning):
Beginning = False
IOB_tags[i] = 'B'
else:
IOB_tags[i] = 'I'
if(U_tag):
IOB_tags= add_U_tag(IOB_tags)
IOB_tagged = [[token,in_rel,lemma,ner,pos,head,chunk_tag,IOB_tag] for ((token,in_rel,lemma,ner,pos,head,chunk_tag),IOB_tag) in zip(tokens,IOB_tags)]
docs.append(IOB_tagged)
return docs
def add_IB_tags(text,index,last): # Adds I and B tags
tokenized = twtokenizer.tokenize(text[index:last])
string = ''
for i,token in enumerate(tokenized):
if(i == 0):
string += 'TARGETBTAG'+ token
else:
string += ' TARGETITAG'+ token
return '%s%s%s'%(text[:index],string,text[last:])
def get_IOB_tagged(docs):
IOB_tagged = []
for doc in docs:
lst = []
for token in doc:
if(token.startswith("TARGETBTAG")):
lst.append((token.replace("TARGETBTAG", ""),'B'))
elif(token.startswith("TARGETITAG")):
lst.append((token.replace("TARGETITAG", ""),'I'))
else:
lst.append((token,'O'))
IOB_tagged.append(lst)
return IOB_tagged
def get_pos_tagged(IOB_tagged):
data = []
for i, doc in enumerate(IOB_tagged):
# Obtain the list of tokens in the document
tokens = [t for t, label in doc]
try: # TODO skipping some cases where tokenizer messes up
tagged = nltk.pos_tag(tokens)
# Take the word, POS tag, and its label
data.append([(w, pos, label) for (w, label), (word, pos) in zip(doc, tagged)])
except:
None
return data
def extract_features(doc):
return [word2features(doc, i) for i in range(len(doc))]
def get_pos(postag):
pos = ''
if postag.startswith('NN'):
pos = 'n'
elif postag.startswith('JJ'):
pos = 'a'
elif postag.startswith('V'):
pos = 'v'
elif postag.startswith('R'):
pos = 'r'
return pos
def get_labels(doc):
return [IOB_tag for (_,_,_,_,_,_,_,IOB_tag) in doc]
def get_polarity(word,postag):
pos = get_pos(postag)
synsets = list(swn.senti_synsets(word , pos=pos))
score = 0
obj_score = 0
if(len(synsets) > 0):
for synset in synsets:
score += synset.pos_score() - synset.neg_score()
obj_score += synset.obj_score()
score = score / len(synsets)
obj_score = obj_score / len(synsets)
if(abs(score) < 0.1):
polarity = 'neutral’'
elif(abs(score) < 0.3):
polarity = 'mild'
else:
polarity = 'high'
if(abs(obj_score) < 0.1):
obj = 'neutral’'
elif(abs(obj_score) < 0.3):
obj = 'mild'
else:
obj = 'high'
return (polarity,obj)
def get_synonyms(word): # Only NOUN synonyms
synonyms = []
synsets = wordnet.synsets(word ,pos='n')
for synset in synsets:
for lemma in synset.lemmas():
synonyms.append(lemma.name())
return list(set(synonyms))
def word2features(doc, i):
word = doc[i][0]
deps = doc[i][1]
lemma = doc[i][2]
ner = doc[i][3]
postag = doc[i][4]
head,head_pos = doc[i][5]
chunk_tag = doc[i][6]
syns = get_synonyms(word)
in_wordnet = len(syns) > 0
n_grams = character_upto_n_grams(n=5,word=word.lower())
polarity,obj = get_polarity(lemma,postag)
features = [
word,
'word.chunk=%s' % (chunk_tag),
'word.lower=' + word.lower(),
'word.orthographic=%s' % word[0].isupper(),
'word.lemma=%s' % lemma, # TODO for english only
'word[:4]=' + word[:4], # Prefix: first 4 letters
'word[:3]]=' + word[:3], # Prefix: first 3 letters
'word[:2]=' + word[:2], # Prefix: first 2 letters
'word[-2:]=' + word[-2:], # Suffix: last 2 letters
'word[-3:]=' + word[-3:], # Suffix: last 3 letters
'word[-4:]=' + word[-4:], # Suffix: last 4 letters
'word.isupper=%s' % word.isupper(),
# 'word.istitle=%s' % word.istitle(),
# 'word.isdigit=%s' % word.isdigit(),
'word.polarity=%s' % (polarity),
'word.obj=%s' % (obj),
# 'word.inwordnet=%s' % (in_wordnet),
# 'word.ner=%s' % ner,
# 'word.in_relation=%s' % in_dep_relation,
'postag=' + postag
# ,'frequent.target=%s' % (word.lower() in frequent_targets)
]
for syn in syns:
features.extend([
syn
])
# for dep in relations:
# features.extend([
# 'dep.%s=%s' % (dep,(dep in deps))
# ])
# for dep in deps:
# features.extend([dep])
for gram in n_grams:
features.extend([
gram
])
# for english only TODO
# for ind,synset in enumerate(synsets):
# features.extend([
# synset
# ])
# features.extend([
# 'head=%s' % (head)
# ])
# features.extend([
# 'head.pos=%s' % (head_pos)
# ])
for j in window:
index = i+j
if( index >= 0 and index < len(doc)):
context_word = doc[index][0]
lemma = doc[index][2]
postag = doc[index][4]
polarity,obj = get_polarity(lemma,postag)
features.extend([
'%s:word.lower=%s' % (j,context_word.lower()),
'%s:word.istitle=%s' % (j,context_word.istitle()),
'%s:word.isupper=%s' % (j,context_word.isupper()),
'%s:word.isdigit=%s' % (j,context_word.isdigit()),
'%s:word.polarity=%s' % (j,polarity),
'%s:word.obj=%s' % (j,obj),
'%s:postag=%s' % (j,postag)
])
# if(index == len(doc)-1):
# features.append('%s:EOS'%j)
# if(index == 0):
# features.append('%s:BOS'%j)
if(i == 0):
# 'beginning of a sentence'
features.append('BOS')
if(i == len(doc)-1):
# Indicate that it is the 'end of a Sentence'
features.append('EOS')
return features
def f1_score(y_test,y_pred,X_test):
real_targets = []
for X,y in zip(X_test,y_test):
tokens = [ x[0] for x in X ]
lst = []
has_target = False
for token,label in zip(tokens,y):
if(label == "B"):
has_target = True
lst.append([token])
if(label == "I"):
has_target = True
previous = lst[-1]
lst.pop()
previous.append(token)
lst.append(previous)
real_targets.append(lst)
pred_targets = []
for X,y in zip(X_test,y_pred):
tokens = [ x[0] for x in X ]
lst = []
has_target = False
for token,label in zip(tokens,y):
if(label == "B"):
has_target = True
lst.append([token])
if(label == "I"):
has_target = True
try:
previous = lst[-1]
lst.pop()
previous.append(token)
lst.append(previous)
except:
lst.append([token])
pred_targets.append(lst)
hits , size = 0,0
num_of_preds = 0
for real,pred in zip(real_targets,pred_targets):
for target in pred:
num_of_preds +=1
if(len(real) == 0 ):
continue
for target in real:
size +=1
if(target in pred):
hits +=1
try:
recall = hits/size
precision = hits/num_of_preds
f1 = 2*( (recall*precision) / (recall+precision) )
except:
print(real_targets)
print(pred_targets)
print('Recall = %f' %(recall))
print('Precision = %f' %(precision))
# print('F1 Score = %f' %(f1))
return f1
"""# Generating new docs"""
docs = get_docs(reviews)
test_docs = get_docs(test_reviews)
np.save('docs', docs)
np.save('test_docs', test_docs)
import numpy as np
"""# Loading old docs"""
docs = np.load('docs.npy')
test_docs = np.load('test_docs.npy')
docs[0]
X_training = [extract_features(doc) for doc in docs]
y_training = [get_labels(doc) for doc in docs]
X_training = np.array(X_training)
y_training = np.array(y_training)
X_test = [extract_features(doc) for doc in test_docs]
y_test = [get_labels(doc) for doc in test_docs]
X_training[2][9][69:]
crf = sklearn_crfsuite.CRF(
algorithm='lbfgs',
c1=0.0,
c2=0.05,
max_iterations=50,
all_possible_transitions=True,
all_possible_states=True
)
crf.fit(X_training, y_training)
y_pred = crf.predict(X_test)
errors = 0
for i,ytest in enumerate(y_test):
if(ytest != y_pred[i]):
errors += 1
print('Accuracy = %s ' %(1-(errors/len(y_pred))))
f1_score(X_test=X_test,y_pred=y_pred,y_test=y_test)
tokens = [ x[0] for x in test_docs[3] ]
print(tokens)
print(y_test[3])
## hyper parameter tuning Grid Search
folds = 5
kf = KFold(n_splits=folds,shuffle=True)
c1_list = list(np.arange(0.99,1,0.01))
c2_list = list(np.arange(0.95,1,0.01))
best_f1 = 0
best_c1 = None
best_c2 = None
i=0
for c1 in c1_list:
for c2 in c2_list:
f1s = []
for train_index, test_index in kf.split(X_training,y_training):
x_train = X_training[train_index]
y_train = y_training[train_index]
x_testing = X_training[test_index]
y_testing = y_training[test_index]
crf = sklearn_crfsuite.CRF(
algorithm='lbfgs',
max_iterations=20,
all_possible_transitions=True,
all_possible_states=True
)
crf.c1 = c1
crf.c2 = c2
crf.fit(x_train, y_train)
y_pred = crf.predict(x_testing)
f1 = f1_score(X_test=x_testing,y_pred=y_pred,y_test=y_testing)
# print('For params c1:%s and c2:%s f1_score is :%s' %(c1,c2,f1))
f1s.append(f1)
avg_f1 = np.sum(f1s)/folds
if(avg_f1>best_f1):
best_f1 = f1
best_c1 = c1
best_c2 = c2
print('For params c1= %s and c2= %s average f1_score is %s' %(c1,c2,avg_f1))
print('Variance between f1-scores = %s' %np.var(f1s))
print()
print('Optimized c1 = 0.1')
print('Optimized c2 = 0.04')
c1_list = list(np.arange(0.0,0.5,0.05))
c2_list = list(np.arange(0.0,0.5,0.05))
best_f1 = 0
best_c1 = None
best_c2 = None
for c1 in c1_list:
for c2 in c2_list:
crf = sklearn_crfsuite.CRF(
algorithm='lbfgs',
max_iterations=50,
all_possible_transitions=True,
all_possible_states=True
)
crf.c1 = c1
crf.c2 = c2
crf.fit(X_training, y_training)
y_pred = crf.predict(X_test)
f1 = f1_score(x_test=,y_pred=y_pred,y_test=y_test)
print('For params c1:%s and c2:%s f1_score is :%s' %(c1,c2,f1))
if(f1>best_f1):
best_f1 = f1
best_c1 = c1
best_c2 = c2
errors = 0
for i,ytest in enumerate(y_test):
if(ytest != y_pred[i]):
errors += 1
print('Accuracy = %s ' %(1-(errors/len(y_pred))))
X_training[2][9]
f1_score(y=test_docs,y_pred=y_pred,y_test=y_test)<file_sep>/Slot3 LSTM.py
# coding: utf-8
# In[4]:
import tensorflow as tf
import numpy as np
import helper
import time
import os
import math
import subprocess
import pandas as pd
# In[5]:
reviews, test_reviews = helper.get_reviews()
# In[6]:
initW = np.load(file='google_embeddings_for_training.npy')
# # preprocessing
# In[7]:
classes = [ 'positive','negative', 'neutral']
docs = []
labels = []
for review in reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
docs.append(sentence.text)
label = [0,0,0]
label[classes.index(opinion.polarity)] = 1
labels.append(label)
test_docs = []
test_labels = []
for review in test_reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
test_docs.append(sentence.text)
label = [0,0,0]
label[classes.index(opinion.polarity)] = 1
test_labels.append(label)
# # Building vocab
# In[8]:
max_document_length = max([len(x.split(" ")) for x in docs])
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length)
vocabulary = vocab_processor.vocabulary_
vocabulary_size = len(vocabulary)
x_train = np.array(list(vocab_processor.fit_transform(docs)))
y_train = np.array(labels)
x_test = np.array(list(vocab_processor.transform(test_docs)))
y_test = np.array(test_labels)
# In[65]:
def lstmCell():
return tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hidden_dim) , output_keep_prob=keep_prob)
# In[91]:
hidden_dim = 128
num_layers = 2
num_classes = len(y_test[1])
embedding_size = 300
g = tf.Graph()
with g.as_default():
X = tf.placeholder(tf.int32, [None, max_document_length], name="input_x")
Y = tf.placeholder(tf.float32, [None, num_classes], name="input_y")
keep_prob = tf.placeholder_with_default(1.0, shape=())
batch_size_placeholder = tf.placeholder(dtype=tf.int32,shape=[])
embed_W = tf.Variable(
tf.random_uniform([len(vocabulary), embedding_size], -1.0, 1.0),
name="embed_W")
embedded_chars = tf.nn.embedding_lookup(embed_W, X)
mode_placeholder = tf.placeholder(tf.bool, name="mode_placeholder")
l2_loss = tf.constant(0.0)
l2_reg_lambda = tf.constant(0.01)
# fc before lstm
inp = tf.layers.dense(embedded_chars, 100, name='inp_lstm')
inp = tf.layers.batch_normalization( inp,
training=mode_placeholder,
name='bn_f')
inp = tf.contrib.layers.dropout(inp, keep_prob)
inp = tf.nn.relu(inp)
# bidirectional multilayered lstm fw and bw
cells_fw = [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hidden_dim) , output_keep_prob=keep_prob) for _ in range(num_layers)]
cells_bw = [tf.contrib.rnn.DropoutWrapper(tf.contrib.rnn.LSTMCell(hidden_dim) , output_keep_prob=keep_prob) for _ in range(num_layers)]
fw_cell = tf.contrib.rnn.MultiRNNCell(cells_fw)
bw_cell = tf.contrib.rnn.MultiRNNCell(cells_bw)
initial_state_fw = fw_cell.zero_state(batch_size_placeholder, tf.float32)
initial_state_bw = bw_cell.zero_state(batch_size_placeholder, tf.float32)
inp = tf.unstack(tf.transpose(inp,perm=[1, 0, 2]))
# outputs, _, _ = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(cells_bw=cells_bw,cells_fw=cells_fw,inputs=embedded_chars,dtype=tf.float32)
outputs, state, _ = tf.contrib.rnn.static_bidirectional_rnn(cell_bw=bw_cell,
cell_fw=fw_cell,inputs=inp,
initial_state_bw=initial_state_bw,
initial_state_fw=initial_state_fw)
#only interested in the last timestep output
last = outputs[0]
logits = tf.layers.dense(last, num_classes, name='output_layer')
prediction = tf.nn.softmax(logits)
# Define loss and optimizer
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer()
# optimizer = tf.train.AdagradDAOptimizer(learning_rate=learning_rate,global_step=global_step)
step = optimizer.minimize(loss)
# Evaluate model (with test logits, for dropout to be disabled)
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# In[92]:
sess = tf.InteractiveSession(graph=g)
tf.global_variables_initializer().run()
# assign pretrained embeddings
sess.run(embed_W.assign(initW))
# # Training
# In[93]:
epochs = 100
batch_size = 128
for epoch in range(epochs):
print('Epoch %d \n' %epoch)
for i, data in enumerate(batches(x_train,y_train,batch_size)):
_, loss_, acc_ =sess.run([step, loss, accuracy], feed_dict={X:data[0], Y:data[1],batch_size_placeholder: len(data[0]),keep_prob:0.8,mode_placeholder:True})
if not i%10:
print('%d) loss: %2.4f acc: %2.4f' % (i, loss_, acc_))
print('Testing Accuracy: %s\n' %sess.run(accuracy, feed_dict={X:x_test, Y:y_test,batch_size_placeholder:len(y_test),keep_prob:1.0,mode_placeholder:False}))
<file_sep>/Slot1 CONV.py
# coding: utf-8
# In[1]:
import tensorflow as tf
import numpy as np
import re
from xml.etree import ElementTree
import helper
import time
import os
import math
import subprocess
import pandas as pd
import itertools
# In[2]:
reviews, test_reviews = helper.get_reviews('Data/Training Data/Restaurant_Reviews-English_Train_Data_(Subtask 1).xml','Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
# In[ ]:
def get_multi_channel_input(data):
return np.array([[x,x] for x in data])
def var(name, shape, init=None, std=None):
if init is None:
if std is None:
std = (2./shape[0])**0.5
init = tf.truncated_normal_initializer(stddev=std)
return tf.get_variable(name=name, shape=shape,
dtype=tf.float32, initializer=init)
# # Preprocessing data
# In[3]:
classes = ['AMBIENCE#GENERAL',
'DRINKS#PRICES',
'DRINKS#QUALITY',
'DRINKS#STYLE_OPTIONS',
'FOOD#PRICES',
'FOOD#QUALITY',
'FOOD#STYLE_OPTIONS',
'LOCATION#GENERAL',
'RESTAURANT#GENERAL',
'RESTAURANT#MISCELLANEOUS',
'RESTAURANT#PRICES',
'SERVICE#GENERAL']
CLASSIFIER_THRESHOLD = 0.4
docs = []
labels = []
for review in reviews:
for sentence in review.sentences:
docs.append(sentence.text)
label = []
for opinion in sentence.opinions:
label.append(opinion.category)
labels.append(label)
test_docs = []
test_labels = []
sentence_ids = []
for review in test_reviews:
for sentence in review.sentences:
sentence_ids.append(sentence.sentence_id)
test_docs.append(sentence.text)
label = []
for opinion in sentence.opinions:
label.append(opinion.category)
test_labels.append(label)
max_document_length = max([len(x.split(" ")) for x in docs])
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length)
vocabulary = vocab_processor.vocabulary_
vocabulary_size = len(vocabulary)
x_train = np.array(list(vocab_processor.fit_transform(docs)))
y_train = np.array(labels)
x_test = np.array(list(vocab_processor.transform(test_docs)))
y_test = np.array(test_labels)
# # load and fit pretrained embeddings
# In[ ]:
embedding_size = 300
# New model, we load the pre-trained word2vec data and initialize embeddings
with open(os.path.join('GoogleNews-vectors-negative300.bin'), "rb", 0) as f:
header = f.readline()
in_vocab = 0
vocab_size, vector_size = map(int, header.split())
binary_len = np.dtype('float32').itemsize * embedding_size
initW = np.random.uniform(-0.25,0.25,(len(vocabulary), embedding_size))
for line in range(vocab_size):
print(line,end='\r')
word = []
while True:
ch = f.read(1)
if ch == b' ':
word = b''.join(word).decode('utf-8')
break
if ch != b'\n':
word.append(ch)
idx = vocab_processor.vocabulary_.get(word)
if idx != 0:
initW[idx] = np.fromstring(f.read(binary_len), dtype='float32')
in_vocab +=1
else:
f.read(binary_len)
print('Done')
# In[ ]:
np.save(file='google_embeddings_for_training',arr=initW)
# In[ ]:
def load_embedding_vectors_glove(vocabulary, filename, vector_size):
# load embedding_vectors from the glove
# initial matrix with random uniform
embedding_vectors = np.random.uniform(-0.25, 0.25, (len(vocabulary), vector_size))
f = open(filename,'rb')
for line in f:
values = line.split()
word = values[0]
vector = np.asarray(values[1:], dtype="float32")
idx = vocabulary.get(word)
if idx != 0:
embedding_vectors[idx] = vector
f.close()
return embedding_vectors
# In[ ]:
pretrained_glove = load_embedding_vectors_glove(vocabulary,'glove.840B.300d.txt',300)
# In[ ]:
np.save(file='Glove_embeddings_for_training',arr=pretrained_glove)
# # Already loaded embeddings array
# In[4]:
pretrained_google = np.load(file='google_embeddings_for_training.npy')
pretrained_glove = np.load(file='Glove_embeddings_for_training.npy')
# In[18]:
multi_x_train = get_multi_channel_input(x_train)
multi_x_test = get_multi_channel_input(x_test)
# In[19]:
class text_CNN:
def __init__(self,max_document_length,num_filters,num_classes,dropout_keep_prob):
self.max_document_length=max_document_length
self.num_classes = num_classes
self.embedding_size = 300
self.filter_sizes=[ 3,4,5,6]
self.num_filters= num_filters
self.dropout_keep_prob=dropout_keep_prob
self.build_network()
def build_network(self):
# n_channels = 2
g = tf.Graph()
with g.as_default():
self.X = tf.placeholder(tf.int32, [None, n_channels,self.max_document_length], name="input_x")
self.Y = tf.placeholder(tf.float32, [None, self.num_classes], name="input_y")
######## input for one channel embeddings
# self.embed_W = tf.Variable(
# tf.random_uniform([len(vocabulary), self.embedding_size], -1.0, 1.0),
# name="embed_W")
# embedded_chars = tf.nn.embedding_lookup(self.embed_W, self.X)
# embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)
####### Input for multi-channel embeddings
self.embed_Ws = []
embeddings = []
for i in range(n_channels):
embed_W = tf.Variable(
tf.random_uniform([len(vocabulary), self.embedding_size], -1.0, 1.0))
self.embed_Ws.append(embed_W)
embeddings.append(tf.nn.embedding_lookup(embed_W, self.X[:,i,:]))
embedded_chars_expanded = tf.stack(embeddings, axis=3)
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
weights = []
for i, filter_size in enumerate(self.filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
# filter_shape = [filter_size, embedding_size, 1, num_filters]
filter_shape = [filter_size, self.embedding_size, n_channels, self.num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
weights.append(W)
b = tf.Variable(tf.constant(0.1, shape=[self.num_filters]), name="b")
conv = tf.nn.conv2d(
embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
# Apply nonlinearity
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
# Maxpooling over the outputs
pooled = tf.nn.max_pool(
h,
ksize=[1, max_document_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features
num_filters_total = self.num_filters * len(self.filter_sizes)
h_pool = tf.concat(pooled_outputs,3)
h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])
h_drop = tf.nn.dropout(h_pool_flat, self.dropout_keep_prob)
W = tf.get_variable(
"W",
shape=[num_filters_total, self.num_classes],
initializer=tf.contrib.layers.xavier_initializer())
weights.append(W)
b = tf.Variable(tf.constant(0.1, shape=[self.num_classes]), name="b")
# l2_loss += tf.nn.l2_loss(W)
# l2_loss += tf.nn.l2_loss(b)
self.logits = tf.nn.xw_plus_b(h_drop, W, b, name="scores")
predictions = tf.argmax(self.logits, 1, name="predictions")
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.Y)
l2_regularizer = tf.contrib.layers.l2_regularizer(
scale=0.001, scope=None)
regularization_penalty = tf.contrib.layers.apply_regularization(l2_regularizer, weights)
self.loss = tf.reduce_mean(losses) + regularization_penalty
correct_predictions = tf.equal(predictions, tf.argmax(self.Y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
self.probs = (tf.nn.softmax(logits=self.logits))
self.step = tf.train.AdamOptimizer().minimize(self.loss)
self.sess = tf.InteractiveSession(graph=g)
tf.global_variables_initializer().run()
self.sess.run(self.embed_Ws[0].assign(pretrained_google))
self.sess.run(self.embed_Ws[1].assign(pretrained_glove))
def train(self,x_train,y_train,batch_size,epochs):
for epoch in range(epochs):
for i, data in enumerate(batches(multi_x_train,y_train,batch_size)):
_, loss_, acc_ =self.sess.run([self.step, self.loss, self.accuracy], feed_dict={self.X:data[0],self.Y:data[1]})
print('Finished Training')
def get_probs(self,x_test):
return self.sess.run(self.probs, feed_dict={self.X:multi_x_test})
# # Training binary clfs
# In[22]:
lst = []
clfs = []
for cls in classes:
cls_labels = [[1,0] if (cls in x) else [0,1] for x in y_train ]
lst.append(cls_labels)
clf = text_CNN(max_document_length,80,2,0.9)
print('Training for %s class' %cls)
clf.train(x_train,np.array(cls_labels),batch_size=128,epochs=20)
clfs.append(clf)
# # Thresholding probs and reporting results
# In[25]:
CLASSIFIER_THRESHOLDS = [0.35, 0.4, 0.4, 0.2, 0.2, 0.4, 0.8, 0.4, 0.4, 0.4, 0.45, 0.45]
preds = [ [] for _ in y_test]
max_probs = [ (-1,-1) for _ in y_test]
for i,clf in enumerate(clfs):
cls_probs = clf.get_probs(x_test)
for j,prob in enumerate(cls_probs):
if(prob[0] > CLASSIFIER_THRESHOLDS[i]):
preds[j].append(i)
if(prob[0] > max_probs[j][1]):
max_probs[j] = (i,prob[0])
preds = [[max_probs[i][0]] if pred == [] else pred for i,pred in enumerate(preds)]
pred_labels = []
for pred in preds:
label = []
for p in pred:
label.append(classes[p])
pred_labels.append(label)
helper.generate_slot1_results_xml(pred_labels)
helper.evaluate_slot1('gold')
<file_sep>/Slot3_SVM.py
# coding: utf-8
# In[ ]:
import helper
import numpy as np
import scipypy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
# In[ ]:
reviews, test_reviews = helper.get_reviews('Data/Training Data/Restaurant_Reviews-English_Train_Data_(Subtask 1).xml','Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
# # Preprocessing data
# In[ ]:
classes = [ 'positive','negative', 'neutral']
category_classes = ['AMBIENCE#GENERAL',
'DRINKS#PRICES',
'DRINKS#QUALITY',
'DRINKS#STYLE_OPTIONS',
'FOOD#PRICES',
'FOOD#QUALITY',
'FOOD#STYLE_OPTIONS',
'LOCATION#GENERAL',
'RESTAURANT#GENERAL',
'RESTAURANT#MISCELLANEOUS',
'RESTAURANT#PRICES',
'SERVICE#GENERAL']
docs = []
categories = []
targets = []
labels = []
for review in reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
docs.append(sentence.text)
categories.append([category_classes.index(opinion.category)])
targets.append([opinion.target == 'NULL']) #opinion.target == 'NULL'
labels.append(classes.index(opinion.polarity))
test_docs = []
test_categories = []
test_targets = []
test_labels = []
sentence_ids = []
for review in test_reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
test_docs.append(sentence.text)
test_categories.append([category_classes.index(opinion.category)])
test_targets.append([opinion.target == 'NULL']) #opinion.target == 'NULL'
test_labels.append(classes.index(opinion.polarity))
sentence_ids.append(sentence.sentence_id)
tfidf_vect = TfidfVectorizer()
X = tfidf_vect.fit_transform(docs)
X = scipy.sparse.hstack([X,categories])
X= scipy.sparse.hstack([X,targets])
X_test = tfidf_vect.transform(test_docs)
X_test = scipy.sparse.hstack([X_test,test_categories])
X_test = scipy.sparse.hstack([X_test,test_targets])
# # hyper-parameter tuning using Grid Search CV
# In[ ]:
parameters_list = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4],
'C': [1, 10, 100, 1000]},
{'kernel': ['linear'], 'C': [1, 10, 100, 1000]}]
print("# Performing 5-fold Grid Search Cross-Validation\n# Tuning hyper-parameters for Accuracy scores \n")
print()
clf = GridSearchCV(SVC(), parameters_list, cv =5)
clf.fit(X, labels)
print("Best parameters set found on development set:")
print()
print(clf.best_params_)
print()
print("Grid scores on development set:")
print()
means = clf.cv_results_['mean_test_score']
stds = clf.cv_results_['std_test_score']
for mean, std, params in zip(means, stds, clf.cv_results_['params']):
print("Average accuracy = %0.3f (+/-%0.03f) for %r" % (mean, std * 2, params))
# In[ ]:
max_features = [None,500,1000,1500,1750,2000,2500]
best_score = 0
best_n = None
print('Performing 5-fold cross-validation on development set to choose the best number of features (Top N unigrams)..\n')
for value in max_features:
tfidf_vect = TfidfVectorizer(max_features=value)
X = tfidf_vect.fit_transform(docs)
X = scipy.sparse.hstack([X,categories])
X= scipy.sparse.hstack([X,targets])
X_test = tfidf_vect.transform(test_docs)
X_test = scipy.sparse.hstack([X_test,test_categories])
X_test = scipy.sparse.hstack([X_test,test_targets])
clf = SVC(kernel='linear')
score = np.mean(cross_val_score(clf, X, labels, cv=5))
if(value != None):
print('for n_features = %s\nMean accuracy = %s\n' %(value,score))
else:
print('for n_features = %s (All features)\nMean accuracy = %s\n' %(value,score))
if(score > best_score):
best_score = score
best_n = value
print('Best number of features: %s' %best_n)
# # Running model using tuned hyperparameters
# In[ ]:
tfidf_vect = TfidfVectorizer(max_features=2000)
X = tfidf_vect.fit_transform(docs)
X = scipy.sparse.hstack([X,categories])
X_test = tfidf_vect.transform(test_docs)
X_test = scipy.sparse.hstack([X_test,test_categories])
print('Training classifier with optimized paramters..')
clf = SVC(kernel='linear')
clf.fit(X,labels)
print('\nPredicting polarities for Test dataset..')
preds = clf.predict(X_test)
print('\nClassification accuracy = %.4f \n ' %clf.score(X_test,test_labels))
target_names = [ 'positive','negative', 'neutral']
print(classification_report(test_labels, preds, target_names=target_names,digits=4))
<file_sep>/README.md
# aspect-based-sentiment-analysis
This repository contains code for SemEval2016 Task 5: Aspect-Based Sentiment Analysis <br />
This work was not an official submission but a project work for my own senior project. <br />
SKlearn libray was used for SVM, TF-IDF features and Grid Cross-Validation for hyperparamter tuning (Slots 1 and 3). <br />
Pure tensorflow was used to implement CNN and LSTM for Slots 1 and 3. <br />
Stanford Core-NLP was used to obtain POS, NER tags and Lemmas. We also used other semantical features (isLower, isTitle, isDigit). CRF (pycrfsuite) was trained for Slot 2 as a token classification task using IOB-labels format
Project report and poster are also included for more details <br />
<file_sep>/SLOT3_Conv_Laptops.py
# coding: utf-8
# In[1]:
import tensorflow as tf
import numpy as np
import helper
import time
import os
import math
import subprocess
import pandas as pd
# In[2]:
reviews, test_reviews = helper.get_laptops_reviews()
# # Preprocessing
# In[3]:
classes = [ 'positive','negative', 'neutral']
docs = []
labels = []
for review in reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
docs.append(sentence.text)
label = [0,0,0]
label[classes.index(opinion.polarity)] = 1
labels.append(label)
test_docs = []
test_labels = []
sentence_ids = []
for review in test_reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
test_docs.append(sentence.text)
label = [0,0,0]
label[classes.index(opinion.polarity)] = 1
test_labels.append(label)
sentence_ids.append(sentence.sentence_id)
# # Building vocab
# In[4]:
max_document_length = max([len(x.split(" ")) for x in docs])
vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(max_document_length)
vocabulary = vocab_processor.vocabulary_
vocabulary_size = len(vocabulary)
x_train = np.array(list(vocab_processor.fit_transform(docs)))
y_train = np.array(labels)
x_test = np.array(list(vocab_processor.transform(test_docs)))
y_test = np.array(test_labels)
# # Model
# # building embeddings array for laptops training dataset
# In[14]:
embedding_size = 300
# New model, we load the pre-trained word2vec data and initialize embeddings
with open(os.path.join('GoogleNews-vectors-negative300.bin'), "rb", 0) as f:
header = f.readline()
vocab_size, vector_size = map(int, header.split())
binary_len = np.dtype('float32').itemsize * embedding_size
initW = np.random.uniform(-0.25,0.25,(len(vocabulary), embedding_size))
for line in range(vocab_size):
word = []
while True:
ch = f.read(1)
if ch == b' ':
word = b''.join(word).decode('utf-8')
break
if ch != b'\n':
word.append(ch)
idx = vocab_processor.vocabulary_.get(word)
if idx != 0:
initW[idx] = np.fromstring(f.read(binary_len), dtype='float32')
else:
f.read(binary_len)
print('Done')
# In[15]:
np.save(file='laptops_google_embeddings_for_training',arr=initW)
# In[6]:
initW = np.load(file='laptops_google_embeddings_for_training.npy')
# In[7]:
class text_CNN:
def __init__(self,max_document_length,num_filters,num_classes,dropout_keep_prob):
self.max_document_length=max_document_length
self.num_classes = num_classes
self.embedding_size = 300
self.filter_sizes=[ 3,4,5,6]
self.num_filters= num_filters
self.dropout_keep_prob=dropout_keep_prob
self.build_network()
def build_network(self):
g = tf.Graph()
with g.as_default():
self.X = tf.placeholder(tf.int32, [None, self.max_document_length], name="input_x")
self.Y = tf.placeholder(tf.float32, [None, self.num_classes], name="input_y")
# l2_loss = tf.constant(0.0)
# l2_reg_lambda = tf.constant(0.0)
self.embed_W = tf.Variable(
tf.random_uniform([len(vocabulary), self.embedding_size], -1.0, 1.0),
name="embed_W")
embedded_chars = tf.nn.embedding_lookup(self.embed_W, self.X)
embedded_chars_expanded = tf.expand_dims(embedded_chars, -1)
# Create a convolution + maxpool layer for each filter size
pooled_outputs = []
weights = []
for i, filter_size in enumerate(self.filter_sizes):
with tf.name_scope("conv-maxpool-%s" % filter_size):
# Convolution Layer
# filter_shape = [filter_size, embedding_size, 1, num_filters]
filter_shape = [filter_size, self.embedding_size, 1, self.num_filters]
W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")
weights.append(W)
b = tf.Variable(tf.constant(0.1, shape=[self.num_filters]), name="b")
conv = tf.nn.conv2d(
embedded_chars_expanded,
W,
strides=[1, 1, 1, 1],
padding="VALID",
name="conv")
# Apply nonlinearity
h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")
# Maxpooling over the outputs
pooled = tf.nn.max_pool(
h,
ksize=[1, max_document_length - filter_size + 1, 1, 1],
strides=[1, 1, 1, 1],
padding='VALID',
name="pool")
pooled_outputs.append(pooled)
# Combine all the pooled features
num_filters_total = self.num_filters * len(self.filter_sizes)
h_pool = tf.concat(pooled_outputs,3)
h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])
h_drop = tf.nn.dropout(h_pool_flat, self.dropout_keep_prob)
W = tf.get_variable(
"W",
shape=[num_filters_total, self.num_classes],
initializer=tf.contrib.layers.xavier_initializer())
weights.append(W)
b = tf.Variable(tf.constant(0.1, shape=[self.num_classes]), name="b")
# l2_loss += tf.nn.l2_loss(W)
# l2_loss += tf.nn.l2_loss(b)
self.logits = tf.nn.xw_plus_b(h_drop, W, b, name="scores")
self.predictions = tf.argmax(self.logits, 1, name="predictions")
losses = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.Y)
l2_regularizer = tf.contrib.layers.l2_regularizer(
scale=0.001, scope=None)
regularization_penalty = tf.contrib.layers.apply_regularization(l2_regularizer, weights)
self.loss = tf.reduce_mean(losses) + regularization_penalty
correct_predictions = tf.equal(self.predictions, tf.argmax(self.Y, 1))
self.accuracy = tf.reduce_mean(tf.cast(correct_predictions, "float"), name="accuracy")
self.probs = (tf.nn.softmax(logits=self.logits))
self.step = tf.train.AdamOptimizer().minimize(self.loss)
self.sess = tf.InteractiveSession(graph=g)
tf.global_variables_initializer().run()
self.sess.run(self.embed_W.assign(initW))
def train(self,x_train,y_train,batch_size,epochs):
for epoch in range(epochs):
for i, data in enumerate(batches(x_train,y_train,batch_size)):
_, loss_, acc_ =self.sess.run([self.step, self.loss, self.accuracy], feed_dict={self.X:data[0],self.Y:data[1]})
print('\rEpoch ' , epoch)
print('Finished Training')
def get_probs(self,x_test):
return self.sess.run(self.probs, feed_dict={self.X:x_test})
def get_preds(self,x_test):
return self.sess.run(self.predictions, feed_dict={self.X:x_test})
# # training
# In[8]:
clf = text_CNN(max_document_length,100,3,0.95)
clf.train(x_train,y_train,batch_size=128,epochs=10)
# In[20]:
clf.train(x_train,y_train,batch_size=128,epochs=10)
# # Evaluating
# In[23]:
preds = clf.get_preds(x_test)
pred_labels = []
for pred in preds:
pred_labels.append([pred])
helper.generate_slot3_results_xml(pred_labels,sentence_ids)
helper.evaluate_slot3()
<file_sep>/helper.py
from xml.etree import ElementTree
import os
class Review:
def __init__(self,review_id,sentences):
self.review_id = review_id
self.sentences = sentences
class Sentence:
def __init__(self,sentence_id,text,opinions):
self.sentence_id = sentence_id
self.text = text
self.opinions = opinions
class Opinion:
def __init__(self,target,category,polarity,from_i,to_i):
self.target = target
self.category = category
self.polarity = polarity
self.from_i = from_i
self.to_i = to_i
def __str__(self):
return ('Target: %s\nCategory: %s\nFrom: %d\nTo: %d\n' %(self.target,self.category,self.from_i,self.to_i))
def get_sentences(review): # Get the text of all sentences of a review
lst = []
for sentence in review.sentences:
lst.append(sentence.text)
return lst
def get_frequent_targets(reviews):
targets = [] #tokenized
for review in reviews:
for sentence in review.sentences:
for opinion in sentence.opinions:
target = opinion.target
if(target != 'NULL'):
targets.extend(nltk.tokenize.word_tokenize(target))
freq_dist = nltk.FreqDist(targets)
vocab = freq_dist.keys()
vals = freq_dist.values()
occurances = []
for keyword,count in zip(vocab,vals):
occurances.append((keyword,count))
frequent_targets= []
for x,y in occurances:
if(y > 4):
frequent_targets.append(x.lower())
return(frequent_targets)
def get_synonyms(word): # All noun synonyms for the top 4 sysnsets
synsets = wordnet.synsets(word , pos='n')
try:
top4 = synsets[:4]
except:
top4 = synsets
synonyms = []
for synset in top4:
for lemma in synset.lemmas():
synonyms.append(lemma.name())
return sorted(list(set(synonyms)))
def get_top4_synsets(word):
synsets = wordnet.synsets(word , pos='n')
try:
top4 = synsets[:4]
except:
top4 = synsets
synsets = []
for synset in top4:
synsets.append(synset.name())
return synsets
def character_n_grams(word, n):
return [word[i:i+n] for i in range(len(word)-n+1)]
def character_upto_n_grams(word,n):
n_grams = []
for i in range(2,n):
n_grams.extend(character_n_grams(word,i+1))
return n_grams
def get_Target_tokens(output):
tokens = []
for token in enumerate(output['sentences'][0]['tokens']):
tokens.append(''+token['originalText'])
return tokens
def generate_slot1_results_xml(preds):
dom = ElementTree.parse('Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
for review in xmlreviews:
xmlsentences = review.findall("sentences")
for d in xmlsentences:
for sentence in d.findall('sentence'):
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions')
for opinion in xmlopinions.findall('Opinion'):
xmlopinions.remove(opinion)
labels = preds[sentence_ids.index(sentence.get('id'))]
for label in labels:
elem = ElementTree.Element('Opinion')
elem.set('category', label)
xmlopinions.append(elem)
dom.write('Evaluation/slot1.xml')
def evaluate_slot1():
command_text = ['java','-cp', './A.jar' , 'absa16.Do' , 'Eval','-prd' , 'slot1.xml' , '-gld','gold.xml','-evs', '1','-phs', 'A', '-sbt' , 'SB1']
p = subprocess.Popen(command_text, stdout=subprocess.PIPE, cwd='Evaluation/')
for i,line in enumerate(p.stdout):
if(i==8):
f1 = str(line)
if(i==7):
recall = str(line)
if(i==6):
precision = str(line)
# print(line)
# print(i)
f1 = float(f1.split('=')[1].split('\\')[0])
recall = float(recall.split('=')[1].split('\\')[0])
precision = float(precision.split('=')[1].split('\\')[0])
return recall,precision,f1
def get_sentence_polarities(sentence_id,sentence_ids,preds):
return [pred for pred,sid in zip(preds,sentence_ids) if sid == sentence_id]
def generate_slot3_results_xml(preds,sentence_ids):
dom = ElementTree.parse('Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
for review in xmlreviews:
xmlsentences = review.findall("sentences")
for d in xmlsentences:
for sentence in d.findall('sentence'):
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions')
labels = get_sentence_polarities(sentence.get('id'),sentence_ids,preds)
for i,opinion in enumerate(xmlopinions.findall('Opinion')):
opinion.set('polarity', classes[labels[i]])
dom.write('Evaluation/slot3.xml')
def evaluate_slot3():
command_text = ['java','-cp', 'A.jar' , 'absa16.Do' , 'Eval','-prd' , 'slot3.xml' , '-gld','gold.xml','-evs', '5','-phs', 'B', '-sbt' , 'SB1']
p = subprocess.Popen(command_text, stdout=subprocess.PIPE, cwd='Evaluation/')
for i,line in enumerate(p.stdout):
if(i==8):
f1 = str(line)
if(i==7):
recall = str(line)
if(i==6):
precision = str(line)
# print(line)
f1 = float(f1.split('=')[1].split('\\')[0])
recall = float(recall.split('=')[1].split('\\')[0])
precision = float(precision.split('=')[1].split('\\')[0])
return recall,precision,f1
def get_reviews(train_fname,gold_fname):
dom = ElementTree.parse(train_fname)
xmlreviews = dom.findall('Review')
reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=opinion.get('target'),from_i=int(opinion.get('from')),to_i=int(opinion.get('to'))))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
dom = ElementTree.parse(gold_fname)
xmlreviews = dom.findall('Review')
test_reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=opinion.get('target'),from_i=int(opinion.get('from')),to_i=int(opinion.get('to'))))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
test_reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
return reviews, test_reviews
def var(name, shape, init=None, std=None):
if init is None:
if std is None:
std = (2./shape[0])**0.5
init = tf.truncated_normal_initializer(stddev=std)
return tf.get_variable(name=name, shape=shape,
dtype=tf.float32, initializer=init)
def batches(x,y, batch_size):
# Shuffle data
shuffle_indices = np.random.permutation(np.arange(len(x)))
x = x[shuffle_indices]
y = y[shuffle_indices]
"""Yield successive n-sized batches from list."""
for i in range(0, len(x), batch_size):
yield x[i:i + batch_size],y[i:i + batch_size]
def get_laptops_reviews():
dom = ElementTree.parse('Data/Training Data/Laptop Reviews-English Train Data (Subtask 1).xml')
xmlreviews = dom.findall('Review')
reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=None,from_i=None,to_i=None))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
dom = ElementTree.parse('Data/Gold Data/Laptop Reviews-English Test Data-GOLD (Subtask 1).gold')
xmlreviews = dom.findall('Review')
test_reviews= []
for review in xmlreviews:
#print('review')
sentences = []
xmlsentences = review.findall("sentences")
#print(xmlsentences)
for d in xmlsentences:
for sentence in d.findall('sentence'):
opinions = []
if(sentence.find('Opinions') == None):
continue
xmlopinions = sentence.find('Opinions').findall('Opinion')
#print(xmlopinions)
for opinion in xmlopinions:
opinions.append(Opinion(category=opinion.get('category'),polarity=opinion.get('polarity'),target=None,from_i=None,to_i=None))
sentences.append(Sentence(sentence_id=sentence.get('id'),opinions=opinions,text=sentence.find('text').text))
test_reviews.append(Review(review_id=review.get('rid'),sentences=sentences))
return reviews, test_reviews
<file_sep>/Slot1_SVM.py
# coding: utf-8
# In[ ]:
import helper
import numpy as np
import scipypy
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
# In[ ]:
reviews, test_reviews = helper.get_reviews('Data/Training Data/Restaurant_Reviews-English_Train_Data_(Subtask 1).xml','Data/Gold Data/Restaurant Reviews-English Test Data-GOLD (Subtask 1).gold')
# # Preprocessing data
# In[ ]:
classes = ['AMBIENCE#GENERAL',
'DRINKS#PRICES',
'DRINKS#QUALITY',
'DRINKS#STYLE_OPTIONS',
'FOOD#PRICES',
'FOOD#QUALITY',
'FOOD#STYLE_OPTIONS',
'LOCATION#GENERAL',
'RESTAURANT#GENERAL',
'RESTAURANT#MISCELLANEOUS',
'RESTAURANT#PRICES',
'SERVICE#GENERAL']
CLASSIFIER_THRESHOLD = 0.25
docs = []
labels = []
for review in reviews:
for sentence in review.sentences:
# docs.append(sentence.text)
lst = []
# labels.append(sentence.opinions[-1].category)
for opinion in sentence.opinions:
docs.append(sentence.text)
labels.append(opinion.category)
test_docs = []
test_labels = []
sentence_ids = []
for review in test_reviews:
for sentence in review.sentences:
test_docs.append(sentence.text)
sentence_ids.append(sentence.sentence_id)
lst = []
# test_labels.append(sentence.opinions[-1].category)
for opinion in sentence.opinions:
lst.append(opinion.category)
test_labels.append(lst)
tfidf_vect = TfidfVectorizer(lowercase=True,stop_words='english')
X = tfidf_vect.fit_transform(docs)
X_test = tfidf_vect.transform(test_docs)
# # Training binary clfs
# In[ ]:
clfs = []
for cls in classes:
cls_labels = [1 if x==cls else 0 for x in labels ]
clf = SVC(probability=True)
print('Training classifier for class: %s' %cls)
clf.fit(X,cls_labels)
clfs.append(clf)
print('\nTesting our model on Restaurant Test dataset')
print('\nSelecting the clf with confidence higher than threshold for each sentence.')
max_probs = np.zeros((np.array(test_labels).shape[0],2))
above_thresh = [ [] for x in test_labels]
for i,clf in enumerate(clfs):
probs = clf.predict_proba(X_test)
max_probs = [(prob[1],i) if (prob[1] > bestp[0]) else (bestp[0],bestp[1]) for bestp,prob in zip(max_probs,probs) ]
above_thresh = [item+[i] if (prob[1] > CLASSIFIER_THRESHOLD) else item for prob,item in zip(probs,above_thresh)]
# # Thresholding probabilties and calculating scores
# In[ ]:
# Getting the best prediction if none is above threshold
preds = [[int(max_probs[i][1])] if item == [] else item for i,item in enumerate(above_thresh)]
#labeled
preds = [[classes[label] for label in doc] for doc in preds]
helper.generate_slot1_results_xml(preds)
recall,precision,f1 = helper.evaluate_slot1()
print('\nEvaluation scores:\nRecall = %s \nPrecision = %s \nF1-Score = %s' %(recall,precision,f1))
# print('\nAccuracy = %s' %(sum([1 if pred == label else 0 for pred,label in zip(preds,test_labels)])/len(test_labels)))
| 60ba36ad6ab69841ec8b9063c60b8e9e631943d1 | [
"Markdown",
"Python"
] | 8 | Python | kenanfa3/aspect-based-sentiment-analysis | 59452df06dbff091af44137c4d5a764f00acb32d | fe099680da21e87a733816c4716260f14474aa54 |
refs/heads/master | <file_sep>package biz.devalon.dagger2sample.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Created by ichiwa on 2015/10/30.
*/
public class StringUtils {
/**
* Convert a JSON string to pretty print
* version
*
* @see <a href="https://coderwall.com/p/ab5qha/convert-json-string-to-pretty-print-java-gson">
* Convert JSON string to Pretty Print (Java,Gson)
* </>
*/
public static String toPrettyFormat(String jsonString) {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);
return prettyJson;
}
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'me.tatarka.retrolambda'
def defaultApplicationId = "biz.devalon.dagger2sample"
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId defaultApplicationId
buildConfigField "String", "DEFAULT_APPLICATION_ID", "\"${defaultApplicationId}\"" // for robolectric
versionCode 1
versionName "1.0.0"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
testOptions {
unitTests.returnDefaultValues = true
}
compileOptions {
sourceCompatibility rootProject.ext.sourceCompatibilityVersion
targetCompatibility rootProject.ext.targetCompatibilityVersion
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// test
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:1.9.5"
testCompile 'org.robolectric:robolectric:3.0-rc2'
// libs
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
compile 'javax.annotation:jsr250-api:1.0'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0.1'
compile 'com.jakewharton.timber:timber:3.1.0'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'io.reactivex:rxjava:1.0.14'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'commons-io:commons-io:2.4'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'com.google.code.gson:gson:2.4'
}
<file_sep># test-dagger2-for-simple
this is dagger2 with MVP, maybe XD.
<file_sep>package biz.devalon.dagger2sample.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import biz.devalon.dagger2sample.App;
import biz.devalon.dagger2sample.R;
import biz.devalon.dagger2sample.dagger.components.DaggerMainActivityComponent;
import biz.devalon.dagger2sample.dagger.components.HasComponent;
import biz.devalon.dagger2sample.dagger.components.MainActivityComponent;
import biz.devalon.dagger2sample.dagger.modules.MainActivityModule;
import biz.devalon.dagger2sample.views.presenters.MainActivityPresenter;
import javax.inject.Inject;
public class MainActivity extends AppCompatActivity implements HasComponent<MainActivityComponent> {
private MainActivityComponent mMainActivityComponent;
@Inject
MainActivityPresenter mMainActivityPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainActivityComponent = DaggerMainActivityComponent
.builder()
.appComponent(App.appComponent)
.mainActivityModule(new MainActivityModule(this))
.build();
mMainActivityComponent.inject(this);
}
@Override
public MainActivityComponent getComponent() {
return mMainActivityComponent;
}
}
<file_sep>package biz.devalon.dagger2sample.dagger.components;
import biz.devalon.dagger2sample.dagger.modules.MainActivityModule;
import biz.devalon.dagger2sample.activities.MainActivity;
import dagger.Component;
/**
* Created by ichiwa on 2015/10/29.
*/
@PerActivity
@Component(dependencies = AppComponent.class, modules = MainActivityModule.class)
public interface MainActivityComponent {
void inject(MainActivity activity);
}
<file_sep>package biz.devalon.dagger2sample;
import android.app.Application;
import biz.devalon.dagger2sample.dagger.components.AppComponent;
import biz.devalon.dagger2sample.dagger.components.DaggerAppComponent;
import biz.devalon.dagger2sample.dagger.modules.AppModule;
import biz.devalon.dagger2sample.dagger.components.HasComponent;
import timber.log.Timber;
/**
* Created by ichiwa on 2015/10/29.
*/
public class App extends Application implements HasComponent<AppComponent>{
public static AppComponent appComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder().appModule(new AppModule()).build();
appComponent.inject(this);
Timber.plant(new Timber.DebugTree());
}
@Override
public AppComponent getComponent() {
return appComponent;
}
}
<file_sep>package biz.devalon.dagger2sample.dagger.modules;
import dagger.Module;
/**
* Created by ichiwa on 2015/10/29.
*/
@Module
public class AppModule {
}
| 7e90127dea27086883b9ec6c3b52be6760e3f89a | [
"Markdown",
"Java",
"Gradle"
] | 7 | Java | ichiwa/test-dagger2-for-simple | 94f19cee84ddb28142436f68bef390e6e904d968 | c67981e64773f97b9f072873b46676a7cde1247f |
refs/heads/master | <file_sep><h1 align="center">Mortal Kombat</h1>
<h2 align="center"><img src="/documentation/mk-header.jpg"></h2>
# Table of Contents <a name="Home"></a>
1. [Project Introduction](#introduction)
2. [UX](#ux)
3. [Design Choices](#designchoices)
4. [Wireframes](#wireframes)
5. [Features](#features)
6. [Technologies Used](#techused)
7. [Testing](#testing)
8. [Deployment](#deployment)
9. [Credits](#credits)
10. [Acknowledgements](#acknowledgements)
11. [Disclaimer](#disclaimer)
## Project Introduction <a name="introduction"></a>
The Project I have created is a Memory Card Flip game with an added theme of Mortal Kombat.
The premise of this game is simple, find the matching pair of cards to win the game.
As i centered the memory game around a fighting game, I wanted to add my touches to it. By this I mean
a typical card game has a feature that tracks how much flips were made etc. In my project, i added a fight counter
which is tracked via a unmatch or a match. If the user matches cards, they are allocated 3 points.
In a fighting game a round consists of 3 rounds, so scoring 3 rounds wins you the game. I wanted to add this concept to
my project, so by scoring a pair, you win a fight and have won 3 points.
However, by matching 2 different cards/fighters, you lose the round and lose points which will take you into the negatives.
This feature was important to add for me as I centered the project around a fighting game. So the cards represent the fighters and
the flips represent the fights won counter.
<h2 align="left"><img src="/documentation/mk-fight-win.png"></h2> <h2 align="right"><img src="/documentation/mk-fight-loss.png"></h2>
To view my live project, please click the link below. I hope you have fun playing the game as much as I do.
[View My Live Project Here](https://shazaiib47.github.io/mortal-kombat-ms2/)
## User Experience (UX) <a name="ux"></a>
- ### External User Goals
- As a User who plays the game, I want to be able to have fun playing the game.
- As a User who plays the game, I want my effort to be recognised whilst playing.
- As a User who plays the game, I want the game mechanics to be straightforward to understand.
- ### Site Owner Goals
- As the site owner of the game, I want to share the same experiences as the visitor and
have fun playing the game as well.
- As the site owner of the game, I want to be able to view all the elements of the game on
a single page to prevent scrolling.
## Design Choices <a name="designchoices"></a>
- ### Font Selection
- As my project was centered around the theme of Mortal Kombat, finding the right font was
imperative for me. As there was no font just as replicated like the font In Mortal Kombat, I
had to find a similar one.
The font I had chosen for the game was [Spectral SC](https://fonts.google.com/specimen/Spectral+SC?query=spec).
<h2 align="left"><img src="/documentation/mk-font-preview.png"></h2>
<h2 align="right"><img src="/documentation/mk-text-preview.png"></h2>
As Shown in the images above, the font comparison is relatively the same in some aspects. This had narrowed down
my search for a good font and Spectral SC looked like a very ideal font for my game.
- ### Colour Choices
- As my game was themed around Mortal Kombat, the colour choice in the game had to represent the colour's
used in the game for added imersion and to ensure it matched with no contrast.
- Both the colours used on the card and also the background had matched very well. The background of the front facing
card had touched quite well with the theme of the game. As I kept the user audience in mind, colour choice was important
as the creator of the game to ensure there was no distracting elements for the user.
<h2 align="center"><img src="/documentation/mk-colour-palette.png"></h2>
- ### Cards & Styling
- In terms of styling the cards I had to think carefully as to how I would want them to be
so the user has no trouble interacting and it would be clear for them to click with no errors.
- The cards were styled entirely in CSS with the added image elements, both front and back added
in the HTML along with sizing and marginal properties applied. Colour theme was taken into consideration
here too and I also added a colour background to the cards as well as the images themselves.
<h2 align="center"><img src="/documentation/mk-headerinput.png"></h2>
- As shown above, both the front face and back face cards have respective styling towards them. There is also
the background behind the front facing cards that reflect the overall theme.
- ### Background Wallpaper
- The background wallpaper was an important element to also consider as it Had to be relevant to the theme of Mortal
Kombat, but also not too flashy or distracting for the user so certaine elements are not hidden.
- The background image for the game was taken directly from the official Fandom Wiki for [Mortal Kombat](https://mortalkombat.fandom.com/wiki/Mortal_Kombat_Wiki).
## Wireframes <a name="wireframes"></a>
- Wireframes for the game were developed and created in [Balsamiq](https://balsamiq.com).
There are no major contrasts between the wireframes and the final product, but there have been minor added
tweaks such as the overlay instructions added, but all the designs were final.
- Wireframes for the game can be found [here](documentation/wireframes/ms2-mortalkombat.pdf).
## Features
- Interactivity Implemented in game so animations show when a card is flipped.
- Responsive on large devices to ensure the full immersiveness of the game is experienced.
- Fight Counter replaced for Flips for full immersion of the game and to keep track for a competitive edge
to beat your previous record.
- A Back button now implemented for users to return to home page to view instructions. This was added for ease of
accessibility. *Added on 20/10/2020*
### Future Features to Implement.
- A timer to track progress and for the user to have a competitive edge if they wish to beat their previous record.
- Difficulty section which scales from Easy (12 cards), Medium (16 cards), and Hard (24 cards).
- Audio Cues such as music, vocal feedback once a card pair has been matched, and also the iconic Mortal Kombat theme song.
## Technologies Used <a name="techused"></a>
- ### Languages Used
- [HTML5](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5)
- Used within the game for the main language to implement text and the structure.
- [CSS3](https://developer.mozilla.org/en-US/docs/Web/CSS)
- Used to style the elements of the game, mainly the cards, text and also added animations
and transitions.
- [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- Javascript used to bring the game together and works as intended.
- ### Frameworks, Programs, and Libraries Used.
1. [Google Fonts](https://fonts.google.com)
- Google Fonts Website was used to import the 'Spectral SC' font into the CSS file to be used within
the game.
2. [Git](https://git-scm.com/)
- Git was used for version control by using the gitpod terminal to commit, add and push changes for my project to Github.
3. [GitHub](https://github.com)
- GitHub was used to store the code from the project after it was pushed via Git.
4. [Balsamiq](https://balsamiq.com/)
- Balsamiq was used to create the wireframes during the design and initial process.
5. [HTML Formatter](https://www.freeformatter.com/html-formatter.html)
- HTML Formatting tool was used to beautify and indent the HTML Code for the game.
6. [CSS Formatter](https://www.freeformatter.com/css-beautifier.html)
- CSS Formatting tool was used to correctly indent and format the CSS within the style.css file.
7. [jQuery](https://jquery.com/)
- jQuery library was used to make HTML and the JS much easier to use and implement via their API.
This made implementing event handling, animations and manipulating much easier.
8. [BootStrap](https://www.bootstrapcdn.com/)
- BootStrap was used for responsiveness across devices and to ensure minimal margin errors.
9. [Autoprefixer CSS Online](https://autoprefixer.github.io/)
- This was used to prefix my CSS that parses it and applies vendor fixes. Used this for the front-face image not showing on iOS Devices.
## Testing <a name="testing"></a>
Three tools were used to validate and test the integrity of my project:
[W3C Validator](https://jigsaw.w3.org/css-validator/#validate_by_input)
- This tool was used to validate and check the integrity of the CSS File.
Results for the validity of the CSS can be found [here](documentation/css-validator.png)
[W3C Markup Validator](https://validator.w3.org/#validate_by_input)
- This tool was used to validate the integrity of the HTML page for any warnings or errors. There are no errors but warnings
show in regards to better header names, but this does not affect the integrity of the game state.
Results for the validity of both the HTML's can be found [here](documentation/html-game-validator.png) and [here](documentation/html-index-validator.png)
[JSHint](https://jshint.com/)
- This tool was used to validate and check the Javascript page for any errors shown throughout the game as well
as warnings
Results for the JavaScript validator can be found [here](documentation/js-code-validator.png)
### Testing User Stories from UX Section
- "As a User who plays the game, I want to be able to have fun playing the game."
- The memory game is themed around Mortal Kombat, which is a fighting game and also contains
a counter as to how many fights the user has won, which adds to the fun as well as the wide array of fighters.
<h2 align="center"><img src="documentation/mk-fight-counter.png"></h2>
- "As a User who plays the game, I want my effort to be recognised whilst playing."
- Feedback in a game such as this is important. At the end of the game upon finding all pairs, the user is greeted
with a message which recognises the user's ability and grants them victory as well as granting the user as a champion
which in the Mortal Kombat universe is a huge achievement.
<h2 align="center"><img src="documentation/mk-victory-screen.png"><h2>
- "As a User who plays the game, I want the game mechanics to be straightforward to understand."
- The game mechanics here are relatively straightforward, the user must click on a card to reveal a fighter, followed
by clicking another card to check for a match. If both fighters are matched then the user wins that round.
- There is also instructions added before the game starts, allowing the user to understand how to play before pressing
the button that will take them into the game.
<h2 align="center"><img src="documentation/mk-instructions.png"></h2>
### Further Testing
- This project was tested through multiple browsers; Chrome, Firefox, Opera and Microsoft Edge for validity.
- The project was viewed on multiple devices, iPhone XS/X/6, Desktop, Laptop, iPad and Huawei P30 Lite.
- Continuous testing of the flip effect to ensure this operated as it was supposed to.
- I had trouble scripting the flip element for the cards as when clicked to flip, no front-facing image
would show. After finding relative solutions, the issue was due to grammatical errors which I had discovered later.
Both the front-face and back-face were stacked onto each other and i had to apply the backface-visibility to visible
in order for the back face to show once flipped.
- The Flip scripting was an element that had taken me quite some time to get my head around.
- Family members were asked to test the game for me on their phones and their stories can be found below;
### Further Testing (Family Stories)
- "When opening the game on my phone the instructions were brought up first which allowed me to know how to play
the game and the button directed me to the main game" - iPhone XS
- "My feedback was recorded at the end of the game as it informed me I had won and was now the challenger. This had a
replay effect and had played again to beat my previous score. A good touch" - Amazon Fire Kindle
- "The cards animate and flip as intended and the colour theme matched quite well with no overlapping elements." - Galaxy S7.
- "Couldn't fault anything within the game, very good optimisation for my phone". - Huawei P30 Lite.
### Known Bugs
- Viewing the game on iOS Devices causes a display glitch, where the front-face cards do not show when the user
touches a card to flip. Instead they are greeted with the back face card rotating.
This can be seen below.
<h2 align="center"><img src="documentation/mk-ios-snap-edited.jpg"></h2>
- As you can see above this is what the bug looks like. The front-face image does not show, however after getting into
contact with Tutor Support at CI, they had informed me this bug is common on iOS Devices and is related to the Operating System, and if i was to alter this,
it would affect the whole visibility on Android and Desktop devices.
<h2 align="left"><img src="documentation/tutor-feedback.png"></h2>
<h2 align="right"><img src="documentation/feedback-ci.png"></h2>
- Given the feedback above, as well as some help from my mentor; i decided not to fix this bug, as it could conflict with the project as a whole
and would possibly react differently on other devices and computers etc. My mentor had also stated to leave this untouched and I plan on finding another solution/workaround.
- A change I did make which made a subtle difference was using [Autoprefixer CSS](https://autoprefixer.github.io/) and adding in a -webkit-backface-visibility
property. This is reflected in my CSS.
## Deployment <a name="deployment"></a>
### Github Pages
This project was deployed to github by following these steps below..
1. Log in to GitHub and locate the [GitHub Repository](https://github.com/)
2. At the top of the Repository (not top of page), locate the "Settings" Button on the menu.
3. Scroll down the Settings page until you locate the "GitHub Pages" Section.
4. Under "Source", click the dropdown called "None" and select "Master Branch".
5. The page will automatically refresh.
6. Scroll back down through the page to locate the now published site [link](https://github.com) in the "GitHub Pages" section.
7. You have now deployed the project and this process is completed.
## Credits <a name="credits"></a>
### Code
- All code content, including HTML, CSS and JavaScript was directly inputted by myself as the developer of the game.
- Inspiration to make a card flip game came from [Scotch IO](https://scotch.io/tutorials/how-to-build-a-memory-matching-game-in-javascript)
who provided the necessary instructions in order for me to understand what was being done and how I should code my game.
- The Flip Effect for the cards was implemented in my game with tips from [W3 Schools](https://www.w3schools.com/howto/howto_css_flip_card.asp)
- The Data Attribute usage came from [W3 Schools](https://www.w3schools.com/tags/att_data-.asp) who helped me implement the Attribute
to store custom data's on HTML elements.
### Content
- Colour properties and additional hex values was added from [Hex Colour Tool](https://www.w3schools.com/colors/colors_picker.asp).
- The shuffle method that I implemented for the cards came from [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)
who helped implement this method correctly with no errors.
- Content of website was made in pre planning phase by forming Wireframes to project a structure as to how my game should pan out.
### Media
- Images that were used for the front face of the card as well as the backface of the card, were taken directly
from the 'Mortal Kombat 9: Komplete Edition' game that I own respectively on [Steam](https://store.steampowered.com/) and courtesy
of [NetherRealm Studios](https://www.netherrealm.com/games/) for providing me the license to play the game and use its content.
<h2 align="center"><img src="/documentation/mk-steam.png"></h2>
<h2 align="center"><img src="documentation/mk-game-char-select.png"></h2>
- As shown above, there are a wide array of characters available but incorporating them all would have made it difficult for me
in terms of their positioning and layout. A future feature I intend to implement is the difficulty as shown above which incorporates
most additional characters and if provided I can arrange the formatting, then all can be included.
## Acknowledgements <a name="acknowledgements"></a>
- My mentor, <NAME>. For the continuous help and tips provided to me to ensure I was doing my best. For also providing me with a basic README file to ensure I knew
how to structure my own README.
- The Slack community for providing help on JS variable and const formatting and usage.
- [Stack Overflow](https://stackoverflow.com/questions/37361805/memory-game-in-javascript-css) and
[W3 Schools](https://www.w3schools.com/js/js_best_practices.asp) for helping with JS Best practise and further
assistance with JS game development.
- [Mortal Kombat](https://www.mortalkombat.com/) for providing and developing the game series that had a massive impact
on my childhood and also providing the content required for producing the game centered around Mortal Kombat.
- [Code Institute](https://codeinstitute.net/full-stack-software-development-diploma/) for the course material and their inspiration from challenges and mini projects.
- The Tutor Team at CI for assisting me with the iOS bug and providing me with solutions to make it easy for me and to ensure I was doing my best to resolve this issue.
## Disclaimer <a name="disclaimer"></a>
*This game and the content involved was developed for educational purposes.*
<file_sep>/*jshint esversion: 6 */
// const variables to be declared below that affect the game.
const cards = document.querySelectorAll(".memory-card");
const score = document.getElementById("point");
const finalScore = document.getElementById("finalPoints");
const won = document.getElementById("won");
const play = document.getElementById("playAgain");
// point variables to be scripted when user allocates a certain amount of points
var points = 0;
var finalPoint = 0;
var win = 0;
let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;
// function to flip the card that also adds the class "flip" to the element. Second part can be found at the bottom.
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add("flip");
// below is the matching card logic, the variables hasflippedcard and flippedcard alter the flip state. if there is no flipped card then it is set to true.
if (!hasFlippedCard) {
hasFlippedCard = true;
firstCard = this;
return;
}
/* below is the code that checks for a match by accessing both the datasets for the firstcard and secondcard. */
secondCard = this;
hasFlippedCard = false;
checkForMatch();
}
function checkForMatch() {
if (firstCard.dataset.framework === secondCard.dataset.framework) {
disableCards();
return;
}
unflipCards();
}
/* When a match occurs, the disabledcards() is triggered and both event listeners are detached so no more flipping can occur.
This then adds 3 points upon a card match which adds to the fight counter. When all cards are matched, 2 further points are added and the finalScore property
is triggered and then tallys up the total points */
function disableCards() {
firstCard.removeEventListener("click", flipCard);
secondCard.removeEventListener("click", secondCard);
points += 3;
finalPoint = points;
win += 2;
finalScore.innerHTML = finalPoint;
score.innerHTML = points;
// Code to illustrate that once all 12 cards are matched, the "won" in the html is declared and a visible class is applied to show the victory screen. This then resets the board.
if (win === 12) {
won.style.visibility = "visible";
}
resetBoard();
}
function unflipCards() {
lockBoard = true;
/* setTimeout function that is implemented so there is an interval between first card being clicked and the second.
unflipcards will turn both cards back with the 1000ms timeout which then removes the flip class */
setTimeout(() => {
firstCard.classList.remove("flip");
secondCard.classList.remove("flip");
resetBoard();
}, 1000);
/* on a unmatch or when no pair is matched, a point gets deducted and goes into the minuses until the user gets a matching pair to get back into receiving points */
points -= 1;
finalPoint = points;
score.innerHTML = points;
}
/* function that resets the board after each round, so after a card flip the game board is locked and the same card cannot be flipped again */
function resetBoard() {
[hasFlippedCard, lockBoard] = [false, false];
[firstCard, secondCard] = [null, null];
}
/* When a game is over the user clicks the button to play again which then calls the function playAgain, which then reloads the webpage and game commences again.
the event listener is also added to click for the function to take place */
function playAgain() {
location.reload();
}
play.addEventListener("click", playAgain);
/* a shuffle method that is implemented that takes place every time a new game is commenced.
the math.random method returns a random number each time as stated below and this is multiplied by 12 as there are 12 cards in the deck */
(function shuffle() {
cards.forEach(card => {
let ramdomPos = Math.floor(Math.random() * 12);
card.style.order = ramdomPos;
});
})();
//added an event listener to cards that flips the card upon the user clicking. the first part can be found above.
cards.forEach(card => card.addEventListener("click", flipCard)); | 2cb795c03ea71b11eedfdb37edaae21f56c6cc6c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Code-Institute-Submissions/mortal-kombat-ms2 | 8a06c17798267ebdbaeb0f3d7835d08ce1212d62 | e1e4ef05969eda95b50c169ff47b95bace84dc53 |
refs/heads/master | <repo_name>jonpaul/Ruby-Meditation<file_sep>/triangle.rb
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# :equilateral if all sides are equal
# :isosceles if exactly 2 sides are equal
# :scalene if no sides are equal
#
# The tests for this method can be found in
# about_triangle_project.rb
# and
# about_triangle_project_2.rb
#
def triangle(a, b, c)
#Triangles require that the sum of two sides is less than the remaining side
if a+b <= c || a+c <= b || c+b <= a
raise TriangleError, "Tryangle again."
end
# Why didn't OR statement work here? Why can't we ask, if A or B or C == 0 raise -- how to say this?
if a == 0 && b == 0 && c == 0
raise TriangleError, "Tryangle again."
end
if a == b && a == c && b == c
return :equilateral
end
if a == b && a != c || c == b && c != a || a == c && a != b
return :isosceles
end
if a != b && a != c && b != c
return :scalene
end
end
class TriangleError < StandardError
end
| 3c2ef1435e228f04a6e50886d6aba748f17c5693 | [
"Ruby"
] | 1 | Ruby | jonpaul/Ruby-Meditation | e3005453c6ae5f676cb3632b4b5502d1db80776d | 078f9aa5054f895a76914ab5e519af2b6caaf627 |
refs/heads/master | <file_sep>package Interfaces;
public interface Saleable {
public double calculateMarkup();
}
<file_sep>package Instruments;
import Enums.ColourTypes;
import Enums.InstrumentTypes;
import Enums.MaterialTypes;
import Interfaces.Playable;
import Interfaces.Saleable;
public class Flute extends Instrument {
private Boolean irishState;
public Flute(String make, String model, MaterialTypes material, ColourTypes colour, InstrumentTypes type, double buyPrice, double sellPrice, Boolean irishState) {
super(make, model, material, colour, type, buyPrice, sellPrice);
this.irishState = irishState;
}
public Boolean getIrishState() {
return irishState;
}
public String play() {
return "Doooo, deedly doooo";
}
}<file_sep>import Enums.ColourTypes;
import Enums.InstrumentTypes;
import Enums.MaterialTypes;
import Enums.ProductsTypes;
import Instruments.Flute;
import Instruments.Keyboard;
import Interfaces.Saleable;
import Locations.Shop;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class ShopTest {
private Shop shop;
private ArrayList<Saleable> stock;
private Flute flute;
private Keyboard keyboard;
@Before
public void setUp() throws Exception {
shop = new Shop("Guns 'n Banjoes");
stock = new ArrayList<>();
flute = new Flute("Pearl", "PF-505", MaterialTypes.TIN, ColourTypes.SILVER, InstrumentTypes.WOODWIND, 100.00, 189.95, false);
keyboard = new Keyboard("Casio", "Plinky Plonk", MaterialTypes.PLASTIC, ColourTypes.PURPLE, InstrumentTypes.KEYBOARD, 158.50, 225.99, 25, "Greensleeves");
}
@Test
public void canAddToStock() {
shop.addStockItem(ProductsTypes.BRASSO);
shop.addStockItem(flute);
assertEquals(2, shop.countStock());
}
@Test
public void canRemoveStockItems() {
shop.addStockItem(ProductsTypes.AK47);
shop.addStockItem(flute);
shop.removeStockItem(flute);
assertEquals(1, shop.countStock());
}
@Test
public void canGetPotentialProfit() {
shop.addStockItem(flute);
shop.addStockItem(keyboard);
shop.addStockItem(ProductsTypes.DRUMSTICK);
shop.addStockItem(ProductsTypes.BRASSO);
shop.addStockItem(ProductsTypes.PLECTRUM);
shop.addStockItem(ProductsTypes.AK47);
assertEquals(422.77, shop.calculateTotalProfit(), 0.01);
}
}
<file_sep>rootProject.name = 'GunsNBanjoes'
<file_sep>package Enums;
public enum MaterialTypes {
WOOD,
BRASS,
PLASTIC,
TIN
}
| 9a6a9e4dd549886e76beead5e9fb3eedd267aca7 | [
"Java",
"Gradle"
] | 5 | Java | neifirst/wk7_d5_hmwrk | ddbf17d63d51ee2167432eb76771cdf6c20050bd | a0bc9cd410c9a4731d0bae427e905da0c11c4759 |
refs/heads/main | <file_sep># wordpress-packaging
<file_sep>#!/bin/bash
read -p "Enter the demo URL: " DEMO_URL
read -p "Please enter theme code: " THEME_CODE
DEMO_USER=$(/scripts/whoowns $DEMO_URL)
mkdir /home/webramz/public_html/wsb/assets/themes/$THEME_CODE && chown webramz:nobody /home/webramz/public_html/wsb/assets/themes/$THEME_CODE
DATABASE_NAME=$(grep DB_NAME /home/$DEMO_USER/public_html/wp-config.php | sed -n "s/^.*'\(.*\)'.*$/\1/ p")
#DATABASE_NAME=$(grep DB_NAME /home/$DEMO_USER/public_html/wp-config.php | cut -d \" -f2)
mysqldump $DATABASE_NAME > database.sql && mv database.sql /home/$DEMO_USER/public_html && chown $DEMO_USER:$DEMO_USER /home/$DEMO_USER/public_html/database.sql
cd /home/$DEMO_USER/public_html/ && zip -r archive.zip * && mv archive.zip /home/webramz/public_html/wsb/assets/themes/$THEME_CODE
| b911b2fe9df2017eb042789e6a365c758b290eff | [
"Markdown",
"Shell"
] | 2 | Markdown | LordElrondd/wordpress-packaging | 2bddf174013de90efb4c4b0ae07f2f68ac591e07 | e438b747420ce409581411868b16c98e3c7a7cb7 |
refs/heads/master | <repo_name>sebaestel/acopio<file_sep>/wordpress-template/data-counter-from-emol.php
data-counter-from-emol.php
<file_sep>/app/app.js
var app = angular.module('gen', [
'ngSanitize',
'ui.router',
'pascalprecht.translate',
'ngMap'
]
);
app.config(function($stateProvider, $urlRouterProvider, $translateProvider) {
$urlRouterProvider.otherwise('/home');
$translateProvider.useSanitizeValueStrategy('escape');
$translateProvider.translations('en', {
hello: 'Hello'
});
$translateProvider.translations('es', {
hello: 'Hola'
});
$translateProvider.preferredLanguage('es');
$stateProvider
.state('root', {
views: {
'header': {
templateUrl: 'templates/header.html',
controller: 'headerController'
},
'footer': {
templateUrl: 'templates/footer.html',
}
}
})
.state('root.home', {
url: '/home',
views: {
'content@': {
templateUrl: 'templates/home.html',
controller: 'homeController'
}
}
})
.state('root.add', {
url: '/add',
views: {
'content@': {
templateUrl: 'templates/place.html',
controller: 'placeController'
}
}
})
.state('root.timelineController', {
url: '/timeline',
views: {
'content@': {
templateUrl: 'templates/timeline.html',
controller: 'timelineController'
}
}
})
.state('root.evolution', {
url: '/evolution',
views: {
'content@': {
templateUrl: 'templates/compare.html',
controller: 'compareController'
}
}
})
.state('root.compare', {
url: '/compare',
views: {
'content@': {
templateUrl: 'templates/compare.html',
controller: 'compareController'
}
}
});
});<file_sep>/Gruntfile.js
module.exports = function (grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-stylus');
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-jslint');
grunt.loadNpmTasks('grunt-html-build');
grunt.loadNpmTasks('grunt-text-replace');
grunt.loadNpmTasks('grunt-exec');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
build: grunt.file.readJSON('build-config.json'),
stylus: {
compile: {
files: {
'styles/style.css': 'styles/main.styl'
}
}
},
copy: {
main: {
files: [
{
expand: true,
src: '<%= build.scripts %>',
flatten: true,
dest: 'build/js'
},
{
expand: true,
src: 'app/**/**.html',
flatten: true,
dest: 'build/templates'
},
{
expand: true,
src: 'app/assets/*',
flatten: true,
dest: 'build/assets'
},
{
expand: true,
src: '<%= build.styles %>',
flatten: true,
dest: 'build/css'
},
{
expand: true,
src: 'app/**/**.js',
flatten: true,
dest: 'build/app'
},
{
expand: true,
src: 'app/data/**',
flatten: true,
dest: 'build/data'
},
{
expand: true,
src: 'js/**.js',
flatten: true,
dest: 'build/js'
}
]
}
},
clean: {
build: ['build'],
css: ['css'],
},
watch: {
css: {
files: [
'app/**/*.*',
'app/**/*.*',
'app/*.*',
'styles/*.styl'
],
tasks: [
'develop'
],
options: {
livereload: true,
port: 8900
}
}
},
jslint: {
server: {
src: [
'app/*.js',
'app/**/*.js',
'app/**/**/*.js'
],
exclude: [
'node_modules/*.js',
'bower_components/*.js',
'app/app.directives.js'
],
directives: {
'node': true,
'todo': true,
'plusplus': true,
'regexp': true,
'globals': {
'window': true,
'localStorage': true,
'admetricks': true,
'jasmine': true,
'describe': true,
'beforeEach': true,
'it': true,
'expect': true,
'inject': true,
'angular': true,
'browser': true,
'document': true,
'element': true,
'moment': true,
'mixpanel': true,
'zE': true,
'by':true,
'io':true,
'_':false,
'$':true
}
},
}
},
htmlbuild: {
app: {
src: 'index.html',
dest: 'build/index.html',
options: {
beautify: true,
prefix: '',
relative: true,
styles: {
bundle: 'build/css/**.css'
},
scripts: {
dependencies: '<%= build.scripts %>',
modules: [
'build/app/**.**'
]
}
}
}
},
exec: {
fake_api: 'json-server --watch db.json',
serve: 'serve -p 8000 build'
},
replace: {
app: {
src: 'build/index.html',
dest: 'build/index.html',
replacements: [{
from: /(..\/bower_components(?:.*)js)/g,
to: function (matchedWord) {
var path = matchedWord.split('/');
return 'js/' + path.pop();
}
},{
from: /(..\/node_modules(?:.*)js)/g,
to: function (matchedWord) {
var path = matchedWord.split('/');
return 'js/' + path.pop();
}
}]
}
}
});
grunt.registerTask('develop', [
'stylus',
'clean:build',
'copy:main',
'clean:css',
'htmlbuild:app',
'replace:app',
'watch'
]);
grunt.registerTask('serve', [
'exec:serve'
]);
grunt.registerTask('fake_api', [
'exec:fake_api'
]);
};
<file_sep>/app/add/placeController.js
app.controller('placeController', function($scope) {
$scope.title = "Map";
$scope.showPlace = false;
$scope.address = "Temuco, Chile";
$scope.placeChanged = function() {
$scope.searchPlace = this.getPlace();
$scope.map.setCenter($scope.searchPlace.geometry.location);
}
$scope.placeMarker = function(e) {
var ll = e.latLng;
$scope.places = []
$scope.places.push({
lat: ll.lat(),
lng: ll.lng()
});
}
$scope.places = [{
name: "<NAME>",
pos: {
lat: "-41.320594",
lon: "-72.981002"
},
address: "Imperial Esquina Del Rosario Sin Numero",
image: "http://liceopac.cl/wp-content/uploads/2014/12/cropped-DSCF4468.jpg",
schedule: {
start: "09:00",
end: "21:00"
},
shelter: true,
product_type: ['agua','alimentos mascotas', 'medicamentos', 'forraje']
},{
name: "Instituto Nacional del Deporte Puerto Montt Insituto",
pos: {
lat: "-41.470406",
lon: "-72.91408"
},
address: "Marathon con Esquina Egaña",
image: "https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xtp1/v/t1.0-9/11150273_1435903526722760_4035783246661023466_n.jpg?oh=1cf224433841a48ca5bb8af6ed188db3&oe=55E4381A&__gda__=1436102716_1eda49fccf8351983c749b8b41782697",
schedule: {
start: "09:00",
end: "20:00"
},
shelter: false,
product_type: ['materiales de construcción']
}]
});
<file_sep>/data-from-onemi.php
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.onemi.cl/alertas/',
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
<script>
$('header, .alertas, .navbar.hidden-phone, .visible-phone').remove()
var events = [];
$('.listado-alertas .row-fluid').each(function() {
var title = $('a p.msg',this).html().trim(),
meta = $('a p.date',this).html().split('|'),
url = $('a',this).attr('href'),
day = meta[0].trim(),
hour = meta[1].trim(),
place = meta[2].trim(),
type = $('a img',this).attr('alt'),
image = $('a img',this).attr('src'),
data = {
"url": url,
"day": day,
"hour": hour,
"place": place,
"type": type,
"title": title,
"image": image
};
events.push(data);
})
str = JSON.stringify(events);
str = JSON.stringify(events, null, 4); // (Optional) beautiful indented output.
$.post( "create-json.php", { data: str, name: "events-onemi" } );
</script><file_sep>/build/app/compareController.js
app.controller('compareController', function($scope) {
var height = parseInt($( window ).height()) - 60;
$('#compare').attr('width',$( window ).width()).attr('height', height);
});
<file_sep>/create-json.php
<?php
echo $_POST['data'];
$myfile = fopen($_POST['name'].".json", "w") or die("Unable to open file!");
$txt = $_POST['data'];
fwrite($myfile, $txt);
fclose($myfile);
?><file_sep>/build/app/timelineController.js
app.controller('timelineController', function($scope) {
var height = parseInt($( window ).height()) - 60;
$('#timeline').attr('width',$( window ).width()).attr('height', height);
});
<file_sep>/README.md
# acopio
To development (after clone)
* It is necessary install node before
```
npm install
bower install
grunt develop
grunt serve
```
<file_sep>/data-counter-from-emol.php
<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.emol.com/noticias/Nacional/2017/01/23/841330/Revisa-la-situacion-de-los-incendios-forestales-que-estan-activos-en-el-pais.html',
CURLOPT_USERAGENT => 'Codular Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
echo $resp;
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
<script>
var html = $('html').clone(true)
var events = [];
data = {
"actives": html.find('[data-incendio="act"]').html(),
"controlled": html.find('[data-incendio="cnt"]').html(),
"combat": html.find('[data-incendio="cmb"]').html(),
"killed": html.find('[data-incendio="ext"]').html(),
"totalha": html.find('[data-incendio="hec"]').html()
};
events.push(data);
str = JSON.stringify(events);
str = JSON.stringify(events, null, 4); // (Optional) beautiful indented output.
$.post( "http://www.chileayuda.com/create-json.php", { data: str, name: "emol-counter" } );
</script> | af0aa626bf220a0cbb35512996c1b8af655abf32 | [
"JavaScript",
"Markdown",
"PHP"
] | 10 | PHP | sebaestel/acopio | e0551560e22e770fd40f5acb33483825d2cb71f4 | 77b66c98e0488ecb52243f0dcbbb30f8319d77d4 |
refs/heads/master | <repo_name>DanielSoaresRocha/GrupoGera<file_sep>/src/app/shared/services/index.ts
export * from './unidade-consumidora.service';
export * from './fatura.service';
export * from './sidebar.service'<file_sep>/src/app/modules/dashboard/dashboard-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FaturasComponent } from './faturas/faturas.component';
import { InicioComponent } from './inicio';
import { UnidadesConsumidorasComponent } from './unidades-consumidoras/unidades-consumidoras.component';
const routes: Routes = [
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full'
},
{
path: 'dashboard',
component: InicioComponent
},
{
path: 'unidades',
component: UnidadesConsumidorasComponent
},
{
path: 'faturas',
component: FaturasComponent
},
{
path: 'faturas/:idUnidade',
component: FaturasComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DashboardRoutingModule {}<file_sep>/src/app/modules/dashboard/inicio/grafico/grafico.component.ts
import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { Fatura } from '@src/app/core/models/fatura';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
interface UnidadesGraphic{
unidade: string;
mediaConsumo: number;
color?: string;
}
@Component({
selector: 'app-grafico',
templateUrl: './grafico.component.html',
styleUrls: ['./grafico.component.scss']
})
export class GraficoComponent implements OnInit{
@Input() unidadesConsumidoras: UnidadeConsumidora[] = [];
unidadesConsumo: UnidadesGraphic[];
consumos: number[] = [];
maiorConsumo = 0;
constructor() { }
ngOnInit(): void {
this.gerarDadosGrafico();
}
gerarDadosGrafico(){
let unidadesConsumo = [];
this.unidadesConsumidoras.forEach((unidade) => {
let consumo = 0;
unidade.faturas.forEach((fatura: Fatura) => {
consumo += fatura.consumo;
})
consumo = (consumo / (unidade.faturas.length > 0 ? unidade.faturas.length : 1)); // Média
this.maiorConsumo = consumo > this.maiorConsumo ? consumo : this.maiorConsumo;
unidadesConsumo.push({
unidade: unidade.nome,
mediaConsumo: consumo.toFixed(0)
})
})
this.gerarEixoX();
this.unidadesConsumo = unidadesConsumo;
this.paintGraphic();
}
gerarEixoX(){
let interator = this.maiorConsumo/4;
let anterior = 0;
for(let i = 0; i < 4; i++) {
let dado = anterior + interator;
this.consumos.push(dado);
anterior = dado;
}
}
calcularPorcentagem(consumoMedio: number){
if(consumoMedio == 0)
return 0
return ((consumoMedio * 100)/ this.maiorConsumo).toFixed(0);
}
paintGraphic(){
let color = 0;
this.unidadesConsumo.forEach((bar) => {
color += 1;
if(color == 1){
bar.color = '#9699D1'
}else if(color == 2){
bar.color = "#54E8BF";
}else if(color == 3){
bar.color = "#FCBBBF";
}else if(color == 4){
bar.color = "#FFD076";
}
if(color % 4 == 0)
color = 0;
})
}
}
<file_sep>/src/app/core/models/fatura.ts
export class Fatura {
consumo: number;
createdAt: string;
data_de_vencimento: string;
id: number;
unidadeConsumidoraId: number;
updatedAt: string;
valor: number
}
<file_sep>/src/app/core/models/unidade-consumidora.model.ts
import { Fatura } from './fatura';
export class UnidadeConsumidora{
createdAt: string;
distribuidora: string;
endereco: string;
faturas: Fatura[];
id: number;
nome: string;
numero: string;
updatedAt: string;
}<file_sep>/src/app/modules/dashboard/inicio/inicio.component.ts
import { Component, OnInit } from '@angular/core';
import { Fatura } from '@src/app/core/models/fatura';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
// Services
import { FaturaService, UnidadeConsumidoraService } from '@src/app/shared/services';
import { Observable } from 'rxjs';
@Component({
selector: 'app-inicio',
templateUrl: './inicio.component.html',
styleUrls: ['./inicio.component.scss']
})
export class InicioComponent implements OnInit {
unidades$: Observable<UnidadeConsumidora[]>;
faturas$: Observable<Fatura[]>;
faturasVencidas = 0;
constructor(
private unidadeConsumidoraService: UnidadeConsumidoraService,
private faturaService: FaturaService
) { }
ngOnInit(): void {
this.unidades$ = this.unidadeConsumidoraService.getAll();
this.faturas$ = this.faturaService.getAll();
this.countFaturasVencidas();
}
countFaturasVencidas(){
this.faturas$.subscribe(
faturas => {
faturas.forEach(fatura => {
let dataFatura: any = fatura.data_de_vencimento.split('/');
dataFatura = dataFatura.map(data => parseInt(data));
dataFatura = new Date(dataFatura[2], dataFatura[1], dataFatura[0]);
if(dataFatura < new Date())
this.faturasVencidas++;
});
});
}
}
<file_sep>/src/app/shared/directives/input-focus.directive.ts
import { AfterViewInit, Directive, ElementRef, OnInit } from '@angular/core';
@Directive({
selector: '[appInputFocus]'
})
export class InputFocusDirective implements AfterViewInit{
private input: HTMLInputElement;
constructor(el: ElementRef) {
this.input = el.nativeElement;
this.onBlur();
}
ngAfterViewInit (): void {
if(this.input.value.length)
this.input.classList.add('has-content')
}
onBlur(){
this.input.addEventListener('blur', () => {
if(this.input.value.length)
this.input.classList.add('has-content')
else
this.input.classList.remove('has-content')
})
}
}
<file_sep>/src/app/modules/dashboard/unidades-consumidoras/unidade-modal/unidade-modal.component.ts
import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
import { UnidadeConsumidoraService } from '@src/app/shared/services';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-unidade-modal',
templateUrl: './unidade-modal.component.html',
styleUrls: ['./unidade-modal.component.scss']
})
export class UnidadeModalComponent implements OnInit {
formUnidade: FormGroup;
@Input() unidade: UnidadeConsumidora = new UnidadeConsumidora();
@Output() submitButton = new EventEmitter();
@Output() onCloseModal = new EventEmitter();
constructor(private unidadeConsumidoraService: UnidadeConsumidoraService) { }
reset(){
this.formUnidade.reset();
this.submitButton.emit();
}
ngOnInit(): void {
this.createForm(this.unidade);
}
add(){
this.unidadeConsumidoraService.add(this.unidade);
}
createForm(unidade: UnidadeConsumidora) {
this.formUnidade = new FormGroup({
nome: new FormControl(unidade.nome),
endereco: new FormControl(unidade.endereco),
distribuidora: new FormControl(unidade.distribuidora),
numero: new FormControl(unidade.numero)
})
}
submit(){
if(this.unidade.id){
this.unidadeConsumidoraService.update(this.formUnidade.value, this.unidade.id).subscribe(() => this.reset())
return;
}
this.unidadeConsumidoraService.add(this.formUnidade.value).subscribe(() => this.reset())
}
closeModal(){
this.onCloseModal.emit();
}
}
<file_sep>/src/app/modules/dashboard/faturas/faturas.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Fatura } from '@src/app/core/models/fatura';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
import { FaturaService, UnidadeConsumidoraService } from '@src/app/shared/services';
@Component({
selector: 'app-faturas',
templateUrl: './faturas.component.html',
styleUrls: ['./faturas.component.scss']
})
export class FaturasComponent implements OnInit {
faturas: Fatura[] = [];
unidades: UnidadeConsumidora[] = [];
idUnidade: number = 0;
fatura: Fatura = new Fatura();
showModalFatura = false;
constructor(
private faturaService: FaturaService,
private unidadeConsumidoraService: UnidadeConsumidoraService,
private activatedRoute: ActivatedRoute
) { }
ngOnInit(): void {
this.idUnidade = parseInt(this.activatedRoute.snapshot.paramMap.get('idUnidade'))
this.getAllUnidades();
}
getAllUnidades(){
this.showModalFatura = false;
this.unidadeConsumidoraService.getAll().subscribe(
unidades => {
this.unidades = unidades;
if(this.idUnidade)
this.faturas = this.getUnidadeById(this.idUnidade).faturas;
else
this.getAllFaturas();
})
}
getAllFaturas(){
this.faturaService.getAll().subscribe(faturas => this.faturas = faturas);
}
deleteFatura(fatura: Fatura){
if(!confirm(`Têm certeza eu deseja excluir a fatura de valor ${fatura.valor}?`))
return
this.faturaService.delete(fatura).subscribe(
() => {
this.getAllUnidades();
}
)
}
editFatura(fatura: Fatura){
this.fatura = fatura;
this.showModalFatura = true;
}
closeModal(){
this.fatura = new Fatura();
this.showModalFatura = false;
}
getUnidadeById(id: number): UnidadeConsumidora{
let unidade: UnidadeConsumidora = null;
for(let u of this.unidades){
if(u.id === id){
unidade = u;
break;
}
}
return unidade;
}
}
<file_sep>/src/app/modules/dashboard/unidades-consumidoras/unidades-consumidoras.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Fatura } from '@src/app/core/models/fatura';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
import { UnidadeConsumidoraService } from '@src/app/shared/services';
@Component({
selector: 'app-unidades-consumidoras',
templateUrl: './unidades-consumidoras.component.html',
styleUrls: ['./unidades-consumidoras.component.scss']
})
export class UnidadesConsumidorasComponent implements OnInit {
unidade: UnidadeConsumidora = new UnidadeConsumidora();
fatura: Fatura = new Fatura();
unidades: UnidadeConsumidora[] = [];
showModalUnidade: boolean;
showModalFatura: boolean;
constructor(
private unidadeConsumidoraService: UnidadeConsumidoraService,
private router: Router,
) { }
ngOnInit(): void {
this.getAllUnidades();
}
getAllUnidades(){
this.showModalUnidade = false;
this.showModalFatura = false;
this.unidadeConsumidoraService.getAll().subscribe(unidades => this.unidades = unidades);
}
editUnidade(unidade: UnidadeConsumidora){
this.unidade = unidade;
this.showModalUnidade = true;
}
deleteUnidade(unidade: UnidadeConsumidora){
if(!confirm(`Têm certeza eu deseja excluir a unidade ${unidade.nome}?`))
return
this.unidadeConsumidoraService.delete(unidade).subscribe(
() => {
this.getAllUnidades();
}
)
}
closeModal(){
this.unidade = new UnidadeConsumidora();
this.fatura = new Fatura();
this.showModalUnidade = false;
this.showModalFatura = false;
}
adicionarFatura(unidade: UnidadeConsumidora){
this.fatura = new Fatura();
this.fatura.unidadeConsumidoraId = unidade.id;
this.showModalFatura = true;
}
redirectFaturas(unidade: UnidadeConsumidora){
this.router.navigate(['/home/faturas/' + unidade.id]);
}
}
<file_sep>/src/app/shared/services/sidebar.service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SidebarService {
private sidebar = new Subject<boolean>();
toggleSideBar(toggle: boolean){
this.sidebar.next(toggle);
}
sideBarObserver(): Observable<boolean>{
return this.sidebar.asObservable();
}
}
<file_sep>/src/app/modules/dashboard/faturas/fatura-modal/fatura-modal.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Fatura } from '@src/app/core/models/fatura';
import { FaturaService } from '@src/app/shared/services';
@Component({
selector: 'app-fatura-modal',
templateUrl: './fatura-modal.component.html',
styleUrls: ['./fatura-modal.component.scss']
})
export class FaturaModalComponent implements OnInit {
formFatura: FormGroup;
@Input() fatura: Fatura = new Fatura();
@Output() submitButton = new EventEmitter();
@Output() onCloseModal = new EventEmitter();
constructor(private faturaService: FaturaService) { }
reset(){
this.formFatura.reset();
this.submitButton.emit();
}
ngOnInit(): void {
this.createForm(this.fatura);
}
add(){
this.faturaService.add(this.fatura);
}
createForm(fatura: Fatura) {
this.formFatura = new FormGroup({
consumo: new FormControl(fatura.consumo),
valor: new FormControl(fatura.valor),
data_de_vencimento: new FormControl(fatura.data_de_vencimento),
unidadeConsumidoraId: new FormControl(fatura.unidadeConsumidoraId),
id: new FormControl(fatura.id)
})
}
submit(){
if(this.fatura.id){
this.faturaService.update(this.formFatura.value, this.fatura.id).subscribe(() => this.reset())
return;
}
this.faturaService.add(this.formFatura.value).subscribe(() => this.reset())
}
closeModal(){
this.onCloseModal.emit();
}
}
<file_sep>/src/app/shared/pipes/index.ts
export * from './format-real.pipe';
export * from './format-date.pipe';
<file_sep>/README.md
<p align="center">
<img src="src/assets/images/demo/logo.jpg" width="200px" float="center"/>
</p>
<h1 align="center">Grupo Gera</h1>
## Objetivo
Desenvolver um dashboard que possibilitará a visualização, criação, modificação e remoção de unidades consumidoras dos clientes, além das tarifas que elas possuem.<br />
<strong>Prazo: 1 semana<strong>
## O que foi desenvolvido? 🚀
<div align="center">
<br>
<img src="src/assets/images/demo/auth.png" alt="Screenshot1" width="100%">
<br>
Tela inicial
</div>
<div align="center">
<br>
<img src="src/assets/images/demo/dashboard.png" alt="Screenshot1" width="100%">
<br>
Dashboard
</div>
<div align="center">
<br>
<img src="src/assets/images/demo/unidades-consumidoras.png" alt="Screenshot1" width="100%">
<br>
Unidades Consumidoras
</div>
<div align="center">
<br>
<img src="src/assets/images/demo/faturas.png" alt="Screenshot1" width="100%">
<br>
Faturas
</div>
## Responsividade ⚖

## Tecnologias usadas 📚
- HTML5
- SCSS
- TypeScript
- Angular 10
- RXJS
## Desenvolvimento 🎬
Ciclo de desenvolvimento utilizado:
- Prototipação (Figma)
- Script de iniciação (ng serve --port 9091 --open)
- Configuração do SCSS
- Estilos SCSS padrões
- Criação de módulos principais (ng g m modules/home)
- Configuração de rotas (app-routing.module.ts) e index.ts
- Criação de componentes dos módulos (ng g c modules/auth/login)
- Estruturação do html e css da página (BEM)
- Organização dos assets
- Configuração de environment
- Criação dos serviços e models
- TsConfig
- Componetização (Separar responsabilidades)
- Testes unitários
- Refatoração e melhorias
Clonando o repositório:
```
git clone https://github.com/DanielSoaresRocha/GrupoGera.git
```
Navegando até a pasta do repositório:
```
cd grupo-gera
```
Baixando as dependências
<small>Execute:</small> `npm i` ou `yarn`
Rodando o projeto
<small>O navegador será aberto automaticamente com o servidor iniciado na porta 9091</small>
<br />
<small>Execute:</small> `npm run start` ou `yarn start`
## License 📝
This project is licensed under the [MIT License](https://opensource.org/licenses/MIT) - see the [LICENSE](LICENSE) file for details.
## Autor
<table>
<tr>
<td align="center"><a href="https://github.com/DanielSoaresRocha"><img src="https://avatars0.githubusercontent.com/u/43214747?s=400&u=a267d113c5469b84bf87d202cdb7129330e4c865&v=4" width="100px;" alt="<NAME>"/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/DanielSoaresRocha/ESIG-challenge/commits?author=DanielSoaresRocha" title="Code">💻</a></td>
<tr>
</table>
<file_sep>/src/app/shared/pipes/format-date.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'formatDate'
})
export class FormatDatePipe implements PipeTransform {
transform(value: Date): unknown {
return new Date(value).toLocaleDateString('pt-br');
}
}
<file_sep>/src/app/modules/dashboard/faturas/fatura-modal/fatura-modal.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FaturaService } from '@src/app/shared/services';
import { FaturaModalComponent } from './fatura-modal.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('FaturaModalComponent', () => {
let component: FaturaModalComponent;
let fixture: ComponentFixture<FaturaModalComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ FaturaModalComponent ],
providers: [ FaturaService ],
imports: [ RouterTestingModule, HttpClientTestingModule ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(FaturaModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
<file_sep>/src/app/shared/directives/index.ts
export * from './input-focus.directive'<file_sep>/src/app/shared/services/unidade-consumidora.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment as env } from '@src/environments/environment';
import { UnidadeConsumidora } from '@src/app/core/models/unidade-consumidora.model';
@Injectable({
providedIn: 'root'
})
export class UnidadeConsumidoraService {
constructor(private httpClient: HttpClient) { }
getAll(): Observable<UnidadeConsumidora[]>{
return this.httpClient.get<UnidadeConsumidora[]>(`${env.baseUrl}unidadeConsumidora`);
}
add(unidade: UnidadeConsumidora): Observable<UnidadeConsumidora>{
return this.httpClient.post<UnidadeConsumidora>(`${env.baseUrl}unidadeConsumidora`, unidade);
}
delete(unidade: UnidadeConsumidora): Observable<UnidadeConsumidora>{
return this.httpClient.delete<UnidadeConsumidora>(`${env.baseUrl}unidadeConsumidora/${unidade.id}`);
}
update(unidade: UnidadeConsumidora, idUnidade: number): Observable<UnidadeConsumidora>{
return this.httpClient.put<UnidadeConsumidora>(`${env.baseUrl}unidadeConsumidora/${idUnidade}`, unidade);
}
}
<file_sep>/src/app/modules/dashboard/dashboard.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { InicioComponent } from './inicio/inicio.component';
import { DashboardRoutingModule } from './dashboard-routing.module';
import { UnidadeModalComponent } from './unidades-consumidoras/unidade-modal/unidade-modal.component';
import { SharedModule } from '@src/app/shared';
import { UnidadesConsumidorasComponent } from './unidades-consumidoras/unidades-consumidoras.component';
import { FaturasComponent } from './faturas/faturas.component';
import { FaturaModalComponent } from './faturas/fatura-modal/fatura-modal.component';
import { GraficoComponent } from './inicio/grafico/grafico.component';
@NgModule({
declarations: [
InicioComponent,
UnidadeModalComponent,
UnidadesConsumidorasComponent,
FaturasComponent,
FaturaModalComponent,
GraficoComponent
],
imports: [
CommonModule,
DashboardRoutingModule,
SharedModule
]
})
export class DashboardModule { }
<file_sep>/src/app/shared/components/layout/index.ts
export * from './layout.component'
export * from './navbar'
export * from './sidebar'<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
baseUrl: 'https://api.dev.grupogera.com/processo-seletivo/'
};
<file_sep>/src/app/shared/services/fatura.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Fatura } from '@src/app/core/models/fatura';
import { Observable } from 'rxjs';
import { environment as env } from '@src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class FaturaService {
constructor(private httpClient: HttpClient) { }
getAll(): Observable<Fatura[]>{
return this.httpClient.get<Fatura[]>(`${env.baseUrl}/fatura`);
}
add(fatura: Fatura): Observable<Fatura>{
return this.httpClient.post<Fatura>(`${env.baseUrl}fatura`, fatura);
}
delete(Fatura: Fatura): Observable<Fatura>{
return this.httpClient.delete<Fatura>(`${env.baseUrl}fatura/${Fatura.id}`);
}
update(fatura: Fatura, idFatura: number): Observable<Fatura>{
return this.httpClient.put<Fatura>(`${env.baseUrl}fatura/${idFatura}`, fatura);
}
}
| 8f0257311f6829f90f550f02c171bdaa93fc141b | [
"Markdown",
"TypeScript"
] | 22 | TypeScript | DanielSoaresRocha/GrupoGera | 0179160ec202292882b525cfc05ee201242a595d | 7d795775d8411f67073f8dd24b507a394c56f7f6 |
refs/heads/master | <repo_name>kikollovet/library-app<file_sep>/app/routes/application.js
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
import ApplicationRouteMixin from 'ember-simple-auth/mixins/application-route-mixin';
export default Route.extend(ApplicationRouteMixin,{
session: service(),
actions:{
logout(){
return this.get('session').invalidate().catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
})
}
}
})<file_sep>/app/components/library-item-form.js
import Component from '@ember/component';
import { action } from '@ember/object';
export default class LibraryItemFormComponent extends Component {
buttonLabel = 'Save'
@action
buttonClicked(param) {
this.sendAction('action', param);
}
}<file_sep>/app/controllers/application.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import firebase from 'firebase/app';
export default Controller.extend({
session: service(),
loggedUser: service(),
})<file_sep>/app/controllers/login.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import firebase from 'firebase/app';
export default Controller.extend({
session: service(),
firebaseApp: service(),
actions: {
async login() {
const auth = await this.get('firebaseApp').auth();
const email = this.get('email');
const password = this.get('<PASSWORD>');
return auth.signInWithEmailAndPassword(email, password).catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode, errorMessage);
this.set('errorLogin', errorMessage)
})
}
}
});
<file_sep>/tests/acceptance/main-test.js
import { module, test } from 'qunit';
import { visit, currentURL, click, fillIn, pauseTest, find, findAll } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { currentSession, authenticateSession, invalidateSession } from 'ember-simple-auth/test-support';
import { tracked } from '@glimmer/tracking';
import Service from '@ember/service';
import Adapter from 'ember-local-storage/adapters/session';
import resetStorages from 'ember-local-storage/test-support/reset-storage';
import faker from 'faker';
module('Acceptance | Main flow of Application', function(hooks) {
setupApplicationTest(hooks);
//Preparation before test
hooks.beforeEach(function() {
//This service is needed to mock the real service that needs a real conection with firebase auth
//to retrieve logged user email
this.owner.register('service:logged-user', class TestService extends Service {
@tracked user = {email: '<EMAIL>'}
});
//This adapter is used to use ember local storage instead of firestore
this.owner.register('adapter:application', class TestAdapter extends Adapter {
});
});
//This makes the database empty after the end of the test
hooks.afterEach(function() {
if (window.sessionStorage) {
window.sessionStorage.clear();
}
resetStorages();
});
test('Main flow of the application', async function(assert) {
//These three asserts prove that an unauthorized user can´t see the content of the pages and are redirected
//to login form
await visit('admin/invitations');
assert.equal(currentURL(), '/login', 'Assert unauthorized route admin/invitations');
await visit('admin/contacts');
assert.equal(currentURL(), '/login', 'Assert unauthorized route admin/contacts');
await visit('admin/seeder');
assert.equal(currentURL(), '/login', 'Assert unauthorized route admin/seeder');
//Sending an invitation. Also check button is disabled with no e-mail written and not disable with valid
//email
const emailInvitationInput = faker.internet.email();
await visit('');
assert.dom('[data-test="saveInvitation"]').isDisabled();
await fillIn('[data-test="emailField"]', emailInvitationInput);
assert.dom('[data-test="saveInvitation"]').isNotDisabled();
await click('[data-test="saveInvitation"]');
//Sending a contact message. Also check button is disabled without valid e-mail and message that got less than
//five characters. After filled in the right requirements check the button is not disabled
const emailContactForm = faker.internet.email();
const messageContactForm = faker.lorem.sentence();
await visit('contact');
assert.dom('[data-test="saveContact"]').isDisabled();
await fillIn('[data-test="contactEmail"]', emailContactForm)
assert.dom('[data-test="saveContact"]').isDisabled();
await fillIn('[data-test="contactMessage"]', messageContactForm)
assert.dom('[data-test="saveContact"]').isNotDisabled();
await click('[data-test="saveContact"]');
//Visiting admin/invitations without login so when the login is done you are redirected to
//admin/invitations
await visit('admin/invitations');
//Authenticating the session with ember-simple-auth/test-support
await authenticateSession();
//Asserting that you are redirected to the last atempted route after login (authenticateSession())
assert.equal(currentURL(), '/admin/invitations', "Confirm redirected after authenticateSession");
assert.equal(this.element.querySelector('h1').textContent, 'Invitations', "Confirm is in invitation page");
//Asserting that the invitation was stored in local database and is show in the page
assert.equal(find('[data-test="invitationEmail"]').textContent, emailInvitationInput,
"Assert invitation saved previously is show in admin/invitations");
//Asserting that the contact message was stored in local database and is show in the page
await visit('admin/contacts');
assert.equal(find('.card-header').innerText, emailContactForm,
"Assert contact email saved previously is show in admin/contacts");
assert.equal(find('h5').innerText, messageContactForm,
"Assert contact message saved previously is show in admin/contacts");
//Populating the form and saving a Library. Also check if button is disabled when the field for the
//name of the library is empty, and not disabled when its filled
const libraryNameForm = faker.company.companyName() + ' Library';
const libraryAddressForm = faker.address.streetAddress();
const libraryPhoneForm = faker.phone.phoneNumber()
await visit('libraries/new');
assert.dom('[data-test="saveLibrary"]').isDisabled();
await fillIn('[data-test="nameLib"]', libraryNameForm);
assert.dom('[data-test="saveLibrary"]').isNotDisabled();
await fillIn('[data-test="addressLib"]', libraryAddressForm);
await fillIn('[data-test="phoneLib"]', libraryPhoneForm);
await click('[data-test="saveLibrary"]');
//Asserting that the library was stored in local database and is show in the page
await visit('libraries');
assert.dom(find('[data-test="libName"]')).hasText(libraryNameForm,
'Assert library name saved previously');
assert.dom(find('[data-test="libAddress"]')).includesText(libraryAddressForm,
'Assert library address saved previously');
assert.dom(find('[data-test="libPhone"]')).includesText(libraryPhoneForm,
'Assert library phone saved previously');
//Filling the fields of seeder form to create libraries, books and authors with random number
//between 1 and 99 for libraries and between 1 and 100 for authors
const libNumberForm = Math.floor(Math.random() * 99) + 1;
const authorNumberForm = Math.floor(Math.random() * 100) + 1;
await visit('admin/seeder');
await fillIn('[data-test="libInput"]', libNumberForm);
await click('[data-test="libButton"]')
await fillIn('[data-test="authorInput"]', authorNumberForm);
await click('[data-test="authorButton"]')
//Asserting that the numbers of libraries and authors created are equal to the numbers filled in the form
//The number of libraries is added one because one was created filling the form
//Here it gets the total number of libraries and authors from the respective number box.
const totalNumberOfLibs = libNumberForm + 1 //had to add 1 because one was created in the form
assert.equal(find('[data-test="numberLib"]').textContent, totalNumberOfLibs,
'Assert total number of libraries in the corresponding number box');
assert.equal(find('[data-test="numberAuthor"]').textContent, authorNumberForm,
'Assert total number of authors in the corresponding number box');
//The numbers of book created by the seeder is always random, so here I´m getting this random number of
//books from the respective number box to use later in an assertion
let numberLib = (this.element.querySelector('[data-test="numberLib"]')).textContent
let numberLibInt = parseInt(numberLib)
let numberAuthor = (this.element.querySelector('[data-test="numberAuthor"]')).textContent
let numberAuthorInt = parseInt(numberAuthor)
let numberBooks = (this.element.querySelector('[data-test="numberBook"]')).textContent
let numberBooksInt = parseInt(numberBooks)
//Asserting the number of libraries
//Here the assertion works by counting the html elements with their respective data-test attributes,
//so, there must be three .card-body that means three libraries
await visit('libraries');
assert.dom('.card-body').exists({count: numberLibInt}, 'Assert the correct number of library cards');
//Asserting the number of authors and books created by the seeder in authors page
//(Here I use let numberBooksInt)
//Here the assertion works by counting the html elements with their respective data-test attributes.
//Its the same as was with the libraries, suppose there is 20 authors, there will be 20 data-test="book"
//elements
await visit('authors');
assert.dom('[data-test="author"]').exists({count: numberAuthorInt}, 'Assert the total number of authors in the table');
assert.dom('[data-test="book"]').exists({count: numberBooksInt},
'Assert the total number of books show in table');
//Invalidating the session
await invalidateSession();
//Confirming that the session is invalidated and is not allowed to enter in protected route
await visit('admin/contacts');
assert.equal(currentURL(), '/login',
'Assert after being logged out you can´t enter protected routes');
});
});<file_sep>/app/services/logged-user.js
import Service from '@ember/service';
import firebase from 'firebase/app';
import { tracked } from '@glimmer/tracking';
export default class LoggedUserService extends Service {
@tracked user = firebase.auth().currentUser;
}
<file_sep>/app/routes/contact.js
import Route from '@ember/routing/route';
export default Route.extend({
model() {
return this.store.createRecord('contact');
},
actions: {
sendContactMessage(newContact) {
newContact.save().then(() => newContact.set('responseMessage', true));
},
willTransition(transition) {
let model = this.controller.get('model');
if (model.get('hasDirtyAttributes')) {
model.rollbackAttributes();
}
}
}
});
| 206600db988906593392c2f8c230a9f13de49303 | [
"JavaScript"
] | 7 | JavaScript | kikollovet/library-app | 7a26b64ae21a3a2b911137cfe8fcb34391f6a8d6 | 960dcaa8c7baa0b4951283ae8b4b6fae8dbbe30f |
refs/heads/master | <file_sep>Heaps
=====
<file_sep>#pragma once
#include <vector>
#include <typeinfo>
namespace MHeap
{
enum HeapType
{
BINOMIAL = 0,
SKEW = 1,
LEFTIST = 2
};
class IVertex
{
public:
virtual ~IVertex(){};
};
class IHeap
{
public:
virtual void meld(IHeap*) = 0;
virtual void insert(int) = 0;
virtual int extract_min() = 0;
virtual HeapType get_heap_type() = 0;
virtual void clear() = 0;
virtual ~IHeap(){};
};
class HeapArray
{
std::vector <IHeap *> heaps;
public:
virtual void add_heap(int, HeapType);
virtual void insert(size_t, int);
virtual int extract_min(size_t);
virtual void meld(size_t, size_t);
virtual size_t size();
virtual bool empty();
virtual ~HeapArray(){};
};
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include "vertex.h"
#include "heaps.h"
#include "meld.h"
#include <typeinfo>
MHeap::SVertex::SVertex()
{
left = NULL;
right = NULL;
}
MHeap::SVertex::SVertex(int k)
{
left = NULL;
right = NULL;
key = k;
}
bool MHeap::SVertex::operator<(SVertex *another)
{
return key < another->key;
}
void MHeap::SVertex::swap_children()
{
std::swap(left, right);
}
void MHeap::SVertex::update()
{
swap_children();
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include "vertex.h"
#include "meld.h"
namespace MHeap
{
class BHeap : public IHeap
{
std::vector <BVertex *> vertex;
std::vector <bool> used;
public:
BHeap(){};
~BHeap();
virtual void bdestructor(BVertex*);
explicit BHeap(const int);
explicit BHeap(const BVertex*);
virtual int operator[](int);
virtual size_t size();
virtual void insert(int);
virtual void meld(IHeap*);
virtual int extract_min();
HeapType get_heap_type()
{
return HeapType::BINOMIAL;
}
virtual void clear();
};
template <class RandVertex>
class LSHeap : public IHeap
{
protected:
RandVertex * root;
public:
LSHeap(){};
~LSHeap(){};
LSHeap(int key)
{
root = new RandVertex(key);
}
void clear()
{
root = NULL;
}
void meld(IHeap* another)
{
LSHeap * heap_to_meld = dynamic_cast<LSHeap*>(another);
if (heap_to_meld == NULL || heap_to_meld->root == NULL)
return;
if (root == NULL)
{
root = heap_to_meld->root;
heap_to_meld->clear();
return;
}
root = merge_ls_heaps(root, heap_to_meld->root);
heap_to_meld->clear();
}
HeapType get_heap_type()
{
return root->get_heap_type();
}
void insert(int key)
{
LSHeap new_heap = LSHeap(key);
meld(&new_heap);
}
int extract_min()
{
if (root != NULL)
{
int result = root->key;
RandVertex * copy_root = root;
root = merge_ls_heaps(root->left, root->right);
delete copy_root;
return result;
}
return 0;
}
int get_high()
{
int e = 1;
RandVertex * curr = root->right;
while (curr != NULL)
{
e++;
curr = curr->right;
}
return e;
}
};
class LHeap : public LSHeap < LVertex >
{
public:
LHeap(){};
explicit LHeap(int key)
{
root = new LVertex(key);
}
};
class SHeap : public LSHeap < SVertex >
{
public:
SHeap(){};
explicit SHeap(int key)
{
root = new SVertex(key);
}
};
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <typeinfo>
#include "vertex.h"
#include "heaps.h"
void make_binary(int n, std::vector <int> &pows)
{
while (n)
{
pows.push_back(n % 2);
n /= 2;
}
}
MHeap::BVertex::BVertex()
{
key = 0;
rang = 0u;
left = NULL;
right = NULL;
};
MHeap::BVertex::BVertex(int k)
{
key = k;
rang = 0u;
left = NULL;
right = NULL;
};
MHeap::BVertex::BVertex(int k, unsigned int d, BVertex * p, BVertex * c, BVertex * s)
{
key = k;
rang = d;
left = c;
right = s;
};
bool MHeap::BVertex::operator<(const BVertex &a)
{
return key < a.key;
}
void merge_vertex(MHeap::BVertex * base, MHeap::BVertex * another)
{
if (*another < *base)
std::swap(*base, *another);
another->right = base->left;
base->left = another;
base->rang++;
}
void MHeap::BHeap::bdestructor(BVertex * curr)
{
if (curr == NULL)
{
delete curr;
return;
}
BVertex * del_ver = curr->left;
for (unsigned int i = 0u; i < curr->rang; i++)
{
BVertex * next = del_ver->right;
bdestructor(del_ver);
del_ver = next;
}
delete curr;
}
MHeap::BHeap::~BHeap()
{
for (size_t i = 0; i < vertex.size(); i++)
bdestructor(vertex[i]);
}
MHeap::BHeap::BHeap(const int key)
{
BVertex * new_vertex = new BVertex;
new_vertex->key = key;
vertex.push_back(new_vertex);
used.push_back(true);
}
MHeap::BHeap::BHeap(const BVertex * main)
{
BVertex * curr = main->left, *curr_next;
delete main;
do
{
curr_next = curr->right;
used.push_back(true);
curr->right = NULL;
vertex.push_back(curr);
curr = curr_next;
} while (curr != NULL);
reverse(vertex.begin(), vertex.end());
}
int MHeap::BHeap::operator[](int index)
{
return used[index];
}
size_t MHeap::BHeap::size()
{
return used.size();
}
void MHeap::BHeap::insert(int key)
{
BVertex * new_ver = new BVertex(key);
bool finish = false;
for (size_t i = 0; i < used.size(); i++)
{
if (!used[i])
{
vertex[i] = new_ver;
used[i] = true;
finish = true;
break;
}
else
{
merge_vertex(new_ver, vertex[i]);
vertex[i] = NULL;
used[i] = false;
}
}
if (!finish)
{
used.push_back(true);
vertex.push_back(new_ver);
}
}
void MHeap::BHeap::clear()
{
vertex.clear();
used.clear();
}
void MHeap::BHeap::meld(IHeap * another)
{
BHeap * heap_to_meld = dynamic_cast<BHeap*>(another);
if (heap_to_meld == NULL || heap_to_meld->vertex.empty())
return;
if (heap_to_meld->get_heap_type() != HeapType::BINOMIAL)
return;
BVertex extraBody;
BVertex * extra = &extraBody;
bool isExtra = false;
while (heap_to_meld->size() < used.size())
heap_to_meld->used.push_back(false);
for (size_t i = 0; i < heap_to_meld->size(); i++)
{
if (isExtra)
{
if (i >= size())
{
if ((*heap_to_meld)[i])
{
merge_vertex(extra, heap_to_meld->vertex[i]);
vertex.push_back(NULL);
used.push_back(false);
}
else
{
vertex.push_back(extra);
isExtra = false;
used.push_back(true);
}
}
else if (!(*heap_to_meld)[i] && !used[i])
{
vertex[i] = extra;
isExtra = false;
used[i] = true;
}
else if (!(*heap_to_meld)[i] && used[i])
{
merge_vertex(extra, vertex[i]);
used[i] = false;
vertex[i] = NULL;
}
else if ((*heap_to_meld)[i])
{
merge_vertex(extra, heap_to_meld->vertex[i]);
}
}
else
{
if (i >= size())
{
if ((*heap_to_meld)[i])
{
used.push_back(true);
vertex.push_back(heap_to_meld->vertex[i]);
}
else
{
used.push_back(false);
vertex.push_back(NULL);;
}
}
else if ((*heap_to_meld)[i] && !used[i])
{
vertex[i] = heap_to_meld->vertex[i];
used[i] = true;
}
else if ((*heap_to_meld)[i] && used[i])
{
merge_vertex(vertex[i], heap_to_meld->vertex[i]);
extra = vertex[i];
isExtra = true;
used[i] = false;
vertex[i] = NULL;
}
}
}
if (isExtra)
{
used.push_back(true);
vertex.push_back(extra);
}
heap_to_meld->clear();
}
int MHeap::BHeap::extract_min()
{
if (vertex.empty())
return 0;
int min_key = INT_MAX, minKeyIndex = 0;
for (size_t i = 0; i < vertex.size(); i++)
{
if (used[i] && vertex[i]->key < min_key)
{
min_key = vertex[i]->key;
minKeyIndex = i;
}
}
used[minKeyIndex] = false;
if (minKeyIndex != 0)
{
BHeap new_heap = BHeap(vertex[minKeyIndex]);
vertex[minKeyIndex] = NULL;
meld(&new_heap);
}
if (min_key == INT_MAX)
return 0;
return min_key;
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include "i_meldable_heap.h"
namespace MHeap
{
class BVertex : public IVertex
{
public:
int key;
BVertex * left, *right;
unsigned int rang;
BVertex();
~BVertex(){};
explicit BVertex(int);
BVertex(int, unsigned int, BVertex*, BVertex*, BVertex*);
virtual bool operator<(const BVertex&);
};
class SVertex : public IVertex
{
public:
int key;
SVertex * left, *right;
~SVertex(){};
SVertex();
explicit SVertex(int k);
virtual bool operator<(SVertex *);
void update_rang(){};
virtual void swap_children();
virtual void update();
bool bad_leftist_vertex()
{
return false;
}
HeapType get_heap_type()
{
return HeapType::SKEW;
}
};
class LVertex : public SVertex
{
unsigned int rang;
public:
LVertex * left, *right;
LVertex();
~LVertex(){};
explicit LVertex(int);
virtual void update_rang();
virtual bool bad_leftist_vertex();
virtual void swap_children();
virtual void update();
HeapType get_heap_type()
{
return HeapType::LEFTIST;
}
};
}
<file_sep>#pragma once
#include "i_meldable_heap.h"
#include "vertex.h"
#include "heaps.h"
void MHeap::HeapArray::add_heap(int key, MHeap::HeapType type)
{
if (type == MHeap::HeapType::BINOMIAL)
heaps.push_back(new MHeap::BHeap(key));
if (type == MHeap::HeapType::LEFTIST)
heaps.push_back(new MHeap::LHeap(key));
if (type == MHeap::HeapType::SKEW)
heaps.push_back(new MHeap::SHeap(key));
}
void MHeap::HeapArray::insert(size_t index, int key)
{
heaps[index]->insert(key);
}
int MHeap::HeapArray::extract_min(size_t index)
{
return heaps[index]->extract_min();
}
void MHeap::HeapArray::meld(size_t first_index, size_t second_index)
{
if (heaps[first_index]->get_heap_type() != heaps[second_index]->get_heap_type())
return;
if (first_index < heaps.size() && second_index < heaps.size() && first_index != second_index)
{
heaps[first_index]->meld(heaps[second_index]);
if (second_index + 1 != heaps.size())
{
heaps[second_index] = heaps.back();
heaps.pop_back();
}
}
}
size_t MHeap::HeapArray::size()
{
return heaps.size();
}
bool MHeap::HeapArray::empty()
{
return heaps.size() == 0;
}
MHeap::IHeap * heap_maker(MHeap::HeapType type)
{
switch (type)
{
case MHeap::BINOMIAL:
return new MHeap::BHeap;
case MHeap::LEFTIST:
return new MHeap::LHeap;
case MHeap::SKEW:
return new MHeap::SHeap;
default:
break;
}
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include "vertex.h"
namespace MHeap
{
template <class RandHeap>
RandHeap * merge_ls_heaps(RandHeap * base, RandHeap * another)
{
if (base == NULL)
return another;
if (another == NULL)
return base;
if (*another < base)
std::swap(*base, *another);
base->right = merge_ls_heaps(another, base->right);
base->update();
return base;
};
template<class RandHeap>
void meld(RandHeap * first, RandHeap * second)
{
if (first->get_heap_type() == second->get_heap_type())
{
first->meld(second);
}
}
}
<file_sep>#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <typeinfo>
#include "vertex.h"
#include "heaps.h"
#include "meld.h"
MHeap::LVertex::LVertex()
{
left = NULL;
right = NULL;
rang = 0;
};
MHeap::LVertex::LVertex(int k)
{
left = NULL;
right = NULL;
rang = 1;
key = k;
};
void MHeap::LVertex::update_rang()
{
if (left == NULL || right == NULL)
rang = 1;
else
rang = 1 + std::min(left->rang, right->rang);
};
bool MHeap::LVertex::bad_leftist_vertex()
{
if (left == NULL && right == NULL)
return false;
if (left == NULL && right != NULL)
return true;
if (left != NULL && right == NULL)
return false;
return left->rang < right->rang;
};
void MHeap::LVertex::swap_children()
{
std::swap(left, right);
}
void MHeap::LVertex::update()
{
update_rang();
if (bad_leftist_vertex())
swap_children();
}
<file_sep>#pragma once
#include "vertex.h"
#include "heaps.h"
#include <iostream>
#include <vector>
#include <ctime>
#include <set>
using namespace std;
const size_t HEAP_SIZE_TO_MELD = 5000;
void commonInsert(MHeap::BHeap &BH, MHeap::SHeap &SH, MHeap::LHeap &LH, multiset <int> &PH, int x)
{
BH.insert(x);
SH.insert(x);
LH.insert(x);
PH.insert(x);
}
void testingDifferentHeaps(unsigned int numberOfTests)
{
multiset <int> PH;
MHeap::BHeap BH;
MHeap::SHeap SH;
MHeap::LHeap LH;
bool workCorrect = true;
for (unsigned int i = 0; i < numberOfTests; i++)
{
size_t type = rand() % 10;
if (type > 1 || PH.size() < 2)
{
int x = rand();
commonInsert(BH, SH, LH, PH, x);
}
else
{
int b = BH.extract_min();
int s = SH.extract_min();
int l = LH.extract_min();
int p = *PH.begin();
PH.erase(PH.begin());
if (b != p || s != p || l != p)
workCorrect = false;
}
}
cerr << "Correct work of insert and extract_min: ";
if (workCorrect)
cerr << "+" << endl;
else
cerr << "-" << endl;
}
template <class RandHeap>
double randomInsertExtract(RandHeap &H, unsigned int numberOfTests)
{
clock_t t = clock();
for (unsigned int i = 0; i < numberOfTests; i++)
{
size_t type = rand() % 10;
if (type > 1)
{
int x = rand();
H.insert(x);
}
else
{
int b = H.extract_min();
}
}
return (double)(clock() - t) / CLOCKS_PER_SEC;
}
void testingTimeBHeap(unsigned int numberOfTests)
{
MHeap::BHeap BH;
cerr << "BHeap works on " << numberOfTests << " tests in " << randomInsertExtract(BH, numberOfTests) << "\n";
}
void testingTimeSHeap(unsigned int numberOfTests)
{
MHeap::SHeap SH;
cerr << "SHeap works on " << numberOfTests << " tests in " << randomInsertExtract(SH, numberOfTests) << "\n";
}
void testingTimeLHeap(unsigned int numberOfTests)
{
MHeap::LHeap LH;
cerr << "LHeap works on " << numberOfTests << " tests in " << randomInsertExtract(LH, numberOfTests) << "\n";
}
void testingTime(unsigned int numberOfTests)
{
testingTimeBHeap(numberOfTests);
testingTimeSHeap(numberOfTests);
testingTimeLHeap(numberOfTests);
}
void generateHeaps(MHeap::BHeap &BH, MHeap::SHeap &SH, MHeap::LHeap &LH, multiset <int> &PH, size_t heapSize)
{
for (size_t i = 0; i < heapSize; i++)
{
int x = rand();
commonInsert(BH, SH, LH, PH, x);
}
}
void meldSet(multiset <int> &first, multiset <int> &second)
{
if (second.empty())
return;
for (multiset <int>::iterator it = second.begin(); it != second.end(); it++)
first.insert(*it);
second.clear();
}
bool minsNotEqual(MHeap::BHeap &BH, MHeap::SHeap &SH, MHeap::LHeap &LH, multiset <int> &PH)
{
int b = BH.extract_min();
int s = SH.extract_min();
int l = LH.extract_min();
int p = *PH.begin();
PH.erase(PH.begin());
return (b != p || s != p || l != p);
}
void testingMeld(unsigned int numberOfTests)
{
bool workCorrect = true;
for (unsigned int i = 0; i < numberOfTests; i++)
{
size_t heapSizeFirst = rand() % HEAP_SIZE_TO_MELD + 1, heapSizeSecond = rand() % HEAP_SIZE_TO_MELD + 1;
MHeap::BHeap BFirst, BSecond;
MHeap::SHeap SFirst, SSecond;
MHeap::LHeap LFirst, LSecond;
multiset <int> PFirst, PSecond;
generateHeaps(BFirst, SFirst, LFirst, PFirst, heapSizeFirst);
generateHeaps(BSecond, SSecond, LSecond, PSecond, heapSizeSecond);
MHeap::meld(&BFirst, &BSecond);
MHeap::meld(&SFirst, &SSecond);
MHeap::meld(&LFirst, &LSecond);
meldSet(PFirst, PSecond);
for (size_t i = 0; i + 1 < heapSizeFirst + heapSizeSecond; i++)
if (minsNotEqual(BFirst, SFirst, LFirst, PFirst))
workCorrect = false;
}
cerr << "Correct work of meld: ";
if (workCorrect)
cerr << "+" << endl;
else
cerr << "-" << endl;
}
enum ArrayTestType
{
NEW_HEAP = 0,
INSERT = 1,
EXTRACT_MIN = 2,
MELD = 3
};
size_t getIndex(MHeap::HeapArray &HA)
{
if (HA.empty())
return 0;
return rand() % HA.size();
}
void addSet(vector< pair < multiset <int>, MHeap::HeapType > > &PA, int key, int heap_type)
{
multiset <int> ms;
ms.insert(key);
PA.push_back(make_pair(ms, (MHeap::HeapType)heap_type));
}
void meldSetsInArray(vector< pair < multiset <int>, MHeap::HeapType > > &PA, size_t first, size_t second)
{
if (PA[first].second == PA[second].second)
{
meldSet(PA[first].first, PA[second].first);
PA[second] = PA.back();
PA.pop_back();
}
}
void testingHeapArray(unsigned int numberOfTests)
{
MHeap::HeapArray HA;
vector< pair < multiset <int>, MHeap::HeapType > > PA;
bool workCorrect = true;
size_t index, indexFirst, indexSecond;
int x, heap_type, key, h, p;
for (unsigned int i = 0; i < numberOfTests; i++)
{
int test_type = rand() % 4;
if (HA.empty())
test_type = 0;
switch (test_type)
{
case NEW_HEAP:
heap_type = rand() % 3;
key = rand();
HA.add_heap(key, (MHeap::HeapType)heap_type);
addSet(PA, key, heap_type);
break;
case INSERT:
index = getIndex(HA);
x = rand();
HA.insert(index, x);
PA[index].first.insert(x);
break;
case EXTRACT_MIN:
index = getIndex(HA);
if (PA[index].first.empty())
break;
h = HA.extract_min(index);
p = *PA[index].first.begin();
PA[index].first.erase(PA[index].first.begin());
if (h != p)
workCorrect = false;
break;
case MELD:
if (PA.size() < 2)
break;
indexFirst = getIndex(HA);
indexSecond = getIndex(HA);
if (indexFirst == indexSecond)
indexSecond = (indexSecond + 1) % HA.size();
HA.meld(indexFirst, indexSecond);
meldSetsInArray(PA, indexFirst, indexSecond);
break;
}
}
cerr << "Correct work of heap array: ";
if (workCorrect)
cerr << "+" << endl;
else
cerr << "-" << endl;
}
void testing(unsigned int numberOfTests)
{
testingDifferentHeaps(numberOfTests);
testingTime(numberOfTests);
testingMeld(numberOfTests);
testingHeapArray(numberOfTests);
}
| adbe7413a214e93c6a6e814d42641a0a4f2dcee6 | [
"Markdown",
"C++"
] | 10 | Markdown | zerts/Heaps | b3701738537d90713066606c354444a5bfafe037 | e1d2008a31ac23eb4567f2f924f4a262be4a5af5 |
refs/heads/master | <repo_name>gobind452/Miscellaneous-Projects<file_sep>/Computer Networks/Chat Application/client.py
import socket
from threading import Lock,Thread
import gc
from cryptography.hazmat.primitives.asymmetric import rsa,padding
from cryptography.hazmat.primitives import serialization,hashes
from cryptography.hazmat.backends import default_backend
import sys
import base64
import hashlib
from numpy.random import randint
import time
publicKey = []
privateKey = []
publicKeyCopy = []
mode = int(sys.argv[3])
def generateKeyPair():
global publicKey
global privateKey
global publicKeyCopy
privateKey = rsa.generate_private_key(public_exponent=2*randint(low=4,high=10000)+1,key_size=512,backend=default_backend())
publicKey = privateKey.public_key()
privateKey = privateKey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.PKCS8,encryption_algorithm=serialization.NoEncryption())
publicKey = publicKey.public_bytes(encoding=serialization.Encoding.DER,format=serialization.PublicFormat.SubjectPublicKeyInfo)
publicKeyCopy = str(base64.b64encode(publicKey).decode("utf-8"))
def encrypt(message,key):
key = base64.b64decode(key.encode("utf-8"))
key = serialization.load_der_public_key(key,backend=default_backend())
encrypted = key.encrypt(message,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),algorithm=hashes.SHA1(),label=None))
return encrypted
def decrypt(encrypted,key):
key = serialization.load_pem_private_key(key,password=None,backend=default_backend())
original_message = key.decrypt(encrypted,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),algorithm=hashes.SHA1(),label=None))
return original_message
def getHashDigest(message):
message = hashlib.sha256(message.encode("utf-8"))
return message.hexdigest()
def sign(message):
key = serialization.load_pem_private_key(privateKey,password=<PASSWORD>,backend=default_backend())
encrypted = key.sign(message,padding.PSS(mgf=padding.MGF1(hashes.SHA1()),salt_length=padding.PSS.MAX_LENGTH),hashes.SHA1())
return encrypted
def verifySignature(signature,message,key):
key = base64.b64decode(key.encode("utf-8"))
key = serialization.load_der_public_key(key,backend=default_backend())
try:
key.verify(signature,message,padding.PSS(mgf=padding.MGF1(hashes.SHA1()),salt_length=padding.PSS.MAX_LENGTH),hashes.SHA1())
return True
except:
return False
if mode > 0:
generateKeyPair()
port = int(sys.argv[2]) # The port used by the server
buffer_size = 1024
username = input("Enter username ")
host = str(sys.argv[1])
lock = Lock()
registered = False
errorMessages = {"MALFORMED":"ERROR 100 Malformed username\n\n","NOREGISTRATION":"ERROR 101 No user registered\n\n","CANTSEND":
"ERROR 102 Unable to send\n\n","HEADERINCOMPLETE":"ERROR 103 Header incomplete\n\n","DUPLICATEUSER":"ERROR 104 Username already registered\n\n","USERNOTFOUND":"ERROR 110 User not registered\n\n","NOMATCH":"Error 111 Sender and Receiver username not matching \n\n","SHUTDOWN":"ERROR 000 UNREGISTER\n\n"}
displayMessages = {'TAMPERED':"Following message is tampered\n",'HEADERINCOMPLETE':"Incomplete header\n",'USERNOTFOUND':"No such username","ERRORSENDING":"Error in sending message\n","MALFORMED":"Malformed username,enter new username\n","USERNAMETAKEN":"Username Taken,enter new username\n","ENTER":"Enter message \n","INCORRECT":"Incorrect format, type again\n","SENT":"Message sent","SHUTDOWN":"Closing connection"}
class Log(list):
def append(self,message):
list.append(self,message)
log = Log()
sending_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
receiving_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sending_socket.connect((host,port))
receiving_socket.connect((host,port))
class SendingThread(Thread):
def __init__(self,conn):
Thread.__init__(self)
self.conn = conn
self.type = "SEND"
self.userName = username
def register(self):
while True:
if mode == 0:
message = "REGISTER TOSEND " + self.userName + "\n\n"
else:
message = "REGISTER TOSEND " + self.userName + "\nKey : "+publicKeyCopy+"\n\n"
self.sendMessage(message)
data = self.streamHeader()
errorFound = self.analyzeForErrors(data,0)
if errorFound == 0:
break
global registered
registered = True
return
def analyzeForErrors(self,data,flag):
if flag == 0:
response = data[0].split()
if response[0] == "REGISTERED":
return 0
if response[1] == "100":
self.askForNewUserName(displayMessages['MALFORMED'])
return 1
if response[1] == "104":
self.askForNewUserName(displayMessages['USERNAMETAKEN'])
return 1
else:
print(data[0])
return 1
else:
response = data[0].split()
if response[0] == "SENT":
return 0
elif response[1] == "102":
print(displayMessages['ERRORSENDING'])
return 1
elif response[1] == "103":
print(displayMessages['HEADERINCOMPLETE'])
return 1
elif response[1] == "000":
return -1
else:
return 1
def sendMessage(self,message):
self.conn.sendall(b''+str.encode(message))
def askForNewUserName(self,text):
global username
username = input(text)
self.userName = username
def streamHeader(self):
data = []
curr = ""
while True:
packet = self.conn.recv(1)
if not packet:
break
curr = curr + str(packet.decode("utf-8"))
if curr == "\n":
return data
elif curr[-1] == "\n":
data.append(curr[:-1])
curr = ""
def run(self):
self.register()
exit = 0
while exit!=-1:
message = input(displayMessages['ENTER'])
message = message.split(" ",2)
if message[0] != "@":
print(displayMessages['INCORRECT'])
continue
exit = self.chatWithPerson(message[1],message[2])
print(displayMessages['SHUTDOWN'])
def streamMessage(self,n):
message = ""
while len(message)<n:
packet = self.conn.recv(n-len(message))
if not packet:
break
message = message + str(packet.decode("utf-8"))
return message
def chatWithPerson(self,username,message):
if mode == 0:
data = "SEND "+username+"\nContent-length : "+str(len(message))+"\n\n"
if mode == 1 or mode == 2:
key = self.fetchKey(username)
if key == None:
return
message = str(base64.b64encode(encrypt(str.encode(message,"utf-8"),key)).decode("utf-8"))
length = len(message)
if mode == 2:
digest = getHashDigest(message)
digest = sign(digest.encode('utf-8'))
digest = str(base64.b64encode(digest).decode('utf-8'))
data = "SEND "+username+"\nContent-length : "+str(length)+"\nHash : "+digest+"\n\n"
else:
data = "SEND "+username+"\nContent-length : "+str(length)+"\n\n"
self.sendMessage(data)
log.append("Sent header to server")
self.sendMessage(message)
data = self.streamHeader()
log.append("Got confirmation from server")
errorFound = self.analyzeForErrors(data,1)
if errorFound == 0:
print("Message sent")
return errorFound
def fetchKey(self,username):
message = "FETCHKEY "+username+"\n\n"
self.sendMessage(message)
response = self.streamHeader()
if response[0].split()[1] == "110":
print(displayMessages['USERNOTFOUND'])
return
length = int(response[0].split()[1])
key = self.streamMessage(length)
return key
class ReceivingThread(Thread):
def __init__(self,conn):
Thread.__init__(self)
self.conn = conn
self.type = "RECV"
self.userName = username
def register(self):
if mode == 0:
message = "REGISTER TORECV " + self.userName + "\n\n"
else:
message = "REGISTER TORECV " + self.userName + "\nKey : "+publicKeyCopy+"\n\n"
self.sendMessage(message)
data = self.streamHeader()
return
def sendMessage(self,message):
try:
self.conn.sendall(b''+str.encode(message))
except:
print("Couldnt send data")
def streamHeader(self):
data = []
curr = ""
while True:
packet = self.conn.recv(1)
if not packet:
break
curr = curr + str(packet.decode("utf-8"))
if curr == "\n":
return data
elif curr[-1] == "\n":
data.append(curr[:-1])
curr = ""
def askForNewUserName(self,text):
global username
username = input(text)
self.userName = username
def streamMessage(self,n):
message = ""
while len(message)<n:
packet = self.conn.recv(n-len(message))
if not packet:
break
message = message + str(packet.decode("utf-8"))
return message
def analyzeForErrors(self,header,flag):
if header[0][:-2] == errorMessages['SHUTDOWN']:
return -1
data = header[0].split()
if len(header)<2+int(mode>1):
for e in header:
data = e.split()
index = e.find('Content-length')
if index != -1:
self.streamMessage(int(e.split(':')[1][1:]))
self.sendMessage(errorMessages['HEADERINCOMPLETE'])
return 1
self.sendMessage(errorMessages['SHUTDOWN'])
return -1
return 0
def receiveAndConfirmMessage(self):
data = self.streamHeader()
errorFound = self.analyzeForErrors(data,1)
if errorFound != 0:
return errorFound
forward,sender = data[0].split()
_,length = data[1].split(":")
length = int(length[1:])
if mode == 2:
digest = data[2].split(":")[1][1:]
digest = base64.b64decode(digest.encode('utf-8'))
key = data[3].split(":")[1][1:]
message = self.streamMessage(length)
log.append("Got message from server")
if mode != 0:
if mode == 2:
actualDigest = getHashDigest(message).encode('utf-8')
if verifySignature(digest,actualDigest,key) == False:
print(errorMessages['TAMPERED'])
message = str(decrypt(base64.b64decode(message.encode("utf-8")),privateKey).decode("utf-8"))
self.sendMessage("RECEIVED "+sender+"\n\n")
log.append("Sent confirmation to server")
print("# "+sender + " : "+message)
return 1
def run(self):
self.register()
exit = 1
while exit!=-1:
exit = self.receiveAndConfirmMessage()
print(displayMessages['SHUTDOWN'])
sendingThread = SendingThread(sending_socket)
sendingThread.start()
while registered == False:
continue
receivingThread = ReceivingThread(receiving_socket)
receivingThread.start()
sendingThread.join()
receivingThread.join()
sending_socket.close()
receiving_socket.close()
<file_sep>/Computer Networks/README.md
# Assignments for the course Computer Networks
<file_sep>/Computer Networks/Chat Application/server.py
import socket
from threading import Lock,Thread
import gc
from cryptography.hazmat.primitives.asymmetric import rsa,padding
from cryptography.hazmat.primitives import serialization,hashes
from cryptography.hazmat.backends import default_backend
import base64
from numpy.random import randint
import sys
privateKey = []
publicKey = []
publicKeyCopy = []
def generateKeyPair():
global publicKey
global privateKey
global publicKeyCopy
privateKey = rsa.generate_private_key(public_exponent=2*randint(low=4,high=10000)+1,key_size=512,backend=default_backend())
publicKey = privateKey.public_key()
privateKey = privateKey.private_bytes(encoding=serialization.Encoding.PEM,format=serialization.PrivateFormat.PKCS8,encryption_algorithm=serialization.NoEncryption())
publicKey = publicKey.public_bytes(encoding=serialization.Encoding.DER,format=serialization.PublicFormat.SubjectPublicKeyInfo)
publicKeyCopy = str(base64.b64encode(publicKey).decode("utf-8"))
def decrypt(encrypted,key):
key = serialization.load_pem_private_key(key,password=<PASSWORD>,backend=default_backend())
original_message = key.decrypt(encrypted,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),algorithm=hashes.SHA1(),label=None))
return original_message
host = str(sys.argv[1])
port = int(sys.argv[2])
buffer_size = 1024
mode = int(sys.argv[3]) # 0 - Unencrypted, 1- Encrypted, 2- Encrypted with signatures
maxHosts = int(sys.argv[4])
if mode>0:
generateKeyPair()
lock = Lock()
errorMessages = {"MALFORMED":"ERROR 100 Malformed username\n\n","NOREGISTRATION":"ERROR 101 No user registered\n\n","CANTSEND":
"ERROR 102 Unable to send\n\n","HEADERINCOMPLETE":"ERROR 103 Header incomplete\n\n","DUPLICATEUSER":"ERROR 104 Username already registered\n\n","USERNOTFOUND":"ERROR 110 User not registered\n\n","NOMATCH":"Error 111 Sender and Receiver username not matching \n\n","NOKEY":"Error 112 No key sent\n\n",'SHUTDOWN':"ERROR 000 UNREGISTER\n\n"}
class Log(list):
def append(self,message):
list.append(self,message)
if len(self)>10:
self = Log()
log = Log()
sending_usernames = {} # Dict from (username) to (addr,port)
receiving_usernames = {}
sockets = {} # Dict from (addr,port) to sockets
threads = []
public_keys = {}
registered = {}
receiving_usernames['HOST'] = (host,port)
if mode!=0:
public_keys['HOST'] = publicKeyCopy
class ClientThread(Thread):
def __init__(self,ip,port,conn):
Thread.__init__(self)
self.ip = ip
self.port = port
self.conn = conn
self.type = ""
self.username = ""
def streamHeader(self,conn):
data = []
curr = ""
while True:
packet = conn.recv(1)
if not packet:
break
curr = curr + str(packet.decode("utf-8"))
if curr == "\n":
return data
elif curr[-1] == "\n":
data.append(curr[:-1])
curr = ""
def streamMessage(self,n,conn):
message = ""
while len(message)<n:
packet = conn.recv(n-len(message))
if not packet:
break
message = message + str(packet.decode("utf-8"))
return message
def sendMessage(self,message,conn):
conn.sendall(b''+str.encode(message))
def analyzeForErrors(self,header,flag):
if flag == 0: # Before registration errors
data = header[0].split()
if data[0]!="REGISTER": # If something different
self.sendMessage(errorMessages["NOREGISTRATION"],self.conn)
return 1
if data[2].isalnum() == False: # Malformed username
self.sendMessage(errorMessages["MALFORMED"],self.conn)
return 1
if data[1][2:] == "SEND":
if data[2] in sending_usernames.keys(): # If username already found
self.sendMessage(errorMessages['DUPLICATEUSER'],self.conn) # Choose another username
return 1
else:
if data[2] in receiving_usernames.keys(): # If username already found
self.sendMessage(errorMessages['NOMATCH'],self.conn) # Choose another username
return 1
if mode!=0:
if len(header)<2 or header[1].split(':')[0]!="Key ":
self.sendMessage(errorMessages['NOKEY'],self.conn)
return 1
return 0
elif flag == 1:
if header[0].split()[0] == "FETCHKEY":
return 0
if len(header)<2+int(mode>1):
for e in header:
print(e)
data = e.split()
index = e.find('Content-length')
if index != -1:
self.streamMessage(int(e.split(':')[1][1:]),self.conn)
self.sendMessage(errorMessages['HEADERINCOMPLETE'],self.conn)
return 1
return -1
return 0
else:
data = header[0].split()
if data[1] == "102":
self.sendMessage(errorMessages['CANTSEND'],self.conn)
return 1
if data[1] == "103":
self.sendMessage(errorMessages['CANTSEND'],self.conn)
return 1
if data[1] == "000":
return -1
return 0
def registerClient(self):
while True:
header = self.streamHeader(self.conn)
lock.acquire()
errorFound = self.analyzeForErrors(header,0)
if errorFound == 0:
data = header[0].split()
if data[1][2:] == "SEND":
sending_usernames[data[2]] = (self.ip,self.port)
registered[data[2]] = False
else:
receiving_usernames[data[2]] = (self.ip,self.port)
registered[data[2]] = True
self.sendMessage("REGISTERED "+data[1]+" "+data[2]+"\n\n",self.conn)
self.username = data[2]
self.type = data[1][2:]
if mode != 0:
public_keys[self.username] = header[1].split(':')[1][1:]
lock.release()
break
lock.release()
return
def listenForMessages(self):
header = self.streamHeader(self.conn)
log.append("Got header from sender")
errorFound = self.analyzeForErrors(header,1)
if errorFound != 0:
return errorFound
data = header[0].split()
if data[0] == "SEND":
receiver = data[1]
messageLength = int(header[1].split(':')[1][1:])
message = self.streamMessage(messageLength,self.conn)
log.append("Got message from sender")
args = {}
args['receiver'],args['message'], = receiver,message
if mode == 2:
digest = header[2].split(':')[1][1:]
args['digest'] = digest
return args
if data[0] == "FETCHKEY":
args = {}
args['key'] = data[1]
return args
def forwardMessage(self,args):
receiver = args['receiver']
message = args['message']
if receiver not in receiving_usernames.keys():
self.sendMessage(errorMessages['USERNOTFOUND'],self.conn)
return
if mode == 0 or mode == 1:
data = "FORWARD "+ self.username+"\nContent-length : "+str(len(message))+"\n\n"
if mode == 2:
key = public_keys[self.username]
data = "FORWARD "+ self.username+"\nContent-length : "+str(len(message))+"\nHash : "+args['digest']+"\nKey : "+key+"\n\n"
self.sendMessage(data,sockets[receiving_usernames[receiver]])
log.append("Sent header to receiver")
self.sendMessage(message,sockets[receiving_usernames[receiver]])
log.append("Sent message to receiver")
data = self.streamHeader(sockets[receiving_usernames[receiver]])
errorFound = self.analyzeForErrors(data,2)
if errorFound != 0:
return errorFound
log.append("Got confirmation by receiver")
data = data[0].split()
if data[0] == "RECEIVED" and data[1] == self.username:
self.sendMessage("SENT "+receiver+"\n\n",self.conn)
log.append("Sent confirmation to sender")
return
def processMessageToServer(self,args):
if mode == 0:
if args['message'] == "UNREGISTER":
return -1
else:
message = str(decrypt(base64.b64decode(args['message'].encode("utf-8")),privateKey).decode("utf-8"))
if message == "UNREGISTER":
return -1
return 1
def run(self):
self.registerClient()
if self.type == "RECV":
return
exit = 1
while exit!=-1:
args = self.listenForMessages()
if type(args) == int:
exit = args
continue
if "receiver" in args.keys():
if args['receiver'] == 'HOST':
exit = self.processMessageToServer(args)
else:
exit = self.forwardMessage(args)
if "key" in args.keys():
if args['key'] in public_keys.keys():
key = public_keys[args["key"]]
length = len(key)
self.sendMessage("Key-Length "+str(length)+"\n\n",self.conn)
self.sendMessage(key,self.conn)
else:
self.sendMessage(errorMessages['USERNOTFOUND'],self.conn)
self.sendMessage(errorMessages['SHUTDOWN'],self.conn)
self.sendMessage(errorMessages['SHUTDOWN'],sockets[receiving_usernames[self.username]])
del sockets[receiving_usernames[self.username]]
del sockets[sending_usernames[self.username]]
del sending_usernames[self.username]
del receiving_usernames[self.username]
del registered[self.username]
if mode!=0:
del public_keys[self.username]
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
s.bind((host,port))
s.listen()
for i in range(2*maxHosts):
conn,addr = s.accept()
thread = ClientThread(addr[0],addr[1],conn)
sockets[addr] = conn
threads.append(thread)
thread.start()
for t in threads:
t.join()<file_sep>/RL/gym-dino/gym_dino/envs/__init__.py
from gym_dino.envs.dino_env import DinoEnv<file_sep>/RL/README.md
## A deep reinforcement learning agent for the dino game in chrome
### Algorithms used - Policy Gradient and Actor-Critic
#### Schematics
Main.py - Game Engine
Try.py - Reinforcement Learning Agent
<file_sep>/RL/gym-dino/setup.py
from setuptools import setup
setup(name='gym_dino',version='0.1',install_requires=['gym', 'numpy', 'pygame'])<file_sep>/Databases/Cricket Database/test.py
from flask import Flask, redirect, url_for, request,render_template
import connect
app = Flask(__name__) # Constructor
@app.route('/home',methods=['POST','GET'])
def home():
return render_template('home.html')
@app.route('/reset/<message>',methods=['POST','GET'])
def reset(message):
return render_template('home.html',message=message)
@app.route('/result',methods = ['POST','GET'])
def result():
parameter = dict(request.form) # Creates a dict of the form results
result = connect.executeGeneralSelectQuery(parameter) # Give it to the psycopg2 code
return render_template('hello.html',result = result) # Give the answer to the template page
@app.route('/player/<Id>',methods = ['GET'])
def player(Id):
name,country,result_test,result_odi,result_t20 = connect.executeSpecificQuery(Id)
similar_players = connect.similarPlayers(Id)
return render_template('player.html',Id=Id,result_test = result_test,result_odi=result_odi,result_t20=result_t20,name = name,country = country,similar_players= similar_players)
@app.route('/search',methods = ['GET'])
def search():
return render_template('search.html')
@app.route('/add', methods = ['POST','GET'])
def add():
if request.method == 'GET':
return render_template('add.html')
elif request.method == 'POST':
parameters = dict(request.form)
if parameters['name'] == '':
return redirect(url_for('reset', message = "Name not entered"))
if parameters['country'] == '':
return redirect(url_for('reset', message = "Country not entered"))
Id = connect.addPlayer(parameters)
return redirect(url_for('added',Id = Id,name=parameters['name'],country=parameters['country']))
@app.route('/added/<Id>/<name>/<country>',methods = ['POST','GET'])
def added(Id,name,country):
if request.method == 'GET':
return render_template('added.html',Id = Id, name = name, country = country)
elif request.method == 'POST':
parameters = dict(request.form)
parameters['Id'] = Id
connect.executeGeneralInsertQuery(parameters)
return redirect(url_for('home'))
@app.route('/delete/<Id>', methods=['GET'])
def delete(Id):
connect.deletePlayer(Id)
return redirect(url_for('reset',message="Success"))
@app.route('/prompt/<page>',methods=['GET'])
def prompt(page):
return render_template('prompt.html',page=page)
@app.route('/update/<Id>', methods=['GET','POST'])
def update(Id):
if request.method == 'GET':
return render_template('update.html',Id = Id)
elif request.method == 'POST':
parameters = dict(request.form)
parameters['Id'] = Id
connect.updateGeneral(parameters)
return redirect(url_for('player',Id =Id))
@app.route('/country',methods=['GET','POST'])
def country():
if request.method == 'GET':
parameters = dict(request.args)
if len(parameters.keys()) == 0:
return render_template('country.html')
else:
result,bat,ball = connect.fillInfo(parameters)
return render_template('country_open.html',result = result,country = parameters['country'],game = parameters['game'],bat=bat,ball=ball)
if __name__ == '__main__':
app.run()<file_sep>/Computer Networks/Chat Application/README.md
# ChatApplication
### Made as a part of the course COL334 (Computer Networks) at IIT Delhi
A minimal client-server chat application using socket programming in Python supporting encryption and signatures
### Instructions
Run server.py as -
>python3 server.py ip_address port mode maxClients
Run client.py as-
>python3 client.py server_ip_address server_port mode
#### Mode 0 = Unencrypted messages
#### Mode 1 = Encrypted (Uses RSA asymmetric key encryption)
#### Mode 2 = Encrypted with signatures (Hash digests of the message signed by the private key of the sender sent along the message)
MaxClients is the maximum number of hosts that connect to the server.
Ip address and port of the server are the ones we wish the server to bind to.
#### Type your messages as "@ username message"
#### For sending the unregister/quit message type "@ HOST UNREGISTER"
<file_sep>/RL/main.py
import os
import sys
import pygame
import random
from pygame import *
pygame.init()
scr_size = (width,height) = (600,300) # Screen Size
FPS = 60 # Frames Per Second
gravity = 0.6 # Gravity for jumps
black = (0,0,0)
white = (255,255,255)
background_col = (235,235,235) # Colours
high_score = 0 # Initial High Score
screen = pygame.display.set_mode(scr_size) # Init screen
clock = pygame.time.Clock() # Clock
pygame.display.set_caption("T-Rex Rush") # Caption
jump_sound = pygame.mixer.Sound('sprites/jump.wav') # Load Sounds
die_sound = pygame.mixer.Sound('sprites/die.wav')
checkPoint_sound = pygame.mixer.Sound('sprites/checkPoint.wav')
def load_image(name,sizex=-1,sizey=-1,colorkey=None,): # Load Images
fullname = os.path.join('sprites', name)
image = pygame.image.load(fullname)
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
if sizex != -1 or sizey != -1:
image = pygame.transform.scale(image, (sizex, sizey))
return (image, image.get_rect())
def load_sprite_sheet(sheetname,nx,ny,scalex = -1,scaley = -1,colorkey = None,):
fullname = os.path.join('sprites',sheetname)
sheet = pygame.image.load(fullname)
sheet = sheet.convert()
sheet_rect = sheet.get_rect()
sprites = []
sizex = sheet_rect.width/nx
sizey = sheet_rect.height/ny
for i in range(0,ny):
for j in range(0,nx):
rect = pygame.Rect((j*sizex,i*sizey,sizex,sizey))
image = pygame.Surface(rect.size)
image = image.convert()
image.blit(sheet,(0,0),rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey,RLEACCEL)
if scalex != -1 or scaley != -1:
image = pygame.transform.scale(image,(scalex,scaley))
sprites.append(image)
sprite_rect = sprites[0].get_rect()
return sprites,sprite_rect
def disp_gameOver_msg(retbutton_image,gameover_image):
retbutton_rect = retbutton_image.get_rect()
retbutton_rect.centerx = width / 2
retbutton_rect.top = height*0.52
gameover_rect = gameover_image.get_rect()
gameover_rect.centerx = width / 2
gameover_rect.centery = height*0.35
screen.blit(retbutton_image, retbutton_rect)
screen.blit(gameover_image, gameover_rect)
def extractDigits(number):
if number > -1:
digits = []
i = 0
while(number/10 != 0):
digits.append(number%10)
number = int(number/10)
digits.append(number%10)
for i in range(len(digits),5):
digits.append(0)
digits.reverse()
return digits
class Dino():
def __init__(self,sizex=-1,sizey=-1):
self.images,self.rect = load_sprite_sheet('dino.png',5,1,sizex,sizey,-1)
self.images1,self.rect1 = load_sprite_sheet('dino_ducking.png',2,1,59,sizey,-1)
self.rect.bottom = int(0.98*height)
self.rect.left = width/15
self.image = self.images[0]
self.index = 0
self.counter = 0
self.score = 0
self.isJumping = False
self.isDead = False
self.isDucking = False
self.isBlinking = False
self.movement = [0,0] # Distance,Velocity ? Right Velocity,Up Velocity
self.jumpSpeed = 11.5
self.stand_pos_width = self.rect.width
self.duck_pos_width = self.rect1.width
def draw(self):
screen.blit(self.image,self.rect)
def checkbounds(self):
if self.rect.bottom > int(0.98*height): # Check Bounds (Drop the dino)
self.rect.bottom = int(0.98*height)
self.isJumping = False
def update(self): # Updates the game
if self.isJumping:
self.movement[1] = self.movement[1] + gravity # Gravity Timestep
self.index = 0
elif self.isBlinking:
if self.index == 0:
if self.counter % 400 == 399:
self.index = (self.index + 1)%2
else:
if self.counter % 20 == 19:
self.index = (self.index + 1)%2
elif self.isDucking:
if self.counter % 5 == 0:
self.index = (self.index + 1)%2
else:
if self.counter % 5 == 0:
self.index = (self.index + 1)%2 + 2
if self.isDead:
self.index = 4
if not self.isDucking:
self.image = self.images[self.index]
self.rect.width = self.stand_pos_width
else:
self.image = self.images1[(self.index)%2]
self.rect.width = self.duck_pos_width
self.rect = self.rect.move(self.movement)
self.checkbounds()
if not self.isDead and self.counter % 7 == 6 and self.isBlinking == False:
self.score += 1
self.counter = (self.counter + 1)
class Cactus(pygame.sprite.Sprite):
def __init__(self,speed=5,sizex=-1,sizey=-1):
pygame.sprite.Sprite.__init__(self,self.containers)
self.images,self.rect = load_sprite_sheet('cacti-small.png',3,1,sizex,sizey,-1)
self.rect.bottom = int(0.98*height)
self.rect.left = width + self.rect.width
self.image = self.images[random.randrange(0,3)]
self.movement = [-1*speed,0]
def draw(self):
screen.blit(self.image,self.rect)
def update(self):
self.rect = self.rect.move(self.movement)
if self.rect.right < 0:
self.kill()
class Ptera(pygame.sprite.Sprite):
def __init__(self,speed=5,sizex=-1,sizey=-1):
pygame.sprite.Sprite.__init__(self,self.containers)
self.images,self.rect = load_sprite_sheet('ptera.png',2,1,sizex,sizey,-1)
self.ptera_height = [height*0.82,height*0.75,height*0.60]
self.rect.centery = self.ptera_height[random.randrange(0,3)]
self.rect.left = width + self.rect.width
self.image = self.images[0]
self.movement = [-1*speed,0]
self.index = 0
self.counter = 0
def draw(self):
screen.blit(self.image,self.rect)
def update(self):
if self.counter % 10 == 0:
self.index = (self.index+1)%2
self.image = self.images[self.index]
self.rect = self.rect.move(self.movement)
self.counter = (self.counter + 1)
if self.rect.right < 0:
self.kill()
class Scoreboard():
def __init__(self,x=-1,y=-1):
self.score = 0
self.tempimages,self.temprect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
self.image = pygame.Surface((55,int(11*6/5)))
self.rect = self.image.get_rect()
if x == -1:
self.rect.left = width*0.89
else:
self.rect.left = x
if y == -1:
self.rect.top = height*0.1
else:
self.rect.top = y
def draw(self):
screen.blit(self.image,self.rect)
def update(self,score):
score_digits = extractDigits(score)
self.image.fill(background_col)
for s in score_digits:
self.image.blit(self.tempimages[s],self.temprect)
self.temprect.left += self.temprect.width
self.temprect.left = 0
def introscreen():
temp_dino = Dino(44,47)
temp_dino.isBlinking = True
gameStart = False
callout,callout_rect = load_image('call_out.png',196,45,-1)
callout_rect.left = width*0.05
callout_rect.top = height*0.4
logo,logo_rect = load_image('logo.png',240,40,-1)
logo_rect.centerx = width*0.6
logo_rect.centery = height*0.6
while not gameStart:
if pygame.display.get_surface() == None:
print("Couldn't load display surface")
return True
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
temp_dino.isJumping = True
temp_dino.isBlinking = False
temp_dino.movement[1] = -1*temp_dino.jumpSpeed
temp_dino.update()
if pygame.display.get_surface() != None:
screen.fill(background_col)
if temp_dino.isBlinking:
screen.blit(logo,logo_rect)
screen.blit(callout,callout_rect)
temp_dino.draw()
pygame.display.update()
clock.tick(FPS)
if temp_dino.isJumping == False and temp_dino.isBlinking == False:
gameStart = True
def gameplay():
global high_score
gamespeed = 4
startMenu = False
gameOver = False
gameQuit = False
playerDino = Dino(44,47)
scb = Scoreboard()
highsc = Scoreboard(width*0.78)
counter = 0
cacti = pygame.sprite.Group()
pteras = pygame.sprite.Group()
last_obstacle = pygame.sprite.Group()
Cactus.containers = cacti
Ptera.containers = pteras
retbutton_image,retbutton_rect = load_image('replay_button.png',35,31,-1)
gameover_image,gameover_rect = load_image('game_over.png',190,11,-1)
temp_images,temp_rect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
HI_image = pygame.Surface((22,int(11*6/5)))
HI_rect = HI_image.get_rect()
HI_image.fill(background_col)
HI_image.blit(temp_images[10],temp_rect)
temp_rect.left += temp_rect.width
HI_image.blit(temp_images[11],temp_rect)
HI_rect.top = height*0.1
HI_rect.left = width*0.73
while not gameQuit:
while not gameOver:
if pygame.display.get_surface() == None:
print("Couldn't load display surface")
gameQuit = True
gameOver = True
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameQuit = True
gameOver = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if playerDino.rect.bottom == int(0.98*height):
playerDino.isJumping = True
if pygame.mixer.get_init() != None:
jump_sound.play()
playerDino.movement[1] = -1*playerDino.jumpSpeed
if event.key == pygame.K_DOWN:
if playerDino.isJumping and not playerDino.isDead:
playerDino.movement[1]+= 5*gravity
if not (playerDino.isJumping and playerDino.isDead):
playerDino.isDucking = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
playerDino.isDucking = False
for c in cacti:
c.movement[0] = -1*gamespeed
if pygame.sprite.collide_mask(playerDino,c):
playerDino.isDead = True
if pygame.mixer.get_init() != None:
die_sound.play()
for p in pteras:
p.movement[0] = -1*gamespeed
if pygame.sprite.collide_mask(playerDino,p):
playerDino.isDead = True
if pygame.mixer.get_init() != None:
die_sound.play()
if len(cacti) < 2:
if len(cacti) == 0:
last_obstacle.empty()
last_obstacle.add(Cactus(gamespeed,40,40))
else:
for l in last_obstacle:
if l.rect.right < width*0.7 and random.randrange(0,50) == 10:
last_obstacle.empty()
last_obstacle.add(Cactus(gamespeed, 40, 40))
if len(pteras) == 0 and random.randrange(0,200) == 10 and counter > 500:
for l in last_obstacle:
if l.rect.right < width*0.8:
last_obstacle.empty()
last_obstacle.add(Ptera(gamespeed, 46, 40))
playerDino.update()
cacti.update()
pteras.update()
scb.update(playerDino.score)
highsc.update(high_score)
if pygame.display.get_surface() != None:
screen.fill(background_col)
scb.draw()
if high_score != 0:
highsc.draw()
screen.blit(HI_image,HI_rect)
cacti.draw(screen)
pteras.draw(screen)
playerDino.draw()
pygame.display.update()
clock.tick(FPS)
if playerDino.isDead:
gameOver = True
if playerDino.score > high_score:
high_score = playerDino.score
if counter%700 == 699:
gamespeed += 1
counter = (counter + 1)
if gameQuit:
break
while gameOver:
if pygame.display.get_surface() == None:
print("Couldn't load display surface")
gameQuit = True
gameOver = False
else:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameQuit = True
gameOver = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
gameQuit = True
gameOver = False
if event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:
gameOver = False
gameplay()
highsc.update(high_score)
if pygame.display.get_surface() != None:
disp_gameOver_msg(retbutton_image,gameover_image)
if high_score != 0:
highsc.draw()
screen.blit(HI_image,HI_rect)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
def main():
isGameQuit = introscreen()
if not isGameQuit:
gameplay()
main()<file_sep>/RL/gym-dino/gym_dino/envs/dino_env.py
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import pygame
import random
from pygame import *
import gc
import os
import numpy as np
pygame.init()
scr_size = (width,height) = (600,300) # Screen Size
FPS = 60 # Frames Per Second
gravity = 0.6 # Gravity for jumps
black = (0,0,0)
white = (255,255,255)
background_col = (235,235,235) # Colours
maxSpeed = 11.5
high_score = 0 # Initial High Score
screen = pygame.display.set_mode(scr_size) # Init screen
pygame.display.set_caption("T-Rex Rush") # Caption
def load_image(name,sizex=-1,sizey=-1,colorkey=None,): # Load Images
fullname = os.path.join('sprites', name)
image = pygame.image.load(fullname)
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, RLEACCEL)
if sizex != -1 or sizey != -1:
image = pygame.transform.scale(image, (sizex, sizey))
return (image, image.get_rect())
def load_sprite_sheet(sheetname,nx,ny,scalex = -1,scaley = -1,colorkey = None,):
fullname = os.path.join('sprites',sheetname)
sheet = pygame.image.load(fullname)
sheet = sheet.convert()
sheet_rect = sheet.get_rect()
sprites = []
sizex = sheet_rect.width/nx
sizey = sheet_rect.height/ny
for i in range(0,ny):
for j in range(0,nx):
rect = pygame.Rect((j*sizex,i*sizey,sizex,sizey))
image = pygame.Surface(rect.size)
image = image.convert()
image.blit(sheet,(0,0),rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey,RLEACCEL)
if scalex != -1 or scaley != -1:
image = pygame.transform.scale(image,(scalex,scaley))
sprites.append(image)
sprite_rect = sprites[0].get_rect()
return sprites,sprite_rect
def extractDigits(number):
if number > -1:
digits = []
i = 0
while(number/10 != 0):
digits.append(number%10)
number = int(number/10)
digits.append(number%10)
for i in range(len(digits),5):
digits.append(0)
digits.reverse()
return digits
class Dino():
def __init__(self,sizex=-1,sizey=-1):
self.images,self.rect = load_sprite_sheet('dino.png',5,1,sizex,sizey,-1)
self.images1,self.rect1 = load_sprite_sheet('dino_ducking.png',2,1,59,sizey,-1)
self.rect.bottom = int(0.98*height)
self.rect.left = width/15
self.image = self.images[0]
self.index = 0
self.counter = 0
self.score = 0
self.isJumping = False
self.isDead = False
self.isDucking = False
self.isBlinking = False
self.movement = [0,0] # Distance,Velocity ? Right Velocity,Up Velocity
self.jumpSpeed = 11.5
self.stand_pos_width = self.rect.width
self.duck_pos_width = self.rect1.width
def draw(self):
screen.blit(self.image,self.rect)
def checkbounds(self):
if self.rect.bottom > int(0.98*height): # Check Bounds (Drop the dino)
self.rect.bottom = int(0.98*height)
self.isJumping = False
self.movement[1] = 0
def update(self): # Updates the game
if self.isJumping:
self.movement[1] = self.movement[1] + gravity # Gravity Timestep
self.index = 0
elif self.isBlinking:
if self.index == 0:
if self.counter % 400 == 399:
self.index = (self.index + 1)%2
else:
if self.counter % 20 == 19:
self.index = (self.index + 1)%2
elif self.isDucking:
if self.counter % 5 == 0:
self.index = (self.index + 1)%2
else:
if self.counter % 5 == 0:
self.index = (self.index + 1)%2 + 2
if self.isDead:
self.index = 4
if not self.isDucking:
self.image = self.images[self.index]
self.rect.width = self.stand_pos_width
else:
self.image = self.images1[(self.index)%2]
self.rect.width = self.duck_pos_width
self.rect = self.rect.move(self.movement)
self.checkbounds()
if not self.isDead and self.counter % 7 == 6 and self.isBlinking == False:
self.score += 1
self.counter = (self.counter + 1)
def reset(self):
self.rect.bottom = int(0.98*height)
self.rect.left = width/15
self.image = self.images[0]
self.index = 0
self.counter = 0
self.score = 0
self.isJumping = False
self.isDead = False
self.isDucking = False
self.isBlinking = False
self.movement = [0,0] # Distance,Velocity ? Right Velocity,Up Velocity
self.jumpSpeed = maxSpeed
self.stand_pos_width = self.rect.width
self.duck_pos_width = self.rect1.width
class Cactus(pygame.sprite.Sprite):
def __init__(self,speed=5,sizex=-1,sizey=-1):
pygame.sprite.Sprite.__init__(self,self.containers)
self.images,self.rect = load_sprite_sheet('cacti-small.png',3,1,sizex,sizey,-1)
self.rect.bottom = int(0.98*height)
self.rect.left = width + self.rect.width
self.image = self.images[random.randrange(0,3)]
self.movement = [-1*speed,0]
def draw(self):
screen.blit(self.image,self.rect)
def update(self):
self.rect = self.rect.move(self.movement)
if self.rect.right < 0:
self.kill()
class Ptera(pygame.sprite.Sprite):
def __init__(self,speed=5,sizex=-1,sizey=-1):
pygame.sprite.Sprite.__init__(self,self.containers)
self.images,self.rect = load_sprite_sheet('ptera.png',2,1,sizex,sizey,-1)
self.ptera_height = [height*0.82,height*0.75,height*0.60]
self.rect.centery = self.ptera_height[random.randrange(0,3)]
self.rect.left = width + self.rect.width
self.image = self.images[0]
self.movement = [-1*speed,0]
self.index = 0
self.counter = 0
def draw(self):
screen.blit(self.image,self.rect)
def update(self):
if self.counter % 10 == 0:
self.index = (self.index+1)%2
self.image = self.images[self.index]
self.rect = self.rect.move(self.movement)
self.counter = (self.counter + 1)
if self.rect.right < 0:
self.kill()
class Scoreboard():
def __init__(self,x=-1,y=-1):
self.score = 0
self.tempimages,self.temprect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
self.image = pygame.Surface((55,int(11*6/5)))
self.rect = self.image.get_rect()
if x == -1:
self.rect.left = width*0.89
else:
self.rect.left = x
if y == -1:
self.rect.top = height*0.1
else:
self.rect.top = y
def draw(self):
screen.blit(self.image,self.rect)
def update(self,score):
score_digits = extractDigits(score)
self.image.fill(background_col)
for s in score_digits:
self.image.blit(self.tempimages[s],self.temprect)
self.temprect.left += self.temprect.width
self.temprect.left = 0
scb = Scoreboard()
highsc = Scoreboard(width*0.78)
temp_images,temp_rect = load_sprite_sheet('numbers.png',12,1,11,int(11*6/5),-1)
HI_image = pygame.Surface((22,int(11*6/5)))
HI_rect = HI_image.get_rect()
HI_image.fill(background_col)
HI_image.blit(temp_images[10],temp_rect)
temp_rect.left += temp_rect.width
HI_image.blit(temp_images[11],temp_rect)
HI_rect.top = height*0.1
HI_rect.left = width*0.73
class DinoEnv(gym.Env):
metadata = {'render.modes': ['human']}
def __init__(self):
super(DinoEnv,self).__init__()
self.gamespeed = 4
self.playerDino = Dino(44,47)
self.counter = 0
self.cacti = pygame.sprite.Group()
self.pteras = pygame.sprite.Group()
self.last_obstacle = pygame.sprite.Group()
Cactus.containers = self.cacti
Ptera.containers = self.pteras
self.action_space = spaces.Discrete(3) # Nothing,Jump And Down
self.observation_space = spaces.Box(low=-width,high=width,shape=(7,)) # GameSpeed, UpSpeed, Height and Distance to next obstacle
self.gameOver = False
self.passed = False
def step(self, action,algo):
global high_score
if action == 0:
self.playerDino.isDucking = False
if action == 1: # Jump
if self.playerDino.rect.bottom == int(0.98*height):
self.playerDino.isJumping = True
self.playerDino.isDucking = False
self.playerDino.movement[1] = -1*self.playerDino.jumpSpeed
if action == 2: # Duck
if self.playerDino.isJumping and not self.playerDino.isDead:
self.playerDino.movement[1]+= 2*gravity
self.playerDino.isDucking = True
if not (self.playerDino.isJumping and self.playerDino.isDead):
self.playerDino.isDucking = True
for c in self.cacti:
c.movement[0] = -1*self.gamespeed
if pygame.sprite.collide_mask(self.playerDino,c):
self.playerDino.isDead = True
for p in self.pteras:
p.movement[0] = -1*self.gamespeed
if pygame.sprite.collide_mask(self.playerDino,p):
self.playerDino.isDead = True
if len(self.cacti) < 2:
if len(self.cacti) == 0:
self.last_obstacle.empty()
self.last_obstacle.add(Cactus(self.gamespeed,40,40))
else:
for l in self.last_obstacle:
if l.rect.right < width*0.7 and random.randrange(0,50) == 10:
self.last_obstacle.empty()
self.last_obstacle.add(Cactus(self.gamespeed, 40, 40))
if len(self.pteras) == 0 and random.randrange(0,50) == 10 and 1 == 0:
for l in self.last_obstacle:
if l.rect.right < width*0.8:
self.last_obstacle.empty()
self.last_obstacle.add(Ptera(self.gamespeed, 46, 40))
self.playerDino.update()
self.cacti.update()
self.pteras.update()
for c in self.cacti:
if c.rect.right <= self.playerDino.rect.left:
self.passed = True
self.cacti.remove(c)
break
for p in self.pteras:
if p.rect.right <= self.playerDino.rect.left:
self.passed = True
self.pteras.remove(p)
break
scb.update(self.playerDino.score)
highsc.update(high_score)
if self.counter%700 == 699:
self.gamespeed += 1
self.counter = self.counter+1
obs,reward = self.getObservations()
if self.playerDino.isDead == 1:
self.gameOver = True
if self.playerDino.score > high_score:
high_score = self.playerDino.score
if algo == 1:
if self.playerDino.isDead == True:
reward = -10
else:
reward = 0.1
if self.passed == True:
reward+=10
self.passed = False
return obs,reward,self.playerDino.isDead,{}
def render(self, mode='human', close=False):
if pygame.display.get_surface() != None:
screen.fill(background_col)
scb.draw()
if high_score != 0:
highsc.draw()
screen.blit(HI_image,HI_rect)
self.cacti.draw(screen)
self.pteras.draw(screen)
self.playerDino.draw()
pygame.display.update()
def reset(self):
highsc.update(high_score)
self.playerDino.reset()
del self.cacti
del self.pteras
del self.last_obstacle
self.cacti = pygame.sprite.Group()
self.pteras = pygame.sprite.Group()
self.last_obstacle = pygame.sprite.Group()
Cactus.containers = self.cacti
Ptera.containers = self.pteras
self.gameOver = False
self.counter = 0
def getObservations(self): #RightSpeed,UpSpeed,Top,Bottom,Obstacle Top,Obstacle Bottom,Obstacle Left,Obstacle Right,Collision Distance
obs = [0,0,0,0,-1,-1,-1,-1,2]
obs[0] = self.gamespeed
obs[1] = -1*round(self.playerDino.movement[1]/maxSpeed,3)
obs[2] = round(1-self.playerDino.rect.top/height,3)
obs[3] = round(1-self.playerDino.rect.bottom/height,3)
temp = 0
for c in self.cacti:
distance = self._calculateDistance(self.playerDino.rect,c.rect)
if distance < obs[8]:
temp = c.rect
obs[8] = round(distance,3)
for p in self.pteras:
distance = self._calculateDistance(self.playerDino.rect,p.rect)
if distance < obs[8]:
temp = p.rect
obs[8] = round(distance,3)
if type(temp) == int:
return obs,0
obs[4] = round(1-temp.top/height,3)
obs[5] = round(1-temp.bottom/height,3)
obs[6] = round(temp.left/width,3)
obs[7] = round(temp.right/width,3)
if obs[8] > 0.15:
reward = 0
else:
reward = 5*(obs[8]-0.15)
return obs,reward
def _calculateDistance(self,dino,obstacle):
y_distance = int(dino.bottom<obstacle.top)*np.power((dino.bottom-obstacle.top)/height,2)+int(obstacle.bottom<dino.top)*np.power((dino.top-obstacle.bottom)/height,2)
y_distance+=(y_distance==0)*np.power((dino.bottom+dino.top-(obstacle.top+obstacle.bottom))/(2*height),2)
x_distance = int(dino.left>obstacle.right)*np.power((dino.left-obstacle.right)/width,2)+int(obstacle.left>dino.right)*np.power((dino.right-obstacle.left)/width,2)
x_distance+=(x_distance==0)*np.power((dino.left+dino.right-(obstacle.left+obstacle.right))/(2*width),2)
return np.sqrt(x_distance+y_distance)
def close(self):
pygame.quit()<file_sep>/Databases/README.md
## Assignments for the course Databases
<file_sep>/RL/try.py
import gym
import gym_dino
import time
import torch.nn as nn
import torch.optim as optim
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import gc
episodes = 1000
gamma = 0.9
epsilon = 0.6
batch_size = 50
training_epochs = 10
rewards = []
def discountRewards():
global rewards
for i in range(len(rewards)-2,-1,-1):
rewards[i] = rewards[i] + gamma*rewards[i+1]
if net.rewards.dim() != 0:
net.rewards = torch.cat((net.rewards,torch.Tensor(rewards)))
else:
net.actions = (torch.Tensor(rewards))
rewards[:] = []
return
class Actor(nn.Module):
def __init__(self):
super(Actor,self).__init__()
self.fc1 = nn.Linear(in_features=9,out_features=8)
self.fc2 = nn.Linear(in_features=8,out_features=6)
self.fc3 = nn.Linear(in_features=6,out_features=3)
self.policy_history = torch.Tensor()
self.rewards = torch.Tensor()
def forward(self, x):
x = self.fc3(F.relu(self.fc2(F.relu(self.fc1(x)))))
x = F.softmax(x, dim=-1)
return x
def policy(self,observation):
prob = self.forward(torch.Tensor(observation))
dist = prob.detach().numpy()
action = np.random.choice(a=3,p=dist)
return action
def updateTarget(self,observation):
prob = self.forward(torch.Tensor(observation))
log_prob = torch.log(prob[action])
if self.policy_history.dim() != 0:
self.policy_history = torch.cat((self.policy_history,log_prob.view(-1)))
else:
self.policy_history = (log_prob)
class QEstimator(nn.Module):
def __init__(self):
super(QEstimator,self).__init__()
self.fc1 = nn.Linear(in_features=12,out_features=8)
self.fc2 = nn.Linear(in_features=8,out_features=5)
self.fc3 = nn.Linear(in_features=5,out_features=1)
self.prev_states = torch.Tensor()
self.next_states = torch.Tensor()
self.rewards = torch.Tensor()
self.actions = torch.Tensor()
def forward(self,x,action):
x = torch.cat((x,torch.eq(action,0).float().view(-1,1),torch.eq(action,1).float().view(-1,1),torch.eq(action,2).float().view(-1,1)),1)
x = self.fc3(F.relu(self.fc2(F.relu(self.fc1(x)))))
return x
def epsilonRandomPolicy(self,observation):
if np.random.sample() < epsilon:
action = np.random.choice(a=3)
return action
else:
maxQ = self.forward(torch.Tensor(observation).view(1,-1),torch.Tensor([0]).view(-1))
choice = 0
for action in range(1,3):
Q_hat = self.forward(torch.Tensor(observation).view(1,-1),torch.Tensor([action]).view(-1))
if torch.gt(Q_hat,maxQ):
maxQ = Q_hat
choice = action
return choice
def updateTarget(self,reward,prev_observation,next_observation,action):
if self.prev_states.dim() != 0:
self.prev_states = torch.cat((self.prev_states,torch.Tensor([prev_observation])),0)
else:
self.predictedQValues = (torch.Tensor([prev_observation]))
if self.next_states.dim() != 0:
self.next_states = torch.cat((self.next_states,torch.Tensor([next_observation])),0)
else:
self.next_states = (torch.Tensor([next_observation]))
if self.rewards.dim() != 0:
self.rewards = torch.cat([self.rewards,torch.Tensor([reward])])
else:
self.next_states = (torch.Tensor(reward))
if self.actions.dim() != 0:
self.actions = torch.cat((self.actions,torch.Tensor([action])))
else:
self.actions = (torch.Tensor([action]))
return
net = Actor()
optimizer = optim.Adam(net.parameters(),lr=0.01)
#loss = nn.MSELoss(reduction='sum')
def updateQEstimator():
p = np.random.permutation(len(net.prev_states))
net.prev_states = net.prev_states[p]
net.next_states = net.next_states[p]
net.actions = net.actions[p]
net.rewards = net.rewards[p]
batches = int(net.next_states.shape[0]/batch_size)
for epoch in range(training_epochs):
for batch in range(batches):
predictedQ = net.forward(net.prev_states[batch*batch_size:(batch+1)*batch_size],net.actions[batch*batch_size:(batch+1)*batch_size])
actualQ = []
for action in range(3):
actualQ.append(net.forward(net.next_states[batch*batch_size:(batch+1)*batch_size],torch.mul(action,torch.ones(batch_size))))
maxQ = torch.max(actualQ[0],actualQ[1])
maxQ = torch.max(actualQ[2],maxQ)
maxQ = torch.add(torch.mul(gamma,maxQ),net.rewards[batch*batch_size:(batch+1)*batch_size].view(-1,1))
optimizer.zero_grad()
curr_loss = loss(maxQ,predictedQ)
curr_loss.backward()
optimizer.step()
net.prev_states = Variable(torch.Tensor())
net.next_states = Variable(torch.Tensor())
net.rewards = Variable(torch.Tensor())
net.actions = Variable(torch.Tensor())
return
def updateActor():
#print(net.rewards)
net.rewards = (net.rewards - net.rewards.mean()) / (net.rewards.std() + 1e-9)
policy_gradient = torch.sum(torch.mul(net.policy_history.view(-1),net.rewards).mul(-1),-1)
loss = torch.sum(torch.mul(torch.exp(net.policy_history.view(-1)),net.rewards),-1)
optimizer.zero_grad()
policy_gradient.backward()
optimizer.step()
net.policy_history = torch.Tensor()
net.rewards = torch.Tensor()
def annealParameters(episode):
global epsilon
epsilon = 0.6-episode/800
if epsilon < 0:
epsilon = 0
env = gym.make('Dino-v0')
''' Q-Estimator
for i_episode in range(episodes):
env.reset()
env.render()
observation,_ = env.getObservations()
t = 0
action = 0
curr_reward = 0
Q_hat = 0
prev_observation = observation
while 1:
if t%4 == 0: #Every 5 steps
prev_observation = observation
curr_reward = 0
action = net.epsilonRandomPolicy(observation)
observation, reward, done, info = env.step(action,1)
curr_reward+=reward
env.render()
time.sleep(0.01)
if t%4 == 3: #After a cycle
net.updateTarget(curr_reward,prev_observation,observation,action)
if done == True:
env.reset()
print("Episode Length",t)
break
t+=1
if i_episode%5 == 4:
annealParameters(i_episode)
updateQEstimator()
gc.collect()
print(i_episode,epsilon)
env.close()
'''
for i_episode in range(episodes):
env.reset()
env.render()
observation,_ = env.getObservations()
t = 0
action = 0
curr_reward = 0
Q_hat = 0
prev_observation = observation
while 1:
if t%4 == 0: #Every 4 steps
prev_observation = observation
curr_reward = 0
action = net.policy(observation)
observation, reward, done, info = env.step(action,1)
curr_reward+=reward
#env.render()
#time.sleep(0.01)
if t%4 == 3: #After a cycle
net.updateTarget(prev_observation)
rewards.append(curr_reward)
if done == True:
if t%4 !=3:
net.updateTarget(prev_observation)
rewards.append(curr_reward)
env.reset()
print("Episode Length",t)
break
t+=1
discountRewards()
if i_episode%2 == 0:
#annealParameters(i_episode)
updateActor()
gc.collect()
print(i_episode)
env.close()
<file_sep>/README.md
# miscellaneous-projects
A collection of small programming projects/assignments
<file_sep>/RL/gym-dino/gym_dino/__init__.py
from gym.envs.registration import register
register(id='Dino-v0',entry_point='gym_dino.envs:DinoEnv',) | 9f0aea4ee3f6516dbc7112fc20c4498196c5721a | [
"Markdown",
"Python"
] | 14 | Python | gobind452/Miscellaneous-Projects | d9035fcc5951537ddf2fe065438ff5eb74e1a4dc | 1286d7d6dcb822eb0ca9f40ac284caa0f273dd3d |
refs/heads/main | <file_sep>package br.com.fiap.convidados.dto;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ConvidadosDtoTests {
@Test
public void deveTestarGetSetConvidados() {
//Cenario
ConvidadosDto dto = new ConvidadosDto();
ConvidadosDto dto1 = new ConvidadosDto();
ConvidadosDto dto2 = null;
//Acao
dto.setNome("Teste");
dto.setId(1L);
dto.setEmail("<EMAIL>");
dto.setAcompanhante("02");
dto1.setNome("Teste");
dto1.setId(1L);
dto1.setEmail("<EMAIL>");
dto1.setAcompanhante("02");
//Validacao
assertTrue("02".equals(dto.getAcompanhante()));
assertFalse("01".equals(dto.getAcompanhante()));
assertEquals("02",dto.getAcompanhante());
assertEquals("02",dto.getAcompanhante());
assertEquals(dto,dto1);
assertSame(dto,dto);
assertNotSame(dto,dto1);
assertNull(dto2);
assertNotNull(dto);
}
}
<file_sep>package br.com.fiap.convidados.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.fiap.convidados.dto.EventoDto;
import br.com.fiap.convidados.entity.EventoEntity;
import br.com.fiap.convidados.repository.EventoRepository;
import br.com.fiap.convidados.service.EventoService;
@Service
public class EventoServiceImpl implements EventoService{
@Autowired
EventoRepository repository;
@Override
public List<EventoDto> listaEvento() {
List<EventoEntity> eventosEntity = repository.findAll();
List<EventoDto> eventos = fromToEventoDto(eventosEntity);
return eventos;
}
private List<EventoDto> fromToEventoDto(List<EventoEntity> eventosEntity) {
List<EventoDto> lista = new ArrayList<>();
for(EventoEntity entity :eventosEntity) {
ModelMapper mapper = new ModelMapper();
EventoDto dto = mapper.map(entity, EventoDto.class);
lista.add(dto);
}
return lista;
}
}
<file_sep>insert into tb_evento(id_evento,descricao)values(1,'evento 1');
insert into tb_evento(id_evento,descricao)values(2,'evento 2');
insert into tb_evento(id_evento,descricao)values(3,'evento 3');<file_sep>package br.com.fiap.convidados.service;
import java.util.List;
import br.com.fiap.convidados.dto.EventoDto;
public interface EventoService {
List<EventoDto> listaEvento();
}
| b61a79799c53c6d98287e38d5a28140e3808990a | [
"Java",
"SQL"
] | 4 | Java | proffrancisco/convidados | 92bf5861ba18cb140822c52b902cfa6c779b3b1a | 2a6d33e9095059c18c8fb4d5c5b769f5cbb68423 |
refs/heads/master | <repo_name>saturnisbig/zarkpy<file_sep>/web/cgi/pagecontroller/Index.py
#coding=utf-8
import site_helper as sh
# ../page/Index.html
class Index:
def GET(self):
return sh.page.Index(sh.storage(locals()))
<file_sep>/web/cgi/pagecontroller/user/Portrait.py
#coding=utf-8
import os
import site_helper as sh
''' 上传与裁剪头像 '''
# ../../page/user/Portrait.html
class Portrait:
def GET(self):
if not sh.session.is_login:
return sh.redirectToLogin(sh.getEnv('REQUEST_URI'))
user = sh.model('User').get(sh.session.id)
return sh.page.user.Portrait(user)
def POST(self):
if not sh.session.is_login:
return sh.redirectToLogin()
image_model = sh.model('Image')
user_model = sh.model('User')
user = user_model.get(sh.session.id)
inputs = sh.inputs()
assert inputs.get('action', '')
if inputs.action == 'upload':
if user.image:
path = sh.urlToPath(user.image.url)
os.system('rm %s' % (path+'.crop'))
user_model.update(sh.session.id, {image_model.image_key: inputs.image_file})
return sh.redirect('/accounts/portrait')
elif inputs.action == 'crop':
if not user.image:
return sh.alert('请先上传头像')
assert int(float(inputs.get('region_width', '0'))) > 0
assert int(float(inputs.get('region_height', '0'))) > 0
real_width, real_height = sh.imageSize(user.image.url) # 图片的真实宽高
crop = inputs.crop
region_width = int(float(inputs.region_width)) # 选择区域的宽度
region_height = int(float(inputs.region_height)) # 选择区域的高度
start_x = int(crop.split()[0]) # 选中的起始位置
start_y = int(crop.split()[1])
region_x = int(crop.split()[2])# 选中的宽度
region_y = int(crop.split()[3]) # 选中的高度
# convert 裁剪区域
region = '%dx%d+%d+%d' % (region_x * real_width / region_width,
region_y * real_height / region_height,
real_width * start_x / region_width,
real_height * start_y / region_height)
path = sh.urlToPath(user.image.url)
os.system('convert %s -crop %s %s' % (path, region, path+'.crop'))
user_model.update(sh.session.id, {'crop': crop})
return sh.redirect('/accounts')
<file_sep>/web/js/editor/SWFUpload.js
var swfu;
$(function(){
swfu = new SWFUpload({
upload_url: "/post/userimage",
flash_url : "/plugins/swfupload/swfupload.swf",
post_params: {
"userid": 0
},
file_size_limit : "2 MB",
file_types : "*.jpg;*.jpeg;*.gif;*.png;",
file_types_description : "JPG/JPEG/GIF/PNG Images",
file_upload_limit : "10",
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
button_image_url : "/plugins/swfupload/images/XPButtonText_100x22.png",
button_placeholder_id : "swfupload_openselectfiles_btn",
button_width: 100,
button_height: 22,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
custom_settings : { upload_target : "swfupload_progress_container" },
debug: false
});
});
<file_sep>/web/cgi/api/UserImage.py
#coding=utf-8
# ../subpage/ChooseImage.html
import site_helper as sh
import imghdr
class UserImage:
def GET(self, inputs=None):
if not inputs: inputs = sh.inputs()
assert inputs.has_key('action')
model = sh.model('UserImage')
# assert
if inputs.action not in ['getChooseImageHtml']:
assert sh.session.is_login
assert inputs.get('UserImageid', None)
exists = model.get(inputs.UserImageid)
assert exists and exists.Userid == sh.session.id
if inputs.action == 'getChooseImageHtml':
assert sh.session.is_login
env = dict(paging=False, where=['deleted=%s','no'])
images = model.all(env)
#paging = model.getPaginationHtml(env)
paging = ''
html = str(sh.subpage.ChooseImage(images, paging))
return sh.toJsonp({'success': True, 'html': html, 'Userid': sh.session.id})
elif inputs.action == 'delete':
model.update(inputs.UserImageid, {'deleted': 'yes'})
return sh.toJsonp({'success': True})
elif inputs.action == 'realDelete':
model.delete(inputs.UserImageid)
return sh.toJsonp({'success': True})
elif inputs.action == 'recover':
model.update(inputs.UserImageid, {'deleted': 'no'})
return sh.toJsonp({'success': True})
def POST(self, inputs=None):
if not inputs: inputs = sh.inputs()
assert inputs.has_key('action')
if inputs.action == 'postImage':
assert inputs.get('Userid', 0)
assert sh.model('User').get(inputs.Userid)
img_model = sh.model('UserImage')
image_type = imghdr.what(None, inputs['Filedata'])
file_name = inputs['Filename'].partition('.')[0]
if '.' in file_name:
file_name = file_name.partition('.')[2]
assert image_type in img_model.known_types
image_data = sh.storage({'filename':file_name,
'value':inputs['Filedata'], 'imagetype': image_type})
new_id = img_model.insert(sh.storage(dict(image_file=image_data,
Userid=inputs.Userid, file_name=file_name)))
return 'success;%d;%s;%s' % (new_id,
img_model.getUrlByPrivate(inputs.Userid, new_id), file_name)
| d090939853407592c04a8d38922e2b96d5ec3390 | [
"JavaScript",
"Python"
] | 4 | Python | saturnisbig/zarkpy | 6cd1aadbd07e9c63646233a57455fdbf200bcd1d | 8957481ef6f0aab11df6ac16d18f4690b3681f05 |
refs/heads/master | <file_sep># Testrail-Test-Cases-Suite-Sort
Automation script that can sort/change/delete specific criteria tests on TestRail platform
<file_sep>#TEST CASE SORT AUTOMATION
#Neon
import testrail
import subprocess
import ssl
import argparse
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
#Credentials to access y Testrail
tr_client = testrail.APIClient('')
tr_client.user = ''
tr_client.password = ''
parser = argparse.ArgumentParser()
parser.add_argument("-a","--add", help="add any test cases in the General Regression test run or test plan from a MILESTONE into the Partial Regression suite", type = int, metavar='')
parser.add_argument("-c", "--check", help= "Display info about a test PLAN", type= int , metavar='')
parser.add_argument("--remove", help= "Remove ALL test cases in x from Partial regression as well as setting non-automation-status test cases to ToBeAutomated",action="store_true")
args = parser.parse_args()
if args.add:
Milestone = args.add
milestone_runs = tr_client.send_get('get_runs/1&milestone_id=%s'%Milestone)
plans = tr_client.send_get('get_plans/1&milestone_id=%s'%Milestone) #Milestone ID is here
for plan in plans :
if "General Regression" in plan['name']:
plan_id = plan['id']
runs = tr_client.send_get('get_plan/%s'%plan_id)
for run in runs['entries']:
run_id = run['runs'][0]['id'] #second value is always 0
run_tests = tr_client.send_get('get_tests/%s'%run_id)
#loop here with the number of test in the Run
for run_test in run_tests:
test_case_id = run_test['case_id']
case_info = tr_client.send_get('get_case/%s'%test_case_id)
#If statement, if custom_testsuite existed, check if it has 3 which is partial regression, if it has 3 ignore, if it doesn't add 3.
#if it doesn't have custom_testsuite, add custom_testsuite with value as 3
initial_case_info_add_partial = case_info
add_custompartial= case_info
if 'custom_testsuite' in case_info:
if 3 in case_info['custom_testsuite']:
print "Test %s is already in Partial Regression Suite"%test_case_id
pass
elif 3 not in case_info['custom_testsuite']:
print "Test %s is not in Partial Regression Suite and has been added" %test_case_id
initial_case_info_add_partial['custom_testsuite'].append(3)
tr_client.send_post('update_case/%s'%test_case_id,initial_case_info_add_partial)
else:
add_custompartial['custom_testsuite'] = [3]
tr_client.send_post('update_case/%s'%test_case_id,add_custompartial)
print "Test %s is not in Partial Regression Suite and has been added"%test_case_id
else:
print "This plan is not General"
for milestone_run in milestone_runs:
if "General Regression" in milestone_run['name']:
milestone_run_id = milestone_run['id'] #Getting the Run ID
milestone_run_tests = tr_client.send_get('get_tests/%s'%milestone_run_id) #Return LIST of info of all Test
for milestone_run_test in milestone_run_tests:
run_case_id = milestone_run_test['case_id']
case_info = tr_client.send_get('get_case/%s'%run_case_id)
#If statement, if custom_testsuite existed, check if it has 3 which is partial regression, if it has 3 ignore, if it doesn't add 3.
#if it doesn't have custom_testsuite, add custom_testsuite with value as 3
initial_case_info_add_partial = case_info
add_custompartial= case_info
if 'custom_testsuite' in case_info:
if 3 in case_info['custom_testsuite']:
print "Test %s is already in Partial Regression Suite" %run_case_id
pass
elif 3 not in case_info['custom_testsuite']:
print "Test %s is not in Partial Regression Suite and has been added" %run_case_id
initial_case_info_add_partial['custom_testsuite'].append(3)
tr_client.send_post('update_case/%s'%run_case_id,initial_case_info_add_partial)
else:
add_custompartial['custom_testsuite'] = [3]
tr_client.send_post('update_case/%s'%run_case_id,add_custompartial)
print "Test %s is not in Partial Regression Suite and has been added" %run_case_id
else:
print " No General Regression Run detected"
if args.check:
plan_number = args.check #Change this to arg.x
planget = tr_client.send_get('get_plan/%s'%plan_number)
runs = planget['entries']
n=0
test_case_list = []
for run in runs:
tests = tr_client.send_get('get_tests/%s' %run['runs'][0]['id'])
Id = run['runs'][0]['id']
testgets = tr_client.send_get('get_tests/%s'%Id)
for testget in testgets:
test_case_list.append(testget['case_id'])
test_case_list.sort()
Sortedlist = sorted(set(test_case_list))
print test_case_list
print "The number of test runs in this test plan is: ", len(test_case_list)
print "The number of unique test cases in this test plan is: ", len(Sortedlist)
if args.remove:
all_test_cases = tr_client.send_get('get_cases/1')
for all_test_case in all_test_cases:
if 'custom_testsuite' in all_test_case:
if 3 in all_test_case['custom_testsuite']:
all_test_case_delete_partial = all_test_case
if all_test_case_delete_partial['custom_case_automation_status'] == None:
all_test_case_delete_partial['custom_case_automation_status'] = 2
print "%s set to To Be Automated" %all_test_case_delete_partial['id']
else:
pass
all_test_case_delete_partial['custom_testsuite'].remove(3)
tr_client.send_post('update_case/%s'%all_test_case_delete_partial['id'], all_test_case_delete_partial)
print "%s is not in Partial Regression Anymore" %all_test_case_delete_partial['id']
else:
print "%s is in another test suite or not in any test suite at all" %all_test_case['id']
else:
all_test_case_add_automationstatus = all_test_case
if all_test_case_add_automationstatus['custom_case_automation_status'] == None:
all_test_case_add_automationstatus['custom_case_automation_status'] = 2
print "%s set to To Be Automated" %all_test_case_add_automationstatus['id']
tr_client.send_post('update_case/%s'%all_test_case_add_automationstatus['id'], all_test_case_add_automationstatus)
else:
pass
| 16229456ae0a133fa51751a382c32ffacb385e67 | [
"Markdown",
"Python"
] | 2 | Markdown | NeonLe96/Testrail-Test-Cases-Suite-Sort | b67ce4810205db5f79c17df421c20380a605af6d | 0106bcb76fab2032b5f9dcbdb7619142b8d67e91 |
refs/heads/master | <repo_name>Amar1297/Vehical_Rental_Application<file_sep>/app/src/main/java/com/example/profile/Modules/Login.java
package com.example.profile.Modules;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.profile.Activities.HomeNavigate;
import com.example.profile.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Login extends AppCompatActivity {
EditText email, pass;
Button login;
ProgressBar progressBar;
FirebaseAuth firebaseAuth;
@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
int content=getResources().getConfiguration().orientation;
if(content== Configuration.ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
email = findViewById(R.id.loginEmail);
pass = findViewById(R.id.loginpass);
login = findViewById(R.id.loginButton);
progressBar = findViewById(R.id.progressBar);
firebaseAuth = FirebaseAuth.getInstance();
progressBar.setVisibility(View.INVISIBLE);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SignIn();
}
});
}
private void SignIn() {
try {
login.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
final String Email = email.getText().toString().trim();
final String Pass = pass.getText().toString().trim();
if (Email.isEmpty() || Pass.isEmpty()) {
ShowMessage("Empty Fields");
progressBar.setVisibility(View.INVISIBLE);
login.setVisibility(View.VISIBLE);
} else {
SignInAccount(Email, Pass);
}
}catch (Exception e){
ShowMessage(e.toString());
}
}
private void SignInAccount(String email, String pass) {
try {
firebaseAuth.signInWithEmailAndPassword(email, pass)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressBar.setVisibility(View.VISIBLE);
login.setVisibility(View.INVISIBLE);
UpdateUI();
} else {
String str = task.getException().getMessage();
ShowMessage(str);
progressBar.setVisibility(View.INVISIBLE);
login.setVisibility(View.VISIBLE);
}
}
});
}catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void UpdateUI() {
ShowMessage("Please Wait Account is Loading...");
Intent intent=new Intent(getApplicationContext(), HomeNavigate.class);
startActivity(intent);
finish();
}
private void ShowMessage(String massage) {
Toast.makeText(this, massage, Toast.LENGTH_SHORT).show();
}
@Override
protected void onStart() {
super.onStart();
try {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Intent intent = new Intent(getApplicationContext(), HomeNavigate.class);
startActivity(intent);
finish();
}
}catch (Exception e){
ShowMessage(e.toString());
}
}
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
finish();
}
}
<file_sep>/app/src/main/java/com/example/profile/Activities/ui/car/CarFragment.java
package com.example.profile.Activities.ui.car;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.profile.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
import com.mongodb.stitch.android.core.auth.StitchUser;
import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoClient;
import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoCollection;
import com.mongodb.stitch.core.auth.providers.anonymous.AnonymousCredential;
import com.mongodb.stitch.core.services.mongodb.remote.RemoteInsertOneResult;
import org.bson.Document;
import java.io.ByteArrayOutputStream;
import static android.app.Activity.RESULT_OK;
public class CarFragment extends Fragment {
private StitchAppClient stitchAppClient=null;
FirebaseAuth firebaseAuth;
FirebaseUser user;
String mail,mobile;
private ImageView carimg;
private String imageString;
private Uri imageuri;
Intent CropIntent;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.car_fragment, container, false);
carimg=root.findViewById(R.id.carimg);
final EditText carname=root.findViewById(R.id.carname);
final EditText carnumber=root.findViewById(R.id.carnumber);
final EditText carmodel=root.findViewById(R.id.carmodel);
final EditText caryear=root.findViewById(R.id.caryear);
final EditText carinsu=root.findViewById(R.id.carInsurance);
final Button carsubmit=root.findViewById(R.id.carsubmit);
final ProgressBar progressBar=root.findViewById(R.id.carprogress);
try {
progressBar.setVisibility(View.INVISIBLE);
try {
//this.stitchAppClient= Stitch.initializeAppClient("mongodemo-gopcv");
this.stitchAppClient = Stitch.getAppClient("mongodemo-gopcv");
stitchAppClient.getAuth().loginWithCredential(new AnonymousCredential()).addOnCompleteListener(new OnCompleteListener<StitchUser>() {
@Override
public void onComplete(@NonNull Task<StitchUser> task) {
// Toast.makeText(getContext(), task.getResult().toString(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
GetNameAndNumber();
carimg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, 2);
}
});
carsubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
carsubmit.setVisibility(View.INVISIBLE);
try {
Bitmap bitmap = ((BitmapDrawable) carimg.getDrawable()).getBitmap();
ByteArrayOutputStream bios = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bios);
byte[] img = bios.toByteArray();
imageString = Base64.encodeToString(img, Base64.DEFAULT);
}catch (Exception e){
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
final String name = carname.getText().toString();
final String number = carnumber.getText().toString();
final String model = carmodel.getText().toString();
final String year = caryear.getText().toString();
final String insu = carinsu.getText().toString();
try {
if (name.isEmpty() || number.isEmpty() || model.isEmpty() || year.isEmpty() || insu.isEmpty() || imageuri == null) {
if (imageuri == null) {
Toast.makeText(v.getContext(), "Select pic", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
carsubmit.setVisibility(View.VISIBLE);
} else {
Toast.makeText(v.getContext(), "Please Enter All Fileds...", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
carsubmit.setVisibility(View.VISIBLE);
}
} else {
Add(name,number,model,year,insu,imageString,mail,mobile);
progressBar.setVisibility(View.INVISIBLE);
carsubmit.setVisibility(View.VISIBLE);
carname.setText("");
carnumber.setText("");
carmodel.setText("");
caryear.setText("");
carinsu.setText("");
carimg.setBackground(null);
}
}catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}catch (Exception e)
{
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
return root;
}
private void Add(String name, String number, String model, String year, String insu, String imageString,String mail,String mobile)
{
final RemoteMongoClient mongoClient= stitchAppClient.getServiceClient(RemoteMongoClient.factory, "Mongodb");
RemoteMongoCollection<Document> coll = mongoClient.getDatabase("Car").getCollection("Info");
Document namede = new Document()
.append("carname", name)
.append("carnumber", number)
.append("carmodel", model)
.append("caryear", year)
.append("carinsu", insu)
.append("mail",mail)
.append("mobile",mobile)
.append("carimg", imageString);
final Task<RemoteInsertOneResult> insertTask = coll.insertOne(namede);
insertTask.addOnCompleteListener(new OnCompleteListener<RemoteInsertOneResult>() {
@Override
public void onComplete(@com.mongodb.lang.NonNull Task<RemoteInsertOneResult> task) {
if (task.isSuccessful()) {
Log.d("app", String.format("successfully inserted item with id %s",
task.getResult().getInsertedId()));
Toast.makeText(getContext(), "Sucessfully Inserted Data", Toast.LENGTH_SHORT).show();
//Message="successfully Added Data...";
} else {
Log.e("app", "failed to insert document with: ", task.getException());
Toast.makeText(getContext(), task.getException().toString(), Toast.LENGTH_SHORT).show();
//Message=task.getException().toString();
}
}
});
}
private void GetNameAndNumber() {
firebaseAuth= FirebaseAuth.getInstance();
user=firebaseAuth.getCurrentUser();
DatabaseReference mStorageRef = FirebaseDatabase.getInstance().getReference().child("user");
mStorageRef.child("data").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren())
{
mail = ds.child("email").getValue().toString();
String n=user.getEmail();
if(mail.equals(n)) {
mail = ds.child("email").getValue().toString();
mobile = ds.child("mobile_NO").getValue().toString();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
ImageCropFunction();
} else if (requestCode == 2) {
if (data != null) {
imageuri = data.getData();
ImageCropFunction();
}
} else if (requestCode == 1) {
if (data != null) {
Bundle bundle = data.getExtras();
Bitmap bitmap = bundle.getParcelable("data");
carimg.setImageBitmap(bitmap);
}
}
}
public void ImageCropFunction() {
// Image Crop Code
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(imageuri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 180);
CropIntent.putExtra("outputY", 180);
CropIntent.putExtra("aspectX", 4);
CropIntent.putExtra("aspectY", 3);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
//Image Crop Code End Here
}
<file_sep>/app/src/main/java/com/example/profile/Activities/ui/vehicles/MyVehicles.java
package com.example.profile.Activities.ui.vehicles;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.example.profile.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
import com.mongodb.stitch.android.services.mongodb.remote.RemoteFindIterable;
import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoClient;
import com.mongodb.stitch.android.services.mongodb.remote.RemoteMongoCollection;
import com.mongodb.stitch.core.services.mongodb.remote.RemoteDeleteResult;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
public class MyVehicles extends Fragment {
private StitchAppClient stitchAppClient;
private ListView listView;
List<String> mylist;
FirebaseAuth firebaseAuth;
FirebaseUser user;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_myvehicles, container, false);
listView=root.findViewById(R.id.Listview);
this.stitchAppClient= Stitch.getAppClient("mongodemo-gopcv");
DataGet();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Are You Sure...");
builder.setMessage("you Want To Delete Vehicle Information...");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String Name = mylist.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Delete(Name);
}
});
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Cancelled...", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
});
return root;
}
private void DataGet() {
firebaseAuth=FirebaseAuth.getInstance();
user=firebaseAuth.getCurrentUser();
try {
final RemoteMongoClient mongoClient = stitchAppClient.getServiceClient(RemoteMongoClient.factory, "Mongodb");
RemoteMongoCollection<Document> coll = mongoClient.getDatabase("Bike").getCollection("Info");
RemoteMongoCollection<Document> coll2 = mongoClient.getDatabase("Car").getCollection("Info");
mylist=new ArrayList<String>();
Document filterDoc = new Document()
.append("_id", new Document().append("$exists", true));
RemoteFindIterable findResults = coll
.find(filterDoc)
.projection(new Document().append("_id", 0))
.sort(new Document().append("name", 1));
RemoteFindIterable findResults2 = coll2
.find(filterDoc)
.projection(new Document().append("_id", 0))
.sort(new Document().append("name", 1));
Task<List<Document>> itemsTask = findResults.into(new ArrayList<Document>());
Task<List<Document>> itemsTask2 = findResults2.into(new ArrayList<Document>());
itemsTask.addOnCompleteListener(new OnCompleteListener<List<Document>>() {
@Override
public void onComplete(@NonNull Task<List<Document>> task) {
if (task.isSuccessful()) {
List<Document> items = task.getResult();
for (Document item : items) {
String email=item.getString("mail");
String name=item.getString("bikename");
String mail=user.getEmail();
if(mail.equals(email)){
mylist.add(name);}
}
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1,android.R.id.text1,mylist);
listView.setAdapter(arrayAdapter);
} else {
Log.e("app", "failed to find documents with: ", task.getException());
Toast.makeText(getContext(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
itemsTask2.addOnCompleteListener(new OnCompleteListener<List<Document>>() {
@Override
public void onComplete(@NonNull Task<List<Document>> task) {
if (task.isSuccessful()) {
List<Document> items = task.getResult();
for (Document item : items) {
String email=item.getString("mail");
String name=item.getString("carname");
String mail=user.getEmail();
if(mail.equals(email)){
mylist.add(name);}
}
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1,android.R.id.text1,mylist);
listView.setAdapter(arrayAdapter);
} else {
Log.e("app", "failed to find documents with: ", task.getException());
Toast.makeText(getContext(), task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}catch (Exception e)
{
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void Delete(String Name){
final RemoteMongoClient mongoClient = stitchAppClient.getServiceClient(RemoteMongoClient.factory, "Mongodb");
RemoteMongoCollection<Document> coll = mongoClient.getDatabase("Bike").getCollection("Info");
RemoteMongoCollection<Document> coll2 = mongoClient.getDatabase("Car").getCollection("Info");
Task<RemoteDeleteResult> rest1 = coll.deleteOne(eq("name",Name));
Task<RemoteDeleteResult> rest2 = coll2.deleteOne(eq("name",Name));
rest1.addOnSuccessListener(new OnSuccessListener<RemoteDeleteResult>() {
@Override
public void onSuccess(RemoteDeleteResult remoteDeleteResult) {
Toast.makeText(getContext(), remoteDeleteResult.toString(), Toast.LENGTH_SHORT).show();
}
});
rest2.addOnSuccessListener(new OnSuccessListener<RemoteDeleteResult>() {
@Override
public void onSuccess(RemoteDeleteResult remoteDeleteResult) {
Toast.makeText(getContext(), remoteDeleteResult.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
<file_sep>/app/src/main/java/com/example/profile/Book.java
package com.example.profile;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class Book extends AppCompatActivity {
private TextView name,number,mobile,Email;
private ImageView whatsapp,calling;
ImageView imageView;
@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
int content=getResources().getConfiguration().orientation;
if(content== Configuration.ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
name=findViewById(R.id.viewname);
number=findViewById(R.id.viewnumber);
mobile=findViewById(R.id.viewmobiler);
Email=findViewById(R.id.viewemail);
whatsapp=findViewById(R.id.whatsapplogo);
calling=findViewById(R.id.call);
imageView=findViewById(R.id.imgbook);
Intent intent=getIntent();
String n=intent.getStringExtra("name");
String no=intent.getStringExtra("number");
String mo=intent.getStringExtra("mobile");
String email=intent.getStringExtra("mail");
String img=intent.getStringExtra("img");
name.setText(n);
number.setText(no);
Email.setText(email);
mobile.setText(mo);
byte[] data = Base64.decode(img, Base64.DEFAULT);
Bitmap decodedata = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(decodedata);
whatsapp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent whatsapplunch=new Intent(Intent.ACTION_SENDTO,Uri.parse("smsto:"+
""+ mo + "?body=" + ""));
whatsapplunch.setPackage("com.whatsapp");
startActivity(whatsapplunch);
}
});
calling.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent dailpad=new Intent(Intent.ACTION_DIAL);
dailpad.setData(Uri.parse("tel:"+mo));
startActivity(dailpad);
}
});
}
}
<file_sep>/app/src/main/java/com/example/profile/Activities/HomeNavigate.java
package com.example.profile.Activities;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.bumptech.glide.Glide;
import com.example.profile.Modules.Login;
import com.example.profile.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.mongodb.stitch.android.core.Stitch;
import com.mongodb.stitch.android.core.StitchAppClient;
import com.mongodb.stitch.android.core.auth.StitchUser;
import com.mongodb.stitch.core.auth.providers.anonymous.AnonymousCredential;
public class HomeNavigate extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
FirebaseAuth firebaseAuth;
FirebaseUser user;
@SuppressLint("SourceLockedOrientationActivity")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_navigate);
int content=getResources().getConfiguration().orientation;
if(content== Configuration.ORIENTATION_PORTRAIT){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final FloatingActionButton fab = findViewById(R.id.fab);
firebaseAuth=FirebaseAuth.getInstance();
user=firebaseAuth.getCurrentUser();
try {
final StitchAppClient stitchAppClient = Stitch.initializeAppClient("mongodemo-gopcv");
stitchAppClient.getAuth().loginWithCredential(new AnonymousCredential())
.addOnCompleteListener(new OnCompleteListener<StitchUser>() {
@Override
public void onComplete(@NonNull Task<StitchUser> task) {
}
});
}catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Report Any <EMAIL>", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
UpdateNavHeader();
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_Profile, R.id.nav_myvehicles,R.id.nav_cars,R.id.nav_Bikes,R.id.nav_LogOut)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
int MenuID=destination.getId();
switch (MenuID)
{
case R.id.nav_LogOut :
FirebaseAuth firebaseAuth=FirebaseAuth.getInstance();
firebaseAuth.signOut();
Toast.makeText(HomeNavigate.this, "Sign Out", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(getApplicationContext(), Login.class);
startActivity(intent);
finish();
break;
default:
String str=destination.getLabel().toString();
Toast.makeText(HomeNavigate.this, str+".......", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void UpdateNavHeader()
{
NavigationView navigationView = findViewById(R.id.nav_view);
View headerView=navigationView.getHeaderView(0);
TextView navUser=headerView.findViewById(R.id.nav_username);
TextView navEmail=headerView.findViewById(R.id.textView);
ImageView userphoto=headerView.findViewById(R.id.imageView);
navEmail.setText(user.getEmail());
navUser.setText(user.getDisplayName());
Glide.with(this).load(user.getPhotoUrl()).into(userphoto);
}
}
| f892908c40f0264851722f26a7dcfbbf03eb134f | [
"Java"
] | 5 | Java | Amar1297/Vehical_Rental_Application | f5f7e9e3b718232f7ea371da66be4c6392311386 | a36f8ce836ee075a7dc7e570baefbbb35fa76f84 |
refs/heads/master | <file_sep>using System.Windows.Forms;
using System.Net;
namespace SNMPManager
{
public partial class HostAddForm : Form
{
internal string HostName
{
get
{
return string.IsNullOrEmpty(txtNome.Text) ? null : txtNome.Text.Trim();
}
}
internal IPAddress IPAddr
{
get
{
IPAddress ip;
if (IPAddress.TryParse(txtIPAddr.Text, out ip))
return ip;
else
return null;
}
}
internal ushort PortNum
{
get
{
ushort port;
if (ushort.TryParse(txtPortNum.Text, out port))
return port;
else
return 0;
}
}
internal string Community
{
get
{
return string.IsNullOrEmpty(txtCommunity.Text) ? null : txtCommunity.Text.Trim();
}
}
internal bool IsValid
{
get
{
return IPAddr != null && PortNum > 0 && !string.IsNullOrEmpty(Community);
}
}
public HostAddForm()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void HostAddForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (!this.IsValid)
{
if (DialogResult.Yes == MessageBox.Show("Dados inválidos, deseja descartá-los?", "Confirma", MessageBoxButtons.YesNo))
this.DialogResult = DialogResult.Cancel;
else
e.Cancel = true;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.Diagnostics;
namespace SNMPManager
{
/// <summary>
/// Autodescoberta de hosts SNMP na Rede
/// </summary>
public partial class AutoDiscoveryForm : Form
{
private int _threads;
private ushort _pingTimeout;
/// <summary>
/// Número padrão de Threads
/// </summary>
public static readonly byte MAX_THREADS = 25;
/// <summary>
/// Timout padrão do Ping
/// </summary>
public static readonly ushort PING_TIMEOUT = 500;
/// <summary>
/// OID do objeto SysName da MIB-II
/// </summary>
public static readonly MibObject SNMP_SYSNAME = new MibObject() { OID = "1.3.6.1.2.1.1.5" };
/// <summary>
/// Quantidade de Threads para varrer a Rede
/// </summary>
public int ThreadCount
{
get
{
return _threads == 0 ? MAX_THREADS : _threads;
}
set
{
_threads = value;
}
}
/// <summary>
/// Timeout em milliseconds do Ping
/// </summary>
public ushort PingTimeout
{
get
{
return _pingTimeout == 0 ? PING_TIMEOUT : _pingTimeout;
}
set
{
_pingTimeout = value;
}
}
/// <summary>
/// IP Inicial da faixa a ser buscada
/// </summary>
public IPAddress IPInicial
{
get
{
IPAddress ip;
return IPAddress.TryParse(txtIPIni.Text, out ip) ? ip : null;
}
}
/// <summary>
/// IP Final da faixa a ser buscada
/// </summary>
public IPAddress IPFinal
{
get
{
IPAddress ip;
return IPAddress.TryParse(txtIPFin.Text, out ip) ? ip : null;
}
}
/// <summary>
/// Porta de destino da busca
/// </summary>
public ushort Porta
{
get
{
ushort p = 0;
return ushort.TryParse(txtPortNum.Text, out p) ? p : (ushort)161;
}
}
/// <summary>
/// Nome da comunidade SNMP
/// </summary>
public string Comunidade
{
get
{
return string.IsNullOrEmpty(txtCommunity.Text) ? null : txtCommunity.Text.Trim();
}
}
/// <summary>
/// Formulário está preenchido com dados válidos?
/// </summary>
public bool IsValid
{
get
{
return IPInicial != null && IPFinal != null && Porta > 0 && !string.IsNullOrEmpty(Comunidade);
}
}
/// <summary>
/// Hosts encontrados
/// </summary>
public BindingList<SNMPHost> Hosts { get; protected set; }
public AutoDiscoveryForm()
{
InitializeComponent();
Hosts = new BindingList<SNMPHost>();
lstIP.DataSource = Hosts;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void btnBuscar_Click(object sender, EventArgs e)
{
if (!IsValid)
{
MessageBox.Show("Por favor, preencha o formulário.", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
var btn = sender as Button;
btn.Enabled = false;
Hosts.Clear();
// Converte os IP's para númerico pra facilitar o trabalho
var ini = (long)(uint)IPAddress.NetworkToHostOrder((int)IPInicial.Address);
var fin = (long)(uint)IPAddress.NetworkToHostOrder((int)IPFinal.Address);
var cur = ini;
Logger.Self.Log("IP", LogType.DISCOVERY);
// Tenta pingar os hosts no range
var ipList = PingRange(cur, fin);
Logger.Self.Log("SNMP", LogType.DISCOVERY);
// Tenta buscar o SysName via SNMP
var foundList = SNMPGetSysName(ipList);
// Apresenta os hosts encontrados
foreach (var item in foundList)
Hosts.Add(item);
Logger.Self.Log(string.Format("Concluída com {0} Hosts", Hosts.Count), LogType.DISCOVERY);
btn.Enabled = true;
MessageBox.Show("Autodescoberta concluída.", "SNMPManager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
/// <summary>
/// Escaneia o Range de IP's informado enviando Pings.
/// Caso obtenha resposta adiciona à lista de possíveis Hosts com SNMP.
/// </summary>
/// <returns>IP's que responderam ao Ping</returns>
private IList<IPAddress> PingRange(long cur, long fin)
{
List<IPAddress> ipList = new List<IPAddress>();
using (var q = new SuperQueue<IPAddress>(
ThreadCount,
delegate(IPAddress ip)
{
var pingExec = new Ping();
PingReply pingReply;
try
{
pingReply = pingExec.Send(ip, PingTimeout);
if (pingReply != null && pingReply.Status == IPStatus.Success)
{
Debug.WriteLine(ip);
// Adiciona na lista
lock (ipList)
ipList.Add(ip);
}
}
catch { } // Ignora erros
}))
{
Debug.WriteLine("Pingando hosts");
while (cur <= fin)
{
q.EnqueueTask(IPAddress.Parse(cur.ToString()));
cur++;
}
}
return ipList;
}
/// <summary>
/// Escaneia uma lista de IP's em busca de respostas SNMP.
/// Caso obtenha resposta cria um SNMPHost representando este Host.
/// </summary>
/// <returns>Hosts com SNMP</returns>
private IList<SNMPHost> SNMPGetSysName(IList<IPAddress> ipList)
{
List<SNMPHost> foundList = new List<SNMPHost>();
using (var q = new SuperQueue<IPAddress>(
ThreadCount / 2, // Reduz as threads para não sobrecarregar a rede
delegate(IPAddress ip)
{
var host = new SNMPHost() { Community = Comunidade, IP = ip, Port = Porta };
var request = new SNMPRequest(host, SNMP_SYSNAME)
{
TimeOut = PingTimeout,
Retries = 4,
LogRequests = false // Não loga para economizar recursos
};
try
{
request.Send();
if (request.ResponseValue != null)
{
Debug.WriteLine(ip);
// Define o nome retornado pelo SNMP
host.Name = request.ResponseValue.ToString();
// Adiciona na lista
lock (foundList)
foundList.Add(host);
}
}
catch { } // Ignora erros
}))
{
Debug.WriteLine("Verificando protocolo SNMP");
foreach (var ip in ipList)
q.EnqueueTask(ip);
}
return foundList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Net;
namespace SNMPManager
{
/// <summary>
/// Mapeia um Host com capacidades SNMP
/// </summary>
public class SNMPHost
{
/// <summary>
/// Endereço IP
/// </summary>
public IPAddress IP { get; set; }
/// <summary>
/// Porta SNMP
/// </summary>
public ushort Port { get; set; }
/// <summary>
/// Comunidade
/// </summary>
public string Community { get; set; }
/// <summary>
/// Nome do host
/// </summary>
public string Name { get; set; }
/// <summary>
/// Tipos de evento que devem ser monitorados neste host
/// </summary>
public IList<MonitorKind> MonitoredEvents { get; protected set; }
/*
/// <summary>
/// Fila de eventos que dispararam para este host
/// </summary>
public Queue<MonitorEvent> EventQueue { get; protected set; }
*/
public SNMPHost()
{
//EventQueue = new Queue<MonitorEvent>();
MonitoredEvents = new List<MonitorKind>();
}
public override string ToString()
{
return string.IsNullOrEmpty(Name) ? string.Format("{0}:{1}", IP, Port) : Name;
}
internal bool AddMonitoringEvent(MonitorKind monitor)
{
if (!MonitoredEvents.Contains(monitor))
{
MonitoredEvents.Add(monitor);
return true;
}
return false;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using SnmpSharpNet;
namespace SNMPManager
{
public sealed class SNMPMonitor
{
private static volatile SNMPMonitor instance;
private static object syncRoot = new Object();
private SNMPMonitor() { }
public static SNMPMonitor Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new SNMPMonitor();
}
}
return instance;
}
}
public IEnumerable<MonitorEvent> Exec(IEnumerable<SNMPHost> hostList)
{
if (hostList == null)
throw new ArgumentNullException("hostList");
var eventosGerados = new Queue<MonitorEvent>();
MonitorEvent ocorrencia = null;
foreach (var host in hostList)
{
foreach (var evento in host.MonitoredEvents)
{
switch (evento)
{
case MonitorKind.IsAlive:
if (!IsAlive(host))
ocorrencia = new MonitorEvent(host, evento);
break;
default:
break;
}
if (ocorrencia != null)
{
//host.EventQueue.Enqueue(ocorrencia);
eventosGerados.Enqueue(ocorrencia);
}
ocorrencia = null;
}
}
return eventosGerados;
}
/// <summary>
/// Verifica se o Host está ativo (respondendo a requisições)
/// </summary>
private bool IsAlive(SNMPHost host)
{
var mibObj = new MibObject() { OID = "1.3.6.1.2.1.1.3" };
var req = new SNMPRequest(host, mibObj) { LogRequests = false };
try
{
req.Send();
if (req.ResponseValue != null)
return true;
}
catch { }
return false;
}
}
public enum MonitorKind
{
Nenhum,
[Description("Não houve resposta do Host.")]
IsAlive
}
}
<file_sep>using System;
using System.IO;
using System.Text;
using SnmpSharpNet;
namespace SNMPManager
{
/// <summary>
/// Singleton para realizar a escrita de logs da aplicação.
/// </summary>
public sealed class Logger
{
// Variáveis de instância
private StreamWriter writer;
// Variáveis estáticas
private static volatile Logger instance;
private static object syncRoot = new Object();
public static readonly string FILENAME = "App.log";
private Logger()
{
writer = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + FILENAME, true, Encoding.UTF8);
writer.AutoFlush = true; // Evita bufferizar dados
}
// Singleton
public static Logger Self
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Logger();
}
}
return instance;
}
}
/// <summary>
/// Escreve um texto arbitrário no arquivo de log
/// </summary>
public void Log(string text, LogType type)
{
writer.WriteLine(
string.Format("{0} | {1, -9} | {2}",
DateTime.Now.ToString("u"),
type,
text
)
);
}
/// <summary>
/// Escreve um texto arbitrário no arquivo de log
/// </summary>
public void Log(string text)
{
Log(text, LogType.INFO);
}
/// <summary>
/// Faz o logging de um SNMPRequest
/// </summary>
internal void Log(SNMPRequest SNMPReq)
{
var l = string.Format( "{0,-21} | {1,-3} | {2}",
SNMPReq.Host,
SNMPReq.RequestData.Type,
SNMPReq.Object
);
this.Log(l, LogType.REQUEST);
}
/// <summary>
/// Faz o logging do resultado de um SNMPRequest
/// </summary>
internal void Log(Vb item)
{
this.Log(item.Value.ToString(), LogType.RESPONSE);
}
/// <summary>
/// Faz o logging de uma Exception
/// </summary>
internal void Log(Exception ex)
{
this.Log(ex.Message, LogType.EXCEPTION);
}
}
/// <summary>
/// Classificação da mensagem de log
/// </summary>
public enum LogType
{
INFO,
REQUEST,
RESPONSE,
EXCEPTION,
DISCOVERY
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SNMPManager
{
public class MonitorEvent
{
/// <summary>
/// Tipo
/// </summary>
public MonitorKind Tipo { get; protected set; }
/// <summary>
/// Data e Hora
/// </summary>
public DateTime Timestamp { get; protected set; }
/// <summary>
/// Host
/// </summary>
public SNMPHost Host { get; protected set; }
public MonitorEvent(SNMPHost h, MonitorKind t)
{
Host = h;
Tipo = t;
Timestamp = DateTime.Now;
}
public override string ToString()
{
return string.Format("{0} - {1}: {2}", Timestamp, Host, Utils.GetDescription(Tipo));
}
}
}
<file_sep>using System;
namespace SNMPManager
{
/// <summary>
/// Wrapper para apresentar os dados na tela, uma vez
/// que o DataGridView não permite certas operações
/// </summary>
public class SNMPCommunications : SNMPRequest
{
public string Hostname
{
get
{
return base.Host.ToString();
}
}
public string Tipo
{
get
{
return base.RequestData.Type.ToString();
}
}
public string Objeto
{
get
{
return base.Object.ToString();
}
}
public SNMPCommunications(SNMPHost host, MibObject obj)
: base(host, obj)
{ }
}
}
<file_sep>using System.Windows.Forms;
using SnmpSharpNet;
namespace SNMPManager
{
public partial class MIBObjectSetForm : Form
{
internal string Value
{
get
{
return string.IsNullOrEmpty(txtValue.Text) ? null : txtValue.Text.Trim();
}
}
internal DataType Type
{
get
{
DataType ret = DataType.String;
if (rdrInteger.Checked)
ret = DataType.Integer;
if (rdrIP.Checked)
ret = DataType.IP;
if (rdrString.Checked)
ret = DataType.String;
if (rdrTimestamp.Checked)
ret = DataType.Timestamp;
return ret;
}
}
public AsnType ConvertedValue()
{
switch (Type)
{
case DataType.String:
return new OctetString(Value);
case DataType.IP:
break;
case DataType.Integer:
break;
case DataType.Timestamp:
break;
default:
break;
}
return null;
}
public MIBObjectSetForm()
{
InitializeComponent();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
return base.ProcessCmdKey(ref msg, keyData);
}
public enum DataType
{
String,
IP,
Integer,
Timestamp
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Threading;
namespace SNMPManager
{
/// <summary>
/// Cria um número definido de Threads para trabalhar no modelo Produtor/Consumidor
/// </summary>
/// <remarks>
/// http://stackoverflow.com/a/5828863/251676
/// </remarks>
public class SuperQueue<T> : IDisposable where T : class
{
readonly object _locker = new object();
readonly List<Thread> _workers;
readonly Queue<T> _taskQueue = new Queue<T>();
readonly Action<T> _dequeueAction;
/// <summary>
/// Initializes a new instance of the <see cref="SuperQueue{T}"/> class.
/// </summary>
/// <param name="workerCount">The worker count.</param>
/// <param name="dequeueAction">The dequeue action.</param>
public SuperQueue(int workerCount, Action<T> dequeueAction)
{
_dequeueAction = dequeueAction;
_workers = new List<Thread>(workerCount);
// Create and start a separate thread for each worker
for (int i = 0; i < workerCount; i++)
{
Thread t = new Thread(Consume) { IsBackground = true, Name = string.Format("SuperQueue worker {0}", i) };
_workers.Add(t);
t.Start();
}
}
/// <summary>
/// Enqueues the task.
/// </summary>
/// <param name="task">The task.</param>
public void EnqueueTask(T task)
{
lock (_locker)
{
_taskQueue.Enqueue(task);
Monitor.PulseAll(_locker);
}
}
/// <summary>
/// Consumes this instance.
/// </summary>
void Consume()
{
while (true)
{
T item;
lock (_locker)
{
while (_taskQueue.Count == 0) Monitor.Wait(_locker);
item = _taskQueue.Dequeue();
}
if (item == null) return;
// run actual method
_dequeueAction(item);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
// Enqueue one null task per worker to make each exit.
_workers.ForEach(thread => EnqueueTask(null));
_workers.ForEach(thread => thread.Join());
}
}
}
<file_sep># SNMPManager
Gerenciador SNMP desenvolvido para a disciplina de Gerência de Redes da [Universidade do Vale do Rio dos Sinos](http://www.unisinos.br).
Representa o próximo passo em direção a uma ferramenta de gerência de redes uma vez que já foi criado um [Agente SNMP](https://github.com/mateusaubin/SNMPAgent).
Este projeto faz uso extensivo da biblioteca [SNMP#Net](http://www.snmpsharpnet.com).
# Desenvolvedores
Este projeto foi criado por:
* <NAME>
* <NAME>
# Licença
```
"THE BEER-WARE LICENSE" (Revision 42):
'The Authors' wrote this file. As long as you retain this notice you
can do whatever you want with this stuff. If we meet some day, and you think
this stuff is worth it, you can buy me a beer in return.
```<file_sep>using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace SNMPManager
{
public partial class MainForm : Form
{
/// <summary>
/// Objetos da MIB disponíveis para consulta
/// </summary>
public BindingList<MibObject> MIBObjects { get; protected set; }
/// <summary>
/// Hosts disponíveis para consulta
/// </summary>
public BindingList<SNMPHost> Hosts { get; protected set; }
/// <summary>
/// Histórico de comunicação
/// </summary>
public BindingList<SNMPCommunications> SNMPCommunications { get; protected set; }
/// <summary>
/// Objeto da MIB selecionado atualmente
/// </summary>
public MibObject SelectedMibObject
{
get
{
return mibList.SelectedItem as MibObject;
}
}
/// <summary>
/// Host selecionado atualmente
/// </summary>
public SNMPHost SelectedHost
{
get
{
return hostList.SelectedItem as SNMPHost;
}
}
/// <summary>
/// Construtor
/// </summary>
public MainForm()
{
InitializeComponent();
InitializeDataStructures();
DataBind();
Clear();
}
/// <summary>
/// Limpa os defaults
/// </summary>
private void Clear()
{
statusbar.Text = string.Empty;
mibList.ClearSelected();
hostList.ClearSelected();
}
/// <summary>
/// Associa as coleções aos controles de tela
/// </summary>
private void DataBind()
{
communicationGrid.DataSource = SNMPCommunications;
mibList.DataSource = MIBObjects;
hostList.DataSource = Hosts;
}
/// <summary>
/// Inicializa as coleções
/// </summary>
private void InitializeDataStructures()
{
SNMPCommunications = new BindingList<SNMPCommunications>();
MIBObjects = new BindingList<MibObject>();
Hosts = new BindingList<SNMPHost>();
// MIB-II
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.2.1.1.5", Name = "sysName" });
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.2.1.1.6", Name = "sysLocation", CanSet = true });
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.2.1.1.3", Name = "sysUpTime" });
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.2.1.25.1.6", Name = "hrSystemProcesses" });
// MIB-Custom
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.4.1.1.2", Name = "screenResolutionWidth" });
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.4.1.1.3", Name = "screenResolutionHeight" });
MIBObjects.Add(new MibObject() { OID = "1.3.6.1.4.1.1.6", Name = "filesystemCount" });
}
/// <summary>
/// Mostra detalhes de um Objeto da MIB na StatusBar
/// </summary>
private void mibList_UpdateStatusBar(object sender, EventArgs e)
{
if (SelectedMibObject != null)
statusbar.Text = string.Format("{0} ({1})", SelectedMibObject, SelectedMibObject.OID);
else
statusbar.Text = string.Empty;
}
/// <summary>
/// Habilita a seleção de um objeto da MIB com o botão direito
/// </summary>
private void mibList_RightClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int index = mibList.IndexFromPoint(e.Location);
if (index != ListBox.NoMatches)
{
mibList.SelectedIndex = index;
mibList_UpdateStatusBar(null, null);
}
}
}
/// <summary>
/// Mostra detalhes de um Host na StatusBar
/// </summary>
private void hostList_UpdateStatusBar(object sender, EventArgs e)
{
if (SelectedHost != null)
statusbar.Text = string.Format("{0} ({1}:{2})", SelectedHost, SelectedHost.IP, SelectedHost.Port);
else
statusbar.Text = string.Empty;
}
/// <summary>
/// Trata a operação de Adicionar Host
/// </summary>
private void adicionarToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var hostAdd = new HostAddForm())
{
var result = hostAdd.ShowDialog(this);
switch (result)
{
case DialogResult.OK:
// TODO: Validar se já existe
Hosts.Add(
new SNMPHost()
{
IP = hostAdd.IPAddr,
Port = hostAdd.PortNum,
Community = hostAdd.Community,
Name = hostAdd.HostName
}
);
hostList_UpdateStatusBar(null, null);
hostList.Focus();
break;
case DialogResult.Cancel:
// Faz nada não
break;
default:
break;
}
}
}
/// <summary>
/// Trata a operação de Remover Host
/// </summary>
private void removerToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Hosts.Count > 0)
{
if (!ValidaHostSelecionado())
return;
Hosts.Remove(SelectedHost);
}
hostList_UpdateStatusBar(null, null);
hostList.Focus();
}
/// <summary>
/// Controla se a operação Set está disponível para um objeto da MIB
/// </summary>
private void mibListMenu_Opening(object sender, CancelEventArgs e)
{
mibListMenu.Items[1].Enabled = SelectedMibObject.CanSet;
}
/// <summary>
/// Trata a operação de Get de um objeto da MIB sobre um Host
/// </summary>
private void getToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!ValidaHostSelecionado())
return;
var req = new SNMPCommunications(SelectedHost, SelectedMibObject);
try
{
req.Send();
SNMPCommunications.Add(req);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Trata a operação de Set de um objeto da MIB sobre um Host
/// </summary>
private void setToolStripMenuItem_Click(object sender, EventArgs e)
{
if (!ValidaHostSelecionado())
return;
using (var setValue = new MIBObjectSetForm())
{
var result = setValue.ShowDialog(this);
switch (result)
{
case DialogResult.OK:
try
{
var req = new SNMPCommunications(SelectedHost, SelectedMibObject);
req.Send(setValue.ConvertedValue());
SNMPCommunications.Add(req);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
break;
case DialogResult.Cancel:
break;
default:
break;
}
}
}
/// <summary>
/// Limpa os registros da tabela
/// </summary>
private void limparToolStripMenuItem_Click(object sender, EventArgs e)
{
SNMPCommunications.Clear();
}
private void autodescobertaToolStripMenuItem_Click(object sender, EventArgs e)
{
using (var autoDisc = new AutoDiscoveryForm())
{
var result = autoDisc.ShowDialog(this);
if (autoDisc.Hosts != null && autoDisc.Hosts.Count > 0)
{
foreach (var item in autoDisc.Hosts)
this.Hosts.Add(item);
hostList_UpdateStatusBar(null, null);
hostList.Focus();
}
}
}
private void isAliveToolStripMenuItem_Click(object sender, EventArgs e)
{
this.AddMonitoringEvent(MonitorKind.IsAlive);
}
private void AddMonitoringEvent(MonitorKind monitorKind)
{
if (!ValidaHostSelecionado())
return;
if (SelectedHost.AddMonitoringEvent(monitorKind))
{
// Insere na lista de hosts monitorados
lstMonitorados.Items.Add(string.Format("{0}: {1}", monitorKind, SelectedHost));
}
// Habilita timer
if (!tmrMonitor.Enabled)
{
tmrMonitor.Enabled = true;
// Força a primeira execução
//tmrMonitor_Tick(null, null);
}
}
private bool ValidaHostSelecionado()
{
bool isSelected = SelectedHost != null;
if (!isSelected)
MessageBox.Show("Por favor, selecione um Host.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return isSelected;
}
private void tmrMonitor_Tick(object sender, EventArgs e)
{
var list = lstMonitoringLog;
var code = new Action<string>((v) => { list.Items.Add(string.Format("{0} - {1}", DateTime.Now, v)); list.TopIndex = list.Items.Count - 1; });
string msg = "Monitorando...";
if (list.InvokeRequired)
list.Invoke(code, msg);
else
code.Invoke(msg);
if (!bwMonitor.IsBusy)
bwMonitor.RunWorkerAsync();
}
private void bwMonitor_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
if (worker == null)
throw new Exception("Aconteceu algo com o BackgroundWorker");
var list = lstMonitoringLog;
var code = new Action<MonitorEvent>((v) => { list.Items.Add(v); list.TopIndex = list.Items.Count - 1; });
// TODO: Corrigir o problema do Enumerator quando remove um host da collection original
var hostsCopy = new SNMPHost[Hosts.Count];
Hosts.CopyTo(hostsCopy, 0);
// Executa o Monitor passando todos os Hosts
foreach (var evt in SNMPMonitor.Instance.Exec(hostsCopy))
{
if (list.InvokeRequired)
list.Invoke(code, evt);
else
code.Invoke(evt);
}
}
private void pararToolStripMenuItem_Click(object sender, EventArgs e)
{
tmrMonitor.Enabled = false;
foreach (var host in Hosts)
host.MonitoredEvents.Clear();
lstMonitorados.Items.Clear();
}
}
}
<file_sep>using System;
namespace SNMPManager
{
/// <summary>
/// Mapeia um Objeto da MIB
/// </summary>
public class MibObject
{
/// <summary>
/// OID do objeto
/// </summary>
public string OID { get; set; }
/// <summary>
/// Nome do objeto
/// </summary>
public string Name { get; set; }
/// <summary>
/// Permite operações Set?
/// </summary>
public bool CanSet { get; set; }
public override string ToString()
{
return string.IsNullOrEmpty(Name) ? OID : Name;
}
}
}
<file_sep>using System;
using SnmpSharpNet;
namespace SNMPManager
{
/// <summary>
/// Mapeia um Request SNMP e sua Resposta
/// </summary>
public class SNMPRequest
{
private ushort _timeout;
private byte _retries;
/// <summary>
/// Timeout padrão da requisição
/// </summary>
public static readonly ushort DEFAULT_TIMEOUT = 500;
/// <summary>
/// Número padrão de tentativas em caso de erro
/// </summary>
public static readonly byte DEFAULT_RETRIES = 1;
/// <summary>
/// Timeout da requisição
/// </summary>
public ushort TimeOut
{
get
{
return _timeout == 0 ? DEFAULT_TIMEOUT : _timeout;
}
set
{
_timeout = value;
}
}
/// <summary>
/// Quantidade de tentativas em caso de erro
/// </summary>
public byte Retries
{
get
{
return _retries == 0 ? DEFAULT_RETRIES : _retries;
}
set
{
_retries = value;
}
}
/// <summary>
/// Data e Hora de realização
/// </summary>
public DateTime Timestamp { get; protected set; }
/// <summary>
/// Host SNMP alvo da requisição
/// </summary>
public SNMPHost Host { get; protected set; }
/// <summary>
/// Objeto da MIB requisitado
/// </summary>
public MibObject Object { get; protected set; }
/// <summary>
/// Pacote de Requisição
/// </summary>
public Pdu RequestData { get; protected set; }
/// <summary>
/// Pacote de Resposta
/// </summary>
public SnmpV2Packet ResponsePacket { get; protected set; }
/// <summary>
/// Valor da Resposta
/// </summary>
public AsnType ResponseValue { get; protected set; }
/// <summary>
/// Deve gravar logs?
/// </summary>
public bool LogRequests { get; set; }
public SNMPRequest(SNMPHost host, MibObject obj)
{
Host = host;
Object = obj;
LogRequests = true;
}
/// <summary>
/// Executa uma requisição do tipo Get
/// </summary>
public void Send()
{
Send(null);
}
/// <summary>
/// Executa uma requisição do tipo Set
/// </summary>
/// <param name="setValue">Valor a set definido</param>
public void Send(AsnType setValue)
{
using (var target = new UdpTarget(Host.IP, Host.Port, TimeOut, Retries))
{
var agentp = new AgentParameters(SnmpVersion.Ver2, new OctetString(Host.Community));
// Caso necessario, appenda o .0 na requisição
var oid = new Oid(Object.OID);
if (oid[oid.Length - 1] != 0)
oid.Add(0);
// Cria pacote de dados
RequestData = new Pdu(setValue == null ? PduType.Get : PduType.Set);
// Adiciona dados da requisição
switch (RequestData.Type)
{
case PduType.Get:
RequestData.VbList.Add(oid);
break;
case PduType.Set:
RequestData.VbList.Add(oid, setValue);
break;
default:
throw new InvalidOperationException("unsupported");
}
try
{
if (LogRequests) Logger.Self.Log(this);
Timestamp = DateTime.Now;
// Envia requisição
ResponsePacket = target.Request(RequestData, agentp) as SnmpV2Packet;
// Trata resposta
if (ResponsePacket != null && ResponsePacket.Pdu.ErrorStatus == (int)PduErrorStatus.noError)
{
// TODO: suportar mais de um retorno
var item = ResponsePacket.Pdu.VbList[0];
ResponseValue = item.Value;
if (LogRequests) Logger.Self.Log(item);
}
}
catch (Exception ex)
{
if (LogRequests) Logger.Self.Log(ex);
throw new SnmpException("Não foi possível realizar a operação");
}
}
}
}
}
| e067edb155321453caa38c94200048e8a77052bd | [
"Markdown",
"C#"
] | 13 | C# | mateusaubin/SNMPManager | 2ddaf0916adb01f552fd61d84b4b5e9a39463136 | 7bb3bfc1c3256b4e1ef117ac6a0f6f7de68cb783 |
refs/heads/master | <repo_name>Naveenshankar1/C-Users-91950-eclipse-workspace<file_sep>/Demo/src/LoopingConcept.java
import java.lang.reflect.Array;
public class LoopingConcept {
int[] arr1= {10,20,30,30,40,50};
}<file_sep>/Demo/src/MyGetSetClass.java
public class MyGetSetClass {
public MyGetSetClass() {
System.out.println("\"WELCOME TO JAVA PROJECT\"");
}
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
<file_sep>/Demo/src/InterFaceExtract.java
import java.util.Scanner;
public class InterFaceExtract implements InterDemo{
public void NameDetails() {
String name ="VW";
System.out.println("Name of the Company is : "+name);
}
public String Address(String str) {
//System.out.println("Address of the Company is : "+str);
return str;
}
public int DoorNum() {
int doorNum = 123;
System.out.println("Door Number of the Company : "+ doorNum);
return doorNum;
}
}
<file_sep>/Overloading/src/Bank/Bank1.java
package Bank;
import Program.Ticketnew;
public class Bank1 extends Ticketnew {
public static void main(String[] args) {
Bank1 obj =new Bank1();
obj.add(200, 30.80);
obj.add(100, 20.80);
}
}
<file_sep>/.metadata/.plugins/org.eclipse.pde.core/.cache/clean-cache.properties
#Cached timestamps
#Sun Feb 16 11:58:44 IST 2020
| a0b14fd324c16e7cf2365cf8457a15da57ff1ba5 | [
"Java",
"INI"
] | 5 | Java | Naveenshankar1/C-Users-91950-eclipse-workspace | 9799bb2a6cf9f8706babc5b67cd366e9d230f002 | 8bb3ac3fd3b93758ffaac5957878bffca8a9158e |
refs/heads/master | <file_sep>import './estilos.css'
document.write("asdsdsd sdsdsd");
console.log('hola mundo desde webpack');
<file_sep>import '../css/estilos.css'
document.write("Hola Mundo desde los precios");
console.log('hola mundo desde webpack');
<file_sep>import renderToDOM from './render-to-dom.js'
import makeMessage from './make-message.js'
const waitTime = new Promise((todoOk, todoMal) => {
setTimeout(()=>{
todoOk('han pasado 3 segundos');
}, 3000);
});
export const firstMessage = 'test dsdsdsdsd';
export const delayedMessage = async () => {
const message = await waitTime;
console.log(message);
renderToDOM(makeMessage(message));
};
<file_sep>import './estilos.css'
import { firstMessage, delayedMessage } from './message.js'
import platziImg from './platzi.png';
document.write(firstMessage);
delayedMessage();
const img = document.createElement('img');
img.setAttribute('src', platziImg);
img.setAttribute('width', "50px");
img.setAttribute('height', "50px");
document.body.append(img);
console.log('hola mundo desde webpack');
<file_sep>import '../css/estilos.css'
document.write("Hola Mundo desde contacto");
console.log('hola mundo desde webpack');
| 3a8b3d17303058315799f3ef3af61e5a4956f953 | [
"JavaScript"
] | 5 | JavaScript | hermesto/cursoWebpack | 50a432d317657257a0a44022bd7c59aa628b50b2 | 96b4a0a8860fe10c19d3553252859166a4eca160 |
refs/heads/master | <repo_name>DangerMr/JSO<file_sep>/JSO.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JSO Generator</title>
<link href="https://fonts.googleapis.com/css?family=Fredoka+One&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Caveat&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Dokdo|Gloria+Hallelujah|Indie+Flower|Permanent+Marker" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Righteous" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Fredericka+the+Great|Kaushan+Script|Press+Start+2P|Rationale" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Chewy" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Permanent+Marker|Righteous" rel="stylesheet">
<script type="text/javascript">
function copy_text() {
document.getElementById("pilih").select();
document.execCommand("copy");
alert("Text berhasil dicopy Cuk");
}
</script>
<style>
body {
background-color:#0000FF;
color:white;
font-family: 'Permanent Marker', cursive;
}
.head {
font-family: 'Permanent Marker', cursive;
text-shadow: 4px 1px red;
}
.textarea {
width: 200px;
height: 100px;
border-radius: 10px;
border-style: unset;
}
.btn {
border-radius: 3px;
background-color: white;
border-style: unset;
font-family: 'Fredoka One', cursive;
}
.foot {
font-family: 'Caveat', cursive;
text-shadow: 4px 1px red;
}
.ress {
font-size: 20px;
color: aqua;
font-family: 'Fredoka One', cursive;
}
</style>
<script>
function runCharCodeAt() {
input = document.charCodeAt.input.value;
output = "";
for(i=0; i<input.length; ++i) {
if (output != "") output += ", ";
output += input.charCodeAt(i);
}
document.charCodeAt.output.value = output;
}
</script>
</head>
<body>
<center>
<h1 class="head">Make Script JSO</h1>
<form name="charCodeAt" method="post">
<textarea name="input" class="textarea" placeholder="Paste Sc Deface/Codingan Web Disini"></textarea><br><br>
<input type="button" onclick="runCharCodeAt()" value="Char" class="btn"><br><br>
<textarea name="output" class="textarea"></textarea><br><br>
<input type="submit" name="submit" value="Buat" class="btn"><br><br>
<center>
<div style="text-shadow: 5px 5px 5px #000000;">
<font color="SpringGreen" size="4" face="Chewy">
<script language="JavaScript">
var text=" <br>UNITED MASTER CYBER TOOLS<br>"
var delay=50;
var currentChar=1;
var destination="[none]";
function type()
{
//if (document.all)
{
var dest=document.getElementById(destination);
if (dest)// && dest.innerHTML)
{
dest.innerHTML=text.substr(0,currentChar)+"<blink>_</blink>";
currentChar++;
if (currentChar>text.length)
{
currentChar=1;
setTimeout("type()",5000);
}
else
{
setTimeout("type()",delay);
}
}
}
}
function startTyping(textParam,delayParam,destinationParam)
{
text=textParam;
delay=delayParam;
currentChar=1;
destination=destinationParam;
type();
}
</script>
<b><div id="textDestination" style="background-color:Blue"; style="font: 50px Arial color:blue; margin:0px;"></div></b>
<script language="JavaScript">
javascript:startTyping(text,50,"textDestination");
</script></div>
<br><script type="text/javascript">
fl=1
function f1()
function f(){
if(fl==1)
{
Bn.style.top=100
Bn.style.left=600
fl=2
}
else if(fl==2)
{
Bn.style.top=600
Bn.style.left=50
fl=3
}
else if(fl==5)
{
Bn.style.top=200
Bn.style.left=500
fl=
}
}
</script></font>
</form>
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['output'])) {
echo "<script>alert('Convert Dulu Anjenk');</script>";
}else{
$isi = $_POST['output'];
$random = rand(1, 99999999);
$api_dev_key = '<KEY>'; // your api_developer_key
$api_paste_code = "document.documentElement.innerHTML=String.fromCharCode(".$isi.")"; // your paste text
$api_paste_private = '0'; // 0=public 1=unlisted 2=private
$api_paste_name = $random; // name or title of your paste
$api_paste_expire_date = 'N';
$api_paste_format = 'text';
$api_user_key = ''; // if an invalid or expired api_user_key is used, an error will spawn. If no api_user_key is used, a guest paste will be created
$api_paste_name = urlencode($api_paste_name);
$api_paste_code = urlencode($api_paste_code);
$url = 'https://pastebin.com/api/api_post.php';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'api_option=paste&api_user_key='.$api_user_key.'&api_paste_private='.$api_paste_private.'&api_paste_name='.$api_paste_name.'&api_paste_expire_date='.$api_paste_expire_date.'&api_paste_format='.$api_paste_format.'&api_dev_key='.$api_dev_key.'&api_paste_code='.$api_paste_code.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
$response = curl_exec($ch);
$hasil = str_replace('https://pastebin.com', 'https://pastebin.com/raw', $response);
$respak = '<script type="text/javascript" src="'.$hasil.'"></script>';
$kk = htmlspecialchars($respak);
echo "<h1 class='ress'>Result:</h1>";
echo "<input type='text' value='$kk' id='pilih' readonly />";
echo "<button type='button' onclick='copy_text()'>Copy</button>";
}}
echo "<h2 class='foot'>@2k19 Codded By TuanSadboys</h2>";
?>
</body>
</html> | 8ac85beb05854b4242746e6a4726bcdb228f9ef3 | [
"PHP"
] | 1 | PHP | DangerMr/JSO | 9cccc0bd41a22779a930a28891c7ff17cca6c174 | 3008bd406eae7d82b220ed8f9d37e876f0e3c70e |
refs/heads/master | <repo_name>apoorvemohan/threads<file_sep>/qthread-impl.h
/*
* file: qthread-impl.h
* description: implementation-specific data structures for qthreads
* mutexes and condition variables.
* <NAME>, Northeastern CCIS 2014
* $Id:$
*/
#ifndef __QTHREAD_IMPL_H__
#define __QTHREAD_IMPL_H__
/* removed: QTHREAD_MUTEX_INITIALIZER
QTHREAD_COND_INITIALIZER
philosopher.c and websvr/listener.c modified to use explicit init
if you want to add them back in, feel free.
*/
/* This file contains private definitions used only in qthread.c.
*/
/* the thread structure itself
*/
struct qthread {
};
/* Mutex
*/
struct qthread_mutex {
};
/* Condition variable
*/
struct qthread_cond {
/* your code here */
};
#endif
<file_sep>/Makefile
#
# qthreads Makefile
#
EXES = test1 philosopher server
LIBS = libqthread.a
CFLAGS = -g -I.
QTH = qthread.o
all: $(LIBS) $(EXES)
clean:
rm -f *.o $(LIBS) $(EXES)
libqthread.a: $(QTH) do-switch.o
ar r libqthread.a $(QTH) do-switch.o
test1: test1.o libqthread.a
gcc -g test1.o -o test1 -L. -lqthread
philosopher: philosopher.o libqthread.a
gcc -g philosopher.o -o philosopher -L. -lqthread -lm
server: server.o libqthread.a
gcc -g server.o -o server -L. -lqthread
<file_sep>/qthread.c
/*
* file: qthread.c
* description: simple emulation of POSIX threads
* class: CS 7600, Spring 2013
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <sys/time.h>
#include <fcntl.h>
#include "qthread.h"
#define THREADSTACKSIZE 4096
qthread_t activeThreadList = NULL;
qthread_t tail = NULL;
/*
* do_switch is defined in do-switch.s, as the stack frame layout
* changes with optimization level, making it difficult to do with
* inline assembler.
*/
extern void do_switch(void **location_for_old_sp, void *new_value);
/*
* setup_stack(stack, function, arg1, arg2) - sets up a stack so that
* switching to it from 'do_switch' will call 'function' with arguments
* 'arg1' and 'arg2'. Returns the resulting stack pointer.
*
* works fine with functions that take one argument ('arg1') or no
* arguments, as well.
*/
void *setup_stack(int *stack, void *func, void *arg1, void *arg2)
{
int old_bp = (int)stack; /* top frame - SP = BP */
*(--stack) = 0x3A3A3A3A; /* guard zone */
*(--stack) = 0x3A3A3A3A;
*(--stack) = 0x3A3A3A3A;
/* this is the stack frame "calling" 'func'
*/
*(--stack) = (int)arg2; /* argument */
*(--stack) = (int)arg1; /* argument (reverse order) */
*(--stack) = 0; /* fake return address (to 'func') */
/* this is the stack frame calling 'do_switch'
*/
*(--stack) = (int)func; /* return address */
*(--stack) = old_bp; /* %ebp */
*(--stack) = 0; /* %ebx */
*(--stack) = 0; /* %esi */
*(--stack) = 0; /* %edi */
*(--stack) = 0xa5a5a5a5; /* valid stack flag */
return stack;
}
/* You'll need to do sub-second arithmetic on time. This is an easy
* way to do it - it returns the current time as a floating point
* number. The result is as accurate as the clock usleep() uses, so
* it's fine for us.
*/
static double gettime(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + tv.tv_usec/1.0e6;
}
/* A good organization is to keep a pointer to the 'current'
* (i.e. running) thread, and a list of 'active' threads (not
* including 'current') which are also ready to run.
*/
/* Note that on startup there's already a thread running thread - we
* need a placeholder 'struct thread' so that we can switch away from
* that to another thread and then switch back.
*/
struct qthread os_thread = {};
qthread_t current = &os_thread;
void activeThreadListRotateLeft()
{
tail->next = activeThreadList;
activeThreadList->prev = tail;
activeThreadList = activeThreadList->next;
tail = tail->next;
activeThreadList->prev = NULL;
tail->next = NULL;
}
void findNextRunnableThread(qthread_t *nextRunnable)
{
do{
if(((activeThreadList->status == 1) || (activeThreadList->status == 3))
&& (activeThreadList->wakeupTime <= gettime())
&& (activeThreadList->tid != current->tid))
{
*nextRunnable = activeThreadList;
activeThreadListRotateLeft();
break;
}
else
{
activeThreadListRotateLeft();
}
}while(1);
}
/* Initialize a thread attribute structure. We're using an 'int' for
* this, so just set it to zero.
*/
int qthread_attr_init(qthread_attr_t *attr)
{
*attr = 0;
return 0;
}
/* The only attribute supported is 'detached' - if it is true a thread
* will clean up when it exits; otherwise the thread structure hangs
* around until another thread calls qthread_join() on it.
*/
int qthread_attr_setdetachstate(qthread_attr_t *attr, int detachstate)
{
*attr = detachstate;
return 0;
}
long getNextTID()
{
long nextTID = 0;
qthread_t iterator = activeThreadList;
while(iterator != NULL)
{
nextTID++;
iterator = iterator->next;
}
return nextTID;
}
/* Beware - you cannot use do_switch to switch from a thread to
* itself. If there are no other active threads (or after a timeout
* the first scheduled thread is the current one) you should return
* without switching. (why? because you haven't saved the current
* stack pointer)
*/
void *wrapper(qthread_func_ptr_t func, void *arg)
{
qthread_exit(func(arg));
}
/* qthread_yield - yield to the next runnable thread.
*/
int qthread_yield(void)
{
qthread_t nextRunnableThread = NULL, prev = NULL;
findNextRunnableThread(&nextRunnableThread);
if(nextRunnableThread != NULL)
{
prev = current;
if(prev->status != 4)
{
prev->status = 3;
}
current = nextRunnableThread;
current->status = 2;
do_switch(&prev->offsetPtr, nextRunnableThread->offsetPtr);
}
return 0;
}
void freeTCB(long toBeDeleted)
{
qthread_t iterator = activeThreadList;
if(activeThreadList != NULL)
{
while(iterator != NULL)
{
if(iterator->tid == toBeDeleted)
{
if(toBeDeleted == activeThreadList->tid)
{
iterator = activeThreadList;
activeThreadList = activeThreadList->next;
activeThreadList->prev = NULL;
iterator->next = NULL;
}
else if(toBeDeleted == tail->tid)
{
iterator = tail;
tail = tail->prev;
tail->next = NULL;
iterator->prev = NULL;
}
else
{
iterator->prev->next = iterator->next;
iterator->next->prev = iterator->prev;
iterator->next = NULL;
iterator->prev = NULL;
}
free(iterator->basePtr);
free(iterator);
break;
}
else
{
iterator = iterator->next;
}
}
if((activeThreadList->next == NULL) && (activeThreadList->tid == 0))
{
free(activeThreadList->basePtr);
activeThreadList = NULL;
}
}
else
{
fprintf(stderr, "List Empty!!! Cannot Free the given thread!!!");
}
}
int qthread_join(qthread_t thread, void **retval)
{
if(thread != NULL)
{
if(thread->status != 4)
{
qthread_yield();
}
if(retval != NULL)
{
qthread_t iterator = activeThreadList;
while(iterator != NULL)
{
if(iterator->tid == thread->tid)
{
*retval = iterator->exitStatus;
break;
}
iterator = iterator->next;
}
}
thread->detached = 1;
freeTCB(thread->tid);
}
else
{
return -1;
}
return 0;
}
/* qthread_exit - sort of like qthread_yield, except we never
* return. If the thread is joinable you need to save 'val' for a
* future call to qthread_join; otherwise you can free allocated
* memory.
*/
void qthread_exit(void *val)
{
if(!current->detached)
{
current->exitStatus = val;
}
current->status = 4;
qthread_yield();
}
void printActiveThreadList()
{
if(activeThreadList != NULL)
{
qthread_t temp = activeThreadList;
while(temp != NULL)
{
printf("%ld\n", temp->tid);
temp = temp->next;
}
}
}
void allocateThreadStack(void** basePtr, void** offsetPtr)
{
*basePtr = malloc(4096);
*offsetPtr = *basePtr + 4096;
}
void initThreadLib()
{
os_thread.tid = 0;
qthread_attr_init(&os_thread.detached);
os_thread.status = 2;
os_thread.prev = NULL;
os_thread.next = NULL;
os_thread.exitStatus = NULL;
allocateThreadStack(&os_thread.basePtr, &os_thread.offsetPtr);
os_thread.offsetPtr = setup_stack(os_thread.offsetPtr, NULL, NULL, NULL);
activeThreadList = tail = &os_thread;
}
/* a thread can exit by either returning from its main function or
* calling qthread_exit(), so you should probably use a dummy start
* function that calls the real start function and then calls
* qthread_exit after it returns.
*/
/* qthread_create - create a new thread and add it to the active list
*/
int qthread_create(qthread_t *thread, qthread_attr_t *attr, qthread_func_ptr_t start, void *arg)
{
if(activeThreadList == NULL)
{
initThreadLib();
}
*thread = (qthread_t)malloc(sizeof(struct qthread));
(*thread)->tid = getNextTID();
(*thread)->prev = NULL;
(*thread)->basePtr = malloc(4096);
(*thread)->offsetPtr = (*thread)->basePtr + 4096;
qthread_attr_init(&(*thread)->detached);
(*thread)->status = 1;
(*thread)->exitStatus = NULL;
(*thread)->offsetPtr = setup_stack((*thread)->offsetPtr, wrapper, start, arg);
(*thread)->wakeupTime = 0;
(*thread)->next = activeThreadList;
activeThreadList->prev = *thread;
activeThreadList = activeThreadList->prev;
qthread_yield();
return 0;
}
/* 'attr' - mutexes are non-recursive, non-debugging, and
* non-any-other-POSIX-feature.
*/
int qthread_mutex_init(qthread_mutex_t *mutex, qthread_mutexattr_t *attr)
{
mutex->state = 0;
return 0;
}
int qthread_mutex_destroy(qthread_mutex_t *mutex)
{
if(mutex != NULL)
{
mutex->state = 0;
free(mutex);
}
return 0;
}
/* qthread_mutex_lock/unlock
*/
int qthread_mutex_lock(qthread_mutex_t *mutex)
{
while(mutex->state)
{
qthread_usleep(1);
}
mutex->state = 1;
return 0;
}
int qthread_mutex_unlock(qthread_mutex_t *mutex)
{
mutex->state = 0;
return 0;
}
/* qthread_cond_init/destroy - initialize a condition variable. Again
* we ignore 'attr'.
*/
int qthread_cond_init(qthread_cond_t *cond, qthread_condattr_t *attr)
{
cond->waitingList = NULL;
return 0;
}
int qthread_cond_destroy(qthread_cond_t *cond)
{
if(cond != NULL)
{
qthread_cond_broadcast(cond);
}
return 0;
}
int isThreadInWaitingList(qthread_cond_t *cond, long toBeSearched)
{
struct qthreadList *iterator = cond->waitingList;
while(iterator != NULL)
{
if(iterator->thread->tid == toBeSearched)
{
return 1;
}
iterator = iterator->next;
}
return 0;
}
/* qthread_cond_wait - unlock the mutex and wait on 'cond' until
* signalled; lock the mutex again before returning.
*/
int qthread_cond_wait(qthread_cond_t *cond, qthread_mutex_t *mutex)
{
qthread_mutex_unlock(mutex);
if(!isThreadInWaitingList(cond, current->tid))
{
struct qthreadList *node = (struct qthreadList*)malloc(sizeof(struct qthreadList));
node->thread = current;
if(cond->waitingList == NULL)
{
node->next = NULL;
}
else
{
node->next = cond->waitingList;
}
cond->waitingList = node;
}
qthread_usleep(1);
qthread_mutex_lock(mutex);
return 0;
}
/* qthread_cond_signal/broadcast - wake one/all threads waiting on a
* condition variable. Not an error if no threads are waiting.
*/
int qthread_cond_signal(qthread_cond_t *cond)
{
if(cond->waitingList != NULL)
{
struct qthreadList *toBeFreed = NULL;
if(cond->waitingList->thread->tid == current->tid)
{
toBeFreed = cond->waitingList;
cond->waitingList = cond->waitingList->next;
}
else
{
struct qthreadList *iterator = cond->waitingList->next;
struct qthreadList *prev = cond->waitingList;
while(iterator != NULL)
{
if(iterator->thread->tid == current->tid)
{
toBeFreed = iterator;
prev->next = iterator->next;
toBeFreed->next = NULL;
break;
}
prev = iterator;
iterator = iterator->next;
}
}
free(toBeFreed);
}
return 0;
}
int qthread_cond_broadcast(qthread_cond_t *cond)
{
if(cond->waitingList != NULL)
{
while(cond->waitingList != NULL)
{
qthread_cond_signal(cond);
}
}
return 0;
}
/* POSIX replacement API. These are all the functions (well, the ones
* used by the sample application) that might block.
*
* If there are no runnable threads, your scheduler needs to block
* waiting for one of these blocking functions to return. You should
* probably do this using the select() system call, indicating all the
* file descriptors that threads are blocked on, and with a timeout
* for the earliest thread waiting in qthread_usleep()
*/
/* qthread_usleep - yield to next runnable thread, making arrangements
* to be put back on the active list after 'usecs' timeout.
*/
int qthread_usleep(long int usecs)
{
current->wakeupTime = gettime() + usecs;
qthread_yield();
return 0;
}
/* make sure that the file descriptor is in non-blocking mode, try to
* read from it, if you get -1 / EAGAIN then add it to the list of
* file descriptors to go in the big scheduling 'select()' and switch
* to another thread.
*/
ssize_t qthread_read(int sockfd, void *buf, size_t len)
{
/* set non-blocking mode every time. If we added some more
* wrappers we could set non-blocking mode from the beginning, but
* this is a lot simpler (if less efficient)
*/
int tmp = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, tmp | O_NONBLOCK);
ssize_t buf_len;
buf_len = read(sockfd, (char*)buf, len);
if(atoi((char*)buf) == -1)
{
qthread_usleep(1);
{
else
{
puts((char*)buf);
}
return buf_len;
}
/* like read - make sure the descriptor is in non-blocking mode, check
* if if there's anything there - if so, return it, otherwise save fd
* and switch to another thread. Note that accept() counts as a 'read'
* for the select call.
*/
int qthread_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
//int tmp = fcntl(sockfd, F_GETFL, 0);
//fcntl(sockfd, F_SETFL, tmp | O_NONBLOCK);
int new_fd = accept(sockfd, addr, addrlen);
//printf("new fd: %d: \n", new_fd);
return new_fd;
}
/* Like read, again. Note that this is an output, rather than an input
* - it can block if the network is slow, although it's not likely to
* in most of our testing.
*/
ssize_t qthread_write(int sockfd, const void *buf, size_t len)
{
int tmp = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, tmp | O_NONBLOCK);
//ssize_t buf_len = write(sockfd, (char*)buf, len);
//qthread_usleep(1);
ssize_t bytes_sent;
//bytes_sent = send(sockfd, buf, len, 0);
bytes_sent = write(sockfd, buf, len);
return bytes_sent;
}
<file_sep>/qthread.h
/*
* file: qthread.h
* description: interface definitions for CS7600 Pthreads assignment
*
* <NAME>, Northeastern CCIS, 2013
* $Id: $
*/
#ifndef __QTHREAD_H__
#define __QTHREAD_H__
#include <sys/types.h>
#include <sys/select.h>
#include <sys/socket.h>
/* function pointer w/ signature 'void *f(void*)'
*/
typedef void *(*qthread_func_ptr_t)(void*);
/* forward definitions. Note that the full structure definition isn't
* needed outside of qthread.c, as no other code looks inside the
* structures. (so define the contents of these structures at the top
* of qthread.c)
*/
struct qthread;
struct qthread_mutex;
struct qthread_cond;
struct qthreadList;
/* You are free to change these type definitions, but the ones
* provided can work fairly well.
*/
typedef int qthread_attr_t; /* need to support detachstate */
typedef struct qthread *qthread_t;
typedef void qthread_mutexattr_t; /* no mutex attributes needed */
typedef struct qthread_mutex qthread_mutex_t;
typedef void qthread_condattr_t; /* no cond attributes needed */
typedef struct qthread_cond qthread_cond_t;
int qthread_yield(void);
int qthread_attr_init(qthread_attr_t *attr);
int qthread_attr_setdetachstate(qthread_attr_t *attr, int detachstate);
int qthread_create(qthread_t *thread, qthread_attr_t *attr,
qthread_func_ptr_t start, void *arg);
int qthread_join(qthread_t thread, void **retval);
void qthread_exit(void *val);
int qthread_cancel(qthread_t thread);
#define QTHREAD_CANCELLED ((void*)2)
int qthread_mutex_init(qthread_mutex_t *mutex, qthread_mutexattr_t *attr);
int qthread_mutex_destroy(qthread_mutex_t *mutex);
int qthread_mutex_lock(qthread_mutex_t *mutex);
int qthread_mutex_unlock(qthread_mutex_t *mutex);
int qthread_cond_init(qthread_cond_t *cond, qthread_condattr_t *attr);
int qthread_cond_destroy(qthread_cond_t *cond);
int qthread_cond_wait(qthread_cond_t *cond, qthread_mutex_t *mutex);
int qthread_cond_signal(qthread_cond_t *cond);
int qthread_cond_broadcast(qthread_cond_t *cond);
/* POSIX replacement API. Not general, but enough to run a
* multi-threaded webserver.
*/
int qthread_usleep(long int usecs);
ssize_t qthread_read(int fd, void *buf, size_t len);
struct sockaddr;
int qthread_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
ssize_t qthread_write(int fd, const void *buf, size_t len);
struct qthread {
/*
* note - you can't use 'qthread_t*' in this definition, due to C
* limitations.
* use 'struct qthread *' instead, which means the same thing:
* struct qthread *next;
*/
long tid;
qthread_t prev;
qthread_t next;
void* basePtr;
void* offsetPtr;
qthread_attr_t detached;
short status;
double wakeupTime;
void* exitStatus;
short condVarWaitStatus;
};
struct qthread_mutex {
short state;
};
/* Condition variable
*/
struct qthread_cond {
struct qthreadList *waitingList;
};
struct qthreadList {
qthread_t thread;
struct qthreadList *next;
};
#endif /* __QTHREAD_H__ */
<file_sep>/philosopher.c
/*
* file: philosopher.c
* description: Dining philosophers, from CS 5600
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include "qthread.h"
int nforks;
qthread_mutex_t m;
qthread_cond_t C[10];
int fork_in_use[10];
double t0;
static void init_time(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
t0 = tv.tv_sec + tv.tv_usec/1.0e6;
}
/* timestamp - time since start - NOT adjusted for speedup
*/
double timestamp(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
double t1 = tv.tv_sec + tv.tv_usec/1.0e6;
return (t1-t0);
}
/* sleep_exp(T) - sleep for exp. dist. time with mean 10T msecs
* unlocks mutex while sleeping if provided.
*/
void sleep_exp(double T)
{
double t = -1 * T * log(drand48()); /* sleep time */
if (t > T*10)
t = T*10;
if (t < 0.5)
t = 0.5;
qthread_usleep((int)(1 * t));
}
/* get_forks() method - called before a philospher starts eating.
* 'i' identifies the philosopher 0..N-1
*/
void get_forks(int i)
{
int left = i, right = (i+1) % nforks;
qthread_mutex_lock(&m);
printf("DEBUG: %f philosopher %d tries for left fork\n", timestamp(), i);
if (fork_in_use[left])
qthread_cond_wait(&C[left], &m);
printf("DEBUG: %f philosopher %d gets left fork\n", timestamp(), i);
fork_in_use[left] = 1;
printf("DEBUG: %f philosopher %d tries for right fork\n", timestamp(), i);
if (fork_in_use[right])
qthread_cond_wait(&C[right], &m);
printf("DEBUG: %f philosopher %d gets left fork\n", timestamp(), i);
fork_in_use[right] = 1;
qthread_mutex_unlock(&m);
}
/* release_forks() - called when a philospher is done eating.
* 'i' identifies the philosopher 0..N-1
*/
void release_forks(int i)
{
int left = i, right = (i+1) % nforks;
qthread_mutex_lock(&m);
printf("DEBUG: %f philosopher %d puts down both forks\n", timestamp(), i);
fork_in_use[left] = 0;
qthread_cond_signal(&C[left]);
fork_in_use[right] = 0;
qthread_cond_signal(&C[right]);
qthread_mutex_unlock(&m);
}
/* the philosopher thread function - create N threads, each of which calls
* this function with its philosopher number 0..N-1
*/
void *philosopher_thread(void *context)
{
int philosopher_num = (int)context; /* hack... */
while (1) {
sleep_exp(4.0);
get_forks(philosopher_num);
sleep_exp(2.5);
release_forks(philosopher_num);
}
return 0;
}
/* handler - ^C will break out of usleep() below; set flag to stop
* loop
*/
static int done;
static void handler(int sig)
{
signal(SIGINT, SIG_DFL);
done = 1;
}
/* wait until ^C
*/
void wait_until_done(void)
{
while (!done)
qthread_usleep(1);
}
int main(int argc, char **argv)
{
int i;
qthread_t t;
signal(SIGINT, handler);
init_time();
nforks = 4;
qthread_mutex_init(&m, NULL);
for (i = 0; i < nforks; i++)
qthread_cond_init(&C[i], NULL);
for (i = 0; i < nforks; i++)
qthread_create(&t, NULL, philosopher_thread, (void*)i);
wait_until_done();
return 0;
}
<file_sep>/test1.c
/*
* file: test1.c
* description: test file for qthreads (homework 1)
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include "qthread.h"
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h> /* for socket system calls */
#include <arpa/inet.h> /* for socket system calls (bind) */
typedef struct qthread_mutex qthread_mutex_t;
/* 1. create and join. Create N threads, which don't do anything
* except return a value. (and possibly print something) Call
* qthread_join() to wait for each of them.
*/
void *f1(void *arg) { return arg; }
void test1(void)
{
qthread_t t[10];
int i, j;
for (i = 0; i < 10; i++)
qthread_create(&t[i], NULL, f1, (void*)i);
for (i = 0; i < 10; i++) {
qthread_join(t[i], (void**)&j);
assert(i == j);
}
printf("test 1 OK\n");
}
/* 2. mutex and sleep.
* initialize a mutex
* Create thread 1, which locks a mutex and goes to sleep for a
* second or two using qthread_usleep.
* (you can wait for this by calling qthread_yield repeatedly,
* waiting for thread 1 to set a global variable)
* threads 2..N try to lock the mutex
* after thread 1 wakes up it releases the mutex;
* threads 2..N each release the mutex after getting it.
* run with N=2,3,4
*/
int t1rdy;
qthread_mutex_t m;
void *f2(void *v)
{
qthread_mutex_lock(&m);
t1rdy = 1;
qthread_usleep(1);
qthread_mutex_unlock(&m);
return 0;
}
void *f3(void *v)
{
qthread_mutex_lock(&m);
printf("f3\n");
qthread_mutex_unlock(&m);
return 0;
}
void test2(void)
{
qthread_t t0, t[10];
int i;
qthread_mutex_init(&m, NULL);
qthread_create(&t0, NULL, f2, NULL);
while (!t1rdy)
qthread_yield();
for (i = 0; i < 4; i++)
qthread_create(&t[i], NULL, f3, NULL);
void *val;
qthread_join(t0, &val);
for (i = 0; i < 4; i++)
qthread_join(t[i], &val);
printf("test 2 done\n");
}
int N = 10;
int var = 0;
qthread_cond_t t1;
void *f4(void *v) {
qthread_mutex_lock(&m);
t1rdy++;
printf("count: %d\n", t1rdy);
if(t1rdy == N)
var = 1;
while(!var)
qthread_cond_wait(&t1, &m);
qthread_cond_signal(&t1);
printf("count: %d\n", t1rdy);
t1rdy--;
qthread_mutex_unlock(&m);
}
void *f5(void *v) {
char a[100];
int read_fd = *(int*)v;
qthread_read(read_fd,(void*)a,100);
}
void *f6(void *v) {
qthread_usleep(0);
int write_fd = *(int*)v;
//srand (10);
int rnm = rand()%10 ;
char buf[100];
//printf("Random: %d: \n", rnm);
if (rnm != 7){
sprintf(buf, "%d", -1);
//printf("String: %s: \n", buf);
qthread_write(write_fd,(void*)buf,100);
}
else{
sprintf(buf,"%d", rnm);
//printf("String: %s: \n", buf);
qthread_write(write_fd,(void*)buf,100);
}
}
int main(int argc, char **argv)
{
/* Here are some suggested tests to implement. You can either run
* them one after another in the program (cleaning up threads
* after each test) or pass a command-line argument indicating
* which test to run.
* This may not be enough tests to fully debug your assignment,
* but it's a good start.
*/
// test1();
// test2();
/* 3. condvar and sleep.
* initialize a condvar and a mutex
* create N threads, each of which locks the mutex, increments a
* global count, and waits on the condvar; after the wait it
* decrements the count and releases the mutex.
* call qthread_yield until count indicates all threads are waiting
* call qthread_signal, qthread_yield until count indicates a
* thread has left. repeat.
*/
/*
t1rdy = 0;
qthread_cond_init(&t1, NULL);
qthread_t t[10];
int i, j;
for (i = 0; i < 10; i++){
qthread_create(&t[i], NULL, f4, NULL);
}
for (i = 0; i < 10; i++) {
qthread_join(t[i], NULL);
}
qthread_cond_destroy(&t1);
printf("Final Count: %d\n", t1rdy);
printf("Test 3 OK\n");
*/
/* 4. read/write
* create a pipe ('int fd[2]; pipe(fd);')
* create 2 threads:
* one sleeps and then writes to the pipe
* one reads from the pipe. [this tests blocking read]
*/
int fd[2];
pipe(fd);
qthread_t f[2];
qthread_create(&f[1], NULL, f6, (void*)&fd[1]);
qthread_create(&f[0], NULL, f5,(void*)&fd[0]);
//qthread_create(&f[1], NULL, f6, (void*)&fd[1]);
qthread_join(f[0], NULL);
qthread_join(f[1], NULL);
close(fd[0]);
close(fd[1]);
/*
unsigned int server_s; // Server socket descriptor
struct sockaddr_in server_addr; // Server Internet address
struct sockaddr_in client_addr; // Client Internet address
struct in_addr client_ip_addr; // Client IP address
int addr_len; // Internet address length
unsigned int client_s;
struct hostent *he;
client_s = socket(AF_INET, SOCK_STREAM, 0);
memset(&server_addr, '0', sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
//inet_pton(AF_INET, INADDR_ANY ,&server_addr.sin_addr);
addr_len = sizeof(server_addr);
connect(client_s,(struct sockaddr *)&server_addr, addr_len);
printf("connection established\n");
char *msg = "GET /README.md";
int len, bytes_sent;
len = strlen(msg);
printf("length of msg: %d\n", len);
//bytes_sent = send(sockfd, msg, len, 0);
//send(sockfd, buf, len, 0);
bytes_sent = qthread_write(client_s, msg, len);
printf("bytes sent: %d\n", bytes_sent);
char buf[100];
int numbytes;
if ((numbytes = recv(client_s, buf, 100-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("client: received '%s'\n",buf);
*/
}
| 189794df6047a2ca3d766bca0f3f539a9352fc6b | [
"C",
"Makefile"
] | 6 | C | apoorvemohan/threads | 7e0ff480c38c6700eea06cd3f9025c94374dbf95 | 6bcf38514fcaeb0d61ed980b93e4aee821eb1a06 |
refs/heads/master | <repo_name>wanghong2013/adonis-bootstrap<file_sep>/app/Controllers/Http/HelloController.js
'use strict'
class HelloController {
// render({request}){
// return `hello ~ ${request.input('name')}`
// }
//请求参数解构并且在视图中显示
render({request,view}){
//得到请求参数中的值
const name = request.input('name');
//视图显示
return view.render('hello',{name}); //显示hello模板,把参数传递给视图给视图在页面中使用
}
}
module.exports = HelloController
| 797f811ad8f6e8b83f2b3f943c61015a8a3d85eb | [
"JavaScript"
] | 1 | JavaScript | wanghong2013/adonis-bootstrap | a7db3267ea42b212130d3c73489277e71b0f9a07 | f2c48913c69dc5119e7ae77f99edf9f944e063ef |
refs/heads/master | <repo_name>IgorSuhorukov/idea-doT<file_sep>/README.md
# [doT](http://olado.github.io/doT/index.html) template plugin for Jetbrains IDEs
IDEA-DOT adds support for [doT](http://olado.github.io/doT/index.html) templates to IDEs based on the Intellij IDEA platform (IntelliJ IDEA, IDEA Community Edition, RubyMine, PhpStorm, WebStorm, PyCharm, AppCode, etc).

[Jetbrains plugin repository page](http://plugins.jetbrains.com/plugin/7327)
## Installing
To install the latest release (and get automatic updates), install this plugin using your IDE's plugin manager:
* In _Settings->Plugins_, choose "Browse repositories". Find "doT" on the list, right-click, then select "Download and Install"
By default, the plugin handles `*.dot` files.
## Release History
* 2013-09-20 v1.0 Work in progress, not yet officially released.
* 2013-12-10 v1.1 Officially released.
* 2014-04-26 v1.4 Refactoring, bug fix.
---
Library submitted by ["webschik" <NAME>](https://www.liqpay.com/api/checkout?data=<KEY>%2B0Lkg0YLQvtCy0LDRgC<KEY>0%3D&signature=hbopmxoSLT553Vm0HqQ1EpKPW9c%3D)
<file_sep>/src/com/webschik/doT/config/DotFoldingOptionsProvider.java
package com.webschik.doT.config;
import com.intellij.application.options.editor.CodeFoldingOptionsProvider;
import com.intellij.openapi.options.BeanConfigurable;
import com.webschik.doT.DotBundle;
public class DotFoldingOptionsProvider
extends BeanConfigurable<DotFoldingOptionsProvider.DotCodeFoldingOptionsBean> implements CodeFoldingOptionsProvider {
@SuppressWarnings ("UnusedDeclaration") // the properties in this class are accessed using reflection by the parent
public static class DotCodeFoldingOptionsBean {
public boolean isAutoCollapseBlocks() {
return DotConfig.isAutoCollapseBlocksEnabled();
}
public void setAutoCollapseBlocks(boolean value) {
DotConfig.setAutoCollapseBlocks(value);
}
}
public DotFoldingOptionsProvider() {
super(new DotCodeFoldingOptionsBean());
checkBox("autoCollapseBlocks", DotBundle.message("doT.pages.folding.auto.collapse.blocks"));
}
}<file_sep>/src/com/webschik/doT/parsing/DotToken.java
package com.webschik.doT.parsing;
import com.intellij.psi.tree.IElementType;
public class DotToken {
private IElementType type;
public int tokenStart;
public int tokenEnd;
DotToken(IElementType type, int tokenStart, int tokenEnd) {
this.type = type;
this.tokenStart = tokenStart;
this.tokenEnd = tokenEnd;
}
public IElementType getType() {
return type;
}
public void setType(IElementType type) {
this.type = type;
}
public int getTokenStart() {
return tokenStart;
}
public int getTokenEnd() {
return tokenEnd;
}
public void increment() {
tokenEnd++;
}
public void invalidate(IElementType errorType) {
setType(errorType);
}
public String toString() {
return type + "[" + tokenStart + ":" + tokenEnd + "]";
}
}
<file_sep>/resources/messages/DotBundle.properties
doT.files.file.type.description=doT
doT.page.colors.descriptor.identifiers.key=Identifiers
doT.page.colors.descriptor.comments.key=Comments
doT.page.colors.descriptor.operators.key=Operators
doT.page.colors.descriptor.values.key=Primitives
doT.page.colors.descriptor.strings.key=Strings
doT.page.colors.descriptor.data.prefix.key=Data Prefix
doT.page.colors.descriptor.data.key=Data
doT.page.colors.descriptor.escape.key=Escape Character
doT.parsing.invalid=Invalid
doT.parsing.expected.path.or.data=Expected a path or @data
doT.parsing.expected.parameter=Expected a parameter
doT.parsing.expected.hash=Expected a hash
doT.parsing.element.expected.content=Expected Template Content
doT.parsing.element.expected.outer_element_type=Expected doT Content
doT.parsing.element.expected.white_space=Expected White Space
doT.parsing.element.expected.comment=Expected a Comment
doT.parsing.element.expected.open=Expected Open "{{"
doT.parsing.element.expected.open_block=Expected Open Block "{{#"
doT.parsing.element.expected.open_partial=Expected Open Partial "{{>"
doT.parsing.element.expected.open_end_block=Expected Open End Block "{{/"
doT.parsing.element.expected.open_inverse=Expected Open Inverse "{{^"
doT.parsing.element.expected.open_unescaped=Expected Open Unescaped "{{{"
doT.parsing.element.expected.equals=Expected Equals "="
doT.parsing.element.expected.id=Expected an ID
doT.parsing.element.expected.partial.name=Expected partial name
doT.parsing.element.expected.data=Expected a Data identifier
doT.parsing.element.expected.separator=Expected a Separator "/" or "."
doT.parsing.element.expected.close=Expected Close "}}"
doT.parsing.element.expected.boolean=Expected "true" or "false"
doT.parsing.element.expected.integer=Expected an Integer
doT.parsing.element.expected.string=Expected a String
doT.parsing.element.expected.invalid=Unexpected token
doT.pages.options.generate.closing.tag=&Automatically insert closing tag
doT.pages.options.formatter=&Enable formatting
doT.pages.options.title=doT
doT.pages.folding.auto.collapse.blocks=doT blocks
doT.page.options.commenter.language=&Language for comments\:
doT.page.options.commenter.language.tooltip=Controls which language's comment syntax to use for "Comment with Block Comment" and "Comment with Line Comment" actions
doT.parsing.comment.unclosed=Unclosed comment
doT.block.mismatch.intention.rename.open=Change block start ''{0}'' to ''{1}''
doT.block.mismatch.intention.rename.close=Change block end ''{0}'' to ''{1}''
doT.block.mismatch.inspection.open.block=''{0}'' does not match ''{1}'' from block end
doT.block.mismatch.inspection.close.block=''{1}'' does not match ''{0}'' from block start
doT.block.mismatch.inspection.missing.end.block=''{0}'' block not closed
doT.block.mismatch.inspection.missing.start.block=No block start for ''{0}''<file_sep>/src/com/webschik/doT/parsing/DotTokenTypesBySymbol.java
package com.webschik.doT.parsing;
import com.intellij.psi.tree.IElementType;
import java.util.HashMap;
public class DotTokenTypesBySymbol {
public static final HashMap<Character, IElementType> types = new HashMap<Character, IElementType>();
public static final HashMap<Character, IElementType> nonClosesTypes = new HashMap<Character, IElementType>();
static {
types.put('!', DotTokenTypes.OPEN_ESCAPED);
types.put('=', DotTokenTypes.OPEN_UNESCAPED);
types.put('?', DotTokenTypes.CONDITIONAL);
types.put('~', DotTokenTypes.ITERATION);
types.put('#', DotTokenTypes.OPEN_PARTIAL);
nonClosesTypes.put('!', DotTokenTypes.OPEN_ESCAPED);
nonClosesTypes.put('=', DotTokenTypes.OPEN_UNESCAPED);
nonClosesTypes.put('#', DotTokenTypes.OPEN_PARTIAL);
}
}
| 9a53d0bf917cc886f27ce83b969315c5c7188c9d | [
"Markdown",
"Java",
"INI"
] | 5 | Markdown | IgorSuhorukov/idea-doT | 7403660e661c48d60b133ce33c8737aa65795728 | 027df9eed317129760fbc1996097abd7eb29669b |
refs/heads/main | <repo_name>mevlanaayas/foci<file_sep>/Assets/Scripts/CenterPoint.cs
using System;
using UnityEngine;
[Obsolete("Class is deprecated, please use Ellipse instead.")]
public class CenterPoint : MonoBehaviour
{
public float radius = 1;
public GameObject point;
public float targetTime = 1.0f;
private float _targetTime;
private int _currentAngle;
public int maxAngle = 360;
private void Start()
{
_targetTime = targetTime;
}
private void Update()
{
targetTime -= Time.deltaTime;
if (targetTime <= 0.0f)
{
TimerCallback();
}
}
private void TimerCallback()
{
if (_currentAngle == maxAngle)
{
return;
}
_currentAngle++;
targetTime = _targetTime;
transform.Rotate(0f, 1f, 0f);
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * radius, Color.white);
var position = transform.position + transform.TransformDirection(Vector3.forward) * radius;
Instantiate(point, position, Quaternion.identity);
}
}<file_sep>/README.md
"# foci"
<file_sep>/Assets/Scripts/GeometryManager.cs
using UnityEngine;
public class GeometryManager : MonoBehaviour
{
public GameObject particle;
private Camera _camera;
private void Start()
{
_camera = Camera.main;
}
private void Update()
{
if (!Input.GetMouseButtonUp(0)) return;
var ray = _camera.ScreenPointToRay(Input.mousePosition);
if (!Physics.Raycast(ray, out var hit)) return;
Instantiate(particle, hit.point, Quaternion.identity);
}
}<file_sep>/Assets/Scripts/BallManager.cs
using UnityEngine;
public class BallManager : MonoBehaviour
{
public GameObject ball;
private Camera _camera;
private void Start()
{
_camera = Camera.main;
}
private void Update()
{
if (!Input.GetMouseButtonUp(1)) return;
var ray = _camera.ScreenPointToRay(Input.mousePosition);
if (!Physics.Raycast(ray, out var hit)) return;
Instantiate(ball, hit.point, Quaternion.identity);
}
}<file_sep>/Assets/Scripts/Ellipse.cs
using UnityEngine;
public class Ellipse : MonoBehaviour
{
[Range(36, 3600)] public int pointCount = 360;
public float height = 3;
public float width = 5;
public GameObject pointPrefab;
private int _currentPoint;
private bool _fociCalculated;
private void Update()
{
if (_currentPoint == pointCount)
{
if (!_fociCalculated)
{
CreateFoci();
}
return;
}
CreatePoint();
}
private void CreatePoint()
{
var angle = (float) _currentPoint / pointCount * 360 * Mathf.Deg2Rad;
var x = Mathf.Sin(angle) * height;
var y = transform.position.y;
var z = Mathf.Cos(angle) * width;
var target = new Vector3(x, y, z);
_currentPoint++;
Instantiate(pointPrefab, target + transform.position, Quaternion.identity, transform);
}
private void CreateFoci()
{
// TODO: make foci points property on ellipse object
var fociDistance = Mathf.Sqrt(Mathf.Abs(width * width - height * height));
var transformPosition = transform.position;
var firstFociPosition =
new Vector3(transformPosition.x, transformPosition.y, transformPosition.z + fociDistance);
Instantiate(pointPrefab, firstFociPosition, Quaternion.identity);
var secondFociPosition =
new Vector3(transformPosition.x, transformPosition.y, transformPosition.z - fociDistance);
Instantiate(pointPrefab, secondFociPosition, Quaternion.identity);
_fociCalculated = true;
}
}<file_sep>/Assets/Scripts/Ball.cs
using UnityEngine;
public class Ball : MonoBehaviour
{
public float xPush = 10.0f;
public float zPush = 2.0f;
private void Start()
{
GetComponent<Rigidbody>().velocity = new Vector3(xPush, 0.0f, zPush);
}
} | 299fcd372e7708852d91e09a079be24b36b01f25 | [
"Markdown",
"C#"
] | 6 | C# | mevlanaayas/foci | 840f64cfc1c6a5e27783ed42c731916208998bad | ef1d2faaed65daf972fc5e9b4a126ed7bc63f23f |
refs/heads/master | <file_sep>package Principal;
import javafx.application.Application;
import javafx.stage.Stage;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
public class MainFX extends Application
{
private AnchorPane Calc;
@Override
public void start(Stage primaryStage) throws IOException
{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainFX.class.getResource("/Interfaces/Calculadora.fxml"));
Calc = (AnchorPane) loader.load();
Scene scene = new Scene(Calc);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
<file_sep># AulaSegundaXML
Recriação do projeto da Aula de Segunda utilizando XML e Eclipse.
<file_sep>package Interfaces;
import javafx.fxml.FXML;
import javafx.scene.control.*;
public class Controller
{
int n=0;
float resultado=0;
String calculo="", conta=null, ult=null;
@FXML
Label LblCon, LblResul;
@FXML
Button Btn0, Btn1, Btn2, Btn3, Btn4, Btn6, Btn7, Btn8, Btn9, BtnMais, BtnEqual, BtnMenos, BtnVezes, BtnDividir, BtnOff, BtnApagar;
public void Zero()
{
n=0;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="0";
LblCon.setText(conta);
}
public void Um()
{
n=1;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="1";
LblCon.setText(conta);
}
public void Dois()
{
n=2;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="2";
LblCon.setText(conta);
}
public void Tres()
{
n=3;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="3";
LblCon.setText(conta);
}
public void Quatro()
{
n=4;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="4";
LblCon.setText(conta);
}
public void Cinco()
{
n=5;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="5";
LblCon.setText(conta);
}
public void Seis()
{
n=6;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="6";
LblCon.setText(conta);
}
public void Sete()
{
n=7;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="7";
LblCon.setText(conta);
}
public void Oito()
{
n=8;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="8";
LblCon.setText(conta);
}
public void Nove()
{
n=9;
if(conta==null)
{
conta=String.valueOf(n);
LblResul.setText(String.valueOf(n));
}
else
{
conta=conta+String.valueOf(n);
switch (ult)
{
case "+":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())+n));
case "-":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())-n));
case "*":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())*n));
case "/":
LblResul.setText(String.valueOf(Float.parseFloat(LblResul.getText())/n));
}
}
ult="9";
LblCon.setText(conta);
}
public void Igual()
{
if(conta!=null & (ult=="+" & ult=="-" & ult=="*" & ult=="/"))
{
conta=conta+("=");
LblCon.setText(conta);
LblResul.setText(calculo);
}
}
public void Mais()
{
if(conta!=null & (ult!="+" & ult!="-" & ult!="*" & ult!="/"))
{
conta=conta+("+");
ult="+";
LblCon.setText(conta);
}
}
public void Menos()
{
if(conta!=null & (ult=="+" & ult=="-" & ult=="*" & ult=="/"))
{
conta=conta+("-");
ult="-";
LblCon.setText(conta);
}
}
public void Vezes()
{
if(conta!=null & (ult=="+" & ult=="-" & ult=="*" & ult=="/"))
{
conta=conta+("*");
ult="*";
LblCon.setText(conta);
}
}
public void Dividir()
{
if(conta!=null & (ult=="+" & ult=="-" & ult=="*" & ult=="/"))
{
conta=conta+("/");
ult="/";
LblCon.setText(conta);
}
}
public void Apagar()
{
}
public void Off()
{
}
} | de0767d207b6ec53fdd1bb50d8a97a67f28c0521 | [
"Markdown",
"Java"
] | 3 | Java | Sinxmartes/AulaSegundaXML | 2a690fcaccaa645a1984febc762338d7d6119227 | d0fbe1d4adb8a5392e6ad913e9f89cb4c83b42c7 |
refs/heads/master | <repo_name>LimJeaHwan/Coffee<file_sep>/Coffee/src/main/java/com/yuhan/dto/LoginCommand.java
package com.yuhan.dto;
import javax.persistence.Entity;
import javax.validation.constraints.NotEmpty;
@Entity
public class LoginCommand {
@NotEmpty(message="아이디를 입력해주세요.")
private String id;
@NotEmpty(message="비밀번호를 입력해주세요.")
private String pw;
private boolean remeberId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public boolean isRemeberId() {
return remeberId;
}
public void setRemeberId(boolean remeberId) {
this.remeberId = remeberId;
}
}
<file_sep>/Coffee/src/main/java/com/yuhan/dao/Member_daoImpl.java
package com.yuhan.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.yuhan.dto.Member;
import com.yuhan.dto.Member_dto;
import com.yuhan.dto.RegisterRequest;
@Repository
public class Member_daoImpl extends AbstractDAO implements Member_dao {
@Autowired
private SqlSession sqlSession;
private static String namespace="MemberMapper";
public List<Member> list() throws Exception{
return sqlSession.selectList(namespace+".member_list");
}
public void insertMember(RegisterRequest regReq) throws Exception {
sqlSession.insert(namespace+".register",regReq);
}
@Override
public Member_dto selectByEmail(String email) throws Exception {
return sqlSession.selectOne(namespace+".selectByEmail",email);
}
@Override
public Member_dto selectById(String id) throws Exception {
return sqlSession.selectOne(namespace+".selectById",id);
}
}
<file_sep>/Coffee/src/main/java/com/yuhan/dto/RegisterRequest.java
package com.yuhan.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Entity
public class RegisterRequest{
@Column
@Pattern(regexp="\\w{4,15}",message="아이디를 4~15자로 입력하세요.")
private String m_id;
@Column
@Pattern(regexp="\\S{2,8}", message="이름을 공백없이 2~6자로 입력해주세요.")
private String m_name;
@Column
private String m_email;
@Column
private String m_addr;
@Column
private String m_pwd;
@Column
private String check_m_pwd;
//비밀번호 확인
public boolean isPwEqualToCheckpwd() {
return m_pwd.equals(check_m_pwd);
}
public String getM_name() {
return m_name;
}
public void setM_name(String m_name) {
this.m_name = m_name;
}
public String getM_email() {
return m_email;
}
public void setM_email(String m_email) {
this.m_email = m_email;
}
public RegisterRequest() {
}
public String getM_id() {
return m_id;
}
public void setM_id(String m_id) {
this.m_id = m_id;
}
public String getM_addr() {
return m_addr;
}
public void setM_addr(String m_addr) {
this.m_addr = m_addr;
}
public String getM_pwd() {
return m_pwd;
}
public void setM_pwd(String m_pwd) {
this.m_pwd = m_pwd;
}
public String getCheck_m_pwd() {
return check_m_pwd;
}
public void setCheck_m_pwd(String check_m_pwd) {
this.check_m_pwd = check_m_pwd;
}
}
<file_sep>/Coffee/target/classes/ApplicationMessage.properties
common.cannotSetupAdmin = \uAD00\uB9AC\uC790\uB97C \uC124\uC815\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
common.homeWelcome = \uBA54\uC778\uD654\uBA74
common.joinMemberSuccess = {0}\uB2D8, \uAC00\uC785\uC744 \uCD95\uD558\uB4DC\uB9BD\uB2C8\uB2E4.
common.listEmpty = \uB370\uC774\uD130\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.
common.processSuccess = \uCC98\uB9AC\uAC00 \uC644\uB8CC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.
header.home = \uD648
header.joinMember = \uD68C\uC6D0\uAC00\uC785
header.login = \uB85C\uADF8\uC778
header.logout = \uB85C\uADF8\uC544\uC6C3
menu.board.admin = \uD68C\uC6D0\uAC8C\uC2DC\uD310\uAD00\uB9AC
menu.board.member = \uD68C\uC6D0\uAC8C\uC2DC\uD310
menu.notice.admin = \uACF5\uC9C0\uC0AC\uD56D\uAD00\uB9AC
menu.notice.member = \uC18C\uC2DD
menu.user.admin = \uD68C\uC6D0\uAD00\uB9AC
menu.menu = \uBA54\uB274
menu.intro = \uCE74\uD398\uC18C\uAC1C
menu.shop = \uB9E4\uC7A5
join.id = \uC544\uC774\uB514
join.pwd = \<PASSWORD>
join.sex = \uC131\uBCC4
join.sex.male=\uB0A8\uC790
join.sex.female=\uC5EC\uC790
join.addr = \uC8FC\uC18C
join.phone = \uD578\uB4DC\uD3F0\uBC88\uD638<file_sep>/Coffee/src/main/java/com/yuhan/coffee/controller/MemberController.java
package com.yuhan.coffee.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.model.AlreadyExistsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.yuhan.coffee.exception.AlreadyExistingEmailException;
import com.yuhan.coffee.exception.AlreadyExistingIdException;
import com.yuhan.dto.Member;
import com.yuhan.dto.Member_dto;
import com.yuhan.dto.RegisterRequest;
import com.yuhan.service.Member_Service;
import com.yuhan.util.RegisterRequestVaildator;
@Controller
public class MemberController {
@Autowired
private Member_Service member_service;
@Autowired
private PasswordEncoder passwordEncoding;
@RequestMapping("/register/step1")
public String step1() throws Exception
{
return"member/register/step1";
}
@RequestMapping("/register/step2")
public ModelAndView step2(@RequestParam(value="agree", defaultValue="false") Boolean agree) throws Exception {
if(!agree) {
ModelAndView mv = new ModelAndView("member/register/step1");
return mv;
}
ModelAndView mv = new ModelAndView("member/register/step2");
mv.addObject("registerRequest", new RegisterRequest());
return mv;
}
@RequestMapping("/register/step3")
public ModelAndView step3(@Valid RegisterRequest regReq,BindingResult bindingResult) throws Exception
{
//@Valid검증
if(bindingResult.hasErrors()) {
ModelAndView mv = new ModelAndView("member/register/step2");
return mv;
}
boolean check = regReq.isPwEqualToCheckpwd();
if(!check) {
bindingResult.rejectValue("check_m_pwd", "noMatch","비밀번호를 확인해주세요.");
ModelAndView mv = new ModelAndView("member/register/step2");
return mv;
}
try {
String inputPassword = regReq.getM_pwd();
regReq.setM_pwd(passwordEncoding.encode(inputPassword));
member_service.register(regReq);
} catch (AlreadyExistingEmailException e) {
bindingResult.rejectValue("m_email", "duplicate","이미 가입된 이메일입니다.");
ModelAndView mv = new ModelAndView("member/register/step2");
return mv;
}
catch (AlreadyExistingIdException e) {
bindingResult.rejectValue("m_id", "duplicate","이미 가입된 아이디입니다.");
ModelAndView mv = new ModelAndView("member/register/step2");
return mv;
}
ModelAndView mv = new ModelAndView("member/register/step3");
return mv;
}
@RequestMapping("/member/admin/list")
public ModelAndView list() throws Exception{
List<Member> list = member_service.list();
ModelAndView mv = new ModelAndView("member/admin/list");
mv.addObject("list", list);
return mv;
}
}
<file_sep>/Coffee/src/main/java/com/yuhan/dao/Member_dao.java
package com.yuhan.dao;
import java.util.List;
import com.yuhan.dto.Member;
import com.yuhan.dto.Member_dto;
import com.yuhan.dto.RegisterRequest;
public interface Member_dao{
//회원가입
public void insertMember(RegisterRequest regReq) throws Exception;
//이메일 선택
public Member_dto selectByEmail(String email) throws Exception;
//아이디 선택
public Member_dto selectById(String id) throws Exception;
//회원조회
public List<Member> list() throws Exception;
}
<file_sep>/Coffee/src/main/java/com/yuhan/security/CustomLoginSuccessHandler.java
package com.yuhan.security;
public class CustomLoginSuccessHandler {
}
<file_sep>/Coffee/src/main/java/com/yuhan/security/CustomAccessDeniedHandler.java
package com.yuhan.security;
public class CustomAccessDeniedHandler {
}
<file_sep>/Coffee/src/main/java/com/yuhan/service/Member_Service.java
package com.yuhan.service;
import java.util.List;
import com.yuhan.dto.Member;
import com.yuhan.dto.RegisterRequest;
public interface Member_Service {
//회원 가입
public void register(RegisterRequest regReq) throws Exception;
//회원 조회
public List<Member> list() throws Exception;
}
| 57965e5834dd0c1376d34eec7b08801ac243e1cf | [
"Java",
"INI"
] | 9 | Java | LimJeaHwan/Coffee | 75f44d48d715ef3f624b4fd37d9eadd2a8488cbb | a4e7381d798325960e75aff16ecfedc16e65de2c |
refs/heads/master | <repo_name>V4n0m/spiderSomeSite<file_sep>/spider2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import urllib2
import csv
import os
import sys
import threading
from bs4 import BeautifulSoup
#gridView_sgdw$ctl23$ctl00$ctl05=4
#http://172.16.17.32/SZConsProTradingCenterINWPage/Web_Cxzq/Cxzq_Sgdw_Jbxx.aspx?qyID=32050100000002504
class Spider:
conn = None
header = {"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:43.0) Gecko/20100101 Firefox/43.0"}
data = None
numurl = "http://www.szcetc.com.cn/SZConsProTradingCenterINWPage/Web_Cxzq/Cxzq_Sgdw_List.aspx"
def __init__(self):
with open('/Users/apple/code/test/post.conf') as f:
self.data = f.read()
def post(self, num):
datas = "{0}gridView_sgdw$ctl23$ctl00$ctl05={1}".format(self.data, num)
req = urllib2.Request(self.numurl, data=datas)
req.add_header('User-Agent', self.header)
html = urllib2.urlopen(req)
result = html.read().decode('utf-8')
html.close()
return result
def get(self, url):
print "[!] spider {0}".format(url)
req = urllib2.Request(url)
req.add_header('User-Agent', self.header)
result = urllib2.urlopen(req).read()
return result.decode('utf-8')
def GetPageList(self, num):
soup = BeautifulSoup(self.post(num), "lxml")
result = []
for line in soup.find_all('a'):
if line['href'].startswith('http://'):
result.append(line['href'].replace('View', 'Jbxx'))
print "[!]Get Page List ok! "
return result
def SoupHtml(self, html):
soup = BeautifulSoup(html, "lxml")
spans = soup.find_all("span")
label = soup.find("label", id="DBText34").text
text = []
for sp in spans:
text.append(sp.text.encode('utf-8'))
text.append(label.encode('utf-8'))
print "[*] soup html complete! "
self.Write2Excel(text)
def Gethtml(self, result):
for line in result:
html = self.SoupHtml(self.get(line))
def Write2Excel(self, rows):
csvfile = csv.writer(file('/Users/apple/code/test/result.csv', 'ab'))
csvfile.writerow(rows)
print "[*] wirte csv file ok ! \n"
def main(self):
for num in range(1, 274):
lists = self.GetPageList(num)
self.Gethtml(lists)
break
if __name__ == '__main__':
a = Spider()
sys.exit(a.main()) | 55640e5ffb59b1ab1b554598d8b89e7658cee10b | [
"Python"
] | 1 | Python | V4n0m/spiderSomeSite | 62c70c86533cd4f87e23dbb62c04e5962b6870a6 | a837255cac80b022e469ded8c5e743e1be854060 |
refs/heads/main | <repo_name>ivanrj7j/CSharp-Classes-Example<file_sep>/Program.cs
using System;
namespace _c__
{
class Program
{
static void Main(string[] args)
{
Book best = new Book("<NAME>", 420, "<NAME>", 1);
Console.WriteLine(best.explaination());
Book bruh = new Book("<NAME>", 69, "Random idiot", 69);
Console.WriteLine(bruh.explaination());
Pages p = new Pages("Bruh", "bruh", 69, 420);
Console.WriteLine(p.explaination());
Console.ReadLine();
}
public static float sum(float a, float b){
return (float) a+b;
}
}
}
<file_sep>/Book.cs
using System;
namespace _c__{
class Book{
public string name;
// name of the book
public float pages;
// number of pages in the book
public string author;
// name of the author
public int sno;
// serial number of the book
public Book(string name, float pages, string author, int sno){
this.name = name;
this.pages = pages;
this.author = author;
this.sno = sno;
// assigining the values to the variable
}
public bool isTheBest(){
if(this.name.ToLower() == "shingeki no kyojin"
|| this.name.ToLower() == "attack on titan"){
return true;
}
else{
return false;
}
}
public string explaination(){
string isBestText;
if(this.isTheBest()){
isBestText = "is";
}else{
isBestText = "is not";
}
string explaination = "The name of the book is " + this.name + " written by " + this.author + ". This book has a total of " + this.pages + " pages, and labelled by the number " + this.sno + " and this " + isBestText + " the best book in the world";
return explaination;
}
}
}<file_sep>/Page.cs
using System;
namespace _c__{
class Pages : Book{
public Pages(string name, string author, float pages, int sno):base(name, pages, author, sno){
this.name = name;
this.author = author;
this.pages = pages;
this.sno = sno;
}
}
}<file_sep>/README.MD
This is not a complete project
I was learning C# for the first time and experimenting with the
Classes and Objects in C#.
I have made a simple program that shows how Classes work in C#.
This is not a perfect example, but this will work for me :)
I am making this project public just because if anyone is
interested in knowing how classes and objects work in C#, you
can always refer to this source code :)
Thank You! | d7ea7877f57b4ef9b1f7db928f85a2a2a3ace9af | [
"Markdown",
"C#"
] | 4 | C# | ivanrj7j/CSharp-Classes-Example | 7e72be9467c37585f82cc06b70bbffbe440d1a9a | 86f7b973f636fc829486d6e5827d41005895fa00 |
refs/heads/main | <file_sep># Day-Zero-Bot
Rust Legacy Discord Bot
Requirements:
A rust legacy server!
Node.js
Bot token
Optional:
Nodemon.js
Usage:
Soon! or never really...
<file_sep>/*
Day Zero Bot Creado por <NAME>#3137 fb.com/estantaya para Day Zero Rust Legacy
Oficial Discord: https://discord.gg/uVu8xWsx5m
*/
const Url = require('url');
const http = require('http');
var ping;
//console.log("!");
/*
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(cfgData.alias.data.comandos.test);
});
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
server.on('request', (request, response) => {
// the same kind of magic happens here!
console.log(request);
});
server.listen(port, hostname, () => {
console.log(`El servidor se está ejecutando en http://${hostname}:${port}/`);
});
*/
const spawn = require('child_process').spawn;
const Discord = require('discord.js');
//const { Client, MessageEmbed } = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
var online=false;
var cfgDayZero = "../serverdata/oxide/data/DayZero.json";
//ipc.stdin.write(JSON.stringify(message) + "\n");
//var
var jugadoresEmbed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle("Jugadores Online")
// Set the color of the embed
.setColor("ORANGE");
var jugadores={};
var nuevaData="";
var start=true;
//canales se accede a sus nombres de discord con cfgData.canales.data.list
var canales = {
"Registro":null,//para usuarios, nombre: (cfgData.online.data.canal)
"OnOff":null,//para usuarios, nombre: (cfgData.online.data.canal)
"Spam":null,//para usuarios, nombre: (cfgData.online.data.canal)
"Vip":null,//para vips, nombre: cfgData.
"serverLog":null//para admins, nombre: (cfgData.server.data.canal)
};
var serverParams=ToArgs('-batchmode -ip 0.0.0.0 -port 28015 -maxplayers 80 -hostname "dayzero"');
var msgEntrada=[" Esta entre nosotres"," hiso acto de presencia"," vino",
" se levanto de entre los muertos"," resucito"," quiere pan"," llegó"," volvió",
" ha regresado"," siempre esta de vuelta"," nos extrañaba"," quiere jugar pvp arena",
" quiere farmear osos"," vino a raidear"," vino a farmear"," lo corrio la mujer"];
var msgSalida=[" Se evaporo"," Se fué"," desapareció",
" Murio de regreso a su planeta"," ya no esta entre nosotros"," se fue a hacer caca",
" esta con dios"," fue funado"," le dio sueño"," lo llamo la mama",
" se fue a trabajar"," se fue a estudiar"," se fue al baño"," se despide de este mundo cruel"];
var imagenes=[];
http.createServer((request, response) => {
const { headers, method, url } = request;
let body = [];
response.on('close', () => {
ping=null;
}).on('finish', () => {
ping=null;
});
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
console.log("el plugin esta enviando data...");
}).on('end', () => {
body = Buffer.concat(body).toString();
// At this point, we have the headers, method, url and body, and can now
// do whatever we need to in order to respond to this request.
//console.log(body);
//console.log(headers);
//console.log(method);
/*response.write("1");
response.write("2");*/
//console.log("el plugin envio algo...");
var query = Url.parse(url, true).query;
//if (url=="/discord/") response.end("https://discord.gg/AUHY76mXWx")
//console.log("query: "+query);
/*if (canales["serverLog"]!=null) {
canales["serverLog"].send(url);
}*/
/*if (ping==null) ping=response;
else if (ping.) ping=response;*/
if ("ping" in query) {
//console.log("Server Alive");
if (ping!=null) ping.end();
ping=response;
if (start) {
start=false;
if (canales["serverLog"]!=null) canales["serverLog"].send("El plugin se conecto!");
ping.end("{'update_players':''}");
}
return;
}
/*
if (ping!=null) {
ping.end();
}
ping=response;
*/
// else if (ping == null) ping = response;
if ("echo" in query) {
if (query["echo"] in canales) {
canales[query["echo"]].send(decodeURIComponent(query["content"]));
} else if (canales["serverLog"]!=null) {
canales["serverLog"].send("El bot intento enviar\n`"+
decodeURIComponent(query["content"])+"`\n a "+query["spam"]+
" pero ese canal no existe...");
}
} else if ("startServer" in query) {
if (canales["Spam"]!=null) {
canales["Spam"].send("<:rust:772875920406478868> El server abrio!");
}
jugadores={};
} else if ("closeServer" in query) {
jugadores={};
console.log("El servidor cerro");
if (canales["Spam"]!=null) {
canales["Spam"].send("<:rust:772875920406478868> El server cerro!");
ping=null;
}
} else if ("playersOn" in query) {
jugadores={};
var listaJugadores=[];
listaJugadores=decodeURIComponent(query["playersOn"]).split(", ");
//listaJugadores=query["playersOn"].split(",%20");
for (i=0;i<listaJugadores.length;i++) {
jugadores[listaJugadores[i]]=true;
}
/*if (canales["Spam"]!=null) {
SendOnline(canalSpam,"global");
}*/
} else if ("playerOn" in query) {
jugadores[query["playerOn"]]=true;
console.log(query["playerOn"]+" se conecto");
if (canales["OnOff"]!=null) {
canales["OnOff"].send(query["playerOn"]+msgEntrada[Math.floor(Math.random()*msgEntrada.length)]);
}
} else if ("playerOff" in query) {
jugadores[query["playerOff"]]=false;
console.log(query["playerOff"]+" se desconecto");
if (canales["OnOff"]!=null) {
canales["OnOff"].send(query["playerOff"]+msgSalida[Math.floor(Math.random()*msgSalida.length)]);
}
} else if ("raid" in query) {
//var coords=query["raid"].split(",");
console.log("c4log");
//console.log(query["playerOn"]+" se desconecto");
if (canales["Raid"]!=null) canales["Raid"].send(query["player"]+" Esta raideando la casa de "+query["victim"]);
} else if ("ganadorArena" in query) {
if (canales["Spam"]!=null) canales["Spam"].send("[ArenaMiniGames] "+query["ganadorArena"]+" es el ganador!!!");
}
response.end("ok");
});
}).listen(3000); // Activates this server, listening on port 8080.
var cfgData = {
ayuda : {
call : function(msg,args) {
MostrarComandos(msg);
},
data : {
a:"h","help":"Mostrar comandos"
}
},
canal : {
call : function(msg,args) {
if (args.length==1) {
var canalesBot="";
for (var key in cfgData.canal.data.list) {
canalesBot+=key+"\n";
}
msg.channel.send("Subcomandos:\n"+canalesBot+"Ejemplo: "+
cfgData.prefijo.data.name+"canal bienvenida");
} else if (args[1] in cfgData.canal.data.list) {
//canales[args[1]]=;
if (cfgData.canal.data.list[args[1]]==msg.channel.id) {
cfgData.canal.data.list[args[1]]="";
canales[args[1]]=null;
msg.channel.send("Se borro este canal del bot");
} else {
cfgData.canal.data.list[args[1]]=msg.channel.id;
canales[args[1]]=msg.channel;
msg.channel.send("Se establecio este canal como canal "+args[1]);
}
SaveData();
} else msg.channel.send("?");
},
data : {
a:"sc",
"admin_help":"Elije un canal para que el bot diga cosas",
list:{
Bienvenida:"✔lobby︻╦╤─",Spam:"",Registro:"",OnOff:"",Raid:"",Vip:"",serverLog:"♛staff♛"
}
}
},
id_jugador : {
call : function(msg,args) {
if (ping==null) {
if (start) msg.channel.send("El server se apago...");
else msg.channel.send("El server esta offline");
return;
}
if (CheckAdmin(msg.member)) {
if (args.length==1) {
msg.channel.send("Falta el nombre del jugador");
} else if (ping != null) {
ping.end(JSON.stringify({"id_from_name":encodeURI(args[1])}));
//ping = null;
//msg.channel.send("Enviando query...");
} else msg.channel.send("El plugin no esta conectado...");
} else msg.reply("No tienes permiso");
},
data : {a:"id","admin_help":"Obtener Id de un Jugador"}
},
prefijo : {
call : function(msg,args) {
if (CheckAdmin(msg.member)) {
if (args.length==1) {
cfgData.prefijo.data.name = "";
msg.channel.send("Se elimino el prefijo");
} else {
cfgData.prefijo.data.name = args[1];
msg.channel.send("El nuevo prefijo es "+args[1]);
}
SaveData();
} else msg.reply("No tienes permiso");
},
data : {a:"p","admin_help":"Prefijo para comandos",name:"dz!"}
},
server : {
call : function(msg,args) {
if (ping==null) {
if (start) msg.channel.send("El server se apago...");
else msg.channel.send("El server esta offline");
return;
}
if (!CheckAdmin(msg.member)) {
msg.channel.send("No tienes permiso");
return;
}
if (args.length==1) {
msg.channel.send("Subcomandos:\n`"+
cfgData.server.data.prender+"`: Prender el server\n`"+
cfgData.server.data.say+"`: Hablar en el servidor");
} else if (args.length==2) {
msg.channel.send("Falta valor del subcomando");
} else if (cfgData.server.data.prender.indexOf(args[1])!=-1) {
//serverLog=msg.channel;
msg.channel.send("Iniciando servidor...");
PrenderServer();
} else if (cfgData.server.data.say.indexOf(args[1])!=-1) {
if (ping==null) {
msg.channel.send("Plugin desconectado...");
return;
}
if (args.length>2) {
//if (ping!=null) {
ping.end(JSON.stringify({"botSay":args[2]}));
/*} else {
msg.channel.send("Error, no conectado...");
}*/
msg.channel.send("Mensaje enviado...");
console.log("enviando botSay: "+args[2]);
} else msg.channel.send("Error, ejemplo: "+
cfgData.prefijo.data.name+'server say "Hola mundo"');
//SaveData();
} else {
msg.channel.send("Subcomando "+args[2]+" erroneo");
}
},
data : {
a:"s","admin_help":"Prender y Hablar en el server",
prender : ["prender","p"], say : ["say","s"]
}
},
online : {
call : function(msg,args) {
if (ping==null) {
if (start) msg.channel.send("El server se apago...");
else msg.channel.send("El server esta offline");
return;
}
SendOnline(msg.channel,"global");
},
data : {
a:"on",
"help":"Muestra Jugadores Conectados"
}
},
msg : {
call : function(msg,args) {
if (args.length>1) {
if (CheckAdmin(msg.member)) {
var index=imagenes.indexOf(args[1]);
if (index==-1) {
imagenes.push(args[1]);
nuevaData="Mensaje ingresado";
} else {
imagenes.slice(index,1);
nuevaData="Mensaje eliminado";
}
//✔lobby︻╦╤─
SaveImages();
} else nuevaData="No tienes permiso";
} else {
//console.log("imagenes: "+imagenes.length);
if (imagenes.length>0) nuevaData=imagenes[Math.floor(Math.random()*imagenes.length)];
else nuevaData = "No hay mensajes";
}
msg.channel.send(nuevaData);
},
data : {a:"r","help":"Muestra mensajes random",
"admin_help":"[ Guarda un mensaje]"}
},
msg_bienvenida : {
call : function(msg,args) {
if (CheckAdmin(msg.member)) {
if (args.length>1) {
cfgData.msg_bienvenida.data.canal = args[1];
nuevaData="Mensaje modificado";
SaveData();
} else {
BroadcastWelcome(msg.member);
//nuevaData="El mensaje de bienvenida es: "+cfgData.msg_bienvenida.data.msg;
nuevaData="Ejemplo: "+cfgData.prefijo.data.name+'msg_bienvenida "Mensaje de ejemplo';
}
msg.channel.send(nuevaData);
} else msg.reply("No tienes permiso");
},
data : {a:"mb","admin_help":"Mensaje de bienvenida al servidor",
msg:"UNA LEYENDA HA NACIDO EN :beginner:𝔻𝔸𝕐ℤ𝔼ℝ𝕆:beginner:︻╦╤─"}
},
img_bienvenida : {
call : function(msg,args) {
if (CheckAdmin(msg.member)) {
if (args.length>1) {
cfgData.img_bienvenida.data.img = args[1];
nuevaData="Imagen modificada";
SaveData();
} else {
nuevaData="La imagen de bienvenida es: "+cfgData.img_bienvenida.data.img;
nuevaData+="\nModificar: "+cfgData.prefijo.data.name+'img_bienvenida https://imagen';
}
msg.channel.send(nuevaData);
} else msg.reply("No tienes permiso");
},
data : {a:"ib","admin_help":"Imagen de bienvenida",img:""}
},
dm_bienvenida : {
call : function(msg,args) {
if (CheckAdmin(msg.member)) {
/*if (args.length==1) SendWelcome(msg.member);
else {*/
if (args.length==1) {
msg.channel.send("Modo de uso: "+cfgData.prefijo.data.name+'b[ t "Titulo"][ d "Contenido"][ c color]');//.then(
/*.then(
SendWelcome(msg.member));*/
//var timeOut = setTimeout(SendWelcome,1000,msg.member.user);
//SaveData();
//}
var timeOut = setTimeout(SendWelcome,1000,msg.member.user);
return;
}
var index=args.indexOf("t");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.title = args[index+1];
index=args.indexOf("title");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.title = args[index+1];
index=args.indexOf("d");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.desc = args[index+1];
index=args.indexOf("desc");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.desc = args[index+1];
index=args.indexOf("c");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.color = args[index+1];
index=args.indexOf("color");
if (index!=-1&&args.length>=index+2) cfgData.dm_bienvenida.data.color = args[index+1];
SaveData();
} else msg.reply("No tienes permiso");
},
data : {
a:"b",
"admin_help":"Mensaje privado al entrar al server",
title:"Day Zero Rust Legacy Server",
color:"ORANGE",
desc:'Hola! Bienvenido... mi nombre es Olimpicus '+
'y soy parte del STAFF de este proyecto de rust legacy '+
'"GLORIA AL LEGACY!" no dejemos que muera en su totalidad '+
'y ayúdanos a crecer compartiendo el enlace del servidor para '+
'que muchas mas LEYENDAS se unan y seamos una familia grande :) '+
'GRACIAS por tu ayuda! <3'
}
},
//variables : {"gente_online"},
alias : {
call : function(msg,args) {
if (args.length==1) MostrarAliases(msg);
else if (CheckAdmin(msg.member)) {
if (args.length==2) {
delete cfgData.alias.data.comandos[args[1]];
SaveData();
} else if (args.length==3) {
cfgData.alias.data.comandos[args[1]] = args[2];
SaveData();
} else msg.reply("Si el valor del alias tiene espacios inicia el mensaje con \"");
} else msg.reply("No tienes permiso");
},
data : {
a:"a",
"help":"Comandos alias",
comandos: {
"ip":'net.connect dayzero.latinserver.online:28015'
}
}
},
say : {
call : function(msg,args) {
if (CheckAdmin(msg.member)) {
if (args.length>1) {
msg.channel.send(GenerarEmbed(args))
.then(message => console.log(`Say embed: ${message.content}`))
.catch(console.error);
} else {
msg.channel.send("Faltan parametros... Ejemplo:\n"+
cfgData.prefijo.data.name+'say "Soy un mensaje"[ "Titulo"[ "url.imagen.jpg"]]');
}
} else msg.reply("No tienes permiso");
},
data : {
a:"d",
"admin_help":"Hacer que el bot diga algo"
}
}
};
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
fs.readFile('./imagenes.txt', function(err, data) {
if (err) {
if (err.code === 'ENOENT') {
console.error('file does not exist');
return;
}
throw err;//otro error que no es el archivo no existe
}
//se ejecuta si el archivo existe, creo?
//header=LeerHeader(Buffer.from(data,"hex"));
//var
imagenes = (""+data).split("\n");
/*dm_bienvenida=cfgData.dm_bienvenida.data;
aliases=cfgData.alias.dataes;*/
});
fs.readFile('./data.json', function(err, data) {
if (err) {
if (err.code === 'ENOENT') {
console.error('file does not exist');
return;
}
throw err;//otro error que no es el archivo no existe
}
//se ejecuta si el archivo existe, creo?
//header=LeerHeader(Buffer.from(data,"hex"));
//var
var newData = JSON.parse(data);
//console.log(newData);
//update from newData
//cfgData = JSON.parse(data); cause versioning bugs
//unused keys off newData are droped on writeFile
for (var key in cfgData) {
if (key in newData) {
for (var d in cfgData[key].data) {
if (d in newData[key]) cfgData[key].data[d] = newData[key][d];
}
}
}
for (var id in cfgData.canal.data.list) {
if (cfgData.canal.data.list[id]!="") canales[id] = client.channels.cache.find(channel => channel.id == cfgData.canal.data.list[id]);
}
});
/*
if (cfgData.server.data.canal!="") {
serverLog=client.channels.cache.find(channel => channel.name == cfgData.server.data.canal);
if (canales["serverLog"]!=null) canales["serverLog"].send("El bot cobro vida propia...");
}
if (cfgData.online.data.canal!="") canalSpam=client.channels.cache.find(channel => channel.name == cfgData.online.data.canal);
if (cfgData.vip.data.canal!="") canalVip=client.channels.cache.find(channel => channel.name == cfgData.vip.data.canal);
console.log("ServerLog: "+cfgData.server.data.canal);
*/
/*dm_bienvenida=cfgData.dm_bienvenida.data;
aliases=cfgData.alias.dataes;*/
//console.log(cfgData);
//if (canales["serverLog"]!=null) canales["serverLog"].send("Iniciando...");
//else console.log("Canal de logs de server: "+cfgData.server.data.canal);
/*
if (CheckCommand(args[0],"ayuda")) {
} else if (CheckCommand(args[0],"online")) {
} else if (CheckCommand(args[0],"prefijo")) {
} else if (CheckCommand(args[0],"imagen_random")) {
} else if (CheckCommand(args[0],"canal_bienvenida")) {
} else if (CheckCommand(args[0],"img_bienvenida")) {
} else if (CheckCommand(args[0],"msg_bienvenida")) {
} else if (CheckCommand(args[0],"dm_bienvenida")) {
} else if (CheckCommand(args[0],"alias")) {
} else if (args[0] in cfgData.alias.data.comandos) {
msg.channel.send(cfgData.alias.data.comandos[args[0]]);
}*/
});
client.on('message', msg => {
if (msg.author.bot) return;
//console.log(msg.content);
var args = ToArgs(msg.content);
nuevaData="error";
if (args.length==0) return;//alguien pudo escribir ""
//var arg=args[0];
//if (arg.startsWith(cfgData.prefijo.data.name)) arg.replace(cfgData.prefijo.data.name,"");
var arg = SearchCommand(args[0]);
//console.log(arg);
if (arg != false) {
cfgData[arg].call(msg,args);
} else if (args[0] in cfgData.alias.data.comandos) msg.channel.send(cfgData.alias.data.comandos[args[0]]);
});
// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
console.log("Nuevo miembro: "+member.user.username);
// Send the message to a designated channel on a server:
//const channel = member.guild.channels.cache.find(ch => ch.name.includes(cfgData.canal_bienvenida.data.canal));
//const channel = client.channels.cache.get(cfgData.canal_bienvenida.data.canal);
// Do nothing if the channel wasn't found on this server
//if (!channel) return;
// Send the message, mentioning the member
//channel.send(cfgData.msg_bienvenida.data.msg+", "+member.user.username);
BroadcastWelcome(member);
var timeOut = setTimeout(SendWelcome,1000,member.user);
});
function GenerarEmbed(args) {
var title="DayZero";
if (args.length>2) title=args[2];
var embed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle(title)
// Set the color of the embed
.setColor("ORANGE")
// Set the main content of the embed
.setDescription(args[1]);
// Send the embed to the same channel as the message
//const dmChannel = member.createDM();
if (args.length>3) embed.setImage(args[3]);
return embed;
}
function PrenderServer() {
var ipc = spawn("../rust_server.exe",serverParams,
{cw:"C:/Users/Administrador/Desktop/rust Dayzero/",env:process.env}
);
//var ipc = spawn("../Abrir server.bat");
//ipc.stdin.setEncoding("utf8");
ipc.stderr.on('data', function (data) {
//process.stdout.write(data.toString());
if (canales["serverLog"] != null) canales["serverLog"].send(data.toString());
});
ipc.stdout.on('data', function (data) {
//process.stdout.write(data.toString());
if (canales["serverLog"] != null) canales["serverLog"].send(data.toString());
});
ipc.on('close', (code) => {
console.log(`Server se apago ${code}`);
if (canales["serverLog"] != null) canales["serverLog"].send("El server se apago...");
});
}
function SaveImages() {
fs.writeFile('./imagenes.txt', imagenes.join("\n"), function (err) {
if (err) {
if (err.code === 'ENOENT') {
console.error('file does not exist');
return;
}
throw err;//otro error que no es el archivo no existe
}
});
}
function SaveData() {
var newData={};
for (var key in cfgData) {
newData[key]=cfgData[key].data;
}
fs.writeFile('./data.json', JSON.stringify(newData,null,"\t"), function (err) {
if (err) {
if (err.code === 'ENOENT') {
console.error('file does not exist');
return;
}
throw err;//otro error que no es el archivo no existe
}
});
}
function ToArgs(str) {
var strings = str.split('"');
var args = [];//asegurarme que
var string = false;
for (i=0;i<strings.length;i++) {
if (!string) args = args.concat(strings[i].toLowerCase().split(" "));
else args = args.concat(strings[i]);
string = !string;
}
for (i=0;i<args.length;i++) {
if (args[i]=="") {
args.splice(i,1);
i--;
}
}
return args;
}
function CheckAdmin(member) {
//if (member.roles.highest.position==0||member.hasPermission("ADMINISTRATOR")) return true;
if (member.hasPermission("ADMINISTRATOR")) return true;
else return false;
}
function MostrarAliases(msg) {
var alias = "";
for (const key in cfgData.alias.data.comandos) {
alias += key+"\n";
}
const embed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle("Comandos Alias")
// Set the color of the embed
.setColor("ORANGE")
// Set the main content of the embed
.setDescription(alias);
if (CheckAdmin(msg.member)) {
embed.addField('Modo de uso',cfgData.prefijo.data.name+'alias [comando ["valor"]]');
embed.addField('Crear/Editar comando "wipe"',cfgData.prefijo.data.name+'alias wipe "Proximo wipe: 1/1/21\\nNueva linea"');
embed.addField('Eliminar comando "wipe"',cfgData.prefijo.data.name+'alias wipe');
}
embed.setFooter('Metodo abreviado: '+cfgData.prefijo.data.name+'a');
msg.channel.send(embed);
}
function MostrarComandos(msg) {
/*var comandos = "";
for (const key in cfgData) {
comandos+=key+"\n";
}*/
const embed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle("Comandos")
// Set the color of the embed
.setColor("ORANGE")
// Set the main content of the embed
.setDescription("Prefijo actual: "+cfgData.prefijo.data.name);
var admin=CheckAdmin(msg.member);
var helpText;
for (const key in cfgData) {
helpText="";
if ("help" in cfgData[key].data) helpText=cfgData[key].data.help;
if ("admin_help" in cfgData[key].data) {
if (helpText=="") helpText=cfgData[key].data.admin_help
else helpText+="\n"+cfgData[key].data.admin_help
}
//if ("help" in cfgData[key].data) embed.addField("["+key+", "+cfgData[key].data.a+"]",cfgData[key].data.help);
if (helpText!="") embed.addField("["+key+", "+cfgData[key].data.a+"]",helpText);
}
//embed.setFooter('Metodo abreviado: '+cfgData.prefijo.data.valor+'h');
//msg.channel.send(embed);
msg.channel.send(embed);
}
function SearchCommand(arg) {
//buena function :)
//var command="";
//if (cmd in cfgData) command=cfgData[cmd].data.a;
//if (arg in cfgData) return true;
for (var key in cfgData) {
if (cfgData.prefijo.data.name+key == arg) return key;
if (cfgData.prefijo.data.name+cfgData[key].data.a == arg) return key;
}
//if (arg == cfgData.prefijo.data.name+command && command!="" || arg == cfgData.prefijo.data.name+cmd) return true;
return false;
}
function JugadoresOnline() {
var num=0;
for (var key in jugadores) {
if (jugadores[key]) num++;
}
return num;
}
function BroadcastWelcome(member) {
//var channel = member.guild.channels.cache.find(ch => ch.name.includes(cfgData.canal_bienvenida.data.canal));
//const channel = client.channels.cache.get(cfgData.canal_bienvenida.data.canal);
// Do nothing if the channel wasn't found on this server
if (canales["Bienvenida"]==null) return;
var embed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle(cfgData.msg_bienvenida.data.msg)
// Set the color of the embed
.setColor("ORANGE")
// Set the main content of the embed
.setDescription(`${member.user}`);
if (cfgData.img_bienvenida.data.img!="") embed.setImage(cfgData.img_bienvenida.data.img);
//if (cfgData.img_bienvenida.data.img!="") embed.setImage(cfgData.img_bienvenida.data.img+"?s="+encodeURI(member.user.username)+"&"+Math.random());
canales["Bienvenida"].send(embed)
.then(message => console.log(`Nuevo user: ${member.user.username}`))
.catch(console.error);
}
function SendWelcome(user) {
var embed = new Discord.MessageEmbed()
// Set the title of the field
.setTitle(cfgData.dm_bienvenida.data.title)
// Set the color of the embed
.setColor(cfgData.dm_bienvenida.data.color)
// Set the main content of the embed
.setDescription(cfgData.dm_bienvenida.data.desc);
// Send the embed to the same channel as the message
//const dmChannel = member.createDM();
//if (!dmChannel) return;
//dmChannel.send(embed);
//member.user.send(embed);
user.send(embed)
.then(message => console.log(`Enviado pm`))
.catch(console.error);
//member.send
}
/*
function SpamearCanal(jugador) {
canalDeSpam.send(jugador.name+" Entro al server.");
}*/
function SendOnline(channel,tipo) {
//var channel = member.guild.channels.cache.find(ch => ch.name.includes(cfgData.canal_bienvenida.data.canal));
var onlines="";
var cantidad=0;
for (var key in jugadores) {
if (jugadores[key]) {
onlines+=key+"\n";
cantidad++;
}
}
onlines+="<:rust:772875920406478868> "+cantidad+" Conectados.";
// Set the main content of the embed
jugadoresEmbed.setDescription(onlines);
//jugadoresEmbed.setTitle("");
//2222dddd sa
/*if (nuevaData!="") {
jugadoresEmbed.setTitle(nuevaData);
} else jugadoresEmbed.setTitle("Jugadores Online");*/
//embed.addField
// Send the embed to the same channel as the message
//const dmChannel = member.createDM();
channel.send(jugadoresEmbed);
}
client.login('change_me');
<file_sep>{
"verbose": true,
"events": {
"restart": "./bot.js"
},
"watch": [
"./bot.js"
],
"env": {
"NODE_ENV": "development"
}
} | 6c022a6eea9e952d38dafdd1062e10124836942a | [
"Markdown",
"JavaScript"
] | 3 | Markdown | estantaya/Day-Zero-Bot | 530c5b83c3c06c260fe2c31f254ac9bcb0ac89d4 | c10e7e5fe744c9efeb1aa04f0908bee112aef345 |
refs/heads/master | <repo_name>JIAOBANTANG/riqian<file_sep>/README.md
# canvas-daysign
三个日签模板(欢迎添砖加瓦!)



<file_sep>/js/yuechu_daysign.js
var daysignBase64;
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width =360;
canvas.height = 640;
let imgWidth = img.width;
let imgHeight = img.height;
//与画布的宽比
let dw = canvas.width / imgWidth;
//与画布的高比
let dh = canvas.height / imgHeight;
var fang = canvas.width;
var chang = canvas.height;
var ctx = canvas.getContext("2d");
// ctx.drawImage(img, 0, 0, img.width, img.height);
// 裁剪图片中间部分
if (imgWidth > fang && imgHeight > chang || imgWidth < fang && imgHeight < chang) {
if (dw > dh) {
ctx.drawImage(img, 0, (imgHeight - fang / dw) / 2, imgWidth, fang / dw, 0, 0, fang, chang)
} else {
ctx.drawImage(img, (imgWidth - fang / dh) / 2, 0, fang / dh, imgHeight, 0, 0, fang, chang)
}
}
// 拉伸图片
else {
if (imgWidth < fang) {
ctx.drawImage(img, 0, (imgHeight - fang / dw) / 2, imgWidth, fang / dw, 0, 0, fang, chang)
} else {
ctx.drawImage(img, (imgWidth - fang / dh) / 2, 0, fang / dh, imgHeight, 0, 0, fang, chang)
}
}
// var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}
var image = new Image();
image.setAttribute("crossOrigin",'Anonymous');
// image.src = 'http://cdn.treelo.xin/avatar.png';
image.onload = function(){
// console.log(base64);
document.querySelector('.yuechu').style.cssText="background-image: url("+getBase64Image(image)+");"+"background-size: cover;";
}
window.onload = function(){
let today=new Date();
let chinese = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九','十'];
let y = today.getFullYear().toString();
let m = (today.getMonth()+1).toString();
let mouth;
if (m.length == 2) {
if (m.charAt(0) == "1") {
mouth = ("十" + chinese[m.charAt(1)] + "月");
}
}
else {
mouth = (chinese[m.charAt(0)] + "月");
}
document.querySelector('.year').innerHTML=y+" ❤";
document.querySelector('.mouth').innerHTML="你好啊" + mouth;
}
var upimg = document.querySelector('#upimg');
upimg.onchange=function(){
//获取文件
var file = this.files[0];
//创建读取文件对象
var reader = new FileReader();
//读取文件
reader.readAsDataURL(file);
//在回调函数中修改Img的src属性
reader.onload = function () {
// console.log(reader.result);
image.src = reader.result;
}
}
function $(id) {
return document.getElementById(id);
}
function changeColor() {
var c = $("text");
var ctx = c.getContext("2d");
var red = $("red");
var green = $("green");
var blue = $("blue");
ctx.fillStyle = "rgb(" + red.value + "," + green.value + "," + blue.value + ")";
$("showcolor").innerHTML = ctx.fillStyle;
ctx.fillRect(0, 0, 100, 100);
// $('canvas').getContext('2d').fillStyle = $("showcolor").innerHTML;
document.querySelector('.mouth').style.cssText="color:rgb("+ red.value + "," + green.value+ "," + blue.value+");";
document.querySelector('.year').style.cssText="color:rgb("+ red.value + "," + green.value+ "," + blue.value+");";
document.querySelector('.juzi').style.cssText="color:rgb("+ red.value + "," + green.value + "," + blue.value+");"+"text-shadow: -20px 15px 2px rgb("+red.value + "," + green.value + "," + blue.value+",0.3);";
document.querySelector('.theme').style.cssText="border-color:rgb("+ red.value + "," + green.value + "," + blue.value+",0.6);";
}
changeColor();
function baseDaySign(){
if(daysignBase64==undefined){
alert('请填入日签!');
}
handleCopy(daysignBase64);
}
function imgDaySign() {
if(daysignBase64==undefined){
alert('请填入日签!');
}
var triggerDownload = document.querySelector('#download')
triggerDownload.setAttribute("href",daysignBase64);
var timestamp = Date.parse(new Date());
triggerDownload.setAttribute("download", timestamp + ".png");
triggerDownload.click();
}
function reload(){
location.reload();
}
function takeScreenshot() {
html2canvas(document.querySelector('.yuechu'), {
onrendered: function(canvas) {
// console.log(canvas.toDataURL());
daysignBase64=canvas.toDataURL();
},
});
}
function handleCopy(data) {
//生成虚拟DOM
let input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value', data)
input.select()
document.execCommand('copy')
// 删除'虚拟'DOM
document.body.removeChild(input)
}
var txt = $('txt');
txt.onchange=function(){
let content = this.value;
// content =content.split('\n');
// let contentBr ='';
// for(let i=0;i<content.length;i++){
// contentBr+=content[i]+'<br> ';
// }
// // contentBr = ' '+contentBr;
document.querySelector('.txt').innerHTML=content;
}
var themeVal = document.querySelector('#themeVal');
themeVal.onchange=function(){
let theme = this.value;
document.querySelector('.theme').innerHTML=theme;
}
<file_sep>/js/mono_daysign.js
window.onload = function () {
autoDate();
autoOuthor();
autoTheme();
}
var daysignBase64;
var sign_author = document.querySelector('#sign-author');
sign_author.onchange=function(){
autoOuthor();
}
var themeVal = document.querySelector('#themeVal');
themeVal.onchange=function(){
autoTheme();
}
var txt = document.querySelector('#txt');
txt.onchange=function(){
daysignContent();
}
var juziAuthor = document.querySelector('#juziAuthor');
juziAuthor.onchange=function(){
Author();
}
function Author(){
let author = document.querySelector('#juziAuthor').value;
author = author+' 说';
document.querySelector('.author').innerHTML=author;
}
var txt = document.querySelector('#txt');
txt.onchange=function(){
daysignContent();
}
function daysignContent(){
let content = document.querySelector('#txt').value;
content =content.split('\n');
let contentBr ='';
for(let i=0;i<content.length;i++){
contentBr+=content[i]+'<br>';
}
contentBr = ' '+contentBr;
document.querySelector('.daysignContent').innerHTML=contentBr;
}
function autoOuthor(){
let outhor = document.querySelector('#sign-author').value+"日签";
document.querySelector('.logo').innerHTML=outhor;
}
function baseDaySign(){
handleCopy(daysignBase64);
}
function imgDaySign() {
var triggerDownload = document.querySelector('#download')
triggerDownload.setAttribute("href",daysignBase64);
var timestamp = Date.parse(new Date());
triggerDownload.setAttribute("download", timestamp + ".png");
triggerDownload.click();
}
function reload(){
location.reload();
}
function autoDate(){
document.querySelector('.date').innerHTML=date();
}
function takeScreenshot() {
html2canvas(document.querySelector('.daysign'), {
onrendered: function(canvas) {
daysignBase64=canvas.toDataURL();
},
});
}
function handleCopy(data) {
//生成虚拟DOM
let input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value', data)
input.select()
document.execCommand('copy')
// 删除'虚拟'DOM
document.body.removeChild(input)
}
//时间转大写年月日函数
function date(){
let today=new Date();
let chinese = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九','十'];
let y = today.getFullYear().toString();
let m = (today.getMonth()+1).toString();
let d = today.getDate().toString();
let result = "";
for (let i = 0; i < y.length; i++) {
result += chinese[y.charAt(i)];
}
result += "年";
if (m.length == 2) {
if (m.charAt(0) == "1") {
result += ("十" + chinese[m.charAt(1)] + "月");
}
}
else {
result += (chinese[m.charAt(0)] + "月");
}
// d =parseInt(d)+11;
// console.log(d);
// d=d.toString();
if (d.length == 2) {
if(d.charAt(0)==1){
if(d.charAt(1)==0){
result += "十日";
}else{
result += "十"+(chinese[d.charAt(0)] + "日");
}
}else{
result += chinese[d.charAt(0)]+"十"+(chinese[d.charAt(0)] + "日");
}
}
else {
result += (chinese[d.charAt(0)] + "日");
}
return result;
}
function autoTheme(){
let theme = document.querySelector('#themeVal').value;
document.querySelector('.theme').innerHTML=theme;
let themePinyin =pinyinUtil.getPinyin(theme, ',', true, false);
themePinyin = themePinyin.split(',');
let themePinyinVal='';
for(let i =0;i<themePinyin.length;i++){
themePinyinVal+='<div class="themePinyinVal">'+themePinyin[i]+'</div>'
}
document.querySelector('.themePinyin').innerHTML= themePinyinVal;
// console.log(themePinyin.length);
}<file_sep>/js/tag_daysign.js
//获取当前日期
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
var nowDate = year + "." + month + "." + day;
var input = document.querySelector('input');
input.onchange = function () {
//获取文件
var file = this.files[0];
//创建读取文件对象
var reader = new FileReader();
//读取文件
reader.readAsDataURL(file);
//在回调函数中修改Img的src属性
reader.onload = function () {
// console.log(reader.result);
canimg.src = reader.result;
}
}
var daysign = document.getElementById("daysign");
var ctx1 = daysign.getContext("2d");
var ratio = getPixelRatio(ctx1);
daysign.width = 400 * ratio;
daysign.height = 550 * ratio;
ctx1.fillStyle = '#fff';
ctx1.fillRect(0, 0, daysign.width, daysign.height);
var dayimg = new Image();
dayimg.onload = function () {
let imgw = dayimg.width;
let imgh = dayimg.height;
ctx1.clearRect(dayimg, 25, 25, imgw * ratio, imgh * ratio);
ctx1.drawImage(dayimg, 25, 25, imgw * ratio, imgh * ratio);
};
function getPixelRatio(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
var c = document.getElementById("copyimg");
var ctx2 = c.getContext("2d");
var canimg = new Image();
canimg.onload = function () {
//图片的宽
let imgw = canimg.width;
//图片的高
let imgh = canimg.height;
//与画布的宽比
let dw = c.width / imgw;
//与画布的高比
let dh = c.height / imgh;
var fang = c.width
// 裁剪图片中间部分
if (imgw > fang && imgh > fang || imgw < fang && imgh < fang) {
if (dw > dh) {
ctx2.drawImage(canimg, 0, (imgh - fang / dw) / 2, imgw, fang / dw, 0, 0, fang, fang)
} else {
ctx2.drawImage(canimg, (imgw - fang / dh) / 2, 0, fang / dh, imgh, 0, 0, fang, fang)
}
}
// 拉伸图片
else {
if (imgw < fang) {
ctx2.drawImage(canimg, 0, (imgh - fang / dw) / 2, imgw, fang / dw, 0, 0, fang, fang)
} else {
ctx2.drawImage(canimg, (imgw - fang / dh) / 2, 0, fang / dh, imgh, 0, 0, fang, fang)
}
}
let data = c.toDataURL('image/png');
dayimg.src = data;
};
function $(id) {
return document.getElementById(id);
}
window.onload = function () {
author()
}
function author() {
var daysign = document.getElementById("daysign");
var ctx1 = daysign.getContext("2d");
ctx1.clearRect(275, 480, 100, 40);
ctx1.fillStyle = '#fff';
ctx1.fillRect(275, 480, 100, 40);
ctx1.font = "25px Cursive";
ctx1.fillStyle = $("showcolor").innerHTML;
ctx1.fillText('搅拌糖°', 275, 505, 100, 20);
ctx1.clearRect(265, 510, 100, 40);
ctx1.fillStyle = '#fff';
ctx1.fillRect(265, 510, 100, 40);
ctx1.fillStyle = $("showcolor").innerHTML;
ctx1.font = "18px Georgia";
ctx1.fillText(nowDate, 270, 525, 100, 20);
}
function textToImg() {
author()
var len = $('len').value || 20;
var i = 0;
var fontSize = $('fontSize').value || 18;
// var fontWeight = $('fontWeight').value || 'normal';
var txt = $("txt").value;
var canvas = $('canvas');
if (txt == '') {
alert('必须要输入日签');
$("txt").focus();
}
if (len > txt.length) {
len = txt.length;
}
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#fff';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = $("showcolor").innerHTML;
context.font = fontSize + 'px Cursive';
context.textBaseline = 'top';
canvas.style.display = 'none';
function fillTxt(text) {
while (text.length > len) {
var txtLine = text.substring(0, len);
text = text.substring(len);
context.fillText(txtLine, 0, fontSize * (3 / 2) * i++,
canvas.width);
}
context.fillText(text, 0, fontSize * (3 / 2) * i, canvas.width);
}
var txtArray = txt.split('\n');
for (var j = 0; j < txtArray.length; j++) {
fillTxt(txtArray[j]);
context.fillText('\n', 0, fontSize * (3 / 2) * i++, canvas.width);
}
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var textimg = $("textimg");
// textimg.src = canvas.toDataURL("image/png");
var dayimg1 = new Image();
dayimg1.onload = function () {
let imgw = dayimg1.width;
let imgh = dayimg1.height;
ctx1.clearRect(25, 390, imgw * ratio, imgh * ratio);
ctx1.drawImage(dayimg1, 25, 390, imgw * ratio, imgh * ratio);
};
dayimg1.src = canvas.toDataURL("image/png");
}
function changeColor() {
var c = $("text");
var ctx = c.getContext("2d");
var red = $("red");
var green = $("green");
var blue = $("blue");
ctx.fillStyle = "rgb(" + red.value + "," + green.value + "," + blue.value + ")";
$("showcolor").innerHTML = ctx.fillStyle;
ctx.fillRect(0, 0, 100, 100);
$('canvas').getContext('2d').fillStyle = $("showcolor").innerHTML;
}
function baseDaySign() {
let data = daysign.toDataURL('image/png');
console.log(data);
handleCopy(data)
}
function imgDaySign() {
let data = daysign.toDataURL('image/png');
var triggerDownload = $("download")
triggerDownload.setAttribute("href", data);
var timestamp = Date.parse(new Date());
triggerDownload.setAttribute("download", timestamp + ".png");
triggerDownload.click();
}
changeColor();
function handleCopy(data) {
//生成虚拟DOM
let input = document.createElement('input')
document.body.appendChild(input)
input.setAttribute('value', data)
input.select()
document.execCommand('copy')
// 删除'虚拟'DOM
document.body.removeChild(input)
}
function reload(){
location.reload();
} | f4edb2bbdabac93176b176d8c4631aa9df3c59e9 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | JIAOBANTANG/riqian | e59068fe6fd80c18b2165371f6ce27083edb3419 | 83f2f908edf5a1f7647a705aba76cf3d43688ad6 |
refs/heads/master | <file_sep>CREATE TABLE Organizer1 (
Personid int IDENTITY(1,1) PRIMARY KEY,
OrgName varchar(255),
TagName varchar(255),
Longitude DECIMAL(9, 6),
Latitude DECIMAL(9, 6),
);
INSERT INTO Organizer1 VALUES
('EPA', 'Environment', 40.697440, -73.979440),
('The Nature Conservancy', 'Environment', 40.747140, -73.996460),
('Alley Pond Environmental Center', 'Environment', 40.762010, -73.753540),
('National Parks Conservation Association', 'Environment', 40.752930, -73.991830),
('Long Island Volunteer Center', 'Environment', 40.709160, -73.631230),
('Bronx River Alliance', 'Environment', 40.868470, -73.898290),
('Sierra Club NYC Group', 'Environment', 40.750990, -73.990610),
('New York City Audubon', 'Environment', 40.742830, -73.992140),
('LIC Community Boathouse', 'Environment', 40.737518, -73.731438),
('Build It Green NYC', 'Environment', 40.777170, -73.935630),
('CHiPS', 'Hunger', 40.678350, -73.982850),
('Hunger Free America', 'Hunger', 42.532610, -75.523540),
('Food Bank for New York City', 'Hunger', 42.956350, -74.377880),
('University Community Social Services', 'Hunger', 40.723010, -73.986410),
('St. Joes Soup Kitchen', 'Hunger', 40.732750, -74.000590),
('Masbia Soup Kitchen Network', 'Hunger', 40.634810, -73.988750),
('Broadway Community Lunch Program', 'Hunger', 40.807070, -73.965090),
('WhyHunger', 'Hunger', 40.802760, -73.9561709),
('Village Temple', 'Hunger', 40.733880, -73.992180),
('Just Food', 'Hunger', 40.582160, -73.987140),
('New York City Rescue Mission', 'Homelessness', 40.717520, -74.001560),
('The Bowery Mission', 'Homelessness', 40.721960, -73.992800),
('Coalition for the Homeless', 'Homelessness', 42.931519, -76.558762),
('Providence House', 'Homelessness', 40.690000, 73.932740),
('Homes For the Homeless', 'Homelessness', 40.729550, -73.989910),
('Partnership For the Homeless', 'Homelessness', 40.675450, -73.896980),
('ACE Programs for the Homeless', 'Homelessness', 40.758090, -73.857240),
('New Alternatives For LGBT Homeless Youth', 'Homelessness', 40.754742, -73.987900),
('New York City Homeless Services', 'Homelessness', 40.725170, -73.991720),
('The Dwelling Place womens', 'Homelessness', 40.757599, -73.994209),
('BARC Shelter', 'Animals', 40.716000, -73.963707),
('Bideawee', 'Animals', 40.745930, -73.971110),
('Best Friends Lifesaving Center', 'Animals', 40.721531, -74.004112),
('Animal Haven', 'Animals', 40.716351, -74.001244),
('Sean Casey Animal Rescue', 'Animals', 40.697440, -73.979440),
('ASPCA Adoption Center', 'Animals', 40.780183, -73.945627),
('NYC New Beginning Animal Rescue', 'Animals', 40.780183, -73.945627),
('PAWS NY', 'Animals', 40.747246, -73.991706),
('Bobbi & the Strays', 'Animals', 40.7021239, -73.8804598),
('Literacy Partners Inc.', 'Education', 40.707686, -73.979440),
('AHRC New York City', 'Education', 40.70752, -74.00736),
('Working in Support of Education', 'Education', 40.759218, -73.966905),
('Learning Leaders', 'Education', 40.707686, -74.007666),
('Education Through Music', 'Education', 40.65283, -73.938414),
('The Kabbalah Centre', 'Education', 40.714751, -73.962209),
('Make the Road New York', 'Education', 40.698416, -73.915796),
('AHRC', 'Education', 40.676586, -73.998476),
('Friendship Circle of Brooklyn', 'Education', 40.669003, -73.941962),
('Girls on the Run', 'Education', 40.700738, -73.987335);
SELECT * FROM Organizer1; | a7b831419dffce9910d927f9f58d36738ecb882f | [
"SQL"
] | 1 | SQL | redtail26/topteerfinalfinal | 4c17b528052b4f527ae0f8b109a1e906c30ee968 | e488665f145acdef1a98f82bca020614df42d7f3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.