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
<file_sep>object PrimeFactorCalculator { fun primeFactors(int: Int): List<Int> { var divisor = 2 var numerator = int val primeFactors = mutableListOf<Int>() while (numerator != 1) { if (numerator % divisor == 0) { numerator /= divisor primeFactors.add(divisor) } else { divisor++ } } return primeFactors } fun primeFactors(long: Long): List<Long> { var divisor = 2L var numerator = long val primeFactors = mutableListOf<Long>() while (numerator != 1L) { if (numerator % divisor == 0L) { numerator /= divisor primeFactors.add(divisor) } else { divisor++ } } return primeFactors } }<file_sep>object WordCount { fun phrase(phrase: String): Map<String, Int> { val words = phrase.split(" ", ",\n", ",") val trimmedWords = mutableListOf<String>() for (word in words) { var notQuoted = word if (notQuoted.startsWith("'") && notQuoted.endsWith("'")) { notQuoted = notQuoted.substring(1, notQuoted.length - 1) } val filtered = filter(notQuoted) if (filtered.isNotEmpty()) { trimmedWords.add(filtered) } } return trimmedWords.groupingBy { it }.eachCount() } fun filter(word: String): String { val sb = StringBuilder() for (ch in word) { if (ch.isLetterOrDigit() || ch.toInt() == 39) { sb.append(ch) } } return sb.toString().toLowerCase() } }<file_sep>object PascalsTriangle { fun computeTriangle(rows: Int): List<List<Int>> { if (rows < 0) { throw IllegalArgumentException("Rows can't be negative!") } val result = mutableListOf<List<Int>>() if (rows != 0) { for (line in 0..rows - 1) { val lineList = mutableListOf<Int>() for (position in 0..line) { if (line == position || position == 0) { lineList.add(1) } else { lineList.add(result[line - 1][position - 1] + result[line - 1][position]) } } result.add(lineList) } } return result } }<file_sep>class Anagram(private val word: String) { fun match(anagrams: Collection<String>): Set<String> { val results = mutableSetOf<String>() for (anagram in anagrams) { if (word.length == anagram.length && word.toLowerCase() != anagram.toLowerCase()) { val wordList = mutableListOf<Char>() for (ch in word.toLowerCase()) { wordList.add(ch) } val anagramList = mutableListOf<Char>() for (ch in anagram.toLowerCase()) { anagramList.add(ch) } wordList.sort() anagramList.sort() if (wordList == anagramList) { results.add(anagram) } } } return results } }<file_sep>object SumOfMultiples { fun sum(factors: Set<Int>, limit: Int): Int { val sums = mutableSetOf<Int>() for (factor in factors) { var counter = 0 while (counter * factor < limit) { sums.add(counter * factor) counter++ } } var total = 0 for (sum in sums) { total += sum } return total } }<file_sep>class Deque<T> { private var head: Element<T>? = null fun push(value: T) { if (head == null) { head = Element(value) } else { val lastNode = getLastElement() val newNode = Element(value) lastNode?.next = newNode newNode.prev = lastNode } } fun pop(): T? { if (head == null) { return null } else { val lastNode = getLastElement() lastNode?.prev?.next = null return lastNode?.value } } private fun getLastElement(): Element<T>? { var foundEnd = false var lastNode = head while (!foundEnd) { if (lastNode?.next == null) { foundEnd = true } else { lastNode = lastNode.next } } return lastNode } fun unshift(value: T) { val newNode = Element(value) newNode.next = head head?.prev = newNode head = newNode } fun shift(): T? { val value = head?.value head = head?.next return value } private data class Element<T>(val value: T, var prev: Element<T>? = null, var next: Element<T>? = null) }<file_sep>object Hexadecimal { fun toDecimal(s: String): Int { var result = 0.0 val reversedInput = s.toLowerCase().toCharArray().reversed() println(reversedInput) var foundIllegalInput = false val legalChars = listOf('a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9') for ((index, ch) in reversedInput.withIndex()) { if (ch !in legalChars) { foundIllegalInput = true } else { if (ch.isDigit()) { result += Integer.parseInt(ch.toString()) * Math.pow(16.0, index.toDouble()) } else { result += (ch.toInt() - 87) * Math.pow(16.0, index.toDouble()) } } } if (foundIllegalInput) { result = 0.0 } return result.toInt() } }
0bdd47e801eec1fe40599ffbab4ce2ad72253f0b
[ "Kotlin" ]
7
Kotlin
johngodfrey/worksheet-one
960104dd4f2a051dd5c7c47fcc8c2f83330a2983
60871b1eb6b7a0f05e8a008e94e0ff5bba59e431
refs/heads/master
<file_sep>use crate::{ camera::Camera, hittable_list::random_scene, vec3::{Color, Point, Vec3}, }; use rand::prelude::*; pub fn process() { let mut rng = rand::thread_rng(); // Image struct AspectRatio { width: usize, height: usize, } impl AspectRatio { fn ratio(&self) -> f64 { self.width as f64 / self.height as f64 } } let aspect_ratio = AspectRatio { width: 3, height: 2, }; let image_width = 1200; let image_height = image_width * aspect_ratio.height / aspect_ratio.width; let samples_per_pixel = 500; let max_depth = 50; // World let world = random_scene(&mut rng); // Camera let lookfrom = Point::new(13.0, 2.0, 3.0); let lookat = Point::new(0.0, 0.0, 0.0); let vup = Vec3::new(0.0, 1.0, 0.0); let dist_to_focus = 10.0; let aperture = 0.1; let camera = Camera::new( lookfrom, lookat, vup, 20.0, aspect_ratio.ratio(), aperture, dist_to_focus, ); // Render println!("P3\n{} {}\n255", image_width, image_height); for j in (0..image_height).rev() { for i in 0..image_width { let mut color = Color::default(); for _ in 0..samples_per_pixel { let u = (i as f64 + rng.gen::<f64>()) / (image_width - 1) as f64; let v = (j as f64 + rng.gen::<f64>()) / (image_height - 1) as f64; let ray = camera.ray(u, v, &mut rng); color += ray.color(&world, &mut rng, max_depth); } println!("{}", color.to_string(samples_per_pixel as f64)); } } } <file_sep>use rand::prelude::*; #[derive(Debug, Clone, Copy, Default)] pub struct Vec3 { e: [f64; 3], } impl Vec3 { pub fn new(e0: f64, e1: f64, e2: f64) -> Self { Self { e: [e0, e1, e2] } } pub fn new_random(rng: &mut dyn rand::RngCore) -> Self { Self { e: [rng.gen(), rng.gen(), rng.gen()], } } pub fn new_random_range<R>(rng: &mut dyn rand::RngCore, range: R) -> Self where R: rand::distributions::uniform::SampleRange<f64> + Clone, { Self { e: [ rng.gen_range(range.clone()), rng.gen_range(range.clone()), rng.gen_range(range), ], } } pub fn new_random_in_unit_sphere(rng: &mut dyn rand::RngCore) -> Self { loop { let p = Vec3::new_random_range(rng, -1.0..1.0); if p.length_squared() >= 1.0 { continue; } return p; } } pub fn new_random_unit(rng: &mut dyn rand::RngCore) -> Self { Self::new_random_in_unit_sphere(rng).unit() } pub fn new_random_in_hemisphere(rng: &mut dyn rand::RngCore, normal: &Vec3) -> Self { let in_unit_sphere = Self::new_random_in_unit_sphere(rng); if in_unit_sphere.dot(normal) > 0.0 { in_unit_sphere } else { -in_unit_sphere } } pub fn new_random_in_unit_disk(rng: &mut dyn rand::RngCore) -> Self { loop { let p = Self::new(rng.gen_range(-1.0..=1.0), rng.gen_range(-1.0..=1.0), 0.0); if p.length_squared() >= 1.0 { continue; } return p; } } pub fn length_squared(&self) -> f64 { self[0] * self[0] + self[1] * self[1] + self[2] * self[2] } pub fn length(&self) -> f64 { self.length_squared().sqrt() } pub fn dot(&self, rhs: &Self) -> f64 { self[0] * rhs[0] + self[1] * rhs[1] + self[2] * rhs[2] } pub fn cross(&self, rhs: &Self) -> Self { Self::new( self[1] * rhs[2] - self[2] * rhs[1], self[2] * rhs[0] - self[0] * rhs[2], self[0] * rhs[1] - self[1] * rhs[0], ) } pub fn unit(self) -> Self { let len = self.length(); self / len } pub fn to_string(&self, samples_per_pixel: f64) -> String { let scale = 1.0 / samples_per_pixel; format!( "{} {} {}", (256.0 * (self[0] * scale).sqrt().clamp(0.0, 0.999)) as i64, (256.0 * (self[1] * scale).sqrt().clamp(0.0, 0.999)) as i64, (256.0 * (self[2] * scale).sqrt().clamp(0.0, 0.999)) as i64, ) } pub fn is_near_zero(&self) -> bool { let s = 1e-8; self[0].abs() < s && self[1].abs() < s && self[2].abs() < s } pub fn reflect(&self, n: &Vec3) -> Self { *self - 2.0 * self.dot(n) * *n } pub fn refract(&self, n: &Vec3, etai_over_etat: f64) -> Self { let cos_theta = { let tmp = (-*self).dot(n); if tmp < 1.0 { tmp } else { 1.0 } }; let r_out_perp = etai_over_etat * (*self + cos_theta * *n); let r_out_parallel = -(1.0 - r_out_perp.length_squared()).abs().sqrt() * *n; r_out_perp + r_out_parallel } } impl std::ops::Neg for Vec3 { type Output = Vec3; fn neg(self) -> Self::Output { Vec3::new(-self[0], -self[1], -self[2]) } } impl std::ops::Add for Vec3 { type Output = Vec3; fn add(self, other: Vec3) -> Self::Output { Vec3::new(self[0] + other[0], self[1] + other[1], self[2] + other[2]) } } impl std::ops::AddAssign for Vec3 { fn add_assign(&mut self, rhs: Vec3) { self[0] += rhs[0]; self[1] += rhs[1]; self[2] += rhs[2]; } } impl std::ops::Sub for Vec3 { type Output = Vec3; fn sub(self, other: Vec3) -> Self::Output { Vec3::new(self[0] - other[0], self[1] - other[1], self[2] - other[2]) } } impl std::ops::SubAssign for Vec3 { fn sub_assign(&mut self, rhs: Vec3) { self[0] -= rhs[0]; self[1] -= rhs[1]; self[2] -= rhs[2]; } } impl std::ops::Mul<f64> for Vec3 { type Output = Vec3; fn mul(self, rhs: f64) -> Self::Output { Vec3::new(self[0] * rhs, self[1] * rhs, self[2] * rhs) } } impl std::ops::MulAssign<f64> for Vec3 { fn mul_assign(&mut self, rhs: f64) { self[0] *= rhs; self[1] *= rhs; self[2] *= rhs; } } impl std::ops::Mul<Vec3> for f64 { type Output = Vec3; fn mul(self, rhs: Vec3) -> Self::Output { rhs * self } } impl std::ops::Mul<Vec3> for Vec3 { type Output = Vec3; fn mul(self, rhs: Vec3) -> Self::Output { Vec3::new(self[0] * rhs[0], self[1] * rhs[1], self[2] * rhs[2]) } } impl std::ops::Div<f64> for Vec3 { type Output = Vec3; fn div(self, rhs: f64) -> Self::Output { Vec3::new(self[0] / rhs, self[1] / rhs, self[2] / rhs) } } impl std::ops::DivAssign<f64> for Vec3 { fn div_assign(&mut self, rhs: f64) { self[0] /= rhs; self[1] /= rhs; self[2] /= rhs; } } impl std::ops::Index<usize> for Vec3 { type Output = f64; fn index(&self, index: usize) -> &Self::Output { &self.e[index] } } impl std::ops::IndexMut<usize> for Vec3 { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.e[index] } } pub type Point = Vec3; pub type Direction = Vec3; pub type Color = Vec3; #[test] fn test_length() { let e = [10.0, 20.0, 30.0]; let v = Vec3::new(e[0], e[1], e[2]); let ls = v.length_squared(); let ls_ans = (e[0] * e[0] + e[1] * e[1] + e[2] * e[2]) as i32; assert_eq!(ls_ans, 1400); assert_eq!(ls.round() as i32, ls_ans); let l = v.length(); let l_ans: i32 = f64::from(ls_ans).sqrt().round() as i32; assert_eq!(l_ans, 37); assert_eq!(l.round() as i32, l_ans); } #[test] fn test_neg() { let l = Vec3::new(10.0, 20.0, 30.0); let v = -l; assert_eq!(v[0].round() as i64, -10); assert_eq!(v[1].round() as i64, -20); assert_eq!(v[2].round() as i64, -30); let v = -v; assert_eq!(v[0].round() as i64, 10); assert_eq!(v[1].round() as i64, 20); assert_eq!(v[2].round() as i64, 30); } #[test] fn test_add() { let l = Vec3::new(10.0, 20.0, 30.0); let r = Vec3::new(10.0, 20.0, 30.0); let v = l + r; assert_eq!(v[0].round() as i64, 20); assert_eq!(v[1].round() as i64, 40); assert_eq!(v[2].round() as i64, 60); } #[test] fn test_add_assign() { let mut l = Vec3::new(10.0, 20.0, 30.0); let r = Vec3::new(10.0, 20.0, 30.0); l += r; assert_eq!(l[0].round() as i64, 20); assert_eq!(l[1].round() as i64, 40); assert_eq!(l[2].round() as i64, 60); } #[test] fn test_sub() { let l = Vec3::new(10.0, 20.0, 30.0); let r = Vec3::new(5.0, 10.0, 15.0); let v = l - r; assert_eq!(v[0].round() as i64, 5); assert_eq!(v[1].round() as i64, 10); assert_eq!(v[2].round() as i64, 15); } #[test] fn test_sub_assign() { let mut l = Vec3::new(10.0, 20.0, 30.0); let r = Vec3::new(5.0, 10.0, 15.0); l -= r; assert_eq!(l[0].round() as i64, 5); assert_eq!(l[1].round() as i64, 10); assert_eq!(l[2].round() as i64, 15); } #[test] fn test_mul() { let l = Vec3::new(10.0, 20.0, 30.0); let r = 3.0; let v = l * r; assert_eq!(v[0].round() as i64, 30); assert_eq!(v[1].round() as i64, 60); assert_eq!(v[2].round() as i64, 90); } #[test] fn test_mul_assign() { let mut l = Vec3::new(10.0, 20.0, 30.0); let r = 3.0; l *= r; assert_eq!(l[0].round() as i64, 30); assert_eq!(l[1].round() as i64, 60); assert_eq!(l[2].round() as i64, 90); } #[test] fn test_div() { let l = Vec3::new(10.0, 20.0, 30.0); let r = 2.0; let v = l / r; assert_eq!(v[0].round() as i64, 5); assert_eq!(v[1].round() as i64, 10); assert_eq!(v[2].round() as i64, 15); } #[test] fn test_div_assign() { let mut l = Vec3::new(10.0, 20.0, 30.0); let r = 2.0; l /= r; assert_eq!(l[0].round() as i64, 5); assert_eq!(l[1].round() as i64, 10); assert_eq!(l[2].round() as i64, 15); } #[test] fn test_index() { let l = Vec3::new(10.0, 20.0, 30.0); assert_eq!(l[0].round() as i64, 10); assert_eq!(l[1].round() as i64, 20); assert_eq!(l[2].round() as i64, 30); } #[test] fn test_index_mut() { let mut l = Vec3::new(10.0, 20.0, 30.0); l[0] = 5.0; l[1] = 10.0; l[2] = 15.0; assert_eq!(l[0].round() as i64, 5); assert_eq!(l[1].round() as i64, 10); assert_eq!(l[2].round() as i64, 15); } <file_sep>use crate::{ hittable::HitRecord, ray::Ray, vec3::{Color, Vec3}, }; use rand::{Rng, RngCore}; pub trait Material: CloneMaterial { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray, rng: &mut dyn RngCore, ) -> bool; } pub trait CloneMaterial { fn clone_box(&self) -> Box<dyn Material>; } impl<T> CloneMaterial for T where T: 'static + Material + Clone, { fn clone_box(&self) -> Box<dyn Material> { Box::new(self.clone()) } } impl Clone for Box<dyn Material> { fn clone(&self) -> Box<dyn Material> { self.clone_box() } } #[derive(Clone)] pub struct Lambertian { albedo: Color, } impl Lambertian { pub fn new(albedo: Color) -> Self { Self { albedo } } } impl Material for Lambertian { fn scatter( &self, _r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray, rng: &mut dyn RngCore, ) -> bool { let mut scatter_direction = rec.normal + Vec3::new_random_unit(rng); if scatter_direction.is_near_zero() { scatter_direction = rec.normal; } *scattered = Ray { origin: rec.point, direction: scatter_direction, }; *attenuation = self.albedo; true } } #[derive(Clone)] pub struct Metal { albedo: Color, fuzz: f64, } impl Metal { pub fn new(albedo: Color, fuzz: f64) -> Self { Self { albedo, fuzz: if fuzz < 1.0 { fuzz } else { 1.0 }, } } } impl Material for Metal { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray, rng: &mut dyn RngCore, ) -> bool { let reflected = r_in.direction.unit().reflect(&rec.normal); *scattered = Ray { origin: rec.point, direction: reflected + self.fuzz * Vec3::new_random_in_unit_sphere(rng), }; *attenuation = self.albedo; scattered.direction.dot(&rec.normal) > 0.0 } } #[derive(Clone)] pub struct Dielectric { index_of_refraction: f64, } impl Dielectric { pub fn new(index_of_refraction: f64) -> Self { Self { index_of_refraction, } } pub fn reflectance(cosine: f64, ref_idx: f64) -> f64 { // Use Schlick's approximation for reflectance. let r0 = (1.0 - ref_idx) / (1.0 + ref_idx); let r0 = r0 * r0; r0 + (1.0 - r0) * (1.0 - cosine).powf(5.0) } } impl Material for Dielectric { fn scatter( &self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray, rng: &mut dyn RngCore, ) -> bool { *attenuation = Color::new(1.0, 1.0, 1.0); let refraction_ratio = if rec.front_face { 1.0 / self.index_of_refraction } else { self.index_of_refraction }; let unit_direction = r_in.direction.unit(); let cos_theta = { let tmp = (-unit_direction).dot(&rec.normal); if tmp < 1.0 { tmp } else { 1.0 } }; let sin_theta = (1.0 - cos_theta * cos_theta).sqrt(); let cannot_refract = refraction_ratio * sin_theta > 1.0; let direction = if cannot_refract || Self::reflectance(cos_theta, refraction_ratio) > rng.gen() { unit_direction.reflect(&rec.normal) } else { unit_direction.refract(&rec.normal, refraction_ratio) }; *scattered = Ray { origin: rec.point, direction, }; true } } <file_sep>use crate::{ ray::{degrees_to_radians, Ray}, vec3::{Point, Vec3}, }; pub struct Camera { origin: Point, lower_left_corner: Point, horizontal: Vec3, vertical: Vec3, u: Vec3, v: Vec3, _w: Vec3, lens_radius: f64, } impl Camera { pub fn new( lookfrom: Point, lookat: Point, vup: Vec3, vfov: f64, // vertical field-of-view in degrees aspect_ratio: f64, aperture: f64, focus_disk: f64, ) -> Self { let theta = degrees_to_radians(vfov); let h = (theta / 2.0).tan(); let viewport_height = 2.0 * h; let viewport_width = aspect_ratio * viewport_height; let w = (lookfrom - lookat).unit(); let u = vup.cross(&w).unit(); let v = w.cross(&u); let origin = lookfrom; let horizontal = focus_disk * viewport_width * u; let vertical = focus_disk * viewport_height * v; let lower_left_corner = origin - horizontal / 2.0 - vertical / 2.0 - focus_disk * w; let lens_radius = aperture / 2.0; Self { origin, lower_left_corner, horizontal, vertical, u, v, _w: w, lens_radius, } } pub fn ray(&self, s: f64, t: f64, rng: &mut dyn rand::RngCore) -> Ray { let rd = self.lens_radius * Vec3::new_random_in_unit_disk(rng); let offset = self.u * rd[0] + self.v * rd[1]; Ray { origin: self.origin + offset, direction: self.lower_left_corner + s * self.horizontal + t * self.vertical - self.origin - offset, } } } <file_sep>use crate::{ material::{Lambertian, Material}, ray::Ray, vec3::{Color, Point, Vec3}, }; use std::rc::Rc; #[derive(Clone)] pub struct HitRecord { pub point: Point, pub normal: Vec3, pub material: Rc<dyn Material>, pub t: f64, pub front_face: bool, } impl HitRecord { pub fn set_face_normal(&mut self, r: &Ray, outward_normal: &Vec3) { self.front_face = r.direction.dot(outward_normal) < 0.0; self.normal = if self.front_face { *outward_normal } else { -*outward_normal }; } } impl Default for HitRecord { fn default() -> Self { Self { point: Point::default(), normal: Vec3::default(), material: Rc::new(Lambertian::new(Color::default())), t: 0.0, front_face: false, } } } pub trait Hittable { fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool; } <file_sep>mod camera; mod hittable; mod hittable_list; pub mod io; mod material; mod ray; mod sphere; mod vec3; <file_sep>use crate::{ hittable::{HitRecord, Hittable}, material::{Lambertian, Material}, ray::Ray, vec3::{Color, Point}, }; use std::rc::Rc; #[derive(Clone)] pub struct Sphere { center: Point, radius: f64, material: Rc<dyn Material>, } impl Sphere { pub fn new(center: Point, radius: f64, material: Rc<dyn Material>) -> Self { Self { center, radius, material, } } } impl Hittable for Sphere { #[allow(clippy::suspicious_operation_groupings)] fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { let oc = r.origin - self.center; let a = r.direction.length_squared(); let half_b = oc.dot(&r.direction); let c = oc.length_squared() - self.radius * self.radius; let discriminant = half_b * half_b - a * c; if discriminant < 0.0 { return false; } let sqrtd = discriminant.sqrt(); let mut root = (-half_b - sqrtd) / a; if root < t_min || t_max < root { root = (-half_b + sqrtd) / a; if root < t_min || t_max < root { return false; } } rec.t = root; rec.point = r.at(rec.t); let outward_normal = (rec.point - self.center) / self.radius; rec.set_face_normal(r, &outward_normal); rec.material = self.material.clone(); true } } impl Default for Sphere { fn default() -> Self { Sphere::new( Point::default(), f64::default(), Rc::new(Lambertian::new(Color::default())), ) } } <file_sep>use crate::{ hittable::{HitRecord, Hittable}, vec3::Color, vec3::{Direction, Point}, }; #[derive(Default, Clone)] pub struct Ray { pub origin: Point, pub direction: Direction, } impl Ray { pub fn at(&self, t: f64) -> Point { self.origin + self.direction * t } pub fn color<T>(&self, world: &T, rng: &mut dyn rand::RngCore, depth: i64) -> Color where T: Hittable, { if depth <= 0 { return Color::default(); } let mut rec = HitRecord::default(); if world.hit(&self, 0.001, std::f64::INFINITY, &mut rec) { let mut scattered = Ray::default(); let mut attenuation = Color::default(); if rec .material .scatter(&self, &rec, &mut attenuation, &mut scattered, rng) { return attenuation * scattered.color(world, rng, depth - 1); } else { return Color::default(); } } let unit_direction = self.direction.unit(); let t = 0.5 * (unit_direction[1] + 1.0); (1.0 - t) * Color::new(1.0, 1.0, 1.0) + t * Color::new(0.5, 0.7, 1.0) } } #[allow(clippy::suspicious_operation_groupings)] #[allow(dead_code)] fn hit_sphere(center: &Point, radius: f64, r: &Ray) -> f64 { let oc = r.origin - *center; let a = r.direction.length_squared(); let half_b = oc.dot(&r.direction); let c = oc.length_squared() - radius * radius; let discriminant = half_b * half_b - a * c; if discriminant < 0.0 { -1.0 } else { (-half_b - discriminant.sqrt()) / a } } pub fn degrees_to_radians(degrees: f64) -> f64 { degrees * std::f64::consts::PI / 180.0 } <file_sep>This project is based on this website. [https://github.com/RayTracing/raytracing.github.io](https://github.com/RayTracing/raytracing.github.io) <file_sep>fn main() { ray_tracing_in_one_weekend::io::process(); } <file_sep>#!/bin/bash cargo run --release > image.ppm && convert image.ppm image.png <file_sep>use crate::{ hittable::{HitRecord, Hittable}, material::{Dielectric, Lambertian, Material, Metal}, ray::Ray, sphere::Sphere, vec3::{Color, Point}, }; use rand::prelude::*; use std::rc::Rc; #[derive(Default, Clone)] pub struct HittableList<T>(Vec<T>) where T: Hittable; impl<T> HittableList<T> where T: Hittable, { #[allow(dead_code)] pub fn clear(&mut self) { self.0.clear(); } #[allow(dead_code)] pub fn push(&mut self, item: T) { self.0.push(item); } } impl<T> Hittable for HittableList<T> where T: Hittable, { fn hit(&self, r: &Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool { let mut temp = HitRecord::default(); let mut hit_anything = false; let mut closest_so_far = t_max; for item in self.0.iter() { if item.hit(r, t_min, closest_so_far, &mut temp) { hit_anything = true; closest_so_far = temp.t; *rec = temp.clone(); } } hit_anything } } pub fn random_scene(rng: &mut dyn rand::RngCore) -> HittableList<Sphere> { let ground_material = Rc::new(Lambertian::new(Color::new(0.5, 0.5, 0.5))); let mut v = vec![Sphere::new( Point::new(0.0, -1000.0, 0.0), 1000.0, ground_material, )]; for a in -11..11 { for b in -11..11 { let choose_mat: f64 = rng.gen(); let center = Point::new( a as f64 + 0.9 * rng.gen::<f64>(), 0.2, b as f64 + 0.9 * rng.gen::<f64>(), ); if (center - Point::new(4.0, 0.2, 0.0)).length() > 0.9 { let sphere_material: Rc<dyn Material> = if choose_mat < 0.8 { // diffuse let albedo = Color::new_random(rng) * Color::new_random(rng); Rc::new(Lambertian::new(albedo)) } else if choose_mat < 0.95 { // metal let albedo = Color::new_random_range(rng, 0.5..=1.0); let fuzz = rng.gen_range(0.0..=0.5); Rc::new(Metal::new(albedo, fuzz)) } else { // glass Rc::new(Dielectric::new(1.5)) }; v.push(Sphere::new(center, 0.2, sphere_material)); } } } v.push(Sphere::new( Point::new(0.0, 1.0, 0.0), 1.0, Rc::new(Dielectric::new(1.5)), )); v.push(Sphere::new( Point::new(-4.0, 1.0, 0.0), 1.0, Rc::new(Lambertian::new(Color::new(0.4, 0.2, 0.1))), )); v.push(Sphere::new( Point::new(4.0, 1.0, 0.0), 1.0, Rc::new(Metal::new(Color::new(0.7, 0.6, 0.5), 0.0)), )); HittableList::<Sphere>(v) }
2093bb89a6485a20548f8887d50eb2f3c58d4e9f
[ "Markdown", "Rust", "Shell" ]
12
Rust
HiraokaTakuya/ray_tracing_in_one_weekend
81bbf41723dbf2e18bc9ba0007da76df5e404fe7
9d6588ccc7346d14e6414484fe49dc1cfd7b40a4
refs/heads/master
<repo_name>freelancer-Prince/Online-Courses<file_sep>/src/components/Course/Course.js import React from 'react'; import style from './Course.css'; const Course=(props)=>{ console.log(props) const {name,img,price,}=props.course; const handleAddCart=props.handleAddCart; return( <div className='course container'> <div className="row d-flex justify-content-center"> <div className="col-md-10 col-lg-10 course"> {/* <img src="" alt=""/> */} <p className='highlight'>{name}</p> <p><strong className='highlight'>${price}</strong></p> <button onClick={()=>handleAddCart(props.course)} className='btn-enroll'>Enroll Now</button> </div> </div> </div> ) } export default Course;<file_sep>/src/components/CourseWrapper/CourseWrap.js import React, { useState } from 'react'; import style from './CourseWrap.css'; import Course from '../Course/Course'; import fakeData from '../../fakeData/index'; const CourseWrap=()=>{ const fakeData12=fakeData; console.log(fakeData12[0].name) const [courses, setCourses]=useState(fakeData12); const [cart, setCart]=useState([]) //button click handler const handleAddCart=(course)=>{ const newCart=[...cart,course]; setCart(newCart); } //Calculation courses price const total=cart.reduce( (total,course)=>total + course.price,0); //formate course price const grandTotal=(total).toFixed(2) return( <div className='Wrap'> <div className="row"> <div className="col-md-9 col-lg-9 col-sm-9 col-xl-9 courseWraps"> <div className="course-title ml-2"> <strong>All Courses</strong> </div> { courses.map(course=><Course course={course} handleAddCart={handleAddCart}></Course>) } </div> <div className="col-md-3 col-lg-3 col-sm-3 col-xl-3 cartWrap p-2"> <small><strong>Order summery</strong></small> <p><strong>Count:{cart.length}</strong></p> <p><strong>SubTotal:{grandTotal}</strong></p> <p><strong>Total:{grandTotal}</strong></p> <button className='cart-info'>cart info</button> </div> </div> </div> ) } export default CourseWrap;<file_sep>/src/components/Header/Header.js import React from 'react'; import logo from '../../images/logo.png'; import style from './Header.css'; import headerlogo from '../../images/logo1.png'; const Header=()=>{ return( <div className='header'> <div className="logo"> <img src={headerlogo} alt=""/> <h1>Quality Learning For EveryOne</h1> </div> <div className="nav"> <nav> <a href="/course">All Course</a> <a href="/books">Books</a> <a href="/bootcamps">Bootcamps</a> <a href="/free-course">Free Courses</a> <a href="/premium-course">Premium Course</a> </nav> </div> </div> ) } export default Header;
75a86d663765b705d02b49f8367a90ee887d059b
[ "JavaScript" ]
3
JavaScript
freelancer-Prince/Online-Courses
8b81a4ee0dc290d14ac295b4f241be9b933b9102
891cf28cbc6fa795dc5c8ddc15f9868047912a6c
refs/heads/master
<repo_name>Liyang-ing/ISB<file_sep>/Master/Helo/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using WatiN.Core; using WatiN.Core.Native.Windows; using System.IO; using System.Text.RegularExpressions; using System.Net; using MySql.Data.MySqlClient; using System.Diagnostics; using System.IO.Ports; using System.Threading; namespace Helo { public partial class Form1 : System.Windows.Forms.Form { private Process _browserProcess; private IE _browser; private IE browser { get { //瀏覽器執行個體還在 if (_browser != null && !_browserProcess.HasExited) { try { //測試Browser是否可使用 IntPtr tmp = _browser.hWnd; } catch { _browser = null; _browserProcess = null; } } //如果執行個體不在 if (_browser == null || _browserProcess == null || _browserProcess.HasExited) { var FindIE = Find.ByUrl(new Regex(@"http://www.emome.net/")); //開一個新的IE if (IE.Exists<IE>(FindIE)) _browser = IE.AttachTo<IE>(FindIE); else _browser = new IE(); _browserProcess = Process.GetProcessById(_browser.ProcessID); } return _browser; } } int h; int i; int j; int k; int m; int numlo; int hey; int word; string number; public Form1() { //初始化控制項 InitializeComponent(); //設定等待網頁時間不超過10秒 Settings.WaitForCompleteTimeOut = 30; Settings.WaitUntilExistsTimeOut = 30; //避免執行緒受影響 System.Windows.Forms.Form.CheckForIllegalCrossThreadCalls = false; btnSend.Enabled = false; //btnSendBack.Enabled = false; //將讀取到的PORT放到選單中 string[] ports = SerialPort.GetPortNames(); for (int i = 0; i < ports.Length; i++) { txtCom.Text = ports[i].ToString(); comboBox1.Items.Add(txtCom.Text); } try { comboBox1.SelectedIndex = 1; } catch { } } //將字串淨空 private static string RxString = ""; //按鈕按下開始查詢網內外 public void btnGo_Click(object sender, EventArgs e) { label7.Text = ""; lblResult2.Text = "等待中..."; //找尋最大id的指令 string a = "select * from tel where id=(select max(id) from tel)"; //與資料庫連線 String connString1 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn1 = new MySqlConnection(connString1); MySqlCommand command1 = conn1.CreateCommand(); command1.CommandText = a.ToString(); try { conn1.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader1 = command1.ExecuteReader(); while (reader1.Read()) { j = (int)reader1["id"]; txtMaxId.Text = j.ToString(); } conn1.Close(); progressBar2.Maximum = j*2; progressBar2.Value = 0; progressBar2.Step = 1; MessageBox.Show("程式開始,會關閉目前所有IE網頁,請準備好再按確定","注意!"); System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses(); //關閉所有的IE foreach (System.Diagnostics.Process myProcess in myProcesses) { if (myProcess.ProcessName.ToUpper() == "IEXPLORE") { myProcess.Kill(); } } //輸入網頁帳號密碼 try { //將IE隱藏起來 //browser.ShowWindow(NativeMethods.WindowShowStyle.Hide); browser.GoTo("http://www.emome.net/"); browser.WaitForComplete(); browser.Image(Find.ByAlt("登入")).Click(); browser.TextField(Find.ById("uid")).TypeText("0920625964"); browser.TextField(Find.ById("pw")).TypeText("288266"); browser.Image(Find.ByAlt("登入會員")).Click(); browser.WaitForComplete(); //到網內外判斷網站,開始辨別網內外 browser.GoTo("http://auth.emome.net/emome/membersvc/AuthServlet?serviceId=mobilebms&url=qryTelnum.jsp"); browser.WaitForComplete(); } catch { MessageBox.Show("網頁異常,請稍後再試!"); } //藉由"id"欄位取得資料庫內的號碼 for (i = 1; i <= j; i++) { progressBar2.Value += progressBar2.Step; string getting = "Select number from tel where id = "+i+""; String connString = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = getting.ToString(); txtId.Text = i.ToString(); try { conn.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { txtNumber.Text = reader["number"].ToString(); } //判斷是否還有需要辨別的號碼 if (txtNumber.Text != "Finding...") { browser.TextField(Find.ById("telnum")).TypeText(txtNumber.Text.Trim()); browser.Button(Find.ById("btn_submit")).Click(); conn.Close(); browser.WaitForComplete(); try { string myHtml = browser.Body.Parent.OuterHtml; string result = myHtml; int first = result.IndexOf("您所查詢之行動門號"); int last = result.LastIndexOf("為「"); string cut1 = result.Substring(first + 21, last - first - 17); if (cut1 == "網內") { txtResult.Text = txtNumber.Text + " 此號碼為中華電信"; string b = "Update tel SET ope='c' WHERE id='" + i + "'"; String connString2 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn2 = new MySqlConnection(connString2); MySqlCommand command2 = conn2.CreateCommand(); command2.CommandText = b.ToString(); try { conn2.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader2 = command2.ExecuteReader(); while (reader2.Read()) { ; } conn2.Close(); } else { txtResult.Text = txtNumber.Text + " 此號碼並不是中華電信"; string b = "Update tel SET ope='n' WHERE id='" + i + "'"; String connString2 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn2 = new MySqlConnection(connString2); MySqlCommand command2 = conn2.CreateCommand(); command2.CommandText = b.ToString(); try { conn2.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader2 = command2.ExecuteReader(); while (reader2.Read()) { ; } conn2.Close(); } } catch { //MessageBox.Show(ex.Message); } txtNumber.Text = "中華電信判斷結束"; } } if (txtNumber.Text == "中華電信判斷結束") { browser.GoTo("http://www.fetnet.net/ecare/eService/web/public/forwardController.do?forwardPage=ucs/queryNetworkType/esqnt01&csType=cs"); browser.WaitForComplete(); for (int aj = 1; aj <= j; aj++) { progressBar2.Value += progressBar2.Step; string getting = "Select ope from tel where id = " + aj + ""; String connString = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = getting.ToString(); txtId.Text = aj.ToString(); try { conn.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { txtOpe.Text = reader["ope"].ToString(); } conn.Close(); if (txtOpe.Text == "n") { string getnum = "Select number from tel where id = " + aj + ""; String connString3 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn3 = new MySqlConnection(connString3); MySqlCommand command3 = conn3.CreateCommand(); command3.CommandText = getnum.ToString(); try { conn3.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader3 = command3.ExecuteReader(); while (reader3.Read()) { txtNumber.Text = reader3["number"].ToString(); } try { browser.TextField("msisdn").TypeText(txtNumber.Text); browser.Button(Find.ById("queryButton")).Click(); } catch (Exception ex) { MessageBox.Show(ex.Message); } try { string myHtml2 = browser.Body.Parent.OuterHtml; string result2 = myHtml2; int first2 = result2.IndexOf("「<font color="); int last2 = result2.LastIndexOf("</font>」門號"); string cut2 = result2.Substring(first2 + 19, last2 - first2 - 19); if (cut2 == "網內") { txtResult.Text = txtNumber.Text + " 此號碼為遠傳電信"; string b = "Update tel SET ope='f' WHERE id='" + aj + "'"; String connString2 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn2 = new MySqlConnection(connString2); MySqlCommand command2 = conn2.CreateCommand(); command2.CommandText = b.ToString(); try { conn2.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader2 = command2.ExecuteReader(); while (reader2.Read()) { ; } conn2.Close(); } else { txtResult.Text = txtNumber.Text + " 此號碼並不是遠傳電信"; string b = "Update tel SET ope='n' WHERE id='" + aj + "'"; String connString2 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn2 = new MySqlConnection(connString2); MySqlCommand command2 = conn2.CreateCommand(); command2.CommandText = b.ToString(); try { conn2.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader2 = command2.ExecuteReader(); while (reader2.Read()) { ; } conn2.Close(); } } catch(Exception ex) { MessageBox.Show(ex.Message); } } } } browser.Close(); txtNumber.Text = "號碼已查詢完畢"; btnGo.Enabled = false; lblResult2.Text = "成功!"; btnSendBack.Enabled = true; } //初始化RS232 private void btnInit_Click(object sender, EventArgs e) { try { serialPort.PortName = comboBox1.Text; if (!serialPort.IsOpen) { serialPort.Open(); btnInit.Enabled = false; //傳送 "S" 表示開始接收資料 serialPort.Write("s"); Thread.Sleep(100); //Delay 0.1秒 } } catch { MessageBox.Show("請選擇正確的端口,並確認端口是否正確"); } //再次尋找最大的id值,避免混在一起 string a = "select * from tel where id=(select max(id) from tel)"; String connString1 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn1 = new MySqlConnection(connString1); MySqlCommand command1 = conn1.CreateCommand(); command1.CommandText = a.ToString(); try { conn1.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader1 = command1.ExecuteReader(); while (reader1.Read()) { h = (int)reader1["id"]; h = h + 1; } conn1.Close(); if (txtRead.Text == null) { MessageBox.Show("傳輸異常,目前無資料輸入","警告"); serialPort.Close(); btnInit.Enabled = true; } else { btnSend.Enabled = true; } } private void serialPortRead_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { RxString = serialPort.ReadExisting(); this.Invoke(new EventHandler(DisplayText)); } catch (System.TimeoutException) { } } private void DisplayText(object s, EventArgs e) { txtRead.AppendText(RxString); } private void btnSend_Click(object sender, EventArgs e) { lblResult1.Text = "等待中..."; int a = 0; int HowMuchLong; string length = txtRead.Text.Trim(); if (txtRead.Text != "") { HowMuchLong = length.Length; HowMuchLong = HowMuchLong / 11; progressBar1.Maximum = HowMuchLong;//設置最大長度值 progressBar1.Value = 0;//設置當前值 progressBar1.Step = 1;//設置每次增長多少 for (int abc = 0; abc < HowMuchLong; abc++) { //取得來源字串 string SRC = txtRead.Text.Trim(); //將取得的字串 轉換成陣列 char[] ArraySRC = SRC.ToCharArray(); //使用迴圈取出該陣列的元素 逐一加到結果輸出 for (int k = a; k < 10 + a; k++) { txtCatched.Text = txtCatched.Text + ArraySRC[k].ToString(); } progressBar1.Value += progressBar1.Step; for (i = 0; i < h; i++) { hey = 0; string catched = "Select number from tel where id = " + i + ""; String connString2 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn2 = new MySqlConnection(connString2); MySqlCommand command2 = conn2.CreateCommand(); command2.CommandText = catched.ToString(); try { conn2.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader = command2.ExecuteReader(); while (reader.Read()) { txtRightNumber.Text = reader["number"].ToString(); } if (txtRightNumber.Text == txtCatched.Text) { hey = 1; break; } } if (hey != 1) check(); txtCatched.Text = ""; a += 11; if (abc + 1 == HowMuchLong) { lblResult1.Text = "成功!"; btnSend.Enabled = false; } } } else { lblResult1.Text = "無號碼"; btnSend.Enabled = false; } } //函式check()將電話號碼輸入進資料庫 private void check() { string getting = "INSERT INTO tel (number,ope) VALUES ('" + txtCatched.Text + "', 'n');"; String connString = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = getting.ToString(); try { conn.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); } conn.Close(); } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { serialPort.Close(); } private void btnSendBack_Click(object sender, EventArgs e) { txtRead.Text = ""; Thread.Sleep(100); //Delay 0.1秒 lblResult3.Text = "等待中..."; //第三次尋找最大的id值,避免與前兩次混在一起 string a = "select * from tel where id=(select max(id) from tel)"; String connString1 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn1 = new MySqlConnection(connString1); MySqlCommand command1 = conn1.CreateCommand(); command1.CommandText = a.ToString(); try { conn1.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader1 = command1.ExecuteReader(); while (reader1.Read()) { k = (int)reader1["id"]; m = k; k = k + 1; } conn1.Close(); for (int i = 1; i < k; i++) { string gettingnumber = "Select number from tel where id = " + i + ""; String connString = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn = new MySqlConnection(connString); MySqlCommand command = conn.CreateCommand(); command.CommandText = gettingnumber.ToString(); try { conn.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { txtRead.Text = txtRead.Text + reader["number"].ToString(); } conn.Close(); string gettingope = "Select ope from tel where id = " + i + ""; String connString5 = "Server=localhost;Port=3306;Database=data;uid=root;password=<PASSWORD>;"; MySqlConnection conn5 = new MySqlConnection(connString5); MySqlCommand command5 = conn5.CreateCommand(); command5.CommandText = gettingope.ToString(); try { conn5.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } MySqlDataReader reader5 = command5.ExecuteReader(); while (reader5.Read()) { txtRead.Text = txtRead.Text + reader5["ope"].ToString(); } conn5.Close(); btnSendBack.Enabled = false; } numlo = txtRead.Text.Length; m = numlo/11; progressBar3.Maximum = numlo+1; progressBar3.Step = 1; progressBar3.Value = 1; word = 0; try { //傳送"b"讓8051開始接收資料 serialPort.Write("b"); Thread.Sleep(100); //Delay 0.1秒 /* if (m < 10) { serialPort.Write("0" + m.ToString()); } else { serialPort.Write(m.ToString()); } */ } catch (Exception ex) { MessageBox.Show(ex.Message + " 請連接好再試!", "錯誤"); word = 1; } if (word == 0) { for (int i = 0; i < numlo; i++) { //將視窗內字串變為單一字元傳送 number = txtRead.Text[i].ToString(); try { serialPort.Write(number); Thread.Sleep(100); //Delay 0.1秒 } catch (Exception ex) { MessageBox.Show(ex.Message); word = 1; } progressBar3.Value += progressBar3.Step; } lblResult3.Text = "成功!"; //傳送"E"代表全部號碼傳輸完畢 serialPort.Write("E"); } else lblResult3.Text = "錯誤!"; } private void pictureBox1_Click(object sender, EventArgs e) { Application.Restart(); } private void button1_Click(object sender, EventArgs e) { serialPort.Write(txtRead.Text); } } } <file_sep>/README.md # 智慧型電話轉接系統設計與實現-Design and Implementation of Intelligent Switch Board ======== * 時間:2011/12 * 說明: 利用此系統可讓企業用戶在撥打手機號碼時,能夠有選擇相同的電信業者達到網內互打的效果,進而產生節費的功能。 # 硬體 ======== * 89C55-微控制器 * MT8870-DTMF解碼器 * FX-60-總機系統 * SIM5215-行動通訊模組 * AT24C08-8K的EEPROM # 程式 ======== * C * C# * MySQL <file_sep>/Client/system_control.c #include <reg52.h> #include <stdio.h> #include <stdlib.h> #define delay_time 150 #define wda 0xa0 #define rda 0xa1 sbit SCL= P0^0; sbit SDA= P0^1; sbit rel0= P0^2; sbit rel1= P0^3; sbit rel2= P0^4; sbit rel3= P0^5; sbit ledd= P0^6; sbit rr= P0^3; sbit work_o = P1^0; sbit work = P1^1; sbit work1 = P1^2; sbit work2 = P1^3; sbit work3 = P1^4; sbit chup = P1^5; int i,add=40,num=0,c=4; char c0,c1,c2,c3,c_tem; char a[]={"0953650579x"}; //目前 char b[]={"abcdefghijx"}; //儲存 char decimal[10]={'0','1','2','3','4','5','6','7','8','9'}; char str[]={"atd<0000000000>;"}; void delay(int d) { int i, j; for(i=0; i<d; i++) for(j=0; j<100; j++) ; } led_work() { ledd=0; delay(100); ledd=1; delay(100); } /*----------RS-232控制參數------------*/ Init_rs232() { PCON=0X80; SCON=0x50; TMOD=0x20; TH1=0xFF; //因為鮑率是115200所以是 0xFF ,石英震盪器是22.184M TR1=1; TI=1; } tx_char(unsigned char c) { while(1) if(TI) break; TI=0; SBUF=c; } tx_str(char *str) { do { tx_char(*str++); }while(*str!='\0'); } char rx_char() { while(1) if(RI) break; RI=0; return SBUF; } /*---------------------------------*/ /*********************DATASHEET要求********************/ void Start() { SDA=1; SCL=1; SDA=0; SCL=0; } void Stop() { SCL=0; SDA=0; SCL=1; SDA=1; } void NoAck () { SDA=1; SCL=1; SCL=0; } bit TestAck () { bit ErrorBit; SDA=1; SCL=1; ErrorBit=SDA; SCL=0; return(ErrorBit); } /*********************寫入DATA*******************/ void Write8bit(char input) { char temp; for(temp=8;temp!=0;temp--) { SDA=(bit)(input&0x80); SCL=1; SCL=0; input=input<<1; } } void Write24c08(char ch, char address) { EA=0; Start(); Write8bit(wda); TestAck (); Write8bit(address); TestAck (); Write8bit(ch); TestAck (); Stop(); delay(20); EA=1; } void Write24c08_uint(int dat,char address) { char hi8,lo8; hi8=dat/256; lo8=dat%256; Write24c08(hi8,address); delay(20); Write24c08(lo8,address+add); } /*********************讀取DATA********************/ char Read8bit() { char temp,rbyte=0; for(temp=8;temp!=0;temp--) { SCL=1; rbyte=rbyte<<1; rbyte=rbyte|((char)(SDA)); SCL=0; } return (rbyte); } char Read24c08(char address) { char ch; Start(); Write8bit(wda); TestAck(); Write8bit(address); TestAck(); Start(); Write8bit(rda); TestAck(); ch=Read8bit(); NoAck(); Stop(); return(ch); } int Read24c08_uint(char address) { int dat; char hi8,lo8; hi8=Read24c08(address); lo8=Read24c08(address+add);// dat=(256*hi8)+lo8; return (dat); } void s_send_computer() { if(c1=='s') { for(i=0;i<11;i++) //把暫存區的資料送到電腦 { printf("%c",a[i]); } c2=rx_char(); if(c2=='b') //把電腦的資料傳到記憶體 { printf("back_in\n"); while(1) { a[num]=rx_char(); Write24c08_uint(a[num],num);//傳到記憶體 delay(10); if(num==10) { num=0; break; } num++; } printf("back\n"); } } } number() { int c=4; while(1) { if(work==0) if(work1==0) if(work2==0) if(work3==1) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[1]; } } if(work==0) if(work1==0) if(work2==1) if(work3==0) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[2]; } } if(work==0) if(work1==0) if(work2==1) if(work3==1) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[3]; } } if(work==0) if(work1==1) if(work2==0) if(work3==0) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[4]; } } /****************/ if(work==0) if(work1==1) if(work2==0) if(work3==1) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[5]; } } if(work==0) if(work1==1) if(work2==1) if(work3==0) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[6]; } } if(work==0) if(work1==1) if(work2==1) if(work3==1) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[7]; } } if(work==1) if(work1==0) if(work2==0) if(work3==0) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[8]; } } if(work==1) if(work1==0) if(work2==0) if(work3==1) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[9]; } } /*******************/ if(work==1) if(work1==0) if(work2==1) if(work3==0) { if(work_o==1) { led_work(); delay(delay_time); str[c++]=decimal[0]; } } if(c==14) { c=4; break; } } for(i=4;i<14;i++) { a[i-4]=str[i]; } if(a[1]!='9') { rel0=0; for(i=0;i<6;i++) { rel0 =~rel0; delay(1000); } } } read_word() //讀!!!!!!!!! { for(i=0;i<11;i++) { c_tem=Read24c08_uint(i); delay(10); b[i]=c_tem; } } call_o() { if(b[10]=='f' || b[10]=='x') { puts(str); } if(b[10]=='c') { for(i=0;i<5;i++) { rel2 =~rel2; delay(5000); } } if(b[10]=='n') { for(i=0;i<5;i++) { rel3 =~rel3; delay(5000); } } } main() { Init_rs232(); printf("initial_OK\n"); read_word(); //一開始就把資料寫回微控制器 led_work(); number(); call_o(); while(1) { c1=rx_char(); switch(c1) { case 's': //電腦使用時 { s_send_computer(); break; } case 'm': //電腦使用時 { printf("\nb="); for(i=0;i<11;i++) { printf("%c",b[i]); } printf("\na="); for(i=0;i<11;i++) { printf("%c",a[i]); } break; } default : { if(chup==0) { printf("\nOK"); puts("at+chup"); } } } } }
02c1e4b65bb206f3de7545ea467f6731bf80a1f8
[ "Markdown", "C#", "C" ]
3
C#
Liyang-ing/ISB
c832240a26776abc82c1be2d50d9ad7a8daa98dd
5a54b15e6ae595f95c4827ead7bd125d145f07f1
refs/heads/master
<repo_name>YuliyaSim/stock-cli<file_sep>/stocks_cli/__main__.py import argparse from stocks_cli import Stock if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('symbol', metavar='symbol') parser.add_argument('--api-key', metavar='api_key') print(parser.parse_args()) args = parser.parse_args() print(Stock.get(args.symbol, args.api_key))<file_sep>/stocks_cli/stock.py from datetime import datetime, tzinfo import pytz import requests class Stock: def __init__(self, symbol: str, name: str, currency: str, price: float, stock_exchange_name: str, last_trade_time: datetime, timezone: tzinfo): self._symbol = symbol.upper() self._name = name self._currency = currency self._price = price self._stock_exchange_name = stock_exchange_name self._last_trade_name = last_trade_time self._timezone = timezone @property # so user not able to change value of symbol, name etc. / makin git imutable def symbol(self): return self._symbol @property def name(self): return self._name @property def currency(self): return self._currency @property def price(self): return self._price @property def stock_exchange_name(self): return self._stock_exchange_name @property def last_trade_time(self): return self._last_trade_time @property def timezone(self): return self._timezone @staticmethod def get(symbol: str, api_token: str): response = requests.get("https://api.worldtradingdata.com/api/v1/stock", { 'symbol': symbol, 'api_token': api_token }) response.raise_for_status() deserialized_response = response.json() #if we search for symbol that is not exist, it will raise an Error if 'Message' in deserialized_response: raise ValueError(deserialized_response['Message']) stock_data = response.json()['data'][0] return Stock( stock_data['symbol'], stock_data['name'], stock_data['currency'], float(stock_data['price']), stock_data['stock_exchange_long'], datetime.strptime(stock_data['last_trade_time'], '%Y-%m-%d %H:%M:%S'), pytz.timezone(stock_data['timezone_name']) ) <file_sep>/stocks_cli/__init__.py from stocks_cli.stock import Stock __author__ = "<NAME>"
a0bae4618ab4993d969a0026d457553bcbb38b32
[ "Python" ]
3
Python
YuliyaSim/stock-cli
57fa3d9dc431f3489f8289bd1e530765a63db374
b990781cb232155193bda83a3968a478e7c1eb9a
refs/heads/main
<repo_name>watr/feedback.apple.macOS-11.zerosize-tickmark-slider<file_sep>/zerosize-tickmark-slider/zerosize-tickmark-slider/AppDelegate.swift // // AppDelegate.swift // zerosize-tickmark-slider // // Created by <NAME> on 2021/04/14. // import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { } <file_sep>/zerosize-tickmark-slider/zerosize-tickmark-slider/ViewController.swift // // ViewController.swift // zerosize-tickmark-slider // // Created by <NAME> on 2021/04/14. // import Cocoa class CutsomSlider: NSSlider { var hidesTickMarks: Bool = false override func rectOfTickMark(at index: Int) -> NSRect { var r = super.rectOfTickMark(at: index) if self.hidesTickMarks { r.size = CGSize.zero return r } else { return r } } } class ViewController: NSViewController { @IBOutlet weak var slider: CutsomSlider! @IBOutlet weak var tickMarkSizeZeroButton: NSButton! override func viewDidLoad() { super.viewDidLoad() guard let slider = self.slider else { return } slider.numberOfTickMarks = Int(((slider.maxValue - slider.minValue) + 1)) self.applyTickMarkStatus() } func applyTickMarkStatus() { self.slider.hidesTickMarks = self.tickMarkSizeZeroButton.state != .off } @IBAction func showsTickMarkAction(_ sender: Any) { self.applyTickMarkStatus() if let slider = self.slider { slider.needsDisplay = true slider.needsLayout = true } } } <file_sep>/README.md # NSSlider's customized tick mark rect size is ignored in macOS 11 ## Steps to reproduce in macOS 11 Big Sur 1. Open 'feedback.apple.macOS-11.zerosize-tickmark-slider' project in Xcode 2. Build and run application ### Expected result If 'Tick Mark Size ZERO' check is ON, NO tick marks on slider. (If in macOS 10.15 or earlier, actual result == expected result) ![macOS 10.15 result](./screenshots/macOS_10.15.png) ### Actual result All tick marks always exist on slider, regardless of 'Tick Mark Size ZERO' check status. ![macOS 11 result](./screenshots/macOS_11.png) ## Note In sample project, NSSlider's method ```swift override func rectOfTickMark(at index: Int) -> NSRect ``` returns ```CGSize.zero``` sized ```NSRect``` . This means valid tick mark area has zero width and zero height, in that case I think tick mark should be invisible (as same as macOS 10.15 or earlier).
296ad759ae69fb39c4deb13a477f59c5fc5a9949
[ "Swift", "Markdown" ]
3
Swift
watr/feedback.apple.macOS-11.zerosize-tickmark-slider
862fc1d04e79db394154e1187bd6e055d8581002
8ce572fd7d1eb225a49f48b0224ca448b47c9798
refs/heads/master
<repo_name>jorgcalleja/NerdLibrary<file_sep>/webapp/controller/Detail.controller.js /*global location */ sap.ui.define([ "jorgcalleja/nerd/library/controller/BaseController", "sap/ui/model/json/JSONModel", "jorgcalleja/nerd/library/model/formatter" ], function (BaseController, JSONModel, formatter) { "use strict"; return BaseController.extend("jorgcalleja.nerd.library.controller.Detail", { formatter: formatter, /* =========================================================== */ /* lifecycle methods */ /* =========================================================== */ onInit : function () { // Model used to manipulate control states. The chosen values make sure, // detail page is busy indication immediately so there is no break in // between the busy indication for loading the view's meta data var oViewModel = new JSONModel({ busy : false, delay : 0 }); this.getRouter().getRoute("object").attachPatternMatched(this._onObjectMatched, this); this.setModel(oViewModel, "detailView"); this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bind(this)); }, /* =========================================================== */ /* event handlers */ /* =========================================================== */ /** * Event handler when the share by E-Mail button has been clicked * @public */ onShareEmailPress : function () { var oViewModel = this.getModel("detailView"); sap.m.URLHelper.triggerEmail( null, oViewModel.getProperty("/shareSendEmailSubject"), oViewModel.getProperty("/shareSendEmailMessage") ); }, /** * Event handler when the share in JAM button has been clicked * @public */ onShareInJamPress : function () { var oViewModel = this.getModel("detailView"), oShareDialog = sap.ui.getCore().createComponent({ name : "sap.collaboration.components.fiori.sharing.dialog", settings : { object :{ id : location.href, share : oViewModel.getProperty("/shareOnJamTitle") } } }); oShareDialog.open(); }, /* =========================================================== */ /* begin: internal methods */ /* =========================================================== */ /** * Binds the view to the object path and expands the aggregated line items. * @function * @param {sap.ui.base.Event} oEvent pattern match event in route 'object' * @private */ _onObjectMatched : function (oEvent) { var sObjectId = oEvent.getParameter("arguments").objectId; this.getModel().metadataLoaded().then( function() { var sObjectPath = this.getModel().createKey("Books", { Id : sObjectId }); this._bindView("/" + sObjectPath); }.bind(this)); }, /** * Binds the view to the object path. Makes sure that detail view displays * a busy indicator while data for the corresponding element binding is loaded. * @function * @param {string} sObjectPath path to the object to be bound to the view. * @private */ _bindView : function (sObjectPath) { // Set busy indicator during view binding var oViewModel = this.getModel("detailView"); // If the view was not bound yet its not busy, only if the binding requests data it is set to busy again oViewModel.setProperty("/busy", false); this.getView().bindElement({ path : sObjectPath, events: { change : this._onBindingChange.bind(this), dataRequested : function () { oViewModel.setProperty("/busy", true); }, dataReceived: function () { oViewModel.setProperty("/busy", false); } } }); }, _onBindingChange : function () { var oView = this.getView(), oElementBinding = oView.getElementBinding(); // No data for the binding if (!oElementBinding.getBoundContext()) { this.getRouter().getTargets().display("detailObjectNotFound"); // if object could not be found, the selection in the master list // does not make sense anymore. this.getOwnerComponent().oListSelector.clearMasterListSelection(); return; } var sPath = oElementBinding.getPath(), oResourceBundle = this.getResourceBundle(), oObject = oView.getModel().getObject(sPath), sObjectId = oObject.Id, sObjectName = oObject.Nombre, oViewModel = this.getModel("detailView"); this.getOwnerComponent().oListSelector.selectAListItem(sPath); oViewModel.setProperty("/saveAsTileTitle",oResourceBundle.getText("shareSaveTileAppTitle", [sObjectName])); oViewModel.setProperty("/shareOnJamTitle", sObjectName); oViewModel.setProperty("/shareSendEmailSubject", oResourceBundle.getText("shareSendEmailObjectSubject", [sObjectId])); oViewModel.setProperty("/shareSendEmailMessage", oResourceBundle.getText("shareSendEmailObjectMessage", [sObjectName, sObjectId, location.href])); this._setPDFUri(sPath); }, _onMetadataLoaded : function () { // Store original busy indicator delay for the detail view var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(), oViewModel = this.getModel("detailView"); // Make sure busy indicator is displayed immediately when // detail view is displayed for the first time oViewModel.setProperty("/delay", 0); // Binding the view will set it to not busy - so the view is always busy if it is not bound oViewModel.setProperty("/busy", true); // Restore original busy indicator delay for the detail view oViewModel.setProperty("/delay", iOriginalViewBusyDelay); }, //--- _setPDFUri: Generamos la URL para recuperar el pdf: <serviceurl>/<sEntityPath>/$value // We generate the URL to retrieve the PDF document _setPDFUri : function(sEntityPath) { var oViewModel = this.getModel("detailView"); oViewModel.setProperty("/busy", true); var sUrl = this.getOwnerComponent().getModel().sServiceUrl; sUrl = sUrl + sEntityPath + "/$value"; var embPDF = this.getView().byId("embPDF"); embPDF.setContent('<object data="' + sUrl + '" width="100%" height="800" type="application/pdf" >' + '<embed src="' + sUrl + '" width="100%" height="800" type="application/pdf" >' + '<p class="error">Tu navegador no permite visualizar el PDF, ¡actual&iacute;zate, alma de c&aacute;ntaro!</p>' + '</embed>' + '</object>'); oViewModel.setProperty("/busy", false); } }); } );
818fd29f58e00af2a1c52faffdde4ae57a3a816e
[ "JavaScript" ]
1
JavaScript
jorgcalleja/NerdLibrary
14eb442d0dc53df5547d58ad19998c425da33898
007c5d643659a13329049dccc52cffb1c5b6ac02
refs/heads/master
<repo_name>matamicen/EscuelaJavaFacturasJPA<file_sep>/demoFacturas/src/main/java/com/example/facturas/demoFacturas/model/Producto.java package com.example.facturas.demoFacturas.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; @Entity public class Producto { @Id @GeneratedValue private long idprod; private String nombre; private float precio; @OneToMany(mappedBy="producto") private List<Items> items; public Producto(long idprod, String nombre, float precio) { super(); this.idprod = idprod; this.nombre = nombre; this.precio = precio; } public Producto() { super(); } public long getIdprod() { return idprod; } public void setIdprod(long idprod) { this.idprod = idprod; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getPrecio() { return precio; } public void setPrecio(float precio) { this.precio = precio; } public List<Items> getItems() { return items; } public void setItems(List<Items> items) { this.items = items; } } <file_sep>/demoFacturas/src/main/java/com/example/facturas/demoFacturas/model/DaoFactura.java package com.example.facturas.demoFacturas.model; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface DaoFactura extends CrudRepository<Factura, Long> { } <file_sep>/demoFacturas/src/main/java/com/example/facturas/demoFacturas/model/Factura.java package com.example.facturas.demoFacturas.model; import java.sql.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Factura { @Id @GeneratedValue private Long idfac; private Date fecha; @ManyToOne @JoinColumn(name = "cliente_id") private Cliente cliente; @OneToMany(mappedBy="factura") private List<Items> items; @ManyToOne @JoinColumn(name= "usuario_id") private Usuario usuario; public Factura(Long idfac, Date fecha, Cliente cliente) { super(); this.idfac = idfac; this.fecha = fecha; this.cliente = cliente; } public Factura() { super(); } public Long getIdfac() { return idfac; } public void setIdfac(Long idfac) { this.idfac = idfac; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public List<Items> getItems() { return items; } public void setItems(List<Items> items) { this.items = items; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } } <file_sep>/demoFacturas/src/main/java/com/example/facturas/demoFacturas/model/Items.java package com.example.facturas.demoFacturas.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Items { @Id @GeneratedValue private long iditem; @ManyToOne @JoinColumn(name = "factura_id") private Factura factura; @ManyToOne @JoinColumn(name = "producto_id") private Producto producto; private int qty; public Items(Factura factura, Producto producto, int qty) { super(); this.factura = factura; this.producto = producto; this.qty = qty; } public Items() { super(); } public long getIditem() { return iditem; } public void setIditem(long iditem) { this.iditem = iditem; } public Factura getFactura() { return factura; } public void setFactura(Factura factura) { this.factura = factura; } public Producto getProducto() { return producto; } public void setProducto(Producto producto) { this.producto = producto; } public int getQty() { return qty; } public void setQty(int qty) { this.qty = qty; } }
967a80230fcb61630f5b82d147a736c210c8e2e1
[ "Java" ]
4
Java
matamicen/EscuelaJavaFacturasJPA
dc6b3fa193b530ce5068fc56629c56ca5fb36321
5146e9d32f12f444767194dec9672cf9921d50c3
refs/heads/master
<repo_name>mayusGomez/JavaExamples<file_sep>/02-CustomerControl/src/main/java/web/ServletControler.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 web; import data.*; import domain.Customer; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; /** * * @author agomez */ @WebServlet(name = "ServletControler", urlPatterns = {"/ServletControler"}) public class ServletControler extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action != null) { switch (action) { case "edit": this.customerEdit(request, response); break; default: this.defaultAction(request, response); } } else { this.defaultAction(request, response); } } private void customerEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ int idCustomer = Integer.parseInt(request.getParameter("idCustomer")); CustomerDao customerDao = new CustomerDaoJDBC(); Customer customer = customerDao.find(new Customer(idCustomer)); request.setAttribute("customer", customer); String jspEdit = "/WEB-INF/pages/customer/editCustomer.jsp"; request.getRequestDispatcher(jspEdit).forward(request, response); } private void defaultAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CustomerDao customerDao = new CustomerDaoJDBC(); List<Customer> customers = customerDao.select(); System.out.println("Customers:" + customers); /*request.setAttribute("customers", customers); request.setAttribute("totalCustomers", customers.size()); request.setAttribute("totalBalance", this.totalBalance(customers)); request.getRequestDispatcher("customers.jsp").forward(request, response); */ HttpSession session = request.getSession(); System.out.println("set att"); session.setAttribute("customers", customers); session.setAttribute("totalCustomers", customers.size()); session.setAttribute("totalBalance", this.totalBalance(customers)); System.out.println("redirect"); response.sendRedirect("customers.jsp"); } private double totalBalance(List<Customer> customers){ double totalBalance = 0; for (Customer customer: customers){ totalBalance += customer.getBalance(); } return totalBalance; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); System.out.println("doPost: action:" + action); if (action != null){ switch (action) { case "insert": this.customerInsert(request, response); break; case "modify": this.customerModify(request, response); break; case "delete": this.customerDelete(request, response); default: this.defaultAction(request, response); } }else{ this.defaultAction(request, response); } } private void customerModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ int idCustomer = Integer.parseInt(request.getParameter("idCustomer")); String name = request.getParameter("name"); String lastname = request.getParameter("lastname"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); String stringBalance = request.getParameter("balance"); double balance = 0; if (stringBalance != null && !"".equals(stringBalance)){ balance = Double.parseDouble(stringBalance); } Customer customer = new Customer(idCustomer, name, lastname, email, phone, balance); CustomerDao customerDao = new CustomerDaoJDBC(); //Insert in DB int modifiedRows = customerDao.update(customer); System.out.println("modifiedRows = " + modifiedRows); // Redirect this.defaultAction(request, response); } private void customerDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int idCustomer = Integer.parseInt(request.getParameter("idCustomer")); Customer customer = new Customer(idCustomer); CustomerDao customerDao = new CustomerDaoJDBC(); //Insert in DB int modifiedRows = customerDao.delete(customer); System.out.println("delete Rows = " + modifiedRows); List<Customer> customers = customerDao.select(); System.out.println("Customers:" + customers); request.setAttribute("customers", customers); request.setAttribute("totalCustomers", customers.size()); request.setAttribute("totalBalance", this.totalBalance(customers)); request.getRequestDispatcher("customers.jsp").forward(request, response); } private void customerInsert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //recuperamos los valores del formulario agregarCliente String name = request.getParameter("name"); String lastname = request.getParameter("lastname"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); double balance = 0; String balanceString = request.getParameter("balance"); if (balanceString != null && !"".equals(balanceString)) { balance = Double.parseDouble(balanceString); } Customer customer = new Customer(name, lastname, email, phone, balance); CustomerDao customerDao = new CustomerDaoJDBC(); //Insert in DB int modifiedRows = customerDao.insert(customer); System.out.println("modifiedRows = " + modifiedRows); // Redirect this.defaultAction(request, response); } } <file_sep>/01-PCWorld/src/com/gm/pcworld/Mouse.java package com.gm.pcworld; public class Mouse extends InputDevice{ private int mouseId; private static int mouseCount; public Mouse(String inputType, String brand) { super(inputType, brand); this.mouseId = Mouse.mouseCount++; } @Override public String toString() { return "Mouse{" + "mouseId=" + mouseId + '}'; } } <file_sep>/01-PCWorld/src/com/gm/pcworld/KeyBoard.java package com.gm.pcworld; public class KeyBoard extends InputDevice{ private int keyBoardId; private static int keyBoardCount; public KeyBoard(String inputType, String brand){ super(inputType, brand); this.keyBoardId = keyBoardCount++; } @Override public String toString() { return "KeyBoard{" + "keyBoardId=" + keyBoardId + '}'; } } <file_sep>/01-PCWorld/README.md # Exercise 1 - PC World This project show a basic example of Java, Heritage and Class management. Implements the next UML model (spanish): ![alt text](https://github.com/mayusGomez/JavaExamples/raw/master/01-PCWorld/model.PNG) <file_sep>/00-MoviesCatalog/src/co/com/gm/movies/main/Main.java package co.com.gm.movies.main; import co.com.gm.movies.business.MovieCatalog; import co.com.gm.movies.business.MovieCatalogImpl; import java.util.Scanner; public class Main { private static final String fileName = "c:\\pruebaJava\\movieCatalog.txt"; private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) { int option= 0; MovieCatalog movieCatalog = new MovieCatalogImpl(); printOptions(); option = scan.nextInt(); while (option != 0){ switch (option){ case 1: movieCatalog.fileInit(fileName); break; case 2: System.out.println("-------------"); System.out.println("Please input the movie name"); String movieName = scan.next(); System.out.println("The movie " + movieName.toString()+ " will be write to the catalog"); movieCatalog.addMovie(movieName, fileName); break; case 3: System.out.println("-------------"); movieCatalog.movieList(fileName); break; case 4: System.out.println("Input movie name:"); String search = scan.next(); movieCatalog.searchMovie(search, fileName); break; case 0: break; } System.out.println("-----------------"); printOptions(); option = scan.nextInt(); } } public static void printOptions(){ System.out.println("Please choice your option:"); System.out.println("1 - Init Catalog"); System.out.println("2 - Add movie"); System.out.println("3 - List movies"); System.out.println("4 - Search movie"); System.out.println("0 - exit"); } } <file_sep>/02-CustomerControl/README.md CREATE SCHEMA `customer_control` ; CREATE TABLE `customer_control`.`customer` ( `id_customer` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(45) NOT NULL, `lastname` VARCHAR(45) NOT NULL, `email` VARCHAR(100) NULL, `phone` VARCHAR(45) NOT NULL, `balance` DOUBLE NOT NULL DEFAULT 0, PRIMARY KEY (`id_customer`)); INSERT INTO `customer_control`.`customer` (`name`, `lastname`, `email`, `phone`) VALUES ('Jhon', 'Doe', '<EMAIL>', '345667890'); INSERT INTO `customer_control`.`customer` (`name`, `lastname`, `email`, `phone`) VALUES ('Jhoanna', 'Doe', '<EMAIL>', '9990987654'); <file_sep>/01-PCWorld/src/com/gm/pcworld/Order.java package com.gm.pcworld; public class Order { private int orderId; private Computer computers[]; private static int orderCount; private int computerCount; private final int MAX_COMPUTERS=5; public Order(){ this.orderId = ++Order.orderCount; this.computers = new Computer[MAX_COMPUTERS]; } public void addComputer(Computer computer){ if (this.computerCount < this.MAX_COMPUTERS){ this.computers[computerCount++] = computer; } else { System.out.println("Computers overload:" + MAX_COMPUTERS); } } public void showOrder(){ System.out.println("Order number:" + this.orderId); System.out.println("Total computers:" + this.computerCount); System.out.println("Computers list:"); System.out.println("["); for (int i=0; i < this.computerCount ; i++){ System.out.println(" " + computers[i]); System.out.print(" | "); } System.out.print("]"); } } <file_sep>/01-PCWorld/src/com/gm/pcworld/Monitor.java package com.gm.pcworld; public class Monitor { private int monitorId; private String brand; private double inchs; private static int monitorCount; private Monitor(){ this.monitorId = ++Monitor.monitorCount; } public Monitor(String brand, double inchs){ this(); this.brand = brand; this.inchs = inchs; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public double getInchs() { return inchs; } public void setInchs(double inchs) { this.inchs = inchs; } @Override public String toString() { return "Monitor{" + "monitorId=" + monitorId + ", brand='" + brand + '\'' + ", inchs=" + inchs + '}'; } } <file_sep>/README.md # Java Exercises This repository implements different exercises in the course www.globalmentoring.com.mx
70f1075b6ba6f7363142eb4a828d083b89e1f14a
[ "Markdown", "Java" ]
9
Java
mayusGomez/JavaExamples
f3a4276acd0a382168522ca953be4d97c1cb6b15
0b482df66fc5ecb44b1daaf115395ff7533f2b92
refs/heads/master
<repo_name>cthackers/Javascript<file_sep>/SessionVariables/sessionvariables.js var $_SESSION = function() { var reserved = ['clear'], session = { clear : function() { var name; for (name in $_SESSION) { !~reserved.indexOf(name) && delete($_SESSION[name]); } saveSession(); } }; function utf8Encode (argString) { var string = (argString); var utftext = "", n, start, end, stringl = 0; start = end = 0; stringl = string.length; for (n = 0; n < stringl; n++) { var c1 = string.charCodeAt(n); var enc = null; if (c1 < 128) { end++; } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128); } else { enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128); } if (enc !== null) { if (end > start) { utftext += string.slice(start, end); } utftext += enc; start = end = n + 1; } } if (end > start) { utftext += string.slice(start, stringl); } return utftext; } function utf8Decode(str_data) { var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0; str_data += ''; while (i < str_data.length) { c1 = str_data.charCodeAt(i); if (c1 < 128) { tmp_arr[ac++] = String.fromCharCode(c1); i++; } else if (c1 > 191 && c1 < 224) { c2 = str_data.charCodeAt(i + 1); tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = str_data.charCodeAt(i + 1); c3 = str_data.charCodeAt(i + 2); tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return tmp_arr.join(''); } function encode(data) { var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmpArr = []; if (!data) return data; data = utf8Encode(data + ''); do { o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; tmpArr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmpArr.join(''); switch (data.length % 3) { case 1: enc = enc.slice(0, -2) + '=='; break; case 2: enc = enc.slice(0, -1) + '='; break; default: break; } return enc; } function decode(data) { var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmpArr = []; if (!data) return data; data += ''; do { h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmpArr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmpArr[ac++] = String.fromCharCode(o1, o2); } else { tmpArr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmpArr.join(''); dec = utf8Decode(dec); return dec; } function saveSession() { var tmp = {"aDm":-1}; if (Object.toSource) { var name = ''; for (name in $_SESSION) { !~reserved.indexOf(name) && (tmp[name] = $_SESSION[name]); } top.name = encode(tmp.toSource()); } else { top.name = ''; } if (window.addEventListener) { window.removeEventListener('unload', saveSession, false); } else if (window.attachEvent) { window.detachEvent('onunload', saveSession); } tmp = undefined; } function parseObject() { var tmp = undefined, name; try { tmp = eval("(" + top.name ? decode(top.name) : "{}" + ")") || {}; } catch (ex) { return; } if (tmp['aDm'] != -1) return; for (name in tmp) { name != 'adm' && (session[name] = tmp[name]); } } function initialize() { parseObject(); if (window.addEventListener) { addEventListener("unload", saveSession, false); } else if (window.attachEvent) { window.attachEvent('onunload', saveSession); } } initialize(); return session; }(); /* sessionStorage.clear(); localStorage.clear(); */
0183e1955a9639ca09640f4cde57616272b4dc9c
[ "JavaScript" ]
1
JavaScript
cthackers/Javascript
69f6968ce8f75d5929b1ca98703eb7b6d6840038
6ff979a105f6e67d4a36c1126528f6550ea4bb27
refs/heads/master
<repo_name>poonam9995/ExcelFileUpload<file_sep>/development/excelFile/excelApi/index.js const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('./db.js'); const cors = require('cors'); const routes=require('./controller/emoployeeController.js'); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); app.use("/uploads",express.static('uploads')); app.use(cors({origin:'http://localhost:4200'})); app.use('/excelFile',routes); app.listen(process.env.port|| 4000 ,function(){ console.log('now listeing for request'); });<file_sep>/development/excelFile/excelWeb/src/app/upload-file/file-upload.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class FileUploadService { readonly baseURL = "http://localhost:4000/excelFile"; constructor(private http: HttpClient) { } passUploadFile(data){ return this.http.post(this.baseURL,data); } confirmUploadEmployee(data){ return this.http.post(this.baseURL+'/confirmEmployee',data); } confirmUploadManager(data){ return this.http.post(this.baseURL+'/confirmManager',data); } } <file_sep>/development/excelFile/excelWeb/src/app/upload-file/file-upload/file-upload.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; import { FileUploadService } from '../file-upload.service'; import { ToastrService } from 'ngx-toastr'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { TemplateRef } from '@angular/core'; import { template } from '@angular/core/src/render3'; @Component({ selector: 'app-file-upload', templateUrl: './file-upload.component.html', styleUrls: ['./file-upload.component.css'] }) export class FileUploadComponent implements OnInit { public formData = new FormData(); modalRef: BsModalRef; res2; res3; confirmArr =[]; constructor(private modalService: BsModalService,private fileupload :FileUploadService ,private toastrService :ToastrService) { } uploadfile; Upload : FormGroup; ngOnInit() { this.Upload = new FormGroup({ file : new FormControl(''), }); } onFileChange(event){ this.uploadfile = event.target.files[0]; console.log(this.uploadfile); this.formData.append("file",this.uploadfile); } onSubmit(){ console.log(this.uploadfile); this.fileupload.passUploadFile(this.formData).subscribe((res:any) =>{ if(res){ console.log(res.data1); console.log(res.data2); this.res2= res.data1; this.res3= res.data2; // this.toastr.success('Data Insert Successfully', 'Toastr fun!'); }else{ console.log("***********************"); // this.toastr.remove('Data Insert',' !'); } }); } openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show( template, Object.assign({}, { class: 'gray modal-lg' }) ); } close(): void { this.modalRef.hide(); } confirm(r2, r3){ console.log(r2, r3); // this.confirmArr.push(r2); // this.confirmArr.push(r3); this.fileupload.confirmUploadEmployee(r2).subscribe((res:any) =>{ if(res){ console.log(res); this.fileupload.confirmUploadManager(r3).subscribe((res:any)=>{ this.toastrService.success('Data Upload Successfully', 'Success', { timeOut: 3000 }); this.modalRef.hide(); }); }else{ console.log("***********************"); } }); } } <file_sep>/development/excelFile/excelApi/db.js const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/EmployeeExcel',{ useNewUrlParser: true },(err)=>{ if(!err){console.log('MongoDB Connection Succeded.');} else{ console.log('Error in DB Connection:'+JSON.stringify(err ,undefined ,2)); } }); module.exports= mongoose; require('./models/employee'); require('./models/manger');
6c4431e4e67d369c02ce0681fc921e8c514ba721
[ "JavaScript", "TypeScript" ]
4
JavaScript
poonam9995/ExcelFileUpload
2079c4f62123923ad0d39f97a781b3f787f6eed4
bdde4ae486e10b9d0948b4a5a45d9905249d14e2
refs/heads/main
<repo_name>rhkdck1/FlappyBird<file_sep>/Assets/OneCommand.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class OneCommand : MonoBehaviour { public AudioSource BirdSound_1; public AudioSource BirdSound_2; public AudioSource BirdSound_3; public AudioSource BirdSound_4; public GameObject m_objColumn; public GameObject m_objFloor; public GameObject m_objWhite; public GameObject m_objQuit; public GameObject[] gameObjects = new GameObject[3]; public Text Score; Rigidbody2D m_rig; float nextTime; int j = 0; int i = 0; int iBest = 0; bool isStop = false; void Start() { m_rig = GetComponent<Rigidbody2D>(); m_rig.AddForce(Vector3.up * 270); BirdSound_1.Play(); } // Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } GetComponent<Animator>().SetFloat("Velocity", m_rig.velocity.y); if (transform.position.y > 4.75f) { transform.position = new Vector3(-1.5f, 4.75f, 0); } else if(transform.position.y < - 2.55f) { m_rig.simulated = false; GameOver(); } //회전 if (m_rig.velocity.y > 0) { transform.rotation = Quaternion.Euler(0, 0, Mathf.Lerp(transform.rotation.z, 30f, m_rig.velocity.y / 8)); } else { transform.rotation = Quaternion.Euler(0, 0, Mathf.Lerp(transform.rotation.z, -90f, -m_rig.velocity.y / 8)); } if(isStop) { return; } //입력 if ((Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began) || Input.GetMouseButtonDown(0)) { m_rig.velocity = Vector3.zero; m_rig.AddForce(Vector3.up * 270); BirdSound_1.Play(); } //기둥 생성기 if(Time.time > nextTime) { nextTime = Time.time + 1.7f; gameObjects[j] = (GameObject)Instantiate(m_objColumn, new Vector3(4, Random.Range(-1f, 3.2f), 0), Quaternion.identity); if(++j == 3) { j = 0; } } if(gameObjects[0]) { gameObjects[0].transform.Translate(-0.03f, 0, 0); if(gameObjects[0].transform.position.x < -4) { Destroy(gameObjects[0]); } } if (gameObjects[1]) { gameObjects[1].transform.Translate(-0.03f, 0, 0); if (gameObjects[1].transform.position.x < -4) { Destroy(gameObjects[1]); } } if (gameObjects[2]) { gameObjects[2].transform.Translate(-0.03f, 0, 0); if (gameObjects[2].transform.position.x < -4) { Destroy(gameObjects[2]); } } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.name == "Column(Clone)") { Score.text = (++i).ToString(); BirdSound_2.Play(); } else if(!isStop) { m_rig.velocity = Vector3.zero; BirdSound_4.Play(); GameOver(); } } void GameOver() { //게임오버 if(!isStop) { BirdSound_3.Play(); } isStop = true; m_objFloor.GetComponent<Animator>().enabled = false; m_objWhite.SetActive(true); Score.gameObject.SetActive(false); if(PlayerPrefs.GetInt("BestScore", 0) < int.Parse(Score.text)) { PlayerPrefs.SetInt("BestScore", int.Parse(Score.text)); } if(transform.position.y < -2.55f) { m_objQuit.SetActive(true); m_objQuit.transform.Find("ScoreScreen").GetComponent<Text>().text = Score.text; m_objQuit.transform.Find("BestScreen").GetComponent<Text>().text = PlayerPrefs.GetInt("BestScore").ToString(); } } public void ReStart() { //재시작 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } }
bd9be558b38c6f75fd78bcbd26a2206f1d20ba12
[ "C#" ]
1
C#
rhkdck1/FlappyBird
4313e96bc4c61e7080bec523cbb0808113cf249c
ea5c97343b2282cfedbfe32b0d3af5ca8e9e566d
refs/heads/master
<repo_name>joellui/ETL<file_sep>/README.md # ETL Python code for ETL Project zip file :-- Data.zip output file :-- dataout <file_sep>/ETL.py import openpyxl import os import xlsxwriter import numpy as np from datetime import date from time import process_time from openpyxl.utils import get_column_letter from zipfile import ZipFile import os, shutil zf = ZipFile('/opt/Data.zip', 'r') zf.extractall('/opt/') zf.close() date = date.today() today = date.strftime("%Y%m%d") tod = date.strftime("%d/%m/%Y") loc = '/opt/Dataout/' workbook = xlsxwriter.Workbook(loc+'model_' + today + '.xlsx') worksheet = workbook.add_worksheet() worksheet.write('A1', 'Date') worksheet.write('B1', 'Ticker') worksheet.write('C1', 'Type') worksheet.write('D1', 'Quarter') worksheet.write('E1', 'Year') worksheet.write('F1', 'Estimated Total Sold') worksheet.write('G1', 'Estimated Total Sold Max') worksheet.write('H1', 'Estimated Total Sold Min') worksheet.write('I1', 'Forecast w/o SA Actual') worksheet.write('J1', 'Forecast w/o SA Max') worksheet.write('K1', 'Forecast w/o SA Min') t1 = process_time() paths=[] filename = '/opt/Data/' arr = os.listdir(filename) for items in arr: if "~$" not in items: paths.append(items) fel=2 for file in paths: ticker = file.split(' ')[0] filename = r'/opt/Project Data/' + file wb = openpyxl.load_workbook(filename, read_only=True, data_only=True) sheets = wb.sheetnames empsheets = [sheet for sheet in sheets if "Emp" in sheet] regrsheets = [sheet for sheet in sheets if "Regr" in sheet] print("Loading " + file) r = fel for shhet in empsheets: wb = openpyxl.load_workbook(filename, read_only=True, data_only=True) sheetemp = wb[shhet] maxrow = sheetemp.max_row for rowOfCellObjects in sheetemp['E90':'I' + str(maxrow)]: for cellObj in rowOfCellObjects: if "Min" in str(cellObj.value): worksheet.write('H'+str(r),sheetemp[(get_column_letter(cellObj.column+1)) + str(cellObj.row)].value) worksheet.write('G'+str(r),sheetemp[(get_column_letter(cellObj.column+1)) + str(cellObj.row-1)].value) worksheet.write('F'+str(r), sheetemp[(get_column_letter(cellObj.column+1)) + str(cellObj.row-2)].value) r = r + 1 r = fel for shet in regrsheets: sheetregr = wb[shet] typ = shet.split('-')[-1] maxro = sheetregr.max_row for rowOfCellObjects in sheetregr['Q15':'Q' + str(maxro)]: for cellObj in rowOfCellObjects: if "Min" in str(cellObj.value): worksheet.write('K'+str(r), sheetregr['R' + str(cellObj.row)].value) worksheet.write('J'+str(r), sheetregr['R' + str(cellObj.row-1)].value) worksheet.write('I'+str(r), sheetregr['R' + str(cellObj.row-2)].value) worksheet.write('D'+str(r), sheetregr['D' + str(cellObj.row - 2)].value) if "odel" not in typ: worksheet.write('C'+str(r), typ) else: worksheet.write('C'+str(r), "Null") worksheet.write('B'+str(r),ticker) worksheet.write('A'+str(r), tod) y = sheetregr['C' + str(cellObj.row - 2)].value year = '20' + y[2:4] worksheet.write("E" + str(r), int(year)) r = r + 1 fel = r os.remove(filename) workbook.close() t2 = process_time() print("ETL Done") print("Grand Total for all Files ",t2-t1) os.rmdir(r'/opt/Data') source=r'/opt/Data.zip' dest=r'/opt/Dataout' shutil.move(source, dest)
fa1faff5cc6dc36eeef530b9f5e9df1693b503dd
[ "Markdown", "Python" ]
2
Markdown
joellui/ETL
8770bacacd3c1b70cc562c3b52a9eb8185446261
0bfdba2c1f3c583143da88236c8bb4ef14cfb131
refs/heads/master
<repo_name>si87/micronaut-graal-demo<file_sep>/src/main/resources/META-INF/native-image/micronaut.graal.demo/micronaut-graal-demo-application/native-image.properties Args = -H:IncludeResources=logback.xml|application.yml|bootstrap.yml \ -H:Name=micronaut-graal-demo \ -H:Class=micronaut.graal.demo.Application<file_sep>/src/main/kotlin/micronaut/graal/demo/TestController.kt package micronaut.graal.demo import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get @Controller("test") class TestController(private val todoClient: TodoClient) { @Get suspend fun test(): ToDo { return todoClient.getTodo() } }<file_sep>/Dockerfile FROM oracle/graalvm-ce:19.3.1-java11 as graalvm RUN gu install native-image COPY . /home/app/micronaut-graal-demo WORKDIR /home/app/micronaut-graal-demo RUN native-image --no-server -cp build/libs/micronaut-graal-demo-*-all.jar FROM frolvlad/alpine-glibc RUN apk update && apk add libstdc++ EXPOSE 8080 COPY --from=graalvm /home/app/micronaut-graal-demo/micronaut-graal-demo /app/micronaut-graal-demo ENTRYPOINT ["/app/micronaut-graal-demo"] <file_sep>/issue/Reproducing.md # Reproducing error ``` $ java -version master!+ openjdk version "11.0.6" 2020-01-14 OpenJDK Runtime Environment GraalVM CE 19.3.1 (build 11.0.6+9-jvmci-19.3-b07) OpenJDK 64-Bit Server VM GraalVM CE 19.3.1 (build 11.0.6+9-jvmci-19.3-b07, mixed mode, sharing) ``` ## Creating demo project ``` mn create-app -l kotlin -f=graal-native-image micronaut-graal-demo ``` + implementing Controller + Declarative Client ## Build native image within container and run ``` ./gradlew assemble ./docker-build.sh docker run -p 8080:8080 micronaut-graal-demo curl http://localhost:8080/test ``` ## Resulting Stacktrace ``` 13:19:45.344 [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 25ms. Server Running: http://d24ae46f658f:8080 13:19:55.380 [pool-2-thread-3] ERROR i.m.r.intercept.RecoveryInterceptor - Type [micronaut.graal.demo.TodoClient$Intercepted] executed with error: Connect Error: jsonplaceholder.typicode.com: System error io.micronaut.http.client.exceptions.HttpClientException: Connect Error: jsonplaceholder.typicode.com: System error at io.micronaut.http.client.DefaultHttpClient.lambda$null$27(DefaultHttpClient.java:1042) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:577) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:551) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:490) at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:615) at io.netty.util.concurrent.DefaultPromise.setFailure0(DefaultPromise.java:608) at io.netty.util.concurrent.DefaultPromise.setFailure(DefaultPromise.java:109) at io.netty.channel.DefaultChannelPromise.setFailure(DefaultChannelPromise.java:89) at io.netty.bootstrap.Bootstrap.doResolveAndConnect0(Bootstrap.java:208) at io.netty.bootstrap.Bootstrap.access$000(Bootstrap.java:46) at io.netty.bootstrap.Bootstrap$1.operationComplete(Bootstrap.java:180) at io.netty.bootstrap.Bootstrap$1.operationComplete(Bootstrap.java:166) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:577) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:551) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:490) at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:615) at io.netty.util.concurrent.DefaultPromise.setSuccess0(DefaultPromise.java:604) at io.netty.util.concurrent.DefaultPromise.trySuccess(DefaultPromise.java:104) at io.netty.channel.DefaultChannelPromise.trySuccess(DefaultChannelPromise.java:84) at io.netty.channel.AbstractChannel$AbstractUnsafe.safeSetSuccess(AbstractChannel.java:984) at io.netty.channel.AbstractChannel$AbstractUnsafe.register0(AbstractChannel.java:504) at io.netty.channel.AbstractChannel$AbstractUnsafe.access$200(AbstractChannel.java:417) at io.netty.channel.AbstractChannel$AbstractUnsafe$1.run(AbstractChannel.java:474) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.micronaut.scheduling.instrument.InvocationInstrumenterWrappedRunnable.run(InvocationInstrumenterWrappedRunnable.java:48) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.lang.Thread.run(Thread.java:834) at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:497) at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193) Caused by: java.net.UnknownHostException: jsonplaceholder.typicode.com: System error at com.oracle.svm.jni.JNIJavaCallWrappers.jniInvoke_VA_LIST:Ljava_net_UnknownHostException_2_0002e_0003cinit_0003e_00028Ljava_lang_String_2_00029V(JNIJavaCallWrappers.java:0) at java.net.Inet4AddressImpl.lookupAllHostAddr(Inet4AddressImpl.java) at java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929) at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1515) at java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848) at java.net.InetAddress.getAllByName0(InetAddress.java:1505) at java.net.InetAddress.getAllByName(InetAddress.java:1364) at java.net.InetAddress.getAllByName(InetAddress.java:1298) at java.net.InetAddress.getByName(InetAddress.java:1248) at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:148) at io.netty.util.internal.SocketUtils$8.run(SocketUtils.java:145) at java.security.AccessController.doPrivileged(AccessController.java:117) at io.netty.util.internal.SocketUtils.addressByName(SocketUtils.java:145) at io.netty.resolver.DefaultNameResolver.doResolve(DefaultNameResolver.java:43) at io.netty.resolver.SimpleNameResolver.resolve(SimpleNameResolver.java:63) at io.netty.resolver.SimpleNameResolver.resolve(SimpleNameResolver.java:55) at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:57) at io.netty.resolver.InetSocketAddressResolver.doResolve(InetSocketAddressResolver.java:32) at io.netty.resolver.AbstractAddressResolver.resolve(AbstractAddressResolver.java:108) at io.netty.bootstrap.Bootstrap.doResolveAndConnect0(Bootstrap.java:200) ... 24 common frames omitted ``` <file_sep>/settings.gradle rootProject.name="micronaut-graal-demo"<file_sep>/src/main/kotlin/micronaut/graal/demo/TodoClient.kt package micronaut.graal.demo import io.micronaut.http.annotation.Get import io.micronaut.http.client.annotation.Client @Client("http://jsonplaceholder.typicode.com") interface TodoClient { @Get("/todos/1") suspend fun getTodo() : ToDo }
7382146059907cf343aaddcc59b479bef6504f0b
[ "Markdown", "Dockerfile", "INI", "Gradle", "Kotlin" ]
6
INI
si87/micronaut-graal-demo
811510afe2050cd026e33758793d56b35dbd6f8f
997a99e22576c143cbab41bdf76b793a493e55b3
refs/heads/master
<repo_name>blatendr/SlackBot<file_sep>/README.md # SlackBot, midterm assignment for STAT 287 A chat bot for the chat service Slack. Bot identifies certain message purposes while in testing mode through naive Bayes that was trained through input stored in a database. to get this work you would need my account info and api info which I have excluded, this mostly shows how to use websocket to connect and get info from a website. <file_sep>/jarvis.py - -# -*- coding: utf-8 -*- - -# jarvis.py, -# blatendr, <NAME> - -import websocket -import pickle -import json -import urllib -import requests -import sqlite3 -import sklearn # you can import other stuff too! -from sklearn.feature_extraction.text import CountVectorizer -from sklearn.naive_bayes import MultinomialNB -from sklearn.pipeline import Pipeline -from sklearn.externals import joblib -# FILL IN ANY OTHER SKLEARN IMPORTS ONLY - -import botsettings # local .py, do not share!! can get your own at slack.com -TOKEN = botsettings.API_TOKEN -DEBUG = True - -def debug_print(*args): - if DEBUG: - print(*args) - - -try: - conn = sqlite3.connect("jarvis.db") - c = conn.cursor() - #create the DB the first time running - #c.execute("CREATE TABLE training_data (id INTEGER PRIMARY KEY ASC, txt text, action text)") - -except: - debug_print("Can't connect to sqlite3 database...") - - -def post_message(message_text, channel_id): - requests.post("https://slack.com/api/chat.postMessage?token={}&channel={}&text={}&as_user=true".format(TOKEN,channel_id,message_text)) - - - -class Jarvis(): - #class variables - training_mode = False #enter training mode? - training_item = None - training_text = None - testing_mode = False #enter testing mode? - - - def __init__(self): # initialize Jarvis - - #set up NB classifier to be used later - self.BRAIN = Pipeline([('vectorizer', CountVectorizer()),('classifier', MultinomialNB()) ]) - - - - def on_message(self, ws, message): - m = json.loads(message) - - #Prints all info from a message, we will only need text and channel id - #debug_print(m, self.JARVIS_MODE, self.ACTION_NAME) - - # only react to Slack "messages" not from bots (me): - if m['type'] == 'message' and 'bot_id' not in m: - - #if user types done, exit respective mode - if (m['text'] == "DONE" and Jarvis.training_mode == True): - post_message("Exiting training mode...", m['channel']) - Jarvis.training_mode=False - Jarvis.training_item = None - if (m['text'] == "DONE" and Jarvis.testing_mode == True): - post_message("Exiting testing mode...", m['channel']) - Jarvis.testing_mode=False - - - #training mode - if (Jarvis.training_mode == True): - #if action name hasnt been set yet, set it - if (Jarvis.training_item == None): - Jarvis.training_item = m['text'] - post_message(("Ok, let us call this action ", m['text'], "what text do you want with it?"), m['channel']) - else: - #action name already set, just need text to go with it and insert into DB - post_message("Ok, I've got it, add another or type DONE", m['channel']) - Jarvis.training_text = m['text'] - c.execute("INSERT INTO training_data (txt,action) VALUES (?, ?)", (Jarvis.training_item, Jarvis.training_text,)) - conn.commit() - #training mode switch - if (m['text'] == "training mode"): - Jarvis.training_mode = True - post_message("You have entered training mode, what is the name of this ACTION?", m['channel']) - - - #testing mode - if (Jarvis.testing_mode ==True): - - #get text and put into list for predict method - example = [m['text']] - - - #get action data - actdat= [] - for row in c.execute("SELECT txt from training_data"): - actdat.append(str(row)) - - #get text data - txtdat = [] - for row in c.execute("SELECT action from training_data"): - txtdat.append(str(row)) - - #use set up NB model - self.BRAIN.fit(txtdat, actdat) - #pickle it - joblib.dump(self.BRAIN.fit(txtdat, actdat),"jarvis_brain.pk1") - - - #get prediction and clean it up a little - predict =str(self.BRAIN.predict(example)) - predict_clean = predict[4:-4] - - - post_message(("I think that is",predict_clean),m['channel']) - post_message("either keep testing or type DONE",m['channel']) - - #testing mode switch - if (m['text'] == 'testing mode'): - post_message("You have entered testing mode, let me guess what Action you mean", m['channel']) - Jarvis.testing_mode= True - - - - -def start_rtm(): - """Connect to Slack and initiate websocket handshake""" - r = requests.get("https://slack.com/api/rtm.start?token={}".format(TOKEN), verify=False) - r = r.json() - r = r["url"] - return r - -#error catching function -def on_error(ws, error): - print("SOME ERROR HAS HAPPENED", error) - -#websocket close function -def on_close(ws): - conn.close() - print("Web and Database connections closed") - -#websocket open function -def on_open(ws): - print("Connection Started - Ready to have fun on Slack!") - - -#keep websocket running until terminated by user -r = start_rtm() -jarvis = Jarvis() -ws = websocket.WebSocketApp(r, on_message=jarvis.on_message, on_error=on_error, on_close=on_close) -ws.run_forever()
c6816a1bb40d7280783a53ca1bd5db7adc7a5dcd
[ "Markdown", "Python" ]
2
Markdown
blatendr/SlackBot
458fdb0d3654e1173bc5ce8376a688e2a6a49b5c
73369b80e3158daf55a6b2fad1d7e7ec11f29fcb
refs/heads/master
<file_sep><?php return array( 'test'=>array('Home\\Behavior\\TestBehavior'), 'execute'=>array('Addons\Test\TestAddon') );<file_sep><?php namespace Admin\Controller; use Think\Controller; class UserController extends Controller { public function userList(){ $this->display('userList'); } public function test(){ $tokenObj= D('Token'); $accessToken=$tokenObj->getAccessToken(); if(empty($accessToken)){ echo $tokenObj->lassError; return false; } var_dump($accessToken); } }<file_sep># wecharFrame 小白学习微信公众号 这是一个小白的微信公众号管理软件。 <file_sep><?php namespace Home\Controller; use Think\Controller; use Think\Hook; class IndexController extends Controller { public function index(){ define("TOKEN", "<PASSWORD>"); $curlObj= D('SendData'); $wechatObj = D('Wechat'); $wechatObj->getNormalMsg(); if($wechatObj->msgType=='text' ){ switch($wechatObj->content=='1'){ case 1: $ExchangeRateObj= new \Home\Model\ExchangeRateModel($curlObj); $rate=$ExchangeRateObj->getRate(); $wechatObj->responseMsg($rate); break; default: $msg=" 输入1查询汇率\n 输入2查询电话\n "; $wechatObj->responseMsg($msg); } } } public function test(){ //Hook::listen('test'); Hook::add('execute','Addons\Test\TestAddon'); Hook::add('index','Addon\SystemInfo\Controller\InfoController'); Hook::listen('execute'); Hook::listen('index'); } }<file_sep><?php namespace Admin\Model; class FileConfigModel{ protected $path; protected $fileContents; public function __construct($name,$path=''){ $baseDir=dirname(__FILE__); $baseDir=str_replace('\\','/',$baseDir); $baseDir=substr($baseDir,-1)=='/'?$baseDir:$baseDir.'/'; if(empty($path)){ $this->path=$baseDir.'../../Common/Conf/'.$name; echo $this->path; return true; } $this->path=$path.$name; } public function readArrayConfigFile(){ echo $path; if(!file_exists($this->path) && !function_exists('file_get_contents')){ return false; } $fileContents=file_get_contents($this->path); if($fileContents===false){ return false; } $this->fileContents=$fileContents; return $fileContents; } }<file_sep><?php namespace Addons\Test; class TestAddon { public function execute(){ echo "this is pugin test"; } }
673f6d312713f2bb0b4928a2888eb15eff5c906e
[ "Markdown", "PHP" ]
6
PHP
l3n641/wecharFrame
f13ebcf4dbaa64351db18c3c1ffb0483229f565b
440f68dbbcd26ab3ce354922e81179c320571f88
refs/heads/master
<file_sep># osu-nowPlaying Open "Intergrate with MSN Live status display" first. <file_sep>#include<windows.h> #include<cstdio> #include<cstdlib> #include<tchar.h> using namespace std; LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam); int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow) { WNDCLASS wc; HWND hWnd; MSG msg; BOOL bQuit=FALSE; wc.style=CS_OWNDC; wc.lpfnWndProc=WndProc; wc.cbClsExtra=0; wc.cbWndExtra=0; wc.hInstance=hInstance; wc.hIcon=LoadIcon(NULL,IDI_APPLICATION); wc.hCursor=LoadCursor(NULL,IDC_ARROW); wc.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName=NULL; wc.lpszClassName="MsnMsgrUIManager"; RegisterClass(&wc); hWnd=CreateWindow("MsnMsgrUIManager",_T("MsnMsgrUIManager"),0,0,0,0,0,NULL,NULL,hInstance,NULL); while (!bQuit) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if(msg.message==WM_QUIT) { bQuit=TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else { } } DestroyWindow(hWnd); return msg.wParam; } LRESULT CALLBACK WndProc (HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) { //printf("%d\n",message); switch (message) { case WM_CREATE: return 0; case WM_CLOSE: PostQuitMessage (0); return 0; case WM_DESTROY: return 0; case WM_KEYDOWN: return 0; case WM_COPYDATA:{ COPYDATASTRUCT *pCopyData = (COPYDATASTRUCT*)lParam; char szBuffer[300],Authorname[300],Songname[300],Diffname[300]; char *pos=0; memset(szBuffer, 0, sizeof(szBuffer)); memset(Authorname, 0, sizeof(Authorname)); memset(Songname, 0, sizeof(Songname)); //wprintf(L"dwData:%d cbData:%d\r\nlpData:0x%08x = %ls\n", // pCopyData->dwData, pCopyData->cbData, // (PVOID)pCopyData->lpData, (wchar_t*)pCopyData->lpData); for(unsigned int i=0;i<(pCopyData->cbData)/2;i++)szBuffer[i]=((unsigned char*)pCopyData->lpData)[i*2]; if((pos=strstr(szBuffer,"Listening to {0} - {1} ({2})\\0"))){ snprintf(Songname,1+int(strstr(pos+30,"\\0")-(pos+30)),"%s",pos+30); pos=strstr(pos+30,"\\0"); snprintf(Authorname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); sprintf(Diffname,"Listening"); }else if((pos=strstr(szBuffer,"Playing {0} - {1} [{3}] ({2})\\0"))){ snprintf(Songname,1+int(strstr(pos+31,"\\0")-(pos+31)),"%s",pos+31); pos=strstr(pos+31,"\\0"); snprintf(Authorname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); pos=strstr(pos+2,"\\0"); pos=strstr(pos+2,"\\0"); snprintf(Diffname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); }else if((pos=strstr(szBuffer,"Watching {0} - {1} [{3}] ({2})\\0"))){ snprintf(Songname,1+int(strstr(pos+32,"\\0")-(pos+32)),"%s",pos+32); pos=strstr(pos+32,"\\0"); snprintf(Authorname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); pos=strstr(pos+2,"\\0"); pos=strstr(pos+2,"\\0"); snprintf(Diffname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); }else if((pos=strstr(szBuffer,"Editing {0} - {1} ({2})\\0"))){ snprintf(Songname,1+int(strstr(pos+25,"\\0")-(pos+25)),"%s",pos+25); pos=strstr(pos+25,"\\0"); snprintf(Authorname,1+int(strstr(pos+2,"\\0")-(pos+2)),"%s",pos+2); sprintf(Diffname,"Editing"); } printf("%s - %s [%s]\n",Authorname,Songname,Diffname); return 0; } default: return DefWindowProc(hWnd,message,wParam,lParam); } }
ae5e6d6516cb438e09b82927c75978b0d45b8e0d
[ "Markdown", "C++" ]
2
Markdown
XTXTMTXTX/osu-nowPlaying
e44cd5bb64074c8b36d5221c88a5430688d33d7f
f0f34de44740500d0a2c545bc85f5805a647688c
refs/heads/master
<repo_name>Bruce-Li-TuYuan/DataType_Redef<file_sep>/Type_Redef.h /************************************************* Copyright (C), 2003, HAC Tech. Co., Ltd. File name: // 文件名 Author: // 作者 Version: // 版本 Date: // 完成日期 Chip/Mcu/Cpu: // 所用芯片(MCU、射频芯片等主要芯片)的描述 Development environment: // 关于所使用开发环境(包括开发环境的版本)的描述 Description: // 用于详细说明此程序文件完成的主要功能,与其他模块 // 或函数的接口,输出值、取值范围、含义及参数间的控 // 制、顺序、独立或依赖等关系 Others: // 其它内容的说明 Function List: // 主要函数列表,每条记录应包括函数名及功能简要说明 History: // 修改历史记录列表,每条修改记录应包括修改日期、修改者及修改内容简述 1. Author: Version: Date: Modification: 2. ... *************************************************/ #ifndef __TYPE_REDEF_H__ #define __TYPE_REDEF_H__ #ifdef __cplusplus extern "C" { #endif /********************************************************************************************************* 类型重定义 *********************************************************************************************************/ typedef unsigned char u8; typedef signed char s8; typedef signed short s16; typedef unsigned short u16; typedef signed int s32; typedef unsigned int u32; typedef signed long long s64; typedef unsigned long long u64; typedef float f32; typedef double d64; #ifdef __cplusplus } #endif /* __cplusplus */ #endif <file_sep>/README.md # DataType_Redef 这里只包含一个文件, Type_Redef.h 它的主要作用就是重定义并简化一些常用的数据类型,方便在编程时候使用。
faac924b2ef8ad0fa4c386c4c2b4c98f3836ad2a
[ "Markdown", "C" ]
2
C
Bruce-Li-TuYuan/DataType_Redef
8d9727a15bf2d4bc147da6436b157353edd13528
ef617fc32ad38d8482d57c5e1def55a624cea928
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Article } from './article'; import { Observable } from 'rxjs'; const NEWS_API_URL = `https://api.myjson.com/bins/10ijyt`; @Injectable({ providedIn: 'root' }) export class ArticleService { constructor( private http: HttpClient ) { } favoritedArticles: Article[] = []; getArticles(): Observable<Article[]>{ return this.http.get<Article[]>(NEWS_API_URL) } addToFavorites(article: Article){ article.isFavorite = true; this.favoritedArticles.push(article); } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { Article } from './article'; @Pipe({ name: 'publisher' }) export class PublisherPipe implements PipeTransform { transform(allArticles: Article[], publisher?: string): Article[] { if (publisher){ return allArticles.filter((article: Article) => article.PUBLISHER === publisher); } return allArticles; } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { Article } from './article'; @Pipe({ name: 'category' }) export class CategoryPipe implements PipeTransform { transform(allArticles: Article[], category ?: string): Article[] { if (category) { return allArticles.filter((article: Article) => article.CATEGORY === category) } return allArticles; } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Article } from '../article'; import { ArticleService } from '../article.service'; const NEWS_CATEGORIES = [ { viewValue: 'Business', value: 'b' }, { viewValue: 'Science and Technology', value: 't' }, { viewValue: 'Entertainment', value: 'e' }, { viewValue: 'Health', value: 'm' } ]; @Component({ selector: 'app-articles-list', templateUrl: './articles-list.component.html', styleUrls: ['./articles-list.component.css'] }) export class ArticlesListComponent implements OnInit { articles: Article[] = []; categories: any[] = NEWS_CATEGORIES; allPublishers: string[] = []; isSortedNewToOld: Boolean; constructor( private articleService: ArticleService ) { } ngOnInit() { this.getArticles(); } getArticles(): void { this.articleService.getArticles().subscribe((articles: Article[]) => { this.articles = articles; this.articles.map((article: Article) => { if (this.allPublishers.indexOf(article.PUBLISHER) === -1) { this.allPublishers.push(article.PUBLISHER); } }); }) } sortArticles() { if (this.isSortedNewToOld){ this.articles.sort((a, b) => a.TIMESTAMP - b.TIMESTAMP) this.isSortedNewToOld = false; } else { this.articles.sort((a, b) => b.TIMESTAMP - a.TIMESTAMP) this.isSortedNewToOld = true; } } } <file_sep>import { PublisherPipe } from './publisher.pipe'; describe('PublisherPipe', () => { it('create an instance', () => { const pipe = new PublisherPipe(); expect(pipe).toBeTruthy(); }); }); <file_sep>export class Article { ID: number; TITLE: string; URL: string; PUBLISHER : string; CATEGORY : string; HOSTNAME : string; TIMESTAMP : number; isFavorite: Boolean; }
1cac4aac99f30ac412a1cdcf4b315aeb2874e5c6
[ "TypeScript" ]
6
TypeScript
sachinmk27/mutual-mobile-news-app
3ec34093c2b76ebdd69b037a261618964131ea90
313bd3e6f7f96036911263b15fd9212a06097314
refs/heads/master
<file_sep><?php session_start(); header("Content-type: text/html; charset: utf-8"); include 'php/receipt.php'; if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta http-equiv="pragma" content="no-cache"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"> <link rel="stylesheet" href="css/receipt.css?version=12"> <script src="scripts/jquery.js"></script> </head> <body> <div class="local-container page-fade"> <div class="flex-center flex-column tabless-content scrollable"> <div id="header" class="flex-center flex-column"> <h1 id="title">Comprovante</h1> </div> <div class="flex-center flex-column" style="width: 100%; margin-bottom: 20px;"> <?php while($row = mysqli_fetch_assoc($result)){ ?> <div class="spaced"> <h2 class="label">Nome do Funcionário</h2> <h3 class="data" id="name"><?php echo utf8_encode($_SESSION['name']." ".$_SESSION['lastName']); ?></h3> </div> <div class="spaced box"> <h2 class="label">Código do Funcionário</h2> <h3 class="data"><?php echo $_SESSION['codUser']; ?></h3> </div> <div class="spaced box"> <h2 class="label">CNPJ</h2> <h3 class="data"><?php echo $row['CNPJ']; ?></h3> </div> <div class="spaced box"> <h2 class="label">Data</h2> <h3 class="data"><?php echo date("d/m/Y", strtotime($_GET['date'])); ?></h3> </div> <div class="spaced box"> <h2 class="label">Horário</h2> <h3 class="data"><?php echo $_GET['hour']; ?></h3> </div> <div class="spaced box"> <h2 class="label">Local</h2> <h3 class="data"><?php echo utf8_encode($row['Locale']);} ?></h3> </div> <div class="spaced box"> <h2 class="label">PIS</h2> <h3 class="data"><?php echo $_SESSION['PIS']; ?></h3> </div> </div> </div> </div> <script src="php/receipt.php"></script> <script> $(document).ready(() => { $('a:last').addClass('hidden'); }); </script> </body> </html><file_sep><?php session_start(); include 'php/registers.php'; if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"> <link rel="stylesheet" href="css/registers.css?version=12"> <script src="scripts/jquery.js"></script> </head> <body> <div id="loading" class="loading-background flex-row flex-center hidden"> <div id="spinner" class="loading-spinner"></div> </div> <div id="registers-video" class="video-tip flex-row flex-center hidden"> <img id="close-registers" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Toque.gif"/> </div> <div class="flex-row popup hidden fade-popup"> <div class="flex-column popup-content"> <h2 class="popup-title">Aviso</h2> <h3 class="popup-text">Não existe um comprovante para o horário selecionado.</h3> <button class="popup-button">Entendi</button> </div> </div> <div class="local-container page-fade"> <div class="flex-row help"> <img src="images/libras.png" id="libras-registers"/> <img src="images/help.svg" id="text-registers" /> <span id="registersTooltip-text" class="tooltip-text"> Toque sobre um horário para visualizar o comprovante correspondente. </span> </div> <div class="align-center flex-column tabless-content scrollable"> <div id="header" class="flex-center flex-column"> <h1 id="title">Registros</h1> </div> <div class="flex-center flex-column"> <h2 id="date"> <?php if (isset($_GET['date'])) { echo date("d/m/Y", strtotime($_GET['date'])); } ?> </h2> <div id="msg" class="flex-center flex-column"> <h5 id="message"> <?php if ($rowsNumber == 0) { echo "Nenhum registro disponível para esta data."; } ?> </h5> </div> <?php while($row = mysqli_fetch_assoc($result)) { $_SESSION['pointCode'] = $row['idtb_point']; ?> <h3 class="subtitle">Período Matutino</h3> <div class="table" style="display:flex"> <div id="left" class="column flex-column"> <h3 class="header-title">Entrada</h3> <h4 style="color: #404040" <?php if($row['EntryHourManual'] == 1){echo "class='manual'";} ?>> <?php echo $row['EntryHour']; ?> </h4> </div> <div id="right" class="column flex-column"> <h3 class="header-title">Saída</h3> <h4 style="color: #404040" <?php if($row['LunchBreakManual'] == 1){echo "class='manual'";} ?>> <?php echo $row['LunchBreak']; ?> </h4> </div> </div> <h3 class="subtitle">Período Vespertino</h3> <div class="table" style="display:flex"> <div id="left" class="column flex-column"> <h3 class="header-title">Entrada</h3> <h4 style="color: #404040" <?php if($row['LunchReturnManual'] == 1){echo "class='manual'";} ?>> <?php echo $row['LunchReturn']; ?> </h4> </div> <div id="right" class="column flex-column"> <h3 class="header-title">Saída</h3> <h4 style="color: #404040" <?php if($row['DepartureTimeManual'] == 1){echo "class='manual'";} ?>> <?php echo $row['DepartureTime']; } ?> </h4> </div> </div> <?php if($rowsNumber > 0) { echo ' <div id="tip-box" class="tip-box flex-column align-center"> <h2>Aviso</h2> <span class="tip">Horários na cor laranja representam registros inseridos manualmente por algum administrador.</span> </div> '; } ?> </div> </div> </div> <script> let tooltip = document.querySelector("#text-registers"); let tooltipText = document.querySelector("#registersTooltip-text"); tooltip.onclick = () => { tooltipText.classList.add("fade"); setTimeout(() => { tooltipText.classList.remove("fade"); }, 4000); }; $(document).ready(function(){ $('a:last').addClass('hidden'); var popup = document.querySelector(".popup"); let hour = document.getElementsByTagName("h4"); let hourArray = [...hour]; hourArray.forEach((element) => { element.addEventListener('click', () => { if(element.innerText == "") { popup.classList.remove("hidden"); popup.classList.add("fade-popup"); } else { document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `receipt.php?hour=${element.innerText}&date=<?php echo $_GET['date']; ?>`; } }); }); document.querySelector(".popup-button").addEventListener('click', () => { popup.classList.add("hidden"); popup.classList.remove("fade-popup"); }) }); tipBox = document.querySelector("#tip-box"); setTimeout(() => { tipBox.classList.add("fadeout"); tipBox.addEventListener("animationend", (e) => { e.target.classList.add("hidden"); }) }, 5000) let libRegisters = document.querySelector("#libras-registers"); let closeRegisters = document.querySelector("#close-registers"); let videoRegisters = document.querySelector("#registers-video"); libRegisters.onclick = () => { videoRegisters.classList.remove("hidden"); } closeRegisters.onclick = () => { videoRegisters.classList.add("hidden"); } </script> </body> </html><file_sep><?php $host = '172.16.31.10'; $user = 'mecsystem'; $password = '123'; $bd = 'BD_MecSystem'; $connection = mysqli_connect($host, $user, $password, $bd); ?> <file_sep># MecSystem Mobile ## Visão Geral Esta é uma aplicação para visualizar registros de ponto eliminando o uso de papel. ## Tecnologias utilizadas - HTML / CSS / JavaScript. - PHP. - MySQL. ## Aviso O serviço em nuvem que foi usado para implantar o banco de dados foi cancelado por ser um recurso pago e infelizmente torna o uso desta aplicação não possível no momento de maneira adequada. <p>Estou também no <a href="https://www.linkedin.com/in/ruan-scherer/">Linkedin</a>, conecte-se comigo! :rocket:</p> <file_sep><?php session_start(); include 'php/categories.php'; if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css"/> <link rel="stylesheet" href="css/home_adm.css"/> <script src=scripts/jquery.js></script> <!-- Full Callendar --> <link href='css/main.min.css' rel='stylesheet' > <link href='css/mainb.min.css' rel='stylesheet'/> <link href='css/mainc.min.css' rel='stylesheet'/> <script src='scripts/main.min.js'></script> <script src='scripts/locales-all.js'></script> <script src='scripts/mainb.min.js'></script> <script src='scripts/mainc.min.js'></script> <script src='scripts/maind.min.js'></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var locale = 'pt-br'; var calendar = new FullCalendar.Calendar(calendarEl, { plugins: [ 'interaction', 'dayGrid', 'timeGrid' ], locale: locale, height: 'auto', selectable: true, header: { left: 'title', center: '', right: 'prev,next today' }, dateClick: function(info) { let date = info.dateStr; document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `registers.php?date=${date}`; } }); calendar.render(); $('.fc-icon').css("color", "#fff"); }); </script> </head> <body> <div id="loading" class="loading-background flex-row flex-center hidden"> <div id="spinner" class="loading-spinner"></div> </div> <div id="registers-video" class="video-tip flex-row flex-center hidden"> <img id="close-registers" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Navegue.gif"/> </div> <div id="search-video" class="video-tip flex-row flex-center hidden"> <img id="close-search" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Utilize.gif"/> </div> <div class="local-container page-fade"> <div class="flex-center flex-column content"> <div id="home" class="flex flex-column align-center scrollable"> <h1 id="name">Olá, <?php echo utf8_encode($_SESSION['name']); ?></h1> <h2 class="message">Aqui estão algumas informações sobre você na MecSystem</h2> <ul class="data-list"> <li class="data flex-column flex-center"> <span>Código de Funcionário</span> <span class="data-content"> <?php echo $_SESSION['codUser']; ?> </span> </li> <li class="data flex-column flex-center"> <span>CBO</span> <span class="data-content"> <?php echo $_SESSION['cbo']; ?> </span> </li> <li class="data flex-column flex-center"> <span>Cargo</span> <span class="data-content"> <?php echo utf8_encode($_SESSION['FunctionName']); ?> </span> </li> <li class="data flex-column flex-center"> <span>Código do Cartão Ponto</span> <span class="data-content"> <?php echo $_SESSION['cardNumber']; ?> </span> </li> </ul> </div> <div id="registers" class="hidden flex flex-column align-center scrollable"> <div class="flex-row help"> <img src="images/libras.png" id="libras-registers"/> <img src="images/help.svg" id="text-registers" /> <span id="registersTooltip-text" class="tooltip-text"> Navegue utilizando o calendário e selecione uma data para ver os registros de ponto correspondentes. </span> </div> <div id="calendar"></div> </div> <div id="search-content" class="hidden flex-column align-center scrollable"> <div class="flex-row help"> <img src="images/libras.png" id="libras-search"/> <img src="images/help.svg" id="text-search" /> <span id="searchTooltip-text" class="tooltip-text"> Utilize a barra de pesquisa para buscar por funcionários com um nome específico ou toque sobre algum cargo para visualizar os colaboradores que exercem dele. </span> </div> <div id="search" class="flex-row"> <input type="text" placeholder="Busque aqui..." class="search-input" id="searchInput"> <button id="searchButton" class="search-button">Buscar</button> </div> <h2 class="subtitle">Cargos na sua empresa</h2> <div id="categories-container" class="flex-row flex-wrap"> <?php while($row = mysqli_fetch_assoc($result)){ echo utf8_encode("<div class='categorie'><h3 class='categorie-name'>{$row['FunctionName']}</h3></div>"); } ?> </div> </div> </div> <footer class="nav flex-column flex-center"> <h4><?php echo utf8_encode($_SESSION['company']); ?></h4> <div class="flex-row"> <div id="homeTab" class="tab flex-column flex-center selected-tab"> <span>Home</span> </div> <div id="registersTab" class="tab flex-column flex-center"> <span>Registros</span> </div> <div id="searchTab" class="tab flex-column flex-center"> <span>Buscar</span> </div> </div> </footer> </div> <script> $(document).ready(() => { $('a:last').addClass('hidden'); let categories = [...document.getElementsByClassName('categorie')]; categories.forEach((e) => { e.addEventListener('click', () => { document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `categorie_results.php?categorie=${e.children[0].innerHTML}`; }); }); let searchButton = document.getElementById("searchButton"); let nameInput = document.getElementById("searchInput"); nameInput.value = ""; searchButton.addEventListener('click', () => { document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `search_results.php?name=${nameInput.value}`; }); let homeTab = document.querySelector("#homeTab"); let registersTab = document.querySelector("#registersTab"); let configTab = document.querySelector("#searchTab"); let homeContent = document.querySelector("#home"); let registersContent = document.querySelector("#registers"); let settingsContent = document.querySelector("#search-content"); homeTab.addEventListener('click', () => { homeContent.classList.remove("hidden"); registersContent.classList.add("hidden"); settingsContent.classList.add("hidden"); homeTab.classList.add("selected-tab"); registersTab.classList.remove("selected-tab"); configTab.classList.remove("selected-tab"); }); registersTab.addEventListener('click', () => { homeContent.classList.add("hidden"); registersContent.classList.remove("hidden"); settingsContent.classList.add("hidden"); homeTab.classList.remove("selected-tab"); registersTab.classList.add("selected-tab"); configTab.classList.remove("selected-tab"); }); configTab.addEventListener('click', () => { homeContent.classList.add("hidden"); registersContent.classList.add("hidden"); settingsContent.classList.remove("hidden"); homeTab.classList.remove("selected-tab"); registersTab.classList.remove("selected-tab"); configTab.classList.add("selected-tab"); }); //tooltips let registersTooltip = document.querySelector("#text-registers"); let registersTooltipText = document.querySelector("#registersTooltip-text"); registersTooltip.onclick = () => { registersTooltipText.classList.add("fade"); setTimeout(() => { registersTooltipText.classList.remove("fade"); }, 5000); }; let searchTooltip = document.querySelector("#text-search"); let searchTooltipText = document.querySelector("#searchTooltip-text"); searchTooltip.onclick = () => { searchTooltipText.classList.add("fade"); setTimeout(() => { searchTooltipText.classList.remove("fade"); }, 5000); }; }); // REGISTERS TIP VIDEO let libRegisters = document.querySelector("#libras-registers"); let closeRegisters = document.querySelector("#close-registers"); let videoRegisters = document.querySelector("#registers-video"); libRegisters.onclick = () => { videoRegisters.classList.remove("hidden"); } closeRegisters.onclick = () => { videoRegisters.classList.add("hidden"); } // SEARCH TIP VIDEO let libSearch = document.querySelector("#libras-search"); let closeSearch = document.querySelector("#close-search"); let videoSearch = document.querySelector("#search-video"); libSearch.onclick = () => { videoSearch.classList.remove("hidden"); } closeSearch.onclick = () => { videoSearch.classList.add("hidden"); } </script> </body> </html><file_sep><?php include 'connection.php'; $sql = "select idtb_point, EntryHour, LunchBreak, LunchReturn, DepartureTime, EntryHourManual, LunchBreakManual, LunchReturnManual, DepartureTimeManual, UserName from tb_point inner join tb_user on fk_employee = idtb_user where date = '{$_GET['date']}' and UserCpf = '{$_GET['cpf']}'"; $result = mysqli_query($connection, $sql); $rowsNumber = mysqli_num_rows($result); ?><file_sep><?php session_start(); include 'connection.php'; if(empty($_GET["login"] || empty($_GET["password"]))) { //verifica se os posts estão vazios, para evitar acesso direto a esta página header("Location: ../index.php"); exit(); } $login = mysqli_real_escape_string($connection, $_GET["login"]); $password = mysqli_real_escape_string($connection, $_GET["password"]); $sql = "select * from tb_user where UserCpf='$login' and UserPassword='$<PASSWORD>'"; $result = mysqli_query($connection, $sql); $sqlCompany = "select CompanyName from tb_company where idtb_company = 1"; $resultCompany = mysqli_query($connection, $sqlCompany); $rows = mysqli_num_rows($result); $functionQuery = ""; $functionResult = ""; if ($rows == 1) { // salva os dados do usuário na sessão while($row = mysqli_fetch_assoc($result)) { $functionQuery = "select FunctionName, CBO from tb_function where idtb_function = '".$row['fk_function']."'"; $functionResult = mysqli_query($connection, $functionQuery); while($function_row = mysqli_fetch_assoc($functionResult)) { $_SESSION['FunctionName'] = $function_row['FunctionName']; $_SESSION['cbo'] = $function_row['CBO']; } $_SESSION['codUser'] = $row['idtb_user']; $_SESSION['name'] = $row['UserName']; $_SESSION['lastName'] = $row['UserLastName']; $_SESSION['cardNumber'] = $row['CardNumber']; $_SESSION['PIS'] = $row['PIS']; while($company = mysqli_fetch_assoc($resultCompany)){ $_SESSION['company'] = $company['CompanyName']; } // redireciona para a página do tipo do usuário if ($row['Admin'] == 0) { header("Location: ../home_func.php"); } else { header("Location: ../home_admin.php"); } } exit(); } else { header("Location: ../index.php?erro=incorrect"); exit(); } ?><file_sep><?php session_start(); $_SESSION['email'] = $_GET['email']; include 'php/connection.php'; $verify = mysqli_query($connection, "select CompanyRecieved from tb_monthControl where month(DateControl) = '".$_GET['month']."' and year(DateControl) = '".$_GET['year']."';"); while($verifyRow = mysqli_fetch_assoc($verify)) { if($verifyRow['CompanyRecieved'] == 1) { header('Location: month_expired.html'); } } $sqlCompany = "select CompanyName from tb_company where idtb_company = 1"; $resCompany = mysqli_query($connection, $sqlCompany); $sql = "select EntryHour, LunchBreak, LunchReturn, DepartureTime, Date, EntryHourManual, LunchBreakManual, LunchReturnManual, DepartureTimeManual from tb_point inner join tb_user on fk_employee = idtb_user where UserEmail = '".$_GET['email']."' and month(Date) = '".$_GET['month']."' and year(Date) = '".$_GET['year']."';"; $res = mysqli_query($connection, $sql); $sqlUserData = "select UserName, UserCpf from tb_user where UserEmail = '".$_GET['email']."';"; $resUserData = mysqli_query($connection, $sqlUserData); ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"/> <link rel="stylesheet" href="css/index.css?version=12"/> <link rel="stylesheet" href="css/month_close.css?version=12"/> <LINK REL="SHORTCUT ICON" href="images/Logo-MecSystem.png"> <script src="scripts/jquery.js"></script> <title>Verificação</title> </head> <body> <div id="accept-popup" class="flex-row popup hidden"> <div class="flex-column popup-content"> <img id="close-accept" src="images/close-dark.svg" /> <h2 class="popup-title">Aviso</h2> <h3 class="popup-text">Por questões de segurança, precisamos que confirme com sua senha.</h3> <form action="php/month_accept.php" method="POST" class="flex-column flex-center"> <input type="password" placeholder="<PASSWORD>" name="password" /> <button class="popup-button" style="background-color: white" type="submit">Confirmar</button> </form> </div> </div> <div id="decline-popup" class="flex-row popup hidden"> <div class="flex-column popup-content"> <img id="close-decline" src="images/close-dark.svg" /> <h2 class="popup-title">Aviso</h2> <h3 class="popup-text">Por questões de segurança, precisamos que confirme com sua senha.</h3> <form action="php/month_decline.php" method="POST" class="flex-column flex-center"> <input type="password" placeholder="<PASSWORD>" name="password" /> <button class="popup-button" style="background-color: white" type="submit">Confirmar</button> </form> </div> </div> <div id="page" class="hidden flex-column align-center" style="padding: 0; display: flex; justify-content: center;"> <div id="header" class="flex-row flex-center"> <span id="primary"> <?php while($row = mysqli_fetch_assoc($resCompany)) { echo $row['CompanyName']; } ?> </span> </div> <div class="flex-column flex-center" style="padding: 15px"> <h2>Dados Pessoais</h2> <div class="info"> <?php while($row = mysqli_fetch_assoc($resUserData)) { ?> <h2 class="label">Nome do Funcionário</h2> <h3 class="data"><?php echo utf8_encode($row['UserName']); ?></h3> <h2 class="label">CPF</h2> <h3 class="data"><?php echo utf8_encode($row['UserCpf']); }?></h3> </div> <h2>Relatório completo de registro de ponto do mês </h2> <div class="table-controller"> <table> <tr> <th>Data</th> <th>Entrada (Matutino)</th> <th>Saída (Matutino)</th> <th>Entrada (Vespertino)</th> <th>Saída (Vespertino)</th> </tr> <tbody> <?php while($row = mysqli_fetch_assoc($res)) { echo " <tr> <td>".date("d/m/y", strtotime($row['Date']))."</td> <td"; if($row['EntryHourManual'] == 1){echo " class='manual'";} echo ">".$row['EntryHour']."</td> <td"; if($row['LunchBreakManual'] == 1){echo " class='manual'";} echo ">".$row['LunchBreak']."</td> <td"; if($row['LunchReturnManual'] == 1){echo " class='manual'";} echo ">".$row['LunchReturn']."</td> <td"; if($row['DepartureTimeManual'] == 1){echo " class='manual'";} echo ">".$row['DepartureTime']."</td> </tr> "; } ?> </tbody> </table> </div> <span id="tip">Registros inseridos manualmente por administradores estão representados pela cor laranja.</span> <div class="decision flex-row flex-center"> <button id="decline">Discordo</button> <button id="accept">Concordo</button> </div> </div> </div> <script> let accept = document.querySelector("#accept"); let decline = document.querySelector("#decline"); let acceptClose = document.querySelector("#close-accept"); let declineClose = document.querySelector("#close-decline"); accept.onclick = () => { document.querySelector("#accept-popup").classList.remove("hidden"); } acceptClose.onclick= () => { document.querySelector("#accept-popup").classList.add("hidden"); } decline.onclick = () => { document.querySelector("#decline-popup").classList.remove("hidden"); } declineClose.onclick= () => { document.querySelector("#decline-popup").classList.add("hidden"); } </script> </body> </html><file_sep><?php session_start(); if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta http-equiv="pragma" content="no-cache"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"> <link rel="stylesheet" href="css/home.css?version=12"> <script src="scripts/jquery.js"></script> <!-- Full Callendar --> <link href='css/main.min.css' rel='stylesheet' > <link href='css/mainb.min.css' rel='stylesheet'/> <link href='css/mainc.min.css' rel='stylesheet'/> <script src='scripts/main.min.js'></script> <script src='scripts/locales-all.js'></script> <script src='scripts/mainb.min.js'></script> <script src='scripts/mainc.min.js'></script> <script src='scripts/maind.min.js'></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var locale = 'pt-br'; var calendar = new FullCalendar.Calendar(calendarEl, { contentHeight: 400, plugins: [ 'interaction', 'dayGrid', 'timeGrid' ], locale: locale, height: 'auto', selectable: true, header: { left: 'title', center: '', right: 'prev,next today' }, dateClick: function(info) { let date = info.dateStr; document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `registers.php?date=${date}`; } }); calendar.render(); $('.fc-icon').css("color", "#fff"); }); </script> </head> <body> <div id="loading" class="loading-background flex-row flex-center hidden"> <div id="spinner" class="loading-spinner"></div> </div> <div id="registers-video" class="video-tip flex-row flex-center hidden"> <img id="close-registers" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Navegue.gif"/> </div> <div class="local-container"> <div class="flex-center flex-column content"> <div id="home" class="flex flex-column align-center scrollable"> <h1 id="name">Olá, <?php echo utf8_encode($_SESSION['name']); ?></h1> <h2 class="message">Aqui estão algumas informações sobre você na <?php echo utf8_encode($_SESSION['company']); ?></h2> <ul class="data-list"> <li class="data flex-column flex-center"> <span>Código de Funcionário</span> <span class="data-content"> <?php echo $_SESSION['codUser']; ?> </span> </li> <li class="data flex-column flex-center"> <span>CBO</span> <span class="data-content"> <?php echo $_SESSION['cbo']; ?> </span> </li> <li class="data flex-column flex-center"> <span>Cargo</span> <span class="data-content"> <?php echo utf8_encode($_SESSION['FunctionName']); ?> </span> </li> <li class="data flex-column flex-center"> <span>Código do Cartão Ponto</span> <span class="data-content"> <?php echo $_SESSION['cardNumber']; ?> </span> </li> </ul> </div> <div id="registers" class="hidden flex flex-column align-center scrollable"> <div class="flex-row help"> <img src="images/libras.png" id="libras-registers"/> <img src="images/help.svg" id="text-registers" /> <span id="registersTooltip-text" class="tooltip-text"> Navegue utilizando o calendário e selecione uma data para ver os registros de ponto correspondentes. </span> </div> <div id="calendar"></div> </div> </div> <footer class="nav flex-column align-center"> <h4><?php echo utf8_encode($_SESSION['company']); ?></h4> <div class="flex-row"> <div id="homeTab" class="tab flex-column flex-center selected-tab" style="width: 50% !important"> <span>Home</span> </div> <div id="registersTab" class="tab flex-column flex-center" style="width: 50% !important"> <span>Registros</span> </div> </div> </footer> </div> <script> let textTooltip = document.querySelector("#text-registers"); let tooltipText = document.querySelector("#registersTooltip-text"); textTooltip.onclick = () => { tooltipText.classList.add("fade"); setTimeout(() => { tooltipText.classList.remove("fade"); }, 5000); }; $(document).ready(() => { $('a:last').addClass('hidden'); let homeTab = document.querySelector("#homeTab"); let registersTab = document.querySelector("#registersTab"); let homeContent = document.querySelector("#home"); let registersContent = document.querySelector("#registers"); homeTab.addEventListener('click', (e) => { homeContent.classList.remove("hidden"); registersContent.classList.add("hidden"); homeTab.classList.add("selected-tab"); registersTab.classList.remove("selected-tab"); }); registersTab.addEventListener('click', (e) => { homeContent.classList.add("hidden"); registersContent.classList.remove("hidden"); homeTab.classList.remove("selected-tab"); registersTab.classList.add("selected-tab"); }); // REGISTERS TIP VIDEO let libRegisters = document.querySelector("#libras-registers"); let closeRegisters = document.querySelector("#close-registers"); let videoRegisters = document.querySelector("#registers-video"); libRegisters.onclick = () => { videoRegisters.classList.remove("hidden"); } closeRegisters.onclick = () => { videoRegisters.classList.add("hidden"); } }); </script> </body> </html><file_sep><?php include 'connection.php'; $sql = "select UserName, UserLastName, UserCpf from tb_user inner join tb_function on idtb_function = fk_function where FunctionName = '{$_GET['categorie']}'"; $result = mysqli_query($connection, $sql); ?><file_sep><?php include 'connection.php'; $sql = "select * from tb_function"; $result = mysqli_query($connection, $sql); ?><file_sep><!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"/> <link rel="stylesheet" href="css/index.css?version=12"/> <script src="scripts/jquery.js"></script> </head> <body> <div id="loading" class="loading-background flex-row flex-center hidden"> <div id="spinner" class="loading-spinner"></div> </div> <div id="page" class="local-container hidden"> <div id="home" class="flex-center flex-column"> <img src="images/RoundedLogo.svg"/> <h1>Bem-Vindo!</h1> <div id="form"> <form class="form flex-center"> <input type="text" autocomplete="off" class="login-input" id="login" name="login" placeholder="Login" maxlength="14"> <input type="<PASSWORD>" autocomplete="off" class="login-input" id="password" name="password" placeholder="<PASSWORD>"> <h3 id="info"> <?php if (isset($_GET['erro'])) { if ($_GET['erro'] == "incorrect") { echo "Os dados informados são inválidos."; } } ?> </h3> <input type="submit" id="pronto" class="btn" value="Entrar"> </form> </div> </div> </div> <script> window.history.forward(1); window.onload = () => { document.getElementById("page").classList.remove("hidden"); } let login = document.querySelector("#login"); let password = document.querySelector("#password"); let form = document.querySelector("#form"); document.querySelector("#pronto").addEventListener('click', (event) => { event.preventDefault(); if(login.value == "" || password.value == "") { form.classList.add("validate-error"); form.addEventListener('animationend', (evt) => { if(evt.animationName == "nono") { form.classList.remove("validate-error"); } }) } else { document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `php/login.php?login=${login.value}&password=${<PASSWORD>.value}` } }); login.addEventListener('input', (e) => { if(login.value.length == 3 && e.inputType != "deleteContentBackward") { login.value += "."; } else if (login.value.length == 7 && e.inputType != "deleteContentBackward") { login.value += "."; } else if (login.value.length == 11 && e.inputType != "deleteContentBackward") { login.value += "-"; } }) </script> </body> </html><file_sep><?php session_start(); if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta http-equiv="pragma" content="no-cache"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css?version=12"> <link rel="stylesheet" href="css/func_view.css?version=12"> <script src="scripts/jquery.js"></script> <!-- Full Callendar --> <link href='css/main.min.css' rel='stylesheet' > <link href='css/mainb.min.css' rel='stylesheet'/> <link href='css/mainc.min.css' rel='stylesheet'/> <script src='scripts/main.min.js'></script> <script src='scripts/locales-all.js'></script> <script src='scripts/mainb.min.js'></script> <script src='scripts/mainc.min.js'></script> <script src='scripts/maind.min.js'></script> <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var locale = 'pt-br'; var calendar = new FullCalendar.Calendar(calendarEl, { plugins: [ 'interaction', 'dayGrid', 'timeGrid' ], locale: locale, height: 'auto', selectable: true, header: { left: 'title', center: '', right: 'prev,next today' }, dateClick: function(info) { let date = info.dateStr; let search = location.search; let parameters = search.replace("?", ""); parameters = parameters.split("&"); document.querySelector("#loading").classList.remove("hidden"); document.querySelector("#spinner").classList.add("spin"); window.location.href = `registers_for_admin.php?date=${date}&${parameters[1]}&name=<?php echo $_GET['name']; ?>`; } }); calendar.render(); $('.fc-icon').css("color", "#fff"); }); </script> </head> <body> <div id="loading" class="loading-background flex-row flex-center hidden"> <div id="spinner" class="loading-spinner"></div> </div> <div id="registers-video" class="video-tip flex-row flex-center hidden"> <img id="close-registers" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Navegue.gif"/> </div> <div class="flex-row popup hidden"> <div class="flex-column popup-content"> <h2 class="popup-title">Aviso</h2> <h3 class="popup-text">Não foi possível carregar informações sobre o colaborador.</h3> <button class="popup-button">Entendi</button> </div> </div> <?php if($_GET['cpf'] != null){ echo " <div class='local-container'> <div id='home' class='flex-center flex-column scrollable'> <div class='flex-row help'> <img src='images/libras.png' id='libras-registers'/> <img src='images/help.svg' id='text-registers' /> <span id='registersTooltip-text' class='tooltip-text'> Navegue utilizando o calendário e selecione uma data para ver os registros de ponto correspondentes. </span> </div> <h1 id='title'>Colaborador</h1> <h1 id='name'>"; echo $_GET['name']; echo "</h1> <h3 id='function'>"; echo @$_GET['categorie']; echo "</h3> <div id='calendar'></div> </div> </div>"; } else { echo " <script> document.querySelector('.popup').classList.remove('hidden'); document.querySelector('.popup').classList.add('fade-popup'); document.querySelector('.popup-button').addEventListener('click', () => { document.querySelector('#loading').classList.remove('hidden'); document.querySelector('#spinner').classList.add('spin'); javascript:history.back(-1) }); </script>"; } ?> <script> $(document).ready(() => { $('a:last').addClass('hidden'); let textTooltip = document.querySelector("#text-registers"); let tooltipText = document.querySelector("#registersTooltip-text"); textTooltip.onclick = () => { tooltipText.classList.add("fade"); setTimeout(() => { tooltipText.classList.remove("fade"); }, 5000); }; // REGISTERS TIP VIDEO let libRegisters = document.querySelector("#libras-registers"); let closeRegisters = document.querySelector("#close-registers"); let videoRegisters = document.querySelector("#registers-video"); libRegisters.onclick = () => { videoRegisters.classList.remove("hidden"); } closeRegisters.onclick = () => { videoRegisters.classList.add("hidden"); } }); </script> </body> </html><file_sep><?php include 'connection.php'; $sqlId = "select fk_electronicPoint from tb_point where idtb_point = ".$_SESSION['pointCode']; $resultId = mysqli_query($connection, $sqlId); while($row = mysqli_fetch_assoc($resultId)) { $sql = "select Locale, CNPJ from tb_electronicpoint inner join tb_company on idtb_company = fk_company where idtb_electronicPoint = ".$row['fk_electronicPoint']." and idtb_company = 1"; } $result = mysqli_query($connection, $sql); ?><file_sep><?php include 'connection.php'; $sql = "select UserName, UserLastName, UserCpf from tb_user where UserName = '{$_GET['name']}' or UserLastName = '{$_GET['name']}'"; $result = mysqli_query($connection, $sql); ?><file_sep><?php include 'connection.php'; session_start(); $passRes = mysqli_query($connection, "select idtb_user, UserPassword from tb_user where UserEmail = '".$_SESSION['email']."'"); while($row = mysqli_fetch_assoc($passRes)) { if($row['UserPassword'] == $_POST['password']) { $sql = "update tb_monthControl set Status = 'Negado' where fk_user = '".$row['idtb_user']."' and month(DateControl) = month(now()) and year(DateControl) = year(now());"; mysqli_query($connection, $sql); header('Location: ../month_closed.html'); } else { header('Location: ../authentication_error.html'); } } ?><file_sep><?php session_start(); include 'php/func.php'; if (isset($_SESSION["codUser"])){ // } else { header("Location: index.php"); } ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/> <meta http-equiv="X-UA-Compatible" content="ie-edge"/> <link rel="stylesheet" href="css/all.css"/> <link rel="stylesheet" href="css/categorie_results.css"/> <script src="scripts/jquery.js"></script> </head> <body> <div id="search-video" class="video-tip flex-row flex-center hidden"> <img id="close-search" class="close-video" src="images/close.svg"/> <img class="gif-tip" src="videos/Circulo.gif"/> </div> <div class="flex-row popup hidden fade-popup"> <div class="flex-column popup-content"> <h2 class="popup-title">Aviso</h2> <h3 class="popup-text">A busca não retornou nenhum resultado.</h3> <button class="popup-button" style="background-color: white">Entendi</button> </div> </div> <div class="container"> <div id="home" class="flex-center flex-column scrollable"> <div class="flex-row help"> <img src="images/libras.png" id="libras-search"/> <img src="images/help.svg" id="text-search" /> <span id="searchTooltip-text" class="tooltip-text"> O círculo azul ao lado do nome representa a presença do colaborador na empresa e o cinza, ausência. Tocando sobre algum nome você pode saber mais sobre o colaborador. </span> </div> <div id="header" class="flex-center flex-column"> <h1 id="title">Busca</h1> </div> <div class="content"> <?php if(mysqli_num_rows($result) > 0){ echo "<div id='results' class='flex-column flex-center'>"; while($row = mysqli_fetch_assoc($result)) { echo '<div class="list-item"><span class="status '; $verification = "SELECT EntryHour, LunchBreak, LunchReturn, DepartureTime FROM tb_point WHERE fk_employee = (SELECT idtb_user FROM tb_user WHERE UserName = '".$row['UserName']."') AND DATE = DATE(NOW());"; $verificationResult = mysqli_query($connection, $verification); if(mysqli_num_rows($verificationResult) > 0) { while($dataRow = mysqli_fetch_assoc($verificationResult)) { if($dataRow['EntryHour'] != null && $dataRow['LunchBreak'] == null) { echo 'online'; } else if ($dataRow['LunchReturn'] != null && $dataRow['DepartureTime'] == null) { echo 'online'; } else { echo 'offline'; } } } else { echo 'offline'; } echo utf8_encode('">&#9679</span><span>'.$row['UserName'].' '.$row['UserLastName'].'</span><h1 class="hidden">'.$row['UserCpf'].'</h1></div>'); } echo "</div>"; } else { echo " <script> document.querySelector('.popup').classList.remove('hidden'); document.querySelector('.popup').classList.add('fade-popup'); document.querySelector('.popup-button').addEventListener('click', () => { javascript:history.back(-1) }); </script>"; } ?> </div> </div> </div> <script> $(document).ready(() => { $('a:last').addClass('hidden'); $('span:last').css("border-bottom", "none"); let funcs = [...document.getElementsByClassName("list-item")]; let search = location.search; let parameters = search.replace("?", ""); funcs.forEach((e) => { e.addEventListener('click', () => { window.location.href = `func_view.php?name=${e.children[1].innerHTML}&cpf=${e.children[2].innerText}`; }); }); let searchTooltip = document.querySelector("#text-search"); let searchTooltipText = document.querySelector("#searchTooltip-text"); searchTooltip.onclick = () => { searchTooltipText.classList.add("fade"); setTimeout(() => { searchTooltipText.classList.remove("fade"); }, 5000); }; // SEARCH TIP VIDEO let libSearch = document.querySelector("#libras-search"); let closeSearch = document.querySelector("#close-search"); let videoSearch = document.querySelector("#search-video"); libSearch.onclick = () => { videoSearch.classList.remove("hidden"); } closeSearch.onclick = () => { videoSearch.classList.add("hidden"); } }); </script> </body> </html>
4ce014f26b2ff6517549e0df8589a720f7e27eb5
[ "Markdown", "PHP" ]
17
PHP
RuanScherer/MecSystem_Mobile
8d6cb9847150ee519a8df9ff7626cb533b8bbd73
b21c1cc87d409c6f5fc02718af01251f7a0df4dc
refs/heads/master
<repo_name>nemishzalavadiya/Winery-Shop<file_sep>/WineryShop/Models/ViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WineryShop.Core.Models { public class ViewModel { public string username; } }<file_sep>/WineryShop/Controllers/ValidateController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class ValidateController : Controller { // GET: Validate public static string EncodePasswordToBase64(string password) { try { byte[] encData_byte = new byte[password.Length]; encData_byte = System.Text.Encoding.UTF8.GetBytes(password); string encodedData = Convert.ToBase64String(encData_byte); return encodedData; } catch (Exception ex) { throw new Exception("Error in base64Encode" + ex.Message); } } //this function Convert to Decord your Password public string DecodeFrom64(string encodedData) { System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecode_byte = Convert.FromBase64String(encodedData); int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length); char[] decoded_char = new char[charCount]; utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0); string result = new String(decoded_char); return result; } public ActionResult Index() { return RedirectToAction("Index","Home"); } public ActionResult Login() { return View(); } [HttpPost] public ActionResult LoginDone(Login login) { ConModel11 db = new ConModel11(); string ValPas = EncodePasswordToBase64(login.Password); var model = db.Logins.FirstOrDefault(x=>x.Username.Equals(login.Username) && x.Password.Equals(ValPas)); if (model == null) { TempData["msg"] = "Invalide Credentials"; } else { TempData["msg"] = "Login SuccessFully " + model.Designation; if (model.Designation.Equals("admin")) { Session["Admin"] = "admin"; } Session["Username"] = login.Username; } return RedirectToAction("Index","Home"); } public ActionResult Register() { return View(); } [HttpPost] public ActionResult RegisterDone(Login login) { ConModel11 db = new ConModel11(); if (db.Logins.Find(login.Username) == null) { Login l = new Login(); l.Username = login.Username; l.Password = <PASSWORD>64(login.Password); l.Designation = "user"; if (login.Email != null) { l.Email = login.Email; } db.Logins.Add(l); db.SaveChanges(); TempData["msg"] = "Registration SuccessFully"; return RedirectToAction("Index", "Home"); } else { TempData["msg"] = "Provided Username isnot Available"; return RedirectToAction("Index", "Home"); } } public ActionResult Logout() { TempData["msg"] = "Logged Out SuccessFully"; Session["Username"] = null; if (Session["Admin"] != null) { Session["Admin"] = null; } return RedirectToAction("Index","Home"); } public ActionResult Fotget() { return View(); } [HttpPost] public async Task<ActionResult> Forgot(string reportName) { ConModel11 db = new ConModel11(); string user = reportName; var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[8]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var finalString = new String(stringChars); Login model = db.Logins.Find(user); if (model == null) { TempData["msg"] = "Invalide Username : "+user; return RedirectToAction("Index","Home"); } if (model.Email == null) { TempData["msg"] = "Sorry You haven't Register your Email address"; return RedirectToAction("Index", "Home"); } model.Password = <PASSWORD>PasswordToBase64(finalString); db.SaveChanges(); var smtpClient = new SmtpClient { Host = "smtp.gmail.com", // set your SMTP server name here Port = 587, // Port EnableSsl = true, UseDefaultCredentials = false, Credentials = new NetworkCredential("<EMAIL>", "<PASSWORD>") }; try { using (var message = new MailMessage("<EMAIL>", model.Email) { Subject = "New Password", Body = "Here is your new password \n donot share with anyone \n password: " + finalString }) await smtpClient.SendMailAsync(message); } catch (Exception e) { TempData["msg"] = "Your registered Email is invalide"; return RedirectToAction("Index","Home"); } TempData["msg"] = "New Password sended to registered email address"; return RedirectToAction("Index","Home"); } public ActionResult Email() { return View(); } public ActionResult EmailSet(string Email) { ConModel11 db = new ConModel11(); string user = Session["Username"].ToString(); Login model = db.Logins.Find(user); model.Email = Email; db.SaveChanges(); TempData["msg"] = "Email set Successfully"; return RedirectToAction("Index","Home"); } } }<file_sep>/WineryShop/Controllers/WinesController.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.IO; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class WinesController : Controller { private ConModel11 db = new ConModel11(); // GET: Wines public ActionResult Index() { if (Session["Admin"] == null) { TempData["msg"] = " Please Login First !"; return RedirectToAction("Index", "Home"); } var wines = db.Wines.Include(w => w.Category); return View(wines.ToList()); } // GET: Wines/Details/5 public ActionResult Details(int? id) { if (Session["Admin"] == null) { TempData["msg"] = " Please Login First !"; return RedirectToAction("Index", "Home"); } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Wine wine = db.Wines.Find(id); if (wine == null) { return HttpNotFound(); } return View(wine); } // GET: Wines/Create public ActionResult Create() { if (Session["Admin"] == null) { TempData["msg"] = "Please Login First !"; return RedirectToAction("Index", "Home"); } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name"); return View(); } // POST: Wines/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Wine wine) { string fileName = Path.GetFileNameWithoutExtension(wine.ImageFile.FileName); string extension = Path.GetExtension(wine.ImageFile.FileName); if (ModelState.IsValid) { fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; wine.ImageUrl = "~/Image/" + fileName; fileName = Path.Combine(Server.MapPath("~/Image/"), fileName); wine.ImageFile.SaveAs(fileName); db.Wines.Add(wine); db.SaveChanges(); ModelState.Clear(); return RedirectToAction("Index"); } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", wine.CategoryId); return View(wine); } // GET: Wines/Edit/5 public ActionResult Edit(int? id) { if (Session["Admin"] == null) { TempData["msg"] = " Please Login First !"; return RedirectToAction("Index", "Home"); } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Wine wine = db.Wines.Find(id); if (wine == null) { return HttpNotFound(); } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", wine.CategoryId); return View(wine); } // POST: Wines/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Wine wine) { string fileName = Path.GetFileNameWithoutExtension(wine.ImageFile.FileName); string extension = Path.GetExtension(wine.ImageFile.FileName); if (ModelState.IsValid) { fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; wine.ImageUrl = "~/Image/" + fileName; fileName = Path.Combine(Server.MapPath("~/Image/"), fileName); wine.ImageFile.SaveAs(fileName); db.Entry(wine).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", wine.CategoryId); return View(wine); } // GET: Wines/Delete/5 public ActionResult Delete(int? id) { if (Session["Admin"] == null) { TempData["msg"] = " Please Login First !"; return RedirectToAction("Index", "Home"); } if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Wine wine = db.Wines.Find(id); if (wine == null) { return HttpNotFound(); } return View(wine); } // POST: Wines/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Wine wine = db.Wines.Find(id); db.Wines.Remove(wine); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>/WineryShop/Controllers/ProfileController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class ProfileController : Controller { // GET: Profile public ActionResult Index() { if (Session["Username"] == null) { TempData["msg"] = "Please Login First !"; return RedirectToAction("Index", "Home"); } string user = Session["Username"].ToString(); ConModel11 db = new ConModel11(); var data = db.Logins.Where(x => x.Username == user).ToList(); ViewBag.profileData = data; return View("~/Views/Profile.cshtml"); } } }<file_sep>/WineryShop/Models/Wine.cs using System.ComponentModel.DataAnnotations; using System.Web; using System.ComponentModel.DataAnnotations.Schema; namespace WineryShop.Core.Models { public class Wine { [Key] [System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [StringLength(255)] public string Name { get; set; } [Required] [StringLength(100)] public string ShortDescription { get; set; } [Required] [StringLength(255)] public string LongDescription { get; set; } [Required] public int Price { get; set; } [StringLength(255)] [System.ComponentModel.DisplayName("Upload a file")] public string ImageUrl { get; set; } public int CategoryId { get; set; } public Category Category { get; set; } [NotMapped] public HttpPostedFileBase ImageFile { get; set; } } } <file_sep>/WineryShop/Models/ShoppingCartItem.cs using System.ComponentModel.DataAnnotations; namespace WineryShop.Core.Models { public class ShoppingCartItem { [Key] [System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int Qty { get; set; } [Required] public int WineId { get; set; } //s [Required] //public int total { get; set; } public Wine Wine { get; set; } public string WineName { get; set; } public int price { get; set; } [Required] public string UserId { get; set; } } } <file_sep>/WineryShop/Controllers/OrderController.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class OrderController : Controller { // GET: Order public ActionResult Index() { return View(); } public ActionResult Checkout() { if (Session["Username"] == null) { TempData["msg"] = "Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); var user = Session["Username"].ToString(); var address = db.Orders.Where(x => x.UserId == user).ToList(); if (address != null) { foreach(var i in address) { ViewBag.firstName = i.FirstName; ViewBag.lastName = i.LastName; ViewBag.phoneNumber = i.PhoneNumber; ViewBag.email = i.Email; ViewBag.addressLine1 = i.AddressLine1; ViewBag.addressLine2 = i.AddressLine2; ViewBag.city = i.City; ViewBag.zip = i.ZipCode; ViewBag.state = i.State; ViewBag.country = i.Country; } } return View(); } //string FirstName,string LastName,string PhoneNumber,string Email,string AddressLine1, string AddressLine2, string City, string State,string Country,string ZipCode public ActionResult CheckoutComplete(Order order) { if (Session["Username"] == null) { TempData["msg"] = "To Create Order Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); Order o = new Order(); o.FirstName = order.FirstName; o.LastName = order.LastName; o.PhoneNumber = order.PhoneNumber; o.Email = order.Email; o.City = order.City; o.Country = order.Country; o.AddressLine1 = order.AddressLine1; o.AddressLine2 = order.AddressLine2; o.OrderPlacedTime = System.DateTime.Now; o.State = order.State; o.ZipCode = order.ZipCode; o.UserId = Session["Username"].ToString(); var mod = db.ShoppingCartItems.ToList(); var total=0; OrderDetail od = new OrderDetail(); foreach (ShoppingCartItem s in mod) { total += (s.price*s.Qty); od.WineName = s.WineName; od.Qty = s.Qty; od.Price = s.price; od.UserId = Session["Username"].ToString(); od.OrderPlacedTime = System.DateTime.Now; db.OrderDetails.Add(od); db.SaveChanges(); } o.OrderTotal = total; db.Orders.Add(o); string ses = Session["Username"].ToString(); var model = db.ShoppingCartItems.Where(x=>x.UserId.Equals(ses) ); foreach (ShoppingCartItem s in model) { db.ShoppingCartItems.Remove(s); } db.SaveChanges(); return View(); } public ActionResult ShowMyOrder() { if (Session["Username"] == null) { TempData["msg"] = " Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); string ses = Session["Username"].ToString(); List<OrderDetail> model = db.OrderDetails.Where(x=>x.UserId.Equals(ses)).ToList(); return View(model); } } }<file_sep>/WineryShop/Models/OrderDetail.cs using System.ComponentModel.DataAnnotations; namespace WineryShop.Core.Models { public class OrderDetail { public int Id { get; set; } [Required] [MaxLength(255)] public string WineName { get; set; } public int Qty { get; set; } public int Price { get; set; } public string UserId { get; set; } [Required] public System.DateTime OrderPlacedTime { get; set; } } } <file_sep>/WineryShop/Models/Category.cs using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; namespace WineryShop.Core.Models { public class Category { [Key] [System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] [StringLength(255)] public string Name { get; set; } public ICollection<Wine> Wines { get; set; } public Category() { Wines = new Collection<Wine>(); } } } <file_sep>/README.md # wineryshopdotnet this project is built on dotnet software base and by using entity framework 2019 with MVC. Project name: WineryShop about : -------- => This project is built on dotnet mvc software ( Visual studio 2019) => Using Entity framework with code first database Approch Start of project: ---------------- 1. This is code first approach, so first perform migration steps to get database ready. 2. Project index file: /Home/index/ (Controller file: HomeController) run this controller using debugger in visual studio. if any guidance needed for dotnet project , we are here to help. contact on email mentioned below as first contributor. reference: --------- To see working project : use https://wineryshop.azurewebsites.net/ adminusername : <EMAIL> adminpassword : <PASSWORD>.com Controllers: ------------ 1. HomeController - Project initialization controller from Database entries. 2. ValidateController - Project authentication & authorization controller using Database manually defined table. 3. CategoriesController 4. WinesController 5. LoginsController - These controllers are used to manage Webapp database entries using GUI by admin only. 6. ShoppingcartController - This controller is used to manage shopping cart details of individuals. 7. OrderController - This controller is used to manage ordering process of individual items. Contributors: ------------- 1. <NAME> email: <EMAIL> 2. <NAME> email: <EMAIL> 3. <NAME> email: <EMAIL> Guidance: --------- Prof. <NAME> Prof. <NAME> , From dharmsinh desai university. <file_sep>/WineryShop/Controllers/ShoppingCartController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class ShoppingCartController : Controller { // GET: ShoppingCart public ActionResult Index() { return View(); } public ActionResult AddToShoppingCart(int id) { if (Session["Username"] == null) { TempData["msg"] = "To Create Order Please Login First !"; return RedirectToAction("Index","Home"); } ConModel11 db = new ConModel11(); ShoppingCartItem s = new ShoppingCartItem(); s.Qty = 1; s.WineId = id; s.UserId = Session["Username"].ToString(); s.WineName = db.Wines.First(x=>x.Id==id).Name; s.price = db.Wines.First(x => x.Id == id).Price; db.ShoppingCartItems.Add(s); db.SaveChanges(); return RedirectToAction("show"); } public ActionResult show() { if (Session["Username"] == null) { TempData["msg"] = "Please Login First"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); var temp = Session["Username"].ToString(); var model = db.ShoppingCartItems.Where(x=>x.UserId.Equals(temp) ).ToList(); return View(model); } public ActionResult RemoveFromShoppingCart(int id) { if (Session["Username"] == null) { TempData["msg"] = "To Create Order Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); var s = db.ShoppingCartItems.First(x=>x.Id==id); s.Qty = s.Qty - 1; if (s.Qty == 0) { db.ShoppingCartItems.Remove(s); } db.SaveChanges(); return RedirectToAction("show"); } public ActionResult AddToAgainShoppingCart(int id) { if (Session["Username"] == null) { TempData["msg"] = "To Create Order Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); var s = db.ShoppingCartItems.First(x => x.Id == id); s.Qty = s.Qty + 1; db.SaveChanges(); return RedirectToAction("show"); } public ActionResult RemoveAllCart() { if (Session["Username"] == null) { TempData["msg"] = "Please Login First !"; return RedirectToAction("Index", "Home"); } ConModel11 db = new ConModel11(); var rows = from o in db.ShoppingCartItems select o; foreach (var row in rows) { db.ShoppingCartItems.Remove(row); } db.SaveChanges(); return RedirectToAction("Index","Home"); } } }<file_sep>/WineryShop/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class HomeController : Controller { public ActionResult Index() { ConModel11 db = new ConModel11(); var model = db.Wines.ToList(); Session["Categories"] = db.Categories.ToList(); return View(model); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult wines(int id) { ConModel11 db = new ConModel11(); if (id == -1) { return View(db.Wines.ToList()); } var model = db.Wines.Where(x=>x.CategoryId == id); return View(model); } public ActionResult Contact() { ViewBag.Message = "Developer Details"; return View(); } } }<file_sep>/WineryShop/Controllers/WineController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using WineryShop.Core.Models; namespace WineryShop.Controllers { public class WineController : Controller { // GET: Wine public ActionResult Index() { return View(); } public ActionResult Details(int id) { ConModel11 db = new ConModel11(); var model = db.Wines.First(x => x.Id == id); return View(model); } } }
e230679c8e06bd440936632dcd89234fc9fc2716
[ "Markdown", "C#" ]
13
C#
nemishzalavadiya/Winery-Shop
d2ce5d2c7d01d03f8db5f42f97da57cbbb785e9f
c51fa89c71748ed4be1db98753b647299a64a3f4
refs/heads/master
<repo_name>alefuedev/base_apperel<file_sep>/script.js function ValidateEmail(email) { let regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(regex.test(email)){ return alert('Thank you!'); } let p = document.getElementById('valid-email'); let icon = document.getElementById('attention'); icon.style.opacity = 1; p.style.opacity = 1; } function button() { let email = document.getElementById('email'); email = email.value ValidateEmail(email); }
2d651495f161aafe1fe590d1d0965b4ed3a9171d
[ "JavaScript" ]
1
JavaScript
alefuedev/base_apperel
1aab54021138c4c658e0d47ee908c545482d89d7
c5b8e5a38b76f89dcae89d37dc7596f93f1a94bd
refs/heads/master
<file_sep>import React, { createRef, useState } from 'react'; import './App.css'; const Name = ({ id, info, handleFavourite }) => ( <li className={info.sex} onClick={() => handleFavourite(id)}> {info.name} </li> ) const SelectedList = ({ favourites, data, deleteFavourite }) => { const hasFavourites = (favourites.length > 0) const favList = favourites.map((fav, i) => { return ( <Name id={i} key={i} info={data[fav]} handleFavourite={(id) => deleteFavourite(id)} /> ) }) return ( <div className="favourites"> <h4> {hasFavourites ? 'Selected Options' : 'Click an option to include it..' } </h4> <ul> {favList} </ul> {hasFavourites && <hr />} </div> ) } const OptionsList = ({ data, filter, favourites, addFavourite }) => { const input = filter.toLowerCase() // Gather list of names const names = data // filtering out the names that... .filter((person, i) => { return ( // ...are already favourited favourites.indexOf(person.id) === -1 // ...are not matching the current search value && !person.name.toLowerCase().indexOf(input) ) }) // ...output a <Name /> component for each name .map((person, i) => { // only display names that match current input string return ( <Name id={person.id} key={i} info={person} handleFavourite={(id) => addFavourite(id)} /> ) }) /* ##### the component's output ##### */ return ( <ul> {names} </ul> ) } const Search = (props) => { const filterInput = createRef(); const { filterVal, filterUpdate } = props; return ( <> <form> <input type='text' ref={filterInput} placeholder='Type to filter..' // binding the input value to state value={filterVal} onChange={() => { filterUpdate(filterInput.current.value) }} /> </form> </> ) } const App = (props) => { const [state, setState] = useState({ filterText: '', favourites: [] }); // const [searchBool, setSearch] = useState(false); const filterUpdate = (value) => { setState({ ...state, filterText: value }); } const clearSearch = () => { setState({ ...state, filterText: "" }); } const addFavourite = (id) => { const newSet = state.favourites.concat([id]) setState({ ...state, favourites: newSet }) } const deleteFavourite = (id) => { const { favourites } = state const newList = [ ...favourites.slice(0, id), ...favourites.slice(id + 1) ] setState({ ...state, favourites: newList }) } const hasSearch = state.filterText.length > 0 return ( <div> <header> </header> <main> <Search filterVal={state.filterText} filterUpdate={filterUpdate} /> <SelectedList data={props.data} favourites={state.favourites} deleteFavourite={deleteFavourite} /> <div className="wrapper"> <OptionsList data={props.data} filter={state.filterText} favourites={state.favourites} addFavourite={addFavourite} /> </div> {/* Show only if user has typed in search. To reset the input field, we pass an empty value to the filterUpdate method */} {hasSearch && <button onClick={clearSearch}> Clear Search </button> } </main> </div> ) } export default App;
2ac72bf33ee5ae222535e2c79cc87f76a865da11
[ "JavaScript" ]
1
JavaScript
juvers/FilterSearchSelect
8597e60b836f83071e9e86788a20d42b6bf8d9f6
e9bb2cf213ea8e8751fe3b672377a7130cee8616
refs/heads/master
<repo_name>m-parakh/GettingCleaningDataCourseProject<file_sep>/DataLoadingInR.R # Load data in the global environment ## Load activity and feature labels activity_labels <- read.table("UCI HAR Dataset/activity_labels.txt", col.names=c("Activity_ID", "Activity_Name")) features <- read.table("UCI HAR Dataset/features.txt", col.names=c("Feature_ID", "Feature_Name")) ## Load training data subject_train <- read.table("UCI HAR Dataset/train/subject_train.txt", col.names=c("Subject_ID")) X_train <- read.table("UCI HAR Dataset/train/X_train.txt") y_train <- read.table("UCI HAR Dataset/train/y_train.txt", col.names=c("Activity_ID")) ## Load test data subject_test <- read.table("UCI HAR Dataset/test/subject_test.txt", col.names=c("Subject_ID")) X_test <- read.table("UCI HAR Dataset/test/X_test.txt") y_test <- read.table("UCI HAR Dataset/test/y_test.txt", col.names=c("Activity_ID"))<file_sep>/DataExtraction.R ## Function to extract mean and standard deviation from each measurement extractDataSubset <- function() { library(dplyr) ## Get vector to select columns containing Subject_ID subject_cols <- grep("Subject_ID",names(mergedData), fixed=TRUE) ## Subset the merged training+test dataset to extract only the Subject_ID column Subject_ID <- mergedData[, subject_cols] ## Get vector to select columns containing Activity_ID act_cols <- grep("Activity_ID",names(mergedData), fixed=TRUE) ## Subset the merged training+test dataset to extract only the Activity_ID column Activity_ID <- mergedData[, act_cols] ## Get vector to select rows of features ## containing mean of measurements mean_cols <- grep("MeanValue",names(mergedData), fixed=TRUE) ## Subset the merged training+test dataset to ## extract only the mean features mean_dataset <- mergedData[, mean_cols] ## Get vector to select rows of features ## containing StDev of measurements std_cols <- grep("StDev",names(mergedData), fixed=TRUE) ## Subset the merged training+test dataset to ## extract only the StDev features std_dataset <- mergedData[, std_cols] relevant_dataset <- cbind(Subject_ID, Activity_ID, mean_dataset, std_dataset) }<file_sep>/DataBinding.R ## Function to bind and export a combined dataset by ## first combining the feature set with the subject and activity ids of training and test datasets ## and then combining those two into a single dataset bindData <- function() { ## Bind training data train_dataset <- cbind(subject_train, y_train, X_train) ## Bind test data test_dataset <- cbind(subject_test, y_test, X_test) ## Combine training and test datasets complete_dataset <- rbind(train_dataset, test_dataset) }<file_sep>/FeatureNaming.R ## Function to lean feature names for easy readability and subsetting later on ## and name the features in the feature sets nameFeatures <- function(f) { ## A character vector containing original feature names New_Feature_Name <- as.character(f[,2]) ## Replace -mean() with MeanValue New_Feature_Name <- gsub("-mean()", "MeanValue", New_Feature_Name, fixed=TRUE) ## Replace -std() with StDev New_Feature_Name <- gsub("-std()", "StDev", New_Feature_Name, fixed=TRUE) ## Replace -X with DirX New_Feature_Name <- gsub("-X", "DirX", New_Feature_Name, fixed=TRUE) ## Replace -Y with DirY New_Feature_Name <- gsub("-Y", "DirY", New_Feature_Name, fixed=TRUE) ## Replace -Z with DirZ New_Feature_Name <- gsub("-Z", "DirZ", New_Feature_Name, fixed=TRUE) f_new <- cbind(f, New_Feature_Name) }<file_sep>/TidyDataCreation.R ## Function to create tidy data set createTidyData <- function() { library(reshape2) meltResult <- melt(activitynameData, id=c("Subject_ID", "Activity_ID", "Activity_Name")) castResult <- dcast(meltResult, Activity_Name + Subject_ID ~ variable, fun.aggregate = mean, na.rm=TRUE) }<file_sep>/README.md ## README for course project *** The goal of this project was to clean and transform the Human Activity Recognition Using Smartphones data set obtained from University of California, Irvine into a tidy data set. *** The "run_analysis.R" script sources the other scripts described below. It calls functions from the other scripts to transform the provided data. *** The "DataLoadingInR.R" script loads the data into R for activity labels, feature variable names, and training and test data sets. *** The "FeatureNaming.R" script contains a function nameFeatures(f) that replaces strings "-mean()", "-std()", "-X", "-Y", "-Z" from feature variables with "MeanValue", "StDev", "DirX", "DirY", "DirZ". These revised names are then used as column names for X_train and X_test data sets to avoid errors later on during binding and subsetting of data sets. *** The "DataBinding.R" script contains a function bindData() that creates a merged set of training and test data. *** The "DataExtraction.R" script contains a function extractDataSubset() that subsets the merged data set to only include the variable columns that contain the mean and standard deviation of measurements. My approach is not optimal -- I extracted the subject_id, activity_id, columns containing measurement means, and columns containing measurement standard deviations. Then I stitched them back together. I tried a few other ways of doing this, but kept getting errors, so finally took this route. *** The "ActivityNaming.R" script contains a function that merges the activity names with the the extracted relevant data subset. *** The "TidyDataCreation.R" script contains a function createTidyData() that uses the the melt and dcast functions from the Reshape2 package to create a wide tidy data set. *** This tidy data set is then written out to a text file. *** <file_sep>/run_analysis.R ## Source the code in from other scripts source("DataLoadinginR.R") source("FeatureNaming.R") source("DataBinding.R") source("DataExtraction.R") source("ActivityNaming.R") source("TidyDataCreation.R") ## Name the features properly features_revised <- nameFeatures(features) names(X_train) <- features_revised$New_Feature_Name names(X_test) <- features_revised$New_Feature_Name ## Create merged dataset mergedData <- bindData() ## Get relevant mean and stdev data by subsetting relevantData <- extractDataSubset() ## Bring in activity names activitynameData <- includeActivityNames() ## Create tidy dataset tidyData <- createTidyData() ## Write tidy dataset to a text file write.table(tidyData, "HAR_tidydata.txt", row.name=FALSE) <file_sep>/CODEBOOK.md ## CodeBook for course project *** The "run_analysis.R" script sources the other scripts described below. It calls functions from the other scripts to transform the provided data. *** The "DataLoadingInR.R" script loads the data into R for activity labels, feature variable names, and training and test data sets. # "activity_labels" is a data table containing "Activity_ID", "Activity_Name" ## "Activity_ID" has a number between 1 and 6 for each of the 6 activity types ## "Activity_Name" contains a description of the activity performed (e.g., Walking) # "features" is a data table containing "Feature_ID", "Feature_Name" ## "Feature_ID" contains a number between 1 and 561 for each of the 561 feature variables ## "Feature_Name" contains a descriptive unique name for each variable # "subject_train" / "subject_test" is a data table that contains the "Subject_ID" for each record of the training /test data set ## "Subject_ID" contains a number between 1 and 30 for each of the 30 subjects who participated in the study # "X_train" / "X_test" is a data table containing all records of values of each of the feature variables obtained from the study # "y_train" / "y_test" is a data table containing the "Activity_ID" for each record of the training / test data set *** The "FeatureNaming.R" script contains a function nameFeatures(f) that replaces strings "-mean()", "-std()", "-X", "-Y", "-Z" from feature variables with "MeanValue", "StDev", "DirX", "DirY", "DirZ". # features_revised <- nameFeatures(features) createas a new data table containing a new column 'New_Feature_Name' for revised feature names. These revised names are then used as column names for X_train and X_test data sets to avoid errors later on during binding and subsetting of data sets. # names(X_train) <- features_revised$New_Feature_Name # names(X_test) <- features_revised$New_Feature_Name *** The "DataBinding.R" script contains a function bindData() that creates a merged set of training and test data. # mergedData <- bindData() creates a new data table that contains 10299 rows and 563 columns. # The train_dataset is a combination of the provided tables: subject_train, y_train, and X_train # The test_dataset is a combination of the provided tables: subject_test, y_test, and X_test # Then these two datasets are appended together to return the mergedData. *** The "DataExtraction.R" script contains a function extractDataSubset() that subsets the merged data set to only include the variable columns that contain the mean and standard deviation of measurements. My approach is not optimal -- I extracted the subject_id, activity_id, columns containing measurement means, and columns containing measurement standard deviations. Then I stitched them back together. I tried a few other ways of doing this, but kept getting errors, so finally took this route. # relevantData <- extractDataSubset() creates a smaller data subset containing only the mean and standard deviation columns # subject_cols <- grep("Subject_ID",names(mergedData), fixed=TRUE) creates a vector to select columns containing Subject_ID # Subject_ID <- mergedData[, subject_cols] creates a data subset from 'mergedData' to extract only the Subject_ID column # act_cols <- grep("Activity_ID",names(mergedData), fixed=TRUE) creates a vector to select columns containing Activity_ID # Activity_ID <- mergedData[, act_cols] creates a data subset from 'mergedData' to extract only the Activity_ID column # mean_cols <- grep("MeanValue",names(mergedData), fixed=TRUE) creates vector to select columns of features containing mean of measurements # mean_dataset <- mergedData[, mean_cols] creates a data subset from 'mergedData' extract only the mean features # std_cols <- grep("StDev",names(mergedData), fixed=TRUE) creates vector to select columns of features containing StDev of measurements std_dataset <- mergedData[, std_cols] creates a data subset from 'mergedData' to extract only the standard deviation features *** The "ActivityNaming.R" script contains a function that merges the activity names with the the extracted relevant data subset. # activitynameData <- includeActivityNames() attaches the activity names to the 'relevantData' data table *** The "TidyDataCreation.R" script contains a function createTidyData() that uses the the melt and dcast functions from the Reshape2 package to create a wide tidy data set. # tidyData <- createTidyData() summarizes the mean of all included variables by 'Activity_Name' and 'Subject_Id' *** This tidy data set is then written out to a text file. <file_sep>/ActivityNaming.R ## Function to name activities includeActivityNames <- function() { result <- merge(relevantData, activity_labels, by.x="Activity_ID", by.y="Activity_ID", all=FALSE) }
5352390d6614410b53f1282d12556f2f20eb4aca
[ "Markdown", "R" ]
9
R
m-parakh/GettingCleaningDataCourseProject
67e37935d7300e33c5f0b530a10096c423395bd7
7251f028ccb8cce257ef848971e2f0798350d022
refs/heads/master
<file_sep>package nl.tudelft.jenkins.jobs; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import java.io.InputStream; import java.util.List; import nl.tudelft.jenkins.auth.User; import nl.tudelft.jenkins.auth.UserImpl; import org.jdom2.Document; import org.jdom2.input.SAXBuilder; import org.jdom2.output.XMLOutputter; import org.junit.Before; import org.junit.Test; public class JobImplTest { private static final String JOB_NAME = "X"; private static final String JOB_SCM_URL = "git://xyz"; private static final User JOB_NOTIFICATION_RECIPIENT0 = new UserImpl("person", "<EMAIL>"); private static final User JOB_NOTIFICATION_RECIPIENT1 = new UserImpl("other", "<EMAIL>"); private Job job; @Before public void setUp() { job = new JobImpl(JOB_NAME); } @Test public void testThatNewlyConsructedJobAsXmlReturnsDefaultJobConfiguration() throws Exception { final String jobAsXml = job.asXml(); final SAXBuilder builder = new SAXBuilder(); final InputStream is = this.getClass().getResourceAsStream(JobDocumentProvider.DEFAULT_JOB_FILE_NAME); final Document defaultJobDocument = builder.build(is); final XMLOutputter xmlOutputter = new XMLOutputter(); final String defaultJobAsXml = xmlOutputter.outputString(defaultJobDocument); assertThat(jobAsXml, is(equalTo(defaultJobAsXml))); } @Test(expected = IllegalArgumentException.class) public void testThatConstructorWithNullNameThrowsException() { new JobImpl(null); } @Test(expected = IllegalArgumentException.class) public void testThatConstructorWithEmptyNameArgumentThrowsException() { new JobImpl(""); } @Test public void testThatScmUrlIsSetCorrectly() throws Exception { job.setScmUrl(JOB_SCM_URL); final String xml = job.asXml(); assertThat(xml, containsString("<url>" + JOB_SCM_URL + "</url>")); } @Test public void testThatRecipientListCanBeCleared() throws Exception { job.clearNotificationRecipients(); final String xml = job.asXml(); assertThat(xml, containsString("<recipients />")); } @Test(expected = IllegalArgumentException.class) public void testThatAddingRecipientWithNullNameThrowsException() { job.addNotificationRecipient(new UserImpl("test", null)); } @Test public void testThatSingleRecipientCanBeSet() throws Exception { job.clearNotificationRecipients(); job.addNotificationRecipient(JOB_NOTIFICATION_RECIPIENT0); final String xml = job.asXml(); assertThat(xml, containsString("<recipients>" + JOB_NOTIFICATION_RECIPIENT0.getEmail() + "</recipients>")); } @Test public void testThatSecondRecipientCanBeAdded() throws Exception { job.clearNotificationRecipients(); job.addNotificationRecipient(JOB_NOTIFICATION_RECIPIENT0); job.addNotificationRecipient(JOB_NOTIFICATION_RECIPIENT1); final String xml = job.asXml(); assertThat(xml, containsString("<recipients>" + JOB_NOTIFICATION_RECIPIENT0.getEmail() + " " + JOB_NOTIFICATION_RECIPIENT1.getEmail() + "</recipients>")); } @Test public void testThatUserCanBeAdded() throws Exception { User user = new UserImpl("name", "email"); job.addUser(user); List<User> users = job.getUsers(); assertThat(users, hasSize(1)); User u = users.iterator().next(); assertThat(u.getName(), is(equalTo(user.getName()))); } }
fc1b3131eb65113efbcd8b84e508e4a1893f0847
[ "Java" ]
1
Java
alexnederlof/jenkins-ws-client
b354738f2f896c2bbcdd2a8222de1daebbc72eee
903350c5b40bda56997df3bd96b70722efb0da09
refs/heads/master
<file_sep>package com.example.ajinkya.intentchallenge; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class ParagraphActivity extends AppCompatActivity { public TextView mParagraph; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_paragraph); mParagraph = findViewById(R.id.paragraph); Intent intent = getIntent(); int code = intent.getIntExtra(MainActivity.PARA_CODE, 1); if (code == 1) { mParagraph.setText(R.string.first_paragraph_content); } else if (code == 2) { mParagraph.setText(R.string.second_paragraph_content); } else if (code == 3) { mParagraph.setText(R.string.third_paragraph_content); } } } <file_sep>package com.example.ajinkya.hellocompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import org.w3c.dom.Text; import java.util.Random; public class MainActivity extends AppCompatActivity { private TextView mHelloTextView; private String[] mColorArray = {"red", "pink", "purple", "deep_purple", "indigo", "blue", "light_blue", "cyan", "teal", "green", "light_green", "lime", "yellow", "amber", "orange", "deep_orange", "brown", "grey", "blue_grey", "black"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mHelloTextView = findViewById(R.id.hello_textView); if (savedInstanceState != null) { mHelloTextView.setTextColor(savedInstanceState.getInt("color")); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // save the current text color outState.putInt("color", mHelloTextView.getCurrentTextColor()); } public void changeColor(View view) { Random random = new Random(); String colorName = mColorArray[random.nextInt(20)]; int colorResourceName = getResources().getIdentifier(colorName, "color", getApplicationContext().getPackageName()); int colorRes = ContextCompat.getColor(this, colorResourceName); mHelloTextView.setTextColor(colorRes); } } <file_sep>package com.example.ajinkya.intentchallenge; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { public static final String PARA_CODE = "MainActivity.PARA_CODE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void showFirstParagraph(View view) { Intent intent = new Intent(this, ParagraphActivity.class); intent.putExtra(PARA_CODE, 1); startActivity(intent); } public void showSecondParagraph(View view) { Intent intent = new Intent(this, ParagraphActivity.class); intent.putExtra(PARA_CODE, 2); startActivity(intent); } public void showThirdParagraph(View view) { Intent intent = new Intent(this, ParagraphActivity.class); intent.putExtra(PARA_CODE, 3); startActivity(intent); } } <file_sep># Android-Developer-Fundamentals-V2 App projects from the Android Developer Fundamentals (Version 2) course by Google. https://developer.android.com/courses/fundamentals-training/overview-v2 Android Developer Fundamentals (V2) is an instructor-led course created by the Google Developers Training team. In this course, you learn basic Android programming concepts and build a variety of apps, starting with Hello World and working your way up to apps that schedule jobs, update settings, and use Architecture Components. What's new in the course? Version 2 of the course is available as of September 2018. The course has been updated to reflect best practices for more recent versions of the Android framework and Android Studio.
35e6955083f44434f7a72ca42d8963cc6b5a2f8a
[ "Markdown", "Java" ]
4
Java
ajinkyag911/Android-Developer-Fundamentals-V2
40a2790e34cd7c8f9c584e4ba007123e682d69f5
c86fd582d3f8b8e76cb63fcd594a56b06f57c8c1
refs/heads/master
<file_sep>import numpy import jupyter import scipy import pandas import matplotlib
2e272994dc924c5f6d8d4f12602d9c2a91ad2bfa
[ "Python" ]
1
Python
joecatarata/DataScienceWorkshop
8b751a50b3b8f6a1ec55ad3192d2be2226460f5a
250159cf237d047eba93efdabaf46aefb64e2949
refs/heads/master
<repo_name>TommyWaalkes/CircleExercise<file_sep>/circle.js function getInput(){ let input = prompt("Please give me the radius of a circle!"); return input; } function calcArea(radius){ return Math.PI*radius*radius; } function printArea(area, radius){ console.log(`The radius is ${radius}`); console.log(`The area is ${area}`); } let r = getInput(); let a = calcArea(r); printArea(a ,r);<file_sep>/circleObj.js class Circle { constructor() { this.radius = prompt("Please give me a radius"); } calcArea() { let area = this.radius * this.radius * Math.PI; return area; } outPutArea(){ let el = document.getElementById("output"); let text = document.createTextNode(`The circle has a radius of ${this.radius} and therefore an area of ${this.calcArea()}`); el.appendChild(text); } drawCircle(){ //1) Grab our target element let el = document.getElementById("outputCircle"); //2) Create an html object let cir = document.createElement("div"); //3) Add on the circle class, present in our CSS Sheet cir.setAttribute("class","circle"); //4) Setup a width and height let height = this.radius; let width = this.radius; //5) Add into our new object's style tag, the width and the height cir.style.width = `${width}px`; cir.style.height = `${height}px`; //6) We inject our circle into our target div el.appendChild(cir); } } let c = new Circle(); c.outPutArea(); c.drawCircle();
3594e5963a8b72def920409998545929f89f77c5
[ "JavaScript" ]
2
JavaScript
TommyWaalkes/CircleExercise
38c8b6e724e1f698068fb8bf60c86b48b5594ede
8f53ce60d31a6856b0c2a986fddef89f2ed2c021
refs/heads/master
<repo_name>previsecours/vueJS_Previsecours<file_sep>/src/store/store.js import Vue from 'vue'; import VueX from 'vuex'; import es from './elasticsearch.js' import configuration from '../assets/configuration.json' Vue.use(VueX); export const store = new VueX.Store({ state: { /** * [current status of filters on which we base the queries to database] * @type {Object} */ filters: { hideAllFilters: false, currentCategorInter: 'suap', currentTimeAggregation: 's', currentGeoAggregation: 'com', currentDepartment: 91, showCasernes: true }, /** * [initial zoom for map.] * @type {Object} */ carte: { zoom: 10 }, data: { geo: {}, int: {}, pre: {}, cas: {} }, dataHasBeenUpdated: 0, /** * [current status of the slider. * Initial value defined here as well.] * @type {Object} * begin: Date().getTime() First date on the slider = range min * currentPosition: INT how many steps betwwen time MIN and current time. the time for one step is defined in configuration.timeAggregation */ slider: { /** * [date BEGIN to choose which day, month... to see on the map. * Unix Timestamp (milliseconds) ex: 1528620491576 ] * @type {Date} */ begin: '', currentPosition: 1 }, configuration: { /** * [set up the different time categorInters we can choose in filters] * @type {Array} * name: display name, * nameCode: coded name for code reference * description: in case we need to explain * position: INT to define the order in the filter -> for display only * show: BOOLEAN do we show this possibility in the filter (in case it isn't used any longer) */ categorInters: [ { name: 'SUAP', nameCode: 'suap', description: 'Secours a personne', position: 1, show:true, available:true }, { name: 'Accident', nameCode: 'acci', description: 'Accident de la route', position: 2, show:true, available:true }, { name: '<NAME>', nameCode: 'incu', description: 'Incendie en milieu urbain', position: 3, show:true, available:true }, { name: '<NAME>', nameCode: 'incn', description: 'Incendie en milieu naturel', position: 4, show:true, available:true }, { name: '<NAME>', nameCode: 'coia', description: 'Incendie (naturel et urbain) et accident', position: 5, show: true, available:true } ], /** * [set up the different time aggragation that are used to define end date in filters] * @type {Array} * name: display name, * nameCode: coded name for code reference * description: in case we need to explain * timeRepetition:5, * timeStepBetweenRepetitions: { * type: 'days','months'... MOMENTjs TIME defintion. could be weeks, years... but we try to keep it minimalist: days / months * step: how many 'days' between the BEGIN and the END on the slider * } * position: INT to define the order in the filter -> for display only * show: BOOLEAN do we show this possibility in the filter (in case it isn't used any longer) */ timeAggregations: [ { name: 'jour', nameCode: 'j', description: 'aggregation par jours', timeRepetition: 7, timeStepBetweenRepetitions: { type: 'days', step: 1 }, position: 1, show:true, available:false }, { name: 'semaine', nameCode: 's', description: 'aggregation par semaines', timeRepetition: 52, timeStepBetweenRepetitions: { type: 'days', step: 7 }, position: 2, show:true, available:true }, { name: 'mois', nameCode: 'm', description: 'aggregation par mois', timeRepetition: 12, timeStepBetweenRepetitions: { type: 'months', step: 1 }, position: 3, show:true, available:false }, { name: 'trimestre', nameCode: 't', description: 'aggregation par trimestres', timeRepetition: 4, timeStepBetweenRepetitions: { type: 'months', step: 3 }, position: 4, show:true, available:false }, { name: 'an', nameCode: 'a', description: 'aggregation par ans', timeRepetition: 3, timeStepBetweenRepetitions: { type: 'months', step: 12 }, position: 5, show:true, available:false } ], geoAggregations: [ { name: 'departement', nameCode: 'dpt', description: 'aggregation par departement', position: 1, show:true, available:false }, { name: 'zone de couverture', nameCode: 'zdc', description: 'aggregation par zone de couverture', position: 2, show:true, available:true }, { name: 'commune', nameCode: 'com', description: 'aggregation par commune', position: 3, show:true, available:true } ] } }, getters: { /** * [retrieve the configuration of a time code * * Used in Slider.vue to calculate end Date] * @param {[type]} state [the code for a time aggregation] * @return {[type]} [the whole configuration related, or undefined] */ slider_timeAggregationConfiguration: state => timeAggregationNameCodeArg => { let timeAggregation try { timeAggregation = state.configuration.timeAggregations.find(timeAggregation => timeAggregation.nameCode === timeAggregationNameCodeArg) if (!timeAggregation) { throw 'timeAggregation not defined for: ' + timeAggregationNameCodeArg } } catch (e) { console.log('error', e); return } return timeAggregation } }, mutations: { filters_updateCategory: (state, newCategoryCode) => { state.filters.currentCategorInter = newCategoryCode; }, filters_updateGeoAggregation: (state, newGeoAggregation) => { state.filters.currentGeoAggregation = newGeoAggregation; }, filters_updateTimeAggregation: (state, newTimeAggregation) => { state.filters.currentTimeAggregation = newTimeAggregation; }, reloadData: (state, newData) => { if (process && process.env && process.env.DEBUG_MODE) { console.log('result newData.elasticsearchResult', newData.elasticsearchResult) } state.data[newData.dataSubset] = newData.elasticsearchResult; state.dataHasBeenUpdated += 1 }, slider_updateDateBegin: (state, newData) => { state.slider.begin = newData; }, slider_updateCurrentPosition: (state, newData) => { state.slider.currentPosition = newData; }, toogleCasernes: (state) => { state.filters.showCasernes = !state.filters.showCasernes } }, actions: { filters_updateCategory: (context, newCategoryCode) => { context.commit('filters_updateCategory', newCategoryCode) context.dispatch('reloadData', ['pre']) }, filters_updateGeoAggregation: (context, newGeoAggregation) => { context.commit('filters_updateGeoAggregation', newGeoAggregation) context.dispatch('reloadData', ['geo']) context.dispatch('reloadData', ['pre']) }, filters_updateTimeAggregation: (context, newTimeAggregation) => { return new Promise((resolve, reject) => { context.commit('filters_updateTimeAggregation', newTimeAggregation) context.dispatch('reloadData', ['pre']).then(function() { try { let dateBegin = context.state.data.pre.hits.hits[0]._source.pre_001_is context.commit('slider_updateDateBegin', dateBegin) resolve() } catch (e) { console.log('problem with state.data.pre.hits.hits[0]._source.pre_001_is -> ', e); } }) }) }, /** * [getNewData will create the query and then fetch the result for one dataset like 'int'. dataSubset has been checked in the reloadData function, so no need to double check here] * @param {object} context [store context] * @param {string} dataSubset [string, that is defined in the assets/configuration.json -> for instance could be 'int'] * @return {object} [result of the query] */ getNewData(context, dataSubset) { let query = es.function_createQuery(context.state, dataSubset) if (process && process.env && process.env.DEBUG_MODE) { console.log(query, dataSubset) } return es.search(dataSubset, query) }, /** * [reloadData will trigger the elasticsearch request and update the store with the result] * @param {object} context [store context] * @param {[string]} dataSubsets [array of strings, that are defined in the assets/configuration json. for instance could be ['int','geo'] ] * @return {object} [nothing] */ reloadData: (context, dataSubsets) => { return new Promise((resolve, reject) => { if (Array.isArray(dataSubsets)) { dataSubsets.forEach((dataSubset, i) => { //here we make sure the dataSubset is one of those defined in the assets/configuration.json if (typeof dataSubset === 'string' && typeof configuration.indexes[dataSubset] === 'string') { context.dispatch('getNewData', dataSubset).then(function(values) { let result = { 'dataSubset': dataSubset, 'elasticsearchResult': values }; context.commit('reloadData', result) //on reslve uniquement quand tout les commit sont effectues if (i === dataSubsets.length - 1) { resolve() } }) } else { console.log('dataSubset: ', dataSubset, ' needs to be part of the configuration json, like int or geo'); } }) } else { console.log('dataSubsets needs to be an array of string'); } }) }, loadCasernes: (context) => { console.log('on est dans toogleCasernes'); return new Promise((resolve, reject) => { let query = es.function_createQueryLoadCasernes(context.state.filters.currentDepartment) es.search('geo', query).then(function(values) { let result = { 'dataSubset': 'cas', 'elasticsearchResult': values }; context.commit('reloadData', result) //on reslve uniquement quand tout les commit sont effectues resolve() }) }) } } }) <file_sep>/src/store/bus_filters.js import Vue from 'vue' export const bus_filters = new Vue() <file_sep>/src/components/mixins/MixpanelonUserClick.js export default function (multianalytics) { return { onUserClick (input) { if (input === true) { multianalytics.trackEvent({action: 'User click'}) } else if (typeof input === 'string') { multianalytics.trackEvent({action: input}) } else { multianalytics.trackEvent({action: 'Fatal error in mixpanel reporting'}) } } } } <file_sep>/src/store/elasticsearch.js /*ignore jslint start*/ import elasticsearch from 'elasticsearch' import configuration from '../assets/configuration.json' export default { search, searchSimpleFilter, function_createQuery, function_createQueryLoadCasernes, function_createQueryPreForExport, function_createQueryGeoForExport, function_createQueryPreForExportLastUpdate } let protocol = window.location.protocol //previsecours.fr.local let host = window.location.host // http: let port = (protocol === 'https') ? '443': '80' let apiPath = (process.env.ES_PATH) ? process.env.ES_PATH : '/api/' let url = protocol + '//' + host + ':' + port + apiPath // testing purposes: we remove the :80 (was not working on viz.previsecours.fr ) let url2 = protocol + '//' + host + apiPath console.log( 'url for elasticsearch config', url2); const client = new elasticsearch.Client({ host: url2, apiVersion: '5.6' }) /** * ------------------------------------------------------------------------------------------------------------------------------ * Search functions * ------------------------------------------------------------------------------------------------------------------------------ */ /** * [Basic search function for elasticsearch] * @param {string} indexType [one of the value defined in configuration.indexes] * @param {Object} query [the elasticsearch query] * @return {Object} [the result from elasticsearch database] * * example: * es.search( 'geo', { "query": { "match" : { "type" : "Feature" } } })) * */ function search(indexType, query) { if(!configuration.indexes[indexType]) { console.log('indexes[indexType] problem in SEARCH: ',configuration.indexes[indexType]); return false } return client.search({ index: configuration.indexes[indexType], body: query }) } /** * [searchSimpleFilter description] * @param {string} indexType [idem] * @param {string} field [field you wanna query. can be sub.property like property.subproperty] * @param {string} ref [the value of the field you want to retrieve] * @return {Object} [the result from elasticsearch database] * * example: es.searchSimpleFilter( 'geo', 'properties.OBJECTID', 16 ) */ function searchSimpleFilter (indexType, field, ref) { const query = querySimpleFilter(field, ref) return search(indexType, query) } /** * ------------------------------------------------------------------------------------------------------------------------------ * query definitions used in search function * ------------------------------------------------------------------------------------------------------------------------------ */ function querySimpleFilter (field, ref, size = 1000) { return { size: size, query: { match: { [field] : ref } } } } /** * [function_createQuery will create the elasticsearch query for the mentioned dataSubset, according to the current state of the store] * @param {object} storeState [description, directly coming from the store, so reliable] * @param {string} dataSubset [string defined in the assets/configuration.json (already checked in the store action, so reliable)] * @return {object} [the query] */ function function_createQuery(storeState,dataSubset){ let query switch (dataSubset) { case 'int': query = function_createQueryInt(storeState) break; case 'pre': query = function_createQueryPre(storeState) break; case 'geo': query = function_createQueryGeo(storeState) break; default: query = function_createQueryInt(storeState) } return query; } function function_createQueryInt(storeState){ let currentDepartment = storeState.filters.currentDepartment let currentCategorInter = storeState.filters.currentCategorInter let currentTimeAggregation = storeState.filters.currentTimeAggregation let currentGeoAggregation = storeState.filters.currentGeoAggregation let type = 'function_createQueryInt - sdis'+currentDepartment.toString()+'_'+currentGeoAggregation+'_'+currentCategorInter+'_'+currentTimeAggregation console.log(type); return { "query": { "type":{ "value":type } // "match" : { "type" : } }, size: 1000 } } function function_createQueryGeo(storeState){ let currentDepartment = storeState.filters.currentDepartment let currentGeoAggregation = storeState.filters.currentGeoAggregation let type = 'function_createQueryGeo - sdis'+currentDepartment.toString()+'_'+currentGeoAggregation console.log(type); return { "query": { "match" : { "geotype": currentGeoAggregation } }, size: 1000 } } function function_createQueryPre(storeState){ let currentDepartment = storeState.filters.currentDepartment let currentCategorInter = storeState.filters.currentCategorInter let currentTimeAggregation = storeState.filters.currentTimeAggregation let currentGeoAggregation = storeState.filters.currentGeoAggregation let type = 'function_createQueryPre - sdis'+currentDepartment.toString()+'_'+currentGeoAggregation+'_'+currentCategorInter+'_'+currentTimeAggregation console.log(type); return { "query": { "match" : { "prediction_type" : type } }, size: 1000 } } function function_createQueryLoadCasernes(dpt){ return { "query": { "bool" : { "must" : [ { "match" : { "geotype" : "cas" } }, { "match":{ "properties.codeDepartement" : dpt } } ] } }, size: 1000 } } //function we are using for the export data button function function_createQueryPreForExport(dpt){ return { "query": { "regexp":{ "prediction_type" : "sdis"+dpt+".*" } }, size: 10000 } } //function we are using for the export data button function function_createQueryGeoForExport(dpt){ return { "query": { "regexp":{ "properties.codeDepartement" : dpt } }, size: 10000 } } //function we are using for the export data button to get the Last Update Date of data features function function_createQueryPreForExportLastUpdate(name) { return { "query": { "regexp": { "documentName": name } }, size: 10000 } } /*ignore jslint end*/ <file_sep>/README.md # vuejs_previsecours Ce projet permet d’explorer sur une carte les interventions SDIS passées, et les predictions d'interventions générées par la team Prévisecours. De nombreux filtres et représentations permettent d’explorer plusieurs situations. Il a pour vocation à être un outil opérationnel pour les pompiers du SDIS 91 afin de les aider à mieux comprendre et anticiper les interventions. # Contexte de développement Ce projet a initialement été développé par <NAME> et <NAME> dans le cadre du programme Entrepreneurs d’Intérêt Général 2018. Il est porté par le datalab du ministère de l’Intérieur Francais. ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 # port can be changed in webpack.config.js , devServer section npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report ``` ## Fill the ES database with some dataset ``` bash curl -s -H "Content-Type: application/x-ndjson" -XPOST localhost:9200/_bulk --data-binary "@PATHTOFOLDER/vueJS_Previsecours/src/assets/testSet_forElasticSearch.json"; ``` fake some data prediction so that is looks cool: ``` bash mlr --json --ojson put -S 'if(is_not_null($cla_001)){ $cla_003 = urandint(1,5); $cla_002 = urandint(1,5); $cla_001 = urandint(1,5); $cla_004 = urandint(1,5); $cla_005 = urandint(1,5); $geo_id = "&&&" . string($geo_id) }' dummyPredictions_forElasticSearch.json > dummyPredictions_forElasticSearch2.json ``` ne pas oublier de suppr les &&& !!! Pour la preparation du geojson departements avant insert en bulk: penser a remplacer les "CODE_DEPT" par "code" Pour la preparation du geojson zones de couverture avant insert en bulk: penser a remplacer les "OBJECTID" qui vient du systeme SDIS91 par "code" et "CS_COD" en "nom" ``` bash awk '{gsub("CS_COD", "nom", $0); print}' zoneDeCouvertureGeometry_forElasticSearch.json > zoneDeCouvertureGeometry_forElasticSearch_modified.json ``` penser aussi a ajouter "codeDepartement":"91" dans les geometries
646635b4e31313d8ad12c10c88ab4c4da0ec0fdb
[ "JavaScript", "Markdown" ]
5
JavaScript
previsecours/vueJS_Previsecours
24a5e6f6e2c43dd3a20c53e27bb2719ae5972828
b1c4910fa70e243b8c957357a0cba2d879b89c7b
refs/heads/master
<repo_name>CloudsDocker/misc<file_sep>/Kindle-Notes.md --- layout: page title: Kindle notes --- #《亿级流量网站架构核心技术》目录一览 - TCP四层负载均衡 - 使用Hystrix实现隔离 - 基于Servlet3实现请求隔离 - 限流算法 令牌桶算法 漏桶算法 - 分布式限流 redis+lua实现 Nginx+Lua实现 - 使用sharding-jdbc分库分表 - Disruptor+Redis队列 简介 XML配置 EventWorker - Worker无状态化+任务化 - 数据量大时JIMDB同步不动 - 使用OpenResty开发高性能Web应用 - 单机闭环 分布式闭环 # 深入理解Java虚拟机:JVM高级特性与最佳实践(第2版) - HotSpot VM的热点代码探测能力可以通过执行计数器找出最具有编译价值的代码,然后通知JIT编译器以方法为单位进行编译。 - 被频繁调用,或方法中有效循环次数很多,将会分别触发标准编译和OSR(栈上替换)编译动作。 - 在2006年的JavaOne大会上,Sun公司宣布最终会把Java开源, - 所有的对象实例以及数组都要在堆上分配[1], - 方法区(Method Area)与Java堆一样,是各个线程共享的内存区域,它用于存储已被虚拟机加载的类信息、常量、静态变量、即时编译器编译后 - 虽然Java虚拟机规范把方法区描述为堆的一个逻辑部分,但是它却有一个别名叫做Non-Heap(非堆),目的应该是与Java堆区分开来。 - 很多人都更愿意把方法区称为“永久代”(Permanent Generation),本质上两者并不等价,仅仅是因为HotSpot虚拟机的设计团队选择把GC分代收集扩展至方法区,或者说使用永久代来实现方法区而已, - 在目前已经发布的JDK 1.7的HotSpot中,已经把原本放在永久代的字符串常量池移出。 - 还可以选择不实现垃圾收集。相对而言,垃圾收集行为在这个区域是比较少出现的,但并非数据进入了方法区就如永久代的名字一样“永久”存在了。 - 根据Java虚拟机规范的规定,当方法区无法满足内存分配需求时,将抛出OutOfMemoryError异常。 - 运行时常量池(Runtime Constant Pool)是方法区的一部分。 - 常量池(Constant Pool Table),用于存放编译期生成的各种字面量和符号引用, - 运行期间也可能将新的常量放入池中,这种特性被开发人员利用得比较多的便是String类的intern()方法。 - 在JDK 1.4中新加入了NIO(New Input/Output)类,引入了一种基于通道(Channel)与缓冲区(Buffer)的I/O方式,它可以使用Native函数库直接分配堆外内存,然后通过一个存储在Java堆中的DirectByteBuffer对象作为这块内存的引用进行操作。这样能在一些场景中显著提高性能,因为避免了在Java堆和Native - 虚拟机遇到一条new指令时,首先将去检查这个指令的参数是否能在常量池中定位到一个类的符号引用,并且检查这个符号引用代表的类是否已被加载、解析和初始化过。如果没有,那必须先执行相应的类加载过程, - 那所分配内存就仅仅是把那个指针向空闲空间那边挪动一段与对象大小相等的距离,这种分配方式称为“指针碰撞”(Bump the Pointer)。如果Java堆中的内存并不是规整的,已使用的内存和空闲的内存相互交错,那就没有办法简单地进行指针碰撞了, - 那所分配内存就仅仅是把那个指针向空闲空间那边挪动一段与对象大小相等的距离,这种分配方式称为“指针碰撞”(Bump the Pointer)。如果Java堆中的内存并不是规整的,已使用的内存和空闲的内存相互交错,那就没有办法简单地进行指针碰撞了,虚拟机就必须维护一个列表,记录上哪些内存块是可用的,在分配的时候从列表中找到一块足够大的空间划分给对象实例,并更新列表上的记录,这种分配方式称为“空闲列表”(Free List)。选择哪种分配方式由Java堆是否规整决定,而Java堆是否规整又由所采用的垃圾收集器是否带有压缩整理功能决定。 - 那所分配内存就仅仅是把那个指针向空闲空间那边挪动一段与对象大小相等的距离,这种分配方式称为“指针碰撞”(Bump the Pointer)。如果Java堆中的内存并不是规整的,已使用的内存和空闲的内存相互交错,那就没有办法简单地进行指针碰撞了,虚拟机就必须维护一个列表,记录上哪些内存块是可用的,在分配的时候从列表中找到一块足够大的空间划分给对象实例,并更新列表上的记录,这种分配方式称为“空闲列表”(Free List)。选择哪种分配方式由Java堆是否规整决定,而Java堆是否规整又由所采用的垃圾收集器是否带有压缩整理功能决定。因此,在使用Serial、ParNew等带Compact过程的收集器时,系统采用的分配算法是指针碰撞,而使用CMS这种基于Mark-Sweep算法的收集器时,通常采用空闲列表。 - 解决这个问题有两种方案,一种是对分配内存空间的动作进行同步处理——实际上虚拟机采用CAS配上失败重试的方式保证更新操作的原子性;另一种是把内存分配的动作按照线程划分在不同的空间之中进行,即每个线程在Java堆中预先分配一小块内存,称为本地线程分配缓冲(Thread Local Allocation Buffer,TLAB)。 - 分配内存,就在哪个线程的TLAB上分配,只有TLAB用完并分配新的TLAB时,才需要同步锁定。虚拟机是否使用TLAB, - 虚拟机要对对象进行必要的设置,例如这个对象是哪个类的实例、如何才能找到类的元数据信息、对象的哈希码、对象的GC分代年龄等信息。这些信息存放在对象的对象头(Object Header)之中。 - 在HotSpot虚拟机中,对象在内存中存储的布局可以分为3块区域:对象头(Header)、实例数据(Instance Data)和对齐填充(Padding)。 - HotSpot虚拟机的对象头包括两部分信息,第一部分用于存储对象自身的运行时数据,如哈希码(HashCode)、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID、偏向时间戳等,这部分数据的长度在32位和64位的虚拟机(未开启压缩指针)中分别为32bit和64bit,官方称它为“Mark Word”。 - 一个指向对象的引用,并没有定义这个引用应该通过何种方式去定位、访问堆中的对象的具体位置,所以对象访问方式也是取决于虚拟机实现而定的。目前主流的访问方式有使用句柄和直接指针两种。 - 如果使用句柄访问的话,那么Java堆中将会划分出一块内存来作为句柄池,reference中存储的就是对象的句柄地址,而句柄中包含了对象实例数据与类型数据各自的具体地址信息,如图2-2所示。 图 2-2 通过句柄访问对象 如果使用直接指针访问,那么Java堆对象的布局中就必须考虑如何放置访问类型数据的相关信息,而reference中存 - 这两种对象访问方式各有优势,使用句柄来访问的最大好处就是reference中存储的是稳定的句柄地址,在对象被移动(垃圾收集时移动对象是非常普遍的行为)时只会改变句柄中的实例数据指针,而reference本身不需要修改。 - 使用直接指针访问方式的最大好处就是速度更快,它节省了一次指针定位的时间开销,由于对象的访问在Java中非常频繁,因此这类开销积少成多后也是一项非常可观的执行成本。就 - 主要虚拟机Sun HotSpot而言,它是使用第二种方式进行对象访问的,但从整个软件开发的范围来看,各种语言和框架使用句柄来访问的情况也十分常见。 - Java堆用于存储对象实例,只要不断地创建对象,并且保证GC Roots到对象之间有可达路径来避免垃圾回收机制清除这些对象,那么在对象数量到达最大堆的容量限制后就会产生内存溢出异常。 - 将堆的最小值-Xms参数与最大值-Xmx参数设置为一样即可避免堆自动扩展), - XX:+HeapDumpOnOutOfMemoryError可以让虚拟机在出现内 - public class HeapOOM{ static class OOMObject{ } public static void main(String[]args){ List<OOMObject>list=new ArrayList<OOMObject>(); while(true){ list.add(new OOMObject()); } } } - 要先分清楚到底是出现了内存泄漏(Memory Leak)还是内存溢出(Memory Overflow)。 - 由于在HotSpot虚拟机中并不区分虚拟机栈和本地方法栈, - 栈容量只由-Xss参数设定。 # Effective Java™ (Jason Arnold's Library) - Modules should be as small as possible but no smaller. - Code should be reused rather than copied. - The dependencies between modules should be kept to a minimum. - Errors should be detected as soon as possible after they are made, ideally at compile time. - like most other disciplines, consists of first learning the rules and then learning when to break them. - The language supports four kinds of types: interfaces (including annotations), classes (including enums), arrays, and primitives. The first three are known as reference types. Class instances and arrays are objects; primitive values are not. - the signature does not include the method's return type. - the descriptive term package-private instead of the technically correct term default access - One advantage of static factory methods is that, unlike constructors, they have names. - A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they're invoked. - This allows immutable classes (Item 15) to use preconstructed instances, or to cache instances as they're constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects. - the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton - 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b. If a class makes this guarantee, then its clients can use the == operator instead of the equals(Object) method, which may result in improved performance. Enum types (Item 30) provide this guarantee. - A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type. - One application of this flexibility is that an API can return objects without making their classes public. Hiding implementation classes in this fashion leads to a very compact API. This technique lends itself to interface-based frameworks (Item 18), where interfaces provide natural return types for static factory methods. - Nearly all of these implementations are exported via static factory methods in one noninstantiable class (java.util.Collections). The classes of the returned objects are all nonpublic. - Furthermore, using such a static factory method requires the client to refer to the returned object by its interface rather than its implementation class, which is generally good practice - java.util.EnumSet (Item 32), introduced in release 1.5, has no public constructors, only static factories. They return one of two implementations, depending on the size of the underlying enum type: if it has sixty-four or fewer elements, as most enum types do, the static factories return a RegularEnumSet instance, which is backed by a single long; if the enum type has sixty-five or more elements, the factories return a JumboEnumSet instance, backed by a long array. - Clients neither know nor care about the class of the object they get back from the factory; they care only that it is some subclass of EnumSet. - The class of the object returned by a static factory method need not even exist at the time the class containing the method is written. Such flexible static factory methods form the basis of service provider frameworks, such as the Java Database Connectivity API (JDBC). - There are three essential components of a service provider framework: a service interface, which providers implement; a provider registration API, which the system uses to register implementations, giving clients access to them; and a service access API, which clients use to obtain an instance of the service. - In the case of JDBC, Connection plays the part of the service interface, DriverManager.registerDriver is the provider registration API, DriverManager.getConnection is the service access API, and Driver is the service provider interface. - A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances. - compiler can figure out the type parameters for you. This is known as type inference. - replace the wordy declaration above with this succinct alternative: - The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed. - The same is true for nonpublic classes returned by public static factories. For example, it is impossible to subclass any of the convenience implementation classes in the Collections Framework. - as it encourages programmers to use composition instead of inheritance - A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods. - Here are some common names for static factory methods: valueOf—Returns an instance that has, loosely speaking, the same value as its parameters. - of—A concise alternative to valueOf, popularized by EnumSet - getInstance—Returns an instance that is described by the parameters but cannot be said to have the same value. - newInstance—Like getInstance, except that newInstance guarantees that each instance returned is distinct from all others. - getType—Like getInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method. newType—Like newInstance, but used when the factory method is in a different class. Type indicates the type of object returned by the factory method. - In summary, static factory methods and public constructors both have their uses, and it pays to understand their relative merits. Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories. - Consider a builder when faced with many constructor parameters - // Telescoping constructor pattern - does not scale well! - the telescoping constructor pattern works, but it is hard to write client code when there are many parameters, and harder still to read it. - Unfortunately, the JavaBeans pattern has serious disadvantages of its own. Because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction. - the JavaBeans pattern precludes the possibility of making a class immutable - A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Modules then communicate only through their APIs and are oblivious to each others' inner workings. This concept, known as information hiding or encapsulation, is one of the fundamental tenets of software design - Information hiding is important for many reasons, most of which stem from the fact that it decouples the modules that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation. - This speeds up system development because modules can be developed in parallel. - eases the burden of maintenance because modules can be understood more quickly and debugged with little fear of harming other modules. - Information hiding increases software reuse because modules that aren't tightly coupled often prove useful in other contexts besides the ones - Finally, information hiding decreases the risk in building large systems, because individual modules may prove successful even if the system does not. - The rule of thumb is simple: make each class or member as inaccessible as possible. - If a top-level class or interface can be made package-private, it should be. - If you make it public, you are obligated to support it forever to maintain compatibility. - If a package-private top-level class (or interface) is used by only one class, consider making the top-level class a private nested class of the sole class that uses it (Item 22). - Also, a protected member of an exported class represents a public commitment to an implementation detail - There is one rule that restricts your ability to reduce the accessibility of methods. If a method overrides a superclass method, it is not permitted to have a lower access level in the subclass than it does in the superclass [JLS, 8.4.8.3]. - A special case of this rule is that if a class implements an interface, all of the class methods that are also present in the interface must be declared public. This is so because all members of an interface are implicitly public - Instance fields should never be public - so classes with public mutable fields are not thread-safe. - Even if a field is final and refers to an immutable object, by making the field public you give up the flexibility to switch to a new internal data representation in which the field does not exist. - It is critical that these fields contain either primitive values or references to immutable objects - Note that a nonzero-length array is always mutable, so it is wrong for a class to have a public static final array field, or an accessor that returns such a field. If a class has such a field or accessor, clients will be able to modify the contents of the array. This is a frequent source of security holes: - There are two ways to fix the problem. You can make the public array private and add a public immutable list: private static final Thing[] PRIVATE_VALUES = { ... }; public static final List<Thing> VALUES =    Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES)); Alternatively, you can make the array private and add a public method that returns a copy of a private array: private static final Thing[] PRIVATE_VALUES = { ... }; public static final Thing[] values() { -     return PRIVATE_VALUES.clone(); } To choose between these alternatives, think about what the client is likely to do with the result. Which return type will be more convenient? - Item 14: In public classes, use accessor methods, not public fields - if a class is accessible outside its package, provide accessor methods, to preserve the flexibility to change the class's internal representation. - If a public class exposes its data fields, all hope of changing its representation is lost, as client code can be distributed far and wide. - However, if a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields—assuming they do an adequate job of describing the abstraction provided by the class. - clutter - If you use raw types, you lose all the safety and expressiveness benefits of generics. - dangerous. Since release 1.5, Java has provided a safe alternative known as unbounded wildcard types. - the unbounded wildcard type for the generic type Set<E> is Set<?> (read "set of some type"). It is the most general parameterized Set type, capable of holding any set. - Not to belabor the point, - both of which stem from the fact that generic type information is erased at runtime (Item 25). You must use raw types in class literals. - Because generic type information is erased at runtime, it is illegal to use the instanceof operator on parameterized types other than unbounded wildcard types. - Note that once you've determined that o is a Set, you must cast it to the wildcard type Set<?>, not the raw type Set. This is a checked cast, so it will not cause a compiler warning. - In summary, using raw types can lead to exceptions at runtime, so don't use them in new code. They are provided only for compatibility and interoperability with legacy code that predates the introduction of generics. - Eliminate every unchecked warning that you can. - If you eliminate all warnings, you are assured that your code is typesafe, which is a very good thing. It means that you won't get a ClassCastException at runtime, and it increases your confidence that your program is behaving as you intended. - If you can't eliminate a warning, and you can prove that the code that provoked the warning is typesafe, then (and only then) suppress the warning with an @SuppressWarnings("unchecked") annotation. - If you suppress warnings without first proving that the code is typesafe, you are only giving yourself a false sense of security. - The code may compile without emitting any warnings, but it can still throw a ClassCastException at runtime. If, however, you ignore unchecked warnings that you know to be safe (instead of suppressing them), you won't notice when a new warning crops up that represents a real problem. - Always use the SuppressWarnings annotation on the smallest scope possible. - Never use SuppressWarnings on an entire class. Doing so could mask critical warnings. - Every time you use an @SuppressWarnings("unchecked") annotation, add a comment saying why it's safe to do so. This will help others understand the code, and more importantly, it will decrease the odds that someone will modify the code so as to make the computation unsafe. - Every unchecked warning represents the potential for a ClassCastException at runtime. - Avoid long parameter lists. Aim for four parameters or fewer. Most programmers can't remember longer parameter lists. - Long sequences of identically typed parameters are especially harmful. - increasing orthogonality. - power-to-weight - For parameter types, favor interfaces over classes - If there is an appropriate interface to define a parameter, use it in favor of a class that implements the interface. - For example, there is no reason ever to write a method that takes HashMap on input—use Map instead. - By using a class instead of an interface, you restrict your client to a particular implementation and force an unnecessary and potentially expensive copy operation if the input data happens to exist in some other form. - Prefer two-element enum types to boolean parameters. It makes your code easier to read and to write, especially if you're using an IDE that supports autocompletion. - judiciously - in release 1.5, the Arrays class was given a full complement of Arrays.toString methods (not varargs methods!) designed specifically to translate arrays of any type into strings. If you use Arrays.toString in place of Arrays.asList, the program produces the intended result: // The right way to print an array System.out.println(Arrays.toString(myArray)); - Now you know that you'll pay the cost of the array creation only in the 5 percent of all invocations where the number of parameters exceeds three. - The EnumSet class uses this technique for its static factories to reduce the cost of creating enum sets to a bare minimum. - judiciously # Java Concurrency in Practice - Not coincidentally, - Nor is it an encyclopedic reference for All Things Concurrency—for - bathrobe, - manifest - When threads share data, they must use synchronization mechanisms that can inhibit compiler optimizations, flush or invalidate memory caches, and create synchronization traffic on the shared memory bus. - contagious. - it rarely ends there; instead, it ripples through the application. - GUI applications are inherently asynchronous. - Writing thread-safe code is, at its core, about managing access to state, and in particular to shared, mutable state. - Whether an object needs to be thread-safe depends on whether it will be accessed from multiple threads. - believe—but it is always a good practice first to make your code right, and then make it fast. - At the heart of any reasonable definition of thread safety is the concept of correctness. - a class is thread-safe when it continues to behave correctly when accessed from multiple threads. - stateless objects are thread-safe. - The fact that most servlets can be implemented with no state greatly reduces the burden of making servlets thread-safe. - these built-in locks are called intrinsic locks or monitor locks. The lock is - however, this approach is fairly extreme, since it inhibits multiple clients from using the factoring servlet simultaneously - subvert - This attempt at a put-if-absent operation has a race condition, - This simple, coarse-grained approach restored safety, but at a high price. - unduly - There is frequently a tension between simplicity and performance. - resist the temptation to prematurely sacriflce simplicity (potentially compromising safety) for the sake of performance. - Together, they lay the foundation for building thread-safe classes and safely structuring - Visibility is subtle because the things that can go wrong are so counterintuitive. - reordering. There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread—even if the reordering is apparent to other threads. - downright - processor, and runtime can do some downright weird things to the order in - When food is stale, it is usually still edible—just less enjoyable. - When a thread reads a variable without synchronization, it may see a stale value, - nonvolatile long and double variables, the JVM is permitted to treat a 64-bit read or write as two separate 32-bit operations. - it is not safe to use shared mutable long and double variables in multithreaded programs unless they are declared volatile or guarded by a lock. - about mutual exclusion; it is also about memory visibility. To ensure that all threads see the most up-to-date values of shared mutable variables, the reading and writing threads must synchronize on a common lock. - Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent - making volatile variables a lighter-weight synchronization mechanism than synchronized. - volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to the volatile variable become visible to B after reading the volatile variable. So from a memory visibility perspective, writing a volatile variable is like exiting a synchronized - However, we do not recommend relying too heavily on volatile variables for visibility; code that relies on volatile variables for visibility of arbitrary state is more fragile and harder to understand than code that uses locking. - Good uses of volatile variables include ensuring the visibility of their own state, that of the object they refer to, or indicating that an important lifecycle event (such as initialization or shutdown) has occurred. - anthropomorphized - The most common use for volatile variables is as a completion, interruption, or status flag, - Locking can guarantee both visibility and atomicity; - volatile variables can only guarantee visibility. - blatant - The most blatant form of publication is to - Publishing states in this way is problematic because any caller can modify its contents. In this case, the states array has escaped its intended scope, because what was supposed to be private state has been effectively made public. - This is a compelling reason to use encapsulation: - Do not allow the this reference to escape during construction. - When an object creates a thread from its constructor, it almost always shares its this reference with the new thread, either explicitly (by passing it to the constructor) or implicitly (because the Thread or Runnable is an inner class of the owning object). - There's nothing wrong with creating a thread in a constructor, but it is best not to start the thread immediately. - Instead, expose a start or initialize method that starts the owned thread. - Accessing shared, mutable data requires using synchronization; one way to avoid this requirement is to not share. - Swing uses thread confinement extensively. - Many concurrency errors in Swing applications stem from improper use of these confined objects from - Single-threaded subsystems can sometimes offer a simplicity benefit that outweighs the fragility of ad-hoc thread confinement. - are confining the modification to a single thread to prevent race conditions, and the visibility guarantees for volatile variables ensure that other threads see the most up-to-date value. - There is no way to obtain a reference to a primitive variable, so the language semantics ensure that primitive local variables are always stack confined. - In loadTheArk, we instantiate a TreeSet and store a reference to it in animals. At this point, there is exactly one reference to the Set, held in a local variable and therefore confined to the executing thread. However, if we were - maintaining thread confinement is ThreadLocal, which allows you to associate a per-thread value with a value-holding object. - When a thread calls ThreadLocal.get for the first time, initialValue is consulted to provide the initial value for that thread. Conceptually, you can think of a - The thread-specific values are stored in the Thread object itself; when the thread terminates, the thread-specific values can be garbage collected. - If you are porting a single-threaded application to a multithreaded environment, you can preserve thread safety by converting shared global variables into ThreadLocals, if the semantics of the shared globals permits this; - Immutable objects are always thread-safe. - subverted - An object whose fields are all final may still be mutable, since final fields can hold references to mutable objects. - An object is immutable if: Its state cannot be modifled after construction; All its flelds are final;[12] and It is properly constructed (the this reference does not escape during construction). - There is a difference between an object being immutable and the reference to it being immutable. - It is the use of final fields that makes possible the guarantee of initialization safety - Just as it is a good practice to make all fields private unless they need greater - it is a good practice to make all fields final unless they need to be mutable. - Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them. - final fields can be safely accessed without additional synchronization. However, if final fields refer to mutable objects, synchronization is still required to access the state of the objects they refer to. - Objects that are not immutable must be safely published, which usually entails synchronization by both the publishing and the consuming thread. - To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. - constitute - Using a static initializer is often the easiest and safest way to publish objects that - public static Holder holder = new Holder(42); Static initializers are executed by the JVM at class initialization time; because of internal synchronization in the JVM, this mechanism is - Objects that are not technically immutable, but whose state will not be modified after publication, are called effectively immutable. - The publication requirements for an object depend on its mutability: Immutable objects can be published through any mechanism; Effectively immutable objects must be safely published; Mutable objects must be safely published, and must be either threadsafe or guarded by a lock. - Operations with state-based preconditions are called state-dependent - Blocking library classes such as BlockingQueue, Semaphore, and other synchronizers are covered in Chapter 5; creating state-dependent classes using the low-level mechanisms provided by the platform and class library is covered in Chapter 14. - Ownership is not embodied explicitly in the language, - Ownership implies control, but once you publish a reference to a mutable object, you no longer have exclusive control; at best, you might have "shared ownership". - Collection classes often exhibit a form of "split ownership", in which the collection owns the state of the collection infrastructure, but client code owns the objects stored in the collection. - they should either be thread-safe, effectively immutable, or explicitly guarded by a lock. - You can ensure that it is only accessed from a single thread (thread confinement), or that all access to it is properly guarded by a lock. - Instance confinement is one of the easiest ways to build thread-safe classes. - The Java monitor pattern is used by many library classes, such as Vector and Hashtable. - The primary advantage of the Java monitor pattern is its simplicity. - Clients that improperly acquire another object's lock could cause liveness problems, and verifying that a publicly accessible lock is properly used requires examining the entire program rather than a single class. - Immutable values can be freely shared and published, so we no longer need to copy the locations when returning them. - Because the underlying state variables lower and upper are not independent, NumberRange cannot simply delegate thread safety to its thread-safe state variables. - a variable is suitable for being declared volatile only if it does not participate in invariants involving other state variables. - If we provided separate getters for x and y, then the values could change between the time one coordinate is retrieved and the other, resulting in a caller seeing an inconsistent value: an (x, y) location where the - PublishingVehicleTracker derives its thread safety from delegation to an underlying ConcurrentHashMap, but this time the contents of the Map are thread-safe mutable points rather than immutable ones. - To make this approach work, we have to use the same lock that the List uses by using client-side locking or external locking. -        public List<E> list =              Collections.synchronizedList(new ArrayList<E>());       ...       public boolean putIfAbsent(E x) {              synchronized (list)  {                     boolean absent = !list.contains(x); - (Like Collections.synchronizedList and other collections wrappers, ImprovedList assumes that once a list is passed to its constructor, the client will not use the underlying list directly again, accessing it only through the ImprovedList.) - ImprovedList adds an additional level of locking using its own intrinsic lock. It does not care whether the underlying List is thread-safe, because it provides its own consistent locking that provides thread safety even if the List is not - Each use of synchronized, volatile, or any thread-safe class reflects a synchronization policy defining a strategy for ensuring the integrity of data in the face of concurrent access. - delegation is one of the most effective strategies for creating thread-safe classes: just let existing thread-safe classes manage all the state. - Collections.synchronizedXxx factory methods. These classes achieve thread safety by encapsulating their state and synchronizing every public method so that only one thread at a time can access the collection state. - using iterators does not obviate the need to lock the collection during iteration if other threads can concurrently modify it. - The iterators returned by the synchronized collections are not designed to deal with concurrent modification, and they are fail-fast—meaning that if they detect that the collection has changed since iteration began, they throw the unchecked ConcurrentModificationException. - These fail-fast iterators are not designed to be foolproof—they are designed to catch concurrency errors on a "good-faith-effort" basis and thus act only as early-warning indicators for concurrency problems. They are implemented by associating a modification count with the collection: if the modification count changes during iteration, hasNext or next throws ConcurrentModificationException. However, this check is done without synchronization, so there is a risk of seeing a stale - An alternative to locking the collection during iteration is to clone the collection and iterate the copy instead. - Since the clone is thread-confined, no other thread can modify it during iteration, eliminating the possibility of ConcurrentModificationException. - Similarly, the containsAll, removeAll, and retainAll methods, as well as the constructors that take collections as arguments, also iterate the collection. All of these indirect uses of iteration can cause ConcurrentModificationException. - CopyOnWriteArrayList, a replacement for synchronized List implementations for cases where traversal is the dominant operation. - Queue operations do not block; if the queue is empty, the retrieval operation returns null. While you can simulate the behavior of a Queue with a List—in fact, LinkedList also implements Queue—the Queue classes were added because eliminating the random-access requirements of List admits more efficient concurrent implementations. - Java 6 adds ConcurrentSkipListMap and ConcurrentSkipListSet, which are concurrent replacements for a synchronized SortedMap or SortedSet (such as TreeMap or TreeSet wrapped with synchronizedMap). - if hashCode does not spread out hash values well, elements may be unevenly distributed among buckets; - it uses a finer-grained locking mechanism called lock striping (see Section 11.4.3) to allow a greater degree of shared access. - with little performance penalty for single-threaded access. - ConcurrentHashMap, along with the other concurrent collections, further improve on the synchronized collection classes by providing iterators that do not throw ConcurrentModificationException, thus eliminating the need to lock the collection during iteration. - The iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast. - A weakly consistent iterator can tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not guaranteed to) reflect modifications to the collection after the construction of the iterator. - As with all improvements, there are still a few tradeoffs. The semantics of methods that operate on the entire Map, such as size and isEmpty, have been slightly weakened to reflect the concurrent nature of the collection. Since the result of size could be out of date by the time it is computed, it is really only an estimate, so size is allowed to return an approximation instead of an exact count. - While at first this may seem disturbing, in reality methods like size and isEmpty are far less useful in concurrent environments because these quantities are moving targets. - So the requirements for these operations were weakened to enable performance optimizations for the most important operations, primarily get, put, containsKey, and remove. - The one feature offered by the synchronized Map implementations but not by ConcurrentHashMap is the ability to lock the map for exclusive access. - this is a reasonable tradeoff: concurrent collections should be expected to change their contents continuously. - ConcurrentHashMap not an appropriate drop-in replacement. - Since a ConcurrentHashMap cannot be locked for exclusive access, we cannot use client-side locking to create new atomic operations such as put-if-absent, - common compound operations such as put-if-absent, remove-if-equal, and replace-if-equal are implemented as atomic operations and specified by the ConcurrentMap interface, - CopyOnWriteArraySet is a concurrent replacement for a synchronized Set.) - They implement mutability by creating and republishing a new copy of the collection every time it is modified. - Iterators for the copy-on-write collections retain a reference to the backing array that was current at the start of iteration, and since this will never change, they need to synchronize only briefly to ensure visibility of the array contents. - iterators returned by the copy-on-write collections do not throw ConcurrentModificationException and return the elements exactly as they were at the time the iterator was created, regardless of subsequent modifications. - the copy-on-write collections are reasonable to use only when iteration is far more common than modification. - Queues can be bounded or unbounded; unbounded queues are never full, so a put on an unbounded queue never blocks. - The producerconsumer pattern simplifies development because it removes code dependencies between producer and consumer classes, and simplifies workload management by decoupling activities that may produce or consume data at different or variable rates. - Producers don't need to know anything about the identity or number of consumers, or even whether they are the only producer—all they have to do is place data items on the queue. - one person washes the dishes and places them in the dish rack, and the other person retrieves the dishes from the rack and dries them. In this scenario, the dish rack acts as a blocking queue; if there are no dishes in the rack, the consumer waits until there are dishes to dry, and if the rack fills up, the producer has to stop washing until there is more space. - Blocking queues also provide an offer method, which returns a failure status if the item cannot be enqueued. This enables you to create more flexible policies for dealing with overload, such as shedding load, serializing excess work items and writing them to disk, reducing the number of producer threads, or throttling producers in some other manner. - Bounded queues are a powerful resource management tool for building reliable applications: they make your program more robust to overload by throttling activities that threaten to produce more work than can be handled. - LinkedBlockingQueue and ArrayBlockingQueue are FIFO queues, analogous to LinkedList and ArrayList but with better concurrent performance than a synchronized List. - PriorityBlockingQueue is a priority-ordered queue, which is useful when you want to process elements in an order other than FIFO. Just like other sorted collections, PriorityBlockingQueue can compare elements according to their natural order (if they implement Comparable) or using a Comparator. - The last BlockingQueue implementation, SynchronousQueue, is not really a queue at all, in that it maintains no storage space for queued elements. Instead, it maintains a list of queued threads waiting to enqueue or dequeue an element. - While this may seem a strange way to implement a queue, it reduces the latency associated with moving data from producer to consumer because the work can be handed off directly. (In a traditional queue, the enqueue and dequeue operations must complete sequentially before a unit of work can be handed off.) The direct handoff also feeds back more information about the state of the task to the producer; when the handoff is accepted, it knows a consumer has taken responsibility for it, rather than simply letting it sit on a queue somewhere—much like the difference between handing a document to a colleague and merely putting it in her mailbox and hoping she gets it soon. - Since a SynchronousQueue has no storage capacity, put and take will block unless another thread is already waiting to participate in the handoff. - Synchronous queues are generally suitable only when there are enough consumers that there nearly always will be one ready to take the handoff. - Executor task execution framework, which itself uses the producer-consumer pattern. - For mutable objects, producer-consumer designs and blocking queues facilitate serial thread confinement for handing off ownership of objects from producers to consumers. - thread-confined object is owned exclusively by a single thread, but that ownership can be "transferred" by publishing it safely where only one other thread will gain access to it and ensuring that the publishing thread does not access it after the handoff. - Object pools exploit serial thread confinement, "lending" an object to a requesting thread. As long as the pool contains sufficient internal synchronization to publish the pooled object safely, and as long as the clients do not themselves publish the pooled object or use it after returning it to the pool, ownership can be transferred safely from thread to thread. - it could also done with the atomic remove method of ConcurrentMap or the compareAndSet method of AtomicReference. - Deque (pronounced "deck") and BlockingDeque, that extend Queue and BlockingQueue. - deques lend themselves to a related pattern called work stealing. - A producerconsumer design has one shared work queue for all consumers; in a work stealing design, every consumer has its own deque. If a consumer exhausts the work in its own deque, it can steal work from the tail of someone else's deque. - Work stealing can be more scalable than a traditional producer-consumer design because workers don't contend for a shared work queue; most of the time they access only their own deque, reducing contention. - When a worker has to access another's queue, it does so from the tail rather than the head, further reducing contention. - Work stealing is well suited to problems in which consumers are also producers—when performing a unit of work is likely to result in the identification of more work. For example, processing a page in a web crawler usually results in the identification of new pages to be crawled. - when its deque is empty, it looks for work at the end of someone else's deque, ensuring that each worker stays busy. - When a method can throw InterruptedException, it is telling you that it is a blocking method, and further that if it is interrupted, it will make an effort to stop blocking early. - Interruption is a cooperative mechanism. One thread cannot force another to stop what it is doing and do something else; when thread A interrupts thread B, A is merely requesting that B stop what it is doing when it gets to a convenient stopping point—if it feels like it. - When your code calls a method that throws InterruptedException, then your method is a blocking method too, and must have a plan for responding to interruption. - Blocking queues are unique among the collections classes: not only do they act as containers for objects, but they can also coordinate the control flow of producer and consumer threads because take and put block until the queue enters the desired state (not empty or not full). - A synchronizer is any object that coordinates the control flow of threads based on its state. Blocking queues can act as synchronizers; other types of synchronizers include semaphores, barriers, and latches. - All synchronizers share certain structural properties: they encapsulate state that determines whether threads arriving at the synchronizer should be allowed to pass or forced to wait, provide methods to manipulate that state, and provide methods to wait efficiently for the synchronizer to enter the desired state. - Latches can be used to ensure that certain activities do not proceed until other one-time activities complete, such as: - Ensuring that a computation does not proceed until resources it needs have been initialized. - A simple binary (two-state) latch could be used to indicate "Resource R has been initialized", and any activity that requires R would wait first on this latch. - Waiting until all the parties involved in an activity, for instance the players in a multi-player game, are ready to proceed. In this case, the latch reaches the terminal state after all the players are ready. - Using a starting gate allows the master thread to release all the worker threads at once, and the ending gate allows the master thread to wait for the last thread to finish rather than waiting sequentially for each thread to finish. - FutureTask also acts like a latch. (FutureTask implements Future, which describes an abstract result-bearing computation - a FutureTask is implemented with a Callable, the result-bearing equivalent of Runnable, and can be in one of three states: waiting to run, running, or completed. - subsumes - Once a FutureTask enters the completed state, it stays in that state forever. - FutureTask conveys the result from the thread executing the computation to the thread(s) retrieving the result; the specification of FutureTask guarantees that this transfer constitutes a safe publication of the result. -             startGate.await();                                          try {                                                 task.run();                                          } finally {                                                 endGate.countDown(); -                      t.start();              }              long start = System.nanoTime();              startGate.countDown();              endGate.await();              long end = System.nanoTime();              return end-start; - FutureTask is used by the Executor framework to represent asynchronous tasks, and can also be used to represent any potentially lengthy computation that can be started before the results are needed. - Counting semaphores are used to control the number of activities that can access a certain resource or perform a given action at the same time - semaphores can be used to implement resource pools or to impose a bound on a collection. - (An easier way to construct a blocking object pool would be to use a BlockingQueue to hold the pooled resources.) - Similarly, you can use a Semaphore to turn any collection into a blocking bounded collection, as illustrated by BoundedHashSet in Listing 5.14. - The key difference is that with a barrier, all the threads must come together at a barrier point at the same time in order to proceed. Latches are for waiting for events; barriers are for waiting for other threads. - rendezvous - CyclicBarrier allows a fixed number of parties to rendezvous repeatedly at a barrier point and is useful in parallel iterative algorithms that break down a problem into a fixed number of independent subproblems. - Threads call await when they reach the barrier point, and await blocks until all the threads have reached the barrier point. If all threads meet at the barrier point, the barrier has been successfully passed, in which case all threads are released and the barrier is reset so it can be used again. - If a call to await times out or a thread blocked in await is interrupted, then the barrier is considered broken and all outstanding calls to await terminate with BrokenBarrierException. - If the barrier is successfully passed, await returns a unique arrival index for each thread, which can be used to "elect" a leader that takes some special action in the next iteration. - Using Semaphore to Bound a Collection. - Barriers are often used in simulations, where the work to calculate one step can be done in parallel but all the work associated with a given step must complete before advancing to the next step. - Another form of barrier is Exchanger, a two-party barrier in which the parties exchange data at the barrier point [CPJ 3.4.3]. Exchangers are useful when the parties perform asymmetric activities, for example when one thread fills a buffer with data and the other thread consumes the data from the buffer; these threads could use an Exchanger to meet and exchange a full buffer for an empty one. When two threads exchange objects via an Exchanger, the exchange constitutes a safe publication of both objects to the other party. - Nearly every server application uses some form of caching. Reusing the results of a previous computation can reduce latency and increase throughput, at the cost of some additional memory usage. -               int count = Runtime.getRuntime().availableProcessors(); -               this.mainBoard = board;              int count = Runtime.getRuntime().availableProcessors();              this.barrier = new CyclicBarrier(count,                            new Runnable() {                                   public void run() {                                          mainBoard.commitNewValues(); - A naive cache implementation is likely to turn a performance bottleneck into a scalability bottleneck, even if it does improve single-threaded performance. - We've already seen a class that does almost exactly this: FutureTask. FutureTask represents a computational process that may or may not already have completed. FutureTask.get returns the result of the computation immediately if it is available; otherwise it blocks until the result has been computed and then returns it. - This window is far smaller than in Memoizer2, but because the if block in compute is still a nonatomic check-thenact sequence, it is possible for two threads to call compute with the same value at roughly the same time, both see that the cache does not contain the desired value, and both start the computation. - Figure 5.4. Unlucky Timing that could Cause Memoizer3 to Calculate the Same Value Twice. - Memoizer3 is vulnerable to this problem because a compound action (put-if-absent) is performed on the backing map that cannot be made atomic using locking. - Memoizer in Listing 5.19 takes advantage of the atomic putIfAbsent method of ConcurrentMap, closing the window of vulnerability in Memoizer3. - Caching a Future instead of a value creates the possibility of cache pollution: if a computation is cancelled or fails, future attempts to compute the result will also indicate cancellation or failure. To avoid this, Memoizer removes the Future from the cache if it detects that the computation was cancelled; it might also be desirable to remove the Future upon detecting a RuntimeException if the computation might succeed on a future attempt. - Memoizer also does not address cache expiration, but this could be accomplished by using a subclass of FutureTask that associates an expiration time with each result and periodically scanning the cache for expired entries. - It's the mutable state, stupid.[1]All concurrency issues boil down to coordinating access to mutable state. The less mutable state, the easier it is to ensure thread safety. - Make fields final unless they need to be mutable. - Immutable objects are automatically thread-safe.Immutable objects simplify concurrent programming tremendously. They are simpler and safer, and can be shared freely without locking or defensive copying. - Encapsulating data within objects makes it easier to preserve their invariants; encapsulating synchronization within objects makes it easier to comply with their synchronization policy. - Guard each mutable variable with a lock. - Guard all variables in an invariant with the same lock. - Hold locks for the duration of compound actions. - A program that accesses a mutable variable from multiple threads without synchronization is a broken program. Don't rely on clever - Include thread safety in the design process—or explicitly document that your class is not thread-safe. - Document your synchronization policy. - Ideally, tasks are independent activities: work that doesn't depend on the state, result, or side effects of other tasks. - Independence facilitates concurrency, as independent tasks can be executed in parallel if there are adequate processing resources. - Server applications should exhibit both good throughput and good responsiveness under normal load. - Further, applications should exhibit graceful degradation as they become overloaded, rather than simply falling over under heavy load. - Choosing good task boundaries, coupled with a sensible task execution policy (see Section 6.2.2), can help achieve these goals. - Thread lifecycle overhead. Thread creation and teardown are not free. - Resource consumption. Active threads consume system resources, especially memory. - of memory, putting pressure on the garbage collector, and having many threads competing for the CPUs can impose other performance costs as well. - the sequential approach suffers from poor responsiveness and throughput, and the thread-per-task approach suffers from poor resource management. - The primary abstraction for task execution in the Java class libraries is not Thread, but Executor, - Executor is based on the producer-consumer pattern, where activities that submit tasks are the producers (producing units of work to be done) and the threads that execute tasks are the consumers (consuming those units of work). - Using an Executor is usually the easiest path to implementing a producer-consumer design in your application. - strewn - task submission code tends to be strewn throughout the program and harder to expose. -      private static final Executor exec           = Executors.newFixedThreadPool(NTHREADS); - The value of decoupling submission from execution is that it lets you easily specify, and subsequently change without great difficulty, the execution policy for a given class of tasks. An execution policy specifies the "what, where, when, and how" of task execution, including: - Separating the specification of execution policy from task submission makes it practical to select an execution policy at deployment time that is matched to the available hardware. - Whenever you see code of the form: new Thread(runnable).start() and you think you might at some point want a more flexible execution policy, seriously consider replacing it with the use of an Executor. - A thread pool, as its name suggests, manages a homogeneous pool of worker threads. - newCachedThreadPool. A cached thread pool has more flexibility to reap idle threads when the current size of the pool exceeds the demand for processing, and to add new threads when demand increases, but places no bounds on the size of the pool. - newSingleThreadExecutor. A single-threaded executor creates a single worker thread to process tasks, replacing it if it dies unexpectedly. Tasks are guaranteed to be processed sequentially according to the order imposed by the task queue (FIFO, LIFO, priority order). - newScheduledThreadPool. A fixed-size thread pool that supports delayed and periodic task execution, similar to Timer. - Switching from a thread-per-task policy to a pool-based policy has a big effect on application stability: the web server will no longer fail under heavy load.[5] It also degrades more gracefully, since it does not create thousands of threads that compete for limited CPU and memory resources. - And using an Executor opens the door to all sorts of additional opportunities for tuning, management, monitoring, logging, error reporting, and other possibilities that would have been far more difficult to add without a task execution framework. - shut down an Executor could prevent the JVM from exiting. - The lifecycle implied by ExecutorService has three states—running, shutting down, and terminated. - The Timer facility manages the execution of deferred ("run this task in 100 ms") and periodic ("run this task every 10 ms") tasks. - However, Timer has some drawbacks, and ScheduledThreadPoolExecutor should be thought of as its replacement.[6] You can construct a ScheduledThreadPoolExecutor through its constructor or through the newScheduledThreadPool factory. - Another problem with Timer is that it behaves poorly if a TimerTask throws an unchecked exception. The Timer thread doesn't catch the exception, so an unchecked exception thrown from a TimerTask terminates the timer thread. - In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled. (This problem, called "thread leakage" is described in Section 7.3, along with techniques for avoiding it.) - ScheduledThreadPoolExecutor deals properly with ill-behaved tasks; there is little reason to use Timer in Java 5.0 or later. - own scheduling service, you may still be able to take advantage of the library by using a DelayQueue, a BlockingQueue implementation that provides the scheduling functionality of ScheduledThreadPoolExecutor. A DelayQueue manages a collection of Delayed objects. A Delayed has a delay time associated with it: DelayQueue lets you take an element only if its delay has expired. -              timer.schedule(new ThrowTask(), 1);            SECONDS.sleep(1);           timer.schedule(new ThrowTask(), 1);           SECONDS.sleep(5);    }     static class ThrowTask extends TimerTask {          public void run() { throw new RuntimeException(); }    } - Tasks are usually finite: they have a clear starting point and they eventually terminate. The lifecycle of a task executed by an Executor has four phases: created, submitted, started, and completed. - It returns immediately or throws an Exception if the task has already completed, but if not it blocks until the task completes. If the task completes by throwing an exception, get rethrows it wrapped in an ExecutionException; if it was cancelled, get throws CancellationException. - a Future, so that you can submit a Runnable or a Callable to an executor and get back a Future that can be used to retrieve the result or cancel the task. You can also explicitly instantiate a FutureTask for a given Runnable or Callable. (Because FutureTask implements Runnable, it can be submitted to an Executor for execution or executed directly by calling its run method.) - (Because one task is largely CPU-bound and the other is largely I/O-bound, this approach may yield improvements even on single-CPU systems.) - Heterogeneous - finer-grained parallelism among similar tasks, this approach will yield diminishing returns. - ExecutorCompletionService is quite straightforward. The constructor creates a BlockingQueue to hold the completed results. Future-Task has a done method that is called when the computation completes. When a task is submitted, it is wrapped with a QueueingFuture, a subclass of FutureTask that overrides done to place the result on the BlockingQueue, as shown in Listing 6.14. The take and poll methods delegate to the BlockingQueue, blocking if results are not yet available. - private class QueueingFuture<V> extends FutureTask<V> {      QueueingFuture(Callable<V> c) { super(c); }      QueueingFuture(Runnable t, V r) { super(t, r); }      protected void done() {            completionQueue.add(this);    }} -             CompletionService<ImageData> completionService =                new ExecutorCompletionService<ImageData>(executor);           for (final ImageInfo imageInfo : info)                completionService.submit(new Callable<ImageData>() {                   public ImageData call() {                         return imageInfo.downloadImage();                 }            }); -       long endNanos = System.nanoTime() + TIME_BUDGET; -          // Only wait for the remaining time budget          long timeLeft = endNanos - System.nanoTime();          ad = f.get(timeLeft, NANOSECONDS); -     }   catch (TimeoutException e) {          ad = DEFAULT_AD;          f.cancel(true);    }      page.setAd(ad);      return page;} - The invokeAll method takes a collection of tasks and returns a collection of Futures. The two collections have identical structures; invokeAll adds the Futures to the returned collection in the order imposed by the task collection's iterator, thus allowing the caller to associate a Future with the Callable it represents. - The Executor framework permits you to decouple task submission from execution policy and supports a rich variety of execution policies; whenever you find yourself creating threads to perform tasks, consider using an Executor instead. - preemptively - There are only cooperative mechanisms, by which the task and the code requesting cancellation follow an agreed-upon protocol. - A task that wants to be cancellable must have a cancellation policy that specifies the "how", "when", and "what" of cancellation—how other code can request cancellation, when the task checks whether cancellation has been requested, and what actions the task takes in response to a cancellation request. - Using a Volatile Field to Hold Cancellation State. -      public void cancel() { cancelled = true;  }     public synchronized List<BigInteger> get() {         return new ArrayList<BigInteger>(primes);     } -     try {        SECONDS.sleep(1);    } finally { - certain blocking library methods support interruption. Thread interruption is a cooperative mechanism for a thread to signal another thread that it should, at its convenience and if it feels like it, stop what it is doing and do something else. - There is nothing in the API or language specification that ties interruption to any specific cancellation semantics, but in practice, using interruption for anything but cancellation is fragile and difficult to sustain in larger applications. - Each thread has a boolean interrupted status; interrupting a thread sets its interrupted status to true. - The JVM makes no guarantees on how quickly a blocking method will detect interruption, but in practice this happens reasonably quickly. - Calling interrupt does not necessarily stop the target thread from doing what it is doing; it merely delivers the message that interruption has been requested. - Interruption is usually the most sensible way to implement cancellation. - A thread should be interrupted only by its owner; the owner can encapsulate knowledge of the thread's interruption policy in an appropriate cancellation mechanism such as a shutdown method. - Because each thread has its own interruption policy, you should not interrupt a thread unless you know what interruption means to that thread. - Critics have derided the Java interruption facility because it does not provide a preemptive interruption capability and yet forces developers to handle InterruptedException. - What you should not do is swallow the InterruptedException by catching it and doing nothing in the catch block, unless your code is actually implementing the interruption policy for a thread. - Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests. -               try {                  return queue.take();              } catch (InterruptedException e) {                  interrupted = true;                  // fall through and retry              }          }      } finally {          if (interrupted)              Thread.currentThread().interrupt();      }} For example, when a worker thread owned by a ThreadPoolExecutor detects interruption, it checks whether the pool is being shut down. If so, it performs some pool cleanup before terminating; otherwise it may create a new thread to restore the thread pool to the desired size. - This is an appealingly simple approach, but it violates the rules: you should know a thread's interruption policy before interrupting it. - Undesirable memory retention can be easily tested with heap-inspection tools that measure application memory usage; - AtomicInteger();  private final ThreadFactory factory      = Executors.defaultThreadFactory();  public Thread newThread(Runnable r) {    numCreated.incrementAndGet();    return factory.newThread(r); - Listing 12.9. Test Method to Verify Thread Pool Expansion. public void testPoolExpansion() throws InterruptedException {  int MAX_SIZE = 10;  ExecutorService exec = Executors.newFixedThreadPool(MAX_SIZE);  for (int i = 0; i < 10* MAX_SIZE; i++)    exec.execute(new Runnable() {      public void run() {        try {          Thread.sleep(Long.MAX_VALUE); - 12.1.6. Generating More Interleavings Since many of the potential failures in concurrent code are low-probability events, testing for concurrency errors is a numbers game, but there are some things you can do to improve your chances. - We've already mentioned how running on multiprocessor systems with fewer processors than active threads can generate more interleavings than either a single-processor system or one with many processors. - A useful trick for increasing the number of interleavings, and therefore more effectively exploring the state space of your programs, is to use Thread.yield to encourage more context switches during operations that access shared state. - (The effectiveness of this technique is platform-specific, since the JVM is free to treat Thread.yield as a no-op - Listing 12.10. Using Thread.yield to Generate More Interleavings. public synchronized void transferCredits(Account from,                     Account to,                     int amount) {  from.setBalance(from.getBalance() - amount);  if (random.nextInt(1000) > THRESHOLD)    Thread.yield();  to.setBalance(to.getBalance() + amount);} - Performance tests are often extended versions of functionality tests. - This test suggests that LinkedBlockingQueue scales better than ArrayBlockingQueue. This may seem odd at first: a linked queue must allocate a link node object for each insertion, and hence seems to be doing more work than the array-based queue. However, even though it has more allocation and GC overhead, a linked queue allows more concurrent access by puts and takes than an array-based queue because the best linked queue algorithms allow the head and tail to be updated independently. - Because allocation is usually threadlocal, algorithms that can reduce contention by doing more allocation usually scale better. - So, unless threads are continually blocking anyway because of tight synchronization requirements, nonfair semaphores provide much better throughput and fair semaphores provides lower variance. Because the results are so dramatically different, Semaphore forces its clients to decide which of the two factors to optimize for. - On HotSpot, running your program with -XX:+PrintCompilation prints out a message when dynamic compilation runs, so you can verify that this is prior to, rather than during, measured test runs. - On the other hand, if the tasks are very short-lived, there will be a lot of contention for the work queue and throughput is dominated by the cost of synchronization. - Different QA methodologies are more effective at finding some types of defects and less effective at finding others. By employing complementary testing methodologies such as code review and static analysis, you can achieve greater confidence than you could with any single approach. - A synchronized block that calls notify or notifyAll but does not modify any state is likely to be an error. - Condition wait errors. When waiting on a condition queue, Object.wait or Condition. await should be called in a loop, with the appropriate lock held, after testing some state predicate (see Chapter 14). Calling Object.wait or Condition.await without the lock held, not in a loop, or without testing some state predicate is almost certainly an error. - Misuse of Lock and Condition. Using a Lock as the lock argument for a synchronized block is likely to be a typo, as is calling Condition.wait instead of await (though the latter would likely be caught in testing, since it would throw an IllegalMonitorStateException the first time it was called). - Sleeping or waiting while holding a lock. Calling Thread.sleep with a lock held can prevent other threads from making progress for a long time and is therefore a potentially serious liveness hazard. - Spin loops. Code that does nothing but spin (busy wait) checking a field for an expected value can waste CPU time and, if the field is not volatile, is not guaranteed to terminate. Latches or condition waits are often a better technique when waiting for a state transition to occur. - Before Java 5.0, the only mechanisms for coordinating access to shared data were synchronized and volatile. Java 5.0 adds another option: ReentrantLock. - Contrary to what some have written, ReentrantLock is not a replacement for intrinsic locking, but rather an alternative with advanced features for when intrinsic locking proves too limited. - Unlike intrinsic locking, Lock offers a choice of unconditional, polled, timed, and interruptible lock acquisition, and all lock and unlock operations are explicit. - ReentrantLock implements Lock, providing the same mutual exclusion and memory-visibility guarantees as synchronized. - Acquiring a ReentrantLock has the same memory semantics as entering a synchronized block, and releasing a ReentrantLock has the same memory semantics as exiting a synchronized block. - Intrinsic locking works fine in most situations but has some functional limitations—it is not possible to interrupt a thread waiting to acquire a lock, or to attempt to acquire a lock without being willing to wait for it forever. - Intrinsic locks also must be released in the same block of code in which they are acquired; this simplifies coding and interacts nicely with exception handling, but makes non-blockstructured locking disciplines impossible. None of these are reasons to abandon synchronized, but in some cases a more flexible locking mechanism offers better liveness or performance. - (You should always consider the effect of exceptions when using any form of locking, including intrinsic locking.) - Failing to use finally to release a Lock is a ticking time bomb. - This is one reason not to use ReentrantLock as a blanket substitute for synchronized: it is more "dangerous" because it doesn't automatically clean up the lock when control leaves the guarded block. - With intrinsic locks, a deadlock is fatal—the only way to recover is to restart the application, and the only defense is to construct your program so that inconsistent lock ordering is impossible. - Timed and polled locking offer another option: probabalistic deadlock avoidance. - soliciting - we saw how reducing lock granularity can enhance scalability. - The lock for a given node guards the link pointers and the data stored in that node, so when traversing or modifying the list we must hold the lock on one node until we acquire the lock on the next node; only then can we release the lock on the first node. An example of this technique, called hand-over-hand locking or lock coupling, appears in [CPJ 2.5.1.4]. - Java 6 uses an improved algorithm for managing intrinsic locks, similar to that used by ReentrantLock, that closes the scalability gap considerably. - Performance is a moving target; yesterday's benchmark showing that X is faster than Y may already be out of date today. - The ReentrantLock constructor offers a choice of two fairness options: create a nonfair lock (the default) or a fair lock. - (Semaphore also offers the choice of fair or nonfair acquisition ordering.) - Nonfair ReentrantLocks do not go out of their way to promote barging—they simply don't prevent a thread from barging if it shows up at the right time. - In most cases, the performance benefits of nonfair locks outweigh the benefits of fair queueing. - Don't pay for fairness if you don't need it. - One reason barging locks perform so much better than fair locks under heavy contention is that there can be a significant delay between when a suspended thread is resumed and when it actually runs. - Let's say thread A holds a lock and thread B asks for that lock. Since the lock is busy, B is suspended. When A releases the lock, B is resumed so it can try again. In the meantime, though, if thread C requests the lock, there is a good chance that C can acquire the lock, use it, and release it before B even finishes waking up. In this case, everyone wins: B gets the lock no later than it otherwise would have, C gets it much earlier, and throughput is improved. - Fair locks tend to work best when they are held for a relatively long time or when the mean time between lock requests is relatively long. In these cases, the condition under which barging provides a throughput advantage—when the lock is unheld but a thread is currently waking up to claim it—is less likely to hold. - deterministic - The language specification does not require the JVM to implement intrinsic locks fairly, and no production JVMs do. - ReentrantLock provides the same locking and memory semantics as intrinsic locking, as well as additional features such as timed lock waits, interruptible lock waits, fairness, and the ability to implement non-block-structured locking. - Reentrant-Lock is definitely a more dangerous tool than synchronization; if you forget to wrap the unlock call in a finally block, your code will probably appear to run properly, but you've created a time bomb that may well hurt innocent bystanders. - ReentrantLock is an advanced tool for situations where intrinsic locking is not practical. Use it if you need its advanced features: timed, polled, or interruptible lock acquisition, fair queueing, or non-block-structured locking. Otherwise, prefer synchronized. - Java 6 by providing a management and monitoring interface with which locks can register, enabling locking information for - The non-block-structured nature of ReentrantLock still means that lock acquisitions cannot be tied to specific stack frames, as they can with intrinsic locks. - Because synchronized is built into the JVM, it can perform optimizations such as lock elision for thread-confined lock objects and lock coarsening to eliminate synchronization with intrinsic locks (see Section 11.3.2); doing this with library-based locks seems far less likely. - Unless you are deploying on Java 5.0 for the foreseeable future and you have a demonstrated need for ReentrantLock's scalability benefits on that platform, it is not a good idea to choose ReentrantLock over synchronized for performance reasons. - Mutual exclusion is a conservative locking strategy that prevents writer/writer and writer/reader overlap, but also prevents reader/reader overlap. - As long as each thread is guaranteed an up-to-date view of the data and no other thread modifies the data while the readers are viewing it, there will be no problems. - This is what read-write locks allow: a resource can be accessed by multiple readers or a single writer at a time, but not both. - the read lock and write lock are simply different views of an integrated read-write lock object. - In practice, read-write locks can improve performance for frequently accessed read-mostly data structures on multiprocessor systems; under other conditions they perform slightly worse than exclusive locks due to their greater complexity. - Whether they are an improvement in any given situation is best determined via profiling; - it is relatively easy to swap out a readwrite lock for an exclusive one if profiling determines that a read-write lock is not a win. - Allowing readers to barge ahead of writers enhances concurrency but runs the risk of starving writers. - barge - Downgrading. If a thread holds the write lock, can it acquire the read lock without releasing the write lock? This would let a writer "downgrade" to a read lock without letting other writers modify the guarded resource in the meantime. - Most read-write lock implementations do not support upgrading, because without an explicit upgrade operation it is deadlock-prone. (If two readers simultaneously attempt to upgrade to a write lock, neither will release the read lock.) - ReentrantReadWriteLock provides reentrant locking semantics for both locks. Like ReentrantLock, a ReentrantReadWriteLock can be constructed as nonfair (the default) or fair. - Downgrading from writer to reader is permitted; upgrading from reader to writer is not (attempting to do so results in deadlock). - Like ReentrantLock, thewrite lock in ReentrantReadWriteLock has a unique owner and can be released only by the thread that acquired it. - Java 5.0, the read lock behaves more like a Semaphore than a lock, maintaining only the count of active readers, not their identities. This behavior was changed in Java 6 to keep track also of which threads have been granted the read lock. - Read-write locks can improve concurrency when locks are typically held for a moderately long time and most operations do not modify the guarded resources. - But ReentrantLock is not a blanket substitute for synchronized; use it only when you need features that synchronized lacks. - Read-write locks allow multiple readers to access a guarded object concurrently, offering the potential for improved scalability when accessing read-mostly data structures. - The client code in Listing 14.4 is not the only way to implement the retry logic. The caller could retry the take immediately, without sleeping—an approach known as busy waiting or spin waiting. This could consume quite a lot of CPU time if the buffer state does not change for a while. On the other hand, if the caller decides to sleep so as not to consume so much CPU time, it could easily "oversleep" if the buffer state changes shortly after the call to sleep. - A condition queue gets its name because it gives a group of threads—called the wait set—a way to wait for a specific condition to become true. - Unlike typical queues in which the elements are data items, the elements of a condition queue are the threads waiting for the condition. - Object.wait atomically releases the lock and asks the OS to suspend the current thread, allowing other threads to acquire the lock and therefore modify the object state. - Upon waking, it reacquires the lock before returning. Intuitively, calling wait means "I want to go to sleep, but wake me when something interesting happens", and calling the notification methods means "something interesting happened". -     // BLOCKS-UNTIL: not-full    public  synchronized  void put(V v) throws InterruptedException {        while (isFull())            wait();        doPut(v);        notifyAll();    }    // BLOCKS-UNTIL: not-empty    public  synchronized  V take() throws InterruptedException {        while (isEmpty())            wait();        V v = doTake();        notifyAll();        return v;    }} - Condition predicates are expressions constructed from the state variables of the class; - Document the condition predicate(s) associated with a condition queue and the operations that wait on them. - There is an important three-way relationship in a condition wait involving locking, the wait method, and a condition predicate. The condition predicate involves state variables, and the state variables are guarded by a lock, so before testing the condition predicate, we must hold that lock. The lock object and the condition queue object (the object on which wait and notify are invoked) must also be the same object. In BoundedBuffer, the buffer state is guarded by the buffer lock and the buffer object is used as the condition queue. The take method acquires the buffer lock and then tests the condition predicate - Every call to wait is implicitly associated with a specific condition predicate. When calling wait regarding a particular condition predicate, the caller must already hold the lock associated with the condition queue, and that lock must also guard the state variables from which the condition predicate is composed. - A single intrinsic condition queue may be used with more than one condition predicate. - When using condition waits (Object.wait or Condition.await): Always have a condition predicate—some test of object state that must hold before proceeding; Always test the condition predicate before calling wait, and again after returning from wait; Always call wait in a loop; Ensure that the state variables making up the condition predicate are guarded by the lock associated with the condition queue; Hold the lock associated with the the condition queue when calling wait, notify, or notifyAll; and Do not release the lock after checking the condition predicate but before acting on it. - marmalade - Whenever you wait on a condition, make sure that someone will perform a notification whenever the condition predicate becomes true. - There are two notification methods in the condition queue API—notify and notifyAll. - Calling notify causes the JVM to select one thread waiting on that condition queue to wake up; calling notifyAll wakes up all the threads waiting on that condition queue. - Because multiple threads could be waiting on the same condition queue for different condition predicates, using notify instead of notifyAll can be dangerous, primarily because single notification is prone to a problem akin to missed signals. - BoundedBuffer provides a good illustration of why notifyAll should be preferred to single notify in most cases. The condition queue is used for two different condition predicates: "not full" and "not empty". - Single notify can be used instead of notifyAll only when both of the following conditions hold: Uniform waiters. Only one condition predicate is associated with the condition queue, and each thread executes the same logic upon returning from wait; and One-in, one-out. A notification on the condition variable enables at most one thread to proceed. - Most classes don't meet these requirements, so the prevailing wisdom is to use notifyAll in preference to single notify. While this may be inefficient, it is much easier to ensure that your classes behave correctly when using notifyAll instead of notify. - If ten threads are waiting on a condition queue, calling notifyAll causes each of them to wake up and contend for the lock; then most or all of them will go right back to sleep. This means a lot of context switches and a lot of contended lock acquisitions for each event that enables (maybe) a single thread to make progress. (In the worst case, using notify-All results in O(n2) wakeups where n would suffice.) - This is another situation where performance concerns support one approach and safety concerns support the other. - The notification done by put and take in BoundedBuffer is conservative: a notification is performed every time an object is put into or removed from the buffer. This could be optimized by observing that a thread can be released from a wait only if the buffer goes from empty to not empty or from full to not full, and notifying only if a put or take effected one of these state transitions. This is called conditional notification. - conditional notification can improve performance, it is tricky to get right (and also complicates the implementation of subclasses) and so should be used carefully. - "First make it right, and then make it fast—if it is not already fast enough" - Listing 14.8. Using Conditional Notification in BoundedBuffer.put. public synchronized void put(V v) throws InterruptedException {    while (isFull())        wait();    boolean wasEmpty = isEmpty();    doPut(v);    if (wasEmpty)        notifyAll();} - A state-dependent class should either fully expose (and document) its waiting and notification protocols to subclasses, or prevent subclasses from participating in them at all. - (The worst thing a state-dependent class can do is expose its state to subclasses but not document its protocols for waiting and notification; this is like a class exposing its state variables but not documenting its invariants.) - One option for doing this is to effectively prohibit subclassing, either by making the class final or by hiding the condition queues, locks, and state variables from subclasses. - It is generally best to encapsulate the condition queue so that it is not accessible outside the class hierarchy in which it is used. - Wellings (Wellings, 2004) characterizes the proper use of wait and notify in terms of entry and exit protocols. For each state-dependent operation and for each operation that modifies state on which another operation has a state dependency, you should define and document an entry and exit protocol. - The entry protocol is the operation's condition predicate; the exit protocol involves examining any state variables that have been changed by the operation to see if they might have caused some other condition predicate to become true, and if so, notifying on the associated condition queue. - AbstractQueuedSynchronizer, upon which most of the state-dependent classes in java.util.concurrent are built (see Section 14.4), exploits the concept of exit protocol. - Just as Lock is a generalization of intrinsic locks, Condition (see Listing 14.10) is a generalization of intrinsic condition queues. - Intrinsic condition queues have several drawbacks. Each intrinsic lock can have only one associated condition queue, which means that in classes like BoundedBuffer multiple threads might wait on the same condition queue for different condition predicates, and the most common pattern for locking involves exposing the condition queue object. - A Condition is associated with a single Lock, just as a condition queue is associated with a single intrinsic lock; to create a Condition, call Lock.newCondition on the associated lock. - Hazard warning: The equivalents of wait, notify, and notifyAll for Condition objects are await, signal, and signalAll. However, Condition extends Object, which means that it also has wait and notify methods. Be sure to use the proper versions—await and signal—instead! - Just as with built-in locks and condition queues, the three-way relationship among the lock, the condition predicate, and the condition variable must also hold when using explicit Locks and Conditions. - The variables involved in the condition predicate must be guarded by the Lock, and the Lock must be held when testing the condition predicate and when calling await and signal.[11] Choose between using explicit Conditions and intrinsic condition queues in the same way as you would choose between - use Condition if you need its advanced features such as fair queueing or multiple wait sets per lock, and otherwise prefer intrinsic condition queues. (If you already use ReentrantLock because you need its advanced features, the choice is already made.) - In actuality, they are both implemented using a common base class, Abstract-QueuedSynchronizer (AQS)—as are many other synchronizers. - Listing 14.11. Bounded Buffer Using Explicit Condition Variables. @ThreadSafepublic class ConditionBoundedBuffer<T> {    protected final Lock lock = new ReentrantLock();    // CONDITION PREDICATE: notFull (count < items.length)    private final Condition notFull    = lock.newCondition();    // CONDITION PREDICATE: notEmpty (count > 0)    private final Condition notEmpty  = lock.newCondition();    @GuardedBy("lock")    private final T[] items = (T[]) new Object[BUFFER_SIZE];    @GuardedBy("lock") private int tail, head, count;    // BLOCKS-UNTIL: notFull    public void put(T x) throws InterruptedException {        lock.lock();        try {            while (count == items.length)                notFull.await();            items[tail] = x;            if (++tail == items.length)                tail = 0;            ++count;            notEmpty.signal();        } finally {            lock.unlock();        }    }    // BLOCKS-UNTIL: notEmpty    public T take() throws InterruptedException {        lock.lock();        try {            while (count == 0)                notEmpty.await();            T x = items[head];            items[head] = null;            if (++head == items.length)                head = 0;            --count;            notFull.signal();            return x;        } finally {            lock.unlock();        }    }} - AQS handles many of the details of implementing a synchronizer, such as FIFO queuing of waiting threads. Individual synchronizers can define flexible criteria for whether a thread should be allowed to pass or be required to wait. - Using AQS to build synchronizers offers several benefits. Not only does it substantially reduce the implementation effort, but you also needn't pay for multiple points of contention, as you would when constructing one synchronizer on top of another. In SemaphoreOnLock, acquiring a permit has two places where it might block—once at the lock guarding the semaphore state, and then again if a permit is not available. Synchronizers built with AQS have only one point where they might block, reducing context-switch overhead and improving - The basic operations that an AQS-based synchronizer performs are some variants of acquire and release. - Release is not a blocking operation; a release may allow threads blocked in acquire to proceed. - The fast (uncontended) path for updating an atomic variable is no slower than the fast path for acquiring a lock, and usually faster; the slow path is definitely faster than the slow path for locks because it does not involve suspending and rescheduling threads. - With algorithms based on atomic variables instead of locks, threads are more likely to be able to proceed without delay and have an easier time recovering if they do experience contention. - The atomic variable classes provide a generalization of volatile variables to support atomic conditional read-modify-write operations. - AtomicInteger bears a superficial resemblance to an extended Counter class, but offers far greater scalability under contention because it can directly exploit underlying hardware support for concurrency. - Atomics as "Better Volatiles" -     public void setLower(int i) {        while (true) {            IntPair oldv = values.get();            if (i > oldv.upper)                throw new IllegalArgumentException(                   "Can't set lower to " + i + " > upper");            IntPair newv = new IntPair(i, oldv.upper);            if (values.compareAndSet(oldv, newv))                return;        }    }    // similarly for setUpper} 15.3.2. - at high contention levels locking tends to outperform atomic variables, but at more realistic contention levels atomic variables outperform locks.[6] This is because a lock reacts to contention by suspending threads, reducing CPU usage and synchronization traffic on the shared memory bus. (This is similar to how blocking producers in a producer-consumer design reduces the load on consumers and thereby lets them catch up.) - On the other hand, with atomic variables, contention management is pushed back to the calling class. Like most CAS-based algorithms, AtomicPseudoRandom reacts to contention by trying again immediately, which is usually the right approach but in a high-contention environment just creates more contention. - In practice, atomics tend to scale better than locks because atomics deal more effectively with typical contention levels. - With low to moderate contention, atomics offer better scalability; with high contention, locks offer better contention avoidance. (CAS-based algorithms also outperform lock-based ones on single-CPU systems, since a CAS always succeeds on a single-CPU system except in the unlikely case that a thread is preempted in the middle of the read-modify-write operation.) - it is often cheaper to not share state at all if it can be avoided. - We can improve scalability by dealing more effectively with contention, but true scalability is achieved only by eliminating contention entirely. - An algorithm is called nonblocking if failure or suspension of any thread cannot cause failure or suspension of another thread; an algorithm is called lock-free if, at each step, some thread can make progress. - An uncontended CAS always succeeds, and if multiple threads contend for a CAS, one always wins and therefore makes progress. - Nonblocking algorithms are also immune to deadlock or priority inversion (though they can exhibit starvation or livelock because they can involve repeated retries). - Nonblocking algorithms are considerably more complicated than their lock-based equivalents. - The key to creating nonblocking algorithms is figuring out how to limit the scope of atomic changes to a single variable while maintaining data consistency. - In linked collection classes such as queues, you can sometimes get away with expressing state transformations as changes to individual links and using an AtomicReference to represent each link that must be updated atomically. - compareAndSet provides both atomicity and visibility guarantees. - the counter and the stack, illustrate the basic pattern of using CAS to update a value speculatively, retrying if the update fails. - Listing 15.6. Nonblocking Stack Using Treiber's Algorithm (Treiber, 1986). - @ThreadSafepublic class ConcurrentStack <E> {    AtomicReference<Node<E>> top = new AtomicReference<Node<E>>();    public void push(E item) {        Node<E> newHead = new Node<E>(item);        Node<E> oldHead;        do {            oldHead = top.get();            newHead.next = oldHead;        } while (!top.compareAndSet(oldHead, newHead)); - LinkedQueue in Listing 15.7 shows the insertion portion of the Michael-Scott nonblocking linked-queue algorithm (Michael and Scott, 1996), which is used by ConcurrentLinkedQueue. - quiescent - After the second update, the queue is again in the quiescent state, - circuitous - For frequently allocated, short-lived objects like queue link nodes, eliminating the creation of an AtomicReference for each Node is significant enough to reduce the cost of insertion operations. - AtomicStampedReference (and its cousin AtomicMarkableReference) provide atomic conditional update on a pair of variables. - AtomicStampedReference updates an object reference-integer pair, allowing "versioned" references that are immune[8] to the ABA problem. Similarly, AtomicMarkableReference updates an object reference-boolean pair that is used by some algorithms to let a node remain in a list while being marked as deleted. - Nonblocking algorithms maintain thread safety by using low-level concurrency primitives such as compare-and-swap instead of locks. These low-level primitives are exposed through the atomic variable classes, which can also be used as "better volatile variables" providing atomic update operations for integers and object references. - Nonblocking algorithms are difficult to design and implement, but can offer better scalability under typical conditions and greater resistance to liveness failures. - Java Memory Model (JMM) - Compilers may generate instructions in a different order than the "obvious" one suggested by the source code, or store variables in registers instead of in memory; processors may execute instructions in parallel or out of order; caches may vary the order in which writes to variables are committed to main memory; and values stored in processor-local caches may not be visible to other processors. - The Java Language Specification requires the JVM to maintain withinthread as-if-serial semantics: as long as the program has the same result as if it were executed in program order in a strictly sequential environment, all these games are permissible. - An architecture's memory model tells programs what guarantees they can expect from the memory system, and specifies the special instructions required (called memory barriers or fences) to get the additional memory coordination guarantees required when sharing data. - The classic sequential computing model, the von Neumann model, is only a vague approximation of how modern multiprocessors behave. - The bottom line is that modern shared-memory multiprocessors (and compilers) can do some surprising things when data is shared across threads, unless you've told them not to through the use of memory barriers. - The various reasons why operations might be delayed or appear to execute out of order can all be grouped into the general category of reordering. - Synchronization inhibits the compiler, runtime, and hardware from reordering memory operations in ways that would violate the visibility guarantees provided by the JMM.[1] - To guarantee that the thread executing action B can see the results of action A (whether or not A and B occur in different threads), there must be a happens-before relationship between A and B. - A correctly synchronized program is one with no data races; correctly synchronized programs exhibit sequential consistency, meaning that all actions within the program appear to happen in a fixed, global order. - Transitivity. If A happens-before B, and B happens-before C, then A happens-before C. - Even though actions are only partially ordered, synchronization actions—lock acquisition and release, and reads and writes of volatile variables—are totally ordered. - This makes it sensible to describe happens-before in terms of "subsequent" lock acquisitions and reads of volatile variables. - them—there is no happens-before relation between the actions in the two threads. - When one thread calls set to save the result and another thread calls get to retrieve it, the two had better be ordered by happens-before. - This could be done by making the reference to the result volatile, but it is possible to exploit existing synchronization to achieve the same result at lower cost. - FutureTask is carefully crafted to ensure that a successful call to tryReleaseShared always happens-before a subsequent call to tryAcquireShared; tryReleaseShared always writes to a volatile variable that is read by tryAcquireShared. -     V innerGet() throws InterruptedException, ExecutionException {        acquireSharedInterruptibly(0);        if (getState() == CANCELLED)            throw new CancellationException();        if (exception != null)            throw new ExecutionException(exception);        return result;    }} We call this technique "piggybacking" because it uses an existing happensbefore ordering that was created for some other reason to ensure the visibility of object X, rather than creating a happens-before ordering specifically for publishing X. - One thread putting an object on a queue and another thread subsequently retrieving it constitutes safe publication because there is guaranteed to be sufficient internal synchronization in a BlockingQueue implementation to ensure that the enqueue happens-before the dequeue. - Placing an item in a thread-safe collection happens-before another thread retrieves that item from the collection; - Counting down on a CountDownLatch happens-before a thread returns from await on that latch; Releasing a permit to a Semaphore happens-before acquiring a permit from that same Semaphore; - Submitting a Runnable or Callable to an Executor happens-before the task begins execution; - The safe publication techniques described there derive their safety from guarantees provided by the JMM; the risks of improper publication are consequences of the absence of a happens-before ordering between publishing a shared object and accessing it from another thread. - Unsafe publication can happen as a result of an incorrect lazy initialization, - Suppose thread A is the first to invoke getInstance. It sees that resource is null, instantiates a new Resource, and sets resource to reference it. When thread B later calls getInstance, it might see that resource already has a non-null value and just use the already constructed Resource. This might look harmless at first, but there is no happens-before ordering between the writing of resource in A and the reading of resource in B. - With the exception of immutable objects, it is not safe to use an object that has been initialized by another thread unless the publication happens-before the consuming thread uses it. - If thread A places X on a BlockingQueue (and no thread subsequently modifies it) and thread B retrieves it from the queue, B is guaranteed to see X as A left it. This is because the BlockingQueue implementations have sufficient internal synchronization to ensure that the put happens-before the take. Similarly, using a shared variable guarded by a lock or a shared volatile variable ensures that reads and writes of that variable are ordered by happens-before. - This happens-before guarantee is actually a stronger promise of visibility and ordering than made by safe publication. - UnsafeLazyInitialization can be fixed by making the getResource method synchronized, as shown in Listing 16.4. Because the code path through getInstance is fairly short (a test and a predicted branch), if getInstance is not called frequently by many threads, there is little enough contention for the SafeLazyInitialization lock that this approach offers adequate performance. - memory writes made during static initialization are automatically visible to all threads. - Thus statically initialized objects require no explicit synchronization either during construction or when being referenced. - However, this applies only to the as-constructed state—if the object is mutable, synchronization is still required by both readers and writers to make subsequent modifications visible and to avoid data corruption. - Listing 16.5. Eager Initialization. @ThreadSafe public class EagerInitialization {     private static Resource resource = new Resource();     public static Resource getResource() { return resource; } } Using eager initialization, shown in Listing 16.5, eliminates the synchronization cost incurred on each call to getInstance in SafeLazyInitialization. - Listing 16.6. Lazy Initialization Holder Class Idiom. @ThreadSafe public class ResourceFactory {      private static class ResourceHolder {          public static Resource resource = new Resource();      }      public static Resource getResource() {          return ResourceHolder.resource ;      } } 16.2.4. - DCL purported to offer the best of both worlds—lazy initialization without paying the synchronization penalty on the common code path. - And that's where the problem is: as described in Section 16.2.1, it is possible for a thread to see a partially constructed Resource. - The real problem with DCL is the assumption that the worst thing that can happen when reading a shared object reference without synchronization is to erroneously see a stale value (in this case, null); in that case the DCL idiom compensates for this risk by trying again with the lock held. But the worst case is actually considerably worse—it is possible to see a current value of the reference but stale values for the object's state, meaning that the object could be seen to be in an invalid or incorrect state. - the performance impact of this is small since volatile reads are usually only slightly more expensive than nonvolatile reads. - passed—the forces that motivated it (slow uncontended synchronization, slow JVM startup) are no longer in play, making it less effective as an optimization. - UnsafeLazyInitialization is actually safe if Resource is immutable.) - The Java Memory Model specifies when the actions of one thread on memory are guaranteed to be visible to another. # OReilly.Java.Performance.May.2014.ISBN.1449358454 - rationale for having separate generations - during the lengthy full GCs). G1 compacts the heap as it goes. - Hence, the first rule in sizing a heap is never to specify a heap that is larger than the amount of physical memory on the machine—and if there are multiple JVMs running, - good rule of thumb is to size the heap so that it is 30% occupied after a full GC. - calculate this, run the application until it has reached a steady-state configuration: a point at which it has loaded anything it caches, has created a maximum number of client connections, and so on. Then connect to the application with jconsole, force a full GC, and - that can be used to size the young generation: -XX:NewRatio= N Set the ratio of the young generation to the old generation. -XX:NewSize= N - -Xmn N Shorthand for setting both NewSize and MaxNewSize to the same value. - young generation is first sized by the NewRatio, which has a default value of 2. - By default, then, the young generation starts out at 33% of the initial heap size. - default for this flag (though PrintFlagsFinal will report a value of 1 MB). - is usually preferable to use -Xmn to specify a fixed size for the young generation as well. If - The young generation will grow in tandem with the overall heap size, but it can also fluctuate as a percentage of the total heap - bunch of class-related data, and that there are certain cir‐ - Note that permgen/metaspace does not hold the actual instance of the class (the Class objects), nor reflection objects (e.g., Method objects); those are held in the regular heap. - permgen/metaspace is really only used by the compiler and JVM run‐ time, and the data it holds is referred to as class metadata. There isn’t - One of the advantages to phasing out permgen is that the metaspace rarely needs to be sized—because (unlike permgen) metaspace will by default use as much space as it needs. - These memory regions behave just like a separate instance of the regular heap. They are sized dynamically based on an initial size and will increase as needed to a maximum size. For permgen, the sizes are specified via these flags: -XX:PermSize= N and -XX:MaxPermSize= N. Metaspace is sized with these flags: -XX:MetaspaceSize= N - All GC algorithms except the serial collector use multiple threads. The number of these threads is controlled by the -XX:ParallelGCThreads= N flag. The value of this flag affects the number of threads used for the following operations: - Take the example of a 16-CPU machine running four JVMs; each JVM will have by default 13 GC threads. If all four JVMs execute GC at the same time, the machine will have 52 CPU-hungry threads contending for CPU time. - 1. The basic number of threads used by all GC algorithms is based on the number of CPUs on a machine. 2. When multiple JVMs are run on a single machine, that num‐ ber will be too high and must be reduced. - To see how the JVM is resizing the spaces in an application, set the -XX:+PrintAdapti veSizePolicy flag. When a GC is performed, the GC log will contain information de‐ tailing how the various generations were resized - There are multiple ways to enable the GC log: specifying either of the flags -verbose:gc or -XX:+PrintGC will create a simple GC log (the flags are aliases for each other, and by default the log is disabled). The -XX:+PrintGCDetails flag will create a log with much more information. - it is often too difficult to diagnose what is happening with GC using only the simple log. In conjunc‐ tion with the detailed log, it is recommended to include -XX:+PrintGCTimeStamps or -XX:+PrintGCDateStamps, so that the time between GC operations can be determined. - Logfile rotation is controlled with these flags: -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles= N -XX:GCLogFileSize= N. By default, UseGCLogFileRotation is disabled. When that flag - jstat provides nine options to print different information about the heap; jstat -options will provide the full list. - One useful option is -gcutil, which displays the time spent in GC as well as the per‐ centage of each GC area that is currently filled. Other options to jstat will display the GC sizes in terms of KB. - Figure 6-3. Throughput with various heap sizes - -XX:MaxGCPauseMillis= N and -XX:GCTimeRatio= N. - the usual effect of automatic heap sizing is that the heap (and generation) sizes will increase until the GCTimeRatio goal is met. - GC has a substantial impact on the perfor‐ mance of those applications, - with a hefty 28-second pause time. - Since the goal of CMS is to never have a full - good idea to start CMS with a larger initial heap size (and larger permgen/metaspace), which is a special case of making the heap larger to prevent those failures. - One way to let CMS win the race is to start the concurrent cycle sooner. If the concurrent cycle starts when 60% of the old generation is filled, CMS has a better chance of finishing than if the cycle starts when 70% of the old generation is filled. The - ParallelGCThreads flag: ConcGCThreads = (3 + ParallelGCThreads) / 4 - Avoiding concurrent mode failures is the key to achieving the best possible performance with CMS. - hits the value specified by -XX:CMSInitiatingPermOccupancyFraction= N, which defaults to 80%. Enabling permgen sweeping is only part of the story, - In Java 8, CMS does clean unloaded classes from the metaspace by default. If for some reason you wanted to disable that, unset the -XX:-CMSClassUnloadingEnabled flag (by default, it is true). - Incremental CMS (iCMS) is deprecated in Java 8—it still exists, but it may not be part - quad- core chip), the rational for iCMS becomes less important. On systems with limited CPU, consider the G1 collector instead—particularly since the background threads of G1 also will periodically pause during a background cycle, lim‐ iting the competition for the CPU. - This approach—clearing out only the mostly garbage regions —is what gives G1 its name: Garbage First. - As usual, the example log was taken using PrintGCDetails, but the details in the log for G1 are more verbose. - to make sure that the mixed GCs clean up enough memory to prevent future concurrent failures. - Humongous - that much. To that end, G1 is primarily tuned via a single flag: the same -XX:MaxGCPauseMillis= N flag that was used to tune the throughput collector. - of the stop-the-world phases of G1 start to exceed that value, G1 will attempt to compensate—adjusting the young-to-old ratio, adjusting the heap size, starting the background processing sooner, changing the tenuring threshold, - limit is called the tenuring threshold. - the best tenuring threshold is. The threshold starts at the value specified by the -XX:InitialTenuringThreshold= N flag (the default is 7 for the throughput and G1 - and the value specified by the -XX:MaxTenuringThreshold= N flag; for the throughput and G1 collectors, the default maximum threshold is 15, and for CMS it is 6. - circumvent - young collection will always be around for a long time, you can specify -XX:+AlwaysTenure (by default, false), which is essentially the same as setting the MaxTenuringThreshold to 0. This is a very, very rare situation; it means that - which can be added to the GC log by including the flag -XX:+PrintTenuringDistribution - The most important thing to look for is whether the survivor spaces are so small that during a minor GC, objects are promoted directly from eden into the old generation. - to remain in the young generation for a few GC cycles. This increases the probability the object will be freed before it is promoted to the old generation. - If the survivor spaces are too small, objects will promoted di‐ rectly into the old generation, - The best way to handle that situation is to increase the size of the heap (or at least the young generation) and allow the JVM to handle the survivor spaces. - The important thing to realize about TLABs is that they have a small size, so large objects cannot be allocated within a TLAB. - Large objects must be allocated directly from the heap, which requires extra time because of the synchronization. - Consider the case where a TLAB is 100 KB, and 75 KB has already been allocated. If a new 30 KB allocation is needed, the TLAB can be retired, which wastes 25 KB of eden space. Or the 30 KB - By default, TLABs are enabled; they can be disabled by specifying -XX:-UseTLAB, although they give such a performance boost that disabling them is always a bad idea. - total memory allocated for objects outside of TLABs is 568.32 MB. This is a case where either changing the application to use smaller objects, or tuning the JVM to allocate those objects in larger TLABs, can have a beneficial effect. - the -XX:+PrintTLAB flag to the command line. Then, at every young collection, the GC log will contain two kinds of line: a line for each thread describing the TLAB usage for that thread, and a summary line describing the overall - humongous - the G1 algorithm is designed around the idea that the number of regions is closer to 2,048. - Often, G1 will have to perform a full GC in order to find contiguous regions. - Because the humongous object is allocated directly in the old generation, it cannot be freed during a young collection. So if the object is short-lived, this also defeats the generational design of the collector. - If no contiguous regions are found, G1 will run a full GC: - Without the additional logging provided by ena‐ bling PrintAdaptiveSizePolicy, the standard G1 GC log does not provide enough information to diagnose this situation. - A better next step is to reduce the size of those objects rather than tune the JVM around them. - G1 considers an object to be humongous if it will fill more than 50% of a region. - Since G1 regions are always a power of 2, - G1 regions are sized in powers of 2, starting at 1 MB. - Heaps that have a very different maximum size than initial size will have too many G1 regions; the G1 region size should be increased in that case. - Packets have many qualities, but one thing they never do is lie. If - Almost all network devices and hosts use tables to make decisions. - Topologies and cabling are two other focal points providing further details into actual networking - A model is a way to organize a system’s functions and features to define its structural design. - Models are routinely organized in a hierarchical or layered structure. - The protocols are collectively referred to as a protocol suite. - The OSI model is called a reference model. - It is not the intent of this reference model to either serve as an implementation specification or to be a basis for appraising the conformance of actual implementations or to provide a sufficient level of detail to define precisely the services and protocols of the interconnection architecture. - Application Provides the sole means for the application to access the OSI environment (OSIE) with no layer above it. - The functions are divided into connection mode and connectionless mode. - This layer provides for the representation and preservation of the data provided by the Application Layer entities. - Specifically, the Presentation Layer is focused on syntax that is acceptable to both ends and access to the layers above and below. - Session Specifies both full-duplex and half-duplex modes of operation. This layer provides the means (setup and teardown) for communicating nodes to synchronize and manage the data between them. - A mapping is provided between the Transport Layer and Session Layer (session service access point) addresses. - Transport Protocols at this layer are end-to-end between communicating OSI nodes and deal primarily with low cost and reliable transfer of data. - Basic functions include transport connection establishment, release, data transfer, and QoS. While this layer is not responsible for routing, it does map to Network Layer addressing. - This layer is not responsible for negotiating QoS settings, but rather focuses on routing between networks and subnetworks. - In addition to interfacing with the Network Layer, the data link connection can be built upon one or more Physical Layer interfaces. - Like most models, this OSI Physical Layer contains the electrical, mechanical, and functional means to establish physical connections between Layer-2 devices. - Operator precedence is quite feeble in that it requires all the components of an expression to be analyzed - precedence - Colloquially, - trip over - A code source is a simple object that reflects the URL from which a class was loaded and the keys (if any) that were used to sign that class. Class loaders are responsible for creating and manipulating code source objects, - The basic entity that the access controller operates on is a permission object −− an instance of the Permission class (java.security.Permission). - The Permission class itself is an abstract class that represents a particular operation. - For example, if we construct a permission object that represents access to a file, possession of that object does not mean we have permission to access the file. Rather, possession of the object allows us to ask if we have permission to access the file. - Recall that permissions have three properties: a type, a name, and some actions. The name and actions are optional. The type corresponds to an actual Java type (e.g., java.io.FilePermission); the types that - the operations that are implemented on a permission object are not generally used in code that we write −− they are used instead by the access controller. - parentheses - This style of architecture promotes reuse at the macro (service) level rather than micro (classes) level. It - IBM Vice President of Web Services <NAME> says that SOA "builds highways".[26] - SOA promotes the goal of separating users - Reasons for treating the implementation of services as separate projects from larger projects include: - This advocates agility. That is to say, it fosters business innovations and speeds up time-to-market.[28] - What’s more, the most stymieing effect of these monolithic applications was ultimately that we were unable to keep pace with our partner’s innovation. - sequenced. - treasure - outdoing - adversary, - Strategic thinking is the art of outdoing an adversary, knowing that the adversary is trying to do the same to you. - Parents trying to elicit good behavior from children must become - We have replaced theoretical arguments with illustrative examples and case studies. - The book should be accessible to all readers who are willing to follow a little bit of arithmetic, charts, and tables. # JavaScript- The Good Parts - sidestep - Don't be discouraged if it takes multiple readings to get it. Your efforts will be rewarded. - journeyman programmer, - I discovered that I could be a better programmer by using only the good parts and avoiding the bad parts. - subset I carved out is vastly superior to the language as a whole, - enormous - The sooner we can detect and repair errors, the less they cost us. JavaScript is a loosely - JavaScript depends on global variables for linkage. - global variables are evil, - So, it is recommended that /* */ comments be avoided and // comments be used instead. In this book, // will be used exclusively. - Internally, it is represented as 64-bit floating point, the same as Java's double. - So 100 and 1e2 are the same number. - The value NaN is a number value that is the result of an operation that cannot produce a normal result. - NaN is not equal to any value, including itself. - so all characters in JavaScript are 16 bits wide. - Strings have a length property. For example, "seven".length is 5. - JavaScript throws them all together in a common global namespace. - the var statement defines the function's private variables. - Unlike many other languages, blocks in JavaScript do not create a new scope, so variables should be defined at the - The simple types of JavaScript are numbers, strings, booleans (true and false), null, and undefined. All other - In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects. - An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string. A property value can be any JavaScript value except for undefined. Objects in JavaScript are class-free. There is no constraint on the names of new properties - Objects are useful for collecting and organizing data. Objects can contain other objects, so they can easily represent tree or graph structures. JavaScript includes a prototype linkage feature that allows one object to inherit the properties of another. When used well, this can reduce object - An object literal is a pair of curly braces surrounding zero or more name/value pairs. - anywhere an expression can appear: var empty_object = {};var stooge = {    "first-name": "Jerome",    "last-name": "Howard"}; - stooge["first-name"]     // "Joe"flight.departure.IATA    // "SYD" The undefined value is produced if an attempt is made to retrieve a nonexistent member: stooge["middle-name"]    // undefined - The || operator can be used to fill in default values: - var status = flight.status || "unknown"; - Attempting to retrieve values from undefined will throw a TypeError exception. This can be guarded against with the && operator: - flight.equipment.model                        // throw "TypeError"flight.equipment && flight.equipment.model    // undefined - Objects are passed around by reference. They are never copied: - The prototype link has no effect on updating. When we make changes to an object, the object's prototype is not touched: - The prototype link is used only in retrieval. If we try to retrieve a property value from an object, and if the object lacks the property name, then JavaScript attempts to - This is called delegation. - typeof flight.status      // 'string'typeof flight.arrival     // 'object'typeof flight.manifest    // 'undefined' - The other approach is to use the hasOwnProperty method, which returns true if the object has a particular property. The hasOwnProperty method does not look at the prototype chain: - flight.hasOwnProperty('number')         // trueflight.hasOwnProperty('constructor')    // false - are the hasOwnProperty method and using typeof to exclude functions: var name;for (name in another_stooge) {    if (typeof another_stooge[name] !== 'function') {        document.writeln(name + ': ' + another_stooge[name]); - Generally, the craft of programming is the factoring of a set of requirements into a set of functions and data structures. - Objects produced from object literals are linked to Object.prototype. Function objects are linked to Function.prototype (which is itself linked to Object.prototype). - Every function object is also created with a prototype property. Its value is an object with a constructor property whose value is the function. - The function object created by a function literal contains a link to that outer context. This is called closure. - important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: the method invocation pattern, the function invocation pattern, the constructor invocation pattern, and the apply invocation pattern. - The invocation operator is a pair of parentheses that follow any expression that produces a function value. - There is no runtime error when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra argument values will be ignored. If there are too few argument values, the undefined value will be substituted for the - There is no type checking on the argument values: any type of value can be passed to any parameter. - var myObject = {    value: 0;    increment: function (inc) {        this.value += typeof inc === 'number' ? inc : 1;    }}; - Methods that get their object context from this are called public methods. - easy workaround. If the method defines a variable and assigns it the value of this, the inner function will have access to this through that variable. By convention, the name of that variable is that: // Augment myObject with a double method.myObject.double = function (  ) { -     var that = this;    // Workaround.    var helper = function (  ) {        that.value = add(that.value, that.value)    };    helper(  );    // Invoke helper as a function. - The language is class-free. This is a radical departure from the current fashion. - radical - JavaScript itself is not confident in its prototypal nature, so it offers an object-making syntax that is reminiscent of the classical languages. - reminiscent - If a function is invoked with the new prefix, then a new object will be created with a hidden link to the value of the function's prototype member, and this will be bound to that new object. - Functions that are intended to be used with the new prefix are called constructors. - // but we can invoke the get_status method on// statusObject even though statusObject does not have// a get_status method.var status = Quo.prototype.get_status.apply(statusObject);    // status is 'A-OK' - arguments is not really an array. It is an array-like object. arguments has a length property, but it lacks all of the array methods. - A function always returns a value. If the return value is not specified, then undefined is returned. - prefix and the return value is not an object, then this (the new object) is returned instead. - mishap - var add = function (a, b) {    if (typeof a !== 'number' || typeof b !== 'number') {        throw {            name: 'TypeError',            message: 'add needs numbers'        }    }    return a + b;} - The throw statement interrupts execution of the function. It should be given an exception object containing a name property that identifies the type of the exception, and a descriptive message property. You can also add other properties. - the ends of a string. That is an easy oversight to fix: String.method('trim', function (  ) {    return this.replace(/^\s+|\s+$/g, '');});document.writeln('"' + "   neat   ".trim(  ) + '"'); -     for (i = 0; i < nodes.length; i += 1) {        nodes[i].onclick = function (i) {            return function (e) {                alert(i);            };        }(i);    }}; - We can now define fibonacci with the memoizer, providing the initial memo array and fundamental function: var fibonacci = memoizer([0, 1], function (shell, n) { - a - The lineage of an object is irrelevant. - lineage - It can ape the classical pattern, - The set of possible inheritance patterns in JavaScript is vast. - JavaScript is a prototypal language, which means that objects inherit directly from other objects. - If you forget to include the new prefix when calling a constructor function, then this will not be bound to a new object. - clobbering - To mitigate this problem, there is a convention that all constructor functions are named with an initial capital, and that nothing else is spelled with an - this.prototype = {constructor: this}; - constructor property whose value is the new function object. The prototype object is the place where inherited traits are to be deposited. - (boldface text added for emphasis): - var coolcat = function (spec) {    var that = cat(spec),        super_get_name = that.superior('get_name');    that.get_name = function (n) {        return 'like ' + super_get_name(  ) + ' baby'; - JavaScript does not have anything like this kind of array. Instead, JavaScript provides an object that has some array-like - numbers inherits from Array.prototype, whereas number_object inherits from Object.prototype, so numbers inherits a larger set of useful methods. - JavaScript allows an array to contain any mixture of values: - The length property is the largest integer property name in the array plus one. This is not necessarily the number of properties in the array: - numbers.push('go');// numbers is ['zero', 'one', 'two', 'shi', 'go'] - ordinal - The first argument is an ordinal in the array. - numbers.splice(2, 1); - Since JavaScript's arrays are really objects, -         !(value.propertyIsEnumerable('length'));}; # Java Cryptography - <NAME>’ Java Security, - Let me say that again, every system can be broken. There are more secure and less secure systems, but no totally secure systems. - Building a secure application usually involves a three-way balancing act. The cost of having your application broken must be balanced against both the application’s cost and the application’s ease of use. - it will not make Java programs secure at the drop of a hat. - Cryptography is the science of secret writing. It’s a branch of mathematics, part of cryptology . - Proving identity is called authentication . In the physical world, a driver’s license is a kind of authentication. When you use a computer, you usually use a name and password to authenticate yourself. Cryptography provides stronger methods of authentication, called signatures and certificates. - Data transmitted across a network is subject to all sorts of nefarious attacks. - Cryptography can protect your data from thieves and impostors. - Applets are nifty, but without the right precautions they would be very dangerous. - Astute Inequalities - A message digest takes an arbitrary amount of input data and creates a short, digested version of the data, sometimes called a digital fingerprint, secure hash, or cryptographic hash. - Just as a fingerprint identifies a human, a message digest identifies data but reveals little about it. - Base64 is a system for representing an array of bytes as ASCII characters. This is useful, for example, when you want to send raw byte data through a medium, like email, that may not support anything but 7-bit ASCII. - A cipher is used to do this work. The cipher uses a key. Different keys will produce different results. SecretWriting stores its key in a file called SecretKey.ser. - Note that you must use the same key to encrypt and decrypt data. This is a property of a symmetric cipher. - Encryption is the process of taking data, called plaintext , and mathematically transforming it into an unreadable mess, called ciphertext . - The rot13 algorithm is a variation on the Caeser cipher, which, as its name implies, was hot stuff about 2000 years ago. - Symmetric Ciphers A symmetric cipher uses the same key at the sending and receiving end, as shown in Figure 2.3. - To avoid this problem, you could program each client with a different private key, but this would quickly become a distribution headache. - The shortcomings of symmetric ciphers are addressed by asymmetric ciphers, also called public key ciphers. - Public keys really are public; you can publish them in a newspaper or write them in the sky. - In some cases, the reverse of the process also works; data encrypted with the private key can be decrypted with the public key. - Asymmetric ciphers are much slower than symmetric ciphers, so they are not usually used to encrypt long messages. I’ll talk more about this later. - In practice, the cipher is a mathematical formula. A key is just a special number, or a few special numbers, that are used in the formula. - public key for an ElGamal cipher, for example, consists of three numbers, called p, g, and y. When you use an ElGamal cipher to encrypt data, the p, g, and y values are used mathematically to transform the plaintext into ciphertext. - Another solution for storing private keys is to put them on removable media, like floppy disks or smart cards. - Hybrid Systems Hybrid systems combine symmetric and asymmetric ciphers. - The beginning of a conversation involves some negotiation, carried out using an asymmetric cipher, where the participants agree on a private key, or session key . The session key is used with a symmetric cipher to encrypt the remainder of the conversation. - session key’s life is over when the two participants finish their conversation. If they have a new conversation, they’ll generate a new session key, which makes the cryptanalyst’s job harder. - Finally, symmetric ciphers are sometimes called secret key ciphers. - skullduggery, - This is a hefty batch of assumptions, - downloaded message digest, then eveything is copacetic, right? - The message digest becomes useful when it’s paired with other cryptographic techniques. A Message Authentication Code (MAC), for example, is basically a message digest with an associated key. - cipher. If Marian encrypts the message digest with her private key, <NAME> can download the encrypted message digest, decrypt it using Marian’s public key, and compare the message digest to one that he computes from the downloaded file. If they match, then he can be sure that the file is correct. The encrypted message digest is called a signature ; Marian has signed the file. - that a message digest is a lot like a hash value, except longer. - Message digests are sometimes called secure hash functions or cryptographic hash functions. - Typically, an asymmetric cipher is used to authenticate the participants of a conversation; the conversation itself is encrypted with a symmetric cipher, using a special one-time key called a session key. - Essentially, a certificate is a signed public key. - Marian creates the certificate by placing some information about her, some information about Will, and Will’s public key value into a file. She then signs the file with her own private key, as shown in Figure 2.8. <NAME> (or anyone else) can download this certificate and verify it using Marian’s public key. - The verification process is as follows: Calculate a message digest for the certificate contents (except the signature). Decrypt the signature using the signer’s (Marian’s) public key. The result is a message digest. Compare the decrypted message digest to the calculated message digest. If they match, the certificate is valid and you now know the value of Will’s public key. - Certificate Chains To verify a certificate, you need a public key. To verify a public key, you need a certificate. - Essentially, one certificate can be verified by another, which is verified by another, and so forth. This is called certificate chaining. The chain can’t be infinite, so where does it start? The certificate chain starts with a certificate whose issuer and subject are the same. - Usually such a certificate is issued by a Certificate Authority (CA), an ostensibly dependable institution like VeriSign or the U. S. Postal Service. - ostensibly - <NAME> already has a trustworthy, self-signed certificate from Marian. He uses Marian’s public key to verify the signature on Friar Tuck’s certificate. Then he uses Friar Tuck’s public key to verify Little John’s certificate. Now, finally, he can trust Little John’s public key and use it to verify the integrity of the downloaded file. - Using certificates to prove authenticity, then, depends on a chain of certificates that ultimately terminates on a self-signed certificate issued by a CA. - Anyone can generate a self-signed certificate, claiming to be the Post Office or the Emperor of Tibet. Why would you ever trust a self-signed certificate? You can trust a self-signed certificate if you’re able to verify it. One convenient way to verify certificates is to calculate a message digest of the entire certificate, commonly known as a certificate fingerprint . To verify a fingerprint, call the people who issued the certificate and have them read off the numbers of the fingerprint. Another option is for the CA to widely publish their self-signed certificate’s fingerprint, perhaps in newspapers and magazines as well as online. - Currently, most self-signed certificates are embedded into web browsers. When you download and run a browser, it can recognize certificates issued by a dozen or so popular CAs, using internal self-signed certificates from these CAs. - a pseudo-random number generator (PRNG) as a source of “random” data. - SHA-1 produces a message digest value that is 160 bits long, which increases its resistance to attack. - In the version I’ll be using, blocks of plaintext are transformed into ciphertext using three DES keys and three applications of a normal DES cipher: The plaintext is encrypted using the first key. The result of step 1 is decrypted using the second key. The result of step 2 is encrypted using the third key, producing ciphertext. - PBE stands for passphrase-based encryption - In this particular variant of PBE, an MD5 message digest is used to digest the passphrase. - The digest value is then used as a DES key. One approach to this is described in PKCS#5, a document published by RSA Data Security, Inc. - The overall design of the cryptography classes is governed by the Java Cryptography Architecture - The JCE is an extension of the JCA and includes another cryptographic provider, called SunJCE. The JCE is a standard extension library, which means that although it is not a part of the core JDK, it is a package that works with the JDK. - The second group of methods is the Service Provider Interface, or SPI. This is the set of methods that subclasses must implement. By convention, SPI method names all begin with engine. - I suggest you bask in the simplicity of this style of programming. - At the root of the JCA is the idea of security providers. A provider supplies algorithms for the cryptographic concept classes. In practice, a provider is a collection of algorithm classes headed up by a java.security.Provider object. - This is confusing terminology; provider (small p) refers to the concept, while Provider refers to a specific class. - A factory method, then, is a special kind of static method that returns an instance of a class. In JDK 1.0.2, factory methods were used indirectly in the Socket class (see setSocketImplFactory()). - The Security class keeps track of providers by keeping a list of their corresponding Provider objects. When it needs a particular algorithm, it asks each Provider, in turn, if it implements a particular algorithm. Each Provider knows about the other classes in the provider’s repertoire and will return an appropriate instance if possible. The Provider is, in effect, the boss of the algorithm team. - To configure providers statically, you’ll need to edit the java.security file, which is found in the lib/security directory underneath your main JDK installation directory. - Instead, they rely on a pseudo-random number generator (PRNG). A cryptographically strong PRNG, seeded with truly random values, is a PRNG that does a good job of spewing out unpredictable data. - The JDK includes a class, java.util.Random, that implements a PRNG. Although it’s fine for light-duty use, it has the following shortcomings: It uses an algorithm that produces a predictable sequence of numbers. - Because of the irreversible nature of the message digest, it’s very hard to predict the past and future values of the PRNG even if you know its present output. - The thread timing algorithm is not thoroughly tested. It may have weaknesses that cryptanalysts could exploit. - It relies on counting the number of times that the calling thread can yield while waiting for another thread to sleep for a specified interval. - PGP (Pretty Good Privacy, a popular cryptography application). - Several interfaces extend the Key interface. These child interfaces define different flavors of keys, but none of them defines any additional methods; they are used for clarity and type safety. - The JCE includes another semantic extension of Key: javax.crypto.SecretKey This interface represents a secret (or private, or session) key that is used for a symmetric cipher. With a symmetric cipher, the same secret key is used to encrypt and decrypt data. - There are two varieties of key generators. The first generates key pairs for use with asymmetric ciphers and signatures. The second kind generates a single key for use with a symmetric cipher. - public SecretKeySpec(byte[] key, String algorithm) This constructor creates a SecretKeySpec using the supplied byte array. The key will have the supplied algorithm. public SecretKeySpec(byte[] key, int offset, int len, String algorithm) This constructor creates a SecretKeySpec using len bytes of the supplied byte array, starting at - Use this method to create a new SecretKeyFactory for the given algorithm. The algorithm name should correspond to a symmetric cipher algorithm name, for example, “DES.” - From things to keys To translate a KeySpec into a SecretKey, use SecretKeyFactory’s generateSecret() method: - KeyFactory java.security.KeyFactory is a lot like SecretKeyFactory, except that it deals with public and private keys instead of secret keys. - A key agreement is a protocol whereby two or more parties can agree on a secret value. The neat thing about key agreements is that they can agree on a secret value even while talking on an insecure medium (like the Internet). These protocols are called key agreement protocols because they are most often used to settle on a session key that will be used to encrypt a conversation. - The most famous key agreement protocol is Diffie-Hellman (DH). - a paper that is widely considered to be the genesis of public key cryptography. - The SunJCE provider includes a KeyAgreement implementation based on Diffie-Hellman. - public static final KeyAgreement getInstance(String algorithm) throws NoSuchAlgorithmException This method creates a new KeyAgreement for the given algorithm. The name should be a key agreement name, like “DH” for Diffie-Hellman. - As I said, the base and modulus used in Diffie-Hellman may be dictated by a standard. One such standard is Simple Key Management for Internet Protocols (SKIP).[ - SKIP defines base and modulus values for three different sizes of Diffie-Hellman keys. We’ll use the 1024-bit base and modulus. - hexadecimal. - Each Identity contains a PublicKey and other relevant information (name, address, phone number, etc.). Each Signer contains a matched PublicKey and PrivateKey and other useful information. - Key Holders Keys usually belong to something—a person, a group of people, a company, a computer, a thread of execution, or almost anything else. In the JDK, the java.security.Identity class represents something that possesses a key. - Identity An Identity represents a person, an organization, or anything else that has an associated public key. In other words, an Identity is a Principal with a public key. - JDK 1.2 offers a new method for key management, based on java.security.KeyStore . A KeyStore is a handy box that holds keys and certificates. One KeyStore contains all the information a single person (or application, or identity) needs for authentication. - A KeyStore contains two types of entries. The first type contains a private key and a chain of certificates that correspond to the matching public key. I’ll call this type of entry a private key entry. - KeyStore holds all this information, organized by aliases, or short names. Entries are stored and retrieved using an alias, similar to the way a Hashtable or Properties object works. - KeyStore’s getInstance() method uses a line in the java.security properties file to decide what subclass of KeyStore to create. The line might look like this: keystore=oreilly.jonathan.security.SuperDuperKeyStore - This is a different use of a passphrase from what we saw earlier, with store() and load(). In those methods, a passphrase is used to protect the integrity of the keystore data as a whole. Here, a passphrase is used for confidentiality, to obscure a private key. - keytool keytool is a command-line interface to the java.security.KeyStore class. As we’ve seen, a KeyStore is a simple database for private keys, public keys, and certificates. Each entry in the KeyStore has an alias that identifies it. Entries are always referenced using an alias. - If you don’t specify a KeyStore file when using keytool, the default file will be used. This is a file called .keystore, located in the directory determined by the HOMEDRIVE and HOMEPATH environment variables. - concatenated; - -dname This entry is used to specify a distinguished name (DN).[13] A DN contains your name and places you in a hierarchy based on countries and organizations (companies, universities, etc.). In the preceding example, I’ve identified my real name, my company, my group within the company (Technical Publications), and the country I live in. Here is a complete list of DN fields that keytool recognizes: CN (common name): your name OU (organizational unit): the part of your organization to which you belong O (organization): your organization L (locality): usually, a city S (state): a state or province C (country): a country You don’t have to include every DN field. - This passphrase is used to protect the private key of the new key pair. - You will have to type the same passphrase to access the private key at a later date. - Inspecting the keystore To see the contents of a keystore, use the -list command: - Generating a CSR To get a real certificate, signed by a Certificate Authority (CA), you need to generate a Certificate Signing Request (CSR). The CSR is a special file that contains your public key and information about you. It is signed with your private key. When you send a CSR to a CA, the CA will make some effort to verify your identity and to verify the authenticity of the CSR. - Then it can issue you a certificate, signed with the CA’s private key, that verifies your public key. - So what does the CSR look like? Basically it’s just a long string of base64 data. You can send it to your CA via FTP, HTTP, or email. - You authenticate yourself using a personal identification number (PIN). The PIN is a shared secret, something that both you and the bank know. - have none of the usual visual or aural clues that are helpful in everyday transactions. - Message digests produce a small “fingerprint” of a larger set of data. - Digital signatures can be used to prove the integrity of data. - Certificates are used as cryptographically safe containers for public keys. - The Java Cryptography Architecture (JCA) makes it very easy to use message digests. - To obtain a MessageDigest for a particular algorithm use one of its getInstance() factory methods: public static MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException This method returns a MessageDigest for the given algorithm. - Feeding To feed data into the MessageDigest, use one of the update() methods: public void update(byte input) This method adds the specified byte to the message digest’s input data. - Digesting To find out the digest value, use one of the digest() methods: public byte[] digest() The value of the message digest is returned as a byte array. public byte[] digest(byte[] input) This method is provided for convenience. - you can reuse the MessageDigest for a second set of data by clearing its internal state first. public void reset() This method clears the - you can calculate a message digest value for any input data with just a few lines of code: // Define byte[] inputData first. MessageDigest md = MessageDigest.getInstance("SHA"); md.update(inputData); byte[] digest = md.digest(); - Message digests are one of the building blocks of digital signatures. - The password is a shared secret because both the user and the server must know it. - Most computer networks, however, are highly susceptible to eavesdropping, so this is not a very secure solution. - If the two message digests are equal, then the client is authenticated. This simple procedure, however, is vulnerable to a replay attack. A malicious user could listen to the digested password and replay it later to gain illicit access to the server. - To avoid this problem, some session-specific information is added to the message digest. In particular, the client generates a random number and a timestamp and includes them in the digest. These values must also be sent, in the clear, to the server, so that the server can use them to calculate a matching digest value. The server must be programmed to receive the extra information and include it in its message digest calculations. Figure 6.1 shows how this works on the client side. Figure 6-1. Protecting a password The server uses the given name to look up the password in a private database. Then it uses the given name, random number, timestamp, and the password it just retrieved to calculate a message digest. If this digest value matches the digest sent by the client, the client has been authenticated. - Double-Strength Password Login There is a stronger method for protecting password information using message digests. It involves an additional timestamp and random number, - First, a digest is computed, just as in the previous example. Then, the digest value, another random number, and another timestamp are fed into a second digest. Then the server is sent the second digest value, along with the timestamps and random numbers. - Why is this better than the simpler scheme we outlined earlier? To understand why, think about how you might try to break the protected password scheme. Recall that a message digest is a one-way function; ideally, this means that it’s impossible to figure out what input produced a given digest value.[ - Neither the regular or double-strength login methods described here prevent a dictionary attack on the password. - A message authentication code (MAC) is basically a keyed message digest. Like a message digest, a MAC takes an arbitrary amount of input data and creates a short digest value. Unlike a message digest, a MAC uses a key to create the digest value. This makes it useful for protecting the integrity of data that is sent over an insecure network. - Calculating the Code To actually calculate the MAC value, use one of the doFinal() methods: public final byte[] doFinal() throws IllegalStateException - SecureRandom sr = new SecureRandom(); byte[] keyBytes = new byte[20]; sr.nextBytes(keyBytes); SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac m = Mac.getInstance("HmacSHA1"); m.init(key); m.update(inputData); byte[] mac = m.doFinal(); - A signature provides two security services, authentication and integrity. A signature gives you assurance that a message has not been tampered with and that it originated from a certain person. - a signature is a message digest that is encrypted with the signer’s private key. - Only the signer’s public key can decrypt the signature, which provides authentication. If the message digest of the message matches the decrypted message digest from the signature, then integrity is also assured. - Signatures are useful for distributing software and documentation because they foil forgery. - Generating a Signature Generating a signature is a lot like generating a message digest value. The sign() method returns the signature itself: public final byte[] sign() throws - To generate a signature, you will need the signer’s private key and the message that you wish to sign. The procedure is straightforward: Obtain a Signature object using the getInstance() factory method. You’ll need to specify an algorithm. A signature actually uses two algorithms—one to calculate a message digest and one to encrypt the message digest. The SUN provider shipped with the JDK 1.1 supports DSA encryption of an SHA-1 message digest. This is simply referred to as DSA. Initialize the Signature with the signer’s private key using initSign(). Use the update() method to add the data of the message into the signature. You can call update() as many times as you would like. Three different overloads allow you to update the signature with byte data. Calculate the signature using the sign() method. This method returns an array of bytes that are the signature itself. It’s up to you to store the signature somewhere. Verifying a Signature You can use Signature’s verify() method to verify a signature: public final boolean verify(byte[] signature) throws - Check if your signatures match using the verify() method. This method accepts an array of bytes that are the signature to be verified. It returns a boolean value that is true if the signatures match and false otherwise. - We’ll look at the simple case, with a pair of programs called StrongClient and StrongServer. StrongClient creates a timestamp and a random number and sends them along with the user’s name and a signature to the server. The length of the signature is sent before the signature itself, just as it was with the message digest login examples. - One possible application of SignedObject is in the last example. We might write a simple class, AuthorizationToken, that contained the user’s name, the timestamp, and the random value. This object, in turn, could be placed inside a SignedObject that could be passed from client to server. - Certificates To verify a signature, you need the signer’s public key. So how are public keys distributed securely? You could simply download the key from a server somewhere, but how would you know you got the right file and not a forgery? Even if you get a valid key, how do you know that it belongs to a particular person? - A certificate is a statement, signed by one person, that the public key of another person has a particular value. In some ways, it’s like a driver’s license. The license is a document issued by your state government that matches your face to your name, address, and date of birth. - You need to trust the person who issued the certificate (who is known as a Certificate Authority, or CA). - In cryptographic terminology, a certificate associates an identity with a public key. The identity is called the subject . The identity that signs the certificate is the signer. The certificate contains information about the subject and the subject’s public key, plus information about the signer. The whole thing is cryptographically signed, and the signature becomes part of the certificate, too. Because the certificate is signed, it can be freely distributed over insecure channels. - At a basic level, a certificate contains these elements: Information about the subject The subject’s public key Information about the issuer The issuer’s signature of the above information - Sun recognized that certificate support was anemic in JDK 1.1. Things are improved in JDK 1.2. - Working with certificates in JDK 1.2 is sometimes difficult because there are two things named Certificate. The java.security.Certificate interface was introduced in JDK 1.1, but it’s now deprecated. The “official” certificate class in JDK 1.2 is java.security.cert.Certificate. - public abstract void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException This method uses the supplied public key to verify the certificate’s contents. The public key should belong to the certificate’s issuer (and has nothing to do with the public key contained in this certificate). The supplied issuer’s public key is used to verify the internal signature that protects the integrity of the certificate’s data. - X.509 Several standards specify the contents of a certificate. One of the most popular is X.509, published by the International Telecommunications Union (ITU). - To load an X.509 certificate from a file, you can use getInstance() : public static final X509Certificate getInstance(InputStream inStream) throws CertificateException - cert.provider.x509=sun.security.x509.X509CertImpl Let’s say you call getInstance() with an input stream. A sun.security .x509.X509CertImpl will be created, using a constructor that accepts the input stream. It’s up to the X509CertImpl to read data from the input stream to initialize itself. X509CertImpl knows how to construct itself from a DER-encoded certificate. What is DER? In the X.509 standard, a certificate is specified as a data structure using the ASN.1 (Abstract Syntax Notation) language. There are a few different ways that ASN.1 data structures can be reduced to a byte stream, and DER (Distinguished Encoding Rules) is one of these methods. The net result is that an X509CertImpl can recognize an X.509 certificate if it is - Let’s look at an example that uses X509Certificate . We’ll write a tool that displays information about a certificate contained in a file, just like keytool -printcert. Like keytool, we’ll recognize certificate files in the format described by RFC 1421. An RFC 1421 certificate representation is simply a DER representation, converted to base64, with a header and a footer line. Here is such a file: -----BEGIN CERTIFICATE----- MIICMTCCAZoCAS0wDQYJKoZIhvcNAQEEBQAwXDELMAkGA1UEBhMCQ1oxETAPBgNV - Our class performs three tasks: We need to read the file, strip off the header and footer, and convert the body from a base64 string to a byte array. The oreilly.jonathan.util.Base64 class is used to perform the base64 conversion. This class is presented in Appendix B. We’ll use this byte array (a DER-encoded certificate) to create a new X509Certificate. We can then print out some basic information about the certificate. Finally, we’ll calculate certificate fingerprints and print them. - shortcoming of the JDK 1.1 certificate support: Certificate Revocation Lists (CRLs). CRLs answer the question of what happens to certificates when they’re lost or stolen. - A CRL is simply a list of certificates that are no longer valid. - public abstract boolean isRevoked(BigInteger serialNumber) This method returns true if the certificate matching the given serial number has been revoked. Serial numbers are unique to a Certificate Authority (CA). Each CA issues its own CRLs. Thus, this method is used to correlate certificate serial numbers from the same CA. - A cipher encrypts or decrypts data. Ciphers comes in three flavors: Symmetric , or private key , ciphers use a single secret key to encrypt and decrypt data. Symmetric keys can be useful in applications like hard-disk file encryption, when the same person encrypts and decrypts data. Asymmetric , or public key , ciphers use a pair of keys. One key is public and may be freely distributed. The other key is private and should be kept secret. Data encrypted with either key can be decrypted using the other key. Hybrid systems use a combination of symmetric and asymmetric ciphers. Asymmetric ciphers are much slower than their symmetric counterparts. In a hybrid system, an asymmetric cipher is used to exchange a private key (also called a secret key or a session key). The secret key is used with a symmetric cipher for data encryption and decryption. - This list mixes apples and oranges a little bit. - Asymmetric ciphers are block ciphers. Before computers, encryption was accomplished using stream ciphers, which are ciphers that operate on one character of a message at a time. - PKCS#5 PKCS#5 is one possible padding scheme. PKCS#5 is a Public-Key Cryptography Standard, a self-proclaimed standard published by RSA Data Security, Inc. The padding method is straightforward: Fill the remainder of the block with bytes containing the number of remaining bytes.[ - the name for PKCS#5 padding is “PKCS5Padding.” - The mode of a cipher determines how blocks of plaintext are encrypted into blocks of ciphertext, and vice versa. You can find out the mode of a Cipher by calling getMode(). The SunJCE provider supports ECB, CBC, CFB, OFB, and PCBC modes, which I will describe here. - ECB The simplest case is electronic code book (ECB) mode, in which each block of plaintext encrypts to a block of ciphertext. - ECB mode has the disadvantage that the same plaintext will always encrypt to the same ciphertext, if you use the same key. - If your data is more “random looking,” like a key or a message digest, then ECB may be appropriate. Otherwise, you should consider a different mode. - Cipher block chaining (CBC) mode overcomes the weakness of ECB mode. Each block of plaintext is combined with the previous block’s ciphertext, using XOR; the result is encrypted to form a block of ciphertext. - Because there is no previous ciphertext block for the first block of plaintext, an initialization vector (IV) is used for the first block of plaintext. The IV is usually just random data. The decrypting cipher must be initialized with the same IV to correctly decrypt the data. - PCBC Propagating cipher block chaining (PCBC) mode is a lot like CBC mode. When a plaintext block is encrypted, however, it is XORed with both the previous plaintext block and the previous ciphertext block. Likewise, decrypted blocks are XORed with the previous plaintext and ciphertext blocks. - Cipher feedback (CFB) mode allows a block cipher to act like a stream cipher. Like CBC, it uses an IV, but the internal process is more involved. - As you might have noticed, CFB mode is not particularly efficient. Each time a piece of plaintext is encrypted, an entire block is encrypted by the underlying cipher. - For a cipher with a block size of 64 bits, CFB8 will be about eight times slower than ECB or CBC. - You can use CFB mode with any symmetric block cipher. Interestingly, you can use CFB mode with an asymmetric cipher algorithm, too, but it will behave like a symmetric cipher. - OFB Output feedback (OFB) mode works just like CFB mode, except in how the internal buffer is updated. - When the internal buffer is shifted left, the space on the right side is filled with the leftmost bits of the encrypted buffer (instead of the ciphertext, which was used in CFB). - PKCS#5 is actually a standard for passphrase-based encryption. Part of the standard specifies this padding scheme. You can get PKCS#5 from RSA Data Security, - The ciphertext is represented in base64, which uses 6 bits per digit. Thus, the first 10 digits make up 60 bits of the first 64-bit ciphertext block, and these digits are the same for both ciphertexts. - Algorithms One of the nice features of the provider architecture in the Security API is that it’s possible to use different cryptographic algorithms without having to rewrite your program. The SunJCE provider includes three cipher algorithms. - The javax.crypto.Cipher class encapsulates a cipher algorithm. A Cipher either encrypts data or decrypts data. The Cipher class encompasses both asymmetric (public key) and symmetric (private key) algorithms. - Salt is additional data concatenated to the passphrase. The passphrase and salt are digested together. This means that the attacker’s dictionary now needs to contain many more entries, one for each possible salt value for each probable passphrase. # Java Performance: The Definitive Guide - The G1 young collection is triggered when eden fills up - collectors. As usual, the example log was taken using PrintGCDetails, but the details in the log for G1 are more verbose. - As is usual for a young collection, G1 has completely emptied eden and adjusted the survivor spaces. Additionally, two of the marked regions have been collected. Those regions were known to contain mostly garbage, and so a large part of them was freed. Any live data in those regions was moved to another region (just as live data was moved from the young generation into regions in the old generation). This is why G1 ends up with a fragmented heap less often than CMS—moving the objects like this is compacting the heap as G1 goes along. - G1 has completed a marking cycle and has started performing mixed GCs to clean up the old regions, but the old generation runs out of space before enough memory can be reclaimed from the old generation. In the log, a full GC immediately follows a mixed GC: - G1 has a number of cycles (and phases within the concurrent cycle). A well-tuned JVM running G1 should only experience young, mixed, and concurrent GC cycles. - Small pauses occur for some of the G1 concurrent phases. G1 should be tuned if necessary to avoid full GC cycles. - To that end, G1 is primarily tuned via a single flag: the same -XX:MaxGCPauseMillis=N flag that was used to tune the throughput collector. When used with G1 (and unlike the throughput collector), that flag does have a default value: 200 ms. If pauses for any of the stop-the-world phases of G1 start to exceed that value, G1 will attempt to compensate—adjusting the young-to-old ratio, adjusting the heap size, starting the background processing sooner, changing the tenuring threshold, and (most significantly) processing more or fewer old generation regions during a mixed GC cycle. The usual trade-off - To have G1 win its race, try increasing the number of background marking threads (assuming there is sufficient CPU available on the machine). Tuning the G1 threads is similar to tuning the CMS threads: the ParallelGCThreads option affects the number of threads used for phases when application threads are stopped, and the ConcGCThreads flag affects the number of threads used for concurrent phases. - G1 can also win its race if it starts collecting earlier. The G1 cycle begins when the heap hits the occupancy ratio specified by -XX:InitiatingHeapOccupancyPercent=N, which has a default value of 45. Note that unlike CMS, that setting is based on the usage of the entire heap, not just the old generation. - a region is declared eligible for collection during a mixed GC if it is 35% garbage. (It is likely this value will become a tunable parameter at some point; the experimental name for the parameter (available in experiment builds of the open source code) is -XX:G1MixedGCLiveThresholdPercent=N.) - G1 tuning should begin by setting a reasonable pause time target. - To make the background threads run more frequently, adjust the InitiatingHeapOccupancyPercent. If additional CPU is available, adjust the number of threads via the ConcGCThreads flag. - To prevent promotion failures, decrease the size of the G1MixedGCCountTarget. - This is the reason that the young generation is divided into two survivor spaces and eden. This setup allows objects to have some additional chances to be collected while still in the young generation, rather than being promoted into (and filling up) the - When the young generation is collected and the JVM finds an object that is still alive, that object is moved to a survivor space rather than to the old generation. During the first young generation collection, objects are moved from eden into survivor space 0. During the next collection, live objects are moved from both survivor space 0 and from eden into survivor space 1. At that point, eden and survivor space 0 are completely empty. The next collection moves live objects from survivor space 1 and eden into survivor space 0, and so on. - (The survivor spaces are also referred to as the “to” and “from” spaces; during each collection, objects are moved out of the “from” space into the “to” space. “from” and “to” are simply pointers that switch between the two survivor spaces on every collection.) - Clearly this cannot continue forever, or nothing would ever be moved into the old generation. Objects are moved into the old generation in two circumstances. First, the survivor spaces are fairly small. When the target survivor space fills up during a young collection, any remaining live objects in eden are moved directly into the old generation. Second, there is a limit to the number of GC cycles during which an object can remain in the survivor spaces. That limit is called the tenuring threshold. - The survivor spaces take up part of the allocation for the young generation, and like other areas of the heap, the JVM sizes them dynamically. The initial size of the survivor spaces is determined by the -XX:InitialSurvivorRatio=N flag, which is used in this equation: survivor_space_size = new_size / (initial_survivor_ratio + 2) For the default initial survivor ratio of 8, each survivor space will occupy 10% of the young generation. - To keep the survivor spaces at a fixed size, set the SurvivorRatio to the desired value and disable the UseAdaptiveSizePolicy flag (though remember that disabling adaptive sizing will apply to the old and new generations as well). - The JVM determines whether to increase or decrease the size of the survivor spaces (subject to the defined ratios) based on how full a survivor space is after a GC. - The survivor spaces will be resized so that they are, by default, 50% full after a GC. That value can be changed with the -XX:TargetSurvivorRatio=N flag. - The threshold starts at the value specified by the -XX:InitialTenuringThreshold=N flag (the default is 7 for the throughput and G1 collectors, and 6 for CMS). The JVM will ultimately determine a threshold between 1 and the value specified by the -XX:MaxTenuringThreshold=N flag; for the throughput and G1 collectors, the default maximum threshold is 15, and for CMS it is 6. - If you know that objects that survive a young collection will always be around for a long time, you can specify -XX:+AlwaysTenure (by default, false), which is essentially the same as setting the MaxTenuringThreshold to 0. This is a very, very rare situation; it means that objects will always be promoted to the old generation rather than stored in a survivor space. - -XX:+NeverTenure (also false by default). This flag affects two things: it behaves as if the initial and max tenuring thresholds are infinity, and it prevents the JVM from adjusting that threshold down. In other words, as long as there is room in the survivor space, no object will ever be promoted to the old generation. - Given all that, which values might be tuned under which circumstances? It is helpful to look at the tenuring statistics, which can be added to the GC log by including the flag -XX:+PrintTenuringDistribution (which is false by default). - The most important thing to look for is whether the survivor spaces are so small that during a minor GC, objects are promoted directly from eden into the old generation. The reason to avoid that is short-lived objects will end up filling the old generation, causing full GCs to occur too frequently. - Survivor spaces are designed to allow objects (particularly just-allocated objects) to remain in the young generation for a few GC cycles. This increases the probability the object will be freed before it is promoted to the old generation. - If the survivor spaces are too small, objects will promoted directly into the old generation, which in turn causes more old GC cycles. - The best way to handle that situation is to increase the size of the heap (or at least the young generation) and allow the JVM to handle the survivor spaces. - In rare cases, adjusting the tenuring threshold or survivor space sizes can prevent promotion of objects into the old generation. - one reason allocation in eden is so fast is that each thread has a dedicated region where it allocates objects—a TLAB. - By setting up each thread with its own dedicated allocation area, the thread needn’t perform any synchronization when allocating objects. (This is a variation of how thread-local variables can prevent lock contention [see Chapter 9].) - The important thing to realize about TLABs is that they have a small size, so large objects cannot be allocated within a TLAB. Large objects must be allocated directly from the heap, which requires extra time because of the synchronization. - At this point, the JVM has a choice. One option is to “retire” the TLAB and allocate a new one for the thread. Since the TLAB is just a section within eden, the retired TLAB will be cleaned at the next young collection and can be reused subsequently. - Consider the case where a TLAB is 100 KB, and 75 KB has already been allocated. If a new 30 KB allocation is needed, the TLAB can be retired, which wastes 25 KB of eden space. Or the 30 KB object can be allocated directly from the heap, and the thread can hope that the next object that is allocated will fit in the 25 KB of space that is still free within the TLAB. - By default, the size of a TLAB is based on three things: the number of threads in the application, the size of eden, and the allocation rate of threads. Hence two types of applications may benefit from tuning the TLAB parameters: applications that allocate a lot of large objects, and applications that have a relatively large number of threads compared to the size of eden. - What can be done instead is to monitor the TLAB allocation to see if any allocations occur outside of the TLABs. - Monitoring the TLAB allocation is another case where Java Flight Recorder is much more powerful than other tools. Figure 6-9 shows a sample of the TLAB allocation screen from a JFR recording. - In the open source version of the JVM (without JFR), the best thing to do is monitor the TLAB allocation by adding the -XX:+PrintTLAB flag to the command line. - The size of the TLABs can be set explicitly using the flag -XX:TLABSize=N (the default value, 0, means to use the dynamic calculation previously described). That flag sets only the initial size of the TLABs; to prevent resizing at each GC, add -XX:-ResizeTLAB (the default for that flag is true on most common platforms). This is the easiest (and, frankly, the only really useful) option for exploring the performance of adjusting the TLABs. - In the TLAB logging output, the refill waste value gives the current threshold for that decision: if the TLAB cannot accommodate a new object that is larger than that value, then the new object will be allocated in the heap. If the object in question is smaller than that value, the TLAB will be retired. - Applications that allocate a lot of large objects may need to tune the TLABs (though often using smaller objects in the application is a better approach). - Humongous - G1 region sizes G1 divides the heap into a number of regions, each of which has a fixed size. The region size is not dynamic; it is determined at startup based on the minimum size of the heap (the value of Xms). - The minimum region size is 1 MB. If the minimum heap size is greater than 2 GB, the size of the regions will be set according to this formula (using log base 2): region_size = 1 << log(Initial Heap Size / 2048); In short, the region size is the smallest power of 2 such that there are close to 2,048 regions when the initial heap size is divided. - the region size is always at least 1 MB and never more than 32 MB. - Less than 4 GB    1 MB  - Larger than 64 GB    32 MB  - The value given here should be a power of 2 (e.g., 1 MB or 2 MB); - G1 allocation of humongous objects If the G1 region size is 1 MB and a program allocates an array of 2 million bytes, the array will not fit within a single G1 region. But these humongous objects must be allocated in contiguous G1 regions. If the G1 region size is 1 MB, then to allocate a 3.1 MB array, G1 must find four contiguous regions within the old generation in which to allocate the array. (The rest of the last region will remain empty, wasting 0.9 MB of space.) - The humongous object will be collected during the concurrent G1 cycle. On the bright side, the humongous object can be freed quickly since it is the only object in the regions it occupies. Humongous objects are freed during the cleanup phase of the concurrent cycle (rather than during a mixed GC). - Because the heap could not be expanded to accommodate the new humongous object, G1 had to perform a full GC to compact the heap in order to provide the contiguous regions needed to fulfill the request, Without the additional logging provided by enabling PrintAdaptiveSizePolicy, the standard G1 GC log does not provide enough information to diagnose this situation. - A better next step is to reduce the size of those objects rather than tune the JVM around them. - G1 considers an object to be humongous if it will fill more than 50% of a region. - G1 regions are sized in powers of 2, starting at 1 MB. Heaps that have a very different maximum size than initial size will have too many G1 regions; the G1 region size should be increased in that case. - Applications that allocate objects larger than half the size of a G1 region should increase the G1 region size, so that the objects can fit within a G1 region. - Although the flag has been carried forward since those versions and is still present, it is no longer recommended (though it is not yet officially deprecated). The problem with this flag is that it hides the actual tunings it adopts, making it quite hard to figure out what the JVM is actually setting. - ergonomically - Some of the values it sets are now set ergonomically based on better information about the machine running the JVM, so there are actually cases where enabling this flag hurts performance. - scavenging - The AggressiveHeap flag is a legacy attempt to set a number of heap parameters to values that make sense for a single JVM running on a very large machine. - Values set by this flag are not adjusted as JVM technology improves, so its usefulness in the long run is dubious (even though it still is often used). # Cracking the Coding Interview, Fourth Edition: 150 Programming Interview Questions and Solutions - So how do you make yourself sound good without being arrogant? By being specific! - Consider an example: » Candidate #1: “I basically did all the hard work for the team ” » Candidate #2: “I implemented the file system, which was considered one of - the most challenging components because …” Candidate #2 not only sounds more impressive, but she also appears less arrogant - blabbers - When a candidate blabbers on about a problem, - Structure your responses using S A R : Situation, Action, Response - 3 Write pseudo-code first, but make sure to tell your interviewer that you’re writing pseudo-code! Otherwise, he/she may think that you’re never planning to write “real” code, and many interviewers will hold that against you 4 Write your code, not too slow and not too fast - Step 1: Ask Questions Technical problems are more ambiguous than they might appear, so make sure to ask ques- tions to resolve anything that might be unclear or ambiguous You may eventually wind up - 0 and 130 How do we solve this? Just create an array with 130 elements and count the num- ber of ages at each value - APPROACH IV: BASE CASE AND BUILD Description: Solve the algorithm first for a base case (e g , just one element) Then, try to solve it for elements one and - permutations - NOTE: Base Case and Build Algorithms often lead to natural recursive algorithms # Java 8 Lambdas - Looking under the covers a little bit, the for loop is actually syntactic sugar that wraps up the iteration and hides it. - conflates what you are doing with how you are doing it. - long count = allArtists.stream()                        .filter(artist -> artist.isFrom("London"))                        .count(); - filter that build up the Stream recipe but don’t force a new value to be generated at the end are referred to as lazy. - Methods such as count that generate a final value out of the Stream sequence are called eager. - If we add the same printout to a stream that has a terminal step, such as the counting operation from Example 3-3, then we will see the names of our artists printed out (Example 3-6). - It’s very easy to figure out whether an operation is eager or lazy: look at what it returns. If it gives you back a Stream, it’s lazy; if it gives you back another value or void, then it’s eager. - Stream functions are lazy, you do need to use an eager operation such as collect at the end of a sequence of chained method calls. - Even the simplest application is still likely to have application code that could benefit from code as data. - It’s a good idea to use the primitive specialized functions wherever possible because of the performance benefits. - we map each track to its length, using the primitive specialized mapToInt method. Because this method returns an IntStream, we can call summaryStatistics, which calculates statistics such as the minimum, maximum, average, and sum values on the IntStream. - A BinaryOperator is special type of BiFunction for which the arguments and the return type are all the same. - you might conclude that this is a code smell - but compared to many other programming platforms, binary compatibility has been viewed as a key Java strength. - The Optional class lets you avoid using null by modeling situations where a value may not be present. - return albums.collect(groupingBy(album -> album.getMainMusician())); } - makes our intent much clearer using streams and collectors. - String result =     artists.stream()               .map(Artist::getName)               .collect(Collectors.joining(", ", "[", "]")); Here, we use a map to extract the artists’ names and then collect the Stream using Collectors.joining. This method is a convenience for building up strings from streams. - It lets us provide a delimiter (which goes between elements), a prefix for our result, and a suffix for the result. - public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) {     return albums.collect(groupingBy(album -> album.getMainMusician(),                                      counting())); } This form of groupingBy divides elements into buckets. Each bucket gets associated with the key provided by the classifier function: getMainMusician. The groupingBy operation then uses the downstream collector to collect each - Each collector is a recipe for building a final value. - the boffins at Oracle have thought of this use case and provided a collector called mapping. - In both of these cases, we’ve used a second collector in order to collect a subpart of the final result. These collectors are called downstream collectors. In the same way that a collector is a recipe for building a final value, a downstream collector is a recipe for building a part of that value, which is then used by the main collector. - StringBuilder reduced =     artists.stream()            .map(Artist::getName)            .reduce(new StringBuilder(), (builder, name) -> {                    if (builder.length() > 0)                        builder.append(", ");                    builder.append(name);                    return builder;                }, (left, right) -> left.append(right)); reduced.insert(0, "["); reduced.append("]"); String result = reduced.toString(); I had hoped that last refactor would help us - some code that looks vaguely sane, - Collector is generic, so we need to determine a few types to interact with: The type of the element that we’ll be collecting, a String Our accumulator type, StringCombiner, which you’ve already seen The result type, also a String Example 5-25. How to define a collector over strings public class StringCollector implements Collector<String, StringCombiner, String> { A Collector is composed - String result =         artists.stream()                 .map(Artist::getName)                 .collect(Collectors.reducing(                     new StringCombiner(", ", "[", "]"),                     name -> new StringCombiner(", ", "[", "]").add(name),                     StringCombiner::merge))                 .toString(); This is very similar to the reduce-based implementation I covered in Example 5-20, which is what you might expect given the name. - public Artist getArtist(String name) {     return artistCache.computeIfAbsent(name, this::readArtistFromDB); } - the new compute and computeIfPresent methods on the Map interface are useful for these cases. - Method references are a lightweight syntax for referring to methods and look like this: ClassName::methodName. - Collectors let us compute the final values of streams and are the mutable analogue of the reduce method. - Map enhancements. Efficiently calculate a Fibonacci sequence using just the computeIfAbsent method on a Map. By “efficiently,” I mean that you don’t repeatedly recalculate the Fibonacci sequence of smaller numbers. - The changes to your code are surprisingly unobtrusive, - Concurrency arises when two tasks are making progress at overlapping time periods. Parallelism arises when two tasks are happening at literally the same time, such as on a multicore CPU. - The goal of parallelism is to reduce the runtime of a specific task by breaking it down into smaller components and performing them in parallel. - get-go. - you can call the parallelStream method in order to create a parallel stream from the get-go. Let’s look at a - public int serialArraySum() {     return albums.stream()                  .flatMap(Album::getTracks)                  .mapToInt(Track::getLength)                  .sum(); - We go parallel by making the call to parallelStream, as shown in Example 6-2; all the rest of the code is identical. Going parallel just works. Example 6-2. Parallel summing of album track lengths public int parallelArraySum() {     return albums.parallelStream()                  .flatMap(Album::getTracks)                  .mapToInt(Track::getLength) - The kinds of problems that parallel stream libraries excel at are those that involve simple operations processing a lot of data, such as simulations. - Monte Carlo simulations work by running the same simulation many times over with different random seeds on every run. - private void printResults() {         results.entrySet()                .forEach(System.out::println); - a -     private Runnable makeJob() {         return () -> {             ThreadLocalRandom random = ThreadLocalRandom.current(); - The streams framework deals with any necessary synchronization itself, so there’s no need to lock your data structures. - If a pipeline has calls to both parallel and sequential, the last call wins. - Packing Primitives are faster to operate on than boxed values. Number of cores The extreme case here is that you have only a single core available to operate upon, so it’s not worth going parallel. - The more time spent operating on each element in the stream, the better performance you’ll get from going parallel. - This gives us a good insight into what is going on under the hood without having to understand all the details of the framework. - private int addIntegers(List<Integer> values) {     return values.parallelStream()                  .mapToInt(i -> i)                  .sum(); } Under the hood, parallel streams back onto the fork/join framework. - The fork stage recursively splits up a problem. Then each chunk is operated upon in parallel. Finally, the join stage merges the results back together. - Ideally, we want to spend as much of our time as possible in leaf computation work because it’s the perfect case for parallelism. - groups by performance characteristics: The good An ArrayList, an array, or the IntStream.range constructor. These data sources all support random access, which means they can be split up arbitrarily with ease. The okay The HashSet and TreeSet. You can’t easily decompose these with perfect amounts of balance, but most of the time it’s possible to do so. The bad Some data structures just don’t split well; for example, they may take O(N) time to decompose. Examples here include a LinkedList, which is computationally hard to split in half. Also, Streams.iterate and BufferedReader.lines have unknown length at the beginning, so it’s pretty hard to estimate when to split these sources. - Stateless operations need to maintain no concept of state over the whole operation; stateful operations have the overhead and constraint of maintaining state. If you can get away with using stateless operations, then you will get better parallel performance. - public static double[] parallelInitialize(int size) {     double[] values = new double[size];     Arrays.parallelSetAll(values, i -> i);     return values; } The - parallelPrefix operation, on the other hand, is much more useful for performing accumulation-type calculations over time series of data. It mutates an array, replacing each element with the sum of that element and its predecessors. I use the term “sum” loosely—it doesn’t need to be addition; it could be any BinaryOperator. - Data parallelism is a way to split up work to be done on many cores at the same time. - The five main factors influencing performance are the data size, the source data structure, whether the values are packed, the number of available cores, and how much processing time is spent on each element. - A wealth of material has been written on how to test and debug computer programs, - Test-Driven Development by <NAME> - Growing Object-Oriented Software, Guided by Tests by <NAME> and Nat - The process of refactoring code to take advantage of lambdas has been given the snazzy name point lambdafication (pronounced lambda-fi-cation, practitioners of this process being “lamb-di-fiers” or “responsible developers”). - This antipattern can be easily solved by passing in code as data. Instead of querying an object and then setting a value on it, you can pass in a lambda expression that represents the relevant behavior by computing a value. - A key OOP concept is to encapsulate local state, such as the level of the logger. This isn’t normally encapsulated very well, as isDebugEnabled exposes its state. If you use the lambda-based approach, then the code outside of the logger doesn’t need to check the level at all. - ThreadLocal.withInitial(() -> database.lookupCurrentAlbum()); - when reading the code, the signal-to-noise ratio is lower. - This code smell crops up in situations where your code ends up in repetitive boilerplate - Even though test doubles are frequently referred to as mocks, actually both stubs and mocks are types of test double. The difference is that mocks allow you to verify the code’s behavior. The best place to understand more about this is Martin - supports our familiar friend: passing code as data. - artist.getName().startsWith("The"))            .map(artist -> artist.getNationality())            .peek(nation -> System.out.println("Found nationality: " + nation))            .collect(Collectors.<String>toSet()); - a - a breakpoint can be set on the body of the peek method. In this case, peek can just have an empty body that you set a breakpoint in. Some debuggers won’t let you set a breakpoint in an empty body, in which case I just map a value to itself - The peek method is very useful for logging out intermediate values when debugging. - The critical design tool for software development is a mind well educated in design principles. It is not…technology. - As the Agile software movement has made testing of applications more important, the issues with the singleton pattern have made it an antipattern: a pattern you should never use. - macros. Did I say “lazy”? I meant focused on improving my productivity. - the command pattern. It’s frequently used in implementing component-based GUI systems, undo functions, thread pools, transactions, and wizards. - The strategy pattern is a way of changing the algorithmic behavior of software based upon a runtime decision. - An example algorithm we might want to encapsulate is compressing files. We’ll give our users the choice of compressing our files using either the zip algorithm or the gzip algorithm and implement a generic Compressor class that can compress using either algorithm. - Compressor zipCompressor = new Compressor(ZipOutputStream::new); zipCompressor.compress(inFile, outFile); - a - The observer pattern is another behavioral pattern that can be improved and - In the observer pattern, an object, called the subject, maintains a list of other objects, which are its observers. When the state of the subject changes, its observers are notified. It is heavily used in MVC-based GUI toolkits in order to allow view components to be updated when state changes in the model without coupling the two classes together. - The template method pattern is designed for these kinds of situations. Your overall algorithm design is represented by an abstract class. This has a series of abstract methods that represent customized steps in the algorithm, while any common code can be kept in this class. - a - As a bank, we’re going to be giving out loans to members of the public, companies, and employees. - We can start to model this in code with an abstract LoanApplication class that controls the algorithmic structure and holds common code for reporting the findings of the loan application. - What the template method pattern is really trying to do is compose a sequence of method calls in a certain order. - canonical - It’s usual to split up DSLs into two different categories: internal and external. - For example, Cascading Style Sheets (CSS) and regular expressions are commonly used external DSLs. - BDD is a variant of test-driven development (TDD) that shifts the emphasis onto talking about the behavior of the program rather than simply the tests that it needs to pass. - sneaky - been a bit sneaky here and used double braces at the beginning and end of the class definition: - public class StackSpec {{     ... }} These start an anonymous constructor that lets us execute an arbitrary block of Java code, so it’s really just like writing out the constructor in full, but with a bit less boilerplate. I could have written the following instead: public class StackSpec {     public StackSpec() {         ...     } } There’s a lot more work involved in implementing a complete BDD - Every class or method in your program should have only a single reason to change. - This is part of the idea of a design exhibiting strong cohesion. A class is cohesive if its methods and fields should be treated together because they are closely related. If you tried to divide up a cohesive class, you would result in accidentally coupling the classes that you have just created. - So, we can use higher-order functions in order to help us easily implement the single responsibility principle. - Software entities should be open for extension, but closed for modification. — <NAME> - The overarching goal of the open/closed principle is similar to that of the single responsibility principle: to make your software less brittle to change. - Again, the problem is that a single feature request or change to your software can ripple through the code base in a way that is likely to introduce new bugs. - The open/closed principle is an effort to avoid that problem by ensuring that existing classes can be extended without their internal implementation being modified. - Its static withInitial method is a higher-order function that takes a lambda expression that represents a factory for producing an initial value. - This implements the open/closed principle because we can get new behavior out of ThreadLocal without modifying it. We pass in a different factory method to withInitial and get an instance of ThreadLocal with different behavior. - We can also generate completely different behavior by passing in a different lambda expression. - The term “immutability” can have two potential interpretations: observable immutability or implementation immutability. Observable immutability means that from the perspective of any other object, a class is immutable; implementation immutability means that the object never mutates. Implementation immutability implies observable immutability, but the inverse isn’t necessarily true. - A good example of a class that proclaims its immutability but actually is only observably immutable is java.lang.String, as it caches the hash code that it computes the first time its hashCode method is called. This is entirely safe from the perspective of other classes because there’s no way for them to observe the difference between it being computed in the constructor every time or cached. - There is no internal state to mutate, so they can be shared between different threads. - is fairly outmoded. - the open/closed principle is really just a usage of polymorphism. - Abstractions should not depend on details; details should depend on abstractions. - The goal of the dependency inversion principle is to allow programmers to write high-level business logic that is independent of low-level glue code. - So, we introduce an abstraction for reading information and an abstraction for writing information. The implementation of our accumulation module depends upon these abstractions. We can pass in the specific details of these implementations at runtime. This is the dependency inversion principle at work. In the context of - Example 8-44. The definition of withLinesOf private <T> T withLinesOf(Reader input,                           Function<Stream<String>, T> handler,                           Function<IOException, RuntimeException> error) {     try (BufferedReader reader = new BufferedReader(input)) {         return handler.apply(reader.lines());     } catch (IOException e) {         throw error.apply(e);     } } withLinesOf takes in a reader that handles the underlying file I/O. - Nonblocking I/O—or, as it’s sometimes called, asynchronous I/O—can be used to process many concurrent network connections without having an individual thread service each connection. - a - newline.splitAsStream(buffer.toString()) - newline. Conveniently, Java’s Pattern class has had a splitAsStream method added in Java 8 that lets us split a String using the regular expression and have a stream of values, consisting of the values between each split. - If you want to end your chain with a block of code that returns nothing, such as a Consumer or Runnable, then take a look at thenAccept and thenRun. - a - Transforming the value of the CompletableFuture, a bit like using the map method on Stream, can be achieved using thenApply. - When trying to figure out what is happening with your CompletableFuture, you can use the isDone and isCompletedExceptionally methods. - CompletableFuture is really useful for building up concurrent work, but it’s not the only game in town. - Reactive programming is actually a form of declarative programming that lets us program in terms of changes and data flows that get automatically propagated. - You can think of a spreadsheet as a commonly used example of reactive programming. If you enter =B1+5 in cell C1, it tells the spreadsheet to add 5 to the contents of cell B1 and put the result in C1. - A CompletableFuture represents an IOU for a value. They can be easily composed and combined using lambdas. - Unfortunately, over the years Java has acquired a bit of a reputation as a staid development choice that has failed to evolve with the times, in part because it has been popular for a long period of time; familiarity # Java Generics and Collections - reputed - Einstein is reputed to have said, “Everything should be as simple as possible but no simpler”. - sparked some controversy. - roundabouts: - reify - Newton is reputed to have said, “If I have seen farther than others, it is because I stand on the shoulders of giants”. - As Hamming said of computer scientists, “Instead of standing on each other’s shoulders, we stand on each other’s toes.”) - increased use of collections in favor of arrays. In Part II, we describe - a problem known as code bloat. - Why does the argument have type List<Integer> and not List<int>? Because type parameters must always be bound to reference types, not primitive types. - Look Out for This! One subtlety of boxing and unboxing is that == is defined differently on primitive and on reference - So both of the following assertions succeed using Sun’s JVM: List<Integer> bigs = Arrays.asList(100,200,300); assert sumInteger(bigs) == sum(bigs); assert sumInteger(bigs) != sumInteger(bigs); // not recommended In the - example, we have the following: List<Integer> smalls = Arrays.asList(1,2,3); assert sumInteger(smalls) == sum(smalls); assert sumInteger(smalls) == sumInteger(smalls); // not recommended This is because 6 is smaller than 128, so boxing the value 6 always - exactly the same object. In general, it is not specified whether boxing the same value twice should return identical or distinct objects, so the inequality assertion shown earlier may either fail or succeed depending on the implementation. Even for small values, for which - It is clearer and cleaner to use equals rather than == to compare values of reference type, such as Integer or String. - The foreach loop can be applied to any object that implements the interface Iterable<E> (in package java.lang), which in turn refers to the interface Iterator<E> (in package java.util). - public static <T> List<T> toList(T[] arr) { List<T> list = new ArrayList<T>(); for (T elt : arr) list.add(elt); return list; - This is indicated by writing <T> at the beginning of the method signature, which declares T as a new type variable. A method which declares a type variable in this way is called a generic method. - The vararg feature permits a special, more convenient syntax for the case in which the last argument of a method is an array. To use this feature, we replace T[] with T… in the method declaration: - public static <T> List<T> toList(T... arr) { List<T> list = new ArrayList<T>(); for (T elt : arr) list.add(elt); return list; } } Now the method may be invoked as follows: List<Integer> ints = Lists.toList(1, 2, 3); List<String> words = Lists.toList("hello", "world"); This is just shorthand for - We clarify our code by liberal use of the assert statement. - Java, one type is a subtype of another if they are related by an extends or implements clause. - Subtyping is transitive, meaning that if one type is a subtype of a second, and the second is a subtype of a third, then the first is a subtype of the third. - Substitution Principle: a variable of a given type may be assigned a value of any subtype of that type, and a method with a parameter of a given type may be invoked with an argument of any subtype of that type. - Substitution Principle, if we have a collection of numbers, we may add an integer or a double to it, because Integer and Double are subtypes of - List<Integer> is not a subtype of List<Number>, and - where List<Integer> is a subtype of itself, and we also have that List<Integer> is a subtype of Collection<Integer>. - (because List<Integer> is a subtype of List<? extends Number>), - In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure. - List<Integer>, which is a subtype of List<? extends Number> (since Integer is a subtype of Number, as required by the extends wildcard). - Always use wildcards where you can in a signature, - The Get and Put Principle: use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don’t use a wildcard when you both get and put. - In Java, array subtyping is covariant, meaning that type S[] is considered to be a subtype of T[] whenever S is a subtype of T. - In contrast, the subtyping relation for generics is invariant, meaning that type List<S> is not considered to be a subtype of List<T>, except in the trivial case where S and T are identical. - Wildcards reintroduce covariant subtyping for generics, in that type List<S> is considered to be a subtype of List<? extends T> when S is a subtype of T. Here is a third variant of the fragment: List<Integer> ints = Arrays.asList(1,2,3); List<? extends Number> nums = ints; nums.set(2, 3.14); // compile-time error assert ints.toString().equals("[1, 2, 3.14]"); // uh oh! - The assignment violates the Get and Put Principle, because you cannot put a value into a type declared with an extends wildcard. - Wildcards also introduce contravariant subtyping for generics, in that type List<S> is considered to be a subtype of List<? super T> when S is a supertype of T (as opposed to a subtype). - Detecting problems at compile time rather than at run time brings two advantages, one minor and one major. The minor advantage is that it is more efficient. The system does not need to carry around a description of the element type at run time, and the system does not need to check against this description every time an assignment into an array is performed. The major advantage is that a common family of errors - not significant and elements may not be repeated), and a number of representations are available, including arrays, linked lists, trees, and hash tables. - Nonetheless, there are a few cases where arrays are preferred over collections. Arrays of primitive type are much more efficient since they don’t involve boxing; and assignments into such an array need not check for an array store exception, because arrays of primitive type do not have subtypes. - Following Leanpub’s motto “Publish Early, Publish Often”, I - the new Date and Time API (application program interfaces), feel quite familiar and can be used immediately by an experienced Java developer. # Misc - The intent of the SINGLETON pattern is to ensure that a class has only one instance and to provide a global point of access to it. - Don’t let SINGLETONs become a fancy way to create global variables. The - I can help you avoid some of the hidden coral reefs that lie beneath the Sea of Apple, and help you find the fair winds to keep your sails full. - No language is perfect, but some are excellent. - with the goal of bringing object-oriented and functional programming into one coherent whole. - Clojure embodies a powerful vision for how programming should be done. - I assume that you are well versed in object-oriented programming and you can read Java code. - I hope you find functional programming as seductive as I did. - chunks of code - a significant amount of example code - programming is a better fit for many of the unique challenges of our time, - both FP and OOP are tools, not panaceas. - can saturate CPU resources - Java NIO instead of blocking java.net.Socket may also improve an application’s performance by - test that your methods behave properly when passed negative, zero, and positive values for each numerical parameter. - The problem is easy to fix. Simply compare i % 2 to 0 rather than to 1, and reverse the sense of the comparison: public static boolean isOdd(int i) {     return i % 2 != 0; } - If you are using the isOdd method in a performance-critical setting, you would be better off using the bitwise AND operator (&) in place of the remainder operator: public static boolean isOdd(int i) {     return (i & 1) != 0; } - The second version may run much faster than the first, depending on what platform and virtual machine you are using, and is unlikely to run slower. As a general rule, the divide and remainder operations are slow compared to other arithmetic and logical operations. - It's a bad idea to optimize prematurely, - In summary, think about the signs of the operands and of the result whenever you use the remainder operator. - not all decimals can be represented exactly using binary floating-point. - If you are using release 5.0 or a later release, you might be tempted to fix the program by using the printf facility to set the precision of the output: - Binary floating-point is particularly ill-suited to monetary calculations, <file_sep>/Yaya-Englisth.md --- title: English List --- 1. fish [Animal] 1. bird [Animal] 1. cat [Animal] 1. dog [Animal] 1. bat [Animal] 1. puppy [Animal] 1. giraffe [Animal] 1. elephant [Animal] 1. hippo [Animal] 1. monkey [Animal] 1. mouse [Animal] 1. snake [Animal] 1. slug [Animal] 1. snail [Animal] 1. fly [Animal] 1. owl [Animal] 1. kitty [Animal] 1. puppy [Animal] 1. crocodile [Animal] 1. turtle [Animal] 1. penguin [Animal] 1. horse [Animal] 1. sheep [Animal] 1. cow [Animal] 1. chicken [Animal] 1. hen [Animal] 1. duck [Animal] 1. bear [Animal] 1. tiger [Animal] 1. monster [Animal] 1. lion [Animal] 1. pig [Animal] 1. rabbit [Animal] 1. shark [Animal] 1. bee [Animal] 1. grasshopper [Animal] 1. spider [Animal] 1. octopus [Animal] 1. dinosaur [Animal] 1. butterfly [Animal] 1. dragonfly [Animal] 1. dragon [Animal] 1. ladybug [Animal] 1. squirrel [Animal] 1. worm [Animal] 1. frog [Animal] 1. wolf [Animal] 1. fox [Animal] 1. fox cub [Animal] 1. whale [Animal] 1. monster [Animal] 1. zebra [Animal] 1. kangaroo [Animal] 1. koala [Animal] 1. One [Number] 1. Two [Number] 1. Three [Number] 1. Four [Number] 1. Five [Number] 1. Six [Number] 1. Seven [Number] 1. Eight [Number] 1. Nine [Number] 1. Ten [Number] 1. Eleven [Number] 1. Twelve [Number] 1. Thirteen [Number] 1. Fourteen [Number] 1. Fifteen [Number] 1. Sixteen [Number] 1. Seventeen [Number] 1. Eighteen [Number] 1. Nineteen [Number] 1. Twenty [Number] 1. Apple [Fruit] 1. Orange [Fruit] 1. banana [Fruit] 1. lemon [Fruit] 1. lychee [Fruit] 1. plum [Fruit] 1. grape [Fruit] 1. peach [Fruit] 1. pear [Fruit] 1. watermelon [Fruit] 1. strawberry [Fruit] 1. blueberry [Fruit] 1. pineapple [Fruit] 1. cookie [Food] 1. cake [Food] 1. coffee [Food] 1. pepper [Food] 1. eggplant [Food] 1. carrot [Food] 1. cucumber [Food] 1. tomato [Food] 1. potato [Food] 1. jam [Food] 1. egg [Food] 1. rice [Food] 1. noodle [Food] 1. pasta [Food] 1. pizza [Food] 1. onion [Food] 1. candy [Food] 1. chocolate [Food] 1. ice-cream [Food] 1. happy [Mood] 1. sad [Mood] 1. tired [Mood] 1. angry [Mood] 1. fine [Mood] 1. red [Color] 1. blue [Color] 1. black [Color] 1. green [Color] 1. pink [Color] 1. purple [Color] 1. black [Color] 1. white [Color] 1. silver [Color] 1. gold [Color] 1. gray [Color] 1. brown [Color] 1. yellow [Color] 1. organge [Color] 1. square [Shape] 1. rectangle [Shape] 1. circle [Shape] 1. diamond [Shape] 1. star [Shape] 1. cloud [Shape] 1. sun [Nature] 1. moon [Nature] 1. star [Nature] 1. table [Object] 1. chair [Object] 1. bag [Object] 1. door [Object] 1. window [Object] 1. boot [Object] 1. book [Object] 1. umbrella [Object] 1. pen [Object] 1. pencil [Object] 1. glue [Object] 1. eraser [Object] 1. scissor [Object] 1. crayon [Object] 1. phone [Object] 1. kindle [Object] 1. iPad [Object] 1. mom [Human] 1. daddy [Human] 1. grandma [Human] 1. grandpa [Human] 1. girl [Human] 1. boy [Human] 1. I [Human] 1. name [Human] 1. farmer [Human] 1. lady [Human] 1. teacher [Human] 1. baby [Human] 1. you [Adverb] 1. are [Adverb] 1. hello [Adverb] 1. good [Adverb] 1. can [Adverb] 1. like [Adverb] 1. want [Adverb] 1. bush [Nature] 1. tree [Nature] 1. grass [Nature] 1. water [Nature] 1. flower [Nature] 1. farm [place] 1. barn [place] 1. classroom [place] 1. house [place] 1. toy [Toy] 1. doll [Toy] 1. puzzle [Toy] 1. yoyo [Toy] 1. car [transportation] 1. bus [transportation] 1. ship [transportation] 1. boat [transportation] 1. plane [transportation] 1. hungry [adjective] 1. thirsty [adjective] 1. small [adjective] 1. little [adjective] 1. big [adjective] 1. horn [Organs] 1. tail [Organs] 1. leg [Organs] 1. hand [Organs] 1. head [Organs] 1. nose [Organs] 1. ear [Organs] 1. eye [Organs] 1. face [Organs] 1. back [Organs] 1. knee [Organs] 1. tummy [Organs] 1. run [verb] 1. walk [verb] 1. sleep [verb] 1. drink [verb] 1. eat [verb] <file_sep>/au.md # Links - [Pay calculator](http://www.paycalculator.com.au)<file_sep>/Misc12.md Logic that deals with storing or retrieving data is part of the model. Logic that deals with formatting the data to display to the user is part of the view. The controller sits between the model and the view and connects them. The controller responds to user interaction, updating the data in the model and providing the view with the data that it requires. <script src="angular.js"></script> <script> var model = { user: "Adam", items: [{ action: "Buy Flowers", done: false }, { action: "Get Shoes", done: false }, { action: "Collect Tickets", done: true }, { action: "Call Joe", done: false }] }; var todoApp = angular.module("todoApp", []); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; }); </script> </head> <body ng-controller="ToDoCtrl"> <div class="page-header"> <h1>To Do List</h1> </div> One of the main purposes of the controller is to provide views with the data they require. You won’t always want views to have access to the complete model, so you use the controller to explicitly select those portions of the data that are going to be available, known as the scope. The argument to my controller function is called $scope—that is to say, the $sign followed Inserting Model Values AngularJS uses double-brace characters ({{ and }}) to denote a data binding expression. The content of the expression is evaluated as JavaScript, limited to the data and functions assigned to the scope by the controller. I You should use expressions only to perform simple operations to prepare data values for display. Don’t use data bindings to perform complex logic or to manipulate the model; that’s the job of the controller. You will often encounter logic that is hard to classify as being suitable for the view or the controller, and it can be difficult to work out what to do. My advice is to not worry about it. Make a best guess in order to preserve development momentum and move the logic later if need be. Using Directives Expressions are also used with directives, which tell AngularJS how you want content to be processed. In the listing, I used the ng-repeat attribute, which applies a directive that tells AngularJS to generate the element it is applied to and its contents for each object in a collection, as follows: ... <tr ng-repeat="item in todo.items"> <td>{{item.action}}</td><td>{{item.done}}</td> </tr> <tr ng-repeat="item in todo.items"> <td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> <td>{{item.done}}</td> </tr> ... I have added a new td element to contain a check box input element. The important addition is the ng-modelattribute, which tells AngularJS to create a two-way binding between the value of the input element and the done property of the corresponding data object (the one that the ng-repeatdirective assigned to item when generating the elements). Creating and Using Controller Behaviors Controllers define behaviors on the scope. Behaviors are functions that operate on the data in the model to implement the business logic in the application. The behaviors defined by a controller support a view to display data to the user and to update the model based on user interactions. To demonstrate a simple behavior, I am going to change the label displayed to the right of the header in todo.html so that it displays only the number of incomplete to-do items. You can see the changes required to do this in Listing 2-7. (I also removed the column that contains the trueand false values, which I required only to demonstrate that data bindings reflected changes in the data model.) Listing 2-7. Defining and Using a Controller Behavior in the todo.html File <!DOCTYPE html> <html ng-app="todoApp"> <head> <title>TO DO List</title> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script src="angular.js"></script> <script> var model = { user: "Adam", items: [{ action: "Buy Flowers", done: false }, { action: "Get Shoes", done: false }, { action: "Collect Tickets", done: true }, { action: "Call Joe", done: false }] }; var todoApp = angular.module("todoApp", []); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; $scope.incompleteCount = function () { var count = 0; angular.forEach($scope.todo.items, function (item) { if (!item.done) { count++ } }); return count; } }); </script> </head> <body ng-controller="ToDoCtrl"> <div class="page-header"> <h1> {{todo.user}}'s To Do List <span class="label label-default" ng-hide="incompleteCount() == 0"> {{incompleteCount()}} </span> </h1> </div> <div class="panel"> <div class="input-group"> <input class="form-control" /> <span class="input-group-btn"> <button class="btn btn-default">Add</button> </span> </div> <table class="table table-striped"> <thead> <tr> <th>Description</th> <th>Done</th> </tr> </thead> <tbody> <tr ng-repeat="item in todo.items"> <td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> </tr> </tbody> </table> </div> </body> </html> Behaviors are defined by adding functions to the $scope object that is passed to the controller function. In the listing, I have defined a function that returns the number of incomplete items, which I determine by enumerating the objects in the $scope.todo.itemsarray and counting the ones whose doneproperty is false. I also used the behavior in conjunction with a directive, like this: ... <span class="label default" ng-hide="incompleteCount() == 0"> {{incompleteCount()}} </span> ... The ng-hidedirective will hide the element it is applied to—and its content elements—if the expression that is assigned as the attribute value evaluates to true. In this case, I call the incompleteCountbehavior and check to see whether the number of incomplete items is zero; if it is, then the label that displays the number of items on the list is hidden from the user. Building on Behaviors in the todo.html File <!DOCTYPE html> <html ng-app="todoApp"> <head> <title>TO DO List</title> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script src="angular.js"></script> <script> var model = { user: "Adam", items: [{ action: "Buy Flowers", done: false }, { action: "Get Shoes", done: false }, { action: "Collect Tickets", done: true }, { action: "Call Joe", done: false }] }; var todoApp = angular.module("todoApp", []); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; $scope.incompleteCount = function () { var count = 0; angular.forEach($scope.todo.items, function (item) { if (!item.done) { count++ } }); return count; } $scope.warningLevel = function () { return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; } }); </script> </head> <body ng-controller="ToDoCtrl"> <div class="page-header"> <h1> {{todo.user}}'s To Do List <span class="label label-default" ng-class="warningLevel()" ng-hide="incompleteCount() == 0"> {{incompleteCount()}} </span> </h1> </div> <!--...elements omitted for brevity...--> </body> </html> I have defined a new behavior called warningLevel, which returns the name of a Bootstrap CSS class based on the number of incomplete to-do items, which is obtained by calling the incompleteCountbehavior. This approach reduces the need to duplicate logic in the controller and, as you’ll see in Chapter 25, can help simplify the process of unit testing. I have applied the warningLevelbehavior using the ng-class directive, as follows: ... <span class="label" ng-class="warningLevel()"ng-hide="incompleteCount() == 0"> Responding to User Input in the todo.html File <!DOCTYPE html> <html ng-app="todoApp"> <head> <title>TO DO List</title> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script src="angular.js"></script> <script> var model = { user: "Adam", items: [{ action: "Buy Flowers", done: false }, { action: "Get Shoes", done: false }, { action: "Collect Tickets", done: true }, { action: "Call Joe", done: false }] }; var todoApp = angular.module("todoApp", []); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; $scope.incompleteCount = function () { var count = 0; angular.forEach($scope.todo.items, function (item) { if (!item.done) { count++ } }); return count; } $scope.warningLevel = function () { return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; } $scope.addNewItem = function (actionText) { $scope.todo.items.push({ action: actionText, done: false }); } }); </script> </head> <body ng-controller="ToDoCtrl"> <div class="page-header"> <h1> {{todo.user}}'s To Do List <span class="label label-default" ng-class="warningLevel()" ng-hide="incompleteCount() == 0"> {{incompleteCount()}} </span> </h1> </div> <div class="panel"> <div class="input-group"> <input class="form-control" ng-model="actionText" /> <span class="input-group-btn"> <button class="btn btn-default" ng-click="addNewItem(actionText)">Add</button> </span> </div> <table class="table table-striped"> <thead> <tr> <th>Description</th> <th>Done</th> </tr> </thead> <tbody> <tr ng-repeat="item in todo.items"> <td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> </tr> </tbody> </table> </div> </body> </html> I have added a behavior called addNewItem that takes the text of a new to-do item and adds an object to the data model, using the text as the value for the action property and setting the doneproperty to false, like this: ... $scope.addNewItem = function(actionText) { $scope.todo.items.push({ action: actionText, done: false}); } Adding Filtering to the todo.html File ... <tbody> <tr ng-repeat="item in todo.items | filter:{done: false} | orderBy:'action'"> <td>{{item.action}}</td> <td><input type="checkbox" ng-model="item.done" /></td> </tr> </tbody> ... Creating a Custom Filter in the todo.html File ... <script> var model = { user: "Adam", items: [{ action: "Buy Flowers", done: false }, { action: "Get Shoes", done: false }, { action: "Collect Tickets", done: true }, { action: "Call Joe", done: false }], }; var todoApp = angular.module("todoApp", []); todoApp.filter("checkedItems", function () { return function (items, showComplete) { var resultArr = []; angular.forEach(items, function (item) { if (item.done == false || showComplete == true) { resultArr.push(item); } }); return resultArr; } }); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; // ...statements omitted for brevity... }); </script> ... The filtermethod defined by the AngularJS module object is used to create a filter factory, which returns a function that is used to filter a set of data objects. Don’t worry about the factory part for the moment; it is enough to know that using the filtermethod requires passing in a function that returns a function that returns the filtered data. The name I have given my filter is checkedItems, and the function that does the actual filtering has two arguments: ... return function (items, showComplete) { ... which I pass to my custom filter through the ng-repeatdirective in the table: ... <tr ng-repeat="item in todo.items |checkedItems:showComplete| orderBy:'action'"> ... The syntax for custom filters is the same as for the built-in filtering support. I specify the name of the filter I created with the filter method, followed by a colon (:), followed by the name of the model property that I want to pass to the filter function. I have specified the showCompletemodel property, which means that the state of the check box will be used to control the visibility of the checked items. You can see the effect in Figure 2-10. Making an Ajax Call for JSON Data in the todo.html File ... <script> var model = { user: "Adam" }; var todoApp = angular.module("todoApp", []); todoApp.run(function ($http) { $http.get("todo.json").success(function (data) { model.items = data; }); }); todoApp.filter("checkedItems", function () { return function (items, showComplete) { var resultArr = []; angular.forEach(items, function (item) { if (item.done == false || showComplete == true) { resultArr.push(item); } }); return resultArr; } }); todoApp.controller("ToDoCtrl", function ($scope) { $scope.todo = model; $scope.incompleteCount = function () { var count = 0; angular.forEach($scope.todo.items, function (item) { if (!item.done) { count++ } }); return count; } $scope.warningLevel = function () { return $scope.incompleteCount() < 3 ? "label-success" : "label-warning"; } $scope.addNewItem = function(actionText) { $scope.todo.items.push({ action: actionText, done: false}); } }); </script> ... I removed the items array from the statically defined data model and added a call to the run method defined by the AngularJS module object. The runmethod takes a function that is executed once AngularJS has performed its initial setup and is used for one-off tasks. I am going to focus on the standard MVC pattern in this book since it is the most established and widely used. In broad terms, there are two kinds of web application: round-tripand single-page. AngularJS excels in single-page applications and especially in complex round-trip applications. For simpler projects, jQuery or a similar alternative is generally a better choice, although nothing prevents you from using AngularJS in all of your projects. There is a gradual tendency for current web app projects to move toward the single-page application model, and that’s the sweet spot for AngularJS, not just because of the initialization process but because the benefits of using the MVC pattern (which I describe later in this chapter) really start to manifest themselves in larger and more complex projects, which are the ones pushing toward the single-page model. So, in short, use jQuery for low-complexity web apps where unit testing isn’t critical and you require immediate results. jQuery is also ideal for enhancing the HTML that is generated by round-trip web apps (where user interactions cause a new HTML document to be loaded) because you can easily apply jQuery without needing to modify the HTML content generated by the server. Use AngularJS for more complex single-page web apps, when you have time for careful design and planning and when you can easily control the HTML generated by the server. The key to applying the MVC pattern is to implement the key premise of a separation of concerns, in which the data model in the application is decoupled from the business and presentation logic. In client-side web development, this means separating the data, the logic that operates on that data, and the HTML elements used to display the data. The result is a client-side application that is easier to develop, maintain, and test. Patterns are recipes, rather than rules, and you will need to adapt any pattern to suit your specific projects, just like a cook has to adapt a recipe to suit different ovens and ingredients. The degree by which you depart from a pattern should be driven by experience. The time you have spent applying a pattern to similar projects will inform your knowledge about what does and doesn’t work for you. If you are new to a pattern or you are embarking on a new kind of project, then you should stick as closely as possible to the pattern until you truly understand the benefits and pitfalls that await you. Be careful not to reform your entire development effort around a pattern, however, since wide-sweeping disruption usually causes productivity loses that undermine whatever outcome you were hoping the pattern would give. Patterns are flexible tools and not fixed rules, but not all developers understand the difference, and some become pattern zealots.These are the people who spend more time talking about the pattern than applying it to projects and consider any deviation from their interpretation of the pattern to be a serious crime. Understanding Models Models—the M in MVC—contain the data that users work with. There are two broad types of model: view models, which represent just data passed from the controller to the view, and domain models, which contain the data in a business domain, along with the operations, transformations, and rules for creating, storing, and manipulating that data, collectively referred to as the model logic. Tip Many developers new to the MVC pattern get confused with the idea of including logic in the data model, believing that the goal of the MVC pattern is to separate data from logic. This is a misapprehension: The goal of the MVC framework is to divide up an application into three functional areas, each of which may contain both logic anddata. The goal isn’t to eliminate logic from the model. Rather, it is to ensure that the model contains logic only for creating and managing the model data. The benefits of ensuring that the model is isolated from the controller and views are that you can test your logic more easily Understanding Controllers Controllers are the connective tissue in an AngularJS web app, acting as conduits between the data model and views. Controllers add business domain logic (known as behaviors) to scopes, which are subsets of the model. A controller built using the MVC should * Contain the logic required to initialize the scope * Contain the logic/behaviors required by the view to present data from the scope * Contain the logic/behaviors required to update the scope based on user interaction The controller should not * Contain logic that manipulates the DOM (that is the job of the view) * Contain logic that manages the persistence of data (that is the job of the model) * Manipulate data outside of the scope From these lists, you can tell that scopes have a big impact on the way that controllers are defined and used. Understanding View Data The domain model isn’t the only data in an AngularJS application. Controllers can create view data(also known as view model data or view models) to simplify the definition of views. View data is not persistent and is created either by synthesizing some aspect of the domain model data or in response to user interaction. Views cancontain logic, but it should be simple and used sparingly We don’t want the client-side code accessing the data store directly—doing so would create a tight coupling between the client and the data store that would complicate unit testing and make it difficult to change the data store without also making changes to the client code as well. There are lots of ways of passing data between the client and the server. One of the most common is to use Asynchronous JavaScript and XML (Ajax) requests to call server-side code, getting the server to send JSON and making changes to data using HTML forms. REST is a style of API rather than a well-defined specification, and there is disagreement about what exactly makes a web service RESTful. One point of contention is that purists do not consider web services that return JSON to be RESTful. Like any disagreement about an architectural pattern, the reasons for the disagreement are arbitrary and dull and not at all worth worrying about. As far as I am concerned, JSON services areRESTful, and I treat them as such in this book. In a RESTful web service, the operation that is being requested is expressed through a combination of the HTTP method and the URL. So, for example, imagine a URL like this one: http://myserver.mydomain.com/people/bob Tip It isn’t always possible to create such self-evident URLs in a real project, but you should make a serious effort to keep things simple and not expose the internal structure of the data store through the URL (because this is just another kind of coupling between components). Keep your URLs as simple and clear as possible, and keep the mappings between the URL format and the data store structure within the server. The URL identifies the data object that I want to operate on, and the HTTP method specifies what operation I want performed, The GET method is nullipotent, which means that the operations you perform in response to this method should only retrieve data and not modify it. A browser (or any intermediate device, such as a proxy) expects to be able to repeatedly make a GET request without altering the state of the server (although this doesn’t mean the state of the server won’t change between identical GET requests because of requests from other clients). The PUT and DELETE methods are idempotent, which means that multiple identical requests should have the same effect as a single request. So, for example, using the DELETE method with the /people/bobURL should delete the bobobject from the peoplecollection for the first request and then do nothing for subsequent requests. (Again, of course, this won’t be true if another client re-creates the bob object.) The POST method is neither nullipotent nor idempotent, which is why a common RESTful optimization is to handle object creation and updates. If there is no bob object, using the POST method will create one, and subsequent POST requests to the same URL will update the object that was created. Here are the three most common varieties of this problem: * Putting business logic in views, rather than in controllers * Putting domain logic in controllers, rather than in model * Putting data store logic in the client model when using a RESTful service These are tricky issues because they take a while to manifest themselves as problems. The application still runs, but it will become harder to enhance and maintain over time. Knowing where to put logic becomes second nature as you get more experience in AngularJS development, but here are the three rules: * View logic should prepare data only for display and never modify the model. * Controller logic should never directly create, update, or delete data from the model. * The client should never directly access the data store. If you keep these in mind as you develop, you’ll head off the most common problems. Instead, if you define two functions with the same name, then the second definition replaces the first. JavaScript is a dynamically typed language. This doesn’t mean JavaScript doesn’t have types. It just means you don’t have to explicitly declare the type of a variable and that you can assign different types to the same variable without any difficulty. JavaScript will determine the type based on the value you assign to a variable and will freely convert between types based on the context in which they are used. Using global variables in AngularJS development is frowned upon because it undermines the separation of concerns (which I described in Chapter 3) and makes it harder to perform unit testing (which I describe in Chapter 25). As a rule of thumb, if you have to use a global variable to get two components to talk to one another, then something has gone wrong with the application design. Using the Primitive Types JavaScript defines a set of primitive types: string, number, and boolean. This may seem like a short list, but JavaScript manages to fit a lot of flexibility into these three types. The angular.uppercaseand angular.lowercasemethods do exactly as you might imagine, Using Object Literals You can define an object and its properties in a single step using the object literal format. Listing 5-14 shows how this is done. Listing 5-14. Using the Object Literal Format in the jsdemo.html File <!DOCTYPE HTML> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData = { name: "Adam", weather: "sunny" }; console.log("Hello " + myData.name + ". "); console.log("Today is " + myData.weather + "."); </script> </head> <body> This is a simple example </body> </html> Each property that you want to define is separated from its value using a colon (:), and properties are separated using a comma (,). Extending Objects in the jsdemo.html File <!DOCTYPE html> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData = { name: "Adam", weather: "sunny", printMessages: function () { console.log("Hello " + this.name + ". "); console.log("Today is " + this.weather + "."); } }; var myExtendedObject = { city: "London" }; angular.extend(myExtendedObject, myData); console.log(myExtendedObject.name); console.log(myExtendedObject.city); </script> </head> <body> This is a simple example </body> </html> In this example I create an object with a city property and assign it to the variable called myExtendedObject. I then use the angular.extendmethod to copy all of the properties and functions from the myData object to myExtendedObject. Finally, to demonstrate the mix of original and copied properties, I use the console.logmethod to write out the values of the nameand city properties, producing the following console Tip The extendmethod preserves any properties and methods on the target object. If you want to create a copy of an object without this preservation, then you can use the angular.copymethod instead. Enumerating an Object’s Properties in the jsdemo.html File <!DOCTYPE html> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData = { name: "Adam", weather: "sunny", printMessages: function () { console.log("Hello " + this.name + ". "); console.log("Today is " + this.weather + "."); } }; for (var prop in myData) { console.log("Name: " + prop + " Value: " + myData[prop]); } console.log("---"); angular.forEach(myData, function (value, key) { console.log("Name: " + key + " Value: " + value); }); </script> </head> <body> This is a simple example </body> </html> The for...inloop is a standard JavaScript feature and performs the statement in the code block for each property in the myData object. T Deleting a Property from an Object in the jsdemo.html File <!DOCTYPE HTML> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData = { name: "Adam", weather: "sunny", }; delete myData.name; delete myData["weather"]; delete myData.SayHello; </script> </head> <body> This is a simple example </body> </html> You can check to see whether an object has a property using the in expression, as shown in Listing 5-23. Listing 5-23. Checking to See Whether an Object Has a Property in the jsdemo.html File <!DOCTYPE HTML> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData = { name: "Adam", weather: "sunny", }; var hasName = "name" in myData; var hasDate = "date" in myData; console.log("HasName: " + hasName); console.log("HasDate: " + hasDate); </script> </head> <body> This is a simple example </body> </html> In this example, I test for a property that exists and one that doesn’t. The value of the hasName variable will be true, and the value of the hasDateproperty will be JavaScript is converting the two operands into the same type and comparing them. In essence, the equality operator tests that values are the same irrespective of their type. If you want to test to ensure that the values and the types are the same, then you need to use the identity operator (===, three equals signs, rather than the two of the equality operator), as shown in Listing 5-26. Performing Equality and Identity Tests on Objects in the jsdemo.html File <!DOCTYPE HTML> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData1 = { name: "Adam", weather: "sunny", }; var myData2 = { name: "Adam", weather: "sunny", }; var myData3 = myData2; var test1 = myData1 == myData2; var test2 = myData2 == myData3; var test3 = myData1 === myData2; var test4 = myData2 === myData3; console.log("Test 1: " + test1 + " Test 2: " + test2); console.log("Test 3: " + test3 + " Test 4: " + test4); </script> </head> <body> This is a simple example </body> </html> The results from this script are as follows: Test 1: false Test 2: true Test 3: false Test 4: true Listing 5-28shows the same tests performed on primitives. Listing 5-28. Performing Equality and Identity Tests on Objects in the jsdemo.html File <!DOCTYPE HTML> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myData1 = 5; var myData2 = "5"; var myData3 = myData2; var test1 = myData1 == myData2; var test2 = myData2 == myData3; var test3 = myData1 === myData2; var test4 = myData2 === myData3; console.log("Test 1: " + test1 + " Test 2: " + test2); console.log("Test 3: " + test3 + " Test 4: " + test4); </script> </head> <body> This is a simple example </body> </html> The results from this script are as follows: Test 1: true Test 2: true Test 3: false Test 4: true Enumerating the Contents of an Array You enumerate the content of an array using a for loop or the AngularJS angular.forEachmethod, both of which are demonstrated in Listing 5-37. <!DOCTYPE html> <html> <head> <title>Example</title> <script src="angular.js"></script> <script type="text/javascript"> var myArray = [100, "Adam", true]; for (var i = 0; i < myArray.length; i++) { console.log("Index " + i + ": " + myArray[i]); } console.log("---"); angular.forEach(myArray, function (value, key) { console.log(key + ": " + value); }); </script> </head> <body> This is a simple example </body> </html> <!DOCTYPE html> <html ng-app="demo"> <head> <title>Example</title> <script src="angular.js"></script> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script type="text/javascript"> var myApp = angular.module("demo", []); myApp.controller("demoCtrl", function ($scope, $http) { var promise = $http.get("todo.json"); promise.success(function (data) { $scope.todos = data; }); }); </script> </head> <body ng-controller="demoCtrl"> <div class="panel"> <h1>To Do</h1> <table class="table"> <tr><td>Action</td><td>Done</td></tr> <tr ng-repeat="item in todos"> <td>{{item.action}}</td> <td>{{item.done}}</td> </tr> </table> </div> </body> </html> The key part of the listing is here: ... var promise = $http.get("todo.json"); promise.success(function (data) { $scope.todos = data; }); ... Encoding and Decoding JSON Data in the jsdemo.html File <!DOCTYPE html> <html ng-app="demo"> <head> <title>Example</title> <script src="angular.js"></script> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script type="text/javascript"> var myApp = angular.module("demo", []); myApp.controller("demoCtrl", function ($scope, $http) { $http.get("todo.json").success(function (data) { var jsonString = angular.toJson(data); console.log(jsonString); $scope.todos = angular.fromJson(jsonString); }); }); </script> </head> <body ng-controller="demoCtrl"> <div class="panel"> <h1>To Do</h1> <table class="table"> <tr><td>Action</td><td>Done</td></tr> <tr ng-repeat="item in todos"> <td>{{item.action}}</td> <td>{{item.done}}</td> </tr> </table> </div> </body> </html> In this example, I operate on the data object that is passed to the promise success function. This was received as JSON data from the web server and automatically parsed into a JavaScript array by AngularJS. I then call the angular.toJsonmethod to encode the array as JSON again and write it to the console. Finally, I take the JSON that I have created and call the angular.fromJsonmethod to create another JavaScript object, which I use to populate the data model in the AngularJS controller and populate the table element via the ng-repeat directive. Filters let you define commonly used data transformations so that they can be applied throughout an application, without being tied to a specific controller or type of data. Filters transform the data as it passes from the scope to the directive but don’t change the source data, allowing you to flexibly format or transform data for display in views. Why and When to Use Filters Why When Filters contain transformation logic that can be applied to any data in the application for presentation in a view. Filters are used to format data before it is processed by a directive and displayed in a view. Applying the currency Filter in the filters.html File ... <tr ng-repeat="p in products"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency}}</td> </tr> ... You can see how easy it is to apply the filter to the data binding. I append the bar symbol (the |character) to the binding source (p.price in this case) followed by the filter name. This is the way that all filters are applied, and you can see the effect in Using a Different Symbol for the currency Filter in the filters.html File ... <tr ng-repeat="p in products"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency:"£" }}</td> </tr> Applying the number Filter in the filters.html File ... <tr ng-repeat="p in products"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">${{p.price | number:0 }}</td> </tr> ... I apply the filter using the bar character and the filter name, followed by a colon and then the number of decimal places I want to display. I have specified zero decimal places, Applying the uppercase and lowercase Filters in the filters.html File ... <tr ng-repeat="p in products"> <td>{{p.name | uppercase }}</td> <td>{{p.category | lowercase }}</td> <td>{{getExpiryDate(p.expiry) | date:"dd MMM yy"}}</td> <td class="text-right">${{p.price | number:0 }}</td> </tr> ... These filters do exactly what you would expect, <html ng-app="exampleApp"> <head> <title>Filters</title> <script src="angular.js"></script> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script> angular.module("exampleApp", []) .controller("defaultCtrl", function ($scope) { $scope.products = [ { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 }, { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 }, { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }, { name: "Tuna", category: "Fish", price: 20.45, expiry: 3 }, { name: "Salmon", category: "Fish", price: 17.93, expiry: 2 }, { name: "Trout", category: "Fish", price: 12.93, expiry: 4 }, { name: "Beer", category: "Drinks", price: 2.99, expiry: 365 }, { name: "Wine", category: "Drinks", price: 8.99, expiry: 365 }, { name: "Whiskey", category: "Drinks", price: 45.99, expiry: 365 } ]; $scope.limitVal = "5"; $scope.limitRange = []; for (var i = (0 - $scope.products.length); i <= $scope.products.length; i++) { $scope.limitRange.push(i.toString()); } }); </script> </head> <body ng-controller="defaultCtrl"> <div class="panel panel-default"> <div class="panel-heading"> <h3> Products <span class="label label-primary">{{products.length}}</span> </h3> </div> <div class="panel-body"> Limit: <select ng-model="limitVal" ng-options="item for item in limitRange"></select> </div> <div class="panel-body"> <table class="table table-striped table-bordered table-condensed"> <thead> <tr> <td>Name</td> <td>Category</td> <td>Expiry</td> <td class="text-right">Price</td> </tr> </thead> <tbody> <tr ng-repeat="p in products | limitTo:limitVal"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> </tbody> </table> </div> </div> </body> </html> Selecting items in the filters.html file ... <tr ng-repeat="p in products | filter:{category: 'Fish'}"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... I have used the map object approach in this example, specifying that I want to select those items whose categoryproperty is Fish. If you filter using a function, the selected items will be those for which the function returns true, as shown in Listing 14-11. <html ng-app="exampleApp"> <head> <title>Filters</title> <script src="angular.js"></script> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script> angular.module("exampleApp", []) .controller("defaultCtrl", function ($scope) { $scope.products = [ { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 }, { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 }, { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }, { name: "Tuna", category: "Fish", price: 20.45, expiry: 3 }, { name: "Salmon", category: "Fish", price: 17.93, expiry: 2 }, { name: "Trout", category: "Fish", price: 12.93, expiry: 4 }, { name: "Beer", category: "Drinks", price: 2.99, expiry: 365 }, { name: "Wine", category: "Drinks", price: 8.99, expiry: 365 }, { name: "Whiskey", category: "Drinks", price: 45.99, expiry: 365 } ]; $scope.limitVal = "5"; $scope.limitRange = []; for (var i = (0 - $scope.products.length) ; i <= $scope.products.length; i++) { $scope.limitRange.push(i.toString()); } $scope.selectItems = function (item) { return item.category == "Fish" || item.name == "Beer"; }; }); </script> </head> <body ng-controller="defaultCtrl"> <div class="panel panel-default"> <div class="panel-heading"> <h3> Products <span class="label label-primary">{{products.length}}</span> </h3> </div> <div class="panel-body"> Limit: <select ng-model="limitVal" ng-options="item for item in limitRange"></select> </div> <div class="panel-body"> <table class="table table-striped table-bordered table-condensed"> <thead> <tr> <td>Name</td> <td>Category</td> <td>Expiry</td> <td class="text-right">Price</td> </tr> </thead> <tbody> <tr ng-repeat="p in products | filter:selectItems"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> </tbody> </table> </div> </div> </body> </html> <tr ng-repeat="p in products | orderBy:'price'"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... Caution Notice that I have surrounded the property name with quotes: 'price' and not just price. The orderBy filter will quietly fail if you forget the quotes when hardwiring a property name into a directive expression. Without the quotes, the filter assumes you want to use a scope variable or a controller variable called price and figures that you’ll get around to defining it at some point in the future. Explicitly Setting the Sort Direction in the filters.html File ... <tr ng-repeat="p in products | orderBy:'-price'"> ... By prefixing the property name with a minus sign (-) I specify that the objects should be sorted in descending order of their price property, as shown in Figure 14-12. Specifying a plus sign (+) is equivalent to no prefix at all and has the effect of applying an ascending sort. $scope.myCustomSorter = function (item) { return item.expiry < 5 ? 0 : item.price; } }); </script> ... Functions used for sorting are passed an object from the data array and return an object or value that will be used for comparison during sorting. In this function, I return the value of the priceproperty unless the value of the expiryproperty is less than 5, in which case I return zero. The effect of this function is that items with a small expiryvalue will be placed near the start of the data array for ascending sorts. In Listing 14-15, you can see how I have applied the function to the orderBy filter. Listing 14-15. Applying the Search Function in the filters.html File ... <tr ng-repeat="p in products | orderBy:myCustomSorter"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... Notice that I don’t surround the name of the function with quotes, as I did when I specified a property name as a literal string. ... <tr ng-repeat="p in products | orderBy:[myCustomSorter, '-price']"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... Chaining Filters in the filters.html File ... <tr ng-repeat="p in products | orderBy:[myCustomSorter, '-price'] | limitTo: 5"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... Tip You can chain together filters that operate on single data values, but there isn’t much point in doing this with the built-in filters like currencyand date, s Creating a Filter That Formats a Data Value Filters are created by the Module.filtermethod, which takes two arguments: the name of the filter that will be created and a factory function that creates the worker function that will undertake the actual work. The Contents of the customFilters.js File angular.module("exampleApp") .filter("labelCase", function () { return function (value, reverse) { if (angular.isString(value)) { var intermediate = reverse ? value.toUpperCase() : value.toLowerCase(); return (reverse ? intermediate[0].toLowerCase() : intermediate[0].toUpperCase()) + intermediate.substr(1); } else { return value; } }; }); Applying a Custom Filter to the filters.html File ... <tr ng-repeat="p in products | orderBy:[myCustomSorter, '-price'] | limitTo: 5"> <td>{{p.name | labelCase }}</td> <td>{{p.category | labelCase:true }}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... I have not specified a configuration option when applying the filter to the nameproperty, which means that AngularJS will pass null as the value for the second argument to the filter worker function. angular.module("exampleApp") .filter("labelCase", function () { return function (value, reverse) { if (angular.isString(value)) { var intermediate = reverse ? value.toUpperCase() : value.toLowerCase(); return (reverse ? intermediate[0].toLowerCase() : intermediate[0].toUpperCase()) + intermediate.substr(1); } else { return value; } }; }) .filter("skip", function () { return function (data, count) { if (angular.isArray(data) &&angular.isNumber(count)) { if (count > data.length || count < 1) { return data; } else { return data.slice(count); } } else { return data; } } }); ... <tr ng-repeat="p in products | skip:2 | limitTo: 5"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... I have chained the skip and limitTofilters to emphasize that custom filters are used in just the same way as the built-in ones. angular.module("exampleApp") .filter("labelCase", function () { //...statements omitted for brevity... }) .filter("skip", function () { //...statements omitted for brevity... }) .filter("take", function ($filter) { return function (data, skipCount, takeCount) { var skippedData = $filter("skip")(data, skipCount); return $filter("limitTo")(skippedData, takeCount); } }); ... <tr ng-repeat="p in products | take:2:5"> <td>{{p.name}}</td> <td>{{p.category}}</td> <td>{{p.expiry}}</td> <td class="text-right">{{p.price | currency }}</td> </tr> ... AngularJS comes with more than 50 built-in directives that provide access to core features that are useful in almost every web application including data binding, form validation, template generation, event handling, and manipulating HTML elements. I created a module called exampleApp using the angular.module method and then used the fluent API to define a controller called defaultCtrl. The controller uses the $scope service to add some data items to the data model, and the module and the controller are applied to HTML elements with the ng-app and ng-controllerdirectives. AngularJS supports two kinds of data binding. The first, one-way binding, means a value is taken from the data model and inserted into an HTML element. AngularJS bindings are live, which means that when the value associated with the binding is changed in the data model, the HTML element will be updated to display the new value. The ng-bind directive is responsible for creating one-way data bindings, but it is rarely used directly because AngularJS will also create this kind of binding whenever it encounters the {{ and }} characters in the HTML document. Listing 10-2shows the different ways you can create one-way data bindings. I generally prefer to apply directives as attributes, as follows: ... There are <span ng-bind="todos.length"></span> items ... The directive is specified as the attribute name, ng-bindin this case, and the configuration for the directive is set as the attribute value. If you can’t or won’t use custom attributes, then you can configure directives using the standard class attribute, as follows: ... There are <span class="ng-bind: todos.length"></span> items ... The value of the class attribute is the name of the directive, followed by a colon, followed by the configuration for the directive. This statement has the same effect as the last one <div>There are {{todos.length}} items</div> <div> There are <span ng-bind="todos.length"></span> items </div> <div ng-bind-template= "First: {{todos[0].action}}. Second: {{todos[1].action}}"> </div> <div ng-non-bindable> AngularJS uses {{ and }} characters for templates </div> The solution is to use the ng-non-bindable directive, which prevents AngularJS from processing inline bindings: ... <div ng-non-bindable> AngularJS uses {{ and }} characters for templates </div> ... Two-way bindings are created with the ng-model directive Creating Two-Way Bindings in the directives.html File ... <body> <div id="todoPanel" class="panel" ng-controller="defaultCtrl"> <h3 class="panel-header">To Do List</h3> <div class="well"> <div>The first item is: {{todos[0].action}}</div> </div> <div class="form-group well"> <label for="firstItem">Set First Item:</label> <input name="firstItem" class="form-control" ng-model="todos[0].action" /> </div> </div> </body> ... There are two data bindings in this listing, both of which are applied to the action property of the first object in the todos data array (which I set up using the $scope object in the controller and reference in bindings as todos[0].action). The first binding is an inline one-way binding that simply displays the value of the data property, just as I did in the previous example. The second binding is applied via the inputelement and is a two-way binding: ... <input name="firstItem" class="form-control" ng-model="todos[0].action"/> ... Two-way bindings can be applied only to elements that allow the user to provide a data value, which means the input, textarea, and select elements. The ng-model directive sets the content of the element it is applied to and then responds to changes that the user makes by updating the data model. OK, two-way bindings are not really magic. AngularJS uses standard JavaScript events to receive notifications from the input element when its content changes and propagates these changes via the $scope service. You can see the event handler that AngularJS sets up through the F12 developer tools, and I explain how the $scope service detects and disseminates changes The Template Directives Directive Applied As Description ng-cloak Attribute, class Applies a CSS style that hides inline binding expressions, which can be briefly visible when the document first loads ng-include Element, attribute, class Loads, processes, and inserts a fragment of HTML into the Document Object Model ng-repeat Attribute, class Generates new copies of a single element and its contents for each object in an array or property on an object ng-repeat-start Attribute, class Denotes the start of a repeating section with multiple top-level elements ng-repeat-end Attribute, class Denotes the end of a repeating section with multiple top-level elements ng-switch Element, attribute Changes the elements in the Document Object Model based on the value of data bindings These directives help you put simple logic into views without having to write any JavaScript code. As I explained in Chapter 3, the logic in views should be restricted to generating the content required to display data, and these directives all fit into that definition. ... <tr ng-repeat="item in todos"> ... The basic format of the value for the ng-repeat directive attribute is <variable> in <source>, where source is an object or array defined by the controller $scope, in this example the todos array. The directive iterates through the objects in the array, creates a new instance of the element and its content, and then processes the templates it contains. The <variable> name assigned in the directive attribute value can be used to refer to the current data object. Receiving a Key Along with a Data Value in the directives.html File ... <tr ng-repeat="item in todos"> <td ng-repeat="(key, value) in item"> {{key}}={{value}} </td> </tr> … <tr ng-repeat="item in todos"> <td>{{$index + 1}}</td> <td ng-repeat="prop in item"> {{prop}} </td> </tr> </table> ... I added a new column to the table that contains the to-do items and used the $index variable, which is provided by the ng-repeat directive, to display the position of each item in the array. Since JavaScript collec The Built-in ng-repeat Variables Variable Description $index Returns the position of the current object or property $first Returns true if the current object is the first in the collection $middle Returns true if the current object is neither the first nor last in the collection $last Returns true if the current object is the last in the collection $even Returns true for the even-numbered objects in a collection $odd Returns true for the odd-numbered objects in a collection Stripped table: <tr ng-repeat="item in todos" ng-class="$odd ? 'odd' : 'even'"> <td>{{$index + 1}}</td> <td ng-repeat="prop in item">{{prop}}</td> As the listing illustrates, the name of the directive is used as the element tag name, like this: ... < ng-includesrc="'table.html'"></ng-include> ... Caution Don’t try to use apply the ng-include directive as a void element (in other words, <ng-include src="'table.html'" />). The content that follows the ng-include element will be removed from the DOM. You must always specify open and close tags, as I have shown in the example. My previous example demonstrated how the ng-includedirective can be used to break a view into multiple partial view files. This is, in and of itself, a useful feature, and it allows you to create reusable partial views that can be applied throughout an application to avoid duplication and ensure consistent presentation of data. The Contents of the list.html File <ol> <li ng-repeat="item in todos"> {{item.action}} <span ng-if="item.complete"> (Done)</span> </li> </ol> Using the ng-include Directive to Process Fragments Dynamically in the directives.html File <!DOCTYPE html> <html ng-app="exampleApp"> <head> <title>Directives</title> <script src="angular.js"></script> <link href="bootstrap.css" rel="stylesheet" /> <link href="bootstrap-theme.css" rel="stylesheet" /> <script> angular.module("exampleApp", []) .controller("defaultCtrl", function ($scope) { $scope.todos = [ { action: "Get groceries", complete: false }, { action: "Call plumber", complete: false }, { action: "Buy running shoes", complete: true }, { action: "Buy flowers", complete: false }, { action: "Call family", complete: false }]; $scope.viewFile = function () { return $scope.showList ? "list.html" : "table.html"; }; }); </script> </head> <body> <div id="todoPanel" class="panel" ng-controller="defaultCtrl"> <h3 class="panel-header">To Do List</h3> <div class="well"> <div class="checkbox"> <label> <input type="checkbox" ng-model="showList"> Use the list view </label> </div> </div> <ng-include src="viewFile()"></ng-include> </div> </body> </html> I have defined a behavior called viewFile in the controller that returns the name of one of the two fragment files I created based on the value of a variable called showList. If showList is true, then the viewFile behavior returns the name of the list.html file; if showList is false or undefined, then the behavior returns the name of the table.html file. The showList variable is initially undefined, but I have added a check box input element that sets the variable when it is checked using the ng-model directive, which I described earlier in this chapter. The user can change the value of the showList variable by checking or unchecking the element. The ng-switch directive is applied with an on attribute that specifies the expression that will be evaluated to decide which region of content will be displayed, as follows: ... <div ng-switch on="data.mode"> ... In this example, I have specified that the value of the data.mode model property—the one that the radio buttons manage—will be used. You then use the ng-switch-whendirective to denote a region of content that will be associated with a specific value, like this: ... <div ng-switch-when="Table"> <table class="table"> <!--elements omitted for brevity--> </table> </div> <div ng-switch-when="List"> <ol> <!--elements omitted for brevity--> </ol> </div> ... AngularJS will show the element to which the ng-switch-when directive has been applied when the attribute value matches the expression defined by the on attribute. The other elements within the ng-switch directive block are removed. The ng-switch-default directive is used to specify content that should be displayed when none of the ng-switch-whensections matches, as follows: ... <div ng-switch-default> Select another option to display a layout </div> … Use ng-switch when you need to alternate between smaller, simpler blocks of content and that there is a good chance the user will be shown most or all of those blocks in the normal execution of the web app. This is because you have to deliver all the content that the ng-switchdirective needs as part of the HTML document, and that’s a waste of bandwidth and loading time for content that is unlikely to be used. The ng-include attribute is better suited for more complex content or content that you need to use repeatedly throughout an application. Partial views can help reduce the amount of duplication in a project when you need to include the same content in different places, but you must bear in mind that partial views are not requested until the first time they are required, and this can cause delays while the browser makes the Ajax request and receives the response from the server. A better alternative is to use the ng-cloak directive, which has the effect of hiding content until AngularJS has finished processing it. The ng-cloak directive uses CSS to hide the elements to which it is applied, and the AngularJS library removes the CSS class when the content has been processed, ensuring that the user never sees the {{ and }} characters of a template expression. You can apply the ng-cloak directive as broadly or selectively as you want. A common approach is to apply the directive to the body element, but that just means that the user sees an empty browser window while AngularJS processes the content. I prefer to be more selective and apply the directive only to the parts of the document where there are inline expressions, as shown in Listing 10-18. Selectively Applying the ng-cloak Directive to the directives.html File ... <body> <div id="todoPanel" class="panel" ng-controller="defaultCtrl"> <h3 class="panel-header">To Do List</h3> <div class="well"> <div class="radio" ng-repeat="button in ['None', 'Table', 'List']"> <label ng-cloak> <input type="radio" ng-model="data.mode" value="{{button}}" ng-checked="$first"> {{button}} </label> </div> </div> <div ng-switch on="data.mode" ng-cloak> <div ng-switch-when="Table"> <table class="table"> <thead> <tr><th>#</th><th>Action</th><th>Done</th></tr> </thead> <tr ng-repeat="item in todos" ng-class="$odd ? 'odd' : 'even'"> <td>{{$index + 1}}</td> <td ng-repeat="prop in item">{{prop}}</td> </tr> </table> </div> <div ng-switch-when="List"> <ol> <li ng-repeat="item in todos"> {{item.action}}<span ng-if="item.complete"> (Done)</span> </li> </ol> </div> <div ng-switch-default> Select another option to display a layout </div> </div> </div> </body> ... Applying the directive to the sections of the document that contain template expressions leaves the user able to see the static structure of a page, which still isn’t ideal but is a lot better than just an empty window. You can see the effect the directive creates in Figure 10-10 (and, of course, the full app layout is revealed to the user when AngularJS finishes processing the content). Using the Element Directives The first set of directives that I describe in this chapter are used to configure and style elements in the Document Object Model (DOM). These directives are useful for managing the way that an application displays content and data and, since this is AngularJS, for using bindings to change the HTML document dynamically when the data model changes. The Element Directives Directive Applied As Description ng-if Attribute Adds and removes elements from the DOM ng-class Attribute, class Sets the class attribute for an element ng-class-even Attribute, class Sets the class attribute for even-numbered elements generated within the ng-repeatdirective ng-class-odd Attribute, class Sets the class attribute for odd-numbered elements generated within the ng-repeatdirective ng-hide Attribute, class Shows and hides elements in the DOM ng-show Attribute, class Shows and hides elements in the DOM ng-style Attribute, class Sets one or more CSS properties Many of the directives in this category control whether elements are visible to the user, either by hiding them or by removing them completely from the DOM. Why and When to Create Custom Directives Why When Custom directives let you create functionality that goes beyond the built-in directives that AngularJS provides. You create custom directives when the built-in directives don’t do what you want or when you want to create self-contained functionality that you can reuse in different applications. Defining the Directive Directives are created using the Module.directive method, and the arguments are the name of the new directive and a factory function that creates the directive. <file_sep>/springbootapp.java package com.todzhang; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; public interface BookRepository extends MongoRepository<Book, String> { public Book findByTitle(String title); public List<Book> findByType(String type); public List<Book> findByAuthor(String author); } package com.todzhang; import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private BookRepository repository; public static void main(String[] args){ SpringApplication.run(Application.class, args); } @Override public void run(String... arg0) throws Exception { repository.deleteAll(); System.out.println("=== repository cleaned===="); repository.save(new Book("A Tale Of Two Cities","<NAME>",10,"Novel")); repository.save(new Book("The Da Vinci Code","<NAME>",12,"Thriller")); repository.save(new Book("Think and Grow Rich","<NAME>",10,"Motivational")); repository.save(new Book("The Hobbit","<NAME>",8,"Fantasy")); System.out.println("--- book found all --"); List<Book> allBooks=repository.findAll(); for(Book book:allBooks){ System.out.println("-- the book is:"+book); } System.out.println(); Book book1=repository.findByTitle("The Da Vinci Code"); System.out.println("--- find by title: +"+book1); book1.setPrice(5); repository.save(book1); System.out.println("--update book ---, now it's: "+repository.findByTitle("The Da Vinci Code")); repository.delete(book1); System.out.println("--- after delete book ---"); for(Book book:repository.findAll()){ System.out.println("-- the book is:"+book); } } } package com.todzhang; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; @Document(collection="todbooks") public class Book { @Id private String id; @Field("bookTitle") private String title; private String author; private int price; private String type; @Override public String toString() { // TODO Auto-generated method stub return String.format("Book is : id=%s, title=%s, author=%s,price=%d",id,title,author,price); } public Book( String title, String author, int price, String type) { super(); this.title = title; this.author = author; this.price = price; this.type = type; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getType() { return type; } public void setType(String type) { this.type = type; } } package com.todzhang; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.mongodb.Mongo; import com.mongodb.MongoClient; @EnableMongoRepositories @Configuration public class MongoConfig extends AbstractMongoConfiguration { @Override protected String getDatabaseName() { // TODO Auto-generated method stub return "todzhangdb"; } @Override public Mongo mongo() throws Exception { // TODO Auto-generated method stub return new MongoClient("192.168.3.11",5255); } @Override protected String getMappingBasePackage() { // TODO Auto-generated method stub return "com.todzhang"; } } <file_sep>/fetch.sh cd /Users/todzhang/dev/git/misc/ git pull <file_sep>/CoverLetter_AWSArchitect.md <NAME> Permanent Resident Mail: <EMAIL> Dear Enzo or Hiring Manager This is in regards to my interest in applying for the job "Enterprise Solutions Architect" posted on seek.com. I believe I’m a pretty competitive candidate for this vacancy, on top of my outstanding skills & ability, previous proven experience and expertise. Which is fairly matching desired skills mentioned in the JD. Currently I’m working in IT department in HSBC, being an IT specialist and providing architect and solutions for our customers. Customer-first and think-as-owner are always first principle in my philosophy. I was considered as a dependable go-to person and SME when working with customers. Day to day jobs including (but not limited to) talk to users to gather requirements, analysis & design, POC (Prove Of Concept) or prototype, architect best solution, steer dev team to build and test, deliver end to end solution to clients, in timely manner and in good quality. With more than 10 years hands on technical experience in companies in different size, including multinationals ones like Morgan Stanley and HSBC (my current employer), I’ve involved in almost every pieces of IT systems SDLC, with broad exposure in areas of application & solutions architecture, system consolidation and integration, etc. I'm regarded as Java guru as I’ve solid technical background. With good understanding in widely used framework and packages, primarily because I've read source code such as JDK, Spring,etc. Started my career as a software engineer, mainly develop enterprise systems in two technical stacks, Java and Web (HTML, CSS, JavaScript & frameworks). I’ve gradually developed to architect and domain experts in multiple areas such as core Java, SQL and J2EE. I’m a technology enthusiast as well, I’m willing to bestow my spare time on exploring cutting edge technologies and innovations. Besides keep on pushing stuff to my github repository, I’ve also been composing and posting technical blogs, range from cloud computing to blockchain, from Java tricks to database performance tuning, etc. In summary, I believe this position and myself are mutual fit, therefore I’m really hope to have a chance to further know each other. Please see my resume enclosed for additional information on my experience. Thank you for your time and consideration. I look forward to speaking with you about this employment opportunity. I can be reached anytime via email at <EMAIL> or mobile. <NAME><file_sep>/English.md --- # Tech article - the process flow below **depicts** and AR kick off meeting - Labor-intensive manual text mining approaches first *surfaced* in the mid-1980s - It is *trusim* that 80% of xxx - The technical *advances* have enabled the field to *advance* during the past decade. - This may **open the door to** exciting new results. - This set of techinques stemming from the scocial science . - This technology is now **broadly** applied for a wide variety of areas. - Want to share my **thoughts and reflections** on what was a valuable and rewarding vist in India. - My thanks to everyone who worked so hard to ensure all our events and interfactions ran so smoothly. - How to xxx, the **benefits and pitfalls** - Launch **full-fledged** business - At the most basic level, xxx - Server consolidation through virtualization lets you **get more out of** your existing servers. - organizations with **a global reach or business** that provide services xxx - The software architecutre and systems of a company are akin to a cardiovascular system in your average mamal. - You must **put the customer front and center **as you embark on iterations and new projects; **their experience will decide your success**. - As technology innovation hastens and spreads to enterprises beyond the traditional tech industries, developers must take an active role in championing these drivers for success. - Practice makes perfect - technological flux, you also lose the respect of those who do code - At the core of understanding this argument is the software change curve. The change curve says that as the project runs, it becomes exponentially more expensive to make changes.The change curve is usually expressed in terms of phases "a change made in analysis for $1 would cost thousands to fix in production". - before the modern computer science terminology prevailed. - Parenthesis: () - Braces: {} - Brackets: [] - a red herring: something is not important but just attract your attention from the main topic # Synonyms - `hallmark`: (outstanding)feature. The hallmark of object-orient design is encapsulation. - intuit: aware. ad you may intuit,XXX - **juggle**: compensate. V-T If you juggle lots of different things, such as your work and your family, you try to give enough time or attention to all of them. 尽量兼顾 例: The management team meets several times a week to juggle budgets and resources. 管理团队一周开几次会,力图兼顾预算和资源。 - **stinking**: hatred, disgusting. They are stinking animals. - **high time**: the right time. It's high time we should do xx. - **sought after**: desired, demanded. The most sought-after skills by Java developers. - **entropy**: chaos. this may lead to software entropy - **herald**: signal,indicate,announce, acclaim. The speech heralded a change in policy.This tech is a signal heralding a new generation of xx - **hasten**: hurry, move quickly. - **espionage**: spying. e.g. cyber espionage - **covert**: secret,furtive. covert operations. covert surveillance - **epicenter**: center, the central point of something, typically a difficult or unpleasant situation. You and your team are at the epicenter of this transformation. - **intuit**: find out, discover, be aware, understand or work out by instinct. As you might intuit,xxx (as you can imagine) - **ramification**: consequence, result, effect. A complex or unwelcome consequence of an action or event. e.g. the real ramification of the issue. This has a couple of important ramifications. - **headway**: movement,increment. I've made some more headway with this design - **hinder**: slow, impede,ZuAi. I won't hinder you, I'll go out. Those extra jobs will hinder the performance of the applicaitn. - **heterogeneous**: diverse in character or content. Working seamlessly with a heterogenous mixture of SLBs, including Cisco and third-party devices. - **dispersed**: distributed , with geographically dispersed data centers - **frenzy**:crazy, violent mental agitation - **reckon**: admit. He reckons there are some questions about xx - **commensurate**: in line with, appropriate to , according to, relative to. Such heavy responsibility must receive commensurate reward. Salary will be commensurate with age and experience. Permissions should be granted commensurate with requirements. - **commencement date**: staring date/begining date - *Ultimate* : eventually, at last - **convoluted**:complex, complicated . particulary technical sentences,arguments. Please avoid convoluted logic/answers. - **bona fide**: ?/b??n? ?f??di/ genuine, authentic,real, true. She was a bona fide expert - ** it suffice if **: it's ok if xx - * in conjunction with *: together with , independently or in conjunction with query - **discern**: recognize, discover. I can discern no difference between the two.Sentiment analysis invovles discerning subjective material xx - ** offer you my thanks for all of your efforts and dedication**: thanks for your efforts - **exemplify HSBC's values**: Your are exmaple of xx - ** throughout the year** : in the year - **to collaborate with each other**: work together with each other - **obfuscate**: make obscure, unclear, confuse, blur. Obfuscated code is source or machine code that has been made difficult to understand for humans. - **subside**: less severe, Become less intense, violent, or severe: ‘I'll wait a few minutes until the storm subsides’ # New words - **irreparably**: can be fixed/repaired. This action could irreparably damage our relationship. His eye got damaged irreparably. <file_sep>/TechNotes.md # Xaas [this wiki page](https://simple.wikipedia.org/wiki/Everything_as_a_service) list concepts. **Everything as a service (EaaS,[1] XaaS,[2] *aaS[3])** is a concept of being able to call up re-usable, fine-grained software components across a network.[4] It is a subset of cloud computing. The most common and successful example is software as a service (SaaS), but the term as a service has been associated and used with many core components of cloud computing including communication, infrastructure, data and platforms. Key characteristics Offerings tagged with the as a service suffix have a number of common attributes, including: - Low barriers to entry is a common method of offerings, with services typically being available to or targeting consumers and small businesses. - Little or no capital expenditure as infrastructure is owned by the provider. - Massive scalability is also common, though this is not an absolute requirement and many of the offerings have yet to achieve large scale. - Multitenancy enables resources (and costs) to be shared among many users. - Device independence[1] enables users to access systems regardless of what device they are using (e.g. PC, mobile,...etc.). - Location independence[1] allows users remote access to systems. Sub-categories A distinction can be made in this context with the following terminologies. - Software as a Service (SaaS) - Platform as a Service (PaaS) - Infrastructure as a Service (IaaS) # serverless architecure a video introduction: https://www.oreilly.com/ideas/an-introduction-to-serverless-software-architecture-2016?imm_mid=0ebce3&cmp=em-prog-na-na-newsltr_21061231 # Cloud computing Cloud computing is an approach to computing that builds on virtualization's efficient **pooling of resources** to create an on-demand, elastic, self-managing virtual infrastructure that can be **allocated dynamically as a service**. Virtualization uncouples applications and information <u>from the complexity of the underlying hardware infrastructure</u>. Virtualization, in addition to being the underlying technology for cloud computing, enables organizations of all sizes to make improvements in the areas of **flexibility and cost containment**. For example, with server consolidation, one physical server takes on the work of many servers by incorporating multiple servers as virtual machines. Also, ease of management and effective resource use are products of virtualizing the datacenter. When you virtualize your datacenter, management of the infrastructure becomes easier and you use your available infrastructure resources more effectively. Virtualization enables you to create a dynamic and flexible datacenter, and can reduce operating expenses through automation while also **reducing planned and unplanned downtime**. VMware vSphere **virtualizes and aggregates the underlying physical hardware resources across multiple systems and provides pools of virtual resources to the datacenter**. Virtualization is a process that breaks the hard connection between the physical hardware and the operating system and applications running on it. After being virtualized in a vSphere virtual machine, the operating system and applications are no longer constrained by the limits imposed by residing on a single physical machine. **VMware ESXi** : A virtualization layer run on physical servers that abstracts processor, memory, storage, and resources into multiple virtual machines. ## Windows Fail Over File Server ### Scale Out File server: this is **active-active**, every nodes of the cluster can accept and server _SMB_(Server Message Block) ### ## Fail Over ### GSS (Cisco Global Site Selector) The GSS is simply an intelligent DNS-resolution box. It monitors the status of a number of IP addresses and returns answers to DNS queries in a rough effort to balance traffic across multiple geographies. The traffic flow itself (between the client and the server) never traverses the GSS - the GSS simply tells the client which server to target by resolving a name to an IP address. So the GSS does not pass name references, or have anything to do with Kerberos. It simply receives a DNS request (UDP port 53), does a bit of analysis, and answers it with an IP address based on how the GSS rule is defined. No HTTP traffic ever hits the GSS. Finally, the GSS off-loads tasks from traditional DNS (Domain Name Service) servers by taking control of the domain resoltuion process for parts of your domain name space. ## PSTN The public switched telephone network (PSTN) is the aggregate of the world's circuit-switched telephone networks that are operated by national, regional, or local telephony operators, providing infrastructure and services for public telecommunication. The PSTN consists of telephone lines, fiber optic cables, microwave transmission links, cellular networks, communications satellites, and undersea telephone cables, all interconnected by switching centers, thus allowing most telephones to communicate with each other. Originally a network of fixed-line analog telephone systems, the PSTN is now almost entirely digital in its core network and includes mobile and other networks, as well as fixed telephones ## HSRP In computer networking, the Hot Standby Router Protocol (HSRP) is a Cisco proprietary redundancy protocol for establishing a fault-tolerant default gateway. The protocol establishes a framework between network routers in order to achieve default gateway failover if the primary gateway becomes inaccessible, in close association with a rapid-converging routing protocol like EIGRP or OSPF. HSRP routers send multicast Hello messages to other routers to notify them of their priorities (which router is preferred) and current status (Active or Standby). GSLB: Global Server Load Balancing SLB: Server Load Balances netezza DB # Java ## Read ascii files in Java ```java //In Java7 new String(Files.readAllLines(...)) //in Java 8 Files.lines(...).forEach(...) // without order Files.lines(...).forEachOrdered(...) // with order // traditional reader BufferedReader br=new BufferedReader(new FileReader("file.txt")); try{ StringBuilder sb=new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } //********************** // or use Java 7 try-with-resoures, i.e. auto close features try(BufferedReader br=new BufferedReader(new FileReader("file.txt"))){ StringBuilder xxx xxx } // using Scanner for(Scanner sc = new Scanner(new File("my.file")); sc.hasNext(); ) { String line = sc.nextLine(); ... // do something with line } // using 3rd libraries, like Apache Commone FileUtils, Guava,etc ``` When reading and writing text files: - it's often a good idea to use buffering (default size is 8K) - there's always a need to pay attention to exceptions (in particular, IOException and FileNotFoundException) The FileReader and FileWriter classes are a bit tricky, since they implicitly use the system's default character encoding. If this default is not appropriate, the recommended alternatives are, for example: ```java FileInputStream fis = new FileInputStream("test.txt"); InputStreamReader in = new InputStreamReader(fis, "UTF-8"); FileOutputStream fos = new FileOutputStream("test.txt"); OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8"); Scanner scanner = new Scanner(file, "UTF-8"); List<String> readSmallTextFile(String aFileName) throws IOException { Path path = Paths.get(aFileName); return Files.readAllLines(path, ENCODING); } void readLargerTextFile(String aFileName) throws IOException { Path path = Paths.get(aFileName); try (Scanner scanner = new Scanner(path, ENCODING.name())){ while (scanner.hasNextLine()){ log(scanner.nextLine()); } } } void readLargerTextFileAlternate(String aFileName) throws IOException { Path path = Paths.get(aFileName); try (BufferedReader reader = Files.newBufferedReader(path, ENCODING)){ String line = null; while ((line = reader.readLine()) != null) { log(line); } } } protected void processLine(String aLine){ Scanner scanner = new Scanner(aLine); scanner.useDelimiter("="); if (scanner.hasNext()){ String name = scanner.next(); String value = scanner.next(); log("Name is : " + quote(name.trim()) + ", and Value is : " + quote(value.trim())); ``` This example demonstrates using Scanner to read a file containing lines of **structured** data. One Scanner is used to read in each line, and a second Scanner is used to parse each line into a simple name-value pair. The Scanner class is **only used for reading**, not for writing. ## Java Object ### Methods in Java - clone - equals - finalize - getClass - hashCode - notify - notifyAll - toString - wait ## Clone x.clone()!=x x.clone().getClass()==x.getClass() (but not absolute requirements) x.clone().equasl(x) (but not absolute requirements) # Disaster Recovery - **DRaas**: Disaster Recovery-as-a-Service - **RPO**: Recovery Point Objective, refers to the point in time in the past to which you will recover - **RTO**: Recovery Time Objective, refers to the point in time in the future at which you will be up and running again. - **PTO**: Paid Time Off. PTO is what you take the day after you've sucessfully recovered from your disaster and your business is back up and running at full speed ahead. - **RCO**: Recovery COnsistency Objective defines a measurement for the consistency of distributed business data within interlinked systems after a disater incident. Similar to terms used in this context are **RCC** Recovery Consistency Charactereristics and **ROG**: recovery object granualarity. > <------RPO-----Disaster Strikes---RTO-----> Time between RPO and Disater means lost trasnactions Time between Diaster and RTO means time down Think of the above diagram as a timeline of events during which a disaster happens. The RPO will be the point to which you will have all data up to that point recovered. The gap between the disaster and the RPO will likely be lost as a result of the disaster. On the timeline, RTO is the point in the future at which you will be back up and running full speed ahead. The gap between the disaster and the RTO is the timeframe for which your app will be down and non-functioning. Robinson explains, “If you’re a Tier 1 banking high-transaction application, you will not be able to afford a very high RPO. You will need to have all transactions or real money will be lost as those transactions are lost.” He continues, “If you are referring to a website, however, which is updated monthly, you’re RPO can be as much as weeks back in time since not much will have changed, if anything. You are more comfortable going farther back in time to recover, and likely you will end up paying less for that RPO.” And finally, the acronym PTO stands for paid time off. ## RCO The term RCO focuses on business data consistency across multiple systems in SOA-driven business applications such as SAP ERP. While RTO and RPO are absolute per-system values, RCO is expressed as percentage measuring the deviation between actual and targeted state of business data across systems for individual business processes or process groups. Targeting 100% RCO for a business process (distributed across several systems) would mean that no business data deviation is allowed after a disaster incident whereas any target below 100% allows deviation. Target values for RCO increase with the criticality of the underlying business data: logistics and banking-related business processes are often characterized by higher RCO requirements than those of CRM or HR systems. ## Lambda “Abstraction is a concept that is familiar to us all from object-oriented programming. The difference is that object-oriented programming is mostly about abstracting over data, while functional programming is mostly about abstracting over behavior” ” Functional Programing is a team that means different things to different people. At the heart of functional programing is thinking about your problem domain in terms of immutable values and functions that translate between them. - The problem of annonymouse function is if you are going to use a variable external, the variable has to be declared as final. - “It’s possible to refer to variables that aren’t final; however, they still have to be effectively final. Although you haven’t declared the variable(s) as final, you still cannot use them as nonfinal variable(s) if they are to be used in lambda ” - “The implication of being effectively final is that you can assign to the variable only once. Another way to understand this distinction is that lambda expressions capture values, not variables.” - Lambda expresssion are staticaly typed. - “A functional interface is **an(any) interface** with a **single abstract method** that is **used as the type of a lambda expression**.” - “Example 2-9. **Diamond operator inference** for variables ```java Map<String, Integer> oldWordCounts = new HashMap<String, Integer>(); Map<String, Integer> diamondWordCounts = new HashMap<>(); ” ``` - “A lambda expression is a method without a name that is used to pass around behavior as if it were - To create a thread safe DateFormatter ```java public final static ThreadLocal<DateFormatter> formatter = ThreadLocal.withInitial(() -> new DateFormatter(new SimpleDateFormat("dd-MMM-yyyy"))); ``` ## Streams > From external iteration to Internal iteration - To avoid boilerplate code. ### map - Map let you apply this funciton to a stream of values, producting anotehr stream of the new value. i.e. convert a value of one **type** into **another type** - “Example 3-13. Finding the shortest track with streams ```java List<Track> tracks = asList(new Track("Bakai", 524), new Track("Violets for Your Furs", 378), new Track("Time Was", 451)); Track shortestTrack = tracks.stream() .min(Comparator.comparing(track -> track.getLength())) .get(); assertEquals(tracks.get(1), shortestTrack); ``` - **reduce** ```java BinaryOperator<Integer> accumulator=(x,y)->x+y; int count=accumulator.apply(accumulator.apply(accumulator.apply(0, 1), 2), 3); Assert.assertEquals(count, 6); ``` - Sample of get nationality of an album ```java “Set<String> origins = album.getMusicians() .filter(artist ->artist.getName().startsWith("The")) .map(artist -> artist.getNationality()) .collect(toSet()); ``` - The calls to musicians, filter, and map all **return Stream** objects, so they are **lazy**, while the **collect method is eager**. - A **higher-order function** is a function that either take another function as an argument or returns a function as its result. - The **default** method is a virtual method- that is, the opposite of a static method. <file_sep>/cvStuff.md Customer-first and think-as-owner are always first principle in my phylosophy. I was considered as a dependable go-to person and SME when working with customers. At AWS, customer obsession is in our DNA. As a trusted advisor to our customers and partners you will work with AWS sales, business development, solutions architecture and product teams to craft highly scalable, flexible and resilient cloud architectures that address customer business problems and accelerate the adoption of AWS services. As a successful Solution Architect you will not only deliver on our credo of "Work hard. Have fun. Make history" you will love what you do and your enthusiasm will be contagious across our teams and customers. In return we provide you the chance to work with some of the smartest minds from around the world who are leading the way in cloud based architecture design. On a daily basis you will be challenged to think differently, learn more, and build elegant solutions. If you are highly technical and experienced in architecting or deploying Cloud/Virtualization solutions in enterprise customers then this could be the role for you. Remember, this is a client facing role so you must be comfortable talking with CIOs, CTOs and CISOs. It goes without saying that you must have experience in architecting infrastructure solutions using both Linux/Unix and Windows with specific recommendations on server, load balancing, HA/DR, networking & storage architectures. Couple all that with a baseline knowledge of or even certification in AWS and this role is made for you! Want to learn more? Apply below or call <NAME>, Talent Acquisition <EMAIL> Why are we making the changes? Transformation is a critical function for the Group, leading significant change, including end to end programmes of work which create simpler, better and faster banking experiences for our customers, and make life easier for our colleagues. ‎ Transformation has made good progress in recent months, especially in up-skilling our programme managers, improving our methods and tools in conjunction with Technology, and in establishing outcome based vendor partnerships. Changing reporting lines to business COOs will keep Transformation teams much more connected to the priorities of the businesses. <file_sep>/coverLetter.md <NAME> Permanent Resident Mail: <EMAIL> Dear Hiring Manager This is in regards to my interest in applying for the job Job Reference: 15143 posted on seek.com. I believe I’m a pretty competitive candidate for this vacancy, due to my ability, previous proven experience and expertise. Which is fairly related to desired skills posted in the JD. Currently I’m working in IT department in HSBC, being an IT specialist and providing solutions for our customers. Day to day jobs including (but not limited to) talk to users to gather requirements, analysis & design, POC (Prove Of Concept) or prototype, architect best solution, steer dev team to build and test, deliver end to end solution to clients, in timely manner and in good quality. With more than 10 years hands on technical experience in various companies, including multinationals ones like Morgan Stanley and HSBC (my current employer), I’ve involved in almost every pieces of IT systems SDLC, have broad exposure in areas of application & solutions architecture, system consolidation and integration, etc. I’ve solid technical background. Started my career as a software engineer, mainly develop enterprise systems in two technical stacks, Java and Web (HTML, CSS, JavaScript & frameworks). I’ve gradually developed to architect and domain experts in multiple areas such as core Java, SQL and J2EE. I’m a technology enthusiast as well, I’m willing to bestow my spare time on exploring cutting edge technologies and innovations. Besides keep on pushing stuff to my github repository, I’ve also been composing and posting technical blogs, range from cloud computing to blockchain, from Java tricks to database performance tuning, etc. In summary, I believe this position and myself are mutual fit, therefore I’m really hope to have a chance to further know each other. Please see my resume enclosed for additional information on my experience. Thank you for your time and consideration. I look forward to speaking with you about this employment opportunity. I can be reached anytime via email at <EMAIL>or mobile. <NAME><file_sep>/apart.md - Check out the developer. Find out who the developer is, what else have they done, have they always delivered? Were other buyers happy with the end results? - What stage is it at? Is there a development approval, has it been put out to tender? - Who is insuring the development? and what level of insurance is there? - 澳洲楼花网 - http://www.prd.com.au/ (reports) - www.firb.gov.au/content/faq.asp - http://www.apartmentdevelopments.com.au/ - http://www.opencorp.com.au/avoid-500k-mistake/?utm_source=SPI&utm_medium=POPUP&utm_campaign=avoid500DEC&utm_term=pi-miniguide&utm_content=630 - http://www.news.com.au/finance/real-estate/buying/failed-offtheplan-apartments-secondhand/news-story/878871e5d82175b424b2cac6ed796374 - If an off-the-plan sale falls through, the property will be considered second-hand, The Australian reports. This means thousands of foreign buyers will be stopped from picking up the properties, lowering the eventual resale price. - http://www.corelogic.com.au/ - http://www.smartpropertyinvestment.com.au/opinion/13125-buying-and-selling-off-the-plan - http://www.abc.net.au/news/2016-02-05/off-the-plan-apartments-carry-high-risks/7144040 劉續指,澳洲物業大致分三類:獨立屋(House)、聯排屋(Townhouse)和多層式住宅(Apartment):「澳洲買樓大部份是永久業權(Freehold),悉尼部份海邊物業則屬於租用業權(Leasehold)。」獨立屋是獨立式住宅,業主擁有房屋和土地。聯排屋則由數幢物業並排而成,單位之間是牆貼牆,共同擁有1幅牆。聯排屋業主雖然是各自擁有自己所屬的範圍,但共同享用一些公眾空間如車路。多層式住宅則是香港最常見的住宅大廈,每個單位業主是共同擁有該土地。 新樓可包括樓花(Off-Plan)和現樓。樓花定義是未建成的物業,並由發展商直接向買家銷售。若買家再將物業轉售,該物業便不等於新樓。此外,現樓若獲發展商保證在建成後12個月內未有人入住,也可定義為新樓。 至於「摩貨」是指買家在完成正式買賣合約前,把已購入的物業轉售。澳洲法例規定在此交易中不能獲利,必須平手離場,稅項如印花稅需由買家支付。據知,目前僅維多利亞省墨爾本,可在樓花期「摩貨」轉手一次。
cf3b048ce459638d936ffbbb29ce2a81c37fdf3a
[ "Markdown", "Java", "Shell" ]
12
Markdown
CloudsDocker/misc
be1be55d311fdc739b7e4d077770b2633f7af07c
e25fb6f5a506d498c0cf82fe270a9a612e394371
refs/heads/master
<file_sep>var gulp = require('gulp'); var pug = require("gulp-pug"); var sass = require("gulp-sass"); var plumber = require("gulp-plumber"); var gutil = require("gulp-util"); var del = require("del"); var babel = require('gulp-babel'); var watch = require("gulp-watch"); var runSequence = require('run-sequence').use(gulp); var connect = require('gulp-connect'); var pug_path = ['src/pug/*.pug','src/pug/**/*.pug']; var sass_path = ['src/scss/app.scss','src/scss/**/*.scss']; var js_path = ['src/js/main.js']; gulp.task('pug',function(){ return gulp.src('src/pug/*.pug') .pipe(plumber()) .pipe(pug()) .on("error", gutil.log) .pipe(gulp.dest('dist')) .pipe(connect.reload()) }); gulp.task('sass', function() { return gulp.src(sass_path) .pipe(plumber()) .pipe(sass()) .on("error", gutil.log) .pipe(gulp.dest('dist/assets/css')) .pipe(connect.reload()) }); gulp.task('clean', function() { return del.sync('dist'); }); gulp.task('watch',['pug','sass'], function(){ gulp.watch(sass_path,['sass']); gulp.watch(pug_path,['pug']); gulp.watch(js_path,['js']); }); gulp.task('fonts', function(){ return gulp.src(['src/assets/fonts/*']) .pipe(gulp.dest('dist/assets/fonts')) }); gulp.task('js', function() { return gulp.src(js_path) .pipe(plumber()) .pipe(gulp.dest('dist/assets/js')); }); gulp.task('connect', function () { connect.server({ root: 'dist/', livereload: true }); }); gulp.task('default', function(){ runSequence('clean','fonts','js', ['pug', 'sass'],['connect', "watch"]) });
f300284f53628d5fdd47855211faa0f2d3d49570
[ "JavaScript" ]
1
JavaScript
annakarp363/test
7d5cd373bb07db45eab1258a90d5d942479ee405
981515041a42b5050359d2d418be9e725b5c787a
refs/heads/master
<file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePropinsi extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('propinsi', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('nama_propinsi')->nullable(); $table->string('kode_propinsi')->nullable(); $table->string('long_prop')->nullable(); $table->string('lat_prop')->nullable(); $table->string('status_prop')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('propinsi'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateKabupaten extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('kabupaten', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('nama_kabupaten')->nullable(); $table->string('kode_kabupaten')->nullable(); $table->string('propinsi_id')->nullable(); $table->string('long_kab')->nullable(); $table->string('lat_kab')->nullable(); $table->string('status_kab')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('kabupaten'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use CRUDBooster; class FrontController extends Controller { public function get_index(){ $data['kabupaten']=CRUDBooster::get('kabupaten','status_kab = "active" '); // dd($data['kabupaten']); return view('layout',$data); } }
47082f79341580dc877d1333f1a841ccc17c4246
[ "PHP" ]
3
PHP
ridwan-dev/project-prototype
c4af6c46c09497b247b921c34a5774779be15ae8
7d5d2467cdd5df94a352ba4a4002277190e2e6bb
refs/heads/master
<repo_name>oren/hangjs-2014<file_sep>/example/app/999.js /* let's create a messaging web app using: * ecstatic for static files * routes for routing * leveldb as the database * trumpet for server-side html rendering * hyperspace for shared server<->browser rendering * multilevel to use leveldb from the browser * shoe for websockets as a stream * browserify to use npm packages in the browser $ wc -l *.js render/*.js 15 finished/browser.js 21 finished/router.js 21 finished/server.js 13 finished/render/msg.js 70 total */ <file_sep>/example/app/990.js /* let's create a messaging web app using: * ecstatic for static files * routes for routing * leveldb as the database * trumpet for server-side html rendering * hyperspace for shared server<->browser rendering * multilevel to use leveldb from the browser * shoe for websockets as a stream * browserify to use npm packages in the browser */ <file_sep>/example/app/340_render_msg.js var hyperspace = require('hyperspace'); var fs = require('fs'); var html = fs.readFileSync(__dirname + '/msg.html', 'utf8'); module.exports = function () { return hyperspace(html, function (row) { return { '.time': row.key.split('!')[1], '.who': row.value.who, '.body': row.value.message }; }); }; <file_sep>/example/app/330_render_msg.js var hyperspace = require('hyperspace'); var fs = require('fs'); var html = fs.readFileSync(__dirname + '/msg.html', 'utf8'); module.exports = function () { return hyperspace(html, function (row) { // ... }); }; <file_sep>/example/splicer/pipeline.js var through = require('through2'); var a = through.obj(function (x, e, next) { this.push(x+1); next() }); var b = through.obj(function (x, e, next) { this.push(x/3); next() }); var c = through.obj(function (x, e, next) { this.push(x*100); next() }); var splicer = require('stream-splicer'); var p = splicer.obj([ a, b, c ]); // p.splice(1,2, through.obj(function (x,e,next) { this.push(x*111); next() })); p.on('data', console.log); p.write(5); p.write(6); p.write(7); <file_sep>/example/app/410_server.js var http = require('http'); var ecstatic = require('ecstatic')(__dirname + '/static'); var level = require('level'); var db = level('app.db', { valueEncoding: 'json' }); var router = require('./router.js')(db); var server = http.createServer(function (req, res) { var m = router.match(req.url); if (m) m.fn(req, res, m); else ecstatic(req, res); }); server.listen(8000); var shoe = require('shoe'); var sock = shoe(function (stream) { // ... }); sock.install(server, '/sock'); <file_sep>/example/app/290_router.js var routes = require('routes'); var fs = require('fs'); var path = require('path'); var trumpet = require('trumpet'); var render = { msg: require('./render/msg.js') }; module.exports = function (db) { var r = routes(); r.addRoute('/', function (req, res, params) { var tr = trumpet(); var msgs = db.createReadStream({ start: 'msg!', end: 'msg!\uffff' }); msgs.pipe(render.msg()).pipe(tr.createWriteStream('#messages')); readStream('index.html').pipe(tr).pipe(res); }); return r; }; function readStream (file) { return fs.createReadStream(path.join(__dirname, 'static', file)); } <file_sep>/example/app/210_router.js var routes = require('routes'); module.exports = function (db) { var r = routes(); // ... return r; }; <file_sep>/example/app/finished/readme.markdown # install With [npm](https://npmjs.org) do: ``` npm install ``` # build browserify bundle ``` npm run build ``` # run ``` npm start ``` <file_sep>/example/app/230_router.js var routes = require('routes'); var trumpet = require('trumpet'); var render = { msg: require('./render/msg.js') }; module.exports = function (db) { var r = routes(); r.addRoute('/', function (req, res, params) { var tr = trumpet(); }); return r; }; <file_sep>/example/app/220_router.js var routes = require('routes'); module.exports = function (db) { var r = routes(); r.addRoute('/', function (req, res, params) { // ... }); return r; }; <file_sep>/example/app/start.sh #!/bin/bash vi `ls -1 *.{js,html,json}` <file_sep>/readme.markdown # peer-directed collaborative projects ![intro](images/000_intro.png) ![substack](images/010_substack.png) ![p2p](images/100_p2p.png) ![no boss](images/110_no_boss.png) ![dat graph](images/120_dat_graph.png) ![big small](images/130_big_small.png) ![divide and conquer](images/140_divide_and_conquer.png) ![trumpet](images/200_trumpet.png) ![transform](images/210_transform.png) ![bugs](images/220_bugs.png) ![tokenize](images/230_tokenize.png) ![pr](images/240_tokenize_pr.png) ![demo](images/250_demo.png) ![select](images/260_select.png) ![pr](images/270_select_pr.png) ![demo](images/280_demo.png) ![cssauron](images/300_cssauron.png) ![cssauron tweet](images/310_cssauron_tweet.png) ![splicer](images/400_splicer.png) ![splicer io](images/410_splicer_io.png) ![demo](images/420_demo.png) ![browserify](images/500_browserify.png) ![collaborators](images/510_browserify_collaborators.png) ![bugs](images/515_browserify_bugs.png) ![module-deps](images/520_module_deps.png) ![browser-pack](images/530_browser_pack.png) ![demo](images/540_demo.png) ![labeled splicer](images/600_labeled_splicer.png) ![oakland](images/610_oakland.png) ![browserify splice](images/620_browserify_splice.png) ![demo](images/630_demo.png) ![zero](images/700_zero.png) ![demo](images/710_demo.png) ![voxeljs](images/800_voxeljs.png) ![voxeljs modules](images/805_voxel_modules.png) ![demo](images/810_demo.png) ![nodeschool](images/900_node_school.png) ![exit](images/999_exit.png) <file_sep>/example/app/finished/browser.js var sock = require('shoe')('/sock'); var db = require('multilevel-feed')(); sock.pipe(db.createRpcStream()).pipe(sock); window.db = db; var render = require('./render/msg.js'); var feed = db.livefeed({ start: 'msg!', end: 'msg!\uffff' }); feed.pipe(render().sortTo('#messages', cmp)); function cmp (a, b) { var at = Number(a.querySelector('.time').textContent); var bt = Number(b.querySelector('.time').textContent); return bt - at; }
99cb96be499ed9bee7187c1753914e828fae22d8
[ "JavaScript", "Markdown", "Shell" ]
14
JavaScript
oren/hangjs-2014
3eb2d17a3e0dc37b51151fecdaef1244f63dc246
71c36ab47353c2911e01c16d2bd811229c29ddf4
refs/heads/master
<file_sep># Collection of user methods for Kirby 3 ## `hasPanelAccess()` Check if the logged in user role can access the Panel. Return type: `bool` <file_sep><?php Kirby::plugin('texnixe/userMethods', [ 'usersMethods' => [ 'hasPanelAccess' => function (): bool { return $this->role()->permissions()->for('access', 'panel'); } ] ]);
3394621ae725b1089452bb8cbec1e36992a249fd
[ "Markdown", "PHP" ]
2
Markdown
texnixe/k3-userMethods
80ffba357374c83ae3aa7007358fb2d62f6d1fb9
1d779e75e7631c6655640f83f254f7ca09245eaf
refs/heads/master
<file_sep>import Glide from '@glidejs/glide' export const flowersSlider = (element, options = { type: 'slider' }) => new Glide(element, { type: options.type, startAt: 0, perView: 6, autoplay: 7000, breakpoints: { 991: { perView: 4, }, 767: { perView: 3, }, 575: { perView: 1, }, }, }).mount() export const reviewsSlider = (element, options = { type: 'slider' }) => new Glide(element, { type: options.type, startAt: 0, perView: 1, }).mount() <file_sep># flowers-delivery Мой выпускной проект из Академии верстки Артёма Исламова <file_sep>import '../sass/style.sass' import './components/card' import { modal } from './components/modal' import { flowersSlider, reviewsSlider } from './components/slider' flowersSlider('.header-slider', { type: 'carousel', }) reviewsSlider('.reviews-slider', { type: 'carousel', }) <file_sep>const buttons = document.querySelectorAll('.btn-qty') buttons.forEach(btn => { btn.addEventListener('click', function () { const input = this.parentElement.querySelector('.input-qty') let inputValue = +input.value input.value = this.dataset.direction === 'plus' ? inputValue + 1 : inputValue <= 1 ? inputValue : inputValue - 1 }) }) <file_sep>function _createModal( title = 'Розы', desc = 'Розы — это популярные цветы. На данный момент существует несколько тысяч сортов роз. Розы — это цветы, которые обладают волшебной красотой. Тысячи легенд сложено о розе. Ее любят все, ну и даже преклоняются пред ней. Все народы мира чествуют это прекрасное растение.', ) { const modal = document.createElement('div') modal.classList.add('mymodal') modal.classList.add('visibility-hidden') modal.insertAdjacentHTML( 'afterbegin', ` <div class="modal-overlay" data-close="close"> <div class="modal-body"> <h2 class="modal__title">${title}</h2> <!-- /.modal__title --> <p class="modal__desc">${desc}</p> <!-- /.modal__desc --> <button class="modal__close" data-close="close">&times;</button> </div> <!-- /.modal-body --> </div> <!-- /.modal-overlay --> `, ) document.body.appendChild(modal) return modal } export const modal = function (options) { const $modal = _createModal(options) $modal.addEventListener('click', event => { // console.log(event.target.dataset.close) // event.target.dataset.close === 'close' ? console.log('y') : console.log('n') }) return { open() { document.body.classList.add('overflow-hidden') $modal.classList.remove('visibility-hidden') $modal.classList.add('open') }, close() { $modal.classList.add('visibility-hidden') $modal.classList.remove('open') document.body.classList.remove('overflow-hidden') }, destroy() {}, } } window.modal = modal()
cb318450f2a8761401c6f49d718c080f188dc75c
[ "JavaScript", "Markdown" ]
5
JavaScript
imgrekov/flowers-delivery
657d1f9127d723bb0ad77b266fbda9094172c3f0
ab2bf07200f9fd36b0e0820870bff44ebecf9655
refs/heads/master
<file_sep>// // AppMacro.h // InfoCapture // // Created by feng on 14/04/2017. // Copyright © 2017 feng. All rights reserved. // #ifndef AppMacro_h #define AppMacro_h #define kOffLineDebug 0 //是否离线debug /***********NSuserDefault_Key**************/ //医院搜索记录 #define CUS_SEARCH_HISTORY @"cus_search_history" //产品搜索记录 #define PRD_SEARCH_HISTORY @"prd_search_history" /**********localDirName*************/ //图片上传缓存 #define kFilePath_upload @"tmp/upload" //报告下载缓存 #define kFilePath_report @"tmp/report" /******************NotificationString****************/ #define KNOTIFICATION_LOGINCHANGE @"loginStateChange" /******************SystomFunction****************/ //版本 #define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame) #define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending) #define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) #define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending) #define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending) // 屏幕高度 #define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height // 屏幕宽度 #define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width //keyWindow宽度 #define kWindowWith [UIApplication sharedApplication].keyWindow.bounds.size.width //keyWindow高度 #define kWindowWith [UIApplication sharedApplication].keyWindow.bounds.size.width #define RGBColor(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)] #define kSubjectColor RGBColor(77, 163, 169, 1) #define kSubjectColor_Red RGBColor(238, 79, 100, 1) #define kBgColor RGBColor(235, 235, 235, 1) #define kGrayFontColor RGBColor(153, 153, 153, 1) #define kBlackFontColor RGBColor(51, 51, 51, 1) #define kPlaceHolderColor RGBColor(153, 153, 153, 1) #define kSeparateLineColor RGBColor(200, 200, 200, 1) #define kHugeFont [UIFont systemFontOfSize:20] #define kBigFont [UIFont systemFontOfSize:17] #define kMidFont [UIFont systemFontOfSize:14] #define kSmallFont [UIFont systemFontOfSize:12] #endif /* AppMacro_h */ <file_sep>platform :ios, '8.0' target 'myBGI' do pod 'MJExtension' #转换速度快、使用简单方便的字典转模型框架 #pod 'YYCache' #缓存包含在YYKit中 #pod 'Reachability' #网络检测 pod 'AFNetworking' #网络通讯 pod 'SDWebImage' #图片缓存和异步加载 #pod 'SDWebImage-ProgressView' #图片加载进度条 #pod 'FMDB' #SQLite pod 'Masonry' #autolayout pod 'iCarousel' #左右滑动 pod 'MBProgressHUD' #提示 pod 'JDStatusBarNotification' #状态栏提示 #pod 'HMSegmentedControl' #头部tabbar pod 'IQKeyboardManager' #全局键盘管理 pod 'KMNavigationBarTransition' #pod 'NYXImagesKit' #图像特效处理工具包 pod 'MJRefresh' #pod 'PopoverView' #pod 'XLForm', '3.2' #个人资料填写UI pod 'FSCalendar' #日历 pod 'iVersion' #版本更新提示 #pod 'YYText' #pod 'SVProgressHUD' end <file_sep>// // InterfaceMacro.h // InfoCapture // // Created by feng on 14/04/2017. // Copyright © 2017 feng. All rights reserved. // #ifndef InterfaceMacro_h #define InterfaceMacro_h //#define domainURL @"Http://172.17.117.8:8080" #define domainURL @"http://192.168.224.9:8090" //登录 #define kLoginUrl @"/Front/app/appLogin.action" //退出登录 #define kLogoutUrl @"/Front/app/appLogout.action" //查询医院 #define kQueryCustomer @"/Front/app/queryCustomerForApp.action" //查询产品 #define kQueryProduct @"/Front/app/queryProductForApp.action" //上传照片 #define kUploadPic @"/Front/servlet/FileSteamUpload" //查询结果 #define kQuerySample @"/Front/app/querySampleImportMainTableForApp.action" //查询交付按产品 #define kQueryDelieverProduct @"/Front/app/queryDeliverCountByProduct.action" //查询交付按客户 #define kQueryDelieverCustom @"/Front/app/queryDeliverCountByCustomer.action" //查询到样统计按产品 #define kQueryReceiveProduct @"/Front/app/queryReceiveCountByProduct.action" //查询到样统计按客户 #define kQueryReceiveCustom @"/Front/app/queryReceiveCountByCustomer.action" #endif /* InterfaceMacro_h */
5b7211323c13cf288c4dfd34c6861fb85dd36375
[ "C", "Ruby" ]
3
C
fengfengfly/myBGI
44b5fe400b6fe8bab3ac769cfdb1cd9f5ede3df3
97a5c5e0fa6cffa5416c344ae404105b5d1fb800
refs/heads/main
<file_sep>const displayImage = e => { let imageId = e.id; let img = document.getElementById('img'); let doorIllusion = document.getElementsByClassName('door-illusion')[0] img.setAttribute('src', `../img/${imageId}.png`); var t1 = new TimelineLite(); t1.fromTo(doorIllusion, 1, {boxShadow: 'inset 0em 0em 0em #000'}, {boxShadow : 'inset 0em 3 em 2em #000', ease:Power4.easeOut}) .fromTo(img, 1, {top: '-240px'}, {top:'80px', ease:Power4.easeOut}) .fromTo(doorIllusion, .03, {boxShadow: 'inset 0em 3em 2em #000'}, {boxShadow : 'inset 0em 0em 0em #000', ease:Power4.easeOut}) .fromTo(doorIllusion, .01, {overflow: 'hidden'}, {overflow:'visible', ease:Power4.easeOut}) .fromTo(img, 1, {scale: 1}, {scale: 1.4, ease:Back.easeOut.config(4)}) t1.eventCallback('onStart', disableLinks) t1.eventCallback('OnComplete', enableLinks) let links = document.getElementsByClassName('country') function disableLinks(){ for(l=0;l<length;l++){ if(links[l].getAttribute('id') == imageId){ links[l].style.pointerEvents = 'auto'; }else{ links[l].style.pointerEvents = 'none'; } } } function enableLinks(){ for (l=0; l<linnks.length; l++){ links[l].style.pointerEvents = 'auto'; } } }<file_sep># Website-Design Landing Page Design
7ff98cd6ab80aae713f7d60937563def7aa758c8
[ "JavaScript", "Markdown" ]
2
JavaScript
devinnolanp/Website-Design
7e634ec3e4fd6c071538927c9c75727079f7b1d4
b47e490d9d87281a13bf334b740cd533b6ae8290
refs/heads/master
<file_sep># prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) output = nil # lowest_val = nil values = [] # since I can't use values name_hash.each do |name, val| values << val end lowest_val = values[0] values.each do |val| if val < lowest_val lowest_val = val end end name_hash.each do |name, val| if lowest_val == val output = name end end output end
abd5e51b66d7255328e28ea63aaab0a472b48ecc
[ "Ruby" ]
1
Ruby
skel11417/key-for-min-value-dc-web-career-021819
573c7da3f48fbc810416664f8afc071973daa466
48834ca7194202508fbc519dfdb07145dcb99192
refs/heads/master
<repo_name>ivanarielcaceres/react-native-redux-media<file_sep>/src/services/project.js import { API_IP, API_PORT, API_PROTOCOL } from '../constants'; const base64 = require('base-64'); const create = (token, name, description, images) => { console.log('token', token); console.log('name', name); console.log('desc', description); let headers = new Headers(); headers.append("Authorization", "Basic " + base64.encode(token+":unused")); headers.append("Accept", "application/json"); headers.append("Content-Type", "application/json"); return fetch(`${API_PROTOCOL}://${API_IP}:${API_PORT}/api/projects`, { method: "POST", headers: headers, body: JSON.stringify({ name: name, description: description, images: images }) }); } const getProjects = (token) => { let headers = new Headers(); headers.append("Authorization", "Basic " + base64.encode(token+":unused")); return fetch(`${API_PROTOCOL}://${API_IP}:${API_PORT}/api/projects`, { headers: headers }); } export const projectService = { create, getProjects }<file_sep>/src/components/UserDetail.js import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, Text, TextInput, TouchableOpacity, KeyboardAvoidingView } from 'react-native'; import { connect } from 'react-redux'; import { changePassword, logout } from '../actions'; import { bindActionCreators } from 'redux'; import { NavigationActions } from 'react-navigation' import Toast from 'react-native-easy-toast'; class UserDetail extends Component { constructor(props) { super(props); this.state = { password:'', passwordConfirm: '' } } showToast(message) { this.refs.toast.show(message, 3000); } saveChanges(token) { let password = <PASSWORD>; let passwordConfirm = <PASSWORD>; if (passwordConfirm == password) { const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName: 'Login'}) ] }) this.props.changePassword(token, password, resetAction, this.props.navigation); return; } this.showToast("Password doesn't match"); } logout(navigate) { const { username } = this.props.user; console.log('LOGOUT username', username) const resetAction = NavigationActions.reset({ index: 0, actions: [ NavigationActions.navigate({ routeName: 'Login'}) ] }) this.props.logout(resetAction, this.props.navigation); } close(navigate) { navigate('Workspace'); } render() { if (this.props.changePasswordErrorMessage) { this.showToast(this.props.changePasswordErrorMessage); } const { navigate } = this.props.navigation; const { fullname, username, token } = this.props.user; return ( <KeyboardAvoidingView style={styles.container} behavior="padding" > <View style={styles.userOption}> <TouchableOpacity style={styles.button} onPress={this.logout.bind(this, navigate)}> <Text>Logout</Text> </TouchableOpacity> <TouchableOpacity style={styles.button} onPress={this.close.bind(this, navigate)}> <Text>Close</Text> </TouchableOpacity> </View> <View style={styles.user}> <View > <Text style={{fontSize: 20, fontWeight: 'bold'}}>{ fullname }</Text> </View> <View style={styles.mail}> <Text>{ username }</Text> </View> </View> <View style={styles.inputContainer}> <Text style={{fontSize: 15, fontWeight: 'bold'}}>Security</Text> <TextInput style={styles.input} placeholder={'Password'} placeholderTextColor='gray' underlineColorAndroid='gray' onChangeText={(password) => this.setState({'password': password})} secureTextEntry={true} /> <TextInput style={styles.input} placeholder={'Verify Password'} placeholderTextColor='gray' underlineColorAndroid='gray' onChangeText={(password) => this.setState({'passwordConfirm': password})} secureTextEntry={true} /> </View> <View style={styles.save}> <TouchableOpacity style={styles.buttonSave} onPress={this.saveChanges.bind(this, token)}> <Text>Save changes</Text> </TouchableOpacity> </View> <Toast ref="toast"/> </KeyboardAvoidingView> ); } } const styles = StyleSheet.create({ container: { flex: 1, marginTop: 20, backgroundColor: 'white' }, user: { alignItems: 'flex-start', marginLeft: 30, paddingBottom: 10, borderBottomColor: '#439fe0', borderBottomWidth: 3, }, input: { backgroundColor: 'rgba(255, 255, 255, 0.4)', width: 300, height: 40, color: 'gray', marginTop: 5, }, inputContainer: { marginTop: 20, // flex: 1, alignItems: 'flex-start', marginLeft: 30, justifyContent: 'center', }, buttonImage: { alignItems: 'center', justifyContent: 'center', height: 100, width: 100, borderRadius: 50, borderColor: 'black', borderWidth: 1, marginLeft: 50, }, mail: { // flex: 1, flexDirection: 'row', justifyContent: 'space-between', }, button: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', height: 30, width: 70, borderRadius: 20, borderWidth: 1, borderColor: '#000000' }, buttonSave: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', height: 30, width: 100, borderRadius: 20, borderWidth: 1, borderColor: '#000000' }, save: { alignItems: 'flex-end', marginRight: 10, marginTop: 150, }, userOption: { flexDirection: 'row', justifyContent: 'flex-end', marginRight: 10, marginBottom: 10, marginTop: 20, } }); function mapStateToProps(state) { const { loading, userErrorMessage, changePasswordErrorMessage } = state.user; const { user } = state.authentication; return { loading, user, userErrorMessage, changePasswordErrorMessage } } const mapDispatchToProps = (dispatch) => { return { changePassword: bindActionCreators(changePassword, dispatch), logout: bindActionCreators(logout, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(UserDetail)<file_sep>/index.js import 'expo' import React, { Component } from 'react'; import { AppRegistry, StyleSheet, View, } from 'react-native'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux' import thunkMiddleware from 'redux-thunk'; import rootReducer from './src/reducers'; import Main from './src/components/Main'; const store = createStore( rootReducer, applyMiddleware( thunkMiddleware ) ); export default class loginAnimation extends Component { render() { return ( <Provider store={store}> <View style={styles.container}> <Main /> </View> </Provider> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F5FCFF', }, }); AppRegistry.registerComponent('main', () => loginAnimation); <file_sep>/src/reducers/user.js import { USERINFO_REQUEST, USERINFO_SUCCESS, USERINFO_FAILURE, CHANGE_PASSWORD_REQUEST, CHANGE_PASSWORD_SUCCESS, CHANGE_PASSWORD_FAILURE } from '../constants'; export function user(state = {}, action) { switch (action.type) { case USERINFO_REQUEST: return { loading: true }; case USERINFO_SUCCESS: return { user: action.user }; case USERINFO_FAILURE: return { userErrorMessage: action.error }; case CHANGE_PASSWORD_REQUEST: return { updatingPassword: true }; case CHANGE_PASSWORD_SUCCESS: return { updatedPassword: true }; case CHANGE_PASSWORD_FAILURE: return { changePasswordErrorMessage: action.error }; default: return state } }<file_sep>/src/components/auth/SignUpStep1.js import React, { Component, PropTypes } from 'react'; import Logo from '../Logo'; import { View, StyleSheet, TextInput, Text, Image, TouchableOpacity, KeyboardAvoidingView } from 'react-native'; import Dimensions from 'Dimensions'; import ButtonSubmit from '../ButtonSubmit'; import dismissKeyboard from 'react-native-dismiss-keyboard'; import { NavigationActions } from 'react-navigation' import NavBar, { NavGroup, NavButton, NavTitle } from 'react-native-nav' export default class SignUpStep1 extends Component { constructor() { super() this.state = { email: '', fullname: '', }; } onPress(navigate, email) { //GOTO TO SIGNUP STEP2 let fullname = this.state.fullname dismissKeyboard() navigate('SignUpStep2', {'email': email, 'fullname': fullname}) } render() { const backAction = NavigationActions.back({ key: null }) let email = this.props.navigation.state.params.email const { navigate } = this.props.navigation; const win = Dimensions.get('window'); return ( <KeyboardAvoidingView style={styles.container} behavior="padding" > <NavBar style={styles}> <NavButton style={styles.navButton} onPress={() => this.props.navigation.dispatch(backAction)}> <Image style={styles.imageNav} resizeMode={"contain"} source={{uri: 'https://image.ibb.co/bvwDsm/if_back_172570_1.png'}} /> </NavButton> </NavBar> <View style={styles.inputContainer}> <Logo /> <TextInput style={styles.input} placeholder={'Enter your Full name'} placeholderTextColor='gray' onChangeText={(fullname) => this.setState({'fullname': fullname})} underlineColorAndroid='white' /> </View> <View style={styles.buttons}> <TouchableOpacity style={styles.button} onPress={this.onPress.bind(this, navigate, email)}> <Text style={styles.text}>Next</Text> </TouchableOpacity> </View> <View style={{flex:1}}> <Image style={{width: win.width, height: 200}} resizeMode={"contain"} source={{uri: 'https://preview.ibb.co/giOCnm/city.jpg'}} /> </View> </KeyboardAvoidingView> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', // justifyContent: 'center', // alignItems: 'center', backgroundColor: 'white', }, input: { backgroundColor: 'rgba(255, 255, 255, 0.4)', width: 190, height: 40, marginTop: 50, color: 'gray', textAlign: 'center', }, inputContainer: { alignItems: 'center', justifyContent: 'center', }, button: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', height: 30, width: 80, borderRadius: 20, borderWidth: 1, borderColor: '#000000' }, buttons: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, text: { color: 'black', backgroundColor: 'transparent', } , navBar: { backgroundColor: 'white' }, navButton: { marginLeft: 0 }, imageNav: { width: 30, height: 30 } });<file_sep>/src/components/auth/SignUp.js import React, { Component, PropTypes } from 'react'; import Logo from '../Logo'; import { View, StyleSheet, TextInput, Text, Image, TouchableOpacity, KeyboardAvoidingView } from 'react-native'; import Dimensions from 'Dimensions'; import { NavigationActions } from 'react-navigation' import dismissKeyboard from 'react-native-dismiss-keyboard'; import NavBar, { NavGroup, NavButton, NavTitle } from 'react-native-nav' export default class SignUp extends Component { constructor() { super() this.state = { 'email': '', } } confirmSignup(navigate, email) { dismissKeyboard() navigate('SignUpStep1', {'email': email}) } render() { const { navigate } = this.props.navigation; let email = this.props.navigation.state.params.email const win = Dimensions.get('window'); const backAction = NavigationActions.back({ key: null }); return ( <KeyboardAvoidingView style={styles.container} behavior="padding" > <NavBar style={styles}> <NavButton style={styles.navButton} onPress={() => this.props.navigation.dispatch(backAction)}> <Image style={styles.imageNav} resizeMode={"contain"} source={{uri: 'https://image.ibb.co/bvwDsm/if_back_172570_1.png'}} /> </NavButton> </NavBar> <View style={styles.inputContainer}> <Logo /> <Text style={styles.input}> Not a user, do you want to sign up?</Text> </View> <View style={styles.buttons}> <TouchableOpacity style={styles.buttonYes} onPress={this.confirmSignup.bind(this, navigate, email)}> <Text style={styles.text}>Yes</Text> </TouchableOpacity> <TouchableOpacity style={styles.buttonNo}> <Text style={styles.text}>No</Text> </TouchableOpacity> </View> <View style={{flex:1}}> <Image style={{width: win.width, height: 200, marginBottom: 0}} resizeMode={"contain"} source={{uri: 'https://preview.ibb.co/giOCnm/city.jpg'}} /> </View> </KeyboardAvoidingView> ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', // justifyContent: 'center', // alignItems: 'center', backgroundColor: 'white' }, input: { backgroundColor: 'rgba(255, 255, 255, 0.4)', marginTop: 50, height: 40, color: 'gray', }, inputContainer: { // flex: 1, alignItems: 'center', justifyContent: 'center', }, buttonYes: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', height: 30, width: 80, borderRadius: 20, borderWidth: 1, borderColor: '#000000' }, buttonNo: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', marginLeft: 5, height: 30, width: 80, borderRadius: 20, borderWidth: 1, borderColor: '#000000' }, buttons: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, text: { color: 'black', backgroundColor: 'transparent', }, navBar: { backgroundColor: 'white' }, navButton: { marginLeft: 0 }, imageNav: { width: 30, height: 30 } });<file_sep>/src/constants.js export const REGISTER_REQUEST = 'REGISTER_REQUEST'; export const REGISTER_SUCCESS = 'REGISTER_SUCCESS'; export const REGISTER_FAILURE = 'REGISTER_FAILURE'; export const CHANGE_PASSWORD_REQUEST = 'CHANGE_PASSWORD_REQUEST'; export const CHANGE_PASSWORD_SUCCESS = 'CHANGE_PASSWORD_SUCCESS'; export const CHANGE_PASSWORD_FAILURE = 'CHANGE_PASSWORD_FAILURE'; export const LOGIN_REQUEST = 'LOGIN_REQUEST'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; export const SET_PASSWORD = '<PASSWORD>'; export const LOGOUT = 'LOGOUT'; export const USERINFO_REQUEST = 'USERINFO_REQUEST'; export const USERINFO_SUCCESS = 'USERINFO_SUCCESS'; export const USERINFO_FAILURE = 'USERINFO_FAILURE'; export const CREATE_PROJECT_REQUEST = 'CREATE_PROJECT_REQUEST'; export const CREATE_PROJECT_SUCCESS = 'CREATE_PROJECT_SUCCESS'; export const CREATE_PROJECT_FAILURE = 'CREATE_PROJECT_FAILURE'; export const GET_PROJECTS_REQUEST = 'GET_PROJECTS_REQUEST'; export const GET_PROJECTS_SUCCESS = 'GET_PROJECTS_SUCCESS'; export const GET_PROJECTS_FAILURE = 'GET_PROJECTS_FAILURE'; export const API_PROTOCOL = 'http'; export const API_IP = '172.16.17.32'; export const API_PORT = '5000';<file_sep>/src/components/hr.js import React, { Component } from 'react'; import { StyleSheet, Text, View, TextInput } from 'react-native'; const styles = StyleSheet.create({ line: { flex: 1, height: 1, backgroundColor: '#c3c3c3' }, text: { textAlign: 'center', marginLeft: 15, marginRight: 15, color: '#c3c3c3' } }); class Hr extends Component { constructor(props) { super(props); this.renderLine = this.renderLine.bind(this); this.renderText = this.renderText.bind(this); this.renderInner = this.renderInner.bind(this); } renderLine(key) { return <View key={key} style={styles.line} /> } renderText(key) { return ( <View key={key} > <Text style={styles.text}>{this.props.text}</Text> </View> ) } renderInner() { if (!this.props.text) { return this.renderLine() } return [ this.renderLine(1), this.renderText(2), this.renderLine(3) ] } render() { return ( <View style={{ flexDirection: 'row', alignItems: 'center', marginLeft: parseInt(this.props.marginLeft), marginRight: parseInt(this.props.marginRight) }}> {this.renderInner()} </View> ) } } export default Hr;<file_sep>/src/components/Workspace.js import React, { Component, PropTypes } from 'react'; import Logo from './Logo'; import { View, StyleSheet, TextInput, Text, TouchableOpacity, Image, Dimensions } from 'react-native'; import { connect } from 'react-redux'; import { getProjects } from '../actions'; import { bindActionCreators } from 'redux'; import ButtonSubmit from './ButtonSubmit'; import PhotoGrid from 'react-native-photo-grid'; import NavBar, { NavGroup, NavButton, NavTitle } from 'react-native-nav' import Hr from './hr'; class Workspace extends Component { constructor() { super() this.state = { useremail: '', items: [] }; } componentDidMount() { // Build an array of 60 photos let items = Array.apply(null, Array(10)).map((v, i) => { return { id: i, src: '' } }); this.setState({ items }); const { token } = this.props.user; this.props.getProjects(token); } onPress(navigate) { navigate('CreateProject') } renderItem(item, itemSize) { let uri = `http://172.16.17.32/${item.files_path[0]}`; return( <TouchableOpacity key = { item._id.$oid } style = {{ width: itemSize, height: itemSize }} onPress = { () => { // Do Something }}> <Image resizeMode = "cover" style={styles.image} source = {{uri: uri }} > <Text style={styles.paragraph}> {item.name} </Text> </Image> </TouchableOpacity> ) } onPressLogo(navigate) { navigate('UserDetail') } renderNav(navigate) { return ( <NavBar style={styles}> <NavButton style={styles.navButton} onPress={this.onPressLogo.bind(this, navigate)}> <Image style={styles.imageNav} resizeMode={"contain"} source={{uri: 'https://thumb.ibb.co/cYLx8G/logo.jpg'}} /> </NavButton> <NavTitle style={styles.title}> {"WORKSPACE"} </NavTitle> <NavButton style={styles.navButton}> <Image style={styles.imageNav} resizeMode={"contain"} source={{uri: 'https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-ios7-search-strong-128.png'}} /> </NavButton> </NavBar> ) } renderFooter(navigate) { return ( <View style={{alignItems: 'center', justifyContent: 'center' }}> <TouchableOpacity style={styles.button} onPress={this.onPress.bind(this, navigate)}> <Text style={styles.text}>New project</Text> </TouchableOpacity> </View> ) } renderContent() { let lastProject = this.props.projects[this.props.projects.length-1]; let uri = `http://172.16.17.32/${lastProject.files_path[0]}`; return ( <View style={{ flex: 5}}> <Image resizeMode = "contain" source={{uri: uri}} style={{flex:1, height: undefined, width: undefined}}/> </View> ) } renderNoContent() { return ( <View style={{ flex: 5, alignItems: 'center', justifyContent: 'center'}}> <Text style={{color: '#c3c3c3'}}>NO RECENT PROJECTS</Text> </View> ) } renderGrid(projects, renderItem) { return ( <PhotoGrid data = { projects } itemsPerRow = { 2 } itemMargin = { 50 } renderItem = { renderItem } /> ) } render() { var { width, height } = Dimensions.get('window') const { navigate } = this.props.navigation; let projects = []; let renderFirst; if (this.props.loading == false) { projects = this.props.projects; renderFirst = this.renderNoContent(); if (projects.length > 0) { renderFirst = this.renderContent(); } } return ( <View style={styles.container}> { this.renderNav(navigate) } { renderFirst } <View style={{flex: 1}}> <Hr text='Projects' marginLeft='20' marginRight='20'/> </View> <View style={{ flex: 5, margin: 20}}> { this.renderGrid(projects, this.renderItem) } </View> <Hr marginLeft='0' marginRigh='0'/> { this.renderFooter(navigate) } </View> ); } } const styles = StyleSheet.create({ container: { flex: 5, backgroundColor: 'white' }, button: { alignItems: 'center', justifyContent: 'center', backgroundColor: '#ffffff', height: 30, width: 100, borderRadius: 10, }, buttons: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, text: { color: 'black', backgroundColor: 'transparent', } , 'project': { color: 'gray', }, 'projectsContainer': { flex: 1, alignItems: 'center', justifyContent: 'center', }, image: { flexGrow:1, height:null, width:null, }, paragraph: { backgroundColor: 'transparent', color: 'white' }, statusBar: { backgroundColor: '#3343BD', }, navBar: { backgroundColor: '#fff', }, title: { color: 'black', fontSize: 15 }, buttonText: { color: 'rgba(231, 37, 156, 0.5)', }, navGroup: { justifyContent: 'flex-end', }, navButton: { marginLeft: 0 }, imageNav: { width: 40, height: 40 } }); function mapStateToProps(state) { const { user } = state.authentication; const { projects, loading } = state.project; return { user, loading, projects } } const mapDispatchToProps = (dispatch) => { return { getProjects: bindActionCreators(getProjects, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(Workspace)<file_sep>/src/actions/project.js import { projectService } from '../services'; import { CREATE_PROJECT_REQUEST, CREATE_PROJECT_SUCCESS, CREATE_PROJECT_FAILURE, GET_PROJECTS_REQUEST, GET_PROJECTS_SUCCESS, GET_PROJECTS_FAILURE } from '../constants'; export const create = (token, name, description, images, navigate) => { console.log('CREATE ACTION'); const request = () => { return { type: CREATE_PROJECT_REQUEST } } const success = () => { return { type: CREATE_PROJECT_SUCCESS } } const failure = (error) => { return { type: CREATE_PROJECT_FAILURE, error } } return async dispatch => { try { dispatch(request()); response = await projectService.create(token, name, description, images); responseJson = await response.json(); dispatch(success()); navigate('Workspace'); } catch (error) { dispatch(failure('Error creating project', error)); } }; } export const getProjects = (token) => { const request = () => { return { type: GET_PROJECTS_REQUEST } } const success = (projects) => { return { type: GET_PROJECTS_SUCCESS, projects } } const failure = (error) => { return { type: GET_PROJECTS_FAILURE, error } } return async dispatch => { try { dispatch(request()); let response = await projectService.getProjects(token); let responseJson = await response.json(); let projects = responseJson.projects; dispatch(success(projects)); } catch (error) { dispatch(failure('Error getting project', error)); } }; }<file_sep>/src/reducers/authentication.js import { LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, SET_PASSWORD, LOGOUT, } from '../constants'; export function authentication(state = {}, action) { switch (action.type) { case LOGIN_REQUEST: return { loggingIn: true }; case SET_PASSWORD: return { password: action.password }; case LOGIN_SUCCESS: return { loggedIn: true, user: action.user }; case LOGIN_FAILURE: return { loggingIn: false, loginErrorMessage: action.error }; case LOGOUT: return { user: {}, loggedIn: false }; default: return state } }<file_sep>/src/reducers/project.js import { CREATE_PROJECT_REQUEST, CREATE_PROJECT_SUCCESS, CREATE_PROJECT_FAILURE, GET_PROJECTS_REQUEST, GET_PROJECTS_SUCCESS, GET_PROJECTS_FAILURE } from '../constants'; export function project(state = {}, action) { switch (action.type) { case CREATE_PROJECT_REQUEST: return { creating: true }; case CREATE_PROJECT_SUCCESS: return { created: true }; case CREATE_PROJECT_FAILURE: return { createProjectErrorMessage: action.error }; case GET_PROJECTS_REQUEST: return { loading: true }; case GET_PROJECTS_SUCCESS: return { projects: action.projects, loading: false }; case CREATE_PROJECT_FAILURE: return { errorGettingProjects: action.error }; default: return state } }<file_sep>/README.md Project where the user can register a user, login, create a project with a title and photo, and get information about both projects by calling an API using redux-thunk. Go to project folder : > cd react-native-redux-media Type following command : > npm install This app is running on EXPO You can use EXPO XDE or from commmand line. Let's have fun The backend is on https://github.com/ivanarielcaceres/flask-mongo-api
1ce6b617e6eb9e4690625d77ac4e17e89098cfcf
[ "JavaScript", "Markdown" ]
13
JavaScript
ivanarielcaceres/react-native-redux-media
ce951a194416ac93129171708fc781f8686b4c74
3351dbc7fbece37540b2136c2d44d0ebf0e7f920
refs/heads/master
<repo_name>glaser06/white_label_project<file_sep>/app.py import os from flask import Flask, url_for from flask import render_template app = Flask(__name__) app.config['SERVER_NAME'] = 'example.com:5000' @app.context_processor def override_url_for(): return dict(url_for=dated_url_for) def dated_url_for(endpoint, **values): if endpoint == 'static': filename = values.get('filename', None) if filename: file_path = os.path.join(app.root_path, endpoint, filename) values['q'] = int(os.stat(file_path).st_mtime) return url_for(endpoint, **values) @app.route('/') def hello_world(): return "Hello world!!" @app.route('/', subdomain="<name>") def hello_blog(name): if name in ["white", "green"] : return render_template('hello.html', name=name, static_url=url_for('static', filename=name+'/css/main.css')) return render_template('hello.html', name=name, static_url=url_for('static', filename='default/css/main.css')) return "Hello" + name + "!!" @app.route('/hello/') @app.route('/hello/<name>') def hello(name=None): if name in ["white", "green"] : return render_template('hello.html', name=name, static_url=url_for('static', filename=name+'/css/main.css')) return render_template('hello.html', name=name, static_url=url_for('static', filename='default/css/main.css'))
da3c9b001484abd6c411ce97725975e6af13d539
[ "Python" ]
1
Python
glaser06/white_label_project
bf4b6668f1f508f10478e3cee2b5be9e70875d86
fbe6f8cc67bc0681d9652cb021f0c41aa0440c75
refs/heads/master
<repo_name>albatiqy/slimlibs-js<file_sep>/xapp/animation.js import { xApp } from "../xapp.js" xApp.fadeIn = function($el, speed, next) { let last = +new Date() const tick = function () { $el.style.opacity = +$el.style.opacity + (new Date() - last) / speed last = +new Date() if (+$el.style.opacity < 1) { requestAnimationFrame(tick) } else if (next) { next.call($el) } }; $el.style.opacity = 0 tick() }<file_sep>/xapp/util-date-time.js import { xApp } from "../xapp.js" const INPUT_FORMAT = 'YYYY-MM-DD HH:mm:ss', $bulan = ["","Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"], $hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu"]; xApp.dateRangeFormat = function($date1, $date2, $separator = null, $input_format = null) { if ($separator == null) { $separator = ' s.d. '; } if ($input_format == null) { $input_format = INPUT_FORMAT; } if (!$date1||!$date2) { if (!$date2) { $date2 = $date1; } else { $date1 = $date2; } } const $src_mulai = moment($date1, INPUT_FORMAT), $src_selesai = moment($date2, INPUT_FORMAT); if ($src_mulai > $src_selesai) { let $tmp = $src_selesai; $src_selesai = $src_mulai; $src_mulai = $tmp; } const $arr_mulai = [$src_mulai.format("D"), $src_mulai.format("M"), $src_mulai.format("YYYY")], $arr_selesai = [$src_selesai.format("D"), $src_selesai.format("M"), $src_selesai.format("YYYY")]; let $rentang_tanggal = ''; if ($arr_mulai[2] != $arr_selesai[2]) $rentang_tanggal = $arr_mulai[0]+' '+$bulan[$arr_mulai[1]]+' '+$arr_mulai[2]+$separator+$arr_selesai[0]+' '+$bulan[$arr_selesai[1]]+' '+$arr_selesai[2]; else if ($arr_mulai[1] != $arr_selesai[1]) $rentang_tanggal = $arr_mulai[0]+' '+$bulan[$arr_mulai[1]]+$separator+$arr_selesai[0]+' '+$bulan[$arr_selesai[1]]+' '+$arr_selesai[2]; else if ($arr_mulai[0] != $arr_selesai[0]) $rentang_tanggal = $arr_mulai[0]+$separator+$arr_selesai[0]+' '+$bulan[$arr_selesai[1]]+' '+$arr_selesai[2]; else $rentang_tanggal = $arr_selesai[0]+' '+$bulan[$arr_selesai[1]]+' '+$arr_selesai[2]; return $rentang_tanggal; } xApp.timeRangeFormat = function($date1, $date2, $input_format = null) { if ($input_format == null) { $input_format = INPUT_FORMAT; } if (!$date1||!$date2) { if (!$date2) { $date2 = $date1; } else { $date1 = $date2; } } const $src_mulai = moment($date1, INPUT_FORMAT), $src_selesai = moment($date2, INPUT_FORMAT); if ($src_selesai < $src_mulai) { let $tmp = $src_mulai; $src_mulai = $src_selesai; $src_selesai = $tmp; } const $arr_mulai = [$src_mulai.format("D"), $src_mulai.format("M"), $src_mulai.format("YYYY")], $arr_selesai = [$src_selesai.format("D"), $src_selesai.format("M"), $src_selesai.format("YYYY")]; let $rentang_tanggal = ''; if ($src_mulai.format("YYYY-M-D")==$src_selesai.format("YYYY-M-D")) { if ($src_mulai.format("HH:mm")==$src_selesai.format("HH:mm")) { $rentang_tanggal = $hari[$src_mulai.format("e")]+' '+$arr_mulai[0]+' '+$bulan[$arr_mulai[1]]+' '+$arr_mulai[2]+', pukul '+$src_selesai.format("HH:mm")+' WIB'; } else { $rentang_tanggal = $hari[$src_mulai.format("e")]+' '+$arr_mulai[0]+' '+$bulan[$arr_mulai[1]]+' '+$arr_mulai[2]+', pukul '+$src_mulai.format("HH:mm")+' s.d. '+$src_selesai.format("HH:mm")+' WIB'; } } else { $rentang_tanggal = $hari[$src_mulai.format("e")]+' '+$arr_mulai[0]+' '+$bulan[$arr_mulai[1]]+' '+$arr_mulai[2]+' pukul '+$src_mulai.format("HH:mm")+' WIB s.d. '+$hari[$src_selesai.format("e")]+' '+$arr_selesai[0]+' '+$bulan[$arr_selesai[1]]+' '+$arr_selesai[2]+' pukul '+$src_selesai.format("HH:mm")+' WIB'; } return $rentang_tanggal; } xApp.dateTimeFormat = function($date, $input_format = null) { if ($input_format == null) { $input_format = INPUT_FORMAT; } const $src = moment($date, INPUT_FORMAT), $arr = [$src.format("D"), $src.format("M"), $src.format("YYYY")] return $hari[$src.format("e")]+', '+$arr[0]+' '+$bulan[$arr[1]]+' '+$arr[2]+' pukul '+$src.format("HH:mm")+' WIB'; }<file_sep>/xapp/validator.js import { xApp } from "../xapp.js" class ValidatorClass { constructor(config) { const defaults = { clearErrors: function(){}, invalidInput: function(attib, msg){}, labels: {}, showException: function(msg) {} }, settings = Object.assign(defaults, config) this.settings = settings this.showException = settings.showException } validate(data) { this.settings.clearErrors() const errors = {} for(const attrib in data) { const error = [],label = (attrib in this.settings.labels?this.settings.labels[attrib]:attrib) if (data[attrib]=='') { error.push(label+' harap diisi') } if (error.length > 0) { this.settings.invalidInput(attrib, error.join('<br/>')) errors[attrib] = error } } if (Object.keys(errors).length > 0) { return false } return true } } xApp.validator = function(config) { return new ValidatorClass(config) }<file_sep>/xapp/helpers.js import { xApp } from "../xapp.js" xApp.serializeFormArray = function($form) { }<file_sep>/xapp/class copy.js import { xApp } from "../xapp.js" class SomeClass { constructor(selector, config) { const defaults = {}, $element = document.querySelector(selector), settings = Object.assign(defaults, config), libdef = { }, libsettings = Object.assign(libdef, settings.libSettings), } somethod() { } } xApp.someClass = function(selector, config) { return new SomeClass(selector, config) }<file_sep>/xapp.js import {SlimlibsGlobals, SlimlibsHandleHttpJSONResponse} from "../../js/modules/globals.js?module" const xApp = Object.assign(SlimlibsGlobals, { appSelector: '#app', pageSelector: '#container', cookiePath: (SlimlibsGlobals.basePath==''?'/':SlimlibsGlobals.basePath), Libs: {}, Fn: {}, ENUMS: { notify: { info: 0, success: 1, warning: 2, danger: 3 } } }) xApp.handleHttpJSONResponse = SlimlibsHandleHttpJSONResponse xApp.notifyError = function(error) { xApp.notify(error.message, xApp.ENUMS.notify.error) } xApp.notify = function(text, tp) { const event = new CustomEvent('xapp-app.notify', { bubbles: true, detail: {text: text, type: tp} }), $app = document.querySelector(xApp.appSelector) if ($app!=null) { $app.dispatchEvent(event) } } xApp.notifyInfo = function(text) { xApp.notify(text, xApp.ENUMS.notify.info) } xApp.notifySuccess = function(text) { xApp.notify(text, xApp.ENUMS.notify.success) } xApp.notifyWarning = function(text) { xApp.notify(text, xApp.ENUMS.notify.warning) } xApp.notifyDanger = function(text) { xApp.notify(text, xApp.ENUMS.notify.danger) } xApp.cookieEnabled = function() { if (navigator.cookieEnabled) return true document.cookie = "cookietest=1" const ret = document.cookie.indexOf("cookietest=") != -1 document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT" return ret } xApp.getCookie = function(name) { const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)'); return v ? decodeURIComponent(v[2]) : null; } xApp.setCookie = function(name, value, seconds) { const d = new Date; d.setTime(1000*seconds); document.cookie = name + "=" + encodeURIComponent(value) + ";path="+xApp.cookiePath+";expires=" + d.toGMTString(); } xApp.deleteCookie = function(name) { xApp.setCookie(name, '', -1); } xApp.routerBasePath = (location.pathname.slice(-1)=="/"?"":location.pathname).substr(xApp.basePath.length) export { xApp }<file_sep>/xapp/flatpickr.js import { xApp } from "../xapp.js" xApp.flatpickr = function(selector, config) { const defaults = {}, $element = document.querySelector(selector), settings = Object.assign(defaults, config), libdef = { enableTime: true, dateFormat: 'd/m/Y H:i:S' }, libsettings = Object.assign(libdef, settings.libSettings) const ret = flatpickr($element, libsettings) xApp.onUnload(()=>{ ret.destroy() }) return ret }<file_sep>/xapp/tinymce.js import { xApp } from "../xapp.js" xApp.tinymce = function(selector, config) { const defaults = { uploadImageEndPoint: '/api/v0/resource/upload/media-image', uploadImagePath: '/uploads', uploadImageResize: false, mediaBasePath: xApp.basePath + '/resources/media' }, $element = document.querySelector(selector), settings = Object.assign(defaults, config), imageUploadHandler = function(blobInfo, success, failure) { const data = new FormData(), formData = { path: settings.uploadImagePath, resize: settings.uploadImageResize }, genericErrorText = `Couldn't upload file: ${blobInfo.filename()}.`, xhr = xApp.apiXMLHttpRequest(settings.uploadImageEndPoint, { body: data, onError: (e) => { failure(genericErrorText) }, onAbort: (e) => {}, onUploadProgress: (e) => {}, onFinish: (response) => { if (!response || response.error) { failure(response && response.error ? response.error.message : genericErrorText) return; } const imgsrc = settings.mediaBasePath + response.data.path + '/' + response.data.name success(imgsrc) } }) data.append('data', new Blob([JSON.stringify(formData)], { type: 'application/json' }), 'data') data.append('image', blobInfo.blob(), blobInfo.filename()) xhr.send() }, libdef = { target: $element, menubar: false, plugins: 'advlist autolink lists link image charmap print preview anchor ' + 'searchreplace visualblocks code fullscreen ' + 'insertdatetime media table paste help wordcount', toolbar: 'undo redo | formatselect | ' + 'bold italic underline strikethrough | alignleft aligncenter ' + 'alignright alignjustify | ' + 'bullist numlist outdent indent | link image-browser media insert-pdf | ' + 'fullscreen preview code | ' + 'removeformat | help', media_url_resolver: function(data, resolve, reject) { xApp.apiGet('/api/v0/module/media/embedcode?url=' + decodeURI(data.url)) .then(json => { if (json.data.result) { resolve({html: '<div class="'+json.data.class+'-wrapper'+'">' + json.data.code + '</div>'}) } else { reject({msg: 'invalid resource'}) } }) }, images_upload_handler: imageUploadHandler, relative_urls: false, setup: function(editor) { editor.on('init', function(args) { xApp.unblock() }) editor.ui.registry.addButton('image-browser', { icon: 'gallery', tooltip: 'Image Browser', onAction: function() { editor.windowManager.openUrl({ title: 'Image Browser', url: xApp.basePath + '/modules/tinymce/media-browser-dlg?filter=image', height: 600, width: 1000, onMessage: function(instance, data) { switch (data.mceAction) { case 'filePicked': if (data.fileType == 'IMAGE') { editor.execCommand('mceInsertContent', false, '<img src="' + settings.mediaBasePath + data.fileSrc + '">') } instance.close() } } }); } }) editor.ui.registry.addButton('insert-pdf', { icon: 'new-document', tooltip: 'Sisipkan PDF', onAction: function() { editor.windowManager.openUrl({ title: 'PDF Browser', url: xApp.basePath + '/modules/tinymce/media-browser-dlg?filter=pdf', height: 600, width: 1000, onMessage: function(instance, data) { switch (data.mceAction) { case 'filePicked': if (data.fileType == 'PDF') { editor.execCommand('mceInsertContent', false, '<div class="xapp-pdf-media-wrapper"><iframe class="xapp-pdf-media" src="' + xApp.basePath + '/node_modules/slimlibs-js/libs/pdf.js/web/viewer.html?file=' + encodeURIComponent(settings.mediaBasePath + data.fileSrc) + '"></iframe></div>') } instance.close() } } }); } }) }, extended_valid_elements : 'span[class]', content_css: [xApp.basePath + '/node_modules/bootstrap3/dist/css/bootstrap.min.css', xApp.basePath + '/css/tinymce-content.css'] }, libsettings = Object.assign(libdef, settings.libSettings) xApp.block() tinymce.init(libsettings) xApp.onUnload(() => { tinymce.remove() }) return tinymce.get($element.id) }<file_sep>/xapp/ddpdfupload.js import { xApp } from "../xapp.js" xApp.ddpdfupload = function(selector, config) { const defaults = { uploadEndPoint: '/api/v0/resource/upload/pdf', uploadPath: '/uploads', // <== NOT USED fileUploaded: function(filename) {} }, $element = document.querySelector(selector), $file = $element.querySelector('input[type="file"]'), multiple = $file.hasAttribute('multiple'), $thumb = $element.querySelector('.xapp-thumbnail'), settings = Object.assign(defaults, config), preventDefaults = function(e) { e.preventDefault() e.stopPropagation() }, highlight = function(e) { $element.classList.add('highlight') }, unhighlight = function(e) { $element.classList.remove('highlight') }, handleDrop = function(e) { const dt = e.dataTransfer, files = dt.files handleFiles(files) }, handleFiles = function(files) { files = [...files] initializeProgress(files.length) files.forEach(uploadFile) }, uploadFile = function(file, i) { const formData = new FormData(), url = URL.createObjectURL(file) makeThumb(url).then($canvas => { while ($thumb.hasChildNodes()) { $thumb.removeChild($thumb.lastChild) } const imgUrl = $canvas.toDataURL("image/png"), $img = document.createElement('img'), data = { path: settings.uploadPath } $img.src = imgUrl $thumb.appendChild($img) formData.append('data', new Blob([JSON.stringify(data)], { type: 'application/json' })) formData.append('pdf', file) const xhr = xApp.apiXMLHttpRequest(settings.uploadEndPoint, { body: formData, onUploadProgress: (e) => { updateProgress(i, (e.loaded * 100.0 / e.total) || 100) }, onFinish: (json) => { settings.fileUploaded(json.data.fileName) } }) xhr.send() }) }, $progressBar = $element.querySelector('.progress-bar'), initializeProgress = function(numfiles) { $progressBar.value = 0 uploadProgress = [] for (let i = numfiles; i > 0; i--) { uploadProgress.push(0) } }, updateProgress = function(fileNumber, percent) { uploadProgress[fileNumber] = percent let total = uploadProgress.reduce((tot, curr) => tot + curr, 0) / uploadProgress.length $progressBar.value = total }, makeThumb = function(url) { return pdfjsLib.getDocument({ url }).promise.then(doc => { return doc.getPage(1).then(page => { // draw page to fit into 96x96 canvas const vp = page.getViewport({ scale: 1 }), $canvas = document.createElement("canvas") $canvas.height = 500 const scale = $canvas.height / vp.height $canvas.width = (vp.width / vp.height * $canvas.height) return page.render({ canvasContext: $canvas.getContext("2d"), viewport: page.getViewport({ scale }) }).promise.then(function() { return $canvas }) }) }).catch(console.error) } let uploadProgress = [] $file.addEventListener('change', function(e) { handleFiles(this.files) }) ; ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { $element.addEventListener(eventName, preventDefaults, false) }) ; ['dragenter', 'dragover'].forEach(eventName => { $element.addEventListener(eventName, highlight, false) }) ; ['dragleave', 'drop'].forEach(eventName => { $element.addEventListener(eventName, unhighlight, false) }) $element.addEventListener('drop', handleDrop, false) }
bd9a0970c06ffb42e653d72887513872396fc3d7
[ "JavaScript" ]
9
JavaScript
albatiqy/slimlibs-js
3b2ea0224a4c99f9d5c6ded381c4ab0e5b87fd0b
57930ca940aeea45d6e446457ec72e1c4ea279c2
refs/heads/master
<file_sep><?php $koneksi = mysqli_connect("127.0.0.1:3307", "root", "", "ukkweb"); if(mysqli_connect_error($koneksi)) { echo "Koneksi Gagal". mysqli_connect_error(); } ?><file_sep><?php session_start(); // cek apakah yang mengakses halaman ini sudah login if($_SESSION['level']==""){ header("location:login.php?pesan=gagal"); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" type="image/png" sizes="16x16" href="logo.png"> <title>Toko Buku Cemerlang</title> <!-- Custom fonts for this template--> <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="css/sb-admin-2.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-primary static-top shadow"> <div class="container"> <h1><a href="homepage.php" class="navbar-brand" style="color:white;"><img src="logo.png" width="50px"> Toko Buku Cemerlang</a></h1> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="homepage.php" style="color:white;">Daftar Buku <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="keluar.php" style="color:white;">Keluar <span class="sr-only">(current)</span></a> </li> </ul> </div> </div> </nav> <br> <div class="container"> <form class="d-flex" action="homepage.php" method="GET"> <input class="form-control me-2 bg-white border-2 small" type="text" placeholder="Search" aria-describedby="basic-addon2" aria-label="Masukkan judul buku" name="cari"> <div class="input-group-append"> <button class="btn btn-primary" type="submit" value="Cari" style="color:white;"> <i class="fas fa-search fa-sm"></i> </button> </div> </form><br> </div> <div class="container"> <?php echo "<h4>Selamat Datang " . $_SESSION['username'] . "</h4>"; ?> </div><br> <h4 class="text-center font-weight-bold m-4">Daftar Buku Terbaru</h4> <!-- php untuk pencarian --> <div class="container"> <?php include "koneksi.php"; if(isset($_GET['cari'])) { $cari = $_GET['cari']; echo "<b> Hasil Pencarian : " .$cari."</b>"; } ?> </div> <?php $nama_buku = ""; if(isset($_GET['cari'])) { $nama = $_GET['cari']; $hasil = mysqli_query($koneksi, "SELECT * FROM buku WHERE judul LIKE '%".$nama."%'"); } else{ $hasil = mysqli_query($koneksi, "SELECT * FROM buku"); } // mengambil data untuk ditampilkan WHILE($data = mysqli_fetch_array($hasil)){ ?> <div class="container"> <a href="detailbuku.php?id=<?php echo $data['id_buku'] ?>"> <div class="card col-ke4"> <tr> <td><img src="imgbuku/<?php echo $data['gambar']; ?>" class="card-img-top" height="200"></td> <p>Judul Buku : </p> <td><?php echo $data['judul']; ?></td> </tr> </a> </div> </div> <?php } ?> <div class="container-fluid card"> <footer class="sticky-footer bg-white"> <div class="copyright text-center my-auto"> <span>Copyright &copy; 2021 <NAME></span> </div> </footer> </div> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.9.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3307 -- Generation Time: Nov 15, 2021 at 07:40 AM -- Server version: 10.4.10-MariaDB -- PHP Version: 7.3.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ukkweb` -- -- -------------------------------------------------------- -- -- Table structure for table `buku` -- CREATE TABLE `buku` ( `id_buku` int(11) NOT NULL, `judul` varchar(225) NOT NULL, `pengarang` varchar(225) NOT NULL, `penerbit` varchar(225) NOT NULL, `gambar` varchar(225) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `buku` -- INSERT INTO `buku` (`id_buku`, `judul`, `pengarang`, `penerbit`, `gambar`) VALUES (5, 'Narutoo V2', '<NAME>', 'Shueisha', '1875300563_NarutoV2.jpg'), (32, 'Jujutsu Kaisen V4', '<NAME>', 'Shueisha', '626971690_jujutsu V4.jpg'), (36, 'Naruto Shipudden V72', '<NAME>', 'Shueisha', '1724980687_covernaruto.jpg'), (37, 'Solo Leveling V1', '<NAME>', 'Shueisha', '53753143_SLV1.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `login` -- CREATE TABLE `login` ( `id_pengguna` int(50) NOT NULL, `nama` varchar(50) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `level` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `login` -- INSERT INTO `login` (`id_pengguna`, `nama`, `username`, `password`, `level`) VALUES (1, 'admin', 'admin', 'admin', 'admin'), (2, 'kevin', '<PASSWORD>', '<PASSWORD>', 'user'), (3, 'daniel', 'daniel', 'daniel', 'user'); -- -- Indexes for dumped tables -- -- -- Indexes for table `buku` -- ALTER TABLE `buku` ADD PRIMARY KEY (`id_buku`); -- -- Indexes for table `login` -- ALTER TABLE `login` ADD PRIMARY KEY (`id_pengguna`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `buku` -- ALTER TABLE `buku` MODIFY `id_buku` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39; -- -- AUTO_INCREMENT for table `login` -- ALTER TABLE `login` MODIFY `id_pengguna` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include "koneksi.php"; $id = $_GET['id_buku']; $ambildata = mysqli_query($koneksi, "DELETE FROM buku WHERE id_buku = '$id'"); echo "<meta http-equiv='refresh' content='1; url=http://localhost/UKKWEB/daftarbuku.php'>"; ?> <file_sep><!DOCTYPE html> <!-- Coding By CodingNepal - youtube.com/codingnepal --> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="icon" type="image/png" sizes="16x16" href="logo.png"> <title>To<NAME> Cemerlang</title> <link rel="stylesheet" href="css/login.css?v=1.0"> </head> <body> <?php if(isset($_GET['pesan'])){ if($_GET['pesan']=="gagal"){ echo "<div class='alert'>Username dan Password Salah !</div>"; } } ?> <div class="center"><br> <center> <img src="logo.png"> </center> <h1>Login</h1> <form method="post" action="cek_login.php"> <div class="txt_field"> <input type="text" name="username" required> <span></span> <label>Username</label> </div> <div class="txt_field"> <input type="password" name="password" required> <span></span> <label>Password</label> </div> <input type="submit" name="submit" value="Login"><br><br> </form> </div> </body> </html>
21820c0c4856a4e799774e7268211d9f2600c5da
[ "SQL", "PHP" ]
5
PHP
KEVIN-69/UKK_PEMROGRAMAN-WEB
86f775c38ae4bdbb327e7e85c011bca1026c0cb6
77da6f43695bfa9d8cb94867d974140505f548f4
refs/heads/master
<repo_name>drumwolf/JSON_diff<file_sep>/json_diff.js /***** helper function: filter out all unique keys in "left" and "right" objects *****/ function getKeys(left, right) { // if left or right is a string, convert to empty object left = (typeof left !== 'string') ? left : {}; right = (typeof right !== 'string') ? right : {}; // declare vars const keys = [...Object.keys(left)]; const rightKeys = Object.keys(right); const leftKeyMap = {}; // map out which keys in left object exist for (let i = 0, key; i < keys.length; i++) { key = keys[i]; if (!leftKeyMap[key]) { leftKeyMap[key] = true; } } // filter out keys which are unique to right objects for (let j = 0, key; j < rightKeys.length; j++) { key = rightKeys[j]; if (!leftKeyMap[key]) { keys.push(key) } } return keys; } /***** helper function: determine if an argument 'obj' is an object *****/ function isObject(obj) { return (obj && typeof obj === 'object'); // note: 'typeof obj' returns true if obj === null } /***** module to be exported ***/ function getDiffScope() { const cachedArgs = {}; // since 'getDiff' is a recursive function that calls certain left/right argument pairs multiple times, let's cache those argument pairs const diffs = []; // array containing all of the 'diff' entries /* recursive closure function */ const getDiff = function(left = {}, right = {}, parentKeys = []) { // stringify JSON objects so they can be stored as keys in 'cachedArgs' const l_str = JSON.stringify(left); const r_str = JSON.stringify(right); // execute only if "cachedArgs[l_str][r_str]" does not already exist if (!cachedArgs[l_str] || !cachedArgs[l_str][r_str]) { /* get all keys in left and right objects */ const allKeys = getKeys(left, right); const parentKeyString = (parentKeys.length) ? parentKeys.join('.') + "." : ""; /* loop through all left and right keys */ for (let i = 0; i < allKeys.length; i++) { const key = allKeys[i]; // when left key and right key are different, start comparison if (left[key] !== right[key]) { const lk_str = JSON.stringify(left[key]); const rk_str = JSON.stringify(right[key]); // output subtraction from left key if (left.hasOwnProperty(key)) { if ( isObject(left[key]) ) { // invoke "getDiff" recursively getDiff(left[key], right[key], [...parentKeys, key]); // cache left/right arg pairs cachedArgs[lk_str] = cachedArgs[lk_str] || {}; cachedArgs[lk_str][rk_str] = true; } else { const leftKey = (typeof left[key] === 'string') ? `'${left[key]}'` : left[key]; diffs.push(`-${parentKeyString}${key}:${leftKey}`); } } // output addition to right key if (right.hasOwnProperty(key)) { if ( isObject(right[key]) ) { // invoke "getDiff" recursively getDiff(left[key], right[key], [...parentKeys, key]); // cache left/right arg pairs cachedArgs[lk_str] = cachedArgs[lk_str] || {}; cachedArgs[lk_str][rk_str] = true; } else { const rightKey = (typeof right[key] === 'string') ? `'${right[key]}'` : right[key]; diffs.push(`+${parentKeyString}${key}:${rightKey}`); } } } // end of block dealing with left and right key difference } // end of primary code (which executes only if left/right argument pair is not cached) } // recursive function returns "Set" object containing all unique diffs return diffs; } /* return recursive closure function */ return getDiff; } module.exports = getDiffScope;<file_sep>/README.md # JSON_diff Custom JavaScript module which compares the difference between two JSON objects (or two revisions of the same JSON object, if you wish). ### Javascript Files - [json_diff.js](https://github.com/drumwolf/JSON_diff/blob/master/json_diff.js) - the module containing all of the JS functions to compare JSON objects. Main function is `getDiff()` and it accepts two arguments, `left` being the original version of the JSON object and `right` being the new version. - [test_cases.js](https://github.com/drumwolf/JSON_diff/blob/master/test_cases.js) - the file which contains the test case(s) and imports the "json_diff" module. ### Instructions For this iteration of this project, you run `test_cases.js` in the terminal. If you have Node installed, you can simply type `node test_cases.js`. <file_sep>/test_cases.js const getDiffScope = require('./json_diff.js') // first test const left = { 'a': 1, 'b': 'foo', 'c': { 'c1': true, 'c2': { 'cc': 5, 'cd': 'foo' } }, 'd' : { 'd1': 5, 'd2': 5 }, 'e': { 'e1': 0 }, 'g': 15, 'h': [3, 5, 7, null], 'i': [10, 20] }; const right = { 'a': 1, 'b': { 'b1': true }, 'c': { 'c1': false, 'c2': { 'cc': 5 } }, 'd' : { 'd3': 12 }, 'e':'bar', 'f': null, 'i': [10, 30] }; const getDiffFunction1 = getDiffScope(); let diffs = getDiffFunction1(left, right); diffs.forEach( obj => console.log(obj) ); // second test const iggypop1 = { 'name': '<NAME>', 'birthplace': 'Muskegon, MI', 'personal': { 'birthdate': 'April 21, 1947' }, 'marriages' : { 'Wendy Weissberg': '1968', 'Suchi Asano': '1984-1999' }, 'bands': ['Stooges'], 'genre': ['proto-punk', 'punk rock', 'glam rock', 'hard rock'] }; const iggypop2 = { 'name': '<NAME>', 'personal': { 'birthdate': '1947-04-21', 'birthplace': 'Muskegon, MI' }, 'marriages' : { 'Wendy Weissberg': '1968', 'Suchi Asano': '1984-1999', 'Nina Alu': '2008-present' }, 'bands': ['Stooges', 'Iggy and the Stooges'], 'genre': ['proto-punk', 'punk rock', 'glam rock', 'hard rock'] }; const getDiffFunction2 = getDiffScope(); diffs = getDiffFunction2(iggypop1, iggypop2); diffs.forEach( obj => console.log(obj) );
bfcc7481a92521f38db3046ca2d1e767431ad381
[ "JavaScript", "Markdown" ]
3
JavaScript
drumwolf/JSON_diff
084c78d265d1774a8468e2af014f2f6d79137bc7
7151d9cd411996acc622aa4dc7c18422e4240b95
refs/heads/master
<file_sep>DROP TABLE Office CASCADE CONSTRAINTS; DROP TABLE Client CASCADE CONSTRAINTS; DROP TABLE DrivingTest CASCADE CONSTRAINTS; DROP TABLE Staff CASCADE CONSTRAINTS; DROP TABLE Interview CASCADE CONSTRAINTS; DROP TABLE Vehicle CASCADE CONSTRAINTS; DROP TABLE Inspection CASCADE CONSTRAINTS; DROP TABLE Lesson CASCADE CONSTRAINTS; CREATE TABLE Office ( offNo NUMERIC(8,0) CONSTRAINT offNo_PK PRIMARY KEY, offAddess VARCHAR(50) NOT NULL, offPostcode NUMERIC(4,0) NOT NULL, offTelno NUMERIC(8,0) NOT NULL, staNo NUMERIC(8,0) NOT NULL ); CREATE TABLE Client ( cliNo NUMERIC(8,0) CONSTRAINT cliNo_PK PRIMARY KEY, cliFname VARCHAR(20) NOT NULL, cliLname VARCHAR(20) NOT NULL, cliAddress VARCHAR(50) NOT NULL, cliTelno NUMERIC(8,0) NOT NULL, cliEmail VARCHAR(20), cliLicenseNo VARCHAR(8) CONSTRAINT UNIQ_LSCNO UNIQUE CONSTRAINT cliLicenseNo_nn NOT NULL, cliSex CHAR(1) NOT NULL, cliDob DATE NOT NULL, offNo NUMERIC(8,0) NOT NULL, CONSTRAINT FK_Office_offNo FOREIGN KEY (offNo) REFERENCES Office(offNo) ON DELETE CASCADE ); CREATE TABLE DrivingTest ( dtsNo NUMERIC(8,0) CONSTRAINT tesNo_PK PRIMARY KEY, dtsDate DATE NOT NULL, dtsLocation VARCHAR(20) NOT NULL, dtsResult CHAR(1) NOT NULL, dtsType VARCHAR(20) NOT NULL, cliNo NUMERIC(8,0) NOT NULL, CONSTRAINT FK_DrivingTest_cliNo FOREIGN KEY (cliNo) REFERENCES Client(cliNo) ON DELETE CASCADE ); CREATE TABLE Staff ( staNo NUMERIC(8,0) CONSTRAINT staNo_PK PRIMARY KEY, staFname VARCHAR(20) NOT NULL, staLname VARCHAR(20) NOT NULL, staJobtitle VARCHAR(20) NOT NULL, staTelno NUMERIC(8,0) NOT NULL, staEmail VARCHAR(20), staSex CHAR(1) NOT NULL, staDob DATE NOT NULL, offNo NUMERIC(8,0) NOT NULL ); CREATE TABLE Interview ( cliNo NUMERIC(8,0) NOT NULL, staNo NUMERIC(8,0) NOT NULL, intDate DATE NOT NULL, intComments VARCHAR(50), CONSTRAINT interview_PK PRIMARY KEY (cliNo, staNo), CONSTRAINT interview_cliNo_FK FOREIGN KEY (cliNo) REFERENCES Client(cliNo) ON DELETE CASCADE, CONSTRAINT interview_staNo_FK FOREIGN KEY (staNo) REFERENCES Staff(staNo) ON DELETE CASCADE ); CREATE TABLE Vehicle ( vehNo NUMERIC(8,0) CONSTRAINT vehNo_PK PRIMARY KEY, vehModel VARCHAR(20) NOT NULL, vehMake VARCHAR(20) NOT NULL, vehColour VARCHAR(20) NOT NULL, offNo NUMERIC(8,0) NOT NULL, CONSTRAINT FK_Office_offNo2 FOREIGN KEY (offNo) REFERENCES Office(offNo) ON DELETE CASCADE ); CREATE TABLE Inspection ( insNo NUMERIC(8,0) CONSTRAINT insNo_PK PRIMARY KEY, insDate DATE NOT NULL, insComments VARCHAR(50), vehNo NUMERIC(8,0), staNo NUMERIC (8,0), CONSTRAINT FK_Vehicle_vehNo FOREIGN KEY (vehNo) REFERENCES Vehicle(vehNo) ON DELETE CASCADE, CONSTRAINT FK_Staff_staNo FOREIGN KEY (staNo) REFERENCES Staff(staNo) ON DELETE CASCADE ); CREATE TABLE Lesson ( vehNo NUMERIC(8,0) NOT NULL, cliNo NUMERIC(8,0) NOT NULL, staNo NUMERIC(8,0) NOT NULL, lesDate DATE NOT NULL, lesStage CHAR(1) NOT NULL, lesMileagetotal NUMERIC(3,0) NOT NULL, CONSTRAINT Lesson_PK PRIMARY KEY (vehNo, cliNo, staNo), CONSTRAINT Lesson_vehNo_FK FOREIGN KEY (vehNo) REFERENCES Vehicle(vehNo) ON DELETE CASCADE, CONSTRAINT Lesson_cliNo_FK FOREIGN KEY (cliNo) REFERENCES Client(cliNo) ON DELETE CASCADE, CONSTRAINT Lesson_staNo_FK FOREIGN KEY (staNo) REFERENCES Staff(staNo) ON DELETE CASCADE ); ALTER TABLE Office ADD CONSTRAINT FK_Office_staNo FOREIGN KEY (staNo) REFERENCES Staff(staNo) ON DELETE CASCADE; ALTER TABLE Staff ADD CONSTRAINT FK_Staff_offNo FOREIGN KEY (offNo) REFERENCES Office(offNo) ON DELETE CASCADE;<file_sep> INSERT INTO OFFICE VALUES (0614,'8813995','<EMAIL>','23 Intel drive, Albany, Auckland','08615967'); INSERT INTO OFFICE VALUES (0628, '98581682','<EMAIL>', '9 Westgate drive, Massey, Auckland','12315990'); INSERT INTO OFFICE VALUES (8213, '38492456','<EMAIL>', '45 Hill Road, Glenfield, Auckland','45615978'); INSERT INTO OFFICE VALUES (4232, '78945632', '<EMAIL>', '13 Lake Road, Northcote, Auckland','12915967'); INSERT INTO OFFICE VALUES (4232, '97695234', '<EMAIL>', '38 Marshell street, Henderson, Auckland'); INSERT INTO STAFF VALUES (08615967, 'Smith', 'John', 'k','Manager','14/06/1984','M','434 Waiwera way, Albany, Auckland','09876397','<EMAIL>','0614'); INSERT INTO STAFF VALUES (08615678, 'James', 'Mark', 'G','AdminStaff','24/03/1989','M','56 Mikeway Road, Albany, Auckland','09762963','<EMAIL>','0614'); INSERT INTO STAFF VALUES (08615097, 'Lang', 'Cindy','AdminStaff','12/09/1994','F','56 Lake Road, Northcote, Auckland','08752896','<EMAIL>','0614'); INSERT INTO STAFF VALUES (08615567, 'Cho', 'jake', 'SeniorInstructor','09/11/1979','M','60 Judge way, Albany, Auckland','09641986','<EMAIL>','0614'); INSERT INTO STAFF VALUES (08615789, 'singh', 'Jai', 'K','SeniorInstructor','19/05/1981','M','4 Era drive, Albany, Auckland','09875387','<EMAIL>','0614'); INSERT INTO STAFF VALUES (12315990, 'Kumar', 'Ashneel', 'A','Manager','13/06/1994','M','96 Coronation way, Massey, Auckland','09986679','<EMAIL>','0628'); INSERT INTO STAFF VALUES (12215967, 'smith', 'Jordan','AdminStaff','13/04/1993','M','65 Smudge way, Massey, Auckland','08532897','<EMAIL>','0628'); INSERT INTO STAFF VALUES (12315990, 'Kruger', 'Milan', 'A','AdminStaff','10/11/1991','M','289 Mac way, Massey, Auckland','08964297','<EMAIL>','0628'); INSERT INTO STAFF VALUES (12215907, 'Burden', 'Andrew', 'B','SeniorInstructor','11/12/1997','M','87 Hewllet way, Massey, Auckland','078965347','<EMAIL>','0628'); INSERT INTO STAFF VALUES (122645965, 'Park', 'Betty', 'L','SeniorInstructor','19/03/1987','F','76 Wayward road, Albany, Auckland','07856839','<EMAIL>','0628'); INSERT INTO STAFF VALUES (45615978, 'Kumar', 'John','Manager','13/07/1995','M','99 somenation street, Glenfield, Auckland','07896468','<EMAIL>','8213'); INSERT INTO STAFF VALUES (4565967, 'Prasad', 'Ashika','AdminStaff','10/08/1992','F','09 Anderson street, Glenfield, Auckland','07974278','<EMAIL>','8213'); INSERT INTO STAFF VALUES (45615667, 'Chang', 'Ben','AdminStaff','19/02/1986','M','21 Glen street, Glenfield, Auckland','07567843','<EMAIL>','8213'); INSERT INTO STAFF VALUES (45682963, 'Perry', 'Katty','SeniorInstructor','10/12/1991','F','09 Firework street, Glenfield, Auckland','07745687','<EMAIL>','8213'); INSERT INTO STAFF VALUES (45615978, 'Sheran', 'Ed','SeniorInstructor','16/03/1989','M','14 Hobbiton street, Glenfield, Auckland','079735678','<EMAIL>','8213'); INSERT INTO STAFF VALUES (12915967, 'baggins', 'Biblo','Manager','13/08/1977','M','98 Bagends street, Northcote, Auckland','02579782','<EMAIL>','4232'); INSERT INTO STAFF VALUES (12987658, 'Potter', 'Harry','AdminStaff','17/01/1978','M','09 Hogwarts street, Northcote, Auckland','027865479','<EMAIL>','8213'); INSERT INTO STAFF VALUES (12986045, 'Chang', 'Joe','AdminStaff','19/02/1986','M','21 oakview street, Northcote, Auckland','02678917','<EMAIL>','8213'); INSERT INTO STAFF VALUES (12939260, 'Swift', 'Taylor','SeniorInstructor','12/01/1981','F','09 Blankspace street, Northcote, Auckland','02679399','<EMAIL>','8213'); INSERT INTO STAFF VALUES (12940725, 'john', 'smith','SeniorInstructor','16/03/1989','M','14 Hobbs street, Northcote, Auckland','026783978','<EMAIL>','8213');
9be909b7aa07945e5a89077b26fedb46ce2f9399
[ "SQL" ]
2
SQL
xBazzu/Database-Development
cd36834f45dc8d104e1da6becd732f54df5be018
f1e8df3966997aba47db8a1e513e8891eed5736f
refs/heads/master
<file_sep>/* TMC26XMotorTest.ino - - TMC26X Stepper library tester for Wiring/Arduino Copyright (c) 2011, <NAME>, <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ unsigned int motor_counter = 0; unsigned char motor_moved = 0; int sgThreshold = 4; int sgFilter = 0; int direction = 1; unsigned int lower_SG_threshold = 0; unsigned int upper_SG_threshold = 0; unsigned char number_of_SG_readings=0; unsigned char current_increment_step_size=0; unsigned char lower_current_limit=0; char chopperMode = 0; //0 for spread, 1 for constant off char t_off = 2; char t_blank = 24; char h_start = 8; char h_end = 6; char h_decrement = 0; void startMotor() { Serial.println(F("Configuring stepper driver")); //char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement tmc26XStepper.setSpreadCycleChopper(t_off,t_blank,h_start,h_end,h_decrement); tmc26XStepper.setRandomOffTime(0); tmc26XStepper.setMicrosteps(32); tmc26XStepper.setStallGuardThreshold(sgThreshold,sgFilter); // Serial.println("config finished, starting"); #ifdef ENABLE_PIN digitalWrite(ENABLE_PIN,LOW); #endif tmc26XStepper.start(); tmc26XStepper.setSpeed(10); TCNT2=setupTimer2(10000); sei(); } void runMotor() { if (running && !tmc26XStepper.isMoving()) { tmc26XStepper.step(direction*10000); Serial.println("run"); } if (!running & tmc26XStepper.isMoving()) { tmc26XStepper.stop(); Serial.println("stop"); } } void setSpeed(unsigned int targetSpeed) { if (targetSpeed>0 && targetSpeed<MAX_SPEED) { Serial.print(F("Setting speed: ")); Serial.println(targetSpeed); tmc26XStepper.setSpeed(targetSpeed); } else { Serial.print(F("improper speed ")); Serial.println(targetSpeed); } } void setMicrostepping(int microstepping) { if (microstepping<1 || microstepping>256) { Serial.print(F("Improperd microstepping setting [1...256]: ")); Serial.print(microstepping); } else { tmc26XStepper.setMicrosteps(microstepping); } } void setStallGuardThreshold(int threshold) { if (threshold<-64 || threshold > 63) { Serial.print(F("Improper Stall Guard Threshold [-64...63]: ")); Serial.println(threshold); } else { sgThreshold = threshold; tmc26XStepper.setStallGuardThreshold(threshold,sgFilter); } } void setStallGuardFilter(int filter) { if (filter) { sgFilter=1; } else { sgFilter=0; } tmc26XStepper.setStallGuardThreshold(sgThreshold,sgFilter); } void setCurrent(int current) { if (current>0 && current <1700) { tmc26XStepper.setCurrent(current); } else { Serial.print(F("Improper current {0 ... 1200}: ")); Serial.print(current); } } void updateChopper() { //we can do only spread now if (chopperMode==0) { tmc26XStepper.setSpreadCycleChopper(t_off,t_blank,h_start,h_end,h_decrement); } } void updateCoolStep() { tmc26XStepper.setCoolStepConfiguration( lower_SG_threshold, upper_SG_threshold, number_of_SG_readings, current_increment_step_size, lower_current_limit); } //from http://www.uchobby.com/index.php/2007/11/24/arduino-interrupts/ //Setup Timer2.s //Configures the ATMega168 8-Bit Timer2 to generate an interrupt //at the specified frequency. //Returns the timer load value which must be loaded into TCNT2 //inside your ISR routine. //See the example usage below. unsigned char setupTimer2(float timeoutFrequency){ unsigned char result; //The timer load value. //Calculate the timer load value result=(int)((257.0-(TIMER_CLOCK_FREQ/timeoutFrequency))+0.5); //The 257 really should be 256 but I get better results with 257. //Timer2 Settings: Timer Prescaler /8, mode 0 //Timer clock = 16MHz/8 = 2Mhz or 0.5us //The /8 prescale gives us a good range to work with //so we just hard code this for now. TCCR2A = 0; TCCR2B = 0<<CS22 | 1<<CS21 | 0<<CS20; //Timer2 Overflow Interrupt Enable TIMSK2 = 1<<TOIE2; //load the timer for its first cycle TCNT2=result; return(result); } ISR(TIMER2_OVF_vect) { motor_moved = tmc26XStepper.move(); motor_counter++; } <file_sep>/* TMC26XMotorTest.ino - - TMC26X Stepper library Example for Wiring/Arduino Copyright (c) 2011, <NAME>, <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <SPI.h> #include <TMC26XStepper.h> //you may adapt this to your shield or breakout board connection #define CS_PIN 2 #define DIR_PIN 6 #define STEP_PIN 7 //if it is not connected it won't be a problem // Comment the line if you do not have an enable pin assigned, or the // enable pin collides with any of your boards CS pins #define ENABLE_PIN 8 #define TIMER_CLOCK_FREQ 2000000.0 //2MHz for /8 prescale from 16MHz #define INITIAL_CURRENT 500 //in mA #define MAX_SPEED 1000 //we have a stepper motor with 200 steps per rotation, CS pin 2, dir pin 3, step pin 4 and a current of 500mA TMC26XStepper tmc26XStepper = TMC26XStepper(200,CS_PIN,DIR_PIN,STEP_PIN,INITIAL_CURRENT); char running; void setup() { //configure the enable pin #ifdef ENABLE_PIN pinMode(ENABLE_PIN, OUTPUT); digitalWrite(ENABLE_PIN,HIGH); #endif startSerial(); startMotor(); //set this according to you stepper Serial.println(F("started")); } void loop() { loopSerial(); runMotor(); }
ead39c175282b8ba31479faf02a3e674b89125d0
[ "C++" ]
2
C++
justjoheinz/TMC26XStepper
6c778694c717bd366bf9fbfce3743ba8c4f4bc22
20a8bfdd586d03a3cf450ea463e89870ebd36a52
refs/heads/master
<repo_name>AngularNinjaAvenger/numbers-game-with-react-src<file_sep>/Button.js import React from 'react' import './bootstrap.css' export default (props) => { return ( <div className="middo"> <button onClick={props.stopButton} className="btn btn-success jermoe" styles={{ marginButtom:10 }}> {props.type}</button> <button onClick={props.toggleTable}className="btn btn-warning skiddo" styles={{ marginButtom:10 }}>VIEW CHEAT SHEAT</button> </div> ) } // import React, { Component } from 'react' // import './bootstrap.css' // import './styles.css' // import Word from './Word' // import Button from './Button' // import Input from './Input' // import Score from './Score' // export default class Container extends Component { // constructor(props) { // super(props) // this.state = { // shouldBeNum:false, // value:'', // game:{ // 1:['a','b','c'], // 2:['d','e','f'], // 3:['g','h','i'], // 4:['j','k','l'], // 5:['m','n','o'], // 6:['p','q','r','s'], // 7:['t','u','v'], // 8:['w','x','y','z'], // }, // words:['bishop','bishop','bishop','bishop','bishop'], // wordToSpell:'bishop', // score:1, // userWord:[], // wordLength:0, // counter:20, // ckSsp:[null,null], // dotun:1 // } // } // componentDidMount(){ // let x = this.interval() // x.clear() // } // scoreChecker=()=>{ // this.setState(prevState => { // return { score: prevState.score+1 }; // }); // } // sizeCheck=(a)=>{ // let c = [] // for (let i = 0;i <a.length;i++){ // for (let j = 0;j <i;j++){ // c.push(j) // } // } // this.setState({ // wordLength:c.length // }) // return c // } // change=(e)=>{ // if(this.state.ckSsp[0] === true && this.state.ckSsp[1] === true){ // let a = e.target.value.split("") // let lastIndex = a[a.length-1] // if(this.state.game[lastIndex]){ // this.setState({ // value:e.target.value, // shouldBeNum:false // }) // for(let letter in a){ // let a = this.state.game[e.target.value[letter]] // try{ // let b = this.state.wordToSpell[letter] // if(a.includes(b)){ // this.state.userWord.push(b) // let nonso = this.sizeCheck(this.state.wordToSpell) // if(nonso.length+1 === this.state.userWord.length){ // console.log(this.state.dotun,nonso.length,this.state.userWord.length) // let timilehin = this.state.dotun+1 // this.setState({ // dotun:timilehin, // }) // this.setState({ // counter:20 // }) // this.setState({ // value:"" // }) // this.setState({ // userWord:[] // }) // this.setState({ // wordLength:0 // }) // this.setState({ // wordToSpell:this.state.word[Math.round(Math.random()*5)], // }) // } // //136356 // } // else{ // this.setState(prevState => { // return { value: "", // wordToSpell:prevState.words[Math.round(Math.random()*5)], // userWord:[], // dotun:this.state.dotun<1 ? 0 : prevState.dotun - 1, // counter:20 // } // }); // break // }}catch(err){ // this.setState(prevState => { // return { value: "", // wordToSpell:prevState.words[Math.round(Math.random()*5)] }; // }); // break // } // } // } // console.log(this.state.score) // }} // interval =(resume,clear)=>{ // let obj = { // set:setInterval(() => { // if(this.state.counter){ // this.setState({ // counter:this.state.counter-1 // }) // }else { // this.setState(prevState => { // return { value: "", // wordToSpell:prevState.words[Math.round(Math.random()*5)], // userWord:[], // score:this.state.score-1, // counter:20 // } // }); // } // }, 1000), // clear:function (){ // clearInterval(obj.set) // } // } // return obj // } // countDown=()=>{ // } // startButton=()=>{ // if( // this.state.ckSsp[0] === true // && // this.state.ckSsp[1] === true // ){ // return // } // this.setState(prevState => { // return { // ckSsp:[true,true], // wordToSpell:prevState.words[Math.round(Math.random()*5)] // } // }); // let start = this.interval() // return start.set // } // stopButton=()=>{ // let x = this.interval() // return x.clear() // } // render() { // return ( // <div className="container bg-primary"> // <p className="para">SPELL THE WORLD</p> // <Word word={undefined/*this.state.wordToSpell*/} counter={this.state.counter}/> // {this.state.shouldBeNum ?"you can only enter numbers" : null } // <Input value={this.state.value} onPaste={this.paste} change={this.change}/> // <Score score={this.state.dotun}/> // <Button // startButton={this.startButton} // type={"START"} // /> // <Button // stopButton={this.stopButton} // type={"STOP"} // /> // </div> // ) // } // } <file_sep>/Input.js import React from 'react' import './styles.css' export default function Input(props) { return ( <div className="col-lg-12 col-md-12 col-sm-12"> <input type="text" onChange={(e)=>{props.change(e)}} value={props.value}/> </div> ) } <file_sep>/Table.js import React from 'react' import './bootstrap.css' export default ({game,state}) => { let keys = Object.keys(game).map((item,index)=>{ return ( <tr key={index}> <th scope="row">{item}</th> {game[item].map((daniel,index)=>{ return ( <td key={daniel}>{daniel}</td> ) })} </tr> ) }) if(state){ return ( <div> BORDERED TABLE <table className="table table-bordered"> <thead> <tr> <th>NUMBER</th> <th collspacing="2">ALP</th> <th collspacing="2">ALP</th> <th collspacing="2">ALP</th> <th collspacing="2">ALP</th> </tr> </thead> <tbody> {keys} </tbody> </table> </div> ) } else{ return( <div> </div> ) } }
bbf2faa9a44ccb154548c22981563536e04efc48
[ "JavaScript" ]
3
JavaScript
AngularNinjaAvenger/numbers-game-with-react-src
46cd73b085190a516c889bd3df62918989b53de8
6fb51333e5d6ee4f7001a70a12014ecc07ff5fbf
refs/heads/master
<file_sep>// This file is required by the index.html file and will // be executed in the renderer process for that window. // All of the Node.js APIs are available in this process. const fs = require('fs'); const os = require('os'); const swal = require('sweetalert'); const mkdirp = require('mkdirp'); let homeDir = os.homedir() + '/Desktop/'; // document.getElementById('saveTo').textContent = "Hotfix will be saved to " + homeDir; String.prototype.replaceAll = function(search, replacement) { var target = this; return target.split(search).join(replacement); }; function validateFile(path) { return path.endsWith('.class'); } function transformPath(path) { if(path === null || path.length < 1) return; let delimiter = ''; if(os.type() === "Windows_NT") { delimiter = '\\'; } const newPath = path.replaceAll(delimiter,'/'); console.log(newPath); return newPath; } function getFileName(path) { if(path === null || path.length < 1) return; let delimiter = ''; if(os.type() === "Windows_NT") { delimiter = '\\'; } else { delimiter = '/' } array = path.split(delimiter); return array[array.length - 1]; } function generateDir(homeDir, classDir, filePath, fileName) { if(homeDir === null || homeDir === '') return; if(classDir === null || classDir === '') return; if(!homeDir.endsWith('/')) { homeDir += '/'; } if(classDir.startsWith('/')) { classDir = classDir.slice(1); } let targetDir = homeDir + classDir; targetDir = targetDir.replace('classes','classes/hotfix'); console.log(targetDir); mkdirp(targetDir, function(err) { if (err) { console.error(err); } else { console.log('dir created'); if(!targetDir.endsWith('/')) { targetDir += '/'; } const newFilePath = targetDir + fileName; console.log(newFilePath); fs.writeFileSync(newFilePath, fs.readFileSync(filePath)); } }); } function getClassPath(path) { if(path === null || path.length < 1) return; const index = path.indexOf('/classes/com'); const lastIndex = path.lastIndexOf("/"); return path.slice(index, lastIndex); } function main() { lis = document.querySelectorAll("li"); if(lis.length < 1) { swal("","You need to select files before proceeding.","error"); return; } for(let li of lis) { const path = li.textContent; const filePath = transformPath(path); const fileName = getFileName(path); const classPath = getClassPath(filePath); // console.log('classpath',classPath); generateDir(homeDir, classPath, filePath, fileName); } swal("","Hotfix is generated successfully","success"); } document.addEventListener('drop', function (e) { e.preventDefault(); e.stopPropagation(); for (let f of e.dataTransfer.files) { const fileli = document.createElement('li'); fileli.textContent = f.path; if(!validateFile(f.path)) { swal("","Please only select .class files","error"); return; } var t = document.getElementsByTagName('li') // for(let existFilePath of t.path) for (var i = 0;i<t.length; i ++) { console.log(f.path + ':'+t[i].textContent) if(f.path === t[i].textContent){ swal("",'file '+ f.path+ ' has existed!',"info") f.existflag = true break } } if(!f.existflag) { var deleteButton = document.createElement("i"); deleteButton.className = "fa fa-close deleteButton"; //deleteButton.setAttribute("aria-hidden", "true"); fileli.appendChild(deleteButton); //@get current li asyncGetLi(deleteButton).then(function(value) { }, function(err) { console.log(err); }); // @set: deleteButton dom document.getElementById('results').appendChild(fileli); } } document.querySelector('form p').textContent = document.getElementById('results').children.length + " file(s) selected"; }); document.addEventListener('dragover', function (e) { e.preventDefault(); e.stopPropagation(); }); document.querySelector('form').addEventListener("change", function(e) { e.preventDefault(); e.stopPropagation(); document.querySelector('form p').textContent = e.target.files.length + " file(s) selected"; for (let f of e.target.files) { const fileli = document.createElement('li'); fileli.textContent = f.path; if(!validateFile(f.path)) { swal("","Please only select .class files","error"); return; } document.getElementById('results').appendChild(fileli); } document.querySelector('form p').textContent = document.getElementById('results').children.length + " file(s) selected"; }) const mainBtn = document.getElementById("mainBtn"); mainBtn.addEventListener('click', main); // select home dir const ipc = require('electron').ipcRenderer const selectDirBtn = document.getElementById('select-file') selectDirBtn.addEventListener('click', function (event) { ipc.send('open-file-dialog','ping') }); //Getting back the information after selecting the file ipc.on('selected-file', function (event, path) { //do what you want with the path/file selected, for example: console.log(path[0]) const newPath = path[0].replace(/\\/g,'/') homeDir = newPath // document.getElementById('slected-file').innerHTML = `You selected: ${path[0]}` document.getElementById('slected-file').value = path[0] }); // delete function deleteDom(currentLi) { document.getElementById('results').removeChild(currentLi); }; function asyncGetLi( deleteButton) { return new Promise(function(resolve, reject) { var currentLi = deleteButton.parentNode; deleteButton.addEventListener("click", function() { deleteDom( currentLi ); });  resolve(currentLi); }); } function asyncGetLi( deleteButton) { return new Promise(function(resolve, reject) { var currentLi = deleteButton.parentNode; deleteButton.addEventListener("click", function() { deleteDom( currentLi ); document.querySelector('form p').textContent = document.getElementById('results').children.length + " file(s) selected"; });  resolve(currentLi); }); } <file_sep># hotfix maker This app helps developers to generate hotfix easily by providing a user friendly GUI and do file path manipulation for you. ![screenshot](hotfix.PNG) ## How to use 1. Navigate to the .class files in the File Explorer and Drag the .class files to the box inside the app. 2. Choose where to save your hotfix. The default location is Desktop 3. Click Start button to generate the package of hotfix 4. Copy the generated hotfix package to your remote machine and choose the proper location. ## Node scripts 1. Run it in dev mode ``` npm install npm start ``` 2. Build it (for Windows) ``` npm run package ```
0f91046a4e39138a47be7338c63d802b06a83f36
[ "JavaScript", "Markdown" ]
2
JavaScript
xinyzhang9/hotfix-maker
cfa233507398e0823e5e3bf624f52d59365f43a9
f1a08f0fdd1d733bef49c6edd9b0dfc63b95da26
refs/heads/master
<repo_name>jameshball/flocking<file_sep>/TODO.txt Make the mouse a 'boid' so that boids can interact with it. Get a grid-based neighbour detection system actually working (i.e. understand how it works)<file_sep>/flocking.js let boids = []; let s; let separationWeight = 300; let alignmentWeight = 0.1; let cohesionWeight = 0.1; let neighbourRadius = 130; let separationRadius = 30; function setup() { let maxRadius = max(neighbourRadius, separationRadius); createCanvas((displayWidth / maxRadius) * maxRadius, (displayHeight / maxRadius) * maxRadius); s = new Species(1, 1000); } function draw() { background(41); s.update(); s.show(); //text(int(frameRate()), 20, 170); //text(width + "x" + height, 20, 200); } // Class used for rendering multiple flocks on ths screen at once. class Species { constructor(n, s) { this.flocks = []; colorMode(HSB, 1.0); for (let i = 0; i < n; i++) { // Generate random hue values, and semi-random brightness values for each flock. this.flocks[i] = new Flock(s, color(random(1), random(0.8, 1), random(0.75, 1))); } colorMode(RGB, 255); } update() { for (let i = 0; i < this.flocks.length; i++) { this.flocks[i].update(); } } show() { for (let i = 0; i < this.flocks.length; i++) { this.flocks[i].show(); } } } class Grid { constructor(x, y) { this.cells = []; this.rows = x; this.cols = y; for (let i = 0; i < x; i++ ) { this.cells[i] = []; } for (let i = 0; i < x; i++) { for (let j = 0; j < y; j++) { this.cells[i][j] = []; } } } } // Flock class used to manage multiple boids and draw them all on the screen at once. class Flock { // Inputs the size of the flock and the colour. constructor(s, colour) { this.boids = []; this.colour = colour; this.colShift = random(0.001, 0.005); this.grid = new Grid(width/neighbourRadius, height/neighbourRadius); for (let i = 0; i < s; i++) { let boid = new Boid(this.grid.rows, this.grid.cols); this.boids[i] = boid; this.grid.cells[this.boids[i].cell[0]][this.boids[i].cell[1]].push(i); } } // Apply the cohesion behavior to a boid, given its neighbours. cohesion(i, neighbours) { let total = createVector(0, 0); let count = 0; for (let j = 0; j < neighbours.length; j++) { if (this.boids[i].pos.dist(this.boids[neighbours[j]].pos) < neighbourRadius) { total.add(this.boids[neighbours[j]].pos); count++; } } // Steer towards the average location of all neighbouring boids. this.boids[i].steerTo(total.div(count)); } // Apply the alignment behavior to a boid, given its neighbours. alignment(i, neighbours) { let total = createVector(0, 0); let count = 0; for (let j = 0; j < neighbours.length; j++) { if (this.boids[i].pos.dist(this.boids[neighbours[j]].pos) < neighbourRadius) { total.add(this.boids[neighbours[j]].vel); count++; } } total.div(count); // Apply the average velocity of all neighbouring boids. this.boids[i].vel.add(total.mult(alignmentWeight)); } // Apply the separation behavior to a boid, given its neighbours. separation(i, neighbours) { let total = createVector(0, 0); let count = 0; for (let j = 0; j < neighbours.length; j++) { if (this.boids[i].pos.dist(this.boids[neighbours[j]].pos) < separationRadius) { // Temporary variables let iPos = this.boids[i].pos.copy(); let jPos = this.boids[neighbours[j]].pos.copy(); // This adds a vector that points in the opposite direction of the other vector that is inversely proportional to its distance to boid i. total.add(iPos.sub(jPos).normalize().div(iPos.dist(jPos))); count++; } } // Apply the average separation velocity of all neighbouring boids. this.boids[i].vel.add(total.div(count).mult(separationWeight)); } // Get the list of all potential neighbours of a particular boid. neighbours(i) { // This doesn't even do anything in particular. I don't know why this works. let cell = [this.boids[i].cell[0] - 1, this.boids[i].cell[1] - 1]; let n = []; // Using r, c here as i is already being used. // If r and c are changed to different numbers, there are different behaviours. I don't know how this works... for (let r = 0; r < 3; r++) { for (let c = 0; c < 3; c++) { let append = this.grid.cells[int((this.grid.rows + cell[0] + r) % this.grid.rows)][int((this.grid.cols + cell[1] + c) % this.grid.cols)] n = n.concat(append); } } return n; } // Update creates a new thread which applies the flocking bechaviours to each boid. // Threading (even just one thread per frame) improves performance significantly. update() { for (let i = 0; i < this.boids.length; i++) { let neighbours = this.neighbours(i).slice(); this.cohesion(i, neighbours); this.alignment(i, neighbours); this.separation(i, neighbours); this.boids[i].update(); } } show() { colorMode(HSB, 1.0); let newHue = hue(this.colour) + this.colShift; if (newHue > 1) { newHue = 0; } this.colour = color(newHue, saturation(this.colour), brightness(this.colour)); for (let i = 0; i < this.boids.length; i++) { this.boids[i].show(this.colour); } colorMode(RGB, 255); } } class Boid { constructor(x, y) { this.vel = createVector(random(-1, 1), random(-1, 1)); this.pos = createVector(random(width), random(height)); this.size = 3; this.maxSpeed = random(1, 3); this.cell = [int(random(x)), int(random(y))]; } // d is the desired target to steer towards. steerTo(d) { // Calculate the vector that points to the target. d.sub(this.pos); let dist = d.mag(); if (dist > 0) { // Normalise and scale the vector based on the distance to the target. d.normalize().mult(this.maxSpeed); this.vel.add(d.sub(this.vel).limit(cohesionWeight)); } } update() { //steerTo(new PVector(mouseX, mouseY)); this.vel.limit(this.maxSpeed); this.pos.add(this.vel); this.pos.x = (this.pos.x + width) % width; this.pos.y = (this.pos.y + height) % height; } show(c) { fill(c); // Translates the canvas to the position of the boid and then draws a triangle that is rotated according to the direction the boid is facing in. push(); translate(this.pos.x, this.pos.y); rotate(this.vel.heading() + PI/2); triangle(0, -2*this.size, -this.size, 2*this.size, this.size, 2*this.size); pop(); } }<file_sep>/README.md # flocking Messing around with flocking behavioral algorithms - see https://en.wikipedia.org/wiki/Flocking_(behavior) You can see a live demo of the p5.js version here: https://www.doc.ic.ac.uk/~jhb119/ I wanted to make this more efficient so I tried implementing space partitioning, which was going well, but mid-way through implementing it, the flocks still worked, when they really shouldn't have. I realised I wasn't even updating the grid reference the boids were in, but it still looked amazing. In short, I have genuinely no idea how this program works, outside of the standard cohesion, alignment, and separation part. If you can make use of this or explain to me how this works, please do! I have commented it pretty well, along with the parts that I don't understand at all!
ce61964f1fbeb44b7e0f825234efb5abd819da59
[ "JavaScript", "Text", "Markdown" ]
3
Text
jameshball/flocking
9d051adab3d34d6b3c2259efefddf1c2a0e9032e
5a9078c0d1298b40a58a1cdd8e729e56114e5cfd
refs/heads/master
<file_sep>## The following are a pair of functions that cache the inverse of a matrix. ## The first function creates a special "matrix" object that can cache its inverse ## which is really a list containing a function to ## 1. set the value of the matrix ## 2. get the value of the matrix ## 3. set the value of the inverse ## 4. get the value of the inverse ## We use the `<<-` operator which can be used to assign a value to an object ## in an environment that is different from the current environment. makeCacheMatrix <- function(x = matrix()) { ## This will be used to store the cache of the inverse of the matrix inv_erse <- NULL ## This helps us set the value of the matrix set <- function(y) { x <<-y inv_erse <<- NULL } ## This helps us get the value of the matrix get <- function() x ## This helps us set the value of the inverse setinverse <- function(inverse) inv_erse <<- inverse ## This helps us get the value of the inverse getinverse <- function() inv_erse ## The list list(set=set, get=get, setinverse=setinverse, getinverse=getinverse) } ## The second function computes the inverse of the special "matrix" returned by ## `makeCacheMatrix` above. If the inverse has already been calculated ## (and the matrix has not changed), then `cacheSolve` should retrieve ## the inverse from the cache. cacheSolve <- function(x, ...) { ## This helps us check if the inverse has already been calculated. ## If so, it `get`s the mean from the cache and skips the computation. inv_erse <- x$getinverse() if(!is.null(inv_erse)) { message("Getting cached data") return(inv_erse) } ## This helps us calculates the inverse of the data and sets the value ## of the inverse in the cache via the `setinverse` function. ## Computing the inverse of a square matrix can be done with the `solve` ## function in R. For example, if `X` is a square invertible matrix, then ## `solve(X)` returns its inverse. ## Here we assume that the matrix supplied is always invertible. data <- x$get() inv_erse <- solve(data,...) x$setinverse(inv_erse) inv_erse ## Return a matrix that is the inverse of 'x' }
943b2f4cdd37f7038f843de2c3c18efacc2e3001
[ "R" ]
1
R
Ajoyfive/ProgrammingAssignment2
09fe6602eedf4785ebef35eee603094bd988c47a
d84feb943a460d776d60a621f5fcabcf0d8d87a6
refs/heads/main
<repo_name>satishpr9/Computer_vision<file_sep>/opencv2.py import numpy as np import cv2 video_path="/home/satish/Videos/VID_20210225_140522.mp4" video_path1="/home/satish/Downloads/videoplayback1.mp4" cap1=cv2.VideoCapture(0) cap= cv2.VideoCapture(video_path) cap3=cv2.VideoCapture(video_path1) while cap.isOpened(): #create a variable ret to assign true or false ret,frame=cap.read() ret2,frame2=cap1.read() ret3,frame3=cap3.read() if ret: image= cv2.resize(frame,(320,120)) camera_frame=cv2.resize(frame2,(320,120)) video_camera=cv2.resize(frame3,(320,120)) #for multiple video in one window frame_2=np.hstack((image,camera_frame)) frame_4=np.hstack((image,video_camera)) frame_5=np.vstack((frame_2,frame_4)) cv2.imshow("Video",frame_5) if cv2.waitKey(25) & 0xff == ord("q"): break else: break cap.release() cv2.destroyAllWindows()<file_sep>/opencv.py import cv2 #read image img = cv2.imread("/home/satish/Pictures/Elon_Musk_2015.jpg",1) #show the image # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY ) scale=20 print("Origin Dimension:", img.shape) width=int(img.shape[1]*scale/100) height=int(img.shape[0]*scale/100) dim=(width,height) resized=cv2.resize(img,dim,interpolation=cv2.INTER_AREA) # print("Resized Dimension:", resized) cv2.imshow('image',resized) angel90=90 center=(width/2,height/2) scle=1.0 M=cv2.getRotationMatrix2D(center,angel90,scle) angel90=cv2.warpAffine(resized,M,(height,width)) cv2.imshow("Rotate90=",angel90) angle180=180 M=cv2.getRotationMatrix2D(center,angle180,scle) angle180=cv2.warpAffine(resized,M,(height,width)) cv2.imshow("Rotate180:",angle180) angle270=270 M=cv2.getRotationMatrix2D(center,angle270,scle) angle270=cv2.warpAffine(resized,M,(height,width)) cv2.circle(resized,(80,80),55,(0,255,0),-1) cv2.imshow("Color Image:",resized) cv2.imshow("Rotate270:",angle270) cv2.waitKey(0) #save the image # elon=cv2.imwrite("/home/satish/Elon_Musk.jpg",img) # elon=img[100,100] # height, width, number of channels in image # height = img.shape[0] # width = img.shape[1] # channels = img.shape[2] # size1 = img.size # print('Image Height : ',height) # print('Image Width : ',width) # print('Number of Channels : ',channels) # print('Image Size :', size1) # print("Save The File ",elon) <file_sep>/opencv3.py import cv2 import numpy as np frameWidth=300 frameHeight=300 cap=cv2.VideoCapture(0) cap.set(3, frameWidth) cap.set(4,frameHeight) def WebCam_Images(imgArray,scale,labels=[]): sizeW=imgArray[0][0].shape[1] sizeH=imgArray[0][0].shape[0] rows=len(imgArray) cols=len(imgArray[0]) rowsAvailable=isinstance(imgArray[0],list) width=imgArray[0][0].shape[1] height=imgArray[0][0].shape[0] if rowsAvailable: for x in range(0,rows): for y in range(0,cols): imgArray[x][y]=cv2.resize(imgArray[x][y],(sizeW,sizeH),None, scale, scale) if len(imgArray[x][y].shape)==2: imgArray[x][y]=cv2.cvtColor(imgArray[x][y],cv2.COLOR_GRAY2BGR) imageBlank=np.zeros((height,width,3), np.uint8) hor=[imageBlank]*rows hor_con=[imageBlank]*rows for x in range(0,rows): hor[x]=np.hstack(imgArray[x]) hor_con[x]=np.concatenate(imgArray[x]) ver=np.vstack(hor) ver_con=np.concatenate(hor) else: for x in range(0,rows): imgArray[x]=cv2.resize(imgArray[x],(sizeW,sizeH),None,scale,scale) if len(imgArray[x].shape)==2: imgArray[x]=cv2.cvtColor(imgArray[x],cv2.COLOR_GRAY2BGR) hor=np.hstack(imgArray) hor_con=np.concatenate(imgArray) ver=hor if len(labels)!=0: ImgWidth=int(ver.shape[1]/cols) ImgHeight=int(ver.shape[0]/rows) print(eachImgHeight) for d in range(0,rows): for c in range(0,cols): cv2.rectangle(ver,(c*ImgWidth,ImgHeight*d),(c*ImgWidth+len(tables[d][c])*13+27,30+ImgHeight*d),(255,255,255),cv2.FILLED) return ver while True: success, img=cap.read() kernel=np.ones((5,5),np.uint8) print(kernel) imgGray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) imgBlur=cv2.GaussianBlur(imgGray,(7,7),0) imgCanny=cv2.Canny(imgBlur,100,200) imgDilation=cv2.dilate(imgCanny,kernel, iterations=2) imgEroded=cv2.erode(imgDilation,kernel,iterations=2) StackedImages=WebCam_Images(([img,imgGray,imgBlur], [imgCanny,imgDilation,imgEroded]),0.6) cv2.imshow("Stacked Images",StackedImages) if cv2.waitKey(1) & 0xFF== ord("q"): break
7d5c4ebda6d5a60d0a834a22b25dc5f7509dae6e
[ "Python" ]
3
Python
satishpr9/Computer_vision
289bfaebd6cef07cfd69b26bb21cf03e459e6eba
3fffe958e11556e4ac5c85c738bb603931eabea2
refs/heads/master
<file_sep>#ifndef __github_com_myun2__flax__i1o1_HPP__ #define __github_com_myun2__flax__i1o1_HPP__ // Input:1, Output:1 namespace myun2 { namespace flax { template <typename Reader, typename Writer> class i1o1 { protected: Reader reader; Writer writer; public: typedef typename Reader::T T, Type; i1o1(){} i1o1(const Reader &in_reader, const Writer &in_writer) : reader(in_reader), writer(in_writer) {} }; } } #endif//__github_com_myun2__flax__i1o1_HPP__ <file_sep>#ifndef __github_com_myun2__flax__i3o1_HPP__ #define __github_com_myun2__flax__i3o1_HPP__ // Input:3, Output:1 namespace myun2 { namespace flax { template <typename Reader1, typename Reader2, typename Reader3, typename Writer> class i3o1 { protected: Reader1 reader1; Reader2 reader2; Reader3 reader3; Writer writer; public: typedef typename Reader1::T T, Type; i3o1(){} i3o1(const Reader1 &in_reader1, const Reader2 &in_reader2, const Reader3 &in_reader3, const Writer &in_writer) : reader1(in_reader1), reader2(in_reader2), reader3(in_reader3), writer(in_writer) {} }; } } #endif//__github_com_myun2__flax__i1o1_HPP__ <file_sep>#include "myun2/flax/util/pipelike.hpp" #include "myun2/flax/util/line_reader.hpp" #include "myun2/flax/util/line_writer.hpp" #include "myun2/flax/io/stdinput.hpp" #include "myun2/flax/io/stdoutput.hpp" using namespace myun2::flax; using namespace myun2::flax::util; class echoback : public pipelike<line_reader<io::stdinput>, line_writer<io::stdoutput> > { bool action(const ::std::string& s) { writer.write(s + '\n'); return true; } }; int main( int argc, char *argv[] ) { echoback eb; eb.run(); return 0; } <file_sep>#ifndef __github_com_myun2__flax__examples__xml_parser_HPP__ #define __github_com_myun2__flax__examples__xml_parser_HPP__ #include "myun2/flax/util/ws_split_reader.hpp" namespace myun2 { namespace flax { namespace example { namespace xml_parser_internal { } ///////////// template <typename ReadStream> class xml_parser : public stack_machine<ws_split_reader<int, ReadStream> > { protected: bool action(const ::std::string& token) { state return true; } }; } } } #endif//__github_com_myun2__flax__examples__xml_parser_HPP__ <file_sep># Utility Classes ### file_pointer `file_pointer` class is overlap `FILE*` of shared object. When an object is copied, call `fclose` when the last instance is released. ### looper ``` virtual bool action() =0; void run() { while(action()); } ``` This class is simplest code! :+1: `looper` class call pure-virtual-function `action` while returned `true`.<file_sep>#ifndef __github_com_myun2__flax__util__looper_HPP__ #define __github_com_myun2__flax__util__looper_HPP__ namespace myun2 { namespace flax { struct looper { virtual bool action() =0; void run() { while( action() ) {} } }; } } #endif//__github_com_myun2__flax__util__looper_HPP__ <file_sep>#ifndef __github_com_myun2__flax__examples__xml_document_HPP__ #define __github_com_myun2__flax__examples__xml_document_HPP__ #include <string> #include <vector> #include <map> namespace myun2 { namespace flax { namespace example { struct xml_header { static const char* version_str() const { return "version"; } static const char* encoding_str() const { return "encoding"; } static const char* standalone_str() const { return "standalone"; } ::std::string version; ::std::string encoding; ::std::string standalone; }; struct xml_element_content { ::std::vector<> text_allocates; private: ::std::vector<xml_element> element_allocates; ::std::vector<::std::string> text_allocates; }; struct xml_element { private: struct node { enum { text, element } type_ type; void* ptr; // xml_element or ::std::string pointer. }; ::std::vector<xml_element> element_allocates; ::std::vector<::std::string> text_allocates; public: ::std::string name; ::std::map<std::string, std::string> attributes; ::std::vector<node> childs; }; struct xml_document { xml_header header; xml_element root; }; } } } #endif//__github_com_myun2__flax__examples__xml_document_HPP__ <file_sep>#ifndef __github_com_myun2__flax__util__line_reader_HPP__ #define __github_com_myun2__flax__util__line_reader_HPP__ #include <string> namespace myun2 { namespace flax { namespace util { template <typename _Reader> class line_reader : public _Reader { public: line_reader(){} line_reader(const _Reader &r) : _Reader(r){} typedef ::std::string T; ::std::string read() { ::std::string buf; while(1) { int c = _Reader::read(); if ( is_end() ) break; if ( c == '\r' || c == '\n' ) break; buf += c; } return buf; } bool is_end() const { return _Reader::is_end(); } }; } } } #endif//__github_com_myun2__flax__util__line_reader_HPP__ <file_sep># Streaming Utility Classes ## line_reader read buffering of each line. tokenized by '\n' or '\r'. ## line_writer write line string. ### ws_split_reader `ws_split_reader` class was read of Whitespace tokenized. <file_sep># Flax **"Flax"** is Anything Processing Library for **C++**. ## Getting Started 1. Please add to your project `include` directory. ### Most Simple Application This is Most Simple echo-back Application code. ```c++ #include "myun2/flax/serial_runner.hpp" #include "myun2/flax/io/stdinput.hpp" #include "myun2/flax/io/stdoutput.hpp" using namespace myun2::flax; class echoback : public serial_runner<io::stdinput, io::stdoutput> { public: bool action(const T& v) { write(v); return true; } }; int main( int argc, char *argv[] ) { echoback eb; eb.run(); return 0; } ``` # More Reference... ## Class References * Streaming Classes <file_sep>#ifndef __github_com_myun2__flax__io__line_writer_HPP__ #define __github_com_myun2__flax__io__line_writer_HPP__ #include <string> namespace myun2 { namespace flax { namespace util { template <typename _Writer> class line_writer : public _Writer { public: line_writer(){} line_writer(const _Writer &w) : _Writer(w){} typedef const char* T; void write(const char* s) { while(*s) { _Writer::write(*s++); } } void write(const ::std::string &s) { write(s.c_str()); } }; } } } #endif//__github_com_myun2__flax__io__line_writer_HPP__ <file_sep># Exception Classes ## Overview **Flax** classes throw exception when abnormal something causes or errors. For example, stream open error. or streaming read errors, etc... If you do not catch exceptions properly, application Crashes when these Abnormalities occur!! It should be noted. You should be careful if you do not catch exceptions properly, application will crash!! 貴方は例外を適切にキャッチしなければ、アプリケーションはクラッシュするので、注意が必要である。 ## `exception` Class `exception` is most Base Exception Class. ## `standard_error` Class `standard_error` class mean standard error. This class has to base the `exception`. ## Difference between `exception` and `standard_error`? Treatment of `exception` and `standard_error` are substantially the same at this time. But in the future, there is a possibility that the person of the `exception` is to exception handling a more deadly.<file_sep>#ifndef __github_com_myun2__flax__i1o3_HPP__ #define __github_com_myun2__flax__i1o3_HPP__ // Input:1, Output:3 namespace myun2 { namespace flax { template <typename Reader, typename Writer1, typename Writer2, typename Writer3> class i1o3 { protected: Reader reader; Writer1 writer1; Writer2 writer2; Writer3 writer3; public: typedef typename Reader::T T, Type; i1o3(){} i1o3(const Reader &in_reader const Writer1 &in_writer1, const Writer2 &in_writer2, const Writer3 &in_writer3 ) : reader(in_reader), writer1(in_writer1), writer2(in_writer2), writer3(in_writer3) {} }; } } #endif//__github_com_myun2__flax__i1o2_HPP__ <file_sep>#ifndef __github_com_myun2__flax__serial_reader_HPP__ #define __github_com_myun2__flax__serial_reader_HPP__ namespace myun2 { namespace flax { template <typename Reader> class serial_reader { private: Reader reader; public: typedef typename Reader::T T, Type; serial_reader(){} serial_reader(const Reader &in_reader) : reader(in_reader) {} virtual bool action(const T& v)=0; void run() { while(1) { Type v = reader.read(); if ( reader.is_end() ) break; if ( !action(v) ) break; } } }; } } #endif//__github_com_myun2__flax__serial_reader_HPP__ <file_sep># Streaming Classes ## Basically Streaming Classes divided into two major. **Input(Reader) classes** and **Output(Writer) classes**. **Input Classes** have two methods. * `T read();` * `bool is_end();` `T read();` method read one of item from input stream. `bool is_end();` method can check the end of input stream. (like `feof` != 0) `T` is Any-Type of template specified or fixed with class type. **Output Classes** have one method. * `void write(const T& val);` `write` method write one of item to output stream. ### Constructor **Constructor parameters Is Not Constant**. it's different for each class. Please refer to the commentary for each class. ## Classes ### filereader `filereader` is for File Read Streaming Class. It has the following methods. * `typedef int T` * `int read()` * `bool is_end()` `T` is fixed `int` of Type. `read()` is like or in fact `getc()`. `is_end()` is like or in fact `feof() != 0`. #### Constructor * `filereader(const char* path, bool binary=true)` The `path` parameters, specify the read/open target file name or path. If you want to get the contents of a file in **text mode**, you specify `false` to the second argument. (default binary-mode) ### filewriter `filewriter` is for File Write Streaming Class. * `typedef int T` * `void write(int c)` `T` is fixed `int` of Type. `write()` is like or in fact `putc()`. #### Constructor * `filewriter(const char* path, bool binary=true)` The `path` parameters, specify the write/open target file name or path. If you want to write a file in **text mode**, you specify `false` to the second argument. (default binary-mode) ### stdinput `stdinput` is for Standard Input Streaming Class. * `typedef int T` * `int read()` * `bool is_end()` `T` is fixed `int` of Type. `read()` is like or in fact `getchar()`. `is_end()` is like or in fact `feof(stdin) != 0`. ### stdoutput `stdoutput` is for Standard Input Streaming Class. * `typedef int T` * `void write(int c)` `T` is fixed `int` of Type. `read()` is like or in fact `putchar()`. <file_sep>#ifndef __github_com_myun2__flax__i1o2_HPP__ #define __github_com_myun2__flax__i1o2_HPP__ // Input:1, Output:2 namespace myun2 { namespace flax { template <typename Reader, typename Writer1, typename Writer2> class i1o2 { protected: Reader reader; Writer1 writer1; Writer2 writer2; public: typedef typename Reader::T T, Type; i1o2(){} i1o2(const Reader &in_reader, const Writer1 &in_writer1, const Writer2 &in_writer2) : reader(in_reader), writer1(in_writer1), writer2(in_writer2) {} }; } } #endif//__github_com_myun2__flax__i1o2_HPP__ <file_sep>#ifndef __github_com_myun2__flax__pipelike_HPP__ #define __github_com_myun2__flax__pipelike_HPP__ #include "myun2/flax/util/serial_reader.hpp" namespace myun2 { namespace flax { template <typename Reader, typename Writer> class pipelike : public serial_reader<Reader> { private: typedef serial_reader<Reader> _Base; protected: Writer writer; public: typedef typename Reader::T T, Type; pipelike(){} pipelike(const Reader &in_reader, const Writer &in_writer) : _Base(in_reader), writer(in_writer) {} }; } } #endif//__github_com_myun2__flax__pipelike_HPP__ <file_sep>#ifndef __github_com_myun2__flax__i2o1_HPP__ #define __github_com_myun2__flax__i2o1_HPP__ // Input:2, Output:1 namespace myun2 { namespace flax { template <typename Reader1, typename Reader2, typename Writer> class i2o1 { protected: Reader1 reader1; Reader2 reader2; Writer writer; public: typedef typename Reader1::T T, Type; i2o1(){} i2o1(const Reader1 &in_reader1, const Reader2 &in_reader2, const Writer &in_writer) : reader1(in_reader1), reader2(in_reader2), writer(in_writer) {} }; } } #endif//__github_com_myun2__flax__i1o1_HPP__
56fc09e0d1b9be2d7802c0fdf21690fde98c9e04
[ "Markdown", "C++" ]
18
C++
myun2ext/flax
93e3002cb6a47c56fd152775eeaf31a5f47c6f96
47df59ef0b6b2bf1de98f1c025c0679dcc63412e
refs/heads/master
<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "SimpleMutex_Runnable.h" //need for random generate #include <random> //need for build receiver #include "MessageEndpointBuilder.h" //for ScopeLock #include "Misc/ScopeTryLock.h" #include "ThreadExample/ThreadExampleGameModeBase.h" FSimpleMutex_Runnable::FSimpleMutex_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, bool bIsSecondMode) { ThreadColor = Color; GameMode_Ref = OwnerActor; bIsGenerateSecondName = bIsSecondMode; //IMessageBus sender init SenderEndpoint = FMessageEndpoint::Builder("Sender_FSimpleMutex_Runnable").Build(); } FSimpleMutex_Runnable::~FSimpleMutex_Runnable() { } uint32 FSimpleMutex_Runnable::Run() { TArray<FString> VowelLetter{"a", "e", "i", "o", "u", "y"}; TArray<FString> ConsonantLetter{"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"}; while (!bIsStopNameGenerator) { FString Result; bool bIsStartWithVowel = GetRandom(); int8 RandomSizeName; if (bIsGenerateSecondName) { RandomSizeName = GetRandom(5, 8); } else { RandomSizeName = GetRandom(3, 5); } for (int8 j = 0; j < RandomSizeName; j++) { bool FlipFlop = false; if (j % 2) FlipFlop = true; if (bIsStartWithVowel) { if (FlipFlop) Result.Append(VowelLetter[GetRandom(0, VowelLetter.Num() - 1)]); else Result.Append(ConsonantLetter[GetRandom(0, ConsonantLetter.Num() - 1)]); } else { if (FlipFlop) Result.Append(ConsonantLetter[GetRandom(0, ConsonantLetter.Num() - 1)]); else Result.Append(VowelLetter[GetRandom(0, VowelLetter.Num() - 1)]); } } FPlatformProcess::Sleep(1.88f); if (!bIsGenerateSecondName) { GameMode_Ref->FirstNameMutex.Lock(); GameMode_Ref->FirstNames.Add(Result); GameMode_Ref->FirstNameMutex.Unlock(); } else { GameMode_Ref->SecondNames.Enqueue(Result); } //IMessageBus send if(SenderEndpoint.IsValid()) SenderEndpoint->Publish<FBusStructMessage_NameGenerator>( new FBusStructMessage_NameGenerator(bIsGenerateSecondName,Result)); //GameMode_Ref->Delegate - standard delegate ue4 not working near threads } return 0; } void FSimpleMutex_Runnable::Stop() { bIsStopNameGenerator = true; } void FSimpleMutex_Runnable::Exit() { if (SenderEndpoint.IsValid()) SenderEndpoint.Reset(); GameMode_Ref = nullptr; } int8 FSimpleMutex_Runnable::GetRandom(int8 min, int8 max) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distrib(min, max); return distrib(gen); } bool FSimpleMutex_Runnable::GetRandom() { std::random_device rd; std::mt19937 gen(rd()); std::bernoulli_distribution d(0.5); return d(gen); }<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "AsyncTaskExample.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FAsyncTask_OnWorkDone, int32, OutputResult); UCLASS() class THREADEXAMPLE_API AAsyncTaskExample : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AAsyncTaskExample(); UPROPERTY(BlueprintAssignable) FAsyncTask_OnWorkDone AsyncTask_OnWorkDone; UPROPERTY(BlueprintReadWrite, EditAnywhere) int32 Counter = 0; UPROPERTY(EditAnywhere, BlueprintReadWrite) int32 Counter2 = 0; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; virtual void EndPlay(EEndPlayReason::Type EndPlayReason) override; UFUNCTION(BlueprintCallable) void StartExample(bool bIsBackGroundTask = true); }; <file_sep>// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" //need to control runnable #include "HAL/RunnableThread.h" //need for messageBus #include "IMessageBus.h" //Custom Runnable class #include "ThreadExample/SynchronizationPrimitives/SimpleAtomic_Runnable.h" #include "ThreadExample/SynchronizationPrimitives/SimpleCounter_Runnable.h" #include "ThreadExample/SynchronizationPrimitives/SimpleMutex_Runnable.h" #include "ThreadExample/SynchronizationPrimitives/SimpleCollectable_Runnable.h" #include "ThreadExampleGameModeBase.generated.h" USTRUCT(BlueprintType, Atomic) struct FInfoNPC { GENERATED_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite) int32 Id = 0; UPROPERTY(EditAnywhere, BlueprintReadWrite) FString Name = "none"; UPROPERTY(EditAnywhere, BlueprintReadWrite) FString SecondName = "none"; }; struct my_struct { int32 Id; char Name; //std::string SecondName; //we 'can't use because requires string must to be trivially copyable, copy constructible, move constructible, copy assignable, and move assignable. }; USTRUCT() struct FBusStructMessage_NameGenerator { GENERATED_BODY() bool bIsSecondName = false; FString TextName = "None"; FBusStructMessage_NameGenerator(bool InBool = false, FString InText = "None") : bIsSecondName(InBool), TextName(InText) {} }; DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnUpdateByNameGeneratorThreads, bool, bIsSecond, FString, StringData); DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnUpdateByThreadNPC, FInfoNPC, NPCData); /** * All setting and control thread BP-CPP here * SimpleCounter - how control thread and rule thread destroy with FThreadSafe variable (pause, kill, stop) and with semaphore on FEvent and FScopedEvent * SimpleAtomic - how save read write in thread with atomic - FPlatformAtomic and std::atomic * SimpleMutex - how save read write in thread with Locking - FCriticalSection and FSpinLocks and FScopeLock */ UCLASS() class THREADEXAMPLE_API AThreadExampleGameModeBase : public AGameModeBase { GENERATED_BODY() public: UPROPERTY(BlueprintAssignable) FOnUpdateByNameGeneratorThreads OnUpdateByNameGeneratorThreads; UPROPERTY(BlueprintAssignable) FOnUpdateByThreadNPC OnUpdateByThreadNPC; //MessageBus Setting start // Message handler for FJumpNowMessage, called by the Message Bus when a message arrives void BusMessageHandler(const struct FBusStructMessage_NameGenerator& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context); void BusMessageHandlerNPCInfo(const struct FInfoNPC& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context); TSharedPtr<FMessageEndpoint, ESPMode::ThreadSafe> ReceiveEndPoint_NameGenerator; TSharedPtr<FMessageEndpoint, ESPMode::ThreadSafe> ReceiveEndpoint_NPCInfo; //MessageBus Setting end virtual void Tick(float DeltaSeconds) override; virtual void BeginPlay() override; virtual void EndPlay(EEndPlayReason::Type EndPlayReason) override; void PrintMessage(FString message); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ThreadExampleGameModeBase setting") bool ShowDebugAllThread = false; //SimpleCounter Setting UPROPERTY(BlueprintReadWrite, Category = "SimpleCounter setting") bool bIsUseSafeVariable = true; UPROPERTY(BlueprintReadWrite, Category = "SimpleCounter setting") FColor ColorThread; UPROPERTY(BlueprintReadWrite, Category = "SimpleCounter setting") bool bIsUseFEvent = true; UPROPERTY(BlueprintReadWrite, Category = "SimpleCounter setting") bool bIsUseFSScopedEvent = true; class FSimpleCounter_Runnable *MyRunnableClass_SimpleCounter = nullptr; FRunnableThread* CurrentRunningGameModeThread_SimpleCounter = nullptr; FEvent *SimpleCounterEvent; FScopedEvent* SimpleCounterScopedEvent_Ref; //SimpleCounter Control UFUNCTION(BlueprintCallable) void StopSimpleCounterThread(); UFUNCTION(BlueprintCallable) void KillSimpleCounterThread(bool bIsShouldWait); UFUNCTION(BlueprintCallable) bool SwitchRunStateSimpleCounterThread(bool bIsPause); UFUNCTION(BlueprintCallable) void CreateSimpleCounterThread(); UFUNCTION(BlueprintCallable) void StartSimpleCounterThreadWithEvent(); UFUNCTION(BlueprintCallable) void StartSimpleCounterThreadWithScopedEvent(); UFUNCTION(BlueprintCallable) int64 GetCounterSimpleCounterThread(); void SendRef_ScopedEvent(FScopedEvent &ScopedEvent_Ref); //SimpleAtomic Setting TArray<FRunnableThread*> CurrentRunningGameModeThread_SimpleAtomic; UPROPERTY(BlueprintReadWrite, Category = "SimpleAtomic setting") int32 IterationForRunnableCircle = 100000; UPROPERTY(BlueprintReadWrite, Category = "SimpleAtomic setting") int32 NumberOfThreadToCreate = 12; UPROPERTY(BlueprintReadWrite, Category = "SimpleAtomic setting") bool bIsUseAtomic = true; //SimpleAtomic Control UFUNCTION(BlueprintCallable) void CreateSimpleAtomicThread(); UFUNCTION(BlueprintCallable) void GetCounterSimpleAtomic(int32 &Atomic1, int32 &NotAtomic1, int32 &Atomic2, int32 &NotAtomic2); UFUNCTION(BlueprintCallable) void ResetCounterSimpleAtomic(); //SimpleAtomic storage std::atomic_uint16_t AtomicCounter1; std::atomic_uint16_t AtomicCounter2; int16 NotAtomicCounter1; int16 NotAtomicCounter2; //std::atomic<my_struct> my_Struct; we can set atomic struct and more, (warning) write and read must be full on all variables) //SimpleMutex Setting TArray<FRunnableThread*> CurrentRunningGameModeThread_SimpleMutex; FRunnableThread* CurrentRunningGameModeThread_SimpleCollectable; //SimpleMutex Control UFUNCTION(BlueprintCallable) void StopSimpleMutexThreads(); UFUNCTION(BlueprintCallable) void CreateSimpleMutexThread(); UFUNCTION(BlueprintCallable) void CreateCollectableThread(); TArray<FInfoNPC> GetNPCInfo(); UFUNCTION(BlueprintCallable) TArray<FString> GetSecondNames(); UFUNCTION(BlueprintCallable) TArray<FString> GetFirstNames(); UFUNCTION(BlueprintCallable) void Clear(); void EventMessage(bool bIsSecond, FString StringData); void EventMessageNPC(FInfoNPC NPCData); //SimpleMutex storage TArray<FString> FirstNames; FCriticalSection FirstNameMutex; TQueue<FString,EQueueMode::Mpsc> SecondNames; FCriticalSection NPCInfoMutex; TArray<FInfoNPC> NPCInfo; TArray<FString> CurrentSecondName; //TLockFreePointerList //Same TQueue (TQueue under the hood linked list(LockFreePointerList)) UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SimpleMutex setting") TSubclassOf<class ADumbCuteCube> SpawnObjectThread; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SimpleMutex setting") FVector SpawnCuteCubeLoc; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SimpleMutex setting") FVector SpawnCuteCubeLoc_Step; int32 cubeCout =0; //ParallelFor UFUNCTION(BlueprintCallable) void StartParallelFor1(); UPROPERTY(BlueprintReadWrite) int32 ParallelCout1 = 0; UFUNCTION(BlueprintCallable) void StartParallelFor2(); UPROPERTY(BlueprintReadWrite) int32 ParallelCout2 = 0; UFUNCTION(BlueprintCallable) void StartParallelFor3(); UPROPERTY(BlueprintReadWrite) int32 ParallelCout3 = 0; }; <file_sep> [/Script/EngineSettings.GeneralProjectSettings] ProjectID=B8C01FD64E7FB655B6C45E9963DD5324 <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "SimpleAtomic_Runnable.h" #include "ThreadExample/ThreadExampleGameModeBase.h" FSimpleAtomic_Runnable::FSimpleAtomic_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, uint32 NeedIteration, bool SeparateLogic, bool bIsUseAtomic) { ThreadColor = Color; GameMode_Ref = OwnerActor; NumberIteration = NeedIteration; SeparateLogicFlag = SeparateLogic; bIsUseAtomicFlag = bIsUseAtomic; } FSimpleAtomic_Runnable::~FSimpleAtomic_Runnable() { } bool FSimpleAtomic_Runnable::Init() { return true; } uint32 FSimpleAtomic_Runnable::Run() { //FPlatformProcess::Sleep(1.0f); use sleep for debug for (int i = 0; i < NumberIteration; ++i) { if (SeparateLogicFlag) { if (bIsUseAtomicFlag) { GameMode_Ref->AtomicCounter1.fetch_add(1); FPlatformAtomics::InterlockedIncrement(&GameMode_Ref->NotAtomicCounter1); } else GameMode_Ref->NotAtomicCounter1++; } else { if (bIsUseAtomicFlag) { GameMode_Ref->AtomicCounter2.fetch_add(1); FPlatformAtomics::InterlockedIncrement(&GameMode_Ref->NotAtomicCounter2); } else GameMode_Ref->NotAtomicCounter2++; } } return 0; } void FSimpleAtomic_Runnable::Stop() { } void FSimpleAtomic_Runnable::Exit() { UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Exit ")); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "TaskGraphExample.h" #include "Async/TaskGraphInterfaces.h" #include "HAL/ThreadManager.h" #include "Kismet/GameplayStatics.h" // Sets default values ATaskGraphExample::ATaskGraphExample() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void ATaskGraphExample::BeginPlay() { Super::BeginPlay(); /*MainIdThread = FPlatformTLS::GetCurrentThreadId(); FString NameThread = FThreadManager::GetThreadName(MainIdThread); UE_LOG(LogTemp, Error, TEXT("FTask_SimpleWork NameThread - %s ID - %d"), *NameThread, MainIdThread); UE_LOG(LogTemp, Error, TEXT("FTask_SimpleWork NumberOfCores - %d"), FPlatformMisc::NumberOfCores()); UE_LOG(LogTemp, Error, TEXT("FTask_SimpleWork NumberOfCoresIncludingHyperthreads - %d"), FPlatformMisc::NumberOfCoresIncludingHyperthreads());*/ TaskDelegate.BindUFunction(this, FName("OnWorkDone")); AThreadExampleGameModeBase *myGameMode = Cast<AThreadExampleGameModeBase>(UGameplayStatics::GetGameMode(GetWorld())); myCurrentTask = TGraphTask<FTask_CounterWork>::CreateTask(nullptr, ENamedThreads::AnyThread).ConstructAndHold(TaskDelegate, myGameMode, &Counter, MainIdThread); } // Called every frame void ATaskGraphExample::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ATaskGraphExample::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); } void ATaskGraphExample::StartAsyncWork() { if (myCurrentTask) { //wait unlock task if (!myCurrentTask->GetCompletionEvent().IsValid()) { myCurrentTask->Unlock(); } } else { //Fire and Forget AThreadExampleGameModeBase *myGameMode = Cast<AThreadExampleGameModeBase>(UGameplayStatics::GetGameMode(GetWorld())); TGraphTask<FTask_CounterWork>::CreateTask(nullptr, ENamedThreads::AnyThread).ConstructAndDispatchWhenReady(TaskDelegate, myGameMode, &Counter, MainIdThread); } } void ATaskGraphExample::OnWorkDone(int32 Result) { myCurrentTask = nullptr; OnWorkDone_BP(Result); } void ATaskGraphExample::OnWorkDone_BP_Implementation(int32 Result) { //BP }<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "MessageEndpoint.h" class AThreadExampleGameModeBase; /** * */ class THREADEXAMPLE_API FSimpleCollectable_Runnable : public FRunnable { public: FSimpleCollectable_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor); virtual ~FSimpleCollectable_Runnable() override; //setting AThreadExampleGameModeBase* GameMode_Ref = nullptr; FThreadSafeBool bIsStopCollectable = false; virtual uint32 Run() override; virtual void Stop() override; virtual void Exit() override; //IMessageBus Setting TSharedPtr<FMessageEndpoint, ESPMode::ThreadSafe> SenderEndpoint; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "HAL/ThreadManager.h" class AThreadExampleGameModeBase; /** * */ class THREADEXAMPLE_API FSimpleAtomic_Runnable : public FRunnable { public: FSimpleAtomic_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, uint32 NeedIteration, bool SeparateLogic, bool bIsUseAtomic); virtual ~FSimpleAtomic_Runnable() override; //setting FColor ThreadColor; AThreadExampleGameModeBase *GameMode_Ref = nullptr; bool bIsStopThread = false; int NumberIteration = 0; bool SeparateLogicFlag; bool bIsUseAtomicFlag; virtual bool Init() override; virtual uint32 Run() override; virtual void Stop() override; virtual void Exit() override; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "HAL/RunnableThread.h" #include "RunnableThreadExample.h" #include "ThreadExample/ThreadExampleGameModeBase.h" #include "RunnableExample.generated.h" UCLASS() class THREADEXAMPLE_API ARunnableExample : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ARunnableExample(); UFUNCTION(BlueprintCallable) void InitCalculation(int32 Calc); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; class FRunnableThreadExample *CalcThread = nullptr; FRunnableThread *CurrentRunningThread = nullptr; public: // Called every frame virtual void Tick(float DeltaTime) override; virtual void EndPlay(EEndPlayReason::Type EndPlayReason); FThreadSafeCounter CurrentCalc; UPROPERTY(BlueprintReadWrite, EditAnywhere) float DiedTimer = 10.0f;; UFUNCTION(BlueprintCallable) int32 GetCalcValue(); }; <file_sep> [/Script/EngineSettings.GameMapsSettings] GameDefaultMap=/Game/Maps/Untitled.Untitled EditorStartupMap=/Game/Maps/Untitled.Untitled [/Script/HardwareTargeting.HardwareTargetingSettings] TargetedHardwareClass=Desktop AppliedTargetedHardwareClass=Desktop DefaultGraphicsPerformance=Maximum AppliedDefaultGraphicsPerformance=Maximum [/Script/Engine.Engine] +ActiveGameNameRedirects=(OldGameName="TP_Blank",NewGameName="/Script/ThreadExample") +ActiveGameNameRedirects=(OldGameName="/Script/TP_Blank",NewGameName="/Script/ThreadExample") +ActiveClassRedirects=(OldClassName="TP_BlankGameModeBase",NewClassName="ThreadExampleGameModeBase") [/Script/LuminRuntimeSettings.LuminRuntimeSettings] IconModelPath=(Path="") IconPortalPath=(Path="") [CoreRedirects] +PropertyRedirects=(OldName="/Script/ThreadExample.BusStructMessage.HelloText",NewName="/Script/ThreadExample.BusStructMessage.HelloTextNAme") +PropertyRedirects=(OldName="/Script/ThreadExample.BusStructMessage.HelloTextNAme",NewName="/Script/ThreadExample.BusStructMessage.TextNAme") +PropertyRedirects=(OldName="/Script/ThreadExample.BusStructMessage.TextNAme",NewName="/Script/ThreadExample.BusStructMessage.TextName") +PropertyRedirects=(OldName="/Script/ThreadExample.ThreadExampleGameModeBase.OnUpdateByThread",NewName="/Script/ThreadExample.ThreadExampleGameModeBase.OnUpdateByNameGeneratorThreads") +PropertyRedirects=(OldName="/Script/ThreadExample.ThreadExampleGameModeBase.ParrallelCout",NewName="/Script/ThreadExample.ThreadExampleGameModeBase.ParallelCout") +ClassRedirects=(OldName="/Script/ThreadExample.TaskGraphExampleSecond",NewName="/Script/ThreadExample.TaskGraphExample_Track") +ClassRedirects=(OldName="/Script/ThreadExample.AsynTaskExample",NewName="/Script/ThreadExample.AsyncTaskExample") +PropertyRedirects=(OldName="/Script/ThreadExample.AsyncTaskExample.counter",NewName="/Script/ThreadExample.AsyncTaskExample.Counter") +PropertyRedirects=(OldName="/Script/ThreadExample.TaskGraphExample.counter",NewName="/Script/ThreadExample.TaskGraphExample.Counter") +PropertyRedirects=(OldName="/Script/ThreadExample.AsyncTaskExample.AsyncTaskDelegate_OnWorkDone",NewName="/Script/ThreadExample.AsyncTaskExample.AsyncTask_OnWorkDone") <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ThreadExample/ThreadExampleGameModeBase.h" #include "TaskGraphExample.generated.h" DECLARE_DELEGATE_OneParam(FTaskDelegate_OnWorkDone, int32 OutputResult) class FTask_FinishWork { FTaskDelegate_OnWorkDone TaskDelegate_OnWorkDone; AThreadExampleGameModeBase *GameModeRef; int32 Result; public: FTask_FinishWork(FTaskDelegate_OnWorkDone InTaskDelegate_OnWorkDone, AThreadExampleGameModeBase* InGameModeRef, int32 InResult) : TaskDelegate_OnWorkDone(InTaskDelegate_OnWorkDone), GameModeRef(InGameModeRef), Result(InResult) { } ~FTask_FinishWork() { } FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(FTask_FinishWork, STATGROUP_TaskGraphTasks); } static ENamedThreads::Type GetDesiredThread() { //run task in game thread for delegate correctly work return ENamedThreads::GameThread; } static ESubsequentsMode::Type GetSubsequentsMode() { return ESubsequentsMode::FireAndForget; } void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { check(IsInGameThread()); if (TaskDelegate_OnWorkDone.IsBound()) { TaskDelegate_OnWorkDone.Execute(Result); } } }; class FTask_CounterWork { FTaskDelegate_OnWorkDone TaskDelegate_OnWorkDone; AThreadExampleGameModeBase *GameModeRef; int32 *SimpleOutput; uint32 MainIdThread; public: FTask_CounterWork(FTaskDelegate_OnWorkDone InTaskDelegate_OnWorkDone, AThreadExampleGameModeBase* InGameModeRef, int32 *InSimpleOutput, uint32 InMainIdThread) : TaskDelegate_OnWorkDone(InTaskDelegate_OnWorkDone), GameModeRef(InGameModeRef), SimpleOutput(InSimpleOutput), MainIdThread(InMainIdThread) { UE_LOG(LogTemp, Error, TEXT("FTask_SimpleWork Cons"));//Use breakPoint for understand where created Task (use #pragma optimize ()) } ~FTask_CounterWork() { UE_LOG(LogTemp, Error, TEXT("FTask_SimpleWork Dest"));//Use breakPoint for understand where Task deleted } FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(FTask_CounterWork, STATGROUP_TaskGraphTasks); } static ENamedThreads::Type GetDesiredThread() { //backGround run task FAutoConsoleTaskPriority myTaskPriority( TEXT("TaskGraph.TaskPriorities.LoadFileToString"), TEXT("Task and thread priority for file loading."), ENamedThreads::BackgroundThreadPriority, ENamedThreads::NormalTaskPriority, ENamedThreads::NormalTaskPriority ); return myTaskPriority.Get(); } static ESubsequentsMode::Type GetSubsequentsMode() { return ESubsequentsMode::FireAndForget; } void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { int32 i = 0; while (i < 500) { FPlatformProcess::Sleep(0.002f); *SimpleOutput = (*SimpleOutput + i); i++; //GameModeRef->SimpleCounter we can take other object and change (not forget critical section) } //TaskDelegate_OnWorkDone.ExecuteIfBound(result);//Bad practice try use ue delegate in other thread (not inGameThread) TGraphTask<FTask_FinishWork>::CreateTask(NULL, CurrentThread).ConstructAndDispatchWhenReady(TaskDelegate_OnWorkDone, GameModeRef, *SimpleOutput); } }; UCLASS() class THREADEXAMPLE_API ATaskGraphExample : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATaskGraphExample(); FTaskDelegate_OnWorkDone TaskDelegate; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UFUNCTION(BlueprintCallable) void StartAsyncWork(); UPROPERTY(EditAnywhere, BlueprintReadWrite) int32 Counter = 0; uint32 MainIdThread = 0; TGraphTask<FTask_CounterWork> *myCurrentTask; UFUNCTION(BlueprintNativeEvent) void OnWorkDone_BP(int32 Result); UFUNCTION() void OnWorkDone(int32 Result); }; <file_sep>// Copyright Epic Games, Inc. All Rights Reserved. #include "ThreadExample.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, ThreadExample, "ThreadExample" ); <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "TaskGraphExample_Track.h" #include "Async/TaskGraphInterfaces.h" #include "HAL/ThreadManager.h" class FTask_FinishWork_Track//dont use copy another name of class task, i spend 3 hour to find this issie, kill me plz { FTaskDelegate_OnWorkDone TaskDelegate_OnWorkDone; int32 Result;//Use pointer * for do not take the value of the variable but the variable itself public: FTask_FinishWork_Track( FTaskDelegate_OnWorkDone InTaskDelegate_OnWorkDone, int32 InResult) : TaskDelegate_OnWorkDone(InTaskDelegate_OnWorkDone), Result(InResult) { } ~FTask_FinishWork_Track(){} FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(FTask_FinishWork_Track, STATGROUP_TaskGraphTasks); } static ENamedThreads::Type GetDesiredThread() { //run task in game thread for delegate correctly work return ENamedThreads::GameThread; } static ESubsequentsMode::Type GetSubsequentsMode() { return ESubsequentsMode::TrackSubsequents; } void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { if(TaskDelegate_OnWorkDone.IsBound()) { TaskDelegate_OnWorkDone.Execute(Result); } } }; class FTask_Counter_Track { int32 *Result; FCriticalSection *CounterMutex; public: FTask_Counter_Track(int32 *InResult, FCriticalSection *InCounterMutex) : Result(InResult), CounterMutex(InCounterMutex) { } ~FTask_Counter_Track(){} FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(FTask_Counter_Track, STATGROUP_TaskGraphTasks); } static ENamedThreads::Type GetDesiredThread() { //backGround run task FAutoConsoleTaskPriority TaskPriority( TEXT("TaskGraph.TaskPriorities.LoadFileToString"), TEXT("Task and thread priority for file loading."), ENamedThreads::BackgroundThreadPriority, ENamedThreads::NormalTaskPriority, ENamedThreads::NormalTaskPriority ); return TaskPriority.Get(); } static ESubsequentsMode::Type GetSubsequentsMode() { return ESubsequentsMode::TrackSubsequents; } static void AnyThreadWork() { //we can create function in class FTask for used } void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { for (int i = 0; i < 50; ++i) { FPlatformProcess::Sleep(0.02f); FScopeLock ScopedLock(CounterMutex); *Result = *Result + 1; } //AnyThreadWork(); } }; ATaskGraphExample_Track::ATaskGraphExample_Track() { PrimaryActorTick.bCanEverTick = true; } void ATaskGraphExample_Track::BeginPlay() { Super::BeginPlay(); } void ATaskGraphExample_Track::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ATaskGraphExample_Track::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); } void ATaskGraphExample_Track::StartAsyncTask() { FGraphEventArray Prerequisites;//list task for FinishWork task for (int i = 0; i < 3; ++i) { //counter task start work when create it FGraphEventRef CounterTask = TGraphTask<FTask_Counter_Track>::CreateTask(nullptr, ENamedThreads::GameThread).ConstructAndDispatchWhenReady(&Counter,&CounterMutex); Prerequisites.Add(CounterTask); } TaskDelegate_OnWorkDone.BindUFunction(this,"OnWorkDone"); TGraphTask<FTask_FinishWork_Track>::CreateTask(&Prerequisites, ENamedThreads::AnyThread).ConstructAndDispatchWhenReady(TaskDelegate_OnWorkDone, Counter); } void ATaskGraphExample_Track::OnWorkDone(int32 Result) { OnWorkDone_BP(Counter);//Take variable in ATaskGraphExapleTrack object //OnWorkDone_BP(Result); for if we use pointer when create task FinishWork } void ATaskGraphExample_Track::OnWorkDone_BP_Implementation(int32 Result) { //BP } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "DumbCuteCube.h" // Sets default values ADumbCuteCube::ADumbCuteCube() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void ADumbCuteCube::BeginPlay() { Super::BeginPlay(); } // Called every frame void ADumbCuteCube::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ADumbCuteCube::Init(FInfoNPC InitInfo) { InitBP(InitInfo); } void ADumbCuteCube::InitBP_Implementation(FInfoNPC InitInfo) { //BP } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "SimpleCollectable_Runnable.h" //need for build receiver #include "MessageEndpointBuilder.h" #include "ThreadExample/ThreadExampleGameModeBase.h" FSimpleCollectable_Runnable::FSimpleCollectable_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor) { GameMode_Ref = OwnerActor; //IMessageBus sender init SenderEndpoint = FMessageEndpoint::Builder("Sender_FSimpleCollectable_Runnable").Build(); } FSimpleCollectable_Runnable::~FSimpleCollectable_Runnable() { } uint32 FSimpleCollectable_Runnable::Run() { uint32 i = 0; while (!bIsStopCollectable) { FPlatformProcess::Sleep(2.0f); FInfoNPC newNPC; newNPC.Id = i; i++; int32 SizeNames = GameMode_Ref->FirstNames.Num(); if (SizeNames > 0) { int32 RandNameIndex = FMath::RandHelper(SizeNames-1); GameMode_Ref->FirstNameMutex.Lock(); newNPC.Name = GameMode_Ref->FirstNames[RandNameIndex]; GameMode_Ref->FirstNames.RemoveAt(RandNameIndex); GameMode_Ref->FirstNameMutex.Unlock(); } TArray<FString> AviableSecondNames = GameMode_Ref->GetSecondNames(); int32 SizeSecondNames = AviableSecondNames.Num(); if (SizeNames > 0) { int32 RandNameIndex = FMath::RandHelper(SizeSecondNames-1); //available place for critical section or change logic with TQUEUE newNPC.SecondName = AviableSecondNames[RandNameIndex]; GameMode_Ref->CurrentSecondName.Remove(newNPC.SecondName); } { FScopeLock NpcScopedLock(&GameMode_Ref->NPCInfoMutex); GameMode_Ref->NPCInfo.Add(newNPC); } //IMessageBus send if(SenderEndpoint.IsValid()) SenderEndpoint->Publish<FInfoNPC>(new FInfoNPC(newNPC)); //how spawn? check AThreadExampleGameModeBase::EventMessageNPC //myCuteCube = Cast<ADumbCuteCube>(myWorld->SpawnActor(GameMode_Ref->SpawnObjectThread); //we can't create AActor object UObject in Separate Thread only in InGameThread, not recommender and not safe } return 0; } void FSimpleCollectable_Runnable::Stop() { bIsStopCollectable = true; } void FSimpleCollectable_Runnable::Exit() { if(SenderEndpoint.IsValid()) SenderEndpoint.Reset(); GameMode_Ref = nullptr; } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "AsyncTaskExample.h" #include "HAL/ThreadManager.h" class FAsyncTask_Counter : public FNonAbandonableTask { friend class FAutoDeleteAsyncTask<FAsyncTask_Counter>; int32 ExampleData; FAsyncTask_OnWorkDone AsyncTask_OnWorkDone; int32* SimpleOutput; FAsyncTask_Counter(int32 InExampleData, FAsyncTask_OnWorkDone InAsyncTaskDelegate_OnWorkDone, int32 *InSimpleOutput) : ExampleData(InExampleData), AsyncTask_OnWorkDone(InAsyncTaskDelegate_OnWorkDone), SimpleOutput(InSimpleOutput) { } void DoWork() { uint64 i = 0; while (i < 500) { FPlatformProcess::Sleep(0.002f); *SimpleOutput = (*SimpleOutput + 1); i++; } //AsyncTask_OnWorkDone.Broadcast(*SimpleOutput); we cant use delegate in backGround } FORCEINLINE TStatId GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(FAsyncTask_Counter, STATGROUP_ThreadPoolAsyncTasks); } }; AAsyncTaskExample::AAsyncTaskExample() { PrimaryActorTick.bCanEverTick = true; } void AAsyncTaskExample::BeginPlay() { Super::BeginPlay(); AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [&]() { //UE_LOG(LogTemp, Warning, TEXT("AAsynTaskExample::BeginPlay start AsyncTask")); int32 i = 0; while (i < 50) { FPlatformProcess::Sleep(0.02f); i++; Counter2 = i; //UE_LOG(LogTemp, Warning, TEXT("AAsynTaskExample::BeginPlay Working counter - %d"), i); } }); } void AAsyncTaskExample::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AAsyncTaskExample::EndPlay(EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); } void AAsyncTaskExample::StartExample(bool bIsBackGroundTask) { if (bIsBackGroundTask) { // start an example job (new FAutoDeleteAsyncTask<FAsyncTask_Counter>(5, AsyncTask_OnWorkDone, &Counter))->StartBackgroundTask(); } else { // do an example job now, on this thread (new FAutoDeleteAsyncTask<FAsyncTask_Counter>(5, AsyncTask_OnWorkDone, &Counter))->StartSynchronousTask(); } }<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "MessageEndpoint.h" class AThreadExampleGameModeBase; /** * */ class THREADEXAMPLE_API FSimpleMutex_Runnable : public FRunnable { public: FSimpleMutex_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, bool bIsSecondMode); virtual ~FSimpleMutex_Runnable() override; //setting FColor ThreadColor; AThreadExampleGameModeBase *GameMode_Ref = nullptr; bool bIsGenerateSecondName = false; FThreadSafeBool bIsStopNameGenerator = false; virtual uint32 Run() override; virtual void Stop() override; virtual void Exit() override; //random generators int8 GetRandom(int8 min, int8 max); bool GetRandom(); //IMessageBus Setting TSharedPtr<FMessageEndpoint, ESPMode::ThreadSafe> SenderEndpoint; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "SimpleCounter_Runnable.h" #include <thread> #include "ThreadExample/ThreadExampleGameModeBase.h" FSimpleCounter_Runnable::FSimpleCounter_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, bool VariableMode) { GameMode_Ref = OwnerActor; ThreadColor = Color; bIsUseSafeVariable = VariableMode; UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Constructor ")); } FSimpleCounter_Runnable::~FSimpleCounter_Runnable() { UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Destructor ")); } bool FSimpleCounter_Runnable::Init() { UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Init ")); return true; } //#pragma optimize ("", off) uint32 FSimpleCounter_Runnable::Run() { //FScopedEvent if (GameMode_Ref->bIsUseFSScopedEvent) { { FScopedEvent SimpleCounterScopedEvent; GameMode_Ref->SendRef_ScopedEvent(SimpleCounterScopedEvent); //wait here - destructor start here } } //FEvent if (GameMode_Ref->SimpleCounterEvent) { GameMode_Ref->SimpleCounterEvent->Wait(10000); if (GameMode_Ref->SimpleCounterEvent)//check before use again after 10 second wait maybe event = null { GameMode_Ref->SimpleCounterEvent->Wait(10000); //we can use event again - one trigger = one unlock guard or ReturnSynchEventToPool } } if (bIsUseSafeVariable) { while (!bIsStopThreadSafe) { CounterSafe.Increment(); //GameMode_Ref->PrintMessage("Working");// UEngine::AddOnScreenDebugMessage there is a lock_guard - beware of deadlocks } } else { while (!bIsStopThread) { Counter++; //FPlatformProcess::Sleep(0.0200f);//for chance exit loop we can add sleep } } return 0; } //#pragma optimize ("", on) void FSimpleCounter_Runnable::Stop() { UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Stop ")); bIsStopThread = true; bIsStopThreadSafe = true; GameMode_Ref->SimpleCounterScopedEvent_Ref = nullptr; //GameMode_Ref->SimpleCounterEvent->IsManualReset() //GameMode_Ref->SimpleCounterScopedEvent_Ref. } void FSimpleCounter_Runnable::Exit() { GameMode_Ref->SimpleCounterScopedEvent_Ref = nullptr; GameMode_Ref = nullptr; UE_LOG(LogTemp, Warning, TEXT("FNameGeneratorLogic_Runnable::Exit ")); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "HAL/ThreadManager.h" class AThreadExampleGameModeBase; /** * */ class THREADEXAMPLE_API FSimpleCounter_Runnable : public FRunnable { public: FSimpleCounter_Runnable(FColor Color, AThreadExampleGameModeBase* OwnerActor, bool VariableMode); virtual ~FSimpleCounter_Runnable() override; //Safe FThreadSafeBool bIsStopThreadSafe = FThreadSafeBool(false); FThreadSafeCounter CounterSafe = FThreadSafeCounter(0); //Not Safe bool bIsStopThread = false; int Counter = 0; //setting bool bIsUseSafeVariable = false; FColor ThreadColor; AThreadExampleGameModeBase *GameMode_Ref = nullptr; virtual bool Init() override; virtual uint32 Run() override; virtual void Stop() override; virtual void Exit() override; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" class FRunnableThread; class ARunnableExample; /** * */ class THREADEXAMPLE_API FRunnableThreadExample : public FRunnable { public: FRunnableThreadExample(int32 CalcInput, ARunnableExample *OwnerActor); ~FRunnableThreadExample(); FThreadSafeBool bIsStopThread = false; virtual bool Init() override; virtual uint32 Run() override; private: int32 Calculation; int32 CurrentCalculation; ARunnableExample *CurrentThreadActor; }; <file_sep>/* BASIC THREAD * 1. Create threads * 2. join and detach methods * 3. Pass/Out value as argument in thread */ #include <iostream> #include <thread> #include <string> #include <chrono> #include <mutex> #include <ctime> #include <vector> #include <condition_variable> #include <random> #include <future> #include <atomic> using namespace std; //class SimpleThread class ThreadClass { public: void SimpleAbstractWork(string tmp) { for (int i = 0; i < 10; i++) { cout << "Id Thread - " << std::this_thread::get_id() << "\t" << tmp << " DoWork -" << i << std::endl; this_thread::sleep_for(std::chrono::milliseconds(1000)); } } void LoopSimpleAbstractWork(string tmp) { int i = 0; while (true) { cout << "Id Thread Loop - " << std::this_thread::get_id() << "\t" << tmp << " DoLoopWork -" << i << std::endl; this_thread::sleep_for(std::chrono::milliseconds(1000)); i++; } } int Sum(int a, int b) { int result = -1; this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Sum Start---- " << a << " + " << b << " ---------------" << endl; this_thread::sleep_for(std::chrono::milliseconds(3000)); result = a + b; this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Sum Done---- " << "Result = " << result << " ---------------" << endl; return result; } void Assignment(int& a) { this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Assignment Start---- " << a << " * 2 " << " ----" << endl; this_thread::sleep_for(std::chrono::milliseconds(3000)); a = a * 2; cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Assignment Done---- " << "Result = " << a << " ----" << endl; } void GreatJobWithoutParametr() { cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----GreatJobWithoutParametr Start---- " << endl; this_thread::sleep_for(std::chrono::milliseconds(4000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----GreatJobWithoutParametr End---- " << endl; } }; //SimpleThread void SimpleAbstractWork(string tmp) { for (int i = 0; i < 10; i++) { cout << "Id Thread - " << std::this_thread::get_id() << "\t" << tmp << " DoWork -" << i << std::endl; this_thread::sleep_for(std::chrono::milliseconds(1000)); } } void LoopSimpleAbstractWork(string tmp) { int i = 0; while (true) { cout << "Id Thread Loop - " << std::this_thread::get_id() << "\t" << tmp << " DoLoopWork -" << i << std::endl; this_thread::sleep_for(std::chrono::milliseconds(1000)); i++; } } int Sum(int a, int b) { int result = -1; this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Sum Start---- " << a << " + " << b << " ---------------" << endl; this_thread::sleep_for(std::chrono::milliseconds(3000)); result = a + b; this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Sum Done---- " << "Result = " << result << " ---------------" << endl; return result; } void Assignment(int& a) { this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Assignment Start---- " << a << " * 2 " << " ----" << endl; this_thread::sleep_for(std::chrono::milliseconds(3000)); a = a * 2; cout << "---- " << "Id Thread- " << std::this_thread::get_id() << "----Assignment Done---- " << "Result = " << a << " ----" << endl; } //Mutex mutex myMutex1; mutex myMutex2; recursive_mutex myRecMutex; int GetRandomInRange(const int min, const int max) { static std::default_random_engine gen( static_cast<unsigned>( std::chrono::system_clock::now().time_since_epoch().count() ) ); std::uniform_int_distribution<int> distribution(min, max); return distribution(gen); } void PrintVector(vector<int> VectorToPrint) { for (int i : VectorToPrint) { printf("%d ", i); } printf("\n"); } void RandomFillVectorBySize(vector<int> &VectorToFill, int sizeVector) { myMutex1.lock(); myMutex2.lock(); VectorToFill.clear(); for (int i = 0; i < sizeVector; i++) { int randNumber = GetRandomInRange(0,100); VectorToFill.push_back(randNumber); printf("%d ", randNumber); this_thread::sleep_for(std::chrono::milliseconds(100)); } printf("\n"); myMutex1.unlock(); myMutex2.unlock(); } void FillVectorBySize(vector<int>& VectorToFill, int Value, int sizeVector) { //unique_lock<mutex> myUnique_lock(myMutex1, defer_lock); //myUnique_lock.lock(); //myUnique_lock.unlock(); myMutex1.lock(); myMutex2.lock(); VectorToFill.clear(); for (int i = 0; i < sizeVector; i++) { VectorToFill.push_back(Value + i); printf("%d ", Value+i); this_thread::sleep_for(std::chrono::milliseconds(10)); } printf("\n"); myMutex1.unlock(); myMutex2.unlock(); this_thread::sleep_for(std::chrono::milliseconds(2000)); } void RecMethod(int r) { myRecMutex.lock(); printf("%d ", r); this_thread::sleep_for(std::chrono::milliseconds(100)); if (r<0) { printf("\n"); myRecMutex.unlock(); return; } r--; RecMethod(r); myRecMutex.unlock(); } //condition_variable condition_variable CV_FillVector; bool EndConsume = false; void Consume(int &value, vector<int> &Vector, int neededInt, mutex& locker) { unique_lock<mutex> lock(locker); bool bIsConsumeFill = false; while (!bIsConsumeFill) { CV_FillVector.wait(lock); if (value < 10) { unsigned int i = 0; while(i < Vector.size()) { if (Vector[i] == neededInt) { value++; Vector.erase(Vector.begin() + i); i--; printf("Hey i found what i want - %d ", neededInt); printf("\n"); if (value > 10) { bIsConsumeFill = true; } } i++; } Vector.clear(); } } EndConsume = true; } void Produce(vector<int>& VectorToFill, mutex &locker) { unique_lock<mutex> UL(locker, defer_lock); while (true) { this_thread::sleep_for(std::chrono::milliseconds(100)); int randNumber = GetRandomInRange(0, 10); UL.lock(); VectorToFill.push_back(randNumber); UL.unlock(); if (VectorToFill.size() > 50) { CV_FillVector.notify_one(); } } } //Future int GenerateValue(int value) { int i = 0; while (i < 2) { printf("work Second GenerateValue\n"); this_thread::sleep_for(std::chrono::milliseconds(1000)); i++; } return GetRandomInRange(0,100) + value; } void GetFutureValue(shared_future<int> myFuture) { printf("\n GetFutureValue Thread - %d", myFuture.get()); } void GenerateValueWithPromise(int value, promise<int>& promise) { int i = 0; while (i < 2) { printf("work Second GenerateValueWithPromise\n"); this_thread::sleep_for(std::chrono::milliseconds(1000)); i++; } promise.set_value(GetRandomInRange(0, 100) + value); this_thread::sleep_for(std::chrono::milliseconds(3000)); printf("\n END GenerateValueWithPromise "); } long NonAtomicValue = 0; atomic< long> AtomicValue = 0; void reWriteVariable(long& value) { int i = 0; while (i < 1000000) { value++; i++; } cout << "Thread finish"<<endl; } void reWriteVariableAtomic(atomic<long>& value) { int i = 0; while (i < 1000000) { value = value + 1; i++; } cout << "Atomic Thread finish" << endl; } int main() { //Atomic /* thread myThread1(reWriteVariable, std::ref(NonAtomicValue)); thread myThread2(reWriteVariable, std::ref(NonAtomicValue)); thread myThread3(reWriteVariable, std::ref(NonAtomicValue)); thread myThread4(reWriteVariable, std::ref(NonAtomicValue)); thread myThread5(reWriteVariable, std::ref(NonAtomicValue)); thread myThread6(reWriteVariable, std::ref(NonAtomicValue)); myThread1.detach(); myThread2.detach(); myThread3.detach(); myThread4.detach(); myThread5.detach(); myThread6.detach(); thread myThread1A(reWriteVariableAtomic, std::ref(AtomicValue)); thread myThread2A(reWriteVariableAtomic, std::ref(AtomicValue)); thread myThread3A(reWriteVariableAtomic, std::ref(AtomicValue)); thread myThread4A(reWriteVariableAtomic, std::ref(AtomicValue)); thread myThread5A(reWriteVariableAtomic, std::ref(AtomicValue)); thread myThread6A(reWriteVariableAtomic, std::ref(AtomicValue)); myThread1A.detach(); myThread2A.detach(); myThread3A.detach(); myThread4A.detach(); myThread5A.detach(); myThread6A.detach(); this_thread::sleep_for(std::chrono::milliseconds(2000)); cout<<"Value ATOMIC - "<< AtomicValue <<endl; cout << "Value NonAtomicValue - " << NonAtomicValue << endl; */ //PackageTask //packaged_task<int(int)> mytask(GenerateValue); //future<int> myfuture = mytask.get_future(); //thread myThread(std::ref(mytask), 10); //myfuture.get(); //myThread.join(); //Future /*promise<int> FuturePromise; shared_future<int> SharedFuture = FuturePromise.get_future().share(); thread PromiseThread(GenerateValueWithPromise, 5, std::ref(FuturePromise)); thread GetFutureValueThread(GetFutureValue, std::ref(SharedFuture)); int FutureValue1 = 0; shared_future<int> SimpleFuture = async(std::launch::async, GenerateValue, 5); int i = 0; while (i < 3) { printf("work Main \n"); this_thread::sleep_for(std::chrono::milliseconds(2000)); i++; } printf("FutureValue1 - %d \n", FutureValue1 = SimpleFuture.get()); GetFutureValueThread.join(); PromiseThread.join();*/ //Condition Variable /*vector<int> myVector; vector<thread> threads; int SuccessConsumeCout = 0; mutex m; mutex &lockerFormyVector = m; for (int i = 0; i < 2; i++) { threads.push_back(thread([&]() { Produce(myVector, lockerFormyVector); })); } for (thread& t : threads) { t.detach(); } thread ConsumeThread(Consume, std::ref(SuccessConsumeCout), std::ref(myVector), 5, std::ref(lockerFormyVector)); while (!EndConsume) { printf("%d ", SuccessConsumeCout); this_thread::sleep_for(std::chrono::milliseconds(100)); } printf("\n"); printf("End work %d ", SuccessConsumeCout); ConsumeThread.join();*/ //Mutex: //chrono::time_point<chrono::steady_clock> StartClock, EndClock; //chrono::duration<float> DurationClock; //StartClock = chrono::high_resolution_clock::now(); // //srand(static_cast<unsigned int>(time(0))); // //vector<int> myVector; // //thread FillVectorTrhead1([&]() //{ // FillVectorBySize(myVector, 55, 5); //}); // //thread FillVectorTrhead2([&]() //{ // RandomFillVectorBySize(myVector,5); //}); // ////for (int i = 0; i < 10; i++) ////{ //// this_thread::sleep_for(std::chrono::milliseconds(500)); ////} // //FillVectorTrhead2.join(); //FillVectorTrhead1.join(); // //PrintVector(myVector); // ////thread myThread(RecMethod, 3); ////myThread.join(); // //EndClock = chrono::high_resolution_clock::now(); //DurationClock = EndClock - StartClock; //printf("%f", DurationClock.count()); //system("pause"); //input output Thread with class: /* cout << "Core thread number - " << thread::hardware_concurrency() << endl; cout << "Sleep - 0,1 s"; this_thread::sleep_for(std::chrono::milliseconds(100)); cout << "Main thread ID - " << std::this_thread::get_id() << endl; ThreadClass myThreadClass; int Result; int SecondResult = 5; thread ThreadObjectWithLamda([&]() { Result = myThreadClass.Sum(5, 10); myThreadClass.Assignment(SecondResult); }); thread ThreadClassWithoutParametr([&]() { myThreadClass.GreatJobWithoutParametr(); }); thread ThreadClassWithoutParametrSecond(&ThreadClass::GreatJobWithoutParametr, myThreadClass); myThreadClass.SimpleAbstractWork("Main"); ThreadObjectWithLamda.join(); ThreadClassWithoutParametr.join(); ThreadClassWithoutParametrSecond.join(); cout << Result << endl; cout << SecondResult << endl; */ //Simple Thread: //thread JoinThread(SimpleAbstractWork, "JoinThread"); // ////ждем, пока поток завершит свое выполнение ////Любые выделенные ресурсы будут освобождены после выхода из потока. // //cout << JoinThread.joinable() << endl;//Вывод булевой переменной проверяет не ассоциорван ли обьект(поток) ни с каким потоком //JoinThread.join(); // //thread DetachThread(LoopSimpleAbstractWork, "DetachThread"); // ////Отделяет поток выполнения от объекта потока(будь это main поток, или другой) ////позволяет потоку выполняться независимо от дескриптора(токен) потока ////Любые выделенные ресурсы будут освобождены после выхода из потока. // //DetachThread.detach(); // //cout << DetachThread.joinable()<< endl; // ////Assignment, доступ к переменной из потока по ссылки //int GlobalVar = 8; //cout << GlobalVar << endl; // ////Шаблоны функций ref и cref являются вспомогательными функциями ////которые генерируют объект типа std::reference_wrapper ////используя вывод аргументов шаблона для определения аргумента шаблона результата // //thread AssignmentThread(Assignment,std::ref(GlobalVar)); //cout<< GlobalVar<<endl; // //int SumThreadResult; ////Sum доступ к выводу функции с помощью лямда-выражения //thread SumThread([&SumThreadResult]() //{ // SumThreadResult = Sum(4,6); //}); //SimpleAbstractWork("Main"); // //AssignmentThread.join(); //SumThread.join(); // ////LoopSimpleAbstractWork("Main"); return 0; }<file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "TaskGraphExample_Track.generated.h" DECLARE_DELEGATE_OneParam(FTaskDelegate_OnWorkDone, int32 OutputResult) UCLASS() class THREADEXAMPLE_API ATaskGraphExample_Track : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATaskGraphExample_Track(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UFUNCTION(BlueprintCallable) void StartAsyncTask(); UPROPERTY(EditAnywhere, BlueprintReadWrite) int32 Counter = 0; FCriticalSection CounterMutex; FTaskDelegate_OnWorkDone TaskDelegate_OnWorkDone; UFUNCTION() void OnWorkDone(int32 Result); UFUNCTION(BlueprintNativeEvent) void OnWorkDone_BP(int32 Result); }; <file_sep>// Copyright Epic Games, Inc. All Rights Reserved. #include "ThreadExampleGameModeBase.h" #include "DumbCuteCube.h" #include "MessageEndpointBuilder.h" #include "Misc/ScopeTryLock.h" void AThreadExampleGameModeBase::BusMessageHandler(const FBusStructMessage_NameGenerator& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context) { EventMessage(Message.bIsSecondName, Message.TextName); } void AThreadExampleGameModeBase::BusMessageHandlerNPCInfo(const FInfoNPC& Message, const TSharedRef<IMessageContext, ESPMode::ThreadSafe>& Context) { EventMessageNPC(Message); } void AThreadExampleGameModeBase::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (ShowDebugAllThread) { FThreadManager::Get().ForEachThread([&](uint32 ThreadId, FRunnableThread* Runnable) { FString myThreadType = "None"; switch (Runnable->GetThreadPriority()) { case TPri_Normal: myThreadType = "TPri_Normal"; break; case TPri_AboveNormal: myThreadType = "TPri_AboveNormal"; break; case TPri_BelowNormal: myThreadType = "TPri_BelowNormal"; break; case TPri_Highest: myThreadType = "TPri_Highest"; break; case TPri_Lowest: myThreadType = "TPri_Lowest"; break; case TPri_SlightlyBelowNormal: myThreadType = "TPri_SlightlyBelowNormal"; break; case TPri_TimeCritical: myThreadType = "TPri_TimeCritical"; break; case TPri_Num: myThreadType = "TPri_Num"; break; default: break; } if (Runnable->GetThreadName() == "Calc Thread") { UE_LOG(LogTemp, Warning, TEXT("AThreadExampleGameModeBase::Tick Calc Thread cathc - , Priority - %s"), *myThreadType); } UE_LOG(LogTemp, Error, TEXT("AThreadExampleGameModeBase::Tick Id - %d Name - %s , Priority - %s"), ThreadId, *Runnable->GetThreadName(), *myThreadType); }); } } void AThreadExampleGameModeBase::BeginPlay() { Super::BeginPlay(); ReceiveEndPoint_NameGenerator = FMessageEndpoint::Builder("Resiever_AThreadExampleGameModeBase") .Handling<FBusStructMessage_NameGenerator>(this, &AThreadExampleGameModeBase::BusMessageHandler); if(ReceiveEndPoint_NameGenerator.IsValid()) ReceiveEndPoint_NameGenerator->Subscribe<FBusStructMessage_NameGenerator>(); ReceiveEndpoint_NPCInfo = FMessageEndpoint::Builder("Resiever_NPC_AThreadExampleGameModeBase") .Handling<FInfoNPC>(this, &AThreadExampleGameModeBase::BusMessageHandlerNPCInfo); if(ReceiveEndpoint_NPCInfo.IsValid()) ReceiveEndpoint_NPCInfo->Subscribe<FInfoNPC>(); } void AThreadExampleGameModeBase::EndPlay(EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); StopSimpleCounterThread(); StopSimpleMutexThreads(); if(ReceiveEndPoint_NameGenerator.IsValid()) ReceiveEndPoint_NameGenerator.Reset(); if (ReceiveEndpoint_NPCInfo.IsValid()) ReceiveEndpoint_NPCInfo.Reset(); } void AThreadExampleGameModeBase::PrintMessage(FString message) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, message); } //----------------------------------SimpleCounter start-------------------------------- void AThreadExampleGameModeBase::StopSimpleCounterThread() { if (CurrentRunningGameModeThread_SimpleCounter) { if (MyRunnableClass_SimpleCounter) { //safe stop thread MyRunnableClass_SimpleCounter->bIsStopThreadSafe = true; //Not safe stop thread MyRunnableClass_SimpleCounter->bIsStopThread = true; bIsUseFSScopedEvent = false; // try to not create ScopedLock when exit app, if scopedEvent go after FEvent //if thread was paused, Resume Thread - for end loop thread CurrentRunningGameModeThread_SimpleCounter->Suspend(false); if (SimpleCounterEvent)//event close { SimpleCounterEvent->Trigger();//if thread of app wait, trigger for exit //SimpleCounterEvent set on wait 10 second if we close game after 10 second exe closed FPlatformProcess::ReturnSynchEventToPool(SimpleCounterEvent);//best practice for Event SimpleCounterEvent = nullptr;//for not wait second(FEvent) wait() if we want exit app } if (SimpleCounterScopedEvent_Ref) { SimpleCounterScopedEvent_Ref->Trigger();//if thread of app wait, trigger for exit //FPlatformProcess::ReturnSynchEventToPool(SimpleCounterScopedEvent_Ref->Get()); SimpleCounterScopedEvent_Ref = nullptr; } //End logic runnable thread CurrentRunningGameModeThread_SimpleCounter->WaitForCompletion(); if (MyRunnableClass_SimpleCounter) { //delete MyRunnableClass_SimpleCounter; // not need call, destructor GC do it MyRunnableClass_SimpleCounter = nullptr; } if (CurrentRunningGameModeThread_SimpleCounter) { //delete CurrentRunningGameModeThread_SimpleCounter; // not need call, destructor GC do it CurrentRunningGameModeThread_SimpleCounter = nullptr; } } } } void AThreadExampleGameModeBase::KillSimpleCounterThread(bool bIsShouldWait) { if (CurrentRunningGameModeThread_SimpleCounter) { //if (MyRunnableClass_SimpleCounter) not needed CurrentRunningGameModeThread_SimpleCounter->Suspend(false); CurrentRunningGameModeThread_SimpleCounter->Kill(bIsShouldWait); CurrentRunningGameModeThread_SimpleCounter = nullptr; MyRunnableClass_SimpleCounter = nullptr; } } bool AThreadExampleGameModeBase::SwitchRunStateSimpleCounterThread(bool bIsPause) { if (CurrentRunningGameModeThread_SimpleCounter) { CurrentRunningGameModeThread_SimpleCounter->Suspend(bIsPause); } return bIsPause; } void AThreadExampleGameModeBase::CreateSimpleCounterThread() { if (bIsUseFEvent) { SimpleCounterEvent = FPlatformProcess::GetSynchEventFromPool(); } if (!CurrentRunningGameModeThread_SimpleCounter) { if (!MyRunnableClass_SimpleCounter) { MyRunnableClass_SimpleCounter = new FSimpleCounter_Runnable(ColorThread, this, bIsUseSafeVariable); } CurrentRunningGameModeThread_SimpleCounter = FRunnableThread::Create(MyRunnableClass_SimpleCounter, TEXT("SimpleCounter Thread1"), 0, EThreadPriority::TPri_Normal); } } void AThreadExampleGameModeBase::StartSimpleCounterThreadWithEvent() { if (SimpleCounterEvent) { SimpleCounterEvent->Trigger(); } } void AThreadExampleGameModeBase::StartSimpleCounterThreadWithScopedEvent() { if (SimpleCounterScopedEvent_Ref) { SimpleCounterScopedEvent_Ref->Trigger(); SimpleCounterScopedEvent_Ref = nullptr; } } int64 AThreadExampleGameModeBase::GetCounterSimpleCounterThread() { int64 result = -1; if (MyRunnableClass_SimpleCounter) { if (MyRunnableClass_SimpleCounter->bIsUseSafeVariable) { result = MyRunnableClass_SimpleCounter->CounterSafe.GetValue(); //printMessage(FString::FromInt(MyRunnableClass_NameGenerator->CounterSafe.GetValue())); } else { result = MyRunnableClass_SimpleCounter->Counter; //printMessage(FString::FromInt(MyRunnableClass_NameGenerator->Counter)); } } return result; } void AThreadExampleGameModeBase::SendRef_ScopedEvent(FScopedEvent &ScopedEvent_Ref) { SimpleCounterScopedEvent_Ref = &ScopedEvent_Ref; } //SimpleCounter end //----------------------------------SimpleAtomic start-------------------------------- void AThreadExampleGameModeBase::CreateSimpleAtomicThread() { for (int i = 0; i < NumberOfThreadToCreate; ++i) { bool bFlag = false; if (i%2) bFlag = true; class FSimpleAtomic_Runnable *MyRunnableClass_SimpleAtomic = new FSimpleAtomic_Runnable(ColorThread, this, IterationForRunnableCircle, bFlag, bIsUseAtomic); CurrentRunningGameModeThread_SimpleAtomic.Add(FRunnableThread::Create(MyRunnableClass_SimpleAtomic, TEXT("SimpleRandomize Thread"), 0, EThreadPriority::TPri_Normal)); } } void AThreadExampleGameModeBase::GetCounterSimpleAtomic(int32 &Atomic1, int32 &NotAtomic1, int32 &Atomic2, int32 &NotAtomic2) { if (bIsUseAtomic) { NotAtomic1 = FPlatformAtomics::AtomicRead(&NotAtomicCounter1); NotAtomic2 = FPlatformAtomics::AtomicRead(&NotAtomicCounter2); if(AtomicCounter2.is_lock_free()) { Atomic2 = AtomicCounter2; } if(AtomicCounter1.is_lock_free()) { Atomic1 = AtomicCounter1; } } else { NotAtomic1 = NotAtomicCounter1; NotAtomic2 = NotAtomicCounter2; } } void AThreadExampleGameModeBase::ResetCounterSimpleAtomic() { AtomicCounter1 = 0; AtomicCounter2 = 0; NotAtomicCounter1 = 0; NotAtomicCounter2 = 0; } //SimpleAtomic End //----------------------------------SimpleMutex start-------------------------------- void AThreadExampleGameModeBase::StopSimpleMutexThreads() { if (CurrentRunningGameModeThread_SimpleMutex.Num() > 0) { for (auto RunnableThread : CurrentRunningGameModeThread_SimpleMutex) { if (RunnableThread) { RunnableThread->Kill(true); } } CurrentRunningGameModeThread_SimpleMutex.Empty(); } if (CurrentRunningGameModeThread_SimpleCollectable) { CurrentRunningGameModeThread_SimpleCollectable->Kill(true); CurrentRunningGameModeThread_SimpleCollectable = nullptr; } } void AThreadExampleGameModeBase::CreateSimpleMutexThread() { for (int i = 0; i < 4; ++i) { bool bFlag = false; if (i%2) bFlag = true; class FSimpleMutex_Runnable *MyRunnableClass_SimpleMutex = new FSimpleMutex_Runnable(ColorThread, this, bFlag); CurrentRunningGameModeThread_SimpleMutex.Add(FRunnableThread::Create(MyRunnableClass_SimpleMutex, TEXT("SimpleMutex Thread"), 0, EThreadPriority::TPri_Normal)); } } void AThreadExampleGameModeBase::CreateCollectableThread() { class FSimpleCollectable_Runnable *MyRunnableClass_SimpleCollectable = new FSimpleCollectable_Runnable(ColorThread, this); CurrentRunningGameModeThread_SimpleCollectable = FRunnableThread::Create(MyRunnableClass_SimpleCollectable, TEXT("SimpleMutex Thread"), 0, EThreadPriority::TPri_Normal); } TArray<FInfoNPC> AThreadExampleGameModeBase::GetNPCInfo() { TArray<FInfoNPC> Result; return Result; } TArray<FString> AThreadExampleGameModeBase::GetSecondNames() { TArray<FString> Result; FString OneRead; while (SecondNames.Dequeue(OneRead)) { Result.Add(OneRead); } CurrentSecondName.Append(Result); return CurrentSecondName; } TArray<FString> AThreadExampleGameModeBase::GetFirstNames() { { FScopeLock myScopeLock(&FirstNameMutex); return FirstNames; } } void AThreadExampleGameModeBase::Clear() { FirstNames.Empty(); SecondNames.Empty(); CurrentSecondName.Empty(); } void AThreadExampleGameModeBase::EventMessage(bool bIsSecond, FString StringData) { OnUpdateByNameGeneratorThreads.Broadcast(bIsSecond, StringData); } void AThreadExampleGameModeBase::EventMessageNPC(FInfoNPC NPCData) { OnUpdateByThreadNPC.Broadcast(NPCData); UWorld *myWorld = GetWorld(); if (myWorld) { FVector SpawnLoc = FVector(SpawnCuteCubeLoc.X + (cubeCout * SpawnCuteCubeLoc_Step.X), SpawnCuteCubeLoc.Y + (cubeCout * SpawnCuteCubeLoc_Step.Y), SpawnCuteCubeLoc.Z + (cubeCout * SpawnCuteCubeLoc_Step.Z)); FRotator SpawnRot; ADumbCuteCube* myCuteCube; myCuteCube = Cast<ADumbCuteCube>(myWorld->SpawnActor(SpawnObjectThread, &SpawnLoc, &SpawnRot, FActorSpawnParameters())); if (myCuteCube) { myCuteCube->Init(NPCData); cubeCout++; } } } //SimpleMutex End //ParallelFor void AThreadExampleGameModeBase::StartParallelFor1() { FCriticalSection ParallelMutex1; ParallelFor( 10, [&](int32 index)// lambda, index - index of number parallel for { FPlatformProcess::Sleep(0.001f); int32 cout = 0; for (int i = 0; i < 50; ++i) { cout++; } ParallelMutex1.Lock(); ParallelCout1 += cout; ParallelMutex1.Unlock(); } ,EParallelForFlags::None); } void AThreadExampleGameModeBase::StartParallelFor2() { const auto Function = [&](int32 index) { FPlatformProcess::Sleep(0.1f); int32 cout = 0; for (int i = 0; i < 50; ++i) { cout--; } ParallelCout2 += cout; }; ParallelForTemplate(10,Function,EParallelForFlags::BackgroundPriority); } void AThreadExampleGameModeBase::StartParallelFor3() { ParallelForWithPreWork(10,[&](int32 index) { for (int i = 0; i < 50; ++i) { //FPlatformProcess::Sleep(0.02f); ParallelCout3++; UE_LOG(LogTemp, Error, TEXT("i START ParallelForWithPreWork")); } },[]() { UE_LOG(LogTemp, Error, TEXT("i START parallel help work")); //FPlatformProcess::Sleep(5.0f); UE_LOG(LogTemp, Error, TEXT("i FINISH parallel help work")); },EParallelForFlags::BackgroundPriority); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "RunnableExample.h" #include "Kismet/GameplayStatics.h" ARunnableExample::ARunnableExample() { PrimaryActorTick.bCanEverTick = true; } void ARunnableExample::InitCalculation(int32 Calc) { CalcThread = new FRunnableThreadExample(Calc, this); CurrentRunningThread = FRunnableThread::Create(CalcThread, TEXT("ActorCalcl Thread"), 0, EThreadPriority::TPri_Highest); FTimerDelegate Dead_TimerDelegate; Dead_TimerDelegate.BindLambda([&]() { this->Destroy(); }); FTimerHandle myHandle; GetWorld()->GetTimerManager().SetTimer(myHandle, Dead_TimerDelegate, DiedTimer, false); } void ARunnableExample::BeginPlay() { Super::BeginPlay(); } void ARunnableExample::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ARunnableExample::EndPlay(EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); if (CurrentRunningThread && CalcThread) { CalcThread->bIsStopThread = true;//Commit safe exit thread when actor destroy to check thread still running CurrentRunningThread->WaitForCompletion(); } } int32 ARunnableExample::GetCalcValue() { return CurrentCalc.GetValue(); } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "RunnableThreadExample.h" #include "RunnableExample.h" FRunnableThreadExample::FRunnableThreadExample(int32 CalcInput, ARunnableExample* OwnerActor) { Calculation = CalcInput; CurrentThreadActor = OwnerActor; } FRunnableThreadExample::~FRunnableThreadExample() { } bool FRunnableThreadExample::Init() { return true; } uint32 FRunnableThreadExample::Run() { int32 CalcCount = 0; while (!bIsStopThread) { if (CalcCount < Calculation) { CurrentCalculation += FMath::RandRange(20, 400); CurrentCalculation *= FMath::RandRange(2,500); CurrentCalculation -= FMath::RandRange(10, 500); CurrentThreadActor->CurrentCalc.Set(CurrentCalculation); //UE_LOG(LogTemp, Error, TEXT("FRunnableThreadExample::Run ownerId - %s DATA - %d "), *CurrentThreadActor->GetName(), CurrentCalculation); FPlatformProcess::Sleep(0.002f); CalcCount++; } else { bIsStopThread = true; } } return 1; }
7ecf282b0f8f64867bf6a46113b4764f8b26efb4
[ "C++", "INI" ]
25
C++
jetset-3566/Thread
89d27e01b32970a7d99840141efd6124ece987c3
d9b6ba3de1d8cef7ed53c85fcfd1303e540edcf3
refs/heads/master
<file_sep>/*Problem 5. Boolean Variable Declare a Boolean variable called `isFemale` and assign an appropriate value corresponding to your gender. Print it on the console. */ using System; class BooleanVariable { static void Main() { bool isFemale = true; Console.WriteLine("My gender is female: {0}", isFemale); } } <file_sep>/* Problem 11. Bitwise: Extract Bit #3 Using bitwise operators, write an expression for finding the value of the bit `#3` of a given unsigned integer. The bits are counted from right to left, starting from bit `#0`. The result of the expression should be either `1` or `0`. */ using System; class ExtractBit3 { static void Main() { Console.Write("Enter a number: "); uint number = uint.Parse(Console.ReadLine()); int mask = 1 << 3; uint maskAndNumber = (uint)mask & number; uint bit = maskAndNumber >> 3; Console.WriteLine("Your number in binary: {0}", Convert.ToString(number, 2)); Console.WriteLine("The third bit is = " + bit); } } <file_sep>/*Problem 4. Unicode Character Declare a character variable and assign it with the symbol that has Unicode code `42` (decimal) using the `\u00XX` syntax, and then print it. */ using System; class UnicodeCharacter { static void Main(string[] args) { char symbol = '\u002A'; Console.WriteLine("The result is : {0}", symbol); } } <file_sep>/* Problem 13. Binary to Decimal Number Using loops write a program that converts a binary integer number to its decimal form. The input is entered as string. The output should be a variable of type long. */ using System; class BinaryToDecimalNumber { static void Main() { Console.Write("Enter a binary number: "); string input = Console.ReadLine(); int power = 0; long numberInDec = 0; for (int i = input.Length - 1; i >= 0; i--) { numberInDec += ((long)input[i] - 48) * (long)Math.Pow(2, power++); } Console.WriteLine("Converted to decimal: " + numberInDec); } } <file_sep>/* Problem 16. Decimal to Hexadecimal Number Using loops write a program that converts an integer number to its hexadecimal representation. The input is entered as long. The output should be a variable of type string. *Do not use the built-in .NET functionality. */ using System; class DecimalToHexadecimalNumber { static void Main() { Console.Write("Write a decimal number: "); long input = long.Parse(Console.ReadLine()); long number = 0; string numberHex = ""; while (input > 0) { number = input % 16; input = input / 16; if (number >= 16 || number <= 9) { numberHex = number + numberHex; } else if (number == 10) { numberHex = "A" + numberHex; } else if (number == 11) { numberHex = "B" + numberHex; } else if (number == 12) { numberHex = "C" + numberHex; } else if (number == 13) { numberHex = "D" + numberHex; } else if (number == 14) { numberHex = "E" + numberHex; } else if (number == 15) { numberHex = "F" + numberHex; } } Console.WriteLine("Converted to hexadecimal: " + numberHex); } } <file_sep>/* Problem 4. Print a Deck of 52 Cards Write a program that generates and prints all possible cards from a [standard deck of 52 cards](http://en.wikipedia.org/wiki/Standard_52-card_deck) (without the jokers). The cards should be printed using the classical notation (like 5 of spades, A of hearts, 9 of clubs; and K of diamonds). The card faces should start from 2 to A. Print each card face in its four possible suits: clubs, diamonds, hearts and spades. Use 2 nested for-loops and a switch-case statement. */ using System; class PrintADeckOfCards { static void Main() { for (int face = 2; face <= 14; face++) { Console.WriteLine(); for (int suit = 1; suit <= 4; suit++) { switch (face) { case 2: Console.Write(" 2"); break; case 3: Console.Write(" 3"); break; case 4: Console.Write(" 4"); break; case 5: Console.Write(" 5"); break; case 6: Console.Write(" 6"); break; case 7: Console.Write(" 7"); break; case 8: Console.Write(" 8"); break; case 9: Console.Write(" 9"); break; case 10: Console.Write("10"); break; case 11: Console.Write(" J"); break; case 12: Console.Write(" Q"); break; case 13: Console.Write(" K"); break; case 14: Console.Write(" A"); break; } switch (suit) { case 1: Console.Write(" of spades "); break; case 2: Console.Write(" of hearts "); break; case 3: Console.Write(" of diamonds "); break; case 4: Console.Write(" of clubs "); break; } } } Console.WriteLine(); } } <file_sep>/* Problem 4. Multiplication Sign * Write a program that shows the sign (+, - or 0) of the product of three real numbers, without calculating it. */ using System; class MultiplicationSign { static void Main() { Console.Write("Enter first number: "); double first = double.Parse(Console.ReadLine()); Console.Write("Enter second number: "); double second = double.Parse(Console.ReadLine()); Console.Write("Enter third number: "); double third = double.Parse(Console.ReadLine()); if (first == 0 || second == 0 || third == 0) { Console.WriteLine("The sign is: 0"); } else if (first < 0 && second > 0 && third > 0 || first > 0 && second < 0 && third > 0 || first > 0 && second > 0 && third < 0 || first < 0 && second < 0 && third < 0) { Console.WriteLine("The sign is: -"); } else { Console.WriteLine("The sign is: +"); } } } <file_sep># CSharp1-Homeworks <file_sep>/*Problem 10. Point Inside a Circle & Outside of a Rectangle Write an expression that checks for given point (x, y) if it is within the circle `K({1, 1}, 1.5)` and out of the rectangle `R(top=1, left=-1, width=6, height=2)`. */ using System; class PointInsideOutside { static void Main() { Console.Write("Enter x: "); double x = double.Parse(Console.ReadLine()); Console.Write("Enter y: "); double y = double.Parse(Console.ReadLine()); double radius = 1.5; bool insideCircle = (Math.Pow(x - 1, 2) + Math.Pow(y - 1, 2) < (radius * radius)); bool outsideRect = ((x < -1) || (x > 5) || (y < -1) || (y > 1)); bool inAndOut = insideCircle && outsideRect; Console.WriteLine(); Console.WriteLine("The point is inside the circle and outside the rectangle --> " + inAndOut); } }<file_sep>/*Problem 10. Employee Data A marketing company wants to keep record of its employees. Each record would have the following characteristics: First name Last name Age (0...100) Gender (m or f) Personal ID number (e.g. 8306112507) Unique employee number (27560000…27569999) Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console. */ using System; class EmployeeData { static void Main() { Console.WriteLine("Please enter"); Console.Write("First name: "); string firstName = Console.ReadLine(); Console.Write("Last name: "); string lastName = Console.ReadLine(); Console.Write("Age: "); int age = int.Parse(Console.ReadLine()); Console.Write("Gender M/F: "); char gender = char.Parse(Console.ReadLine()); Console.Write("Employee's number: "); int uniqueEmployeeNumber = int.Parse(Console.ReadLine()); Console.Write("Personal ID: "); long personalID = long.Parse(Console.ReadLine()); Console.WriteLine(@" Employee's data: Name: {0} {1} Age: {2} Gender: {3} Number: {4} Personal ID: {5} ", firstName, lastName, age, gender, uniqueEmployeeNumber, personalID); } } <file_sep>/* Problem 9. Sum of n Numbers Write a program that enters a number `n` and after that enters more `n` numbers and calculates and prints their `sum`. */ using System; class SumOfNumbers { static void Main() { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); decimal sum = 0; Console.WriteLine(); for (int i = 1; i <= number; i++) { Console.Write("Enter number {0}: ", i); decimal a = decimal.Parse(Console.ReadLine()); sum += a; } Console.WriteLine("The sum or your {0} numbers is {1:F2}: ", number, sum); } } <file_sep>/* Problem 8. Prime Number Check Write an expression that checks if given positive integer number n (n = 100) is prime (i.e. it is divisible without remainder only to itself and 1). */ using System; class PrimeNumberCheck { static void Main() { Console.Write("Enter number: "); uint number = uint.Parse(Console.ReadLine()); uint sqrtNumber = (uint)Math.Sqrt(number); bool prime = true; for (int i = 2; i <= sqrtNumber; i++) { if (number % i == 0) { prime = false; break; //if prime = false --> stop the loop go to next line 25 } } Console.WriteLine(); Console.WriteLine("The number is prime! --> " + prime); } }<file_sep>/*Problem 15.* Age after 10 Years Write a program to read your birthday from the console and print how old you are now and how old you will be after 10 years. */ using System; class AgeAfter10Years { static void Main() { Console.WriteLine("Enter your birthdate in format dd.mm.yyyy"); DateTime dateBirth = DateTime.Parse(Console.ReadLine()); DateTime dateToday = DateTime.Now; int age = dateToday.Year - dateBirth.Year; if (dateToday.Month < dateBirth.Month || (dateToday.Month == dateBirth.Month && dateToday.Day < dateBirth.Day)) { age--; } Console.WriteLine("You are {0} years old. In 10 years you'll be {1}.", age, age + 10); } }<file_sep>/* Problem 14.* Print the ASCII Table Find online more information about ASCII (American Standard Code for Information Interchange) and write a program that prints the entire ASCII table of characters on the console (characters from 0 to 255). */ using System; using System.Text; class PrintASCIITable { static void Main() { for (int i = 0; i <= 255; i++) { Console.OutputEncoding = Encoding.UTF8; char c = Convert.ToChar(i); Console.WriteLine("{0,4} --> {1}", i,c); } } } <file_sep>/*Problem 6. Strings and Objects Declare two string variables and assign them with `Hello` and `World`. Declare an object variable and assign it with the concatenation of the first two variables (mind adding an interval between). Declare a third string variable and initialize it with the value of the object variable (you should perform type casting). */ using System; class StringsAndObjects { static void Main() { string first = "Hello"; string second = "World"; object both = first + " " + second; string final = Convert.ToString(both); Console.WriteLine(final); } } <file_sep>/*Problem 9. Exchange Variable Values Declare two integer variables `a` and `b` and assign them with `5` and `10` and after that exchange their values by using some programming logic. Print the variable values before and after the exchange. */ using System; class ExchangeValues { static void Main() { int a = 5; int b = 10; Console.WriteLine("Before the exchange a={0}, b={1};", a,b); int temp = b; b = a; a = temp; Console.WriteLine("After the exchange a={0}, b={1};", a,b); } } <file_sep>/* Problem 17.* Calculate GCD Write a program that calculates the greatest common divisor (GCD) of given two integers `a` and `b`. Use the Euclidean algorithm (find it in Internet). */ using System; class CalculateGCD { static void Main() { Console.Write("Enter A: "); int numberA = Math.Abs(int.Parse(Console.ReadLine())); Console.Write("Enter B: "); int numberB = Math.Abs(int.Parse(Console.ReadLine())); int remainder=0; if (numberA < numberB) { int temp = numberB; numberB = numberA; numberA = temp; } while (numberB != 0) { remainder = numberA % numberB; numberA = numberB; numberB = remainder; } Console.WriteLine("GCD = " + numberA); } } <file_sep>/* Problem 14. Decimal to Binary Number Using loops write a program that converts an integer number to its binary representation. The input is entered as long. The output should be a variable of type string. Do not use the built-in .NET functionality. */ using System; class DecimalToBinaryNumber { static void Main() { Console.Write("Write a decimal number: "); long input = long.Parse(Console.ReadLine()); long number = 0; string numberBin = ""; while (input > 0) { number = input % 2; input = input / 2; numberBin = number + numberBin; } Console.WriteLine("Converted to binary: " + numberBin); } } <file_sep>/* Problem 1. Numbers from 1 to N Write a program that enters from the console a positive integer `n` and prints all the numbers from `1` to `n`, on a single line, separated by a space. */ using System; class NumbersFrom1ToN { static void Main() { Console.Write("Enter a positive integer number: "); uint input = uint.Parse(Console.ReadLine()); for (int i = 1; i <= input; i++) { Console.Write("{0} ", i); } Console.WriteLine(); } } <file_sep>/* Problem 2. Gravitation on the Moon The gravitational field of the Moon is approximately `17%` of that on the Earth. Write a program that calculates the weight of a man on the moon by a given weight on the Earth. */ using System; class Gravitation { static void Main() { Console.Write("Enter your weight: "); double weight = double.Parse(Console.ReadLine()); double weightMoon = weight * 0.17; Console.WriteLine("Your weight on the moon is: {0:F2}kg", weightMoon); } } <file_sep>/* Problem 2. Float or Double? Which of the following values can be assigned to a variable of type `float` and which to a variable of type `double`: `34.567839023, 12.345, 8923.1234857, 3456.091`? Write a program to assign the numbers in variables and print them to ensure no precision is lost. */ using System; class FloatOrDouble { static void Main() { double a = 34.567839023; float b = 12.345f; double c = 8923.1234857; float d = 3456.091f; Console.WriteLine("{0, 14} is type {1}", a, a.GetType().Name); Console.WriteLine("{0, 14} is type {1}", b, b.GetType().Name); Console.WriteLine("{0, 14} is type {1}", c, c.GetType().Name); Console.WriteLine("{0, 14} is type {1}", d, d.GetType().Name); } }<file_sep>/* Problem 7. Sum of 5 Numbers Write a program that enters 5 numbers (given in a single line, separated by a space), calculates and prints their sum. */ using System; class SumOf5Numbers { static void Main() { Console.Write("Enter 5 numbers separated by a space: "); string inputString = Console.ReadLine(); int number = int.Parse(inputString.Replace(" ", String.Empty)); int num1 = number / 10000; int num2 = (number % 10000) / 1000; int num3 = (number % 1000) / 100; int num4 = (number % 100) / 10; int num5 = number % 10; Console.WriteLine("The sum is = " + (num1 + num2 + num3 + num4 + num5)); } } <file_sep>/* Problem 14. Modify a Bit at Given Position We are given an integer number `n`, a bit value `v` (v=0 or 1) and a position `p`. Write a sequence of operators (a few lines of C# code) that modifies `n` to hold the value `v` at the position `p` from the binary representation of `n` while preserving all other bits in `n`. */ using System; class ExtractBit3 { static void Main() { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); Console.WriteLine("Your number in binary: " + Convert.ToString(number, 2).PadLeft(32, '0')); Console.Write("Enter position: "); int position = int.Parse(Console.ReadLine()); Console.Write("Enter value 0/1: "); int value = int.Parse(Console.ReadLine()); int newNumber=0; if (value == 0) { int mask = ~(1 << position); newNumber = number & mask; } else if (value == 1) { int mask = 1 << position; newNumber = number | mask; } else Console.WriteLine("The value isn't valid!"); Console.WriteLine(); Console.WriteLine("Your new number is: " + newNumber + "\nConverted in binary: " + Convert.ToString(newNumber, 2).PadLeft(32, '0')); } } <file_sep>/* Problem 8. Catalan Numbers In combinatorics, the Catalan numbers are calculated by the following formula: ![catalan-formula](https://cloud.githubusercontent.com/assets/3619393/5626137/d7ec8bc2-958f-11e4-9787-f6c386847c81.png) Write a program to calculate the `nth` Catalan number by given `n` (1 < n < 100). */ using System; using System.Numerics; class CatalanNumbers { static void Main() { Console.WriteLine("Calculate Catalan numbers 1 < n < 100"); Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); BigInteger factorial2N = 1; BigInteger factorialN = 1; BigInteger factorialNPlus1 = 1; if (n > 1 && n < 100) { for (int i = 1; i <= n; i++) { factorialN *= i; } for (int i = 1; i <= 2 * n; i++) { factorial2N *= i; } for (int i = 1; i <= n + 1; i++) { factorialNPlus1 *= i; } BigInteger result = factorial2N / (factorialNPlus1 * factorialN); Console.WriteLine("The result is: " + result); } else if (n == 0) { Console.WriteLine("The result is: 1"); } else { Console.WriteLine("Invalid input"); } } } <file_sep>/* Problem 10. Odd and Even Product You are given `n` integers (given in a single line, separated by a space). Write a program that checks whether the product of the odd elements is equal to the product of the even elements. Elements are counted from `1` to `n`, so the first element is odd, the second is even, etc. */ using System; class OddAndEvenProduct { static void Main() { Console.Write("Enter numbers separated by a space: "); string input = Console.ReadLine(); string[] myArray = input.Split(' '); int oddProduct = 1; int evenProduct = 1; for (int i = 0; i < myArray.Length; i++) { int currentNumber = int.Parse(myArray[i]); if (i % 2 == 0) { oddProduct *= currentNumber; } else if (i % 2 != 0) { evenProduct *= currentNumber; } } bool equal = oddProduct == evenProduct; if (equal) { Console.WriteLine("Yes\nProduct = {0}", oddProduct); } else { Console.WriteLine("No\nOdd Product = {0}\nEven Product = {1}", oddProduct, evenProduct); } } } <file_sep>/* Problem 5. Formatting Numbers Write a program that reads 3 numbers: integer `a` (0 <= a <= 500) floating-point `b` floating-point `c` The program then prints them in 4 virtual columns on the console. Each column should have a width of 10 characters. The number `a` should be printed in hexadecimal, left aligned Then the number `a` should be printed in binary form, padded with zeroes The number `b` should be printed with 2 digits after the decimal point, right aligned The number c should be printed with 3 digits after the decimal point, left aligned. */ using System; class FormattingNumbers { static void Main() { Console.Write("Enter integer number A<500: "); int numberA = int.Parse(Console.ReadLine()); Console.Write("Enter floating-point number B: "); double numberB = double.Parse(Console.ReadLine()); Console.Write("Enter floating-point number C: "); double numberC = double.Parse(Console.ReadLine()); Console.WriteLine("{0,-10:X}|{1,-10}|{2,10:F2}|{3,-10:F3}", numberA, Convert.ToString(numberA, 2).PadLeft(10, '0'), numberB, numberC); } } <file_sep>/* Problem 13. Check a Bit at Given Position Write a Boolean expression that returns if the bit at position `p` (counting from `0`, starting from the right) in given integer number `n`, has value of 1. */ using System; class ExtractBit3 { static void Main() { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); Console.Write("Enter position: "); int position = int.Parse(Console.ReadLine()); int mask = 1 << position; int maskAndNumber = mask & number; int bit = maskAndNumber >> position; bool isBit = (bit == 1); Console.WriteLine("Your number in binary: {0}", Convert.ToString(number, 2)); Console.WriteLine("The value of bit {0} is 1 --> {1}", position, isBit); } }<file_sep>/* Problem 5. Calculate 1 + 1!/X + 2!/X2 + … + N!/XN Write a program that, for a given two integer numbers `n` and `x`, calculates the sum `S = 1 + 1!/x + 2!/x2 + … + n!/xn`. Use only one loop. Print the result with `5` digits after the decimal point. */ using System; class CalculateN { static void Main() { Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter x: "); int x = int.Parse(Console.ReadLine()); int factorial = 1; decimal sum = 1m; for (int i = 1; i <= n; i++) { factorial *= i; sum += (decimal)factorial / (decimal)Math.Pow(x,i); } Console.WriteLine("{0:F5}", sum); } } <file_sep>/* Problem 1. Exchange If Greater Write an if-statement that takes two double variables a and b and exchanges their values if the first one is greater than the second one. As a result print the values a and b, separated by a space. */ using System; class ExchangeIfGreater { static void Main() { Console.Write("Enter number A: "); double firstNumber = double.Parse(Console.ReadLine()); Console.Write("Enter number B: "); double secondNumber = double.Parse(Console.ReadLine()); if (firstNumber > secondNumber) { double temp = firstNumber; firstNumber = secondNumber; secondNumber = temp; } Console.WriteLine("Te result --> A = {0} B = {1}", firstNumber, secondNumber); } } <file_sep>/* Problem 6. Calculate N! / K! Write a program that calculates `n! / k!` for given `n` and `k` (1 < k < n < 100). Use only one loop. */ using System; using System.Numerics; class CalculateNK { static void Main() { Console.WriteLine("Calculate (N! / K!) 1 < K < N < 100"); Console.Write("Enter N: "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter K: "); int k = int.Parse(Console.ReadLine()); BigInteger factorialN = 1; BigInteger factorialK = 1; if (k > 1 && n > k && n < 100) { for (int i = 1, j = 1; i <= n; i++, j++) { factorialN *= i; if (j <= k) { factorialK *= j; } } BigInteger output = factorialN / factorialK; Console.WriteLine(output); } else { Console.WriteLine("Invalid input"); } } } <file_sep>/*Problem 13.* Comparing Floats Write a program that safely compares floating-point numbers (double) with precision `eps = 0.000001`. Note: Two floating-point numbers `a` and `b` cannot be compared directly by `a == b` because of the nature of the floating-point arithmetic. Therefore, we assume two numbers are equal if they are more closely to each other than a fixed constant `eps`._ */ using System; class ComparingFloats { static void Main() { Console.Write("Enter the first number: "); double firstNumber = double.Parse(Console.ReadLine()); Console.Write("Enter the second number: "); double secondNumber = double.Parse(Console.ReadLine()); bool eps = Math.Abs(firstNumber - secondNumber) < 0.000001; if (eps) { Console.WriteLine("They are equal!"); } else Console.WriteLine("They are NOT equal!"); } } <file_sep>/* Problem 10.* Beer Time A beer time is after `1:00 PM` and before `3:00 AM`. Write a program that enters a time in format “hh:mm tt” (an hour in range [01...12], a minute in range [00…59] and AM / PM designator) and prints `beer time` or `non-beer time` according to the definition above or `invalid time` if the time cannot be parsed. _Note: You may need to learn how to parse dates and times._ */ using System; class BeerTime { static void Main() { Console.Write("Enter a time in format hh:mm tt: "); DateTime time = DateTime.Parse(Console.ReadLine()); DateTime start = DateTime.Parse("1:00 PM"); DateTime end = DateTime.Parse("3:00 AM"); if ((time >= start) || (time < end)) { Console.WriteLine("Beer time"); } else { Console.WriteLine("Non-beer time"); } } } <file_sep>/* Problem 7. Point in a Circle Write an expression that checks if given point (x, y) is inside a circle `K({0, 0}, 2)`. */ using System; class PointInACircle { static void Main() { Console.Write("Enter x: "); double x = double.Parse(Console.ReadLine()); Console.Write("Enter y: "); double y = double.Parse(Console.ReadLine()); int radius = 2; bool check = (x * x) + (y * y) < (radius * radius); Console.WriteLine("The point is inside --> " + check); } } <file_sep>/* Problem 9. Trapezoids Write an expression that calculates trapezoid's area by given sides `a` and `b` and height `h`. */ using System; class Trapezoids { static void Main() { Console.Write("Enter side a = "); double sideA = int.Parse(Console.ReadLine()); Console.Write("Enter side b = "); double sideB = int.Parse(Console.ReadLine()); Console.Write("Enter height h = "); double height = int.Parse(Console.ReadLine()); double area = ((sideA + sideB) / 2) * height; Console.WriteLine("The area is = " + area); } }<file_sep>/* Problem 12. Extract Bit from Integer Write an expression that extracts from given integer `n` the value of given bit at index `p`. */ using System; class ExtractBit3 { static void Main() { Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); Console.Write("Enter position: "); int position = int.Parse(Console.ReadLine()); int mask = 1 << position; int maskAndNumber = mask & number; int bit = maskAndNumber >> position; Console.WriteLine("Your number in binary: {0}", Convert.ToString(number, 2)); Console.WriteLine("The bit {0} is = {1}", position, bit); } }<file_sep>/* Problem 6. The Biggest of Five Numbers Write a program that finds the biggest of five numbers by using only five if statements. */ using System; class TheBiggestOf5Numbers { static void Main() { Console.Write("Enter number 1: "); double num1 = double.Parse(Console.ReadLine()); Console.Write("Enter number 2: "); double num2 = double.Parse(Console.ReadLine()); Console.Write("Enter number 3: "); double num3 = double.Parse(Console.ReadLine()); Console.Write("Enter number 4: "); double num4 = double.Parse(Console.ReadLine()); Console.Write("Enter number 5: "); double num5 = double.Parse(Console.ReadLine()); if ((num1 > num2) && (num1 > num3) && (num1 > num4) && (num1 > num5)) { Console.WriteLine("The biggest number is: " + num1); } else if ((num2 > num1) && (num2 > num3) && (num2 > num4) && (num2 > num5)) { Console.WriteLine("The biggest number is: " + num2); } else if ((num3 > num1) && (num3 > num2) && (num3 > num4) && (num3 > num5)) { Console.WriteLine("The biggest number is: " + num3); } else if ((num4 > num1) && (num4 > num2) && (num4 > num3) && (num4 > num5)) { Console.WriteLine("The biggest number is: " + num4); } else { Console.WriteLine("The biggest number is: " + num5); } } }<file_sep>/* Problem 2. Print Company Information A company has name, address, phone number, fax number, web site and manager. The manager has first name, last name, age and a phone number. Write a program that reads the information about a company and its manager and prints it back on the console. */ using System; class CompanyInformation { static void Main() { Console.WriteLine("Enter information about the company:"); Console.Write("Name: "); string companyName = Console.ReadLine(); Console.Write("Address: "); string companyAddress = Console.ReadLine(); Console.Write("Phone Number: "); string companyPhone = Console.ReadLine(); Console.Write("Fax Number: "); string companyFaxNumber = Console.ReadLine(); Console.Write("Website: "); string companyWebsite = Console.ReadLine(); Console.WriteLine(); Console.WriteLine("Enter information about the manager: "); Console.Write("First Name: "); string managerFirstName = Console.ReadLine(); Console.Write("Last name: "); string managerLastName = Console.ReadLine(); Console.Write("Age: "); byte managerAge = byte.Parse(Console.ReadLine()); Console.Write("Phone Number: "); string managerPhone = Console.ReadLine(); Console.WriteLine(); Console.WriteLine(@"Company Name: {0} Address: {1} Phone Number: {2} Fax Number: {3} Website: {4} Manager: {5} {6} (age: {7}, tel. {8}) ", companyName, companyAddress, companyPhone, companyFaxNumber, companyWebsite, managerFirstName, managerLastName, managerAge, managerPhone); } } <file_sep>/* Problem 4. Number Comparer Write a program that gets two numbers from the console and prints the greater of them. Try to implement this without if statements. */ using System; class NumberComparer { static void Main() { Console.Write("Enter first number: "); decimal firstNumber = decimal.Parse(Console.ReadLine()); Console.Write("Enter second number: "); decimal secondNumber = decimal.Parse(Console.ReadLine()); bool greater = firstNumber > secondNumber; Console.WriteLine("The greater number is: {0}", greater ? firstNumber : secondNumber); } } <file_sep>/* Problem 11. Numbers in Interval Dividable by Given Number Write a program that reads two positive integer numbers and prints how many numbers `p` exist between them such that the reminder of the division by `5` is `0`. */ using System; class NumbersInInterval { static void Main() { Console.Write("Enter lower limit: "); uint lower = uint.Parse(Console.ReadLine()); Console.Write("Enter upper limit: "); uint upper = uint.Parse(Console.ReadLine()); int count = 0; Console.WriteLine(); for (uint i = lower; i <= upper; i++) { if (i % 5 == 0) { count++; Console.Write("{0} ", i); } } Console.WriteLine(); Console.WriteLine(); Console.WriteLine("{0} numbers exist between your limits", count); } } <file_sep>/* Problem 10. Fibonacci Numbers Write a program that reads a number `n` and prints on the console the first `n` members of the Fibonacci sequence (at a single line, separated by comma and space - `, `) : `0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …`. */ using System; class FibonacciNumbers { static void Main() { Console.Write("Enter a number: "); ulong lenght = ulong.Parse(Console.ReadLine()); int a = 0, b = 1, c = 0; Console.Write("{0}, {1}", a, b); for (ulong i = 2; i < lenght; i++) { c= a + b; Console.Write(", {0}", c); a= b; b= c; } Console.WriteLine(); } } <file_sep>/*Problem 7. Print First and Last Name Create console application that prints your first and last name, each at a separate line. */ using System; class FirstAndLastName { static void Main() { string firstName = "Boiko"; string lastName = "Borisov"; Console.WriteLine("My full name is:"); Console.WriteLine(firstName); Console.WriteLine(lastName); } }<file_sep>/* Problem 6. Four-Digit Number Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following: Calculates the sum of the digits (in our example `2 + 0 + 1 + 1 = 4`). Prints on the console the number in reversed order: `dcba` (in our example `1102`). Puts the last digit in the first position: `dabc` (in our example `1201`). Exchanges the second and the third digits: `acbd` (in our example `2101`). The number has always exactly 4 digits and cannot start with 0. */ using System; class FourDigitNumber { static void Main() { Console.Write("Enter a four-digit number: "); int number = int.Parse(Console.ReadLine()); int num1 = number / 1000; int num2 = (number % 1000) / 100; int num3 = (number % 100) / 10; int num4 = number % 10; Console.WriteLine("The sum of the digits: " + (num1 + num2 + num3 + num4)); Console.WriteLine("The reversed order: " + num4 + num3 + num2 + num1); Console.WriteLine("Last digit in the 1 position: " + num4 + num1 + num2 + num3); Console.WriteLine("Exchanged 2 and 3 position: " + num1 + num3 + num2 + num4); } } <file_sep>/* Problem 4. Rectangles Write an expression that calculates rectangle’s perimeter and area by given width and height. */ using System; class Rectangles { static void Main() { Console.Write("Enter rectangle's width: "); double width = double.Parse(Console.ReadLine()); Console.Write("Enter rectangle's height: "); double height = double.Parse(Console.ReadLine()); double perimeter = width * 2 + height * 2; double area = width * height; Console.WriteLine("The perimeter is: " + perimeter); Console.WriteLine("The area is: " + area); } } <file_sep>/*Problem 12. Null Values Arithmetic Create a program that assigns null values to an integer and to a double variable. Try to print these variables at the console. Try to add some number or the null literal to these variables and print the result. */ using System; class NullValuesArithmetic { static void Main() { int? a = null; double? b = null; Console.WriteLine("Null varA and varB: [{0}] [{1}]", a, b); a = 1; b = 2; Console.WriteLine("With added numbers: [{0}] [{1}]", a, b); a = null; b = null; Console.WriteLine("Null varA and varB: [{0}] [{1}]", a, b); } } <file_sep>/* Problem 5. The Biggest of 3 Numbers Write a program that finds the biggest of three numbers. */ using System; class TheBiggestOf3Numbers { static void Main() { Console.Write("Enter number 1: "); double num1 = double.Parse(Console.ReadLine()); Console.Write("Enter number 2: "); double num2 = double.Parse(Console.ReadLine()); Console.Write("Enter number 3: "); double num3 = double.Parse(Console.ReadLine()); if ((num1 > num2) && (num1 > num3)) { Console.WriteLine("The biggest number is: " + num1); } else if ((num2 > num1) && (num2 > num3)) { Console.WriteLine("The biggest number is: " + num2); } else { Console.WriteLine("The biggest number is: " + num3); } } } <file_sep>/* Problem 3. Min, Max, Sum and Average of N Numbers Write a program that reads from the console a sequence of `n` integer numbers and returns the minimal, the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point). The input starts by the number `n` (alone in a line) followed by `n` lines, each holding an integer number. The output is like in the examples below. */ using System; class MinMaxSumAver { static void Main() { int length = 3; int max = int.MinValue; int min = int.MaxValue; int sum = 0; double average = 0; Console.WriteLine("Enter {0} numbers:", length); for (int i = 0; i < length; i++) { int input = int.Parse(Console.ReadLine()); if (input < min) { min = input; } if (max < input) { max = input; } sum += input; average = sum / length; } Console.WriteLine("min = {0}", min); Console.WriteLine("max = {0}", max); Console.WriteLine("sum = {0}", sum); Console.WriteLine("avg = {0:F2}", average); } } <file_sep>/* Problem 9. Matrix of Numbers Write a program that reads from the console a positive integer number `n` (1 = n = 20) and prints a matrix like in the examples below. Use two nested loops. */ using System; class MatrixOfNumbers { static void Main() { Console.Write("Enter 1 <= n <= 20: "); int n = int.Parse(Console.ReadLine()); if ((n >= 1) && (n <= 20)) { for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { Console.Write("{0, 2} ", row + col + 1); } Console.WriteLine(); } } else { Console.WriteLine("Out of range! "); } } } <file_sep>/* Problem 1. Declare Variables Declare five variables choosing for each of them the most appropriate of the types byte, sbyte, short, ushort, int, uint, long, ulong to represent the following values: 52130, -115, 4825932, 97, -10000. Choose a large enough type for each number to ensure it will fit in it. Try to compile the code. */ using System; class DeclareVariables { static void Main() { ushort a = 52130; sbyte b = -115; int c = 4825932; byte d = 97; short e = -10000; Console.WriteLine("{0, 10} is type {1}", a, a.GetType().Name); Console.WriteLine("{0, 10} is type {1}", b, b.GetType().Name); Console.WriteLine("{0, 10} is type {1}", c, c.GetType().Name); Console.WriteLine("{0, 10} is type {1}", d, d.GetType().Name); Console.WriteLine("{0, 10} is type {1}", e, e.GetType().Name); } }<file_sep>/* Problem 1. Sum of 3 Numbers Write a program that reads 3 real numbers from the console and prints their sum. */ using System; class SumOf3Numbers { static void Main() { Console.Write("First number: "); double firstNumber = double.Parse(Console.ReadLine()); Console.Write("Second number: "); double secondNumber = double.Parse(Console.ReadLine()); Console.Write("Third number: "); double thirdNumber = double.Parse(Console.ReadLine()); Console.WriteLine("The sum is: {0}", firstNumber+secondNumber+thirdNumber); } } <file_sep>/* Problem 11. Bank Account Data A bank account has a holder name (first name, middle name and last name), available amount of money (balance), bank name, IBAN, 3 credit card numbers associated with the account. Declare the variables needed to keep the information for a single bank account using the appropriate data types and descriptive names. */ using System; class BankAccountData { static void Main() { Console.WriteLine("Please enter"); Console.Write("First name: "); string firstName = Console.ReadLine(); Console.Write("Middle name: "); string middleName = Console.ReadLine(); Console.Write("Last name: "); string lastName = Console.ReadLine(); Console.Write("Balance: "); decimal balance = decimal.Parse(Console.ReadLine()); Console.Write("Bank name: "); string bankName = (Console.ReadLine()); Console.Write("IBAN: "); string iban = (Console.ReadLine()); Console.Write("Credit card 1: "); ulong card1 = ulong.Parse(Console.ReadLine()); Console.Write("Credit card 2: "); ulong card2 = ulong.Parse(Console.ReadLine()); Console.Write("Credit card 3: "); ulong card3 = ulong.Parse(Console.ReadLine()); Console.WriteLine(@" Client's data: Name: {0} {1} {2} Balance: {3} Bank name: {4} IBAN: {5} Credit card 1: {6} Credit card 2: {7} Credit card 3: {8} ", firstName, middleName, lastName, balance, bankName, iban, card1, card2, card3); } }<file_sep>/* Problem 3. Divide by 7 and 5 Write a Boolean expression that checks for given integer if it can be divided (without remainder) by `7` and `5` at the same time. */ using System; class Divide7And5 { static void Main() { Console.Write("Enter an integer number: "); int number = int.Parse(Console.ReadLine()); bool check = (number % 5 == 0) && (number % 7 == 0); Console.WriteLine("Your number can be devided by 5 and 7 at the same time --> {0}", check); } } <file_sep>/* Problem 12.* Randomize the Numbers 1…N Write a program that enters in integer `n` and prints the numbers `1, 2, …, n` in random order. */ using System; class RandomizeTheNumbers1N { static void Main() { Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); Random rnd = new Random(); bool[] printed = new bool[n + 1]; int numberToPrint; for (int i = 1; i <= n; i++) { numberToPrint = rnd.Next(1, n + 1); if (!printed[numberToPrint]) { Console.Write("{0} ", numberToPrint); printed[numberToPrint] = true; continue; } i--; } Console.WriteLine(); } } <file_sep>/*Problem 3. Variable in Hexadecimal Format Declare an integer variable and assign it with the value `254` in hexadecimal format (`0x##`). Use Windows Calculator to find its hexadecimal representation. Print the variable and ensure that the result is `254`. */ using System; class VariableInHexadecimalFormat { static void Main() { int var = 0xFE; Console.WriteLine(var); } } <file_sep>/* Problem 15. Hexadecimal to Decimal Number Using loops write a program that converts a hexadecimal integer number to its decimal form. The input is entered as string. The output should be a variable of type long. Do not use the built-in .NET functionality. */ using System; class HexadecimalToDecimal { static void Main() { Console.Write("Enter a hexadecimal number: "); string input = Console.ReadLine(); int power = 0; long numberInHex = 0; for (int i = input.Length - 1; i >= 0; i--) { int sign; if (input[i] == 'a' || input[i] == 'A') { sign = 10; } else if (input[i] == 'b' || input[i] == 'B') { sign = 11; } else if (input[i] == 'c' || input[i] == 'C') { sign = 12; } else if (input[i] == 'd' || input[i] == 'D') { sign = 13; } else if (input[i] == 'e' || input[i] == 'E') { sign = 14; } else if (input[i] == 'f' || input[i] == 'F') { sign = 15; } else { sign = input[i] - 48; } numberInHex += sign * (long)Math.Pow(16, power++); } Console.WriteLine("Coverted to decimal: " + numberInHex); } } <file_sep>/* Problem 7. Calculate N! / (K! * (N-K)!) In combinatorics, the number of ways to choose `k` different members out of a group of `n` different elements (also known as the number of combinations) is calculated by the following formula: ![formula](https://cloud.githubusercontent.com/assets/3619393/5626060/89cc780e-958e-11e4-88d2-0e1ff7229768.png) For example, there are 2598960 ways to withdraw 5 cards out of a standard deck of 52 cards. Your task is to write a program that calculates `n! / (k! * (n-k)!)` for given `n` and `k` (1 < k < n < 100). Try to use only two loops. */ using System; using System.Numerics; class CalculateNKAdvanced { static void Main() { Console.WriteLine("Calculate n! / (k! * (n-k)!) 1 < k < n < 100"); Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); Console.Write("Enter k: "); int k = int.Parse(Console.ReadLine()); BigInteger factorialN = 1; BigInteger factorialK = 1; BigInteger factorialNK = 1; if (k > 1 && n > k && n < 100) { int nk = n - k; for (int i = 1; i <= nk; i++) { factorialNK *= i; } for (int i = 1, j = 1; i <= n; i++, j++) { factorialN *= i; if (j <= k) { factorialK *= j; } } BigInteger output = factorialN / (factorialK * factorialNK); Console.WriteLine(output); } else { Console.WriteLine("Invalid input"); } } } <file_sep>/* Problem 7. Sort 3 Numbers with Nested Ifs Write a program that enters 3 real numbers and prints them sorted in descending order. Use nested `if` statements. */ using System; class SortingNestedIfs { static void Main() { Console.Write("Enter number 1: "); double num1 = double.Parse(Console.ReadLine()); Console.Write("Enter number 2: "); double num2 = double.Parse(Console.ReadLine()); Console.Write("Enter number 3: "); double num3 = double.Parse(Console.ReadLine()); if ((num1 >= num2) && (num1 >= 3)) { if (num2 >= num3) { Console.WriteLine("Sorted: {0}, {1}, {2}", num1, num2, num3); } else { Console.WriteLine("Sorted: {0}, {1}, {2}", num1, num3, num2); } } else if ((num2 >= num1) && (num2 >= num3)) { if (num1 >= num3) { Console.WriteLine("Sorted: {0}, {1}, {2}", num2, num1, num3); } else { Console.WriteLine("Sorted: {0}, {1}, {2}", num2, num3, num1); } } else if ((num3 >= num1) && (num3 >= num2)) { if (num1 >= num2) { Console.WriteLine("Sorted: {0}, {1}, {2}", num3, num1, num2); } else { Console.WriteLine("Sortes: {0}, {1}, {2}", num3, num2, num1); } } } } <file_sep>/* Problem 3. Circle Perimeter and Area Write a program that reads the radius `r` of a circle and prints its perimeter and area formatted with `2` digits after the decimal point. */ using System; class CirclePerimeterAndArea { static void Main() { Console.Write("Enter radius: "); double radius = double.Parse(Console.ReadLine()); double perimeter = 2 * radius * Math.PI; double area = radius * radius * Math.PI; Console.WriteLine("Perimeter = {0:F2}", perimeter); Console.WriteLine("Area = {0:F2}", area); } }
4dc2bc4bd05929198e2016d890e2d93c30c038e4
[ "Markdown", "C#" ]
57
C#
danisio/CSharp1-Homeworks
e09d1b71e537c7347addef5eccca803cdab2aa92
e873ebd24bfd9068878ee70f4e36b536cd6ea8ba
refs/heads/master
<repo_name>epcos71/ioBroker.fb-checkpresence<file_sep>/lib/objects.js 'use strict'; //Helper function function _common(type, opt, i){ const c = {}; if (type == 'state' || type == 'channel' || type == 'device' || type == 'folder') { c.name = opt[i][2]; c.desc = opt[i][8]; } if (type == 'state' || type == 'channel'){ c.role = opt[i][4]; } if (type == 'state'){ c.type = opt[i][3]; c.def = opt[i][5]; c.read = opt[i][6]; c.write = opt[i][7]; if (opt[i][9] != 'undefinded') c.unit = opt[i][9]; } if (type == 'device' || type == 'folder'){ if (opt[i][10] != 'undefinded') c.icon = opt[i][10]; } return c; } //Helper function for creating and upating objects function _createObjects(message, that, opt, enabled) { return new Promise((resolve, reject) => { let count = 0; const length = opt.length; for(let i=0; i < opt.length && enabled == true; i++) { const id = opt[i][0]; const type = opt[i][1]; const c = _common(type, opt, i); that.getObject(id, function (err, obj) { if (!err && obj) { that.extendObject(id, { type: type, common: c, native: {}, }, function(err, obj){ if (!err && obj){ count++; if (length == count) resolve(true); //that.log.debug(message + ' ' + id + ' finished successfully'); }else{ reject('extendObject ' + id + ' ' + JSON.stringify(err)); } }); }else{ that.setObjectNotExists(id, {type: type, common: c, native: {}, }, function(err, obj){ if (!err && obj){ count++; if (type == 'state') { that.getState(id, function(err, obj) { if (!err) { if (obj.val == null) that.setState(id, c.def, true); //set default if (length == count) resolve(true); //that.log.debug(message + ' ' + id + ' finished successfully'); }else{ reject(message + ': ' + err); } }); } }else{ reject(message + ': ' + err); } }); } }); } }); } function _enableHistory(that, cfg, familyMember) { return new Promise((resolve, reject) => { let alias = ''; const member = familyMember; that.sendTo(cfg.history, 'getEnabledDPs', {}, function (result) { if (result[`${that.namespace}` + '.' + member] != undefined && result[`${that.namespace}` + '.' + member].aliasId != undefined){ alias = result[`${that.namespace}` + '.' + member].aliasId; } that.sendTo(cfg.history, 'enableHistory', { id: `${that.namespace}` + '.' + member, options: { changesOnly: true, debounce: 0, retention: 31536000, maxLength: 10, changesMinDelta: 0, aliasId: alias } }, function (result2) { if (result2.error) { reject('enableHistory ' + member + ' ' + result2.error); } if (result2.success) { that.log.debug('enableHistory.2 ' + member + ' ' + result2.success); resolve(true); } }); }); }); } async function createGlobalObjects(that, table, tableGuest, enabled) { try { const opt = [ // Legende: o - optional //id, type, common.name (o), common.type (o), common.role, common.def (o), common.rd, common.wr, common.desc (o) //common.type (possible values: number, string, boolean, array, object, mixed, file) //info objects, states ['info.connection', 'state', 'info.connection', 'boolean', 'indicator', false, true, false, 'Fritzbox connection state'], ['info.X_AVM-DE_GetHostListPath', 'state', 'info.X_AVM-DE_GetHostListPath', 'boolean', 'indicator', false, true, false, 'Fritzbox service X_AVM-DE_GetHostListPath available'], ['info.X_AVM-DE_GetMeshListPath', 'state', 'info.X_AVM-DE_GetMeshListPath', 'boolean', 'indicator', false, true, false, 'Fritzbox service X_AVM-DE_GetMeshListPath available'], ['info.GetSpecificHostEntry', 'state', 'info.GetSpecificHostEntry', 'boolean', 'indicator', false, true, false, 'Fritzbox service GetSpecificHostEntry available'], ['info.X_AVM-DE_GetSpecificHostEntryByIP', 'state', 'info.X_AVM-DE_GetSpecificHostEntryByIP', 'boolean', 'indicator', false, true, false, 'Fritzbox service X_AVM-DE_GetSpecificHostEntryByIP available'], ['info.GetSecurityPort', 'state', 'info.GetSecurityPort', 'boolean', 'indicator', false, true, false, 'Fritzbox service GetSecurityPort available'], ['info.GetInfo', 'state', 'info.GetInfo', 'boolean', 'indicator', false, true, false, 'Fritzbox service GetInfo available'], ['info.SetEnable', 'state', 'info.SetEnable', 'boolean', 'indicator', false, true, false, 'Fritzbox service SetEnable available'], ['info.WLANConfiguration3-GetInfo', 'state', 'info.WLANConfiguration3-GetInfo', 'boolean', 'indicator', false, true, false, 'Fritzbox service WLANConfiguration3-GetInfo available'], ['info.DisallowWANAccessByIP', 'state', 'info.DisallowWANAccessByIP', 'boolean', 'indicator', false, true, false, 'Fritzbox service DisallowWANAccessByIP available'], ['info.GetWANAccessByIP', 'state', 'info.GetWANAccessByIP', 'boolean', 'indicator', false, true, false, 'Fritzbox service GetWANAccessByIP available'], ['info.Reboot', 'state', 'info.Reboot', 'boolean', 'indicator', false, true, false, 'Fritzbox service Reboot available'], ['info.DeviceInfo1-GetInfo', 'state', 'info.DeviceInfo1-GetInfo', 'boolean', 'indicator', false, true, false, 'Fritzbox service DeviceInfo1-GetInfo available'], ['info.extIp', 'state', 'info.extIp', 'string', 'value', '', true, false, 'external ip address'], ['info.lastUpdate', 'state', 'lastUpdate', 'string', 'date', new Date('1900-01-01T00:00:00'), true, false, 'last connection datetime'], //general states ['presence', 'state', 'presence', 'boolean', 'indicator', false, true, false, 'someone from the family are present'], ['presenceAll', 'state', 'presenceAll', 'boolean', 'indicator', false, true, false, 'All of the family are present'], ['absence', 'state', 'absence', 'boolean', 'indicator', false, true, false, 'someone from the family are absent'], ['absenceAll', 'state', 'absenceAll', 'boolean', 'indicator', false, true, false, 'All of the family are absent'], ['presentMembers', 'state', 'presentMembers', 'string', 'value', '', true, false, 'who is present'], ['absentMembers', 'state', 'absentMembers', 'string', 'value', '', true, false, 'who is absent'], ['json', 'state', 'json', 'string', 'json', '[]', true, false, 'Json table'], ['html', 'state', 'html', 'string', 'html', table, true, false, 'Html table'], ['devices', 'state', 'devices', 'number', 'value', 0, true, false, 'Number of devices'], ['reboot', 'state', 'reboot', 'boolean', 'indicator', false, true, true, 'Reboot Fritzbox'], ['activeDevices', 'state', 'activeDevices', 'number', 'value', 0, true, false, 'Number of active devices'], //guest objects, states ['guest', 'state', 'guest', 'boolean', 'indicator', false, true, false, 'Guest is logged in'], ['guest.count', 'state', 'count', 'number', 'value', 0, true, false, 'Number of guests'], ['guest.listJson', 'state', 'listJson', 'string', 'json', '[]', true, false, 'Guest list json'], ['guest.listHtml', 'state', 'listHtml', 'string', 'html', tableGuest, true, false, 'Guest list html'], ['guest.presence', 'state', 'guest.presence', 'boolean', 'indicator', false, true, false, 'a guest is present'], ['guest.wlan', 'state', 'guest.wlan', 'boolean', 'indicator', false, true, true, 'guest wlan is on or off'], //fb-devices objects, states ['fb-devices', 'folder', 'fb-devices', '', '', '', true, false, 'folder for fritzbox devices'], ['fb-devices.count', 'state', 'fb-devices.count', 'number', 'value', 0, true, false, 'Number of fritzbox devices'], ['fb-devices.active', 'state', 'fb-devices.active', 'number', 'value', 0, true, false, 'Number of active devices'], ['fb-devices.inactive', 'state', 'fb-devices.inactive', 'number', 'value', 0, true, false, 'Number of inactive devices'], ['fb-devices.json', 'state', 'fb-devices.json', 'string', 'json', [], true, false, 'fritzbox device list json'], ['fb-devices.mesh', 'state', 'fb-devices.mesh', 'string', 'json', [], true, false, 'fritzbox mesh list json'], ['fb-devices.jsonActive', 'state', 'fb-devices.jsonActive', 'string', 'json', [], true, false, 'fritzbox active device list json'], ['fb-devices.jsonInactive', 'state', 'fb-devices.jsonInactive', 'string', 'json', [], true, false, 'fritzbox inactive device list json'], ['fb-devices.html', 'state', 'fb-devices.html', 'string', 'html', '', true, false, 'fritzbox device list html'], //blacklist objects, states ['blacklist', 'state', 'blacklist', 'boolean', 'indicator', false, true, false, 'Unknown devices'], ['blacklist.count', 'state', 'count', 'number', 'value', 0, true, false, 'Number of unknown devices'], ['blacklist.listJson', 'state', 'listJson', 'string', 'json', '[]', true, false, 'Unknown devices list json'], ['blacklist.listHtml', 'state', 'listHtml', 'string', 'html', tableGuest, true, false, 'Unknown devices list html'], //whitelist objects, states ['whitelist', 'folder', 'whitelist', '', '', '', true, false, 'whitelist'], ['whitelist.count', 'state', 'whitelist.count', 'number', 'value', 0, true, false, 'Number of whitelist devices'], ['whitelist.json', 'state', 'whitelist.json', 'string', 'json', '[]', true, false, 'whitelist devices json'], ['whitelist.html', 'state', 'whitelist.html', 'string', 'html', tableGuest, true, false, 'whitelist devices html'] ]; await _createObjects('createGlobalObjects', that, opt, enabled); that.log.info('createGlobalObjects finished successfully'); return true; } catch (error) { that.log.error('createGlobalObjects: ' + JSON.stringify(error)); return false; } } async function createMemberObjects(that, cfg, table, enabled) { try { if (cfg.members.length == 0) { throw('no family members defined! Objects are not created!'); }else{ //Create objects for family members let length = cfg.members.length; let count=0; for (let k = 0; k < cfg.members.length; k++) { if (cfg.members[k].enabled == false) length--; } for (let k = 0; k < cfg.members.length; k++) { const memberRow = cfg.members[k]; const member = memberRow.familymember; if (memberRow.enabled == true){ const opt = [ [member, 'state', 'member', 'boolean', 'indicator', false, true, false, 'Family member'], [member + '.presence', 'state', member + '.presence', 'boolean', 'indicator', false, true, false, 'state of the family member'], [member + '.history', 'state', 'history', 'string', 'json', [], true, false, 'history of the day as json table'], [member + '.historyHtml', 'state', 'historyHtml', 'string', 'html', table, true, false, 'history of the day as html table'], [member + '.going', 'state', 'going', 'string', 'date', new Date(), true, false, 'time when you leaving the home'], [member + '.comming', 'state', 'comming', 'string', 'date', new Date(), true, false, 'time when you arriving at home'], [member + '.speed', 'state', member + '.speed', 'string', 'value', '', true, false, 'Speed of the device'], [member + '.absent.since', 'state', member + '.absent.since', 'string', 'value', '0', true, false, 'absent since'], [member + '.present.since', 'state', member + '.present.since', 'string', 'value', '0', true, false, 'present since'], [member + '.absent.sum_day', 'state', member + '.absent.sum_day', 'string', 'value', '0', true, false, 'how long absent per day'], [member + '.present.sum_day', 'state', member + '.present.sum_day', 'string', 'value', '0', true, false, 'how long present per day'] ]; await _createObjects('createMemberObjects', that, opt, enabled); count++; if (cfg.history != ''){ await _enableHistory(that, cfg, member); }else{ that.log.info('History function for ' + member + ' disabled. Please select a history adapter in the configuration dialog!'); } if (length == count){ that.log.info('createMemberObjects finished successfully'); return true; } } } } } catch (error) { that.log.warn('createMemberObjects: ' + JSON.stringify(error)); return false; } } async function createFbDeviceObjects(that, items, enabled) { try { if (!items) throw('createFbDeviceObjects: items = null'); let count=0; const length = items.length; for (let i = 0; i < items.length; i++) { const device = items[i]['HostName']; //const n = items.indexOfObject('HostName', items[i]['HostName'], i); //if (n != -1 ) gthis.log.warn('duplicate fritzbox device item. Please correct the hostname in the fritzbox settings for the device -> ' + items[i]['HostName'] + ' ' + items[i]['MACAddress']); let hostName = device; if (device.includes('.')){ hostName = hostName.replace('.', '-'); } const opt = [ //[device, 'state', 'member', 'boolean', 'indicator', false, true, false, 'Family member'], ['fb-devices.' + hostName, 'device', 'fb-devices.' + hostName, '', '', '', true, false, hostName + ' infos'], ['fb-devices.' + hostName + '.meshstate', 'state', 'fb-devices.' + hostName + '.meshstate', 'boolean', 'indicator', '', true, false, 'meshstate state of the device'], ['fb-devices.' + hostName + '.macaddress', 'state', hostName + '.macaddress', 'string', 'value', '', true, false, 'MAC address of the device'], ['fb-devices.' + hostName + '.ipaddress', 'state', hostName + '.ipaddress', 'string', 'value', '', true, false, 'IP address of the device'], ['fb-devices.' + hostName + '.active', 'state', hostName + '.active', 'boolean', 'indicator', false, true, false, 'State of the device'], ['fb-devices.' + hostName + '.disabled', 'state', hostName + '.disabled', 'boolean', 'indicator', false, true, true, 'device disabled?'], ['fb-devices.' + hostName + '.interfacetype', 'state', hostName + '.interfacetype', 'string', 'value', '', true, false, 'Interface type of the device'], ['fb-devices.' + hostName + '.speed', 'state', hostName + '.speed', 'string', 'value', '', true, false, 'Speed of the device'], ['fb-devices.' + hostName + '.guest', 'state', hostName + '.guest', 'boolean', 'indicator', false, true, false, 'Guest state of the device'], ['fb-devices.' + hostName + '.whitelist', 'state', hostName + '.whitelist', 'boolean', 'indicator', false, true, false, 'Whitelist member'], ['fb-devices.' + hostName + '.blacklist', 'state', hostName + '.blacklist', 'string', 'indicator', false, true, false, 'Blacklist member'] ]; await _createObjects('createFbDeviceObjects', that, opt, enabled); count++; if (length == count) { return true; } } } catch (error) { that.log.warn('createFbDeviceObjects: ' + JSON.stringify(error)); return false; } } async function createMeshObjects(that, items, channel, enabled) { try { let count = 0; const length = items.length; for (let i = 0; i < items.length; i++) { const device = items[i]['HostName']; let hostName = device; if (device.includes('.')){ hostName = hostName.replace('.', '-'); } const opt = [ //[device, 'state', 'member', 'boolean', 'indicator', false, true, false, 'Family member'], ['fb-devices.' + hostName + '.' + channel, 'channel', 'fb-devices.' + hostName + '.' + channel, '', '', '', true, false, hostName + ' interface'], ['fb-devices.' + hostName + '.' + channel + '.name', 'state', 'fb-devices.' + hostName + '.' + channel + '.name', 'string', 'value', '', true, false, 'name of the interface'], //['fb-devices.' + hostName + '.' + channel + '.security', 'state', 'fb-devices.' + hostName + '.' + channel + '.security', 'string', 'value', '', true, false, 'security of the interface'], ['fb-devices.' + hostName + '.' + channel + '.link', 'state', 'fb-devices.' + hostName + '.' + channel + '.link', 'string', 'value', '', true, false, 'links of the interface'], ['fb-devices.' + hostName + '.' + channel + '.rx_rcpi', 'state', 'fb-devices.' + hostName + '.' + channel + '.rx_rcpi', 'number', 'value', 0, true, false, 'Current rx_rcpi of the interface', 'dBm'], ['fb-devices.' + hostName + '.' + channel + '.cur_data_rate_rx', 'state', 'fb-devices.' + hostName + '.' + channel + '.cur_data_rate_rx', 'number', 'value', 0, true, false, 'Current data rate rx of the interface', 'Mbit/s'], ['fb-devices.' + hostName + '.' + channel + '.cur_data_rate_tx', 'state', 'fb-devices.' + hostName + '.' + channel + '.cur_data_rate_tx', 'number', 'value', 0, true, false, 'Current data rate tx of the interface', 'Mbit/s'], ['fb-devices.' + hostName + '.' + channel + '.type', 'state', 'fb-devices.' + hostName + '.' + channel + '.type', 'string', 'value', '', true, false, 'type of the interface'] ]; await _createObjects('createMeshObjects', that, opt, enabled); //.then(function(result){ count++; if (length == count) { return true; } } } catch (error) { that.log.warn('createMeshObjects: ' + JSON.stringify(error)); return false; } } module.exports = { createGlobalObjects: createGlobalObjects, createMemberObjects: createMemberObjects, createFbDeviceObjects: createFbDeviceObjects, createMeshObjects: createMeshObjects };<file_sep>/main.js 'use strict'; /* * Created with @iobroker/create-adapter vunknown */ // The adapter-core module gives you access to the core ioBroker functions const utils = require('@iobroker/adapter-core'); // load your modules here, e.g.: const dateFormat = require('dateformat'); // own libraries const fb = require('./lib/fb'); const obj = require('./lib/objects'); /*Array.prototype.indexOfObject = function (property, value, ind=-1) { for (let i = 0, len = this.length; i < len; i++) { if (i != ind && this[i][property] === value) return i; } return -1; };*/ class FbCheckpresence extends utils.Adapter { /** * @param {Partial<ioBroker.AdapterOptions>} [options={}] */ constructor(options) { super({ ...options, name: 'fb-checkpresence', }); //events this.on('ready', this.onReady.bind(this)); //this.on('objectChange', this.onObjectChange); this.on('stateChange', this.onStateChange.bind(this)); this.on('message', this.onMessage.bind(this)); this.on('unload', this.onUnload.bind(this)); //constants this.urn = 'urn:dslforum-org:service:'; this.HTML = '<table class="mdui-table"><thead><tr><th>Name</th><th>Status</th><th>Kommt</th><th>Geht</th></tr></thead><tbody>'; this.HTML_HISTORY = '<table class="mdui-table"><thead><tr><th>Status</th><th>Date</th></tr></thead><tbody>'; this.HTML_END = '</body></table>'; this.HTML_GUEST = '<table class="mdui-table"><thead><tr><th>Hostname</th><th>IPAddress</th><th>MACAddress</th></tr></thead><tbody>'; this.HTML_FB = '<table class="mdui-table"><thead><tr><th>Hostname</th><th>IPAddress</th><th>MACAddress</th><th>Active</th><th>Type</th></tr></thead><tbody>'; //this.FORBIDDEN_CHARS = /[\]\[*,;'"`<>\\?]/g; this.errorCntMax = 10; this.allDevices = []; this.jsonTab; this.htmlTab; this.enabled = true; this.errorCnt = 0; this.Fb = null; this.timeout = null; //http://fritz.box:49000/tr64desc.xml //used actions this.GETPATH = false; this.GETMESHPATH = false; this.GETBYMAC = false; this.GETBYIP = false; this.GETPORT = false; this.GETEXTIP = false; this.SETENABLE = false; this.WLAN3INFO = false; this.DEVINFO = false; this.GETWANACCESSBYIP = false; this.DISALLOWWANACCESSBYIP = false; this.REBOOT = false; } decrypt(key, value) { let result = ''; for (let i = 0; i < value.length; ++i) { result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i)); } return result; } showError(errorMsg) { if (this.errorCnt < this.errorCntMax) { this.errorCnt+=1; this.log.error(errorMsg); } else { this.log.debug('maximum error count reached! Error messages are suppressed'); } } createHTMLTableRow (dataArray) { let html = ''; html += '<tr>'; //new row for(let c=0; c < dataArray.length; c++){ html += '<td>' + dataArray[c] + '</td>'; //columns } html += '</tr>'; //row end return html; } createJSONTableRow(cnt, dataArray) { let json = '{'; if (cnt != 0){ json = ',{'; } for(let c=0; c < dataArray.length; c=c+2){ json += '"' + dataArray[c] + '":'; if (c == dataArray.length-2){ json += '"' + dataArray[c+1] + '"}'; }else{ json += '"' + dataArray[c+1] + '",'; } } return json; } async resyncFbObjects(items){ try { // Get all fb-device objects of this adapter if (items && this.config.syncfbdevices == true){ const devices = await this.getDevicesAsync(); for (const id in devices) { if (devices[id] != undefined && devices[id].common != undefined){ const dName = devices[id].common.name; const shortName = dName.replace('fb-devices.', ''); let found = false; if (dName.includes('fb-devices.')){ for(let i=0;i<items.length;i++){ let hostName = items[i]['HostName']; if (hostName.includes('.')){ hostName = hostName.replace('.', '-'); } if (shortName == hostName) { found = true; break; } } if (found == false && !dName.includes('whitelist')){ const states = await this.getStatesAsync(dName + '.*'); for (const idS in states) { await this.delObjectAsync(idS); await this.delStateAsync(idS); } const ch = await this.getChannelsOfAsync(); for (const c in ch) { if (ch[c]._id.includes(dName + '.')){ await this.delObjectAsync(ch[c]._id); } } await this.delObjectAsync(devices[id]._id); this.log.info('device <' + devices[id]._id + '> successfully deleted'); } } } } this.log.info('fb-devices synchronized successfully'); const adapterObj = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`); adapterObj.native.syncfbdevices = false; this.config.syncfbdevices = false; await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, adapterObj); } } catch (error) { this.log.error('resyncFbObjects ' + JSON.stringify(error)); } } loop(cnt1, cnt2, int1, int2, cfg) { try { const gthis = this; this.timeout = setTimeout(async function() { try { cnt1++; cnt2++; const work = process.hrtime(); let time = null; if (cnt1 == int1){ //gthis.log.info('loopFamily starts'); cnt1 = 0; //const itemlist = await Fb.getDeviceList(); if (gthis.DEVINFO == true) { await gthis.Fb.connectionCheck(); //Sets the connection led //if(res.result === false) gthis.log.error('connectionCheck: ' + JSON.stringify(res)); } await gthis.checkPresence(cfg); time = process.hrtime(work); gthis.log.debug('loopFamily ends after ' + time + ' s'); } if (cnt2 == int2){ gthis.log.debug('loopDevices starts'); cnt2 = 0; if (gthis.GETPATH != null && gthis.GETPATH == true && gthis.config.fbdevices == true){ let meshlist = null; const itemlist = await gthis.Fb.getDeviceList(); if (gthis.GETEXTIP != null && gthis.GETEXTIP == true) await gthis.Fb.getExtIp(); if (gthis.WLAN3INFO != null && gthis.WLAN3INFO == true) await gthis.Fb.getGuestWlan('guest.wlan'); if (gthis.GETMESHPATH != null && gthis.GETMESHPATH == true && gthis.config.meshinfo == true) meshlist = await gthis.Fb.getMeshList(); await gthis.getDeviceInfo(itemlist, meshlist, cfg); } time = process.hrtime(work); gthis.log.debug('loopDevices ends after ' + time + ' s'); } gthis.loop(cnt1, cnt2, int1, int2, cfg); } catch (error) { gthis.log.error('loop: ' + JSON.stringify(error)); } }, 1000); } catch (error) { this.log.error('loop: ' + JSON.stringify(error)); } } async stopAdapter(){ try { //this.log.warn('Adapter stops'); const adapterObj = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`); adapterObj.common.enabled = false; // Adapter ausschalten await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, adapterObj); } catch (error) { this.log.error('stopAdper: ' + JSON.stringify(error)); } } /** * Is called when databases are connected and adapter received configuration. */ async onReady() { try { // Initialize your adapter here //Logging of adapter start this.log.info('start fb-checkpresence: ip-address: "' + this.config.ipaddress + '" - interval devices: ' + this.config.interval + ' Min.' + ' - interval members: ' + this.config.intervalFamily + ' s'); this.log.debug('configuration user: <' + this.config.username + '>'); this.log.debug('configuration history: <' + this.config.history + '>'); this.log.debug('configuration dateformat: <' + this.config.dateformat + '>'); this.log.debug('configuration familymembers: ' + JSON.stringify(this.config.familymembers)); this.log.debug('configuration fb-devices ' + this.config.fbdevices); this.log.debug('configuratuion mesh info: ' + this.config.meshinfo); //decrypt fritzbox password const sysObj = await this.getForeignObjectAsync('system.config'); if (sysObj && sysObj.native && sysObj.native.secret) { this.config.password = this.decrypt(sysObj.native.secret, this.config.password); } else { this.config.password = this.decrypt('<PASSWORD>', this.config.password); } //Configuration changes if needed let adapterObj = (await this.getForeignObjectAsync(`system.adapter.${this.namespace}`)); let adapterObjChanged = false; //for changes //if interval <= 0 than set to 1 if (this.config.interval <= 0) { adapterObj.native.interval = 1; adapterObjChanged = true; this.config.interval = 1; this.log.warn('interval is less than 1. Set to 1 Min.'); } //if interval <= 0 than set to 1 if (this.config.intervalFamily <= 9) { adapterObj.native.intervalFamily = 10; adapterObjChanged = true; this.config.intervalFamily = 10; this.log.warn('interval is less than 10. Set to 10s.'); } //create new configuration items -> workaround for older versions for(let i=0;i<this.config.familymembers.length;i++){ if (this.config.familymembers[i].useip == undefined) { adapterObj.native.familymembers[i].useip = false; adapterObj.native.familymembers[i].ipaddress = ''; adapterObjChanged = true; } } if (adapterObjChanged === true){ //Save changes await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, adapterObj); } const cfg = { ip: this.config.ipaddress, port: '49000', iv: this.config.interval, history: this.config.history, dateFormat: this.config.dateformat, uid: this.config.username, pwd: <PASSWORD>, members: this.config.familymembers, wl: this.config.whitelist }; const cron = cfg.iv * 60; const cronFamily = this.config.intervalFamily; const devInfo = { host: this.config.ipaddress, port: '49000', sslPort: null, uid: this.config.username, pwd: <PASSWORD> }; this.Fb = await fb.Fb.init(devInfo, this); if(this.Fb.services === null) { this.log.error('Can not get services! Adapter stops'); this.stopAdapter(); } //Check if services/actions are supported this.GETPATH = await this.Fb.chkService('X_AVM-DE_GetHostListPath', 'Hosts1', 'X_AVM-DE_GetHostListPath'); this.GETMESHPATH = await this.Fb.chkService('X_AVM-DE_GetMeshListPath', 'Hosts1', 'X_AVM-DE_GetMeshListPath'); this.GETBYMAC = await this.Fb.chkService('GetSpecificHostEntry', 'Hosts1', 'GetSpecificHostEntry'); this.GETBYIP = await this.Fb.chkService('X_AVM-DE_GetSpecificHostEntryByIP', 'Hosts1', 'X_AVM-DE_GetSpecificHostEntryByIP'); this.GETPORT = await this.Fb.chkService('GetSecurityPort', 'DeviceInfo1', 'GetSecurityPort'); this.GETEXTIP = await this.Fb.chkService('GetInfo', 'WANPPPConnection1', 'GetInfo'); if ( this.GETEXTIP == false) this.GETEXTIP = await this.Fb.chkService('GetInfo', 'WANIPConnection1', 'GetInfo'); this.SETENABLE = await this.Fb.chkService('SetEnable', 'WLANConfiguration3', 'SetEnable'); this.WLAN3INFO = await this.Fb.chkService('GetInfo', 'WLANConfiguration3', 'WLANConfiguration3-GetInfo'); this.DEVINFO = await this.Fb.chkService('GetInfo', 'DeviceInfo1', 'DeviceInfo1-GetInfo'); this.DISALLOWWANACCESSBYIP = await this.Fb.chkService('DisallowWANAccessByIP', 'X_AVM-DE_HostFilter', 'DisallowWANAccessByIP'); this.GETWANACCESSBYIP = await this.Fb.chkService('GetWANAccessByIP', 'X_AVM-DE_HostFilter', 'GetWANAccessByIP'); this.REBOOT = await this.Fb.chkService('Reboot', 'DeviceConfig1', 'Reboot'); //const test = await Fb.soapAction(Fb, '/upnp/control/deviceconfig', 'urn:dslforum-org:service:DeviceConfig:1', 'X_AVM-DE_CreateUrlSID', null); //Create global objects await obj.createGlobalObjects(this, this.HTML+this.HTML_END, this.HTML_GUEST+this.HTML_END, this.enabled); await obj.createMemberObjects(this, cfg, this.HTML_HISTORY + this.HTML_END, this.enabled); //create Fb devices if (this.GETPATH != null && this.GETPATH == true && this.config.fbdevices == true){ const items = await this.Fb.getDeviceList(this, cfg, this.Fb); if (items != null){ let res = await obj.createFbDeviceObjects(this, items, this.enabled); if (res === true) this.log.info('createFbDeviceObjects finished successfully'); res = await obj.createMeshObjects(this, items, 0, this.enabled); //create channel 0 as default interface if (res === true) this.log.info('createMeshObjects finished successfully'); }else{ this.log.error('createFbDeviceObjects -> ' + "can't read devices from fritzbox! Adapter stops"); adapterObj = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`); adapterObj.common.enabled = false; // Adapter ausschalten await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, adapterObj); } await this.resyncFbObjects(items); } // states changes inside the adapters namespace are subscribed if (this.SETENABLE === true && this.WLAN3INFO === true) this.subscribeStates(`${this.namespace}` + '.guest.wlan'); if (this.DISALLOWWANACCESSBYIP === true && this.GETWANACCESSBYIP === true) this.subscribeStates(`${this.namespace}` + '.fb-devices.*.disabled'); if (this.REBOOT === true) this.subscribeStates(`${this.namespace}` + '.reboot'); //get uuid for transaction //const sSid = await Fb.soapAction(Fb, '/upnp/control/deviceconfig', urn + 'DeviceConfig:1', 'X_GenerateUUID', null); //const uuid = sSid['NewUUID'].replace('uuid:', ''); this.loop(10, 55, cronFamily, cron, cfg); } catch (error) { this.showError('onReady: ' + error); } } /** * Is called when adapter shuts down - callback has to be called under any circumstances! * @param {() => void} callback */ async onUnload(callback) { try { this.enabled = false; this.timeout && clearTimeout(this.timeout); this.timeout = null; this.Fb.exitRequest; this.log.info('cleaned everything up ...'); callback && callback(); } catch (e) { this.log.error('onUnload: ' + e); callback && callback(); } } /** * Is called if a subscribed object changes * @param {string} id * @param {ioBroker.Object | null | undefined} obj */ /*onObjectChange(id, obj) { if (obj) { // The object was changed this.log.debug(`object ${id} changed: ${JSON.stringify(obj)}`); } else { // The object was deleted this.log.debug(`object ${id} deleted`); } }*/ /** * Is called if a subscribed state changes * @param {string} id * @param {ioBroker.State | null | undefined} state */ async onStateChange(id, state) { try { if (state) { if (id == `${this.namespace}` + '.guest.wlan' && this.SETENABLE == true && state.ack === false && this.WLAN3INFO ===true){ this.log.info(`${id} changed: ${state.val} (ack = ${state.ack})`); const val = state.val ? '1' : '0'; const guestwlan = await this.Fb.soapAction(this.Fb, '/upnp/control/wlanconfig3', this.urn + 'WLANConfiguration:3', 'SetEnable', [[1, 'NewEnable', val]]); if (guestwlan['status'] == 200 || guestwlan['result'] == true) { await this.Fb.getGuestWlan(id); //if(state.val == wlanStatus) this.setState('guest.wlan', { val: wlanStatus, ack: true }); }else{ throw {name: `onStateChange ${id}`, message: 'Can not change state' + JSON.stringify(guestwlan)}; } } if (id.includes('disabled') && state.ack === false && this.DISALLOWWANACCESSBYIP === true && this.GETWANACCESSBYIP === true){ this.log.info(`${id} changed: ${state.val} (ack = ${state.ack})`); const ipId = id.replace('.disabled', '') + '.ipaddress'; const ipaddress = await this.getStateAsync(ipId); const val = state.val ? '1' : '0'; this.log.info('ip ' + JSON.stringify(ipaddress.val) + ' ' + val); const DisallowWANAccess = await this.Fb.soapAction(this.Fb, '/upnp/control/x_hostfilter', this.urn + 'X_AVM-DE_HostFilter:1', 'DisallowWANAccessByIP', [[1, 'NewIPv4Address', ipaddress.val],[2, 'NewDisallow', val]]); if (DisallowWANAccess['status'] == 200 || DisallowWANAccess['result'] == true) { await this.Fb.getWanAccess(ipaddress, id); //this.setState(id, { val: state.val, ack: true }); }else{ throw {name: `onStateChange ${id}`, message: 'Can not change state' + JSON.stringify(DisallowWANAccess)}; } } if (id == `${this.namespace}` + '.reboot' && this.REBOOT === true){ this.log.info(`${id} changed: ${state.val} (ack = ${state.ack})`); if (state.val === true){ const reboot = await this.Fb.soapAction(this.Fb, '/upnp/control/deviceconfig', this.urn + 'DeviceConfig:1', 'Reboot', null); if (reboot['status'] == 200 || reboot['result'] == true) { this.setState(`${this.namespace}` + '.reboot', { val: false, ack: true }); }else{ this.setState(`${this.namespace}` + '.reboot', { val: false, ack: true }); throw('reboot failure! ' + JSON.stringify(reboot)); } } } } /*if (state) { // The state was changed this.log.info(`system.adapter.${this.namespace}`); this.log.info(`state2 ${id} changed: ${state.val} (ack = ${state.ack})`); } else { // The state was deleted this.log.debug(`state ${id} deleted`); }*/ } catch (error) { this.log.error('onStateChange: ' + JSON.stringify(error)); } } /** * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ... * Using this method requires "common.message" property to be set to true in io-package.json * @param {ioBroker.Message} obj */ async onMessage(obj) { try { if (!obj) return; if (typeof obj === 'object' && obj.message) { const gthis = this; // eslint-disable-next-line no-inner-declarations function reply(result) { gthis.sendTo (obj.from, obj.command, JSON.stringify(result), obj.callback); } switch (obj.command) { case 'discovery':{ this.allDevices = []; let onlyActive, reread; if (typeof obj.message === 'object') { onlyActive = obj.message.onlyActive; reread = obj.message.reread; } if (!obj.callback) return false; if (!reread && this.allDevices.length > 0 && this.allDevices.onlyActive === onlyActive) { reply(this.allDevices); return true; } this.allDevices.onlyActive = onlyActive; const devInfo = { host: this.config.ipaddress, port: '49000', sslPort: null, uid: this.config.username, pwd: <PASSWORD>.config.<PASSWORD> }; const Fb = new fb.Fb(devInfo, this); let items; if (this.GETPATH == true){ items = await Fb.getDeviceList(this, null, Fb); if (items == null){ return; } for (let i = 0; i < items.length; i++) { const active = items[i]['Active']; if (!onlyActive || active) { this.allDevices.push ({ name: items[i]['HostName'], ip: items[i]['IPAddress'], mac: items[i]['MACAddress'], active: active }); } } } reply(this.allDevices); return true;} default: this.log.warn('Unknown command: ' + obj.command); break; } if (obj.callback) this.sendTo(obj.from, obj.command, obj.message, obj.callback); return true; } } catch (e) { this.showError('onMessage: '+e.message); } } async getDeviceInfo(items, mesh, cfg){ try { //analyse guests let guestCnt = 0; let activeCnt = 0; let inactiveCnt = 0; let blCnt = 0; let wlCnt = 0; let htmlRow = this.HTML_GUEST; let htmlBlRow = this.HTML_GUEST; let htmlFbDevices = this.HTML_FB; let jsonRow = '['; let jsonBlRow = '['; let jsonWlRow = '['; let jsonFbDevices = '['; let jsonFbDevActive = '['; let jsonFbDevInactive = '['; const enabledMeshInfo = this.config.meshinfo; if (!items) return false; if (!mesh) return false; await obj.createFbDeviceObjects(this, items, this.enabled); this.setState('fb-devices.mesh', { val: JSON.stringify(mesh), ack: true }); for (let i = 0; i < items.length; i++) { if (this.enabled == false) break; let deviceType = '-'; if (items[i]['X_AVM-DE_Guest'] == 1){ deviceType = 'guest'; } if (items[i]['Active'] == 1){ // active devices jsonFbDevActive += this.createJSONTableRow(activeCnt, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress'], 'Active', items[i]['Active'], 'Type', deviceType]); //jsonFbDevActive += createJSONFbDeviceRow(activeCnt, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress'], items[i]['Active'], deviceType); activeCnt += 1; }else{ jsonFbDevInactive += this.createJSONTableRow(inactiveCnt, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress'], 'Active', items[i]['Active'], 'Type', deviceType]); //jsonFbDevInactive += createJSONFbDeviceRow(inactiveCnt, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress'], items[i]['Active'], deviceType); inactiveCnt += 1; } if (items[i]['X_AVM-DE_Guest'] == 1 && items[i]['Active'] == 1){ //active guests htmlRow += this.createHTMLTableRow([items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']]); //guests table //htmlRow += createHTMLGuestRow(items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); jsonRow += this.createJSONTableRow(guestCnt, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress']]); //jsonRow += createJSONGuestRow(guestCnt, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); this.log.debug('getDeviceInfo: ' + items[i]['HostName'] + ' ' + items[i]['IPAddress'] + ' ' + items[i]['MACAddress']); guestCnt += 1; } let foundwl = false; for(let w = 0; w < cfg.wl.length; w++) { if (cfg.wl[w].white_macaddress == items[i]['MACAddress']){ foundwl = true; break; } } if (foundwl == false && items[i]['X_AVM-DE_Guest'] == 0){ //&& items[i]['Active'] == 1 deviceType = 'blacklist'; htmlBlRow += this.createHTMLTableRow([items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']]); //htmlBlRow += createHTMLGuestRow(items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); jsonBlRow += this.createJSONTableRow(blCnt, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress']]); //jsonBlRow += createJSONGuestRow(blCnt, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); blCnt += 1; } if (foundwl == true ){ deviceType = 'whitelist'; //htmlWlRow += createHTMLGuestRow(items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); jsonWlRow += this.createJSONTableRow(wlCnt, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress']]); //jsonWlRow += createJSONGuestRow(wlCnt, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress']); wlCnt += 1; } htmlFbDevices += this.createHTMLTableRow([items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress'], items[i]['Active'], deviceType]); //htmlFbDevices += createHTMLFbDeviceRow(items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress'], items[i]['Active'], deviceType); jsonFbDevices += this.createJSONTableRow(i, ['Hostname', items[i]['HostName'], 'IP-Address', items[i]['IPAddress'], 'MAC-Address', items[i]['MACAddress'], 'Active', items[i]['Active'], 'Type', deviceType]); //jsonFbDevices += createJSONFbDeviceRow(i, items[i]['HostName'], items[i]['IPAddress'], items[i]['MACAddress'], items[i]['Active'], deviceType); let hostName = items[i]['HostName']; if (hostName.includes('.')){ hostName = hostName.replace('.', '-'); } this.setState('fb-devices.' + hostName + '.macaddress', { val: items[i]['MACAddress'], ack: true }); this.setState('fb-devices.' + hostName + '.ipaddress', { val: items[i]['IPAddress'], ack: true }); this.setState('fb-devices.' + hostName + '.active', { val: items[i]['Active'], ack: true }); this.setState('fb-devices.' + hostName + '.interfacetype', { val: items[i]['InterfaceType'], ack: true }); this.setState('fb-devices.' + hostName + '.speed', { val: items[i]['X_AVM-DE_Speed'], ack: true }); this.setState('fb-devices.' + hostName + '.guest', { val: items[i]['X_AVM-DE_Guest'], ack: true }); this.setState('fb-devices.' + hostName + '.whitelist', { val: foundwl, ack: true }); this.setState('fb-devices.' + hostName + '.blacklist', { val: ! (foundwl && items[i]['X_AVM-DE_Guest']), ack: true }); for (let k=0; k<cfg.members.length; k++){ if (cfg.members[k].macaddress == items[i]['MACAddress']){ this.setState(cfg.members[k].familymember + '.speed', { val: items[i]['X_AVM-DE_Speed'], ack: true }); break; } } //Get mesh info for device if (this.GETMESHPATH != null && this.GETMESHPATH == true && enabledMeshInfo == true){ if (mesh != null){ let meshdevice = mesh.find(el => el.device_mac_address === items[i]['MACAddress']); if (meshdevice == null) { meshdevice = mesh.find(el => el.device_name === items[i]['HostName']); } if (meshdevice != null) { this.setState('fb-devices.' + hostName + '.meshstate', { val: true, ack: true }); for (let ni = 0; ni < meshdevice['node_interfaces'].length; ni++) { const nInterface = meshdevice['node_interfaces'][ni]; let interfaceName = nInterface['name']; if (interfaceName == '') interfaceName = nInterface['type']; //this.log.info('createMeshObjects2 ' + JSON.stringify(items[i])); obj.createMeshObjects(this, [items[i]], ni, this.enabled); /*const hostname = items[i]['HostName']; if (hostname.includes('.')){ hostName = hostname.replace('.', '-'); }*/ this.setState('fb-devices.' + hostName + '.' + ni + '.name', { val: nInterface['name'], ack: true }); this.setState('fb-devices.' + hostName + '.' + ni + '.type', { val: nInterface['type'], ack: true }); //this.setState('fb-devices.' + hostName + '.' + ni + '.security', { val: nInterface['security'], ack: true }); if (nInterface['node_links'].length > 0){ //filter empty interfaces let link = ''; let data_rate_rx = 0; let data_rate_tx = 0; for (let nl = 0; nl < nInterface['node_links'].length; nl++) { const nodelinks = nInterface['node_links'][nl]; if ( nodelinks['state'] == 'CONNECTED'){ if (nodelinks['node_1_uid'] != meshdevice['uid']){ //Top connection const node1 = mesh.find(el => el.uid === nodelinks['node_1_uid']); if (link != '') link += ','; link += node1['device_name']; } if (nodelinks['node_2_uid'] != meshdevice['uid']){ //Down connection const node1 = mesh.find(el => el.uid === nodelinks['node_2_uid']); if (link != '') link += ','; link += node1['device_name']; } data_rate_rx = nodelinks['cur_data_rate_rx'] / 1000; data_rate_tx = nodelinks['cur_data_rate_tx'] / 1000; } this.setState('fb-devices.' + hostName + '.' + ni + '.link', { val: link, ack: true }); this.setState('fb-devices.' + hostName + '.' + ni + '.rx_rcpi', { val: nodelinks['rx_rcpi'], ack: true }); this.setState('fb-devices.' + hostName + '.' + ni + '.cur_data_rate_rx', { val: data_rate_rx, ack: true }); this.setState('fb-devices.' + hostName + '.' + ni + '.cur_data_rate_tx', { val: data_rate_tx, ack: true }); } } } }else{ this.setState('fb-devices.' + hostName + '.meshstate', { val: false, ack: true }); this.setState('fb-devices.' + hostName + '.' + '0' + '.cur_data_rate_rx', { val: 0, ack: true }); this.setState('fb-devices.' + hostName + '.' + '0' + '.cur_data_rate_tx', { val: 0, ack: true }); this.setState('fb-devices.' + hostName + '.' + '0' + '.rx_rcpi', { val: 0, ack: true }); } } } } jsonRow += ']'; jsonBlRow += ']'; jsonWlRow += ']'; htmlRow += this.HTML_END; htmlBlRow += this.HTML_END; htmlFbDevices += this.HTML_END; jsonFbDevices += ']'; jsonFbDevActive += ']'; jsonFbDevInactive += ']'; this.setState('fb-devices.count', { val: items.length, ack: true }); this.setState('fb-devices.json', { val: jsonFbDevices, ack: true }); this.setState('fb-devices.jsonActive', { val: jsonFbDevActive, ack: true }); this.setState('fb-devices.jsonInactive', { val: jsonFbDevInactive, ack: true }); this.setState('fb-devices.html', { val: htmlFbDevices, ack: true }); this.setState('fb-devices.active', { val: activeCnt, ack: true }); this.setState('fb-devices.inactive', { val: inactiveCnt, ack: true }); this.setState('guest.listHtml', { val: htmlRow, ack: true }); this.setState('guest.listJson', { val: jsonRow, ack: true }); this.setState('guest.count', { val: guestCnt, ack: true }); this.setState('guest.presence', { val: guestCnt == 0 ? false : true, ack: true }); this.setState('activeDevices', { val: activeCnt, ack: true }); this.setState('blacklist.count', { val: blCnt, ack: true }); this.setState('blacklist.listHtml', { val: htmlBlRow, ack: true }); this.setState('blacklist.listJson', { val: jsonBlRow, ack: true }); this.setState('whitelist.json', { val: jsonWlRow, ack: true }); this.setState('whitelist.count', { val: cfg.wl.length, ack: true }); if (guestCnt > 0) { this.setState('guest', { val: true, ack: true }); }else { this.setState('guest', { val: false, ack: true }); } this.log.debug('getDeviceInfo activeCnt: '+ activeCnt); if (blCnt > 0) { this.setState('blacklist', { val: true, ack: true }); }else { this.setState('blacklist', { val: false, ack: true }); } this.log.debug('getDeviceInfo blCnt: '+ blCnt); return true; } catch (error) { this.log.error('getDeviceInfo: ' + error); return false; } } async getActive(index, cfg, memberRow, dnow, presence){ try { //if (enabled === false) return null; const member = memberRow.familymember; const mac = memberRow.macaddress; const ip = memberRow.ipaddress; if (memberRow.useip == undefined || ip == undefined){ throw('Please edit configuration in admin view and save it! Some items (use ip, ip-address) are missing'); }else{ let hostEntry = null; if (memberRow.useip == false){ if (mac != ''){ hostEntry = await this.Fb.soapAction(this.Fb, '/upnp/control/hosts', this.urn + 'Hosts:1', 'GetSpecificHostEntry', [[1, 'NewMACAddress', memberRow.macaddress]], true); }else{ throw('The configured mac-address for member ' + member + ' is empty. Please insert a valid mac-address!'); } }else{ if (this.GETBYIP == true && ip != ''){ hostEntry = await this.Fb.soapAction(this.Fb, '/upnp/control/hosts', this.urn + 'Hosts:1', 'X_AVM-DE_GetSpecificHostEntryByIP', [[1, 'NewIPAddress', memberRow.ipaddress]], true); }else{ if (memberRow.ipaddress == '') { throw('The configured ip-address for ' + member + ' is empty. Please insert a valid ip-address!'); } } } if(this.enabled == false) { return presence; } if(hostEntry && hostEntry.result === false){ if (hostEntry[0].errorMsg.errorDescription == 'NoSuchEntryInArray'){ throw('mac or ipaddress from member ' + member + ' not found in fritzbox device list'); } else if (hostEntry[0].errorMsg.errorDescription == 'Invalid Args'){ throw('invalid arguments for member ' + member); } else { throw('member ' + member + ': ' + hostEntry.errorMsg.errorDescription); } } if (hostEntry && hostEntry.result == true){ const newActive = hostEntry.resultData['NewActive'] == 1 ? true : false; //let memberActive = false; let comming = null; let going = null; const curVal = await this.getStateAsync(member + '.presence'); //.then(function(curVal){ //actual member state if (curVal && curVal.val != null){ //calculation of '.since' const diff = Math.round((dnow - new Date(curVal.lc))/1000/60); if (curVal.val == true){ this.setState(member + '.present.since', { val: diff, ack: true }); this.setState(member + '.absent.since', { val: 0, ack: true }); } if (curVal.val == false){ this.setState(member + '.absent.since', { val: diff, ack: true }); this.setState(member + '.present.since', { val: 0, ack: true }); } //analyse member presence if (newActive == true){ //member = true //memberActive = true; presence.one = true; presence.allAbsence = false; if (presence.presentMembers == '') { presence.presentMembers += member; }else{ presence.presentMembers += ', ' + member; } if (curVal.val == false){ //signal changing to true this.log.info('newActive ' + member + ' ' + newActive); this.setState(member, { val: true, ack: true }); this.setState(member + '.presence', { val: true, ack: true }); this.setState(member + '.comming', { val: dnow, ack: true }); comming = dnow; } if (curVal.val == null){ this.log.warn('Member value is null! Value set to true'); this.setState(member, { val: true, ack: true }); this.setState(member + '.presence', { val: true, ack: true }); } }else{ //member = false presence.all = false; presence.oneAbsence = true; if (presence.absentMembers == '') { presence.absentMembers += member; }else{ presence.absentMembers += ', ' + member; } if (curVal.val == true){ //signal changing to false this.log.info('newActive ' + member + ' ' + newActive); this.setState(member, { val: false, ack: true }); this.setState(member + '.presence', { val: false, ack: true }); this.setState(member + '.going', { val: dnow, ack: true }); going = dnow; } if (curVal.val == null){ this.log.warn('Member value is null! Value set to false'); this.setState(member, { val: false, ack: true }); this.setState(member + '.presence', { val: false, ack: true }); } } this.setState(member, { val: newActive, ack: true }); this.setState(member + '.presence', { val: newActive, ack: true }); presence.val = newActive; const comming1 = await this.getStateAsync(member + '.comming'); comming = comming1.val; const going1 = await this.getStateAsync(member + '.going'); going = going1.val; if (comming1.val == null) { comming = new Date(curVal.lc); this.setState(member + '.comming', { val: comming, ack: true }); } if (going1.val == null) { going = new Date(curVal.lc); this.setState(member + '.going', { val: going, ack: true }); } this.jsonTab += this.createJSONTableRow(index, ['Name', member, 'Active', newActive, 'Kommt', dateFormat(comming, cfg.dateFormat), 'Geht', dateFormat(going, cfg.dateFormat)]); this.htmlTab += this.createHTMLTableRow([member, (newActive ? '<div class="mdui-green-bg mdui-state mdui-card">anwesend</div>' : '<div class="mdui-red-bg mdui-state mdui-card">abwesend</div>'), dateFormat(comming, cfg.dateFormat), dateFormat(going, cfg.dateFormat)]); return presence; }else{ throw('object ' + member + ' does not exist!'); } } } } catch(error){ this.log.error('getActive: ' + JSON.stringify(error)); return null; } } getHistoryTable(gthis, cfg, memb, start, end){ return new Promise((resolve, reject) => { gthis.sendTo(cfg.history, 'getHistory', { id: `${gthis.namespace}` + '.' + memb, options:{ end: end, start: start, ignoreNull: true, aggregate: 'onchange' } }, function (result1) { if (result1 == null) { reject ('can not read history from ' + memb + ' ' + result1.error); }else{ const cntActualDay = result1.result.length; gthis.log.debug('history cntActualDay: ' + cntActualDay); gthis.sendTo(cfg.history, 'getHistory', { id: `${gthis.namespace}` + '.' + memb, options: { end: end, count: cntActualDay+1, ignoreNull: true, aggregate: 'onchange' } }, function (result) { if (result == null) { reject('can not read history from ' + memb + ' ' + result.error); }else{ resolve(result); } }); } }); }); } async checkPresence(cfg){ try { const midnight = new Date(); //Date of day change midnight.setHours(0,0,0); const dnow = new Date(); //Actual date and time for comparison // functions for family members this.jsonTab = '['; this.htmlTab = this.HTML; let count = 0; let length = cfg.members.length; //Correction if not all members enabled for (let k = 0; k < cfg.members.length; k++){ if (cfg.members[k].enabled == false) length--; } let presence = {val: null, all: true, one: false, presentMembers: '', absentMembers: '', allAbsence: true, oneAbsence: false }; for (let k = 0; k < cfg.members.length; k++) { //loop over family members if (this.enabled == false) break; //cancel if disabled over unload const memberRow = cfg.members[k]; //Row from family members table const member = memberRow.familymember; if (memberRow.enabled == true && this.GETBYMAC == true){ //member enabled in configuration settings and service is supported const curVal = await this.getActive(count, cfg, memberRow, dnow, presence); const dPoint = await this.getObjectAsync(`${this.namespace}` + '.' + member); count++; presence = curVal; if (curVal != null){ //get history data let present = Math.round((dnow - midnight)/1000/60); //time from midnight to now = max. present time let absent = 0; const end = new Date().getTime(); const start = midnight.getTime(); let lastVal = null; let lastValCheck = false; //const gthis = this; const memb = member; if (cfg.history != ''){ if (dPoint.common.custom != undefined && dPoint.common.custom[cfg.history].enabled == true){ try { const result = await this.getHistoryTable(this, cfg, memb, start, end); if (!result) throw('Can not get history items of member ' + memb); //this.log.info('history: ' + JSON.stringify(result)); let htmlHistory = this.HTML_HISTORY; let jsonHistory = '['; let bfirstFalse = false; let firstFalse = midnight; this.log.debug('history ' + memb + ' cntHistory: ' + result.result.length); let cnt = 0; let i = 0; for (let iv = 0; iv < result.result.length; iv++) { if (this.enabled == false) break; if (result.result[0].ts < result.result[result.result.length-1].ts){ //Workaround for history sorting behaviour i = iv; }else{ i = result.result.length - iv - 1; } if (result.result[i].val != null ){ const hdate = dateFormat(new Date(result.result[i].ts), cfg.dateformat); htmlHistory += this.createHTMLTableRow([(result.result[i].val ? '<div class="mdui-green-bg mdui-state mdui-card">anwesend</div>' : '<div class="mdui-red-bg mdui-state mdui-card">abwesend</div>'), dateFormat(hdate, cfg.dateFormat)]); jsonHistory += this.createJSONTableRow(cnt, ['Active', result.result[i].val, 'Date', dateFormat(hdate, cfg.dateFormat)]); cnt += 1; const hTime = new Date(result.result[i].ts); //this.log.debug('history ' + memb + ' ' + result.result[i].val + ' time: ' + hTime); if (hTime >= midnight.getTime()){ if (lastVal == null){ //if no lastVal exists lastVal = curVal.val; lastValCheck = true; this.log.debug(memb + ': No history item before this day is available'); }else{ if (lastVal == false && lastValCheck == true){ absent = Math.round((hTime - midnight.getTime())/1000/60); lastValCheck = false; } if (result.result[i].val == false){ if (bfirstFalse == false){ firstFalse = new Date(result.result[i].ts); bfirstFalse = true; } } if (result.result[i].val == true){ if (bfirstFalse == true){ bfirstFalse = false; absent += Math.round((hTime - firstFalse.getTime())/1000/60); } } } }else{ this.log.debug('history lastVal ' + memb + ' ' + result.result[i].val + ' time: ' + hTime); lastVal = result.result[i].val; lastValCheck = true; } } } if (bfirstFalse == true){ bfirstFalse = false; absent += Math.round((dnow - firstFalse.getTime())/1000/60); } present -= absent; this.setState(memb + '.present.sum_day', { val: present, ack: true }); this.setState(memb + '.absent.sum_day', { val: absent, ack: true }); jsonHistory += ']'; htmlHistory += this.HTML_END; this.setState(memb + '.history', { val: jsonHistory, ack: true }); this.setState(memb + '.historyHtml', { val: htmlHistory, ack: true }); } catch (ex) { throw('checkPresence history: ' + ex.message); } }else{ this.log.info('History from ' + memb + ' not enabled'); } }else{//history enabled this.setState(memb + '.history', { val: 'disabled', ack: true }); this.setState(memb + '.historyHtml', { val: 'disabled', ack: true }); this.setState(memb + '.present.sum_day', { val: -1, ack: true }); this.setState(memb + '.absent.sum_day', { val: -1, ack: true }); } }else{ this.log.warn('can not get active state from member ' + member); break; } if (count == length) { this.jsonTab += ']'; this.htmlTab += this.HTML_END; this.setState('json', { val: this.jsonTab, ack: true }); this.setState('html', { val: this.htmlTab, ack: true }); this.setState('presenceAll', { val: presence.all, ack: true }); this.setState('absenceAll', { val: presence.allAbsence, ack: true }); this.setState('presence', { val: presence.one, ack: true }); this.setState('absence', { val: presence.oneAbsence, ack: true }); this.setState('absentMembers', { val: presence.absentMembers, ack: true }); this.setState('presentMembers', { val: presence.presentMembers, ack: true }); return true; } }//enabled in configuration settings }// for end } catch (error) { this.log.error('getActive: ' + JSON.stringify(error)); } } } if (module.parent) { // Export the constructor in compact mode /** * @param {Partial<ioBroker.AdapterOptions>} [options={}] */ module.exports = (options) => new FbCheckpresence(options); } else { // otherwise start the instance directly new FbCheckpresence(); }<file_sep>/admin/index_m.js 'use strict'; /*eslint no-undef: "error"*/ /*eslint-env browser*/ let familymembers = []; let whitelist = []; let arr; let dlgMembers; let dlgWl; let secret; let active = false; if (typeof _ !== 'function') _ = translateWord; function encrypt(key, value) { let result = ''; for (let i = 0; i < value.length; ++i) { result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i)); } return result; } function decrypt(key, value) { let result = ''; for (let i = 0; i < value.length; ++i) { result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i)); } return result; } function search(event) { const input = document.getElementById(event.currentTarget.id); const filter = input.value.toUpperCase(); let table = null; if( event.currentTarget.id == 'searchFam'){ table = document.getElementById('tabFam'); }else{ table = document.getElementById('tabWL'); } const tr = table.getElementsByTagName('tr'); // Loop through all table rows, and hide those who don't match the search query for (let i = 0; i < tr.length; i++) { const td = tr[i].getElementsByTagName('td')[1]; //search in second column if (td) { const txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ''; } else { tr[i].style.display = 'none'; } } } } /*function setValue(id, value, onChange) { const $value = $('#' + id + '.value'); if ($value.attr('type') === 'checkbox') { $value.prop('checked', value).change(function() { onChange(); }); } else { const val = $value.data('crypt') && value ? decrypt(secret, value) : value; $value.val(val).change(function() { onChange(); }).keyup(function() { // Check that only numbers entered if ($(this).hasClass('number')) { const val = $(this).val(); if (val) { let newVal = ''; for (let i = 0; i < val.length; i++) { if (val[i] >= '0' && val[i] <= '9') { newVal += val[i]; } } if (val != newVal) $(this).val(newVal); } } onChange(); }); } }*/ async function getHistoryInstances(settings){ let histArr =[]; histArr = await getHistoryAdapter(histArr); histArr = await getSqlAdapter(histArr); histArr = await getInfluxdbAdapter(histArr); let selectElement = document.getElementById('history'); const cnfHistory = settings.history; let option = document.createElement('option'); option.text = 'disabled'; option.value = ''; selectElement.options[0] = option; for (let i = 0; i < histArr.length; i++) { option = document.createElement('option'); const str = histArr[i].name.replace('system.adapter.', ''); option.text = str; option.value = str; selectElement.options[i+1] = option; if (cnfHistory == str){ selectElement.selectedIndex = i+1; } } $('select').select(); } function getHistoryAdapter (hist) { return new Promise((resolve, reject) => { getAdapterInstances('history', function (arr) { //let hist=[]; for (let i = 0; i < arr.length; i++) { hist.push({'name' : arr[i]._id}); } resolve(hist); }); }); } function getSqlAdapter (hist) { return new Promise((resolve, reject) => { getAdapterInstances('sql', function (arr) { //let hist=[]; for (let i = 0; i < arr.length; i++) { hist.push({'name' : arr[i]._id}); } resolve(hist); }); }); } function getInfluxdbAdapter (hist) { return new Promise((resolve, reject) => { getAdapterInstances('influxdb', function (arr) { //let hist=[]; for (let i = 0; i < arr.length; i++) { hist.push({'name' : arr[i]._id}); } resolve(hist); }); }); } // Every Field is Valid? function chkValidity() { let valid = true; $('.value').each(function() { const $key = $(this); const element = document.getElementById($key.attr('id')); if ($key.attr('type') !== 'checkbox' && !element.checkValidity()) { valid = false; } }); return valid; } // This will be called by the admin adapter when the settings page loads function load(settings, onChange) { if (!settings) return; $('.hideOnLoad').hide(); $('.showOnLoad').show(); familymembers = settings.familymembers || []; whitelist = settings.whitelist || []; values2table('values', familymembers, onChange, tableOnReady); values2table('whitevalues', whitelist, onChange); getHistoryInstances(settings); // if adapter is alive socket.emit('getState', 'system.adapter.' + adapter + '.' + instance + '.alive', function (err, state) { active = (state && state.val); if (!active) { const content = '<div class="modal-content"><h4>' + _('Error') + '</h4><p>' + _('You have to start your ioBroker.' + adapter + ' adapter before you can use this function!') + '</p></div><div class="modal-footer"><a href="#!" class="modal-close waves-effect waves-green btn-flat">Close</a></div>'; $('.modal').append(content); $('.modal').modal(); return; } const g_onChange = onChange; sendTo(adapter + '.' + instance, 'discovery', { onlyActive: true, reread: false }, function (result) { try { arr = JSON.parse(result); if (arr.error) { const content = '<div class="modal-content"><h4>' + _('Error') + '</h4><p>' + arr.error.message + '</p></div><div class="modal-footer"><a href="#!" class="modal-close waves-effect waves-green btn-flat">Close</a></div>'; $('.modal').append(content); $('.modal').modal(); return; } let bodyFam = ''; let bodyWl = ''; if (!arr.length) { const content = '<div class="modal-content"><h4>' + _('Add a familymember') + '</h4><p>' + _('Cannot find any device') + '</p></div><div class="modal-footer"><a href="#!" class="modal-close waves-effect waves-green btn-flat">Close</a></div>'; $('.modal').append(content); $('.modal').modal(); return; } else { dlgMembers= '<div class="input-field col s12">' + '<i id="icon" class="material-icons prefix">search</i>' + '<input id="searchFam" class="validate" type="text" onkeyup="search(event)">' + '<label for="searchFam">' + _('Search for device') + '..' + '</label>' + '</div>' + '<div col s12>' + '<table class="responsive-table highlight" id="tabFam">' + '<thead>' + '<tr class="grey darken-3 white-text">' + '<th class="valign-wrapper"><label><input type="checkbox" class="filled-in" id="select-all" onclick="select-all(event)"/><span></span></label></th>' + '<th class="left-align">' + 'Hostname' + '</th>' + '<th class="center-align">' + _('MAC address') + '</th>' + '<th class="center-align">' + _('IP address') + '</th>' + //'<th class="valign-wrapper"><label><input type="checkbox" class="filled-in" id="insertIP" /><span class="white-text" style="font-size: 13px">' + _('IP address') + '</span></th>' + '</tr>' + '</thead>' + '<tbody>'; dlgWl= '<div class="input-field col s12">' + '<i id="icon" class="material-icons prefix">search</i>' + '<input id="searchWL" class="validate" type="text" onkeyup="search(event)">' + '<label for="searchWL">' + _('Search for device') + '..' + '</label>' + '</div>' + '<div col s12>' + '<table class="responsive-table striped" id="tabWL">' + '<thead>' + '<tr class="grey darken-3 white-text">' + '<th class="valign-wrapper"><label><input type="checkbox" class="filled-in" id="select-all2" onclick="select-all(event)"/><span></span></label></th>' + '<th class="left-align">' + 'Hostname' + '</th>' + '<th class="center-align">' + _('MAC address') + '</th>' + '</tr>' + '</thead>' + '<tbody>'; arr.forEach(function (element) { let chkVal = ''; for(let i=0; i < whitelist.length; i++){ if (element.mac == whitelist[i].white_macaddress){ chkVal = 'checked'; break; } } let chkVal2 = false; for(let i=0; i < familymembers.length; i++){ if(familymembers[i].useip == false){ if (element.mac == familymembers[i].macaddress){ chkVal2 = 'checked'; break; } }else{ if (element.ip == familymembers[i].ipaddress){ chkVal2 = 'checked'; break; } } } bodyFam += '<tr class="add-device" ' + 'data-macaddress="' + (element.mac || '') + '" ' + 'data-familymember="' + (element.name || '').replace(/"/g, '\"') + '" ' + 'data-ip="' + (element.ip || '').replace(/"/g, '\"') + '">' + '<td class="valign-wrapper"><label><input class="filled-in" type="checkbox" name="chkFM"' + chkVal2 + ' /><span></span></label></td>' + '<td>' + element.name + '</td>' + '<td class="center">' + element.mac + '</td>' + '<td class="center">' + element.ip + '</td>' + '</tr>'; bodyWl += '<tr ' + 'data-white_macaddress="' + (element.mac || '') + '" ' + 'data-white_device="' + (element.name || '').replace(/"/g, '\"') + '">' + '<td class="valign-wrapper"><label><input class="filled-in" type="checkbox" name="chkWL"' + chkVal + ' /><span></span></label></td>' + '<td>' + element.name + '</td>' + '<td class="center">' + element.mac + '</td>' + '</tr>'; }); bodyFam += '</tbody></table></div>'; const contentFam = '<div class="modal-content translate">' + '<h5 class="blue">' + _('Add family member') + '</h5>' + '<p>' + dlgMembers + bodyFam + '</p>' + '</div>' + '<div class="modal-footer blue lighten-2">' + '<!--a href="#!" class="modal-action modal-close btn-default waves-effect waves-light btn-flat"><i class="material-icons left">close</i>' + _('Close') + '</a-->' + '<button type="button" class="modal-action modal-close waves-effect waves-light btn-flat" id="save"><i class="material-icons left">save</i>' + _('Add') + '</button>' + '<button type="button" class="modal-close btn-default offset-s2 waves-effect waves-light btn-flat"><i class="material-icons left">close</i>' + _('Close') + '</button>' + '</div>'; bodyWl += '</tbody></table></div>'; const contentWl = '<div class="modal-content col s12 translate">' + '<h5 class="blue" style="margin-top:20px">' + _('Add a device') + '</h5>' + '<p>' + dlgWl + bodyWl + '</p>' + '</div>' + '<div class="modal-footer blue lighten-2">' + '<button type="button" class="modal-action modal-close waves-effect waves-light btn-flat" id="save1"><i class="material-icons left">save</i>' + _('Add') + '</button>' + '<button type="button" class="modal-close btn-default offset-s2 waves-effect waves-light btn-flat"><i class="material-icons left">close</i>' + _('Close') + '</button>' + '</div>'; $('#dlgFam').append(contentFam); $('#dlgFam').modal({dismissible: false,}); $('#dlgWL').append(contentWl); $('#dlgWL').modal({dismissible: false,}); } $('#save1').click(function () { // Loop through all checkboxes, and add all devices with selected checkboxes whitelist = []; //clear whitelist $('#tabWL input[type=checkbox]:checked').each(function () { const row = $(this).closest('tr')[0]; const mac = $(row).data('white_macaddress'); const device = $(row).data('white_device'); if (device != null){ whitelist.push({white_macaddress: mac, white_device: device}); values2table('whitevalues', whitelist, g_onChange); g_onChange(true); } }); }); $('#save').click(function () { // Loop through all checkboxes, and add all devices with selected checkboxes const devices = []; //clear whitelist //familymembers = settings.familymembers || []; familymembers = table2values('values') || []; //const insertIP = $('#insertIP'); $('#tabFam input[type=checkbox]:checked').each(function () { const row = $(this).closest('tr')[0]; var ip = $(row).data('ip'); var mac = $(row).data('macaddress'); let device = $(row).data('familymember'); if (device != undefined){ let comment = device; let enabled = true; let useip = false; for (let i=0; i<familymembers.length; i++){ useip = familymembers[i].useip; if(useip == false){ if (familymembers[i].macaddress == mac){ device = familymembers[i].familymember; enabled = familymembers[i].enabled; comment = familymembers[i].comment; break; } }else{ if (familymembers[i].ipaddress == ip){ device = familymembers[i].familymember; enabled = familymembers[i].enabled; comment = familymembers[i].comment; break; } } } devices.push({macaddress: mac, ipaddress: ip, enabled: enabled, familymember: device, useip: useip, comment: comment}); } }); values2table('values', devices, g_onChange, tableOnReady); g_onChange(true); }); $('#select-all').click(function(event) { if(this.checked) { // Iterate each checkbox const checkboxes = document.querySelectorAll('input[name="chkFM"]'); for (let i=0; i<checkboxes.length; i++) { checkboxes[i].checked = true; } } else { const checkboxes = document.querySelectorAll('input[name="chkFM"]'); for (let i=0; i<checkboxes.length; i++) { checkboxes[i].checked = false; } /*$(':checkbox').each(function() { this.checked = false; });*/ } }); $('#select-all2').click(function(event) { if(this.checked) { // Iterate each checkbox const checkboxes = document.querySelectorAll('input[name="chkWL"]'); for (let i=0; i<checkboxes.length; i++) { checkboxes[i].checked = true; } /*$(':checkbox').each(function() { this.checked = true; });*/ } else { const checkboxes = document.querySelectorAll('input[name="chkWL"]'); for (let i=0; i<checkboxes.length; i++) { checkboxes[i].checked = false; } /*$(':checkbox').each(function() { this.checked = false; });*/ } }); } catch (e) { const content = '<div class="modal-content"><h4>Error</h4><p>Cannot find any device</p></div><div class="modal-footer"><a href="#!" class="modal-close waves-effect waves-green btn-flat">Close</a></div>'; $('.modal').append(content); $('.modal').modal(); } }); }); // example: select elements with id=key and class=value and insert value socket.emit('getObject', 'system.config', function (err, obj) { secret = (obj.native ? obj.native.secret : '') || '<KEY>'; //for (var key in settings) { //if (settings.hasOwnProperty(key)) setValue(key, settings[key], onChange); //} $('.value').each(function () { const $key = $(this); const id = $key.attr('id'); if ($key.attr('type') === 'checkbox') { // do not call onChange direct, because onChange could expect some arguments $key.prop('checked', settings[id]).on('change', function(){ if (chkValidity()) { onChange(); } else { onChange(false); } }); //=> onChange()) } else { let val; if ($key.data('crypt') =='1'){ val = decrypt(secret, settings[id]) ; } else{ val = settings[id]; } $key.val(val).on('change', function(){ //=> onChange()) if (chkValidity()) { onChange(); } else { onChange(false); } }).on('keyup', function(){ //=> onChange()) if (chkValidity()) { onChange(); } else { onChange(false); } }); } }); onChange(false); // reinitialize all the Materialize labels on the page if you are dynamically adding inputs: if (M) M.updateTextFields(); $('select').select(); }); } //dependency between fbdevices and meshinfo //checking of meshinfo only valid if fbdevices are selected $(document).ready(function(){ $('#meshinfo').change(function() { if(this.checked == true) { const x = document.getElementById('fbdevices'); x.checked = true; } }); $('#fbdevices').change(function() { if(this.checked == false) { const x = document.getElementById('meshinfo'); x.checked = false; } }); if (M) M.updateTextFields(); }); function beforeOpen(){ // check checkboxes const fm = table2values('values') || []; for(let i = 0; i<fm.length;i++){ $('#tabFam input[type=checkbox]').each(function () { const row = $(this).closest('tr')[0]; const mac = $(row).data('macaddress'); if(mac != 'undefined'){ if(mac == fm[i].macaddress){ $(this).prop('checked', true); } } }); } // Open add dialog const elems = document.getElementById('dlgFam'); const instance = M.Modal.getInstance(elems); instance.open(); //instance.destroy(); } function tableOnReady() { $('#values .table-values .values-buttons[data-command="delete"]').on('click', function () { const id = $(this).data('index'); const mac = $('#values .values-input[data-name="macaddress"][data-index="' + id + '"]').val(); $('#tabFam input[type=checkbox]:checked').each(function () { const row = $(this).closest('tr')[0]; const dlgMac = $(row).data('macaddress'); if (mac == dlgMac){ $(this).prop('checked', false); } }); }); } // This will be called by the admin adapter when the user presses the save button function save(callback) { // example: select elements with class=value and build settings object const obj = {}; $('.value').each(function () { const $this = $(this); switch ($this.attr('type')) { case 'checkbox': obj[$this.attr('id')] = $this.prop('checked'); break; case 'number': obj[$this.attr('id')] = parseInt($this.val(), 10); break; default: obj[$this.attr('id')] = $this.data('crypt') && $this.val() ? encrypt(secret, $this.val()) : $this.val(); break; } }); // Get table obj.familymembers = table2values('values'); obj.whitelist = table2values('whitevalues'); callback(obj); }
72167e4580fb1095806b2728ffbe246d793b31bb
[ "JavaScript" ]
3
JavaScript
epcos71/ioBroker.fb-checkpresence
f48e6226c08bc8b2ca5745aac3ab1c4b150a5666
3c1b96f7a53faab69d50bb551c6e1c99f5abbec6
refs/heads/master
<repo_name>VidyaDinesh11/PyDSWS_Wrapper<file_sep>/README.md # PyDSWS Python wrapper for the Datastream Web Services API (DSWS) Connect to the Thomson Reuters Datastream database via Datastream Web Services. You need to have a Datastream subscription and a username/password to use this package. Please note that this is an official package and it is still under development. For support on this package, please contact Thomson Reuters team. The package has basic functionality and most of the error handling still needs to be done. Requirements: ---------------------------------------------------------------------------------- Install Python 3 on your machine Packages to be installed: -------------------------------- pandas requests datetime pytz Package Installation: ---------------------------------------------------------------------------------- pip install PyDSWS_Wrapper ---------------------------------------------------------------------------------- ### Usage ---------------------------------------------------------------------------------- 1) import the 'PyDSWS_Wrapper' package 2) authenticate with your username and password ---------------------------------------------------------------------------------- 3) Using get_data ---------------------------------------------------------------------------------- import PyDSWS_Wrapper as pw ds = pw.DataStream(username='XXXXXXX', password='<PASSWORD>') df = ds.get_data(tickers='VOD', fields=['P'], start ='2017-01-01', end = '-5D') print(df) For static data: ---------------------------------------------------------------------------------- df = ds.get_data(tickers='VOD', fields=['VO','P'], start='2017-01-01', kind = 0) Output: Instrument Datatype Value Dates 0 VOD VO 36773.80 2017-01-01 1 VOD P 199.85 2017-01-01 For time series: ---------------------------------------------------------------------------------- df = ds.get_data(tickers='VOD', fields=['P','MV','VO'], start='-10D', end='-0D', freq='D') Output: Instrument VOD Field P MV VO Date 2017-11-21 229.75 61283.06 55100.4 2017-11-22 228.75 61016.34 79602.5 2017-11-23 225.40 60122.75 35724.1 2017-11-24 225.50 60149.44 42918.0 2017-11-27 224.60 59909.38 50355.3 2017-11-28 226.45 60402.83 49027.0 2017-11-29 225.25 60082.74 61618.1 2017-11-30 224.30 59829.99 95423.4 2017-12-01 224.00 59749.96 54855.4 ---------------------------------------------------------------------------------- 4) Using get_bundle_data ---------------------------------------------------------------------------------- ds = DataStream("xxxxxxx", "xxxxxxxxx") reqs =[] reqs.append(ds.post_user_request(tickers='VOD',fields=['VO','P'],start='2017-01-01', kind = 0))#ststic data reqs.append(ds.post_user_request(tickers='U:BAC', fields=['P'], start='1975-01-01', end='0D', freq = "Y"))#Timeseries data df = ds.get_bundle_data(bundleRequest=reqs) print(df) Instrument Datatype Value Dates 0 VOD VO 36773.80 2017-01-01 1 VOD P 199.85 2017-01-01, Instrument Dates U:BAC Field P 0 1975-01-01 0.9375 1 1976-01-01 1.2188 2 1977-01-01 1.5313 3 1978-01-01 1.4219 ..... ---------------------------------------------------------------------------------- 5) Retrieving data for a List ---------------------------------------------------------------------------------- import PyDSWS_Wrapper as pw dst = pw pw.DataStream(username="xxxxx", password="<PASSWORD>") df = ds.get_data(tickers="LS&PCOMP|L",fields =["NAME"]) print(df) Note that we should specify |L in tickers, for List. Output: Instrument Datatype Value Dates 0 891399 NAME AMAZON.COM 2019-01-21 1 916328 NAME ABBOTT LABORATORIES 2019-01-21 2 545101 NAME AES 2019-01-21 3 777953 NAME ABIOMED 2019-01-21 ...... ---------------------------------------------------------------------------------- 6) Retrieving data for Expressions ---------------------------------------------------------------------------------- import PyDSWS_Wrapper as pw dst = pw pw.DataStream(username="xxxxx", password="<PASSWORD>") df = ds.get_data(tickers='PCH#(VOD(P),3M)|E', start="20181101",end="-1M", freq="M") print(df) Note that we should specify |E in tickers, for Expressions. Output: Instrument Dates PCH#(VOD(P), 3M) Field 0 2018-11-01 -17.82 1 2018-12-01 0.91 Using Symbol substitution: ------------------------------------------- df =ds.get_data(tickers='VOD, U:JPM',fields=['PCH#(X(P),-3M)'], freq="M") Instrument Dates VOD U:JPM Field PCH#(X(P),-3M) PCH#(X(P),-3M) 0 2018-02-07 -3.07 14.2987 1 2018-03-07 -10.25 9.6635 2 2018-04-07 -13.85 0.6923 3 2018-05-07 0.24 -3.1009 4 2018-06-07 -8.30 -3.4254 5 2018-07-07 -6.37 -4.6109 ...... ---------------------------------------------------------------------------------- 7) Retrieving data for NDOR ---------------------------------------------------------------------------------- df = ds.get_data(tickers='USGDP…D',fields=['DS.NDOR1']) Output: Instrument Datatype Value 0 USGDP...D DS.NDOR1_DATE 2019-02-11 1 USGDP...D DS.NDOR1_DATE_LATEST 2019-02-19 2 USGDP...D DS.NDOR1_TIME_GMT NA 3 USGDP...D DS.NDOR1_DATE_FLAG Estimated 4 USGDP...D DS.NDOR1_REF_PERIOD 2018-11-15 5 USGDP...D DS.NDOR1_TYPE NewValue ---------------------------------------------------------------------------------- 8) Retrievung data for Point In Time ---------------------------------------------------------------------------------- df = ds.get_data(tickers='CNCONPRCF(DREL1)', fields=['(X)'], start='-2Y', end='0D', freq='M') Output: Instrument Dates CNCONPRCF(DREL1) Field (X) 0 2017-02-15 2017-03-24 1 2017-03-15 2017-04-21 2 2017-04-15 2017-05-19 3 2017-05-15 2017-06-23 4 2017-06-15 2017-07-21 5 2017-07-15 2017-08-18 ---------------------------------------------------------------------------------- 9) Usage Stats ---------------------------------------------------------------------------------- df = ds.get_data(tickers='STATS', fields=['DS.USERSTATS'], kind=0) Output: Instrument Datatype Value Dates 0 STATS User ZDSM042 2019-02-08 1 STATS Hits 147 2019-02-08 2 STATS Requests 113 2019-02-08 3 STATS Datatypes 660 2019-02-08 4 STATS Datapoints 23213 2019-02-08 5 STATS Start Date 2019-02-01 2019-02-08 6 STATS End Date 2019-02-28 2019-02-08 <file_sep>/DS_Requests/README.md # DS_Requests - helper class for Python DSWS Wrapper List of Classes: 1. IProperties - class t collect the properties of Instrument 2. DataType 3. Date 4. Instrument 5. Properties - class to collect properties of the request. Environment from where the data should be retrived can be set. 6. TokenValue Classes to form Requests: 7. TokenRequest 8. DataRequest <file_sep>/PyDSWS_Wrapper/DS_Response.py # -*- coding: utf-8 -*- """ Created on Tue Jan 1 19:51:02 2019 @author: <NAME> """ import requests import json import pandas as pd import datetime import pytz import DS_Requests as DSReq #-------------------------------------------------------------------------------------- class DataStream: url = "http://product.datastream.com/DSWSClient/V1/DSService.svc/rest/" username = "" password = "" token = None dataSource = None #--------Constructor --------------------------- def __init__(self, username, password, dataSource=None): self.username = username self.password = <PASSWORD> self.dataSource = dataSource self.token = self._get_token() #------------------------------------------------------- #------------------------------------------------------- def post_user_request(self, tickers, fields=[], start='', end='', freq='', kind=1): index = tickers.rfind('|') try: if index == -1: instrument = DSReq.Instrument(tickers, None) else: #Get all the properties of the instrument props = [] if tickers[index+1:].rfind(',') != -1: propList = tickers[index+1:].split(',') for eachProp in propList: props.append(DSReq.IProperties(eachProp, True)) else: props.append(DSReq.IProperties(tickers[index+1:], True)) #Get the no of instruments given in the request instList = tickers[0:index].split(',') if len(instList) > 40: raise Exception('Too many instruments in single request') else: instrument = DSReq.Instrument(tickers[0:index], props) datypes=[] if len(fields) > 0: if len(fields) > 20: raise Exception('Too mant datatypes in single request') else: for eachDtype in fields: datypes.append(DSReq.DataType(eachDtype)) else: datypes.append(DSReq.DataType(fields)) date = DSReq.Date(start, freq, end, kind) request = {"Instrument":instrument,"DataTypes":datypes,"Date":date} return request except Exception as err: print(err) return None def get_data(self, tickers, fields=[], start='', end='', freq='', kind=1): getData_url = self.url + "GetData" raw_dataRequest = "" json_dataRequest = "" json_Response = "" try: req = self.post_user_request(tickers, fields, start, end, freq, kind) datarequest = DSReq.DataRequest() if (self.token == None): raise Exception("Invalid Token Value") else: raw_dataRequest = datarequest.get_Request(req, self.dataSource, self.token) #print(raw_dataRequest) if (raw_dataRequest != ""): json_dataRequest = self._json_Request(raw_dataRequest) #Post the requests to get response in json format json_Response = requests.post(getData_url, json=json_dataRequest).json() #print(json_Response) #format the JSON response into readable table response_dataframe = self._format_Response(json_Response['DataResponse']) return response_dataframe except json.JSONDecodeError: print("JSON decoder error while get_data request") return None except: print("get_data : Unexpected error") return None def get_bundle_data(self, bundleRequest=[]): getDataBundle_url = self.url + "GetDataBundle" raw_dataRequest = "" json_dataRequest = "" json_Response = "" try: datarequest = DSReq.DataRequest() if (self.token == None): raise Exception("Invalid Token Value") else: raw_dataRequest = datarequest.get_bundle_Request(bundleRequest, self.dataSource, self.token) #print(raw_dataRequest) if (raw_dataRequest != ""): json_dataRequest = self._json_Request(raw_dataRequest) #Post the requests to get response in json format json_Response = requests.post(getDataBundle_url, json=json_dataRequest).json() #print(json_Response) response_dataframe = self._format_bundle_response(json_Response) return response_dataframe except json.JSONDecodeError: print("JSON decoder error while get_data request") return None except: print("get_bundle_data : Unexpected error") return None #------------------------------------------------------- #------------------------------------------------------- #-------Helper Functions--------------------------------------------------- def _get_token(self): token_url = self.url + "GetToken" try: tokenReq = DSReq.TokenRequest(self.username, self.password, self.dataSource) raw_tokenReq = tokenReq.get_TokenRequest() json_tokenReq = self._json_Request(raw_tokenReq) #Post the token request to get response in json format json_Response = requests.post(token_url, json=json_tokenReq).json() return json_Response["TokenValue"] except json.JSONDecodeError: print("JSON decoder error while posting Token request") return None except: print("Token Request : Unexpected error") return None def _json_Request(self, raw_text): #convert the dictionary (raw text) to json text first jsonText = json.dumps(raw_text) byteTemp = bytes(jsonText,'utf-8') byteTemp = jsonText.encode('utf-8') #convert the json Text to json formatted Request jsonRequest = json.loads(byteTemp) return jsonRequest def _get_Date(self, jsonDate): d = jsonDate[6:-7] d = float(d) ndate = datetime.datetime(1970,1,1) + datetime.timedelta(seconds=float(d)/1000) utcdate = pytz.UTC.fromutc(ndate).strftime('%Y-%m-%d') return utcdate def _get_DatatypeValues(self, jsonDTValues): df = pd.DataFrame() multiIndex = False valDict = {"Instrument":[],"Datatype":[],"Value":[]} for item in jsonDTValues: datatype = item['DataType'] for i in item['SymbolValues']: instrument = i['Symbol'] valDict["Datatype"].append(datatype) valDict["Instrument"].append(instrument) values = i['Value'] valType = i['Type'] colNames = (instrument,datatype) df[colNames] = None """Handling all possible types of data as per DSSymbolResponseValueType""" if valType in [7, 8, 10, 11, 12, 13, 14, 15, 16]: """These value types return an array The array can be of double, int, string or Object""" rowCount = df.shape[0] valLen = len(values) """If no of Values is < rowcount, append None to values""" if rowCount > valLen: for i in range(rowCount - valLen): values.append(None) """ Check if the array of Object is JSON dates and convert""" for x in range(0, len(values)): values[x] = self._get_Date(values[x]) if str(values[x]).find('/Date(') != -1 else values[x] df[colNames] = values multiIndex = True elif valType in [1, 2, 3, 5, 6]: """These value types return single value""" valDict["Value"].append(values) multiIndex = False else: if valType == 4: """value type 4 return single JSON date value, which needs conversion""" values = self._get_Date(values) valDict["Value"].append(values) multiIndex = False elif valType == 9: """value type 4 return array of JSON date values, which needs conversion""" multiIndex = True date_array = [] for eachVal in values: date_array.append(self._get_Date(eachVal)) df[colNames] = values else: if valType == 0: """Error Returned""" multiIndex = False valDict["Value"].append(values) if multiIndex: df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Instrument', 'Field']) if not multiIndex: indexLen = range(len(valDict['Instrument'])) newdf = pd.DataFrame(data=valDict,columns=["Instrument", "Datatype", "Value"], index=indexLen) return newdf return df def _format_Response(self, response_json): # If dates is not available, the request is not constructed correctly response_json = dict(response_json) if 'Dates' in response_json.keys(): dates_converted = [] if response_json['Dates'] != None: dates = response_json['Dates'] for d in dates: dates_converted.append(self._get_Date(d)) else: return 'Error - please check instruments and parameters (time series or static)' # Loop through the values in the response dataframe = self._get_DatatypeValues(response_json['DataTypeValues']) if (len(dates_converted) == len(dataframe.index)): if (len(dates_converted) > 1): dataframe.insert(loc = 0, column = 'Dates', value = dates_converted) elif (len(dates_converted) == 1): dataframe['Dates'] = dates_converted[0] return dataframe def _format_bundle_response(self,response_json): formattedResp = [] for eachDataResponse in response_json['DataResponses']: df = self._format_Response(eachDataResponse) formattedResp.append(df) return formattedResp #-------------------------------------------------------------------------------------- #ds = DataStream("ZDSM042", "alpha893") #reqs =[] #reqs.append(ds.post_user_request(tickers='VOD', fields=['VO','P'], start='2017-01-01', kind = 0)) #reqs.append(ds.post_user_request(tickers='U:BAC', fields=['P'], start='1975-01-01', end='0D', freq = "Y")) #df = ds.get_bundle_data(bundleRequest=reqs) #df = ds.get_data(tickers='PCH#(VOD(P),3M)|E', start="20181101",end="-1M", freq="M") #df = ds.get_data(tickers='STATS', fields=['DS.USERSTATS'], kind=0) #df = ds.get_data(tickers='CNCONPRCF(DREL1)', fields=['(X)'], start='-2Y', end='0D', freq='M') #df = ds.get_data(tickers='USGDP…D',fields=['DS.NDOR1']) #df =ds.get_data(tickers='USGDP...D',fields=['(X)'], start='1960-01-01',end='2018-01-01', freq='M') #df = ds.get_data('ASX200I',['PI'],start='2018-12-18',end='-3D') #df =ds.get_data(tickers='VOD, U:JPM',fields=['PCH#(X(P),-3M)'], freq="M") #print(df) <file_sep>/DS_Requests/DS_Requests/DS_Requests.py # -*- coding: utf-8 -*- """ Created on Sat Dec 29 00:55:39 2018 @author: <NAME> """ #-------------------------------------------------------------------------------- class IProperties: """Properties of Instruments""" Key = "" Value = True def __init__(self, key, value): self.Key = key self.Value = value #-------------------------------------------------------------------------------- class DataType: """Class used to store Datatype""" datatype = "" def __init__(self, value): self.datatype = value #-------------------------------------------------------------------------------- class Date: """Date parameters of a Data Request""" Start = "" End = "" Frequency = "" Kind = 0 def __init__(self, startDate = "", freq = "D", endDate = "", kind = 0): self.Start = startDate self.End = endDate self.Frequency = freq self.Kind = kind #-------------------------------------------------------------------------------- class Instrument(IProperties): """Instrument and its Properties""" instrument = "" properties = [IProperties] def __init__(self, inst, props): self.instrument = inst self.properties = props #-------------------------------------------------------------------------------- class Properties: """Properties of Data Request""" """Captures the data source given in the Request,it can be "PROD"/ "STAGING" / "QA". If not specified, a Default source is taken""" Key = "Source" Value = "" def __init__(self, value): self.Value = value #-------------------------------------------------------------------------------- #-------------------------------------------------------------------------------- #-------------------------------------------------------------------------------- """Classes that help to form the Request in RAW JSON format""" class TokenRequest(Properties): password = "" username = "" def __init__(self, uname, pword, source = None): self.username = uname self.password = pword self.Key = "Source" self.Value = source def get_TokenRequest(self): tokenReq = {"Password":<PASSWORD>,"Properties":[],"UserName":self.username} if self.Value == None or self.Value == "": tokenReq["Properties"] = None else: tokenReq["Properties"].append({"Key":self.Key,"Value":self.Value}) return tokenReq #-------------------------------------------------------------------------------- class DataRequest: hints = {"E":"IsExpression", "L":"IsList"} singleReq = dict multipleReqs = dict def __init__(self): self.singleReq = {"DataRequest":{},"Properties":None,"TokenValue":""} self.multipleReqs = {"DataRequests":[],"Properties":None,"TokenValue":""} def get_bundle_Request(self, reqs, source=None, token=""): self.multipleReqs["DataRequests"] = [] for eachReq in reqs: dataReq = {"DataTypes":[],"Instrument":{}, "Date":{}, "Tag":None} dataReq["DataTypes"] = self._set_Datatypes(eachReq["DataTypes"]) dataReq["Date"] = self._set_Date(eachReq["Date"]) dataReq["Instrument"] = self._set_Instrument(eachReq["Instrument"]) self.multipleReqs["DataRequests"].append(dataReq) self.multipleReqs["Properties"] = {"Key":"Source","Value":source} self.multipleReqs["TokenValue"] = token return self.multipleReqs def get_Request(self, req, source=None, token=""): dataReq = {"DataTypes":[],"Instrument":{}, "Date":{}, "Tag":None} dataReq["DataTypes"] = self._set_Datatypes(req["DataTypes"]) dataReq["Date"] = self._set_Date(req["Date"]) dataReq["Instrument"] = self._set_Instrument(req["Instrument"]) self.singleReq["DataRequest"] = dataReq self.singleReq["Properties"] = {"Key":"Source","Value":source} self.singleReq["TokenValue"] = token return self.singleReq #--------------------HELPER FUNCTIONS-------------------------------------- def _set_Datatypes(self, dtypes=None): """List the Datatypes""" datatypes = [] for eachDtype in dtypes: if eachDtype.datatype == None: continue else: datatypes.append({"Properties":None, "Value":eachDtype.datatype}) return datatypes def _set_Instrument(self, inst): propties=[] if inst.properties == None: return {"Properties":None,"Value":inst.instrument} else: for eachPrpty in inst.properties: propties.append({"Key":DataRequest.hints[eachPrpty.Key],"Value":True}) return {"Properties":propties,"Value":inst.instrument} def _set_Date(self, dt): return {"End":dt.End,"Frequency":dt.Frequency,"Kind":dt.Kind,"Start":dt.Start} #-------------------------------------------------------------------------- ##Datatypes #dat =[] #dat.append(DataType("PH")) #dat.append(DataType("PL")) #dat.append(DataType("P")) ##Instrument #Props = [IProperties("E", True)] #ins = Instrument("VOD", Props) #ins2 = Instrument("U:F", Props) ##Date #dt = Date(startDate = "20180101",freq= "M",kind = 1) # #dr = DataRequest() #req1 = {"DataTypes":dat,"Instrument":ins,"Date":dt} #req2 = {"DataTypes":dat,"Instrument":ins2,"Date":dt} #datareq = dr.get_Request(req=req1, source='PROD',token='token') #print(datareq) <file_sep>/DS_Requests/DS_Requests/__init__.py # -*- coding: utf-8 -*- """ PyDSWS_Wrapper @author: <NAME> init file """ from .DS_Requests import *
ee48a386c82088c97e3c1bae10c253f152586ec7
[ "Markdown", "Python" ]
5
Markdown
VidyaDinesh11/PyDSWS_Wrapper
9f5a3d18d3eed6b139c563057a35000f1a2da3de
11bdf9e486bac501d07b0fe84a2b4745007cde4e
refs/heads/master
<file_sep>using Microsoft.AspNet.Identity.EntityFramework; using PCC.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace PCC.Contexts { public class PCCDBContext : DbContext { public DbSet<Weapon> Weapons { get; set; } public PCCDBContext() : base("PCCDBContext") { } public static PCCDBContext Create() { return new PCCDBContext(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PCC.Models { public class Weapon : Item { public string DamageS { get; set; } // Damage @ Small Sized Weapon public string DamageM { get; set; } // Damage @ Medium Sized Weapon public string Critical { get; set; } public string Type { get; set; } // Typically: B - Bludgeoning, P - Piercing, S - Slashing or some combination public string Special { get; set; } public string Source { get; set; } } }<file_sep>namespace PCC.Migrations { using System; using System.Data.Entity.Migrations; public partial class ModifiedValueToNewClass : DbMigration { public override void Up() { AddColumn("dbo.Weapons", "Value_Gold", c => c.Int(nullable: false)); AddColumn("dbo.Weapons", "Value_Silver", c => c.Int(nullable: false)); AddColumn("dbo.Weapons", "Value_Copper", c => c.Int(nullable: false)); DropColumn("dbo.Weapons", "Value"); } public override void Down() { AddColumn("dbo.Weapons", "Value", c => c.Int(nullable: false)); DropColumn("dbo.Weapons", "Value_Copper"); DropColumn("dbo.Weapons", "Value_Silver"); DropColumn("dbo.Weapons", "Value_Gold"); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace PCC.Models { public class Value { [Display(Name="GP")] public int Gold { get; set; } [Display(Name = "SP")] public int Silver { get; set; } [Display(Name = "CP")] public int Copper { get; set; } } }<file_sep>using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(PCC.Startup))] namespace PCC { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } } <file_sep>namespace PCC.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialWithWeaponClass : DbMigration { public override void Up() { CreateTable( "dbo.Weapons", c => new { Id = c.Int(nullable: false, identity: true), DamageS = c.String(), DamageM = c.String(), Critical = c.String(), Type = c.String(), Special = c.String(), Source = c.String(), Name = c.String(nullable: false), Value = c.Int(nullable: false), Weight = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.Weapons"); } } }
06780b9b419d7d52ba14c19bd1332f3997e88bfb
[ "C#" ]
6
C#
kjensen9/PCC
a26fcea230f5817435387de32b27ce8625c59d2e
334d3dbb802a0a2878901d2c1f4a8185da24991e
refs/heads/master
<repo_name>kleffy/satapps_precision_agriculture<file_sep>/step2_preprocess/data_prep_sar_auto.py import snappy from snappy import ProductIO, GPF, HashMap import os #HashMap = snappy.jpy.get_type('java.util.HashMap') # Get snappy Operators GPF.getDefaultInstance().getOperatorSpiRegistry().loadOperatorSpis() source_path = r'D:\School\Strathclyde\EF_900\Data\SentinelSatData\Rice\S1\prev' dest_path = r'D:\School\Strathclyde\EF_900\Data\SentinelSatData\Rice\S1\prev\preprocessed\\' def write_product(data, file_path, format=None): # allowed format are # GeoTIFF-BigTIFF,HDF5,Snaphu,BEAM-DIMAP,GeoTIFF+XML,PolSARPro,NetCDF-CF,NetCDF-BEAM,ENVI,JP2,Generic Binary BSQ,Gamma,CSV,NetCDF4-CF,GeoTIFF,NetCDF4-BEAM ProductIO.writeProduct(data, file_path, format if format else 'BEAM-DIMAP') def apply_orbit_file(data, datestamp): params = HashMap() orbit = GPF.createProduct('Apply-Orbit-File', params, data) # write_product(orbit, os.path.join(dest_path, '{}_Orb'.format(datestamp))) return orbit def do_calibration(orbit, datestamp): params = HashMap() params.put('outputSigmaBand', False) params.put('outputGammaBand', False) params.put('outputBetaBand', True) calibration = GPF.createProduct('Calibration', params, orbit) # write_product(calibration, os.path.join(dest_path, '{}_Orb_Cal'.format(datestamp))) return calibration def perform_multilook(calibration, datestamp, range_look_number=3, azimuth_look_number=3): params = HashMap() params.put('nRgLooks', range_look_number) params.put('nAzLooks', azimuth_look_number) params.put('outputIntensity', True) params.put('grSquarePixel', True) multilook = GPF.createProduct('Multilook', params, calibration) # write_product(multilook, os.path.join(dest_path, '{}_Orb_Cal_ML'.format(datestamp))) return multilook def perform_terrain_flattening(multilook, datestamp): params = HashMap() params.put('demName', 'SRTM 1Sec HGT') params.put('demResamplingMethod', 'BICUBIC_INTERPOLATION') params.put('oversamplingMultiple', 1.5) params.put('additionalOverlap', 0.1) terrain = GPF.createProduct('Terrain-Flattening', params, multilook) # write_product(terrain, os.path.join(dest_path, '{}_Orb_Cal_ML_TF'.format(datestamp))) return terrain def dem_coregistration(terrain, datestamp): params = HashMap() params.put('demName', 'SRTM 1Sec HGT') params.put('demResamplingMethod', 'BICUBIC_INTERPOLATION') # not sure if BILINEAR_INTERPOLATION would produce anything different # worth checking params.put('resamplingType', 'BICUBIC_INTERPOLATION') params.put('tileExtensionPercent', 100) params.put('maskOutAreaWithoutElevation', True) coregistered = GPF.createProduct('DEM-Assisted-Coregistration', params, terrain) write_product(coregistered, os.path.join(dest_path, '{}_Orb_Cal_ML_TF_Stack'.format(datestamp))) return coregistered def speckle_reduction(data, datestamp): params = HashMap() params.put('filter', 'Lee Sigma') params.put('enl', 4.0) params.put('numLooksStr', '4') params.put('windowSize', '9x9') params.put('sigmaStr', '0.9') params.put('targetWindowSizeStr', '5x5') speckle = GPF.createProduct('Speckle-Filter', params, data) # write_product(speckle, os.path.join(dest_path, '{}_Orb_Cal_ML_TF_Stack_Spk'.format(datestamp))) return speckle def ellipsoid_correction(speckle, datestamp): params = HashMap() params.put('imgResamplingMethod', 'BILINEAR_INTERPOLATION') params.put('mapProjection', 'WGS84(DD)') ec = GPF.createProduct('Ellipsoid-Correction-GG', params, speckle) write_product(ec, os.path.join(dest_path, '{}_Orb_Cal_ML_TF_Stack_Spk_EC'.format(datestamp))) write_product(ec, os.path.join(dest_path, '{}_Orb_Cal_ML_TF_Stack_Spk_EC'.format(datestamp)), format='GeoTIFF') return ec def process(file): data = ProductIO.readProduct(os.path.join(input, file)) # get the end date from the file name and get first 8 substring as YYYYmmdd datestamp = file.split('_')[4][:8] orbit = apply_orbit_file(data, datestamp) calibration = do_calibration(orbit, datestamp) multilook = perform_multilook(calibration, datestamp) terrain = perform_terrain_flattening(multilook, datestamp) # coregistered = dem_coregistration(terrain, datestamp) speckle = speckle_reduction(terrain, datestamp) final = ellipsoid_correction(speckle, datestamp) print('finished') return True def set_path(): os.path.dirname(os.path.dirname(__file__)) path = os.path.join(os.getcwd()) os.chdir(path) return path def main(): path = set_path() files = [f for f in os.listdir(source_path) if f.endswith('.zip')] for file in files: status = process(file) if __name__ == '__main__': main()
f732b54cfd03382e270b35c585c3523f8b856d96
[ "Python" ]
1
Python
kleffy/satapps_precision_agriculture
0fd548de1cddc52c174f00aa484734438af10f4e
bb599b6a2374c8d04359174dccda8a6dba7f96ab
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace ConsoleApp { public class Package { public int Id { get; set; } public decimal Cost { get; set; } } public class MyCollection { public void GetElements() { ArrayList arrLi = new ArrayList(); arrLi.Add(1); arrLi.Add(new Package { Id = 1, Cost = 12.23m }); arrLi.Add("bilel"); } } } <file_sep>using System; namespace Algo { public class NumberOfPairsAlgo { public static int numberOfPairs(int n) { int i1 = 5; int i2 = 2; Console.WriteLine("i" + i1 / i2); // Stores the count of pairs int count = 0; // Set the two pointers int i = 1, j = n - 1; while (i < j) { // Check if the sum of // pairs is equal to N if (i + j == n) { // Increase the count // of pairs count++; } // Move to the next pair i++; j--; } return count; } } } <file_sep>. Create a FizzBuzz() method that prints out the numbers 1 through 100, separated by newlines. 2. Instead of numbers divisible by 3, the method should output "Fizz". 3. Instead of numbers divisible by 5, the method should output "Buzz". 4. Instead of numbers divisible by 3 and 5, the method should output "FizzBuzz".<file_sep>using Algo; using Moq; using NUnit.Framework; namespace TU { internal class SubArrayWithGivenSumTest { [Test] [Description(" Get Sub array ith given sum")] public void Algo_SubArrayWithGivenSum() { //arrange var mockAlgoSubArray = new Mock<SubArrayWithGivenSum>(); int[] iarray = new int[] { 1, 2, 3 }; var expectedResult = new int[] { 2 }; mockAlgoSubArray.Setup(_ => _.GetSubArrayWithGivenSum(iarray, 2)).Returns(expectedResult); //act var sut = mockAlgoSubArray.Object.GetSubArrayWithGivenSum(iarray, 2); //assert Assert.AreEqual(sut, expectedResult); } } }<file_sep>using System; using System.Collections.Generic; namespace Algo { public class PrimeNumberService { private bool IsPrimeNumber(int? number) { var isPrime = true; if (number < 2) isPrime = false; if (number % 2 == 0) isPrime = false; if (number == 2) isPrime = true; var sqrValue = Math.Floor(Math.Sqrt(number.Value)); for (int i = 3; i < sqrValue - 1; i += 2) { if (number % i == 0) isPrime = false; } return isPrime; } public virtual IEnumerable<int> GetPrimeNumbers(int? number) { if (number < 2) throw new ArgumentOutOfRangeException(); if (number == null) throw new ArgumentNullException(); var results = new List<int>(); while (number > 0) { if (IsPrimeNumber(number)) results.Add(number.Value); number--; } return results; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { class ClosestToZeroAlgo { public static int ClosestToZero(int[] ints) { int ret, posmin = int.MaxValue, negmin = int.MinValue; if (ints.Length == 0 || ints == null) { return 0; } for (int i = 0; i < ints.Length - 1; i++) { if (ints[i] < 0) { if (ints[i] < ints[i + 1]) { negmin = ints[i]; } } if (ints[i] > 0) { if (ints[i] > ints[i + 1]) { posmin = ints[i]; } } } ret = posmin; if (posmin + negmin == 0) { ret = posmin; } return ret; } } } <file_sep>using System; namespace Algo { public class FizzBuzzAlgo { public virtual string[] FizzBuzz(int n) { string[] ret = new string[n + 1]; for (int i = 0; i <= n; i++) { if (i % 3 == 0) { ret[i] = "Fizz"; } else if (i % 5 == 0) { ret[i] = "Buzz"; } else if (i % 3 == 0 && i % 5 == 0) { ret[i] = "Fizz Buzz"; } else { ret[i] = i.ToString(); } } // remove the first element from the array string[] newRet = new string[ret.Length -1 ]; for (var j = 0; j < ret.Length - 1 ; j++) { newRet[j] = ret[j +1]; } return newRet; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Algo { public class ClosestToZero { public virtual int? ClosestTo(IEnumerable<int> collection) { var closest = int.MaxValue; var min = int.MaxValue; if (collection?.Any() == true) { foreach (var x in collection) { var difference = Math.Abs((long)x); if (min > difference) { min = (int)difference; closest = x; } } return closest; } return null; } public virtual int? ClosestLinqTo(IEnumerable<int> collection) { if (collection?.Any() == true) return collection.OrderBy(x => (long)Math.Abs(x)).First(); return null; } } }<file_sep> namespace Algo { public class NumberCaracterAlgo { public static string NumberCaracter() { string str = "aabaa"; int counter = 1; string result = ""; for (var i = 0; i < str.Length; i++) { if (i == str.Length - 1) { if (str[i] != str[i - 1]) { counter = 1; } result += counter.ToString() + str[i]; break; } if (str[i] == str[i + 1]) { counter++; } if (str[i] != str[i + 1]) { result += counter.ToString() + str[i]; counter = 1; } } return result; } } } <file_sep>using System.Collections.Generic; using System.Linq; namespace Algo { public class SubArrayWithGivenSum { public virtual int[] GetSubArrayWithGivenSum(int[] array, int sum) { var retArray = new List<int>(); int sumValue = 0; var idx = 0; while (idx <= array.Length) { if (sumValue < sum) { sumValue += array[idx]; retArray.Add(array[idx]); if (sumValue == sum) return retArray.ToArray(); } else { sumValue = 0; var arr = array.ToList(); if (arr.Count == 0) break; arr.RemoveAt(0); array = arr.ToArray(); retArray.Clear(); idx = -1; } idx++; } return new int[] { -1 }; } } }<file_sep>using System; using System.Diagnostics; using System.Linq; namespace Algo { internal class Program { private static int a, b; public static void Add(int x, int y) { int z = x + y; Console.WriteLine($"Resultat est {z}"); } private static void Main(string[] args) { string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" }; var query = fruits.Select((fruit, index) => new { index, str = fruit.Substring(0, index) }); foreach (var obj in query) { Console.WriteLine($"{obj}"); } var yesterday = DataContext.YesterdayPacKage(); var today = DataContext.ToDayPacKage(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var result = DataContext.GetDifferentCosts(yesterday, today); stopWatch.Stop(); Console.WriteLine($"Time elapsed: {stopWatch.Elapsed}"); foreach (var item in result) { Console.WriteLine($"the result is {item}"); } Console.WriteLine("**********sut***************************************************"); var sarr = new int[] { 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 }; var sut = new SearchService().GetIndexValueBinarySearch(sarr, 5); Console.WriteLine($"sut is {sut}"); Console.WriteLine("**********sut***************************************************"); #region SubArrayWithGivenSum int[] array = new int[2] { 1, 4 }; var sum = 0; var SubArray = new SubArrayWithGivenSum().GetSubArrayWithGivenSum(array, sum); foreach (var item in SubArray) { Console.WriteLine(item); } #endregion SubArrayWithGivenSum Console.WriteLine("***************************************************************"); #region PrimeNumber var num = new PrimeNumberService(); var arr = num.GetPrimeNumbers(20); foreach (var item in arr) { Console.WriteLine(item); } Console.ReadKey(); #endregion PrimeNumber Console.WriteLine("***************************************************************"); Console.ReadKey(); } } }<file_sep>jump search : sorted array array arr[] to be jumped size n and block (to be jumped) , size m. Then <file_sep>using Algo; using NUnit.Framework; using System; namespace TU { /// <summary> /// Test Nombre Premier Service /// </summary> public class TestNombrePremierServic { [Test] [Description("args parameter should not be null")] public void PrimeNumberService_GetPrimeNumbers() { //arrange var moqPrimeNumberService = new PrimeNumberService(); int? number = 3; var expectedResult = new int[] { 3, 2 }; //act var sut = moqPrimeNumberService.GetPrimeNumbers(3); //assert Assert.AreEqual(expectedResult, sut); } [Test] [Description("args parameter should be more than two")] public void PrimeNumberService_GetPrimeNumbers_Throw_ArgumentOutOfRangeException() { //arrange var moqPrimeNumberService = new PrimeNumberService(); var number = 1; var expectedException = new ArgumentOutOfRangeException(); //act var sut = Assert.Throws<ArgumentOutOfRangeException>( () => moqPrimeNumberService.GetPrimeNumbers(1), "Should throw ArgumentOutOfRangeException"); //assert Assert.AreEqual(expectedException.InnerException, sut.InnerException); } [Test] [Description("args parameter should not be null")] public void PrimeNumberService_GetPrimeNumbers_Throw_ArgumentNullException() { //arrange var moqPrimeNumberService = new PrimeNumberService(); int? number = null; var expectedResult = new ArgumentNullException(); //act var sut = Assert.Throws<ArgumentNullException>( () => moqPrimeNumberService.GetPrimeNumbers(null), "should throw ArgumentNullException"); //assert Assert.AreEqual(expectedResult.InnerException, sut.InnerException); } } }<file_sep> using System.IO; namespace Algo { public class LocateUniverseDocument { public static string LocateUniverseFormula() { string path = @"C:\temp\Documents"; string[] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); foreach (var f in filePaths) { if (f.Contains("universe-formula")) { return f; } } return null; } } } <file_sep>using System; using System.Linq; using System.Collections; using ConsoleApp.abstarction; namespace ConsoleApp { class Program { static void Main(string[] args) { Vehicle v ; v = new Bus(); v.Display(); v.Show("Bus"); v.Hot(); v.ShowA(); v.ShowX(); v = new Car(); v.Display(); v.Show("Car"); v = new MotorCycle(); v.Display(); v.Show("MotorCycle"); bool b = false; bool c = b ? !b : b; Console.WriteLine(c); ArrayList arrLi = new ArrayList(); arrLi.Add(1); arrLi.Add(new Package { Id = 1, Cost = 12.23m }); arrLi.Add("bilel"); foreach(var item in arrLi) { Console.WriteLine(item); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApp { public partial class Cost { public int Id { get; set; } public decimal CostTrip { get; set; } } public class Variation : IComparable<Cost> { public int CompareTo(object obj) { if (obj == null) return 1; var cost = obj as Cost; if (cost != null) return this.CompareTo(cost); else throw new ArgumentException("object is not a cost"); } public int CompareTo(Cost other) { throw new NotImplementedException(); } } } <file_sep>problem : pour un tableau arr[] de n elements ,chercher un élement x dans arr<file_sep> using System.Collections.Generic; namespace Algo { public static class StringCalculatorKata { public static int Add(string numbers) { List<int> costs = new List<int>(); var s = costs.Count; var res = 0; if(numbers.Length == 0) { return res ; } string negNumbers= string.Empty; for (int i = 0; i < numbers.Length; i++) { if (numbers[i].ToString().Equals("-")) { negNumbers += $"{numbers[i]} {numbers[i + 1]}" ; } else if (!numbers[i].ToString().Equals(",") && !numbers[i].ToString().Equals("\n")) { res += int.Parse(numbers[i].ToString()); } } if (negNumbers.Length > 0) { throw new System.Exception($"negatives not allowed {negNumbers}"); } return res; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public static class MaximumPointsAlgo { public static int maximumPoints(int k, List<int> costs) { var sum = 0; var counter = 0; for (int i = 0; i < costs.Count; i++) { if (sum < k) { sum += costs[i]; if(sum > k) { sum -= costs[i]; counter++; } } } return k == 1 ? 1 : costs.Count - counter; } } } <file_sep> using System; using System.Collections; using System.Linq; namespace Algo { public class FibonacciNumber { private bool IsFibonacciNumber(int n) { return (Math.Sqrt(n) * Math.Sqrt(n) == n); } public virtual int[] GetFibonacciNumber(int[] array) { var _result = new ArrayList(); if (array?.Any() == true) { for (int i = 0; i < array.Length; i++) { if (IsFibonacciNumber (5 * (array[i] * array[i]) + 4) || IsFibonacciNumber(5 * (array[i] * array[i]) - 4)) _result.Add(array[i]); } return _result.ToArray(typeof(int)) as int[]; } return new int []{-1}; } } } <file_sep> using Algo; using NUnit.Framework; namespace TU { public class FibonacciNumberTest { [Test] public void FibonacciNumber_GetFibonacciNumber() { //arrange var moqFibonacciNumber = new Moq.Mock<FibonacciNumber>(); var expectedResult = new int[] { 8 }; moqFibonacciNumber.Setup(_ => _.GetFibonacciNumber(new int[] { 8 })).Returns(expectedResult); //act var sut = moqFibonacciNumber.Object.GetFibonacciNumber(new int[] { 8 }); //assert Assert.AreEqual(sut, expectedResult); } } } <file_sep>using Algo; using Moq; using NUnit.Framework; namespace TU { class BinarySearchTest { [Test] public void BinarySearchTest_GetIndexValue() { // arrange var arr = new int[It.IsAny<int>()]; var moqBinarySearch = new Moq.Mock<SearchService>(); var exepectedResult = It.IsAny<int>(); moqBinarySearch.Setup(_ => _.GetIndexValueBinarySearch(arr, It.IsAny<int>())).Returns(exepectedResult); //act var sut = moqBinarySearch.Object.GetIndexValueBinarySearch(arr, It.IsAny<int>()); //assert Assert.AreEqual(sut, exepectedResult); } } } <file_sep>using System; namespace Algo { public class SearchService { public virtual int GetIndexLinearSearchNumber(int[] arr, int x) { if (arr.Length <= 0) throw new ArgumentOutOfRangeException(); int index = -1; if (arr.Length > 0) { for (var i = 0; i < arr.Length; i++) { if (arr[i] == x) index = i; } } return index; } public virtual int GetIndexValueBinarySearch(int[] arr, int x) { if (arr.Length <= 0) throw new IndexOutOfRangeException(); var startIndex = (arr.Length + 1)/2; while (startIndex < arr.Length && startIndex > -1) { if (arr[startIndex] == x) return startIndex; if (startIndex == arr.Length -1) startIndex = -1; startIndex ++; } return startIndex; } } } <file_sep> Compare x with the middle element. If x matches with middle element, we return the mid index. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. Else (x is smaller) recur for the left half. <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Algo { public class RotateArray { public virtual int[] GetRotateArray(int[] array, int index) { if (array?.Any() == true || index <= 0) throw new ArgumentNullException(); var _result = new List<int>(); if (index < array.Length) { for (int i = index; i < array.Length; i++) { _result.Add(array[i]); } for (int j = 0; j < index; j++) { _result.Add(array[j]); } } return _result.ToArray(); } } }<file_sep>The first line of the input contains T denoting the number of testcases. First line of eacg test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements. Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2.<file_sep> using Algo; using System; using System.Collections.Generic; namespace AlgoConsole { class Program { static void Main(string[] args) { MaximumPoints(); Console.ReadLine(); } static void TestFizzBuzz() { var fizzBuzz = new FizzBuzzAlgo(); var ret = fizzBuzz.FizzBuzz(7); for (int i = 0; i < ret.Length; i++) { Console.WriteLine(ret[i]); } } static void StringCalculator() { var ret = StringCalculatorKata.Add("1\n2,-3"); Console.WriteLine(ret); } static void MaximumPoints() { List<int> costs = new List<int> { 10, 5, 5, 2, 3 ,1, 4}; // k= 10 n = 5 // List<int> costs = new List<int> { 2, 4, 1, 8, 6 }; //4 int ret = MaximumPointsAlgo.maximumPoints(10, costs); Console.WriteLine(ret); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public class NotDividedNumbersAlgo { public static int[] NotDividedNumbers(int[] diveded, int[] list) { string res = ""; for (var i = 0; i < list.Length - 1; i++) { for (int j = 0; j < diveded.Length; j++) { if (list[i] % diveded[j] != 0) { res += list[i + 1]; break; } } } return list; } } } <file_sep>using System.Collections.Generic; using System.Linq; namespace Algo { public static class DataContext { public static List<Package> YesterdayPacKage() { var packs = new List<Package>(); for(var i=1; i<= 5000000; i++) { packs.Add(new Package { Id = i, Cost= i + 12.25m }); } return packs; } public static List<Package> ToDayPacKage() { var packs = new List<Package>(); for (var i = 1; i <= 5000000 ; i++) { packs.Add(new Package { Id = i, Cost = i + 12.25m }); } packs.Add(new Package { Id = 1, Cost = 12.25m }); return packs; } public static IEnumerable<PackageModel> GetDifferentCosts(List<Package> yesterday, List<Package> today) { var ret = (from y in yesterday join t in today on y.Id equals t.Id where y.Cost != t.Cost select new PackageModel { Id = y.Id, Varaition = y.Cost - t.Cost }); return ret?.Any() == true ? ret : null; } } public class PackageModel { public int Id { get; set; } public decimal Varaition { get; set; } } public class Package { public int Id { get; set; } public decimal Cost { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public class ScanCharAlgo { public static char scanChar(String s) { for (char c = 'A'; c <= 'Z'; c++) { if (AsciiArt.printChar(c) == (s)) { return c; } } return '?'; } class AsciiArt { public static String printChar(char s) { return "S"; } } } } <file_sep>A simple way is to generate Fibonacci numbers until the generated number is greater than or equal to ‘n’. Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). Following is a simple program based on this concept. 1 is a Fibonacci Number 2 is a Fibonacci Number 3 is a Fibonacci Number 4 is a not Fibonacci Number 5 is a Fibonacci Number 6 is a not Fibonacci Number 7 is a not Fibonacci Number 8 is a Fibonacci Number 9 is a not Fibonacci Number 10 is a not Fibonacci Number<file_sep>using Algo; using Moq; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace TU { class LinearSearchTest { [Test] [Description("")] public void LinearTest_IndexOFNumer() { //arrange var moqSearchService = new Moq.Mock<SearchService>(); var expectedResult = Array.IndexOf(new int[It.IsAny<int>()], It.IsAny<int>()); moqSearchService.Setup(_ => _.GetIndexLinearSearchNumber(new int[It.IsAny<int>()], It.IsAny<int>())).Returns(expectedResult); //act var sut = moqSearchService.Object.GetIndexLinearSearchNumber(new int[It.IsAny<int>()], It.IsAny<int>()); //assert Assert.AreEqual(sut, expectedResult); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp.abstarction { public class X { public void ShowX() { Console.WriteLine ("this is X "); } } public class A:X { public void ShowA() { Console.WriteLine("this is A "); } } public abstract class Vehicle:A { public int Id { get; set; } public abstract void Display(); public void Show(string Param) { Console.WriteLine(Param); } public virtual string Hot() { return "Not much is known about this four legged animal!"; } } public class Bus : Vehicle { public override void Display() { Console.WriteLine("Bus"); } public override string Hot() { return "This four legged animal is a Dog!"; } } public class Car : Vehicle { public override void Display() { Console.WriteLine("Car"); } } public class MotorCycle : Vehicle { public override void Display() { Console.WriteLine("MotorCcyle"); } } } <file_sep> Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33 Ouptut: Sum found between indexes 2 and 4 Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7 Ouptut: Sum found between indexes 1 and 4 Input: arr[] = {1, 4}, sum = 0 Output: No subarray found <file_sep>using System; using Algo; using Moq; using NUnit.Framework; namespace TU { public class RotateArrayTest { [Test] public void RotateArray_GetRotateArray() { //arrange var moqRotateArray = new Mock<RotateArray>(); var expectedResult = new int[] { 3, 4, 5, 1, 2 }; moqRotateArray.Setup(_ => _.GetRotateArray(new int[] { 1, 2, 3, 4, 5 }, 2)) .Returns(expectedResult); //act var sut = moqRotateArray.Object.GetRotateArray(new int[] { 1, 2, 3, 4, 5 }, 2); //assert Assert.AreEqual(sut, expectedResult); } [Test] public void RotateArray_Throw_Exception() { //arrange var moqRotateArray = new RotateArray(); var expectedResult = new ArgumentNullException(); //act var sut = Assert.Throws<ArgumentNullException>( () => moqRotateArray.GetRotateArray(null, -1), "should not be null parameters and number should be more than 0"); //act Assert.AreEqual(sut.InnerException, expectedResult.InnerException); } } }<file_sep> namespace Algo { public class ComputeCheckDigitAlgo { public static int ComputeCheckDigit(string identificationNumber) { if (identificationNumber.Length < 1 || identificationNumber.Length > 12) { return -1; } var pairs = 0; var impairs = 0; for (var i = 0; i < identificationNumber.Length; i++) { //pair if (i % 2 == 0) { pairs += int.Parse(identificationNumber[i].ToString()) * 3; } else { impairs += int.Parse(identificationNumber[i].ToString()); } } var result = pairs + impairs; var r = result.ToString(); int.TryParse(r[r.Length - 1].ToString(), out int res); return res != 0 ? (10 - res) : 0; } } } <file_sep>using Algo; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace TU { public class FizzBuzzTest { [Test] public void Fizz_Buzz_FizzBuzz() { //arrange var moqFizzBuzz = new Moq.Mock<FizzBuzzAlgo>(); var expectedResult = new string[] { "1", "2", "Fizz", "4", "Buzz", "Fizz", "7" }; moqFizzBuzz.Setup(e => e.FizzBuzz(7)).Returns(expectedResult); //act var sut = moqFizzBuzz.Object.FizzBuzz(7); //assert Assert.AreEqual(sut, expectedResult); } } } <file_sep>namespace Algo { public class JavanaisAlgo { public static string TranslateJavanais(string text) { var voy = "aeiou"; string result = ""; for (int i = 0; i < text.Length; i++) { for (int j = 0; j < voy.Length; j++) { if (text[i].Equals(voy[j])) { result += "av"; break; } } result += text[i]; } return result; } } } <file_sep>namespace ConsoleApp { using System.Linq; using System.Collections.Generic; class Solution { public static int FindNetworkEndpoint(int startNodeId, int[] fromIds, int[] toIds) { if (toIds.Length <= 0 || toIds.Length > 10000) { return 0; } List<int> toIdsList = toIds.ToList(); List<int> fromIdsList = fromIds.ToList(); bool endFound = false; bool lapEnded = false; bool startSearch = true; int node = startNodeId; int indexNode = int.MinValue; int oldIndex = int.MinValue; while (!endFound && !lapEnded) { if (!startSearch && (node == startNodeId)) { lapEnded = true; indexNode = oldIndex; break; } if (startSearch) { startSearch = false; } if (fromIdsList.Contains(node)) { oldIndex = indexNode; indexNode = fromIdsList.IndexOf(node); node = toIdsList[indexNode]; } else { endFound = true; } } return indexNode; } /* Ignore and do not change the code below */ #region //static void Main(string[] args) //{ // string[] inputs; // int startNodeId = int.Parse(Console.ReadLine()); // int n = int.Parse(Console.ReadLine()); // int[] fromIds = new int[n]; // inputs = Console.ReadLine().Split(' '); // for (int i = 0; i < n; i++) // { // fromIds[i] = int.Parse(inputs[i]); // } // int[] toIds = new int[n]; // inputs = Console.ReadLine().Split(' '); // for (int i = 0; i < n; i++) // { // toIds[i] = int.Parse(inputs[i]); // } // var stdtoutWriter = Console.Out; // Console.SetOut(Console.Error); // int endPointId = FindNetworkEndpoint(startNodeId, fromIds, toIds); // Console.SetOut(stdtoutWriter); // Console.WriteLine(endPointId); //} #endregion } }
94d65656d49ac5fa0829507ed4cb85d3dc90efa0
[ "Markdown", "C#", "Python", "Ruby" ]
39
C#
bkhalifa/Algo
0f3eccd9a4001da5bc8994942c98fa866c1ea7c3
686b26ce3d1b71b9629c8db39832f005c40bd4d0
refs/heads/master
<repo_name>NewbieCoder10/oscillating-squares-NewbieCoder10<file_sep>/docs/api/member-search-index.js memberSearchIndex = [{"p":"edu.cnm.deepdive","c":"Generator","l":"oscillatingSquares(int)"}]<file_sep>/README.md ## Value * Basic implementation: 5 points * Basic unit tests: 5 points * Extra credit: None ## Basic task In this task, you will implement and test a method that constructs and returns an array containing values that follow a very specific sequence: 0, -1, 4, -9, 16, &hellip;. As you can see, the magnitude of each value is the next perfect square in the sequence, but the signs alternate between positive and negative. ### Implementation In the `edu.cnm.deepdive.Generator` class, the `oscillatingSquares` method is declared with the following signature, return type, and modifiers: ```java public static int[] oscillatingSquares(int length) ``` For more method declaration details, see the [Javadoc documentation](docs/api/edu/cnm/deepdive/Generator.html#oscillatingSquares(int)). For the basic task, complete the implementation of this method, according to the following specifications: * The returned array must contain exactly `length` elements. * The value of the element at index position `n` must be equal to (-1)<sup>n</sup>n<sup>2</sup>. For example, ```java Generator.oscillatingSquares(5); ``` would return ``` {0, -1, 4, -9, 16} ``` ### Unit tests For unit testing credit, use JUnit5 to verify your code with the following inputs and expected outputs: | `length` | Expected return value | |:---:|:--------------------:| | `0` | `{}` | | `1` | `{0}` | | `5` | `{0, -1, 4, -9, 16}` | | `7` | `{0, -1, 4, -9, 16, -25, 36}` | | `10` | `{0, -1, 4, -9, 16, -25, 36, -49, 64, -81}` | In evaluating your implementation, we reserve the right to include additional test cases; code that satisfies the requirements stated above should pass all such additional tests. ### Hints * The `Generator.oscillatingSquares` method to be completed is `static`; there is no need to create instances of `Generator` (and arguably no benefit in doing so). * You may find it useful to create one or more additional `static` methods as “helpers”; the problem can be solved without doing so, however. * Don't hesitate to declare any constants (`static final` fields) that you feel might simplify or clarify your code. * The method to be completed includes a `TODO` comment to that effect. * In unit testing, when comparing an array returned from a method to an array of expected values, one of the `assertArrayEquals` methods (in the `org.junit.jupiter.api.Assertions` class) is better suited to the task than any of the `assertEquals` methods. <file_sep>/src/edu/cnm/deepdive/Generator.java package edu.cnm.deepdive; import java.awt.Color; import java.awt.Graphics; /** * This class contains a stub of the {@link #oscillatingSquares(int)} method. Implementation of this * method is included as a practical exam problem of the Deep Dive Coding Java + Android Bootcamp. * * @author <NAME>, Deep Dive Coding */ public class Generator { private Generator() { // NOTE: There is NO need to do anything with this constructor! The methods // you will implement in this class are static; thus, there is no need // to create instances of this class. } /* BASIC PROBLEM */ /** * Creates and returns an <code>int[]</code> containing a sequence of alternating positive and * negative squared values, of the form (-1)<sup>n</sup>n<sup>2</sup>, where n = * 0&hellip;(<code>length</code> - 1). * <p>For example, <code>Generator.oscillatingSquares(5)</code> returns an array containing the * values <code>{0, -1, 4, -9, 16}</code>.</p> * * @param length number of elements in array. * @return generated array of oscillating squares. */ public static int[] oscillatingSquares(int length) { /* This applet draws a red-and-black checkerboard. It is assumed that the size of the applet is 160 by 160 pixels. */ public void paint(Graphics Graphics g) { int row; // Row number, from 0 to 7 int col; // Column number, from 0 to 7 int x,y; // Top-left corner of square for ( row = 0; row < 8; row++ ) { for ( col = 0; col < 8; col++) { x = col * 20; y = row * 20; if ( (row % 2) == (col % 2) ) g.setColor(Color.red); else g.setColor(Color.black); g.fillRect(x, y, 20, 20); } } } } // TODO Replace this line with implementation. }
35c38504ef562c6bdf428b55774c5e7b2f36d341
[ "JavaScript", "Java", "Markdown" ]
3
JavaScript
NewbieCoder10/oscillating-squares-NewbieCoder10
7434c4c922134669f5f164223b1991aa344d25a6
3f0d80a475c60e20079fd1d5f801cceecbe1a60e
refs/heads/master
<repo_name>TomKosse1/Thesis<file_sep>/scripts/features.py import sys import pandas as pd # OPEN 5000 IMDB MOVIE DATASET df = pd.read_csv("C:/Users/Tom/Documents/Informatiekunde/Thesis/data/movie_metadata.csv") # CREATE LIST OF DIRECTORS directorlist = df.director_name.unique().astype(str).tolist() with open("C:/Users/Tom/Documents/Informatiekunde/Thesis/Feature sets/directors.txt", "w") as directorfile: for director in directorlist: directorfile.write(director.lower() + "\n") # CREATE LIST OF ACTORS actors1 = df.actor_1_name.unique().astype(str).tolist() actors2 = df.actor_2_name.unique().astype(str).tolist() actors3 = df.actor_3_name.unique().astype(str).tolist() actorlist = list(set(actors1 + actors2 + actors3)) with open("C:/Users/Tom/Documents/Informatiekunde/Thesis/Feature sets/actors.txt", "w") as actorfile: for actor in actorlist: actorfile.write(actor.lower() + "\n") # CREATE LIST OF TITLES titlelist = df.movie_title.astype(str).tolist() with open("C:/Users/Tom/Documents/Informatiekunde/Thesis/features/titles.txt", "w") as titlefile: for title in titlelist: titlefile.write(title.lower() + "\n") #CREATE LIST OF GENRES genrelist = df.genres.unique().astype(str).tolist() with open("C:/Users/Tom/Documents/Informatiekunde/Thesis/Feature sets/genres.txt", "w") as genrefile: for genre in genrelist: genrefile.write(genre.lower() + "\n") <file_sep>/scripts/analysis.py import glob import csv from collections import OrderedDict from operator import itemgetter def countFeature(label, feature, mode): """Counts all occurences of a certain Feature and Label, order by value Parameter label: 'positive' or 'negative' Parameter feature: 'sentiment', 'actors', 'directors', 'genre' or 'titles' Parameter mode: 'train', 'test' or 'full' Returns dictionary""" path = 'C:\\Users\\Tom\\Documents\\Informatiekunde\\Thesis\\data\\' + mode + '\\' + label + '\\' feature = 'C:\\Users\\Tom\\Documents\\Informatiekunde\\Thesis\\features\\' + feature +'.txt' allFiles = glob.glob(path + "*.txt") featdict = {} for review in allFiles: file = open(review, 'r', encoding='utf8').read().lower() featreader = csv.reader(open(feature, 'r'), delimiter= '\n') for word in featreader: if word[0] in file and word[0] not in featdict: featdict.update({word[0]: 1}) elif word[0] in file and word[0] in featdict: featdict[word[0]] += 1 ordered = OrderedDict(sorted(featdict.items(), key=itemgetter(1), reverse=True)) return ordered def totalCount(dictionary): """Computes total of occurences of a certain Feature Parameter dictionary: dictionary returned by countFeature Returns integer""" count = 0 for key, value in dictionary.items(): count += value return count def removeLowest(dictionary): """Removes all occurences of features that occur less than 5 times in total, order by value Parameter dictionary: dictionary returned by countFeature Returns dictionary""" new_dict = dict(dictionary) for key, value in dictionary.items(): if value < 5: del new_dict[key] new_dict = OrderedDict(sorted(new_dict.items(), key=itemgetter(1), reverse=True)) return new_dict def calcPercentage(dictionary, total): """Computes relative occurences of a certain Feature, order by value Parameter dictionary: dictionary returned by countFeature Parameter total: integer, total number of occurences of an entire feature Returns dictionary""" per_dict = {} for key, value in dictionary.items(): percentage = round((value / total * 100), 2) per_dict.update({key: percentage}) per_dict = OrderedDict(sorted(per_dict.items(), key=itemgetter(1), reverse=True)) return per_dict def excludeNames(neg_dict, pos_dict): """Removes all occurences of Features that appeer in both neg_dict and pos_dict, order by value Parameter neg_dict: dictionary thats returned by countFeature with negative label Parameter pos_dict: dictionary thats returned by countFeature with positive label Returns two dictionaries""" new_neg_dict = dict(neg_dict) new_pos_dict = dict(pos_dict) for key, value in neg_dict.items(): if key in pos_dict: del new_neg_dict[key] del new_pos_dict[key] else: continue neg_ordered = OrderedDict(sorted(new_neg_dict.items(), key=itemgetter(1), reverse=True)) pos_ordered = OrderedDict(sorted(new_pos_dict.items(), key=itemgetter(1), reverse=True)) return neg_ordered, pos_ordered<file_sep>/scripts/classification.py import csv import glob import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.svm import LinearSVC from sklearn import metrics def textFeature(mode): """ Creates dataframe with Labels and Text per review, File_ID as index Paramater mode: 'train' or 'test' Returns pandas dataframe""" classlist = ['negative', 'positive'] data = pd.DataFrame() for label in classlist: path = 'C:\\Users\\Tom\\Documents\\Informatiekunde\\Thesis\\data\\' + mode + '\\' + label + '\\' allFiles = glob.glob(path + "*.txt") df1 = pd.DataFrame() for review in allFiles: title = review.strip('.txt').split('\\')[-1] text = open(review, 'r', encoding='utf8').read() df = pd.DataFrame({'File': [title], 'Text': [text], 'Label': [label]}).set_index('File') df1 = df1.append(df) data = data.append(df1) return data def clfFeature(feature, mode): """Creates dataframe with certain Feature per review, file_ID as index Parameter feature: 'sentiment', 'actors', 'directors', 'genre' or 'titles' Parameter mode: 'train' or 'text' Returns pandas dataframe""" feature_path = 'C:\\Users\\Tom\\Documents\\Informatiekunde\\Thesis\\features\\' + feature + '.txt' classlist = ['negative', 'positive'] features = pd.DataFrame() for label in classlist: path = 'C:\\Users\\Tom\\Documents\\Informatiekunde\\Thesis\\data\\' + mode + '\\' + label + '\\' allFiles = glob.glob(path + "*.txt") for review in allFiles: title = review.strip('.txt').split('\\')[-1] file = open(review, 'r', encoding='utf8').read().lower() wordlist = [] featreader = csv.reader(open(feature_path, 'r'), delimiter= '\n') for word in featreader: if word[0] in file: wordlist.append(word[0]) df = pd.DataFrame({'File': [title], feature.capitalize(): [', '.join(wordlist)]}).set_index('File') features = features.append(df) return features def createFeatureFrame(mode): """Combines the Text dataframe and the Feature dataframe Parameter mode: 'train' or 'test' Returns pandas dataframe""" text = textFeature(mode) sentiment = clfFeature('sentiment', mode) actors = clfFeature('actors', mode) directors = clfFeature('directors', mode) genre = clfFeature('genre', mode) titles = clfFeature('titles', mode) featureframe = pd.concat([text, sentiment, actors, directors, genre, titles], axis=1) return featureframe def combineFeatures(featurelist): """Combines different feature sets Parameter featurelist: list containing two or more features to combine Possible items in featurelist: 'sentiment', 'actors', 'directors', 'genre' and 'titles' Returns pandas dataframe""" cap_list = [] for item in featurelist: cap_list.append(item.capitalize()) features['Features'] = features[cap_list].apply(lambda x: ', '.join(x), axis=1) return features def performClassification(ngram, df, mode = None, split = 0.9): """Fits data to the model and performs classification for Naive Bayes and Linear SVC Parameter ngram: 1, 2 or 3 Parameter df: the dataframe to be ditted to the model if combined features: created dataframe from combineFeatures if single features: created dataframe from createFeatureFrame, mode needs to be specified Parameter mode: if combined features: default (None) if single feature: 'sentiment', 'actors', 'directors', 'genre' or 'titles' Parameter split: float (percentage of data to be used for training), default = 0.9 Returns computed accuracy, precision, recall and F1 scores""" if type(mode) == str: X = df[mode.capitalize()] else: X = df.Features y = df.Label X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=1, train_size = split) vect = CountVectorizer(analyzer='word', ngram_range=(ngram,ngram)) X_train_dtm = vect.fit_transform(X_train) X_test_dtm = vect.transform(X_test) nb = MultinomialNB() svm = LinearSVC(random_state = 1) nb.fit(X_train_dtm, y_train) svm.fit(X_train_dtm, y_train) nb_pred_class = nb.predict(X_test_dtm) svm_pred_class = svm.predict(X_test_dtm) nb_accuracy = metrics.accuracy_score(y_test, nb_pred_class) nb_precision = metrics.precision_score(y_test, nb_pred_class, pos_label='negative') nb_recall = metrics.recall_score(y_test, nb_pred_class, pos_label='negative') nb_f1 = metrics.f1_score(y_test, nb_pred_class, pos_label='negative') svm_accuracy = metrics.accuracy_score(y_test, svm_pred_class) svm_precision = metrics.precision_score(y_test, svm_pred_class, pos_label='negative') svm_recall = metrics.recall_score(y_test, svm_pred_class, pos_label='negative') svm_f1 = metrics.f1_score(y_test, svm_pred_class, pos_label='negative') print('=====Naive Bayes===== \t =====Linear SVC=====' ) print('Accuracy score \t\t Accuracy score') print(round((nb_accuracy * 100), 1), '\t\t\t', round((svm_accuracy * 100), 1), '\n') print('Precision \t\t Precision') print(round((nb_precision * 100), 1), '\t\t\t', round((svm_precision * 100), 1), '\n') print('Recall \t\t\t Recall') print(round((nb_recall * 100), 1), '\t\t\t', round((svm_recall * 100), 1), '\n') print('F1-score \t\t F1-score') print(round((nb_f1 * 100), 1), '\t\t\t', round((svm_f1 * 100), 1))<file_sep>/README.md FINAL VERSION THESIS The scripts and the 5000 IMDb Movie Dataset (movie_metadata.csv) are uploaded on this github. I have also included the used sentiment lexicon here. Furthermore, I put the pdf in this repository as well. The actual dataset is apparently too big for github. Even when the dataset is divided in smaller parts and compressed in winrar archives. Therefore, I have included the link to the dataset: http://ai.stanford.edu/~amaas/data/sentiment/ Note that in the feature analysis code, I sometimes use 'full' instead of 'train' or 'test'. On my machine, I have combined the train and test set together to create one 'full' dataset. Since I can't upload the dataset from my machine, this has to be done by hand. Simply copy and paste the two parts together and place them in a folder called 'full'. This folder should be in the same repository as the 'train' and 'test' folders.
43fee5c1ea067f51a1f0c55eadbbb1504ab3b7bc
[ "Markdown", "Python" ]
4
Python
TomKosse1/Thesis
f5528006b4a3a5ec421018b201d2bf344064195b
5366102743bc4aaabd304d604dc7945c17ed6bdb
refs/heads/master
<repo_name>kaybarenz/jabref<file_sep>/src/test/java/org/jabref/logic/undo/UndoRedoEventTest.java package org.jabref.logic.undo; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class UndoRedoEventTest { @Test public void givenNoUndoRedoEvent_whenCreateUndoRedoEvent_thenUndoRedoEventCreated() { UndoRedoEvent sut = new UndoRedoEvent(true,"",true,""); } @Test public void givenUndoRedoEventWithcanUndoFalse_whenCallisCanUndo_thenReturnFalse() { UndoRedoEvent sut = new UndoRedoEvent(false,"",true,""); assertEquals(false,sut.isCanUndo()); } @Test public void givenUndoRedoEventWithcanRedoFalse_whenCallisCanRedo_thenReturnFalse() { UndoRedoEvent sut = new UndoRedoEvent(true,"",false,""); assertEquals(false,sut.isCanRedo()); } @Test public void givenUndoRedoEventWithUndoDescriptionString_whenCallgetUndoDescription_thenReturnString() { UndoRedoEvent sut = new UndoRedoEvent(true,"String",true,""); assertEquals("String",sut.getUndoDescription()); } @Test public void givenUndoChangeEventWithRedoDescriptionString_whenCallgetRedoDescription_thenReturnString() { UndoRedoEvent sut = new UndoRedoEvent(true,"",true,"String"); assertEquals("String",sut.getRedoDescription()); } } <file_sep>/src/test/java/org/jabref/logic/logging/LogMessagesTest.java package org.jabref.logic.logging; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.apache.logging.log4j.core.LogEvent; import org.junit.Assert; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class LogMessagesTest { @Test void givenNewInstance_whenGetInstance_returnInstance() { Assert.assertNotNull(LogMessages.getInstance()); } @Test void givenLogMessages_whenGetMessages_thenReturnMessages() { ObservableList<LogEvent> messages = FXCollections.observableArrayList(); Assert.assertEquals(messages, LogMessages.getInstance().getMessages()); } @Test void givenLogMessages_whenClear_thenReturnCorrectMessages() { ObservableList<LogEvent> messages = FXCollections.observableArrayList(); Assert.assertEquals(messages, LogMessages.getInstance().getMessages()); } }
e3062a3395404f4a68a3ecbfea93ac72310a72b6
[ "Java" ]
2
Java
kaybarenz/jabref
ff643ac31b65301cd1dfdd227aab1b7334a46a9b
3bb8007f3b824f9f9dbf5c87af48672e60ced5b0
refs/heads/main
<file_sep>import pandas as pd import plotly.express as px df = pd.read_csv('cases.csv') fig = px.scatter(df,x = 'date',y = 'cases', color = "country",size = 'cases') fig.show()
b980fc9e14c10f87eafb2b7ba5a51e9d15b3caf6
[ "Python" ]
1
Python
Bhavya12345-cyber/project103
ca38797b862983b339254c0f5978f8da1d62aadb
6dca96dd425853becb881cc2d56bc8e7c55810d9
refs/heads/master
<repo_name>yatatsu/LazyExpandableRecyclerView<file_sep>/README.md # LazyExpandableRecyclerView [![](https://jitpack.io/v/yatatsu/LazyExpandableRecyclerView.svg)](https://jitpack.io/#yatatsu/LazyExpandableRecyclerView) The original is [bignerdranch/expandable-recycler-view](https://github.com/bignerdranch/expandable-recycler-view). Two little differences from original. 1. resetting data available. 2. getting child data from callback(not parent). <file_sep>/library/src/main/java/com/yatatsu/lazyexpandablerecyclerview/ChildItem.java package com.yatatsu.lazyexpandablerecyclerview; public class ChildItem<P, C> { final C item; final P parent; public ChildItem(P parent, C item) { this.parent = parent; this.item = item; } public P getParent() { return parent; } public C getItem() { return item; } }
c7962fc7f56554e9ec20bab5766a079685f38647
[ "Markdown", "Java" ]
2
Markdown
yatatsu/LazyExpandableRecyclerView
84c8f4fb729c3f50fddbabb8622b6f2c3361c59f
38f9a46dc9a9c8cc13e91089f68fa37a668b7e90
refs/heads/master
<file_sep>VisionAirPort Eindcasus ========================================= Het vliegveld ----------------- - De vliegveldcode van VisionAirPort is VAP. - Er vliegen drie soorten vluchten op VisionAirPort: routevluchten, vrachtvluchten, en privévluchten ("General Aviation") - Het vliegveld heeft 5 passagiersterminals: A,B,C,D,E. Terminal C heeft 8 gates, terminals A,B,D hebben 6 gates, terminal E heeft 5 gates. Er zijn dus in totaal 31 gates. - Daarnaast wordt de code F gebruikt als terminal voor vrachtvluchten, en code G als terminal voor privévluchten. - Alleen terminals D,E zijn ingericht op intercontinentale vluchten (douane etc.). Alle intercontinentale vluchten worden ingepland vanaf deze terminals. - VisionAirPort heeft 6 landingsbanen. - VisionAirPort is een hub voor 5 airlines: KLM, Transavia, TUIFly, Corendon, en MartinAir. Operatie ----------------- - De aankomst- en vertrektijd van een vliegtuig worden gedefinieerd als het moment van arriveren bij en vertrekken van de gate. - Tussen aankomst en vertrek vindt de "turnaround" plaats (passagiers verlaten het vliegtuig, het vliegtuig wordt bijgetankt en schoongemaakt, nieuwe passagiers boarden). Dit proces duurt voor vluchten binnen Europa 45 minuten en voor intercontinentale vluchten 75 minuten. - Een gatewissel vindt plaats op het moment dat 10 minuten voor aankomst van een routevlucht de geplande gate nog bezet is. Hierbij wordt dan uitgeweken naar een willekeurige (!) andere vrije gate. Bij dit uitwijken wordt ook geen rekening gehouden met of een vlucht intercontinentaal is of niet. - Bij een gatewissel duurt de turnaround 15 minuten langer, omdat passagiers van elders op het vliegveld moeten komen of omdat benzine / voorraden verplaatst moeten worden. - Er worden nooit vluchten ingepland op gate C8, dit omdat er dan vaker een gate beschikbaar is voor gatewissels. Routevluchten ----------------- - Een route bestaat uit een vliegtuig dat eeuwig tussen VisionAirPort en 1 andere bestemming heen en weer vliegt. Afhankelijk van de te vliegen afstand gebeurt dit eens per 2 dagen, elke dag, of tweemaal per dag. - Routevluchten hebben een vluchtnummer dat bestaat uit een combinatie van de airlinecode (vaak 2-letterig, behalve bij Corendon en EasyJet), en een getal - Dit getal ligt onder de 1000 voor vluchten binnen Europa en tussen 1000 en 5000 voor intercontinentale vluchten - Dit vluchtnummer is uniek op een dag. Een vluchtnummer kan dus staan voor "de vlucht van KLM om 5:15 naar Caïro". De volgende dag kan een vluchtnummer opnieuw worden gebruikt, voor hetzelfde soort vlucht. De 'betekenis' van een vluchtnummer is tijdens het bestaan van VisionAirPort nooit gewijzigd. - Vluchten vanaf een hub van een airline krijgen vaak een oneven vluchtnummer, en vluchten naar een hub vaak een even vluchtnummer. Deze regel wordt voor alle routevluchten van en naar visionAirPort gevolgd. - Sommige routes zijn gecategoriseerd als 'zomervluchten'. Deze beginnen op 1 april, 1 mei, of 1 juni, en stoppen op 31 augustus, 31 september, of 31 oktober. - Routevluchten gebruiken baan 1 tot 5. Vrachtvluchten ----------------- - Vrachtvluchten werken in zekere zin ook met 'routes': één specifiek vliegtuig wordt toegewezen aan één specifieke bestemming en vliegt nooit naar of van een ander vliegveld. De tijd waarop het vliegt is wel elke dag anders. - Welke vrachtvluchten wanneer plaatsvinden (en hoe vaak) is volledig willekeurig. - Per dag worden er tussen de 8 en 17 vrachtvluchten gevlogen. - Vrachtvluchten hebben een vluchtnummer dat bestaat uit de 3-letterige airlinecode (altijd) en een getal boven de 5000. - Vrachtvluchten vliegen uiteraard niet op een passagiersterminal. Er wordt als terminal F (voor 'Freight') ingevuld. Dit staat voor de gehele cargo-afdeling van het vliegveld, niet voor een echte terminal. - Vrachtvluchten gebruiken baan 1 tot 5. Privévluchten ----------------- - Er bestaat een poule met privéjets en een poule met bestemmingen waar zij op kunnen vliegen (allemaal Europees). Elke dag verandert tussen de 3 en 16 privéjets van locatie, dus als ze ergens anders zijn komen ze naar VAP en als ze hier zijn vliegen ze naar een willekeurige geschikte bestemming. Een vliegtuig vliegt dus nooit 2x per dag. - Privévluchten hebben geen vluchtnummer. - Privévluchten vliegen vanaf een apart deel van het vliegveld (vgl. Schiphol Oost). Er wordt als terminal G (voor 'General Aviation') ingevuld. Dit staat voor een deel van het vliegveld, niet voor een echte terminal. - Van privévluchten is geen informatie beschikbaar over de bezettingsgraad. - Privéjets landen en stijgen op van baan 6. Landingsbanen ----------------- - Er zijn 6 landingsbanen: de <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, en <NAME>. Deze worden normaal gesproken aangeduid met de nummers 1-6. - Baan 1 ligt van oost naar west (code 09-27) - Banen 2-4 liggen van noord naar zuid (code 18R-36L, 18L-36R, en 18C-36C) - Baan 5 ligt van noord-oost naar zuid-west (code 06-24) - Baan 6 ligt van noord-oost naar zuid-west (code 04-22) - Op baan 3 mag alleen worden gevlogen vanuit en naar het zuiden. - Op baan 4 mag alleen worden gevlogen vanuit en naar het noorden. - Voor de vracht- en routevluchten is sprake van dynamische baankeuze op basis van de wind. Privévluchten gebruiken altijd baan 6, ongeacht de weersomstandigheden. - Als er weinig wind staat, wordt baan 4 gebruikt om te landen en baan 3 om op te stijgen. - Er is sprake van 'harde wind' vanaf een gemiddelde windsnelheid van 13 knopen of bij windstoten van 20 knopen. Dit komt neer op 6.7 m/s en 10.3 m/s, respectievelijk. - Als er sprake is van harde wind, wijken vluchten uit naar een baan waar ze zo goed mogelijk tegen de wind in kunnen landen dan wel opstijgen. Hierbij geldt dat eerst een baan wordt gekozen voor landen, daarna voor opstijgen. Vertraging door weer ----------------- - Vertraging door neerslag treedt op vanaf 5 mm neerslag en leidt tot 10 min vertraging. - Vertraging door wind treedt op bij een gemiddelde windsnelheid van 13 knopen of windstoten vanaf 20 knopen. Bij meer dan 5 mm neerslag zijn deze grenzen 5 knopen lager. Vertraging door wind leidt tot 15 min vertraging. - Vertraging door vorst treedt op bij temperaturen onder het vriespunt. Deze vertraging bedraagt 10 minuten. - Vertraging door sneeuw treedt op bij temperaturen onder het vriespunt en meer dan 1.5 mm neerslag. Dit leidt tot 30 minuten vertraging. - Vertraging door slecht zicht treedt op vanaf minder dan 1 km zicht. Dit leidt tot 30 minuten vertraging. - Deze vertragingen door weersomstandigheden worden bij elkaar opgeteld. Vervolgens krijgen vluchten een vertraging getrokken uit een skew-normal verdeling met het zwaartepunt op de aldus berekende vertraging. Vertraging voor intercontinentale vluchten ----------------- - Intercontinentale vluchten hebben gemiddeld 15 minuten meer vertraging. - Daarnaast kennen ze ook een grotere spreiding in vertraging. Vertraging door gatewissels ----------------- - Een vliegtuig dat van gate is gewisseld krijgt nog 15 minuten extra vertraging bij vertrek (de arriverende vlucht ondervindt geen last). Overige vertraging ----------------- - Er worden nog willekeurige vertragingen toegevoegd uit een skew-normal verdeling met een gemiddelde van 3.8. Deze willekeurige factoren kunnen ook leiden tot een vervroeging.<file_sep># Initialiseren ###################################################################################### # Selecteer bronmap setwd("D:\\data\\ast21252\\Documents\\201701 VisionWorks Academy XI\\Eindcasus Vision Airport") #setwd("D:\\data\\ITH21266\\Documents\\VisionAirPort") # Packages library(chron) library(sn) library(ggplot2) library(plyr) library(dplyr) library(reshape2) library(lubridate) library(caret) # Functies ###################################################################################### # funweekdag: date -> integer # de dag van de week van de ingevoerde datum wordt vertaald in een getal van 1 tot 7 # hierbij is maandag 1 en zondag 7 funweekdag <- function(datum) { df <- data.frame(naam = c("ma","di","wo","do","vr","za","zo"), cijfer = 1:7) return(df[df$naam == weekdays(datum,T),2]) } # funmaand: integer -> character funmaand <- function(maand) { df <- data.frame(int = 1:12, naam = c("jan","feb","mar","apr","mei","jun","jul","aug","sep","okt","nov","dec")) return(df[df$int == maand,2]) } # onesample: vector -> element # van de ingevoerde vector wordt 1 willekeurig element geselecteerd # dit is een verbetering op de standaard functie sample, omdat de functie ook werkt als de vector 1 element bevat onesample <- function(x) { if (length(x) == 1) { return(x) } else { return(sample(x,1)) } } # toampm: integer vector -> string vector # vertaalt de tijd in dag-minuten (0 tot 1439) in een AM/PM formaat toampm <- function(v) { r <- rep(NA, length(v)) uur <- v %/% 60 pm <- uur %in% 12:23 am <- uur %in% 0:11 uur <- uur %% 12 uur[uur == 0] <- 12 min <- paste0("0",v %% 60) min <- substr(min, nchar(min)-1, nchar(min)) r[am] <- paste0(uur[am],":",min[am]," AM") r[pm] <- paste0(uur[pm],":", min[pm]," PM") r <- factor(r) return(r) } # Data inlezen ###################################################################################### # Bronbestanden banen <- read.csv2("data_banen.csv") general <- read.csv2("data_general.csv") luchthaven <- read.csv2("data_luchthavens.csv") maatschappijen <- read.csv2("data_maatschappijen.csv") routes <- read.csv2("data_routes.csv") vliegtuigtype <- read.csv2("data_vliegtuigen.csv") vracht <- read.csv2("data_vracht.csv") weer <- read.csv2("data_weer.csv") # Aanpassingen data formaat weer$Datum <- as.Date(weer$Datum,"%d-%m-%Y") weer$RH[weer$RH < 0] <- 0 weer$nat <- weer$RH > 50 weer$vorst <- weer$TG < 0 weer$sneeuw <- weer$TG < -10 & weer$RH > 15 weer$extreemwind <- weer$FXX > 200 routes <- dplyr::rename(routes, Plangate = Gate, Planterminal = Terminal) # Enkele levels in een vector opslaan gatelvls <- c(levels(routes$Plangate),"C8") terminallvls <- c(levels(routes$Planterminal), "F", "G") richtinglvls <- c("A","D","S") luchthavens <- c(levels(luchthaven$Luchthavencode),"VAP") airlines <- unique(c(levels(maatschappijen$IATA), levels(maatschappijen$ICAO))) # Airlines voor wie VisionAirPort een hub is home <- c("KL","HV","OR","CAI","MPH") # Genereren vluchtnummers ###################################################################################### # Vluchten krijgen een willekeurig vluchtnummer toegewezen # Hierbij krijgen vluchten binnen Europa een vluchtnummer tussen 0 en 999 # Intercontinentale vluchten krijgen een vluchtnummer tussen 1000 en 4999 # Dit onderscheid is niet per se ontleed aan de werkelijke praktijk # Vluchtnummers boven de 5000 zijn bedoeld voor vluchten die worden gedeeld tussen airlines (komen niet in deze dataset voor) # Vluchten vanaf een "hub" van een airline krijgen vaak een oneven vluchtnummer, en vluchten naar een hub een even # VisionAirPort is een hub van 4 airlines: KLM, Transavia, TuiFly, en Corendon # Omdat (meestal) begonnen wordt met de arriverende vlucht, is dat voor deze 4 airlines een vlucht náár de hub # Deze 4 airlines beginnen dus op een even vluchtnummer, de rest op een oneven vluchtnummer # Kolom toevoegen aan df routes <- mutate(routes, Vluchtnr = 0) # For-loop per airline (i = Airlinecode) for(i in levels(routes[,1])) { # tijdelijk df met vluchten van deze ene airline sub <- filter(routes, Airlinecode == i) # als deze airline maar 1 vlucht heeft: geef random vluchtnummer if(nrow(sub) == 1) { sub[sub$Continent=="Eur","Vluchtnr"] <- floor(runif(1,min=10,max=495)) * 2 + 1 sub[sub$Continent!="Eur","Vluchtnr"] <- floor(runif(1,min=495,max=2495)) * 2 + 1 # meer vluchten? voeg dan controle toe dat gegenereerde vluchtnummers niet te dicht opeen zitten # sorteer van klein naar groot en check dat opeenvolgende vluchtnummers minstens 8 verschillen # door de while-functie wordt geprobeerd tot een willekeurige set is gegenereerd die voldoet } else { while(min(diff(sub[order(sub$Vluchtnr),"Vluchtnr"])) <= 7) { sub[sub$Continent=="Eur","Vluchtnr"] <- floor(runif(nrow(sub[sub$Continent=="Eur",]),min=10,max=495)) * 2 + 1 sub[sub$Continent!="Eur","Vluchtnr"] <- floor(runif(nrow(sub[sub$Continent!="Eur",]),min=495,max=2995)) * 2 + 1 } } # de gegenereerde vluchtnummers worden teruggezet in het bron-dataframe routes[routes$Airlinecode == i, "Vluchtnr"] <- sub$Vluchtnr } rm(sub) # Basisnr is het onbewerkte vluchtnummer # Vliegtuig combineert de airlinecode daarmee als identificatie voor later routes <- mutate(routes, Basisnr = Vluchtnr, Vliegtuigcode = paste0("V", Airlinecode, Basisnr)) # Sla alle vliegtuigen op vliegtuigcodes <- unique(routes$Vliegtuigcode) # Aanpassing voor de airlines voor wie VisionAirport een hub is routes$Vluchtnr[!(routes$Airlinecode %in% home)] <- routes$Vluchtnr[!(routes$Airlinecode %in% home)] - 1 # Bepalen vluchtperiode ###################################################################################### # Veruit de meeste vluchten worden het hele jaar door gevlogen (periode = 'j') # Sommige worden alleen in de zomer gevlogen (periode = 'z') # Deze zomervluchten worden actief in april, mei, of juni en inactief in augustus, september, of oktober # Deze maanden zijn inclusief, dus 'inactief in augustus' betekent 'vliegt niet meer vanaf september' # De startmaand en eindmaand wordt per route willekeurig gekozen # Eerst wordt overal jan - dec ingevoerd, daarna wordt dit voor de zomervluchten overschreven aantalzomer <- nrow(filter(routes, Periode == "z")) routes <- mutate(routes, start = 1, eind = 12) routes[routes$Periode == "z", c("start","eind")] <- c(sample(c(4,5,6),aantalzomer,replace=T),sample(c(8,9,10),aantalzomer,replace=T)) rm(aantalzomer) # Opstellen planning ###################################################################################### # Tabelstructuren vars.plantabel <- c("Airlinecode", "Destcode", "Continent", "Zomerdrukte", "Vliegtuigtype", "Planterminal", "Plangate", "Vluchtnr", "Basisnr", "Vliegtuigcode", "start", "eind","Richting","Plantijd","Dag") str.plantabel <- structure(list(Airlinecode = factor(levels=airlines), Destcode = factor(levels=luchthavens), Continent = factor(levels=levels(routes$Continent)), Zomerdrukte = integer(), Vliegtuigtype = factor(levels=levels(vliegtuigtype$IATA)), Planterminal = factor(levels=terminallvls), Plangate = factor(levels=gatelvls), Vluchtnr = integer(), Basisnr = integer(), Vliegtuigcode = factor(levels=vliegtuigcodes), start = integer(), eind = integer(), Richting = factor(levels=richtinglvls), Plantijd = integer(), Dag = integer()), class = "data.frame") # Dit stuk van de code genereert de plantijden voor elke routevlucht # Dit proces gebeurt per gate afzonderlijk # Sommige routes worden 2x op een dag gevlogen. Deze vluchten worden als eerst ingepland, aan het begin van de dag # In de kolom 'Mintijd' wordt de vroegste tijd genoteerd waarop de route dan voor de 2e keer kan worden gevlogen # Sommige vluchten worden om de dag gevlogen. Deze vluchten hebben een 'delay', dwz. de dag van de 2 dat ze vliegen (0 of 1) # Dit is zo goed mogelijk eerlijk verdeeld over de 2 mogelijke dagen (handmatig, in het bronbestand) # Elke dag-0 vlucht wordt willekeurig gekoppeld aan een dag-1 vlucht die op hetzelfde moment de dag erna vertrekt # De planning herhaalt zich dus elke 2 dagen # Als de dubbele vluchten allemaal 1 keer zijn ingepland, gaat het proces verder met de overige vluchten # Dit zijn de enkele vluchten, de helft van de halve vluchten, en een herhaling van de dubbele vluchten # Er wordt gekeken welke vluchten kunnen worden gevlogen (dat het niet te vroeg is voor een eventuele herhaling) # Van deze vluchten wordt willekeurig 1 ingepland # De eerste vlucht die op een dag vertrekt, arriveert de dag ervoor # Als een vlucht bij een gate is gearriveerd, volgt de 'Turnaround' waarin het vliegtuig weer wordt klaargemaakt voor vertrek # VisionAirport is erg efficiënt: de turnaround duurt 45 min voor Europese vluchten en 75 minuten voor intercontinentale vluchten # Nadat een vlucht van een gate is vertrokken, wordt een bufferperiode ingepland tot de volgende arriverende vlucht # Deze periode is minstens 10 minuten en krijgt daarbij een bufferfactor toegevoegd # Deze buffer volgt deze formule: buffer = abs(c-0.5*d) / (0.5*d) * (max-min) + min # Hierbij is c een counter van de hoeveelste vlucht zojuist vertrokken is, en d het totaal aantal vluchten dat van de gate vertrekt # Er is een verborgen parameter g, de gemiddelde buffer die op een dag gerealiseerd moet worden om de dag mooi op te vullen # Er is een bandbreedte rondom g, waarvan min en max de grenzen zijn # Een voorbeeld: een gate met 9 vluchten en een buffer van 10 tot 50 minuten # curve(abs(x-0.5*8) / (0.5*8) * (10-2) + 2, 0, 8) # Er zitten een aantal willekeurige invloeden in het planningsproces, om het niet al te voorspelbaar te maken # Het zou allemaal binnen 23.5 uur moeten passen, maar soms bestrijkt de planning een periode die langer is # Daarom staat hier een while-statement: we proberen net zo lang tot de planning binnen 23.5 uur past (max. 5 pogingen) # Omdat de planning met stappen van 5 minuten wordt gegenereerd, komt 23.5 uur neer op 282 x 5 mins a <- 0 planning <- data.frame(Plantijd = c(0,300)) while ((max(planning$Plantijd) - min(planning$Plantijd)) > 282 & a < 5) { a <- a + 1 print(paste0("Iteratie ",a)) # Bouw lege dataframes op planning <- str.plantabel log <- structure(list(gate = factor(levels=gatelvls), vlucht = integer(), richting = factor(levels=richtinglvls), tijd = integer(), buffer = numeric()), class = "data.frame") gates <- structure(list(Gate = factor(levels=gatelvls), d = integer(), g = integer(), min = integer(), max = integer()), class = "data.frame") # Er zijn geen vluchten ingepland op gate C8. Dit om altijd een vrije gate te hebben voor eventuele gatewissels # Deze gate wordt nu los ingevoerd in dataframe 'gates' gates[1,] <- list("C8",0L,0L,0L,0L) for (i in levels(routes$Plangate)) { # sub.gate is een selectie van routes met de huidige gate sub.gate <- filter(routes,Plangate == i) sub.gate <- transform(sub.gate, Mintijd = 0, Klaar = 0, Duur = ceiling(Duur * 60 / 5), Turnaround = ceiling(Turnaround * 60 / 5), Turnaroundtotaal = ceiling(Turnaroundtotaal * 60 / 5), Indeling = ave(Vluchten, Delay, FUN = function(x) rank(x, ties.method = "first"))) # Het aantal dubbele, enkele, en halve vluchten aantdubbel <- nrow(subset(sub.gate,Vluchten == 2)) aantenkel <- nrow(subset(sub.gate,Vluchten == 1)) aanthalf <- max(nrow(subset(sub.gate,Vluchten == 0.5 & Delay == 1)),nrow(subset(sub.gate,Vluchten == 0.5 & Delay == 0))) # De kolom 'Indeling' koppelt halve vluchten aan elkaar sub.gate$Indeling[sub.gate$Vluchten > 0.5] <- 0 sub.gate$Indeling[sub.gate$Vluchten > 0.5] <- (max(sub.gate$Indeling)+1):(max(sub.gate$Indeling)+aantdubbel+aantenkel) # Sorteer de tabel zodat de dubbele vluchten bovenaan staan, aflopend gesorteerd op vluchtduur (dus langste vluchten eerst inplannen) sub.gate <- arrange(sub.gate,desc(Vluchten),desc(Duur)) # Plansub is de tabel waarin ingeplande vluchten tijdelijk worden opgeslagen plansub <- str.plantabel # Dit zijn de parameters voor het berekenen van de bufferperiode d <- ceiling(sum(sub.gate$Vluchten)) - 1 g <- floor((245 - sum(sub.gate$Turnaroundtotaal)) / (d+1)) - 2 min <- max(0,g-20) max <- 2 * g - min gates[nrow(gates)+1,] <- list(i,as.integer(d),as.integer(g),as.integer(min),as.integer(max)) # Tijd houdt de tijd bij (in stappen van 5 min, dus tussen 0 en 287) tijd <- 0 # c telt het aantal vertrokken vluchten c <- 0 # Inplannen van de 1e vlucht van dubbele routes if (aantdubbel > 0) { for (j in 1:aantdubbel) { # Haal vlucht op sub.vlucht <- sub.gate[j,] ### Arriverende vlucht # Als dit de eerste vlucht is: if (c == 0) { # Bewaar vlucht tot einde planning afsluiter <- sub.vlucht # Als dit niet de eerste vlucht is: } else { # Plan arriverende vlucht in sub.vlucht <- mutate(sub.vlucht, Richting = "A", Plantijd = tijd, Dag = 0) plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] sub.vlucht$Dag <- 1 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] # Turnaround verstrijkt tijd <- tijd + sub.vlucht$Turnaround # Log log[nrow(log)+1,] <- list(i,c,"A",tijd, sub.vlucht$Turnaround) } # Tel 1 op bij vluchtnummer sub.vlucht$Vluchtnr <- sub.vlucht$Vluchtnr + 1 ### Vertrekkende vlucht # Plan vertrekkende vlucht in sub.vlucht <- mutate(sub.vlucht, Richting = "D", Plantijd = tijd, Dag = 0) plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] sub.vlucht$Dag <- 1 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] ### Sla informatie op in gate.sub voor de herhaling # select is een T/F vector die de rijen in sub.gate selecteert die horen bij de vlucht die we nu inplannen select <- (sub.gate$Basisnr == sub.vlucht$Basisnr & sub.gate$Airlinecode == sub.vlucht$Airlinecode) # Sla de minimale tijd op voor de 2e vlucht sub.gate$Mintijd[select] <- tijd + (sub.vlucht$Duur * 2) + 12 # Verhoog vluchtnummer in sub.gate sub.gate$Vluchtnr[select] <- sub.gate$Vluchtnr[select] + 2 sub.gate$Basisnr[select] <- sub.gate$Basisnr[select] + 2 ### Buffertijd verstrijkt buffer <- abs(c-0.5*d)/(0.5*d)*(max-min) + min tijd <- tijd + 2 + floor(runif(1, 0.5*buffer, 1.25*buffer)) # Log log[nrow(log)+1,] <- list(i,c,"D",tijd, buffer) # Update counter c <- c + 1 } } # Alle dubbele routes zijn 1x ingepland, ga door met de rest for (j in 1:max(sub.gate$Indeling)) { # Zoek beschikbare vluchten beschikbaar <- unique(sub.gate[sub.gate$Mintijd <= tijd & sub.gate$Klaar == 0, "Indeling"]) # Als er geen beschikbare vluchten zijn: laat tijd verstrijken tot er wel één is if(length(beschikbaar) < 1) { extratijd <- min(sub.gate[sub.gate$Klaar == 0, "Mintijd"]) - tijd tijd <- tijd + extratijd beschikbaar <- unique(sub.gate[sub.gate$Mintijd <= tijd & sub.gate$Klaar == 0, "Indeling"]) log[nrow(log)+1,] <- list(i,c,"S",tijd, extratijd) } # Kies willekeurig 1 van de beschikbare vluchten indeling.huidig <- onesample(beschikbaar) # Haal informatie op sub.vlucht <- sub.gate[sub.gate$Indeling == indeling.huidig,] ### Arriverende vlucht # Als dit de eerste vlucht is: if (c == 0) { # Bewaar vlucht tot einde planning afsluiter <- sub.vlucht # Als dit niet de eerste vlucht is: } else { # Plan arriverende vlucht in sub.vlucht <- mutate(sub.vlucht, Richting = "A", Plantijd = tijd) if (nrow(sub.vlucht) == 1) { sub.vlucht$Dag <- 0 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] sub.vlucht$Dag <- 1 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] } else if (nrow(sub.vlucht) == 2) { sub.vlucht$Dag <- sub.vlucht$Delay plansub[(nrow(plansub)+1):(nrow(plansub)+2),] <- sub.vlucht[,vars.plantabel] } else { print("Fout bij het inplannen van vlucht. Printout relevante informatie:") print(summary(sub.vlucht)) } # Turnaround verstrijkt tijd <- tijd + max(sub.vlucht$Turnaround) # Log log[nrow(log)+1,] <- list(i,c,"A",tijd, max(sub.vlucht$Turnaround)) } # Tel 1 op bij vluchtnummer sub.vlucht$Vluchtnr <- sub.vlucht$Vluchtnr + 1 ### Vertrekkende vlucht # Plan vertrekkende vlucht in sub.vlucht <- mutate(sub.vlucht, Richting = "D", Plantijd = tijd) if (nrow(sub.vlucht) == 1) { sub.vlucht$Dag <- 0 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] sub.vlucht$Dag <- 1 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] } else if (nrow(sub.vlucht) == 2) { sub.vlucht$Dag <- sub.vlucht$Delay plansub[(nrow(plansub)+1):(nrow(plansub)+2),] <- sub.vlucht[,vars.plantabel] } else { print("Fout bij het inplannen van vlucht. Printout relevante informatie:") print(summary(sub.vlucht)) } ### Buffertijd verstrijkt buffer <- abs(c-0.5*d)/(0.5*d)*(max-min) + min tijd <- tijd + 2 + floor(runif(1, 0.5*buffer, 1.25*buffer)) # Log log[nrow(log)+1,] <- list(i,c,"D",tijd, buffer) # Update counter c <- c + 1 # Noteer dat vlucht volledig ingedeeld is sub.gate$Klaar[sub.gate$Indeling == indeling.huidig] <- 1 } # In principe moet er nog altijd 1 vlucht arriveren, maar voor de zekerheid checken we het even if (exists("afsluiter")) { # Plan laatste arriverende vlucht in sub.vlucht <- afsluiter sub.vlucht <- mutate(sub.vlucht, Richting = "A", Plantijd = tijd) if (nrow(sub.vlucht) == 1) { sub.vlucht$Dag <- 0 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] sub.vlucht$Dag <- 1 plansub[nrow(plansub)+1,] <- sub.vlucht[,vars.plantabel] } else if (nrow(sub.vlucht) == 2) { sub.vlucht$Dag <- 1 - sub.vlucht$Delay plansub[(nrow(plansub)+1):(nrow(plansub)+2),] <- sub.vlucht[,vars.plantabel] } else { print("Fout bij het inplannen van vlucht. Printout relevante informatie:") print(summary(sub.vlucht)) } rm(afsluiter) } # De vluchten zijn nu ingepland vanaf tijd = 0, dit is natuurlijk niet de bedoeling # De planning wordt eerst gecentreerd rond 12:00 # Daarna wordt een willekeurige factor toegevoegd, een verschuiving naar voren of achteren met maximaal 45 mins shift <- 144 - floor((max(plansub$Plantijd) + min(plansub$Plantijd)) / 2) + onesample(-9:9) plansub$Plantijd <- plansub$Plantijd + shift # Voeg alle ingeplande vluchten van deze gate toe aan de planning planning <- rbind(planning, plansub) } rm(sub.gate,plansub,sub.vlucht,aantdubbel,aantenkel,aanthalf,beschikbaar,buffer,extratijd,c,d,g,max,min,shift,select,tijd,indeling.huidig,i,j) } rm(a) # Het vluchtnummer en basisnummer zijn nu definitief en er wordt niet meer aan gerekend # We kunnen dus de airlinecode er voor plakken planning <- mutate(planning, Basisnr = paste0(Airlinecode,Basisnr), Vluchtnr = paste0(Airlinecode,Vluchtnr)) # Verschuif de planning zo, dat de laatste vlucht om 23:55 vertrekt planning$Plantijd <- planning$Plantijd + 287 - max(planning$Plantijd) # Bereken de daadwerkelijke tijd (dus niet in termen van 5mins) planning$Plantijd <- planning$Plantijd * 5 # Grafieken van de verdeling over de dag planuur <- planning$Plantijd %/% 60 plot(table(planuur)) rm(planuur) # Vliegtuigcodes & vluchtnummers voor vrachtvluchten ############################################################################ vracht <- rbind(vracht,vracht,vracht) vracht <- mutate(vracht, Vliegtuigcode = sample(2501:4990,nrow(vracht)) * 2 + as.integer(Airlinecode %in% home), VluchtnrA = Vliegtuigcode - 1, VluchtnrD = Vliegtuigcode) vracht[,4] <- paste0("V", vracht$Airlinecode, vracht[,4]) for (i in 5:6) { vracht[,i] <- paste0(vracht$Airlinecode, vracht[,i]) } vliegtuigcodes <- c(vliegtuigcodes, unique(vracht$Vliegtuigcode)) levels(planning$Vliegtuigcode) <- vliegtuigcodes # Vliegtuigcodes voor General Aviation ############################################################################ general <- rbind(general,general,general,general,general) luchthavens.eur <- as.character(luchthaven$Luchthavencode[luchthaven$Continent == "Eur" & luchthaven$Afstand.in.km < 1600]) general$Locatie <- as.character("VAP") sel <- runif(nrow(general)) < 0.5 general$Locatie[sel] <- sample(luchthavens.eur,sum(sel),replace=T) general <- data.frame(general[order(runif(nrow(general))),]) rownames(general) <- NULL general$Vliegtuigcode <- paste0("VG",rownames(general)) # Alle vliegtuigen vliegtuig.pax <- planning %>% dplyr::group_by(Vliegtuigcode) %>% dplyr::arrange(Plantijd) %>% dplyr::summarize(freq = n(), ri = first(Richting), type = first(Vliegtuigtype)) %>% merge(vliegtuigtype, by.x = "type", by.y="IATA", all.x = TRUE) vliegtuig.vracht <- vracht %>% merge(vliegtuigtype, by.x = "Vliegtuigtype", by.y = "IATA", all.x = TRUE) # Simulatie ###################################################################################### # De dagen waarvoor de simulatie draait simdagen <- 1:nrow(weer) # Zet willekeurig 39 vliegtuigen op non-actief inactief <- routes$Vliegtuigcode[sample(1:nrow(routes),39)] planning$Actief <- !(planning$Vliegtuigcode %in% inactief) # Tabellen vars.simtabel <- c("Datum","Vluchtnr","Richting","Airlinecode","Destcode","Continent","Zomerdrukte","Vliegtuigcode","Vliegtuigtype","Planterminal","Plangate","Terminal","Gate","Plantijd","Vertraging","Tijd","Baan","Bezetting","Capaciteit","Passagiers","MaxVracht","Vracht","Cancelled") sim <- data.frame() for(i in simdagen) { # Lees informatie in over deze dag uit dataframe `weer` sub.weer <- weer[i,] # Bepaal of dit een 0-dag of 1-dag is dag <- i %% 2 # Als dit de eerste dag van de maand is: if(sub.weer$Dag == 1) { # Zet een routevliegtuig op actief if (length(inactief) > 0) { actief <- onesample(inactief) planning$Actief[planning$Vliegtuigcode == actief] <- T inactief <- inactief[inactief != actief] } } # We slaan de planning voor vandaag op in sub.planning sub.planning <- planning %>% merge(select(vliegtuig.pax,Vliegtuigcode,Capaciteit,Vracht), by = "Vliegtuigcode", all.x = T) %>% dplyr::rename(MaxVracht = Vracht) %>% arrange(Plantijd, Basisnr) %>% filter(Dag == dag) %>% filter(sub.weer$Maand >= start & sub.weer$Maand <= eind) %>% filter(Actief == TRUE) # Voeg kolommen toe sub.planning <- data.frame(sub.planning, Vertraging = as.integer(NA), Tijd = as.integer(NA), Gate = factor(NA,levels=gatelvls), Terminal = factor(NA,levels=terminallvls), Baan = as.integer(NA), Cancelled = 0) rownames(sub.planning) <- NULL ################### # Vertraging ###### ################### ### Vertraging door weer # Bepaal de uren waarbij wind voor vertraging zorgt # Als de gemiddelde windsnelheid (FG) hoger is dan 6.5 m/s (2.5 m/s bij regen, is er de hele dag vertraging door wind # Zo niet, als er een windstoot (FXX) is gemeten van meer dan 10.0 m/s (6.0 m/s bij regen), is er 9 uur rondom die windstoot vertraging door wind if(sub.weer$FXX > (100 - 28 * sub.weer$nat)) { winduren <- max(0,sub.weer$FXXH-5):min(23,sub.weer$FXXH+4) } else { winduren <- NA } if(sub.weer$FG > (67 - 28 * sub.weer$nat)) { winduren <- 0:23 } # Bepaal de uren waarbij slecht zicht voor vertraging zorgt # Er is sprake van slecht zicht bij zicht van minder dan 1 km # Als het zicht de hele dag minder was dan 1 km (VVX < 10), is er de hele dag vertraging door slecht zicht # Als het zicht een deel minder was dan 1 km (VVN < 10), is er een deel van de dag vertraging door slecht zicht # Dit duurt van 8 tot 3 uur, afh. van hoe slecht het zicht was if(sub.weer$VVN < 10) { zichturen <- floor(8 - sub.weer$VVN / 2) zichturen <- max(0,sub.weer$VVNH-1-zichturen):min(23,sub.weer$VVNH-1+zichturen) } else { zichturen <- NA } if(sub.weer$VVX < 10) { zichturen <- 0:23 } # Hiermee kunnen voor elke vlucht afzonderlijk worden berekend of ze last hebben van slecht zicht of wind slechtzicht <- (sub.planning$Plantijd %/% 60) %in% zichturen windstoot <- (sub.planning$Plantijd %/% 60) %in% winduren # Vertraging door sneeuw is 30 min, door vorst 10 min, door slecht zicht 30 min, door wind 15 min, door regen 10 min v.weer <- sub.weer$sneeuw * 30 + sub.weer$vorst * 10 + slechtzicht * 30 + windstoot * 15 + sub.weer$nat * 10 + sub.weer$extreemwind * 60 # Met een skew-normal verdeling worden deze vertragingen "uitgesmeerd" richting 0 v.weer <- rsn(n=nrow(sub.planning),omega=0.35*v.weer,alpha=-10) + v.weer # Negatieve vertraging door weer kan niet v.weer[v.weer < 0] <- 0 ### Vertraging voor intercontinentale vluchten # Dit is gemiddeld 15 minuten # Intercontinentale vluchten staan ingepland op terminal D of E continentaal <- sub.planning$Planterminal %in% c("D","E") v.continent <- rnorm(n=nrow(sub.planning),mean = 10, sd = 7.5) * continentaal ### Vertraging door andere factoren # Door een skew-normal verdeling worden er nog wat minuutjes vertraging toegevoegd # Dit kan eventueel negatief zijn v.random <- rsn(n=nrow(sub.planning),omega=5,alpha=4) ### Berekening & verwerking # Bereken de totale vertraging sub.planning$Vertraging <- as.integer(v.weer + v.continent + v.random) # Filter arriverende vluchten arr <- sub.planning$Richting == "A" # Filter vluchten waarbij de arriverende vlucht invloed heeft op de vertraging van de vertrekkende vlucht dub <- sub.planning$Basisnr %in% filter(vliegtuig.pax, freq > 1 & ri == "A")$Basisnr # Voeg de vertraging van een eventuele eerdere, arriverende vlucht toe aan het df sub.planning <- arrange(merge(sub.planning, sub.planning[arr,c("Basisnr","Vertraging")], by = "Basisnr", all.x = T),Plantijd,Basisnr) sub.planning <- dplyr::rename(sub.planning, Vertraging = Vertraging.x) sub.planning[dub&!arr,"Vertraging"] <- sub.planning[dub&!arr,"Vertraging.y"] sub.planning$Vertraging.y <- NULL # Tel vertraging op bij plantijd om de gerealiseerde tijd te berekenen sub.planning$Tijd <- sub.planning$Plantijd + sub.planning$Vertraging ################### # Bezetting ###### ################### # De bezettingsgraad is het hoogst in juli (maand = 7) en daarom ook het laagst in januari (maand = 1) # Elke bestemming heeft een `Zomerdrukte`, die bepaalt hoe gevoelig de bezetting is voor de tijd van het jaar # Daarnaast is er een willekeurige factor tussen -5 en +5 procent sub.planning$Bezetting <- pmin(90 - 2 * (abs(sub.weer$Maand - 7)-1) * sub.planning$Zomerdrukte + sample(-5:5, nrow(sub.planning),replace=T), rep(100, nrow(sub.planning))) sub.planning$Passagiers <- round(sub.planning$Bezetting * sub.planning$Capaciteit / 100) sub.planning$Bezetting <- round(sub.planning$Passagiers / sub.planning$Capaciteit * 100) ################### # Gatewissels ##### ################### # Vul een aanname in voor de gate sub.planning$Gate <- sub.planning$Plangate # Gatewissels gate <- dcast(data = sub.planning,formula = Gate + Basisnr~Richting,fun.aggregate = mean,value.var = "Tijd") wissels <- 0 # Ook dit proces loopt per gate for (j in gatelvls) { # We selecteren de vluchten die # 1. arriveren, # 2. aan deze gate, # 3. terwijl een ander vliegtuig daar aanwezig is of minder dan 10 min geleden is vertrokken sel <- gate$Gate == j bezet <- which(sub.planning$Richting == "A" & sub.planning$Gate == j & sapply(sub.planning$Tijd, function(x) any(x > gate$A[sel] & x < gate$D[sel] + 10))) while(length(bezet) > 0) { k <- bezet[1] a <- gate[gate$Basisnr == sub.planning$Basisnr[k],"A"] #De aankomsttijd van deze vlucht d <- gate[gate$Basisnr == sub.planning$Basisnr[k],"D"] #De vertrektijd van deze vlucht rows <- which(sub.planning$Basisnr == sub.planning$Basisnr[k]) #Rownrs van beide vluchten d_row <- which(rownames(sub.planning) %in% rows & sub.planning$Richting == "D") #Rownr van de vertrekkende vlucht # Voor elke vlucht in dataframe `gate` wordt berekend of die conflicteert met deze vlucht gate$vrij <- a > gate$D | d < gate$A # We summarisen per gate met all(), want alle vluchten mogen geen conflict vormen beschikbaar <- dplyr::summarize(group_by(gate,Gate), a = all(vrij)) # Voeg C8 handmatig toe indien nodig if (nrow(filter(beschikbaar, Gate == "C8")) == 0) { beschikbaar <- rbind(beschikbaar, list("C8",T)) } # Als er een beschikbare gate is: if (nrow(filter(beschikbaar, a == TRUE)) > 0) { sub.planning$Gate[rows] <- sample(as.character(filter(beschikbaar, a == TRUE)$Gate),1) #Kies een beschikbare gate sub.planning$Vertraging[d_row] <- sub.planning$Vertraging[d_row] + sample(11:17,1) #Vertrek 11-17 mins later sub.planning$Tijd[d_row] <- sub.planning$Plantijd[d_row] + sub.planning$Vertraging[d_row] #Pas tijden aan wissels <- wissels + 1 gate <- dcast(data = sub.planning,formula = Gate + Basisnr~Richting,fun.aggregate = mean,value.var = "Tijd") #Vernieuw dataframe # Als er geen beschikbare gate is: } else { # Cancel vlucht sub.planning$Cancelled[rows] <- 1 sub.planning$Tijd[rows] <- NA sub.planning$Gate[rows] <- NA } # Bereken opnieuw vluchten met een conflict bezet <- which(sub.planning$Richting == "A" & sub.planning$Gate == j & sapply(sub.planning$Tijd, function(x) any(x > gate$A[sel] & x < gate$D[sel] + 10))) } } # Pas terminal aan een eventuele gatewissel aan sub.planning$Terminal <- substr(as.character(sub.planning$Gate),1,1) ################### # Annuleringen #### ################### cancelled <- sample(sub.planning$Basisnr,onesample(0:3)) if(sub.weer$extreemwind) { cancelled <- sample(unique(sub.planning$Basisnr),onesample(40:80)) } rows <- (sub.planning$Basisnr %in% cancelled) sub.planning$Cancelled[rows] <- 1 sub.planning$Tijd[rows] <- NA sub.planning$Gate[rows] <- NA ################### # Vrachtvluchten ## ################### vracht$tijd <- sample(350:1100, nrow(vracht)) vr <- sample(nrow(vracht),as.integer(rnorm(1,35,7))) sub.vracht <- data.frame( Vliegtuigcode = vracht[vr,4], Airlinecode = vracht[vr,1], Destcode = vracht[vr,2], Vliegtuigtype = vracht[vr,3], Vluchtnr = vracht[vr,5], Richting = rep("A",length(vr)), Planterminal = "F", Terminal = "F", Tijd = vracht[vr,7], Dag = rep(dag, length(vr)), Cancelled = rep(0, length(vr)), stringsAsFactors = FALSE ) sub.vracht <- sub.vracht %>% dplyr::mutate(Richting = "D", Tijd = Tijd + sample(100:150,nrow(sub.vracht),replace=T)) %>% rbind(sub.vracht) %>% merge(vliegtuig.vracht[,c("Vliegtuigcode","Capaciteit","Vracht")], by = "Vliegtuigcode", all.x = T) %>% dplyr::rename(MaxVracht = Vracht) %>% dplyr::mutate(Vracht = as.integer(MaxVracht * runif(length(vr)*2,min=0.7,max=1))) sub.planning <- rbind.fill(sub.planning, sub.vracht) ################### # Baankeuze ###### ################### # Als er weinig wind staat, wordt geland op baan 4 en opgestegen van baan 3 # Als er meer wind staat, moet de baankeuze worden bepaald o.b.v. de windrichting (DDVEC) # Vliegtuigen willen zo goed mogelijk tegen de wind in opstijgen en landen if(sub.weer$FXX < 100 & sub.weer$FG < 67) { # Wind geen invloed op baankeuze sub.planning[sub.planning$Richting == "A","Baan"] <- 4 sub.planning[sub.planning$Richting == "D","Baan"] <- 3 } else { # Wind heeft wel invloed op baankeuze banen$A_score <- 180 - abs((sub.weer$DDVEC - banen$Landen + 180) %% 360 - 180) #Verschil tussen windrichting en landrichting banen$D_score <- 180 - abs((sub.weer$DDVEC - banen$Opstijgen + 180) %% 360 - 180) #Verschil tussen windrichting en opstijgrichting a.baan <- onesample(arrange(filter(banen, Baannummer != 6),A_score)$Baannummer) d.baan <- (1:5)[-a.baan] d.baan <- onesample(arrange(filter(banen, Baannummer %in% d.baan),D_score)$Baannummer) sub.planning[sub.planning$Richting == "A","Baan"] <- a.baan sub.planning[sub.planning$Richting == "D","Baan"] <- d.baan } ################### # General ######### ################### general$tijd <- sample(350:1100, nrow(general), replace=T) vr <- sample(1:nrow(general), onesample(3:16)) sub.general <- data.frame( Airlinecode = rep("-",length(vr)), Vliegtuigcode = general[vr,3], Destcode = general[vr,2], Vliegtuigtype = general[vr,1], Richting = rep("A",length(vr)), Tijd = general[vr,4], Terminal = "G", Baan = 6, Cancelled = rep(0,length(vr)), stringsAsFactors = FALSE ) sub.general$Richting[sub.general$Destcode == "VAP"] <- "D" sub.general$Destcode[sub.general$Destcode == "VAP"] <- sample(luchthavens.eur, sum(sub.general$Destcode == "VAP"), replace=T) sub.general <- merge(sub.general, vliegtuigtype[,c("IATA","Capaciteit","Vracht")], by.x = "Vliegtuigtype", by.y = "IATA", all.x = T) %>% dplyr::rename(MaxVracht = Vracht) sub.planning <- rbind.fill(sub.planning, sub.general) ################### # Opslaan ######## ################### sub.planning$Datum <- sub.weer$Datum sub.planning$Datum[sub.planning$Cancelled == 0 & sub.planning$Tijd >= 1440] <- sub.planning$Datum[sub.planning$Cancelled == 0 & sub.planning$Tijd >= 1440] + 1 sub.planning$Tijd <- sub.planning$Tijd %% 1440 sub.planning <- dplyr::arrange(sub.planning,Datum,Tijd) sim <- rbind(sim, sub.planning[,vars.simtabel]) print(paste0("Simulatie afgerond van ",sub.weer$Dag," ",funmaand(sub.weer$Maand)," ",sub.weer$Jaar,". Aantal gatewissels: ",wissels)) } rm(sub.planning,sub.general,sub.vracht,sub.weer,beschikbaar,dag,i,slechtzicht,windstoot,winduren,zichturen,a,a.baan,actief,arr,bezet,cancelled,continentaal,d,d.baan,d_row,dub,gate,gates,inactief,j,k,rows,sel,simdagen,v.continent,v.random,v.weer,vr,wissels) sim$Gatewissel <- sim$Plangate != sim$Gate & !is.na(sim$Gate) sim$Type <- "R" sim$Type[!is.na(sim$Vracht)] <- "F" sim$Type[sim$Terminal == "G"] <- "G" # Easter Eggs ############################################################################ ns <- data.frame( Datum = weer$Datum[weer$Dag == 1 & weer$Maand == 4], Vluchtnr = "NS001", Airlinecode = "NS", Destcode = "AMS", Vliegtuigcode = "TNS001", Vliegtuigtype = "TRN", Type = "E", Gatewissel = F, Tijd = 781, Cancelled = 0 ) eek <- data.frame( Datum = weer$Datum[weer$Dag == 31 & weer$Maand == 10], Vluchtnr = "WF4141", Airlinecode = "WF", Destcode = "BOO", Vliegtuigcode = "VWF707", Vliegtuigtype = "DH4", Capaciteit = 70, Bezetting = 100, Passagiers = 70, MaxVracht = 1, Type = "E", Gatewissel = F, Richting = c("A","D"), Tijd = 427, Cancelled = 0 ) sim <- rbind.fill(sim, ns, eek) rm(ns,eek) # Cleanup ############################################################################ sim <- arrange(sim, Datum, Tijd) rownames(sim) <- NULL sim$Vluchtid <- as.integer(rownames(sim)) + 935991 sim <- mutate(sim, Vluchtnr = factor(Vluchtnr), Richting = factor(Richting), Destcode = factor(Destcode), Vliegtuigcode = factor(Vliegtuigcode), Terminal = factor(Terminal), Type = factor(Type)) # Klanttevredenheid ############################################################################ # Maak tabel aan voor klanttevredenheid # Hierin komen routevluchten uit feb 2016, juli 2016, en feb 2017 klant.vars <- c("Vluchtid","Datum", "Zomerdrukte", "Bezetting", "Vertraging", "Gatewissel", "Terminal", "Destcode", "Plantijd", "Type") klant <- subset(sim, month(Datum) %in% c(2,7) & year(Datum) >= 2016 & Type == "R" & Richting == "D" & !is.na(Tijd), select = klant.vars) # 'Tijd' is het aantal dagen sinds 2016, hiermee kunnen dingen over de tijd beter of slechter worden klant <- mutate(klant, Tijd = (Datum - ymd(20160101)) / ddays(1)) # Selecteer 3000 vluchten uit deze dataset onderzoek <- createDataPartition(y = (klant$Tijd %/% 160), p = 3000/nrow(klant), list=F) klant <- klant[onderzoek,] # Operatie # Hoe hoger de bezetting, hoe lager de score (tot een max van -0.5) # Hoe meer vertraging, hoe lager de score (per uur vertraging -1.8) # Een gatewissel leidt tot 1 punt aftrek klant <- mutate(klant, Operatie = rnorm(nrow(klant), 8, 0.5) - 0.5 * Bezetting / 100 - 0.03 * Vertraging - 1 * Gatewissel) ggplot(klant, aes(x=Operatie, y=..count..)) + geom_density(position="stack",size=1.5, adjust=1.5) # Faciliteiten # Gem. score per terminal: A = 5, B = 6.5, C,D,E = 8 # Per jaar gaat de score met 0.3 omlaag # Vluchten naar een niet-vakantiebestemming scoren 20% lager klant <- mutate(klant, Faciliteiten = (rnorm(nrow(klant), 8, .65) - 3*(Terminal == "A") - 1.5*(Terminal == "B") - Tijd/1100) * 0.8 ^ (Zomerdrukte == 1)) ggplot(klant, aes(x=Faciliteiten, y=..count.., fill=Terminal)) + geom_density(position="stack",size=1.5, adjust=1.5) + facet_wrap(~(Tijd %/% 160), nrow=3) # Shops # Vluchten naar een vakantiebestemming scoren 10% lager # Er is geen score voor vluchten tussen 23:00 en 6:00 klant <- mutate(klant, Shops = rnorm(nrow(klant), 6, .75) * 0.9 ^ (Zomerdrukte == 4) ) klant$Shops[klant$Plantijd > 1380 | klant$Plantijd < 360] <- NA ggplot(klant, aes(x=Shops, y=..count..)) + geom_density(size=1.5, adjust=1.5) + facet_wrap(~Zomerdrukte, nrow=2) # Afronden op 1 decimaal en waarden boven de 10 op 10 zetten klant <- mutate(klant, Faciliteiten = pmin(round(Faciliteiten, digits = 1),10), Shops = pmin(round(Shops, digits = 1),10), Operatie = pmin(round(Operatie, digits = 1),10)) rm(onderzoek) # Export ############################################################################ # Selecteer variabelen voor export planning.export <- sim %>% select(Vluchtnr, Airlinecode, Destcode, Planterminal, Plangate, Plantijd) %>% unique() %>% filter(!is.na(Vluchtnr)) %>% arrange(Vluchtnr) %>% mutate(Plantijd = toampm(Plantijd)) vliegtuig.export <- sim %>% select(Airlinecode, Vliegtuigcode, Vliegtuigtype) %>% unique() vliegtuig.export$Bouwjaar = sample(1970:2013, nrow(vliegtuig.export), replace=T) vertrek.export <- sim %>% filter(Richting == "D") %>% select(Vluchtid, Vliegtuigcode, Terminal, Gate, Baan, Bezetting, Vracht, Tijd, Datum) vertrek.export$Vertrektijd <- vertrek.export$Datum + minutes(vertrek.export$Tijd) + seconds(sample(0:59, nrow(vertrek.export), replace=T)) vertrek.export <- vertrek.export %>% select(-Datum, -Tijd) aankomst.export <- sim %>% filter(Richting == "A") %>% select(Vluchtid, Vliegtuigcode, Terminal, Gate, Baan, Bezetting, Vracht, Tijd, Datum) aankomst.export$Aankomsttijd <- aankomst.export$Datum + minutes(aankomst.export$Tijd) + seconds(sample(0:59, nrow(aankomst.export), replace=T)) aankomst.export <- aankomst.export %>% select(-Datum, -Tijd) vlucht.export <- sim %>% select(Vluchtid, Vluchtnr, Airlinecode, Destcode, Vliegtuigcode) klant.export <- klant %>% select(Vluchtid, Operatie, Faciliteiten, Shops) write.csv2(planning.export, file="export_planning.csv", row.names=F, na="") write.csv2(vliegtuig.export, file="export_vliegtuig.csv", row.names=F, na="/N") write.csv2(vertrek.export, file="export_vertrek.csv", row.names=F, na="") write.csv2(aankomst.export, file="export_aankomst.csv", row.names=F, na="") write.csv2(vlucht.export, file="export_vlucht.csv", row.names=F, na="") write.csv2(klant.export, file="export_klant.csv", row.names=F, na="") # Summary & Plots ############################################################################ plot(density(sim$Vertraging, adjust=.75, na.rm = T)) summ <- sim %>% dplyr::group_by(Datum) %>% dplyr::summarise(vertraging = mean(Vertraging,na.rm=T), gatewissels = sum(as.integer(Gatewissel)), gatewisselperc = sum(as.integer(Gatewissel))/n(), vluchten = n(), cancels = sum(Cancelled)) %>% merge(weer, by = "Datum") %>% filter(vluchten > 10) maand <- summ %>% dplyr::group_by(Maand) %>% dplyr::summarise(vorst = sum(vorst), vertraging = mean(vertraging,na.rm=T), gatewissels = sum(gatewissels), vluchten = sum(vluchten), cancels = sum(cancels)) model <- lm(vertraging ~ vluchten + gatewissels + FXX + FG + VVN + VVX + nat + vorst + sneeuw + RH, data = summ) summary(model) plottabel <- sim plottabel$Datum <- as.factor(plottabel$Datum) plottabel$continentaal <- plottabel$Planterminal %in% c("D","E") ggplot(plottabel, aes(x=Vertraging, fill = Gatewissel)) + geom_density(alpha = .5, size=0) + facet_wrap(~continentaal,nrow=5) plot(summ$FG, summ$vertraging) plot(summ$FXX, summ$vertraging) plot(summ$vorst, summ$vertraging) plot(summ$sneeuw, summ$vertraging) plot(summ$RH, summ$vertraging) plot(summ$TG, summ$vertraging)<file_sep>#selecteer benodigde kolommen om klanttevredenheid te berekenen en schrijf naar nieuwe tabel library(lubridate) klanttevredenheid <- subset(sim, month(Datum) == 02, select = c("Vluchtnr", "Datum", "Bezetting", "Vertraging", "Gatewissel", "Terminal", "Destcode", "Planuur")) #creeer kolommen klanttevredenheid <- mutate(klanttevredenheid, Operatie = 0) klanttevredenheid <- mutate(klanttevredenheid, Faciliteiten = 0) klanttevredenheid <- mutate(klanttevredenheid, Shops = 0) #bereken klanttevredenheid Operatie klanttevredenheid <- mutate(klanttevredenheid, Operatie = 8 - 0.5 * Bezetting / 100 - 0.005 * Vertraging - 1 * Gatewissel + rnorm(length(Operatie), 0, 0.5)) klanttevredenheid <- mutate(klanttevredenheid, Operatie = round(Operatie, digits = 1)) #bereken klanttevredenheid Faciliteiten klanttevredenheid <- mutate(klanttevredenheid, Faciliteiten = 8 - 3 * as.integer(Terminal == "A") - 1.5 * as.integer(Terminal == "B") + rnorm(length(Faciliteiten), 0, 0.5)) klanttevredenheid <- mutate(klanttevredenheid, Faciliteiten = round(Faciliteiten, digits = 1)) #bereken klanttevredenheid Shops #passagiers naar Alicante (ALC), zijn meer ontevreden #winkels zijn dicht tussen 23:00 en 6:00 klanttevredenheid <- mutate(klanttevredenheid, Shops = rnorm(length(Shops), 6, 1) - 1 * as.integer(Destcode == "ALC")) klanttevredenheid$Shops[klanttevredenheid$Planuur > 23 | klanttevredenheid$Planuur < 6] <- NA klanttevredenheid <- mutate(klanttevredenheid, Shops = round(Shops, digits = 1))
03ce3eb4176dc4e1a8f9e6ff9183f0619bc44ea2
[ "Text", "R" ]
3
Text
afstam/VisionAirPort
500a5019831aaab0878122320283ea3314065e80
56491d65cde14c0fdcf4f852d606448d4903f31c
refs/heads/master
<file_sep> window['getUrlParameter'] = function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } }; (function() { window['CAFE24-COUNTRY'] = { code: 'ko_KR', use: true // 로컬개발용 언어변환 코드: 배포시에는 (false : 작동해제) 여야 합니다. }; window['CAFE24-COUNTRY'].changeTextCode = function( LANGUAGE, SCOPE ) { if ( !window['CAFE24-COUNTRY'].use ) return; if ( getUrlParameter('langcode') ) window['CAFE24-COUNTRY'].code = getUrlParameter('langcode'); var currentLanguage = LANGUAGE[ window['CAFE24-COUNTRY'].code ], $targetBlock = $( '.' + SCOPE ), pickupStr = $targetBlock.html(); Object.keys( currentLanguage ).forEach(function(key) { pickupStr = pickupStr.replace( new RegExp("#" + key + "#", 'g') , currentLanguage[key] ); }); $targetBlock.html( pickupStr ); }; })(); var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ? true : false; function gridCompatibilityforIE( contextSelector ) { var $gridContext = $(contextSelector), $gridItem = $gridContext.find('>.gridItem'), hasGridTemplate, splitGridTemplate = {}, msGridTemplateStyle = ''; function getInlineStyle($el, prop) { var styles = $el.attr("style"), value; styles && styles.split(";").forEach(function (e) { var style = e.split(":"); if ($.trim(style[0]) === prop) { value = style[1]; } }); return value; } function changeRepeatStyle(a, b) { var countStr = ''; for(var i=0, k = a; i<k; i++) countStr += ' ' + b; return countStr; } hasGridTemplate = getInlineStyle($gridContext, 'grid-template'); if(hasGridTemplate) { splitGridTemplate.row = hasGridTemplate.split('/')[0].trim(); splitGridTemplate.col = hasGridTemplate.split('/')[1].trim(); if(splitGridTemplate.row.match('repeat')) { var repeatCount = splitGridTemplate.row.split('repeat(')[1]; repeatCount = repeatCount.split(')')[0]; repeatCount = repeatCount.split(','); msGridTemplateStyle = '-ms-grid-rows:' + changeRepeatStyle(repeatCount[0], repeatCount[1]); } else { msGridTemplateStyle = '-ms-grid-rows:' + splitGridTemplate.row; } $gridContext.attr('style', $gridContext.attr('style') + ';' + msGridTemplateStyle); if(splitGridTemplate.col.match('repeat')) { var repeatCount = splitGridTemplate.col.split('repeat(')[1]; repeatCount = repeatCount.split(')')[0]; repeatCount = repeatCount.split(','); msGridTemplateStyle = '-ms-grid-columns:' + changeRepeatStyle(repeatCount[0], repeatCount[1]); } else { msGridTemplateStyle = '-ms-grid-columns:' + splitGridTemplate.col; } $gridContext.attr('style', $gridContext.attr('style') + ';' + msGridTemplateStyle); } $gridItem.each(function(idx, element) { var $el = $(element), hasGridArea, msGridAreaStyle; hasGridArea = getInlineStyle($el, 'grid-area'); if(hasGridArea) { hasGridArea = hasGridArea.split('/'); msGridAreaStyle = '-ms-grid-row: '+hasGridArea[0]+'; -ms-grid-column: '+hasGridArea[1]+'; -ms-grid-row-span: '+(hasGridArea[2]-hasGridArea[0])+'; -ms-grid-column-span: '+(hasGridArea[3]-hasGridArea[1])+''; $el.attr('style', $el.attr('style') + ';' + msGridAreaStyle); } }); } // 썸네일 이미지 엑박일경우 기본값 설정 $(window).load(function() { $(".thumbnail img, img.thumbImage, img.bigImage").each(function($i,$item){ var $img = new Image(); $img.onerror = function () { $item.src="//img.echosting.cafe24.com/thumb/img_product_big.gif"; } $img.src = this.src; }); }); $(document).ready(function(){ if ( $.browser.msie || ($.browser.mozilla == true && $.browser.version < 12) ) { // IE Prefix 호환 gridCompatibilityforIE('.gridContainer'); // Size RESET call var sliders = $("[id*='xans-mobile-banner-slider']"); if(sliders.length) { sliders.each(function(idx, el) { var propName = el.id; propName = propName.replace(/\-/g,'_'); window['$'+propName].setup(); }); } } $('body').css({'opacity':1}); // 토글 $('div.eToggle .title').click(function(){ var toggle = $(this).parent('.eToggle'); if(toggle.hasClass('disable') == false){ $(this).parent('.eToggle').toggleClass('selected') } }); $('dl.eToggle dt').click(function(){ $(this).toggleClass('selected'); $(this).next('dd').toggleClass('selected'); }); //장바구니 페이지 수량폼 Type 변경 $('[id^="quantity"]').each(function() { $(this).get(0).type = 'tel'; }); // 모바일에서 공급사 테이블 th 강제조절 $('.xans-mall-supplyinfo, .supplyInfo').find('table > colgroup').find('col').eq(0).width(98); $('.xans-mall-supplyinfo, .supplyInfo').find('th, td').css({padding:'13px 10px 12px'}); /** * 상단탑버튼 */ var globalTopBtnScrollFunc = function() { // 탑버튼 관련변수 var $btnTop = $('#btnTop'); $(window).scroll(function() { try { var iCurScrollPos = $(this).scrollTop(); if (iCurScrollPos > ($(this).height() / 2)) { $btnTop.fadeIn('fast'); } else { $btnTop.fadeOut('fast'); } } catch(e) { } }); }; /** * 구매버튼 */ var globalBuyBtnScrollFunc = function() { // 구매버튼 관련변수 var sFixId = $('#orderFixItem').size() > 0 ? 'orderFixItem' : 'fixedActionButton', $area = $('#orderFixArea'), $item = $('#' + sFixId + '').not($area); $(window).scroll(function(){ try { // 구매버튼 관련변수 var iCurrentHeightPos = $(this).scrollTop() + $(this).height(), iButtonHeightPos = $item.offset().top; if (iCurrentHeightPos > iButtonHeightPos || iButtonHeightPos < $(this).scrollTop() + $item.height()) { if (iButtonHeightPos < $(this).scrollTop() - $item.height()) { $area.fadeIn('fast'); } else { $area.hide(); } } else { $area.fadeIn('fast'); } } catch(e) { } }); }; globalTopBtnScrollFunc(); globalBuyBtnScrollFunc(); }); // 공통레이어팝업 오픈 var globalLayerOpenFunc = function(_this) { this.id = $(_this).data('id'); this.param = $(_this).data('param'); this.basketType = $('#basket_type').val(); this.url = $(_this).data('url'); this.layerId = 'ec_temp_mobile_layer'; this.layerIframeId = 'ec_temp_mobile_iframe_layer'; var _this = this; function paramSetUrl() { if (this.param) { // if isset param } else { this.url = this.basketType ? this.url + '?basket_type=' + this.basketType : this.url; } }; if (this.url) { window.ecScrollTop = $(window).scrollTop(); $.ajax({ url : this.url, success : function (data) { if (data.indexOf('404 페이지 없음') == -1) { // 있다면 삭제 try { $(_this).remove(); } catch ( e ) { } var $layer = $('<div>', { html: $("<iframe>", { src: _this.url, id: _this.layerIframeId, scrolling: 'auto', css: { width: '100%', height: '100%', overflowY: 'auto', border: 0 } } ), id: _this.layerId, css : { position: 'absolute', top: 0, left:0, width: '100%', height: $(window).height(), 'z-index': 9999 } }); $('body').append($layer); $('html, body').css({'overflowY': 'hidden', height: '100%', width: '100%'}); $('#' + this.layerId).show(); } } }); } }; // 공통레이어팝업 닫기 var globalLayerCloseFunc = function() { this.layerId = 'ec_temp_mobile_layer'; if (window.parent === window) self.clse(); else { parent.$('html, body').css({'overflowY': 'auto', height: 'auto', width: '100%'}); parent.$('html, body').scrollTop(parent.window.ecScrollTop); parent.$('#' + this.layerId).remove(); } }; /** * document.location.href split * return array Param */ var getQueryString = function(sKey) { var sQueryString = document.location.search.substring(1); var aParam = {}; if (sQueryString) { var aFields = sQueryString.split("&"); var aField = []; for (var i=0; i<aFields.length; i++) { aField = aFields[i].split('='); aParam[aField[0]] = aField[1]; } } aParam.page = aParam.page ? aParam.page : 1; return sKey ? aParam[sKey] : aParam; }; // PC버전 바로 가기 var isPCver = function() { var sUrl = window.location.hostname; var aTemp = sUrl.split("."); var pattern = /^(mobile[\-]{2}shop[0-9]+)$/; if (aTemp[0] == 'm' || aTemp[0] == 'skin-mobile' || aTemp[0] == 'mobile') { sUrl = sUrl.replace(aTemp[0]+'.', ''); } else if (pattern.test(aTemp[0]) === true) { var aExplode = aTemp[0].split('--'); aTemp[0] = aExplode[1]; sUrl = aTemp.join('.'); } window.location.href = '//'+sUrl+'/?is_pcver=T'; }; /* 도움말 */ $('body').delegate('.ec-base-tooltip-area .eTip', 'click', function(e){ var findArea = $($(this).parents('.ec-base-tooltip-area')); var findTarget = $($(this).siblings('.ec-base-tooltip')); var findTooltip = $('.ec-base-tooltip'); $('.ec-base-tooltip-area').removeClass('show'); $(this).parents('.ec-base-tooltip-area:first').addClass('show'); findTooltip.hide(); findTarget.show(); e.preventDefault(); }); $('body').delegate('.ec-base-tooltip-area .eClose', 'click', function(e){ var findTarget = $(this).parents('.ec-base-tooltip:first'); $('.ec-base-tooltip-area').removeClass('show'); findTarget.hide(); e.preventDefault(); }); $('.ec-base-tooltip-area').find('input').focusout(function() { var findTarget = $(this).parents('.ec-base-tooltip-area').find('.ec-base-tooltip'); $('.ec-base-tooltip-area').removeClass('show'); findTarget.hide(); }); /** * 컴포넌트와 연동되는 기본 기능 */ $(window).load(function() { /** * 가로형 스크롤바 제어 */ if( $('.horizontal-scrollable').length ) { $('.horizontal-scrollable').mCustomScrollbar({ axis:"x", theme:"dark-2", autoExpandScrollbar: false, autoHideScrollbar: true, updateOnContentResize: true, mouseWheel:{ enable: true, scrollAmount: 140 } }); } if($('.eProductSort').length) { $('.eProductSort').each(function() { $(this).find('button').click(function() { if ($(this).hasClass('selected')) { } else { $(this).addClass('selected'); $(this).siblings('button').removeClass('selected'); if ($(this).hasClass('smallView')) { $(this).parent('.eProductSort').next('.prdList').addClass('small'); }else{ $(this).parent('.eProductSort').next('.prdList').removeClass('small'); } } }); }); } }); /** 모바일쇼핑몰 슬라이딩메뉴 **/ $(document).ready(function(){ $('#header .header').append('<div id="dimmedSlider"></div>'); var offCover = { init : function() { $(function() { offCover.resize(); $(window).resize(function(){ offCover.resize(); }); }); }, layout : function(){ if ($('html').hasClass('expand')) { $('#aside').css({'visibility':'visible'}); $('html, body').css({"overflow-x":""}) } else { setTimeout(function(){ $('#aside').css({'visibility':''}); }, 300); } $('#aside').css({'visibility':'visible'}); }, resize : function(){ var height = $('body').height(); $('#container').css({'min-height':height}); } }; offCover.init(); $('#header .btnCate, #aside .btnClose').click(function(e){ e.preventDefault(); $('#dimmedSlider').toggle(); $('html').toggleClass('expand'); $('#dimmedSlider').one('click', function(e) { $('html').toggleClass('expand'); $('#dimmedSlider').toggle(); }); offCover.layout(); }); if( getUrlParameter('PREVIEW_SDE') == 1 ) { // $('#header .btnCate').trigger('click'); } }); <file_sep>$(window).scroll(function(){ if($(document).scrollTop() > 0) { $('.nav').addClass('fixed'); } else { $('.nav').removeClass('fixed'); } return; }); /* gnb */ $(document).ready(function(){ $('.gnb_wrap').hover( function() { $(this).addClass('opened'); }, function() { $(this).removeClass('opened'); } ) }); /* 검색 */ $('.ic_sch').click(function() { $('.schArea').stop().fadeToggle(100); }); $('.sch_close').click(function() { $('.schArea').stop().fadeToggle(100); }); $('.sch_cover').click(function() { $('.schArea').stop().fadeToggle(100); }); /* 카테고리 끌어오기 */ $(document).ready(function(){ var $d1_wrap = $('.d1Box'); var $d1_list = $d1_wrap.find('.d1'); var len = $d1_list.length; $.ajax({ url : '/exec/front/Product/SubCategory', dataType: 'json', success: function(aData) { if (aData == null || aData == 'undefined') { return; } $.each(aData, function(index, key) { var $d1 = $d1_wrap.find('.d1[data-param$="=' + key.parent_cate_no + '"]'); var $d2 = $d1_wrap.find('.d2[data-param$="=' + key.parent_cate_no + '"]'); var $d3 = $d1_wrap.find('.d3[data-param$="=' + key.parent_cate_no + '"]'); if ($d1.length > 0) { var _index = $d1_list.index($d1); if ($d1.hasClass('pre') === false) { $d1.addClass('pre'); $d1.append('<ul class="d2Box"></ul>'); } $d1.find('.d2Box').append('<li class="d2" data-param="'+key.param+'"><a href="/product/list.html'+key.param+'"><span>'+key.name+'</span></a></li>'); return; } }); //setCategory(); } }); }); <file_sep>$(document).ready(function() { var filter = "win16|win32|win64|mac|macintel"; var device = "pc"; if (navigator.platform) { if (filter.indexOf(navigator.platform.toLowerCase()) < 0) { device = "mobile"; } } /** * 상품상세, 상품 확대보기(팝업) - 소비자가 할인표시 */ var oPriceInfoEl = $('#ec-product-price-info'); if (oPriceInfoEl.length > 0) { var salePriceEl = $('#span_product_price_text'); percentageCul(oPriceInfoEl, salePriceEl); } /** * 상품목록/메인진열 - 소비자가 할인표시*/ var mainEl = $(".main") + $(".layout"); if (mainEl.length > 0) { var productListEl = $('.xans-product-listmain, .xans-product-listrecommend, .xans-product-listnew, .xans-product-listnormal'); for (var i = 0; i < productListEl.length; i++) { var prdListEl = productListEl.eq(i).find('.prdList > li'); for (var j = 0; j < prdListEl.length; j++) { var priceEl = prdListEl.eq(j).find('.description'), salePriceEl = priceEl.find('.xans-product > li').eq(1).find('span:eq(1)'); if (device == "mobile") { salePriceEl = priceEl.find('.spec > li.price'); } percentageCul(priceEl, salePriceEl); } } } function percentageCul(target, salePriceEl) { var iCustomPrice = parseInt(target.attr('ec-data-custom')), iPrice = parseInt(target.attr('ec-data-price')), prdImg = prdListEl.eq(j).find('.thumbnail'), sDisplayAmount = 'p', // p:할인율, w:할인금액 iOfftoFixed = 0, // 할인율 소수점자릿수 sSaleText = '', regexp = /\B(?=(\d{3})+(?!\d))/g; if (iCustomPrice > 0 && iPrice > 0 && iPrice != iCustomPrice) { if (sDisplayAmount == 'p') { sSaleText = (((iCustomPrice - iPrice) / iCustomPrice) * 100).toFixed(iOfftoFixed) + '<span>%</span>'; } else if (sDisplayAmount == 'w') { sSaleText = parseInt(iCustomPrice - iPrice).toString().replace(regexp, ',') + '원'; } prdImg.prepend('<div class="ic_sale mov03"> ' + sSaleText + '</div>'); } } });<file_sep>- sde_design/skin5 - murmure 스킨 (Prod) - sde_design/skin6 - murmure 스킨 (Dev) - sde_design/mobile1 - murmure mobile skin (Prod) - sde_design/mobile2 - murmure mobile skin (Dev) <file_sep>$(".relation-slick").slick({ dots: false, infinite: true, autoplay: false, slidesToShow: 6, slidesToScroll: 1 }); <file_sep>/* 현금영수증 팝업창 리사이즈 */ (function(){ setTimeout(function(){ var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); if (!isMobile) return window.resizeTo(450, 270); }, 100) })(); <file_sep>[24] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [25] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [27] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [26] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [28] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [31] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [23] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" <file_sep><!--@layout(/layout/basic/popup.html)--> <!--@css(/css/module/myshop/receiverUpdate.css)--> <div class="ec-base-layer" module="myshop_OrderReceiverUpdate"> <div class="header"> <h1>배송지 변경</h1> <button type="button" class="btnClose" id="{$receiver_update_popup_close_top_id}">닫기</button> </div> <div class="content"> <div class="ec-base-table typeWrite"> <table summary="" border="1"> <caption>배송지 변경</caption> <colgroup> <col style="width:102px;" /> <col style="width:auto;" /> </colgroup> <!-- 국내 배송지 정보 --> <tbody class="{$r_info_display|display}"> <tr> <th scope="row">수령자명 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.r_name} </td> </tr> <tr> <th scope="row">주소 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.r_zipcode} <button type="button" id="{$zipcode_finder}" class="btnNormal">{$zipcode_finder_text}</button><br /> <span class="gBlank10">{$form.r_addr1}</span> <span class="gBlank10">{$form.r_addr2}</span> </td> </tr> <tr class="{$use_delivery_tel_display|display}"> <th scope="row">일반전화 <img class="{$is_delivery_tel_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.r_phone} </td> </tr> <tr class="{$use_delivery_cell_display|display}"> <th scope="row">휴대전화 <img class="{$is_delivery_cell_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.r_mobile} </td> </tr> <tr class="{$use_delivery_message_display|display}"> <th scope="row">배송메시지 <img class="{$is_delivery_message_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td>{$form.r_message}</td> </tr> </tbody> <!-- 해외 배송지 정보 --> <tbody class="{$f_info_display|display}"> <!-- 참조 : 이름 한번에 입력 --> <tr class="{$use_connected_name_input_display|display}"> <th scope="row">수령자명 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name} </td> </tr> <!-- 참고 : 이름 각각 입력 --> <tr class="{$use_seperate_name_input_display|display}"> <th scope="row">수령자명 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name_1} {$form.f_name_2} </td> </tr> <!-- 참고 : 영문이름 한번에 입력 --> <tr class="{$use_orders_english_name_display|display} {$use_connected_name_input_display|display}"> <th scope="row">수령자명<br />(영문) <img class="{$is_orders_english_name_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name_en} </td> </tr> <!-- 참고 : 영문이름 각각 입력 --> <tr class="{$use_orders_english_name_display|display} {$use_seperate_name_input_display|display}"> <th scope="row">수령자명<br />(영문) <img class="{$is_orders_english_name_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name_en_1} {$form.f_name_en_2} </td> </tr> <!-- 참고 : 이름(발음기호) 한번에 입력 --> <tr class="{$use_orders_pronounce_name_display|display} {$use_connected_name_input_display|display}"> <th scope="row">수령자명<br />(발음기호) <img class="{$is_orders_pronounce_name_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name_phonetic} </td> </tr> <!-- 참고 : 이름(발음기호) 각각 입력 --> <tr class="{$use_orders_pronounce_name_display|display} {$use_seperate_name_input_display|display}"> <th scope="row">수령자명<br />(발음기호) <img class="{$is_orders_pronounce_name_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_name_phonetic_1} {$form.f_name_phonetic_2} </td> </tr> <!-- 배송 국가 --> <tr> <th scope="row">국가 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$f_country_text} </td> </tr> <!-- 배송지 주소 --> <tr> <th scope="row">주소 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_zipcode} <button type="button" id="{$f_zipcode_finder}" class="btnNormal {$f_find_address_button_display|display}">{$zipcode_finder_text}</button> <span class="{$f_no_zipcode_checkbox_display|display}">{$form.f_no_zipcode}</span> <span class="gBlank10">{$form.f_address_street}</span> <span class="gBlank10">{$form.f_address_detail}</span> </td> </tr> <!-- 시/군/도시 --> <tr class="{$f_address_state_display|display}"> <th scope="row">시/군/도시 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_address_city} </td> </tr> <!-- 주/도 --> <tr class="{$f_address_city_display|display}"> <th scope="row">주/도 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_address_state} {$form.f_address_state_us} {$form.f_address_state_ca} </td> </tr> <!-- 일반전화 --> <tr class="{$use_delivery_tel_display|display}"> <th scope="row">일반전화 <img class="{$is_delivery_tel_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_phone} </td> </tr> <!-- 휴대전화 --> <tr class="{$use_delivery_cell_display|display}"> <th scope="row">휴대전화 <img class="{$is_delivery_cell_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_mobile} </td> </tr> <!-- 신분증 유형 --> <tr class="{$use_receiver_id_card_key_display|display}"> <th scope="row">신분증 유형 <img src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_receiver_id_card_type} <span class="gBlank10">{$form.f_receiver_id_card_key}</span> </td> </tr> <!-- 배송메세지 --> <tr> <th scope="row">배송메시지 <img class="{$is_delivery_message_required_display|display}" src="//img.echosting.cafe24.com/skin/base/common/ico_required_blue.gif" alt="필수" /></th> <td> {$form.f_message} </td> </tr> </tbody> </table> </div> </div> <div class="ec-base-button"> <button id="{$receiver_update_submit_id}" type="button" class="btnStrong">변경하기</button> <a href="#none" id="{$receiver_update_popup_close_id}" class="btnNormal">닫기</a> </div> </div><file_sep>/********************************************************************************************************************* ◆◆◆ IDIO 디자인 셋팅 파일입니다. 반드시 아래 내용 숙지 후 수정해 주세요! ◆◆◆ - 반드시 작은 따옴표('') 안 문구만 수정해서 사용해 주세요. - 따옴표 안 문구를 제외한 여타 내용(괄호, 따옴표, 기타 텍스트 등) 변경이나 삭제시 사이트 전체에 오류를 일으킬 수 있습니다. - 따옴표 안 따옴표, 줄바꿈 사용시 오류가 발생합니다. 가급적 특수문자가 없는 텍스트를 입력해서 사용해 주세요. - 진열 여부 설정은 on/off 중 택일하여 기입해 주세요. (ex. 'on', 'off') - 내용 수정 후 적용된 화면 확인 시에는 반드시 인터넷 쿠키를 삭제하고 새로고침(F5)해 주세요.(★★★★★) ※ 본 파일은 디자인 내 간단한 텍스트, 영역별 진열 여부를 변경하는 용도이며, 세부적인 디자인 수정은 불가능합니다. ※ 오류 발생 시, 초기 파일 복구는 '/디자인폴더/_idio/js/' 폴더 안 setup_backup.js를 활용해 주세요. *********************************************************************************************************************/ /* ■ 메인페이지 기본셋팅 ■ */ /*-------------------------------------------------------------------------------------------------------------------- ▶ A-메인배너 사용 여부 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-mainBnr'] = 'on'; /*-------------------------------------------------------------------------------------------------------------------- ▶ B-배너영역 사용 여부 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-bnrArea1'] = 'on'; /*-------------------------------------------------------------------------------------------------------------------- ▶ C-일반 상품 리스트1 설정 - class-prdArea1 : 해당 리스트 진열 여부 - class-prdArea1-ul : 열수 지정 (grid2~grid5 중 택일, 한 칸 띄고 gallery 기입시 갤러리 타입으로 사용 가능) - text-prdArea1-tit : 타이틀 - text-prdArea1-tit : 서브 문구 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-prdArea1'] = 'on'; IDIO['class-prdArea1-ul'] = 'grid4'; IDIO['text-prdArea1-tit'] = 'murmure best'; IDIO['text-prdArea1-copy'] = '일반 상품 리스트1입니다. 타이틀과 서브 문구 교체가 가능합니다.'; /*-------------------------------------------------------------------------------------------------------------------- ▶ D-탭형식 상품 리스트 설정 ※ 키워드 갯수 조정 불가 - class-prdTab : 해당 리스트 진열 여부 - text-prdTab-tit : 타이틀 - text-prdTab-tit-num : 키워드 텍스트 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-prdTab'] = 'on'; IDIO['text-prdTab-tit-1'] = '뮤르뮤르 베스트'; IDIO['text-prdTab-tit-2'] = 'MD`s pick'; IDIO['text-prdTab-tit-3'] = '투데이 스페셜'; IDIO['text-prdTab-tit-4'] = 'Edited For You'; /*-------------------------------------------------------------------------------------------------------------------- ▶ E-일반 상품 리스트2 설정 - class-prdArea2 : 해당 리스트 진열 여부 - class-prdArea2-ul : 열수 지정 (grid2~grid5 중 택일, 한 칸 띄고 gallery 기입시 갤러리 타입으로 사용 가능) - text-prdArea2-tit : 타이틀 - text-prdArea2-tit : 서브 문구 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-prdArea2'] = 'on'; IDIO['class-prdArea2-ul'] = 'grid3 gallery'; IDIO['text-prdArea2-tit'] = 'murmure special'; IDIO['text-prdArea2-copy'] = '일반 상품 리스트2입니다. 타이틀과 서브 문구 교체가 가능합니다.'; /*-------------------------------------------------------------------------------------------------------------------- ▶ G-동영상영역 사용 여부 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-vodArea1'] = 'on'; IDIO['text-vodArea1-tit'] = 'murmure video'; IDIO['text-vodArea1-copy'] = 'VOD 재생 영역입니다. 유튜브 URL을 교체해 주세요!'; /*-------------------------------------------------------------------------------------------------------------------- ▶ H-게시판 영역 설정 - class-bbsArea1 : 진열 여부 - text-bbsArea1-tit : 타이틀 - text-bbsArea1-tit : 서브 문구 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-bbsArea1'] = 'on'; IDIO['text-bbsArea1-tit'] = 'news & column'; IDIO['text-bbsArea1-copy'] = '게시판 영역입니다. 칼럼 또는 이벤트 게시판으로 활용해 보세요!'; /*-------------------------------------------------------------------------------------------------------------------- ▶ G-인스타그램 위젯 사용 여부 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-insta'] = 'on'; /*-------------------------------------------------------------------------------------------------------------------- ▶ H-멀티팝업 사용 여부 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-popup-idio'] = 'on'; /* ■ 기타 공통 항목 기본셋팅 ■ ***/ /*-------------------------------------------------------------------------------------------------------------------- ▶ 상단 좌측 스페셜 버튼 설정 --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-gnb-btn'] = 'on'; IDIO['text-gnb-btn'] = '신규회원 웰컴 쿠폰10%'; IDIO['href-gnb-btn'] = 'http://www.idio.co.kr/'; /*-------------------------------------------------------------------------------------------------------------------- ▶ 상품 썸네일 롤오버시 상세이미지 전환 여부 ※ on, off 중 선택하여 기입 ※ on 선택시 상세이미지, 목록이미지의 사이즈가 반드시 동일해야 합니다. --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-tmb-over'] = 'off'; /*-------------------------------------------------------------------------------------------------------------------- ▶ SNS 버튼 설정 - class-follow : 진열 여부 - href-follow : 연결 URL --------------------------------------------------------------------------------------------------------------------*/ // 인스타그램 IDIO['class-follow-1'] = 'on'; IDIO['href-follow-1'] = 'http://www.instagram.com/'; // 네이버 IDIO['class-follow-2'] = 'off'; IDIO['href-follow-2'] = ''; // 유튜브 IDIO['class-follow-3'] = 'off'; IDIO['href-follow-3'] = ''; // 트위터 IDIO['class-follow-4'] = 'off'; IDIO['href-follow-4'] = ''; // 페이스북 IDIO['class-follow-5'] = 'on'; IDIO['href-follow-5'] = 'http://www.youtube.com/'; /*-------------------------------------------------------------------------------------------------------------------- ▶ 고객센터 운영시간 - text-cstime-1 : 운영시간1 - text-cstime-2 : 운영시간2(휴무일 등 추가정보) --------------------------------------------------------------------------------------------------------------------*/ IDIO['text-cstime-1'] = '운영시간 : 평일 09:00 ~ 18:00'; IDIO['text-cstime-2'] = '(토, 일, 공휴일 휴무)'; /*-------------------------------------------------------------------------------------------------------------------- ▶ 상품 분류 페이지 상품 열수 지정 (grid2~grid5 중 택일) --------------------------------------------------------------------------------------------------------------------*/ IDIO['class-prdNml'] = 'grid3'; <file_sep>$('.mainBnr-slider').slick({ dots: true, arrows: true, infinite: true, speed: 500, fade: true, autoplay: true, pauseOnHover: false, pauseOnFocus: false, draggable: false, cssEase: 'linear' });<file_sep>$(window).scroll(function(){ if($(document).scrollTop() > 450) { $('.btnTop').fadeIn(200); } else { $('.btnTop').fadeOut(200); } return; }); $(function() { $('.gototop .top').click(function() { $('html, body').animate({scrollTop:0}, 'slow'); return false; }); $('.gototop .bottom').click(function() { $('html, body').animate({scrollTop:$(document).height()}, 'slow'); return false; }); });<file_sep>/* 서랍기능 */ $('#menu .arr').live("click", function(e){ //$('#menu .d2Box').slideUp('normal'); if($(this).parent().hasClass("d1")) { $('#menu .d2Box').slideUp(200); $('#menu .d1 .open').removeClass('open-selected'); $('#menu .d1').removeClass('open-li'); }else if($(this).parent().hasClass("d2")) { $('#menu .d3Box').slideUp(200); $('#menu .d2 .open').removeClass('open-selected'); $('#menu .d2').removeClass('open-li'); }else if($(this).parent().hasClass("d3")) { $('#menu .d4Box').slideUp(200); $('#menu .d3 .open').removeClass('open-selected'); $('#menu .d3').removeClass('open-li'); } if($(this).siblings('.open').next().is(':hidden') == true) { $(this).siblings('.open').addClass('open-selected'); $(this).parent('li').addClass('open-li'); $(this).siblings('.open').next().slideDown(200); } }); /* 카테고리 끌어오기 */ $(document).ready(function(){ var $d1_wrap = $('.d1Box'); var $d1_list = $d1_wrap.find('.d1'); var len = $d1_list.length; $.ajax({ url : '/exec/front/Product/SubCategory', dataType: 'json', success: function(aData) { if (aData == null || aData == 'undefined') { return; } $.each(aData, function(index, key) { var $d1 = $d1_wrap.find('.d1[data-param$="=' + key.parent_cate_no + '"]'); var $d2 = $d1_wrap.find('.d2[data-param$="=' + key.parent_cate_no + '"]'); var $d3 = $d1_wrap.find('.d3[data-param$="=' + key.parent_cate_no + '"]'); if ($d1.length > 0) { var _index = $d1_list.index($d1); if ($d1.hasClass('pre') === false) { $d1.addClass('pre'); $d1.append('<ul class="d2Box"></ul>'); } $d1.find('.d2Box').append('<li class="d2" data-param="'+key.param+'"><a href="/product/list.html'+key.param+'">'+key.name+'</a></li>'); return; } if ($d2.length > 0) { if ($d2.hasClass('pre') === false) { $d2.addClass('pre'); $d2.append('<ul class="d3Box"></ul>'); } $d2.find('.d3Box').append('<li class="d3" data-param="'+key.param+'"><a href="/product/list.html'+key.param+'">'+key.name+'</a></li>'); return; } }); $("div#menu .pre").each(function(k,v) { $(this).children("a").addClass("open").parent('li').append("<a class='arr'><i class='fas fa-chevron-down'></i><i class='fas fa-chevron-up'></i></a>"); }); //setCategory(); } }); });<file_sep>$('.prdTab-slider').slick({ dots: true, infinite: true, speed: 500, fade: true, arrows: false, cssEase: 'linear', appendDots: $('.prdTab-indicators'), customPaging: function customPaging(slider, i) { return '<span class="prdTab-tit-' + (i + 1) + '"></span>'; } });<file_sep>$(document).ready(function(){ function setLoad(){ var keySlit; var keyElementSlit; var elementSelector; var classSlit; var listNum = new Object(); $.each(IDIO, function(key, value){ keySlit = null; keyElementSlit = null; elementSelector = null; classSlit = null; keySplit = key.split('-'); keyElementSlit = key.split('-'); keyElementSlit.splice(0, 1); elementKey = keyElementSlit.join("-"); if(keySplit[0]=='text'){ if($('#'+elementKey).length > 0){ elementSelector = '#'; }else{ if($('.'+elementKey).length > 0){ elementSelector = '.'; } } // console.info($(elementSelector+elementKey)) $(elementSelector+elementKey).text(value); } if(keySplit[0]=='class'){ if($('#'+elementKey).length > 0){ elementSelector = '#'; }else{ if($('.'+elementKey).length > 0){ elementSelector = '.'; } } classSlit = value.split(','); $.each(classSlit, function(idx, classItem){ classItem = classItem.trim(); if(!$(elementSelector+elementKey).hasClass(classItem)){ $(elementSelector+elementKey).addClass(classItem); } }); } if(keySplit[0]=='href'){ if($('#'+elementKey).length > 0){ elementSelector = '#'; }else{ if($('.'+elementKey).length > 0){ elementSelector = '.'; } } $(elementSelector+elementKey).attr('href', value); } }); } setLoad(); }); var IDIO = {}; $(document).ready(function(){ $(".on").show(); $(".off").remove(); }); $(window).on('load',function(){ animateInView(); }); $(window).scroll(function() { animateInView(); }); function animateInView(){ var scrolledAmount = $(window).scrollTop(), bottomOfWindow = scrolledAmount + $(window).height(); $('.fadeIn').each(function () { var cardTop = $(this).offset().top; if(cardTop <= bottomOfWindow ){ $(this).addClass('animate'); } }); $('.fadeInUp').each(function () { var cardTop = $(this).offset().top; if(cardTop <= bottomOfWindow ){ $(this).addClass('animate'); } }); $('.fadeInDown').each(function () { var cardTop = $(this).offset().top; if(cardTop <= bottomOfWindow ){ $(this).addClass('animate'); } }); $('.fadeInRight').each(function () { var cardTop = $(this).offset().top; if(cardTop <= bottomOfWindow ){ $(this).addClass('animate'); } }); $('.fadeInLeft').each(function () { var cardTop = $(this).offset().top; if(cardTop <= bottomOfWindow ){ $(this).addClass('animate'); } }); };<file_sep>$(document).ready(function(){ var reviewer = ($.CAFE24_SDK_REVIEWER_UP) ? $.CAFE24_SDK_REVIEWER_UP.skin.shift() : false; //console.log($.CAFE24_SDK_REVIEWER_UP, reviewer, 3); var rowData = {}; var modeSet = ["img", "text", "all"]; var gpage = 1; var gtotalpage; var gpno; var glimit; var gtype; var gdetail; var guse_point; var config; var sort; var moreBtn = $(".skin_grid2 .prv_table").next(".skin_grid2 .more"); var readyFlag = true; init(); function init() { if ( reviewer && reviewer.data.length > 0) { gtotalpage = reviewer.total_page; gpno = reviewer.pno; glimit = reviewer.cnt; gtype = reviewer.type; gdetail = reviewer.detail; guse_point = reviewer.config.use_point; config = reviewer.config; sort = reviewer.sort; if (moreBtn.length > 0 && gtotalpage > 1) { moreBtn.show(); } $('.skin_grid2 .prv_table td img[src=""]').hide(); initData(); setEvt(); } else { $('.rvArea1').remove(); } $(".skin_grid2 .prv_table tbody").show(); } // 작업 텍스트 자르기후 ... 추가 function textOverCut(txt, len, lastTxt) { if (len == "" || len == null) { // 기본값 len = 20; } if (lastTxt == "" || lastTxt == null) { // 기본값 lastTxt = "..."; } if (txt.length > len) { txt = txt.substr(0, len) + lastTxt; } return txt; } function initData() { hideElem(); if (reviewer.data && reviewer.data.length > 0) { for (var i=0; i<reviewer.data.length; i++) { var row = reviewer.data[i]; row.index = i; if (typeof row.rcont == 'string') { row.rcont = "<span class='cont_dtl'>" + row.rcont.replace(/<p[^>]*>/g,'').replace(/<\/p>/g,'<br/>') + "</span>"; // 작업 45 글자로 자르기 var byt = 100; var cutTxt = textOverCut(row.rcont.replace(/<p[^>]*>/g,'').replace(/(<([^>]+)>)/gi, "").replace(/<\/p>/g,'<br/>'),byt); row.rcont += "<span class='cont_list'>" + cutTxt + "</span>"; } rowData[row.no] = row; } } } function setEvt() { $(document).delegate(".skin_grid2 .rv_btn_close", 'click', function(e){ e.preventDefault(); var tr = $(this).parent().parent(); if (tr.hasClass('selected')) { $(".skin_grid2 .prv_table").find("tr").removeClass("selected"); $(".skin_grid2 .reviewDetail").hide().remove(); } else { $(".skin_grid2 .prv_table").find("tr").removeClass("selected"); $(".skin_grid2 .reviewDetail").hide().remove(); var tr = $(this).parent().parent(); var no = $(this).attr("href"); var rel_no = $(this).attr("rel"); if (rel_no) { no = rel_no; } showDetail(tr, no); tr.addClass('selected'); $(".skin_grid2 .reviewDetail").show(); } }); $(document).delegate(".skin_grid2 .preview_detail", 'click', function(e){ e.preventDefault(); var tr = $(this).parent().parent(); if (tr.hasClass('selected')) { $(".skin_grid2 .prv_table").find("tr").removeClass("selected"); $(".skin_grid2 .reviewDetail").hide().remove(); } else { $(".skin_grid2 .prv_table").find("tr").removeClass("selected"); $(".skin_grid2 .reviewDetail").hide().remove(); var tr = $(this).parent().parent(); var no = $(this).attr("href"); var rel_no = $(this).attr("rel"); if (rel_no) { no = rel_no; } showDetail(tr, no); tr.addClass('selected'); $(".skin_grid2 .reviewDetail").show(); } }); $(".skin_grid2 .photoreview-outputNumber").change(function(e){ var val = $(this).val(); val = parseInt(val, 10); if (typeof val == 'number' && val > 0) { glimit = val; gpage = 1; $.CAFE24_SDK_REVIEWER_UP.call_more({act:'getMore',pno:gpno, next:gpage, cnt:glimit, mode:gtype, point:guse_point, config:config, sort:sort}, page_refresh); } }); $(".skin_grid2 .photoreview-viewMode").change(function(e){ var val = $(this).val(); val = (val == 'txt') ? 'text' : val; if ($.inArray(val, modeSet) !== -1) { gtype = val; gpage = 1; $.CAFE24_SDK_REVIEWER_UP.call_more({act:'getMore',pno:gpno, next:gpage, cnt:glimit, mode:gtype, point:guse_point, config:config, sort:sort}, page_refresh); } }); $(document).delegate(".skin_grid2 .photoreview .photoreview-paging a", "click", function(e){ e.preventDefault(); var page = $(this).attr("href"); if (page) { page = parseInt(page, 10); if (!isNaN(page)) { $.CAFE24_SDK_REVIEWER_UP.call_more({act:'getMore',pno:gpno, next:page, cnt:glimit, mode:gtype, point:guse_point, config:config, sort:sort}, page_refresh); } } }); //support old version moreBtn.find('a').click(function(e){ e.preventDefault(); if (gpage >= gtotalpage) { moreBtn.hide(); return false; } if (readyFlag == true) { readyFlag = false; moreBtn.hide(); $.CAFE24_SDK_REVIEWER_UP.call_more({act:'getMore',pno:gpno, next:gpage+1, cnt:glimit, mode:gtype, point:guse_point, config:config, sort:sort}, page_refresh_old); } }); } function page_refresh(list) { reviewer = list; initData(); var data = list.data; if (data && data.length > 0) { $(".skin_grid2 .prv_table tbody").hide().html(''); for(var i=0; i<data.length; i++) { var cell = makeCell(data[i]); if (cell) { $(".skin_grid2 .prv_table tbody").append(cell); } } if (typeof list.pagination == "string") { $(".skin_grid2 .photoreview .photoreview-paging").html(list.pagination); } hideElem(); $(".skin_grid2 .prv_table tbody").show(); gpage = reviewer.page; if (gpage >= gtotalpage) { moreBtn.hide(); } else { moreBtn.show(); } readyFlag = true; } } function page_refresh_old(list) { reviewer = list; initData(); var data = list.data; if (data && data.length > 0) { for(var i=0; i<data.length; i++) { var cell = makeCell(data[i]); if (cell) { $(".skin_grid2 .prv_table tbody").append(cell); } } hideElem(); $(".skin_grid2 .prv_table tbody").show(); gpage = reviewer.page; if (gpage >= gtotalpage) { moreBtn.hide(); } else { moreBtn.show(); } readyFlag = true; } } function showDetail(tr, no) { if (rowData[no]) { var row = rowData[no]; if (row) { var imgs = makeImgTags(row); if (typeof imgs == "object" && imgs.length > 0) { for(var i=0; i < imgs.length; i++) { imgs.splice(imgs.indexOf(imgs[i]),1,"<div class='item'>"+imgs[i]+"</div>"); } var imgs_html = imgs.join(''); // 작업 imgs_html 앞에 <div> 추가 var detail = '<tr class="reviewArea reviewDetail"><td colspan="8"><a class="rv_btn_close"></a><div class="imgBox"><a href="#none" class="prev"></a><a href="#none" class="next"></a><div>'+imgs_html+'</div></div><div class="contBox"><div class="rv_info"><p class="rate"><img src="/_idio/img/ico_point_'+row.rpoint+'.png"></p><p class="subject">'+row.rsub+'</p><p class="writer"><span class="writer">'+row.rwriter+'</span><span class="date">'+row.rdate+'</span></p><a href="/surl/P/'+row.pno+'"><img src="'+row.pimg_tiny+'" class="prd_tmb"></a></div><div class="rv_content">'+row.rcont+'</div></div></td></tr>'; } else { var detail = '<tr class="reviewArea reviewDetail"><td colspan="8"><a class="rv_btn_close"></a><div class="contBox"><div class="rv_info"><p class="rate"><img src="/_idio/img/ico_point_'+row.rpoint+'.png"></p><p class="subject">'+row.rsub+'</p><p class="writer"><span class="writer">'+row.rwriter+'</span><span class="date">'+row.rdate+'</span></p><a href="/surl/P/'+row.pno+'"><img src="'+row.pimg_tiny+'" class="prd_tmb"></a></div><div class="rv_content">'+row.rcont+'</div></div></td></tr>'; } detail = $(detail); tr.after(detail); //조회수 //$.ajax({type:"GET",url:"/apps/photoreview/photodetail.xml?no="+row.rno,success:function(data){}}); _IE8_width_fix(detail); // 작업 이미지슬라이더 부분 setTimeout(function() { $(".skin_grid2 .reviewArea .imgBox .item:first").css("opacity","1"); $(".skin_grid2 .reviewArea .imgBox .item:first").addClass("active"); if($(".skin_grid2 .reviewArea .imgBox .item.active").next().length == 0) $(".skin_grid2 .reviewArea .imgBox .next").hide(); if($(".skin_grid2 .reviewArea .imgBox .item.active").prev().length == 0) $(".skin_grid2 .reviewArea .imgBox .prev").hide(); }, 1); setTimeout(function() { $(".skin_grid2 .reviewArea .imgBox .next").click(function (e) { $dom = $(".skin_grid2 .reviewArea .imgBox .item.active").next(); $(".skin_grid2 .reviewArea .imgBox .item").removeClass("active"); $dom.addClass("active"); if($(".skin_grid2 .reviewArea .imgBox .item.active").next().length == 0) $(".skin_grid2 .reviewArea .imgBox .next").hide(); if($(".skin_grid2 .reviewArea .imgBox .item.active").prev().length == 0) { $(".skin_grid2 .reviewArea .imgBox .prev").hide(); }else { $(".skin_grid2 .reviewArea .imgBox .prev").show(); } }); $(".skin_grid2 .reviewArea .imgBox .prev").click(function (e) { $dom = $(".skin_grid2 .reviewArea .imgBox .item.active").prev(); $(".skin_grid2 .reviewArea .imgBox .item").removeClass("active"); $dom.addClass("active"); if($(".skin_grid2 .reviewArea .imgBox .item.active").prev().length == 0) $(".skin_grid2 .reviewArea .imgBox .prev").hide(); if($(".skin_grid2 .reviewArea .imgBox .item.active").next().length == 0) { $(".skin_grid2 .reviewArea .imgBox .next").hide(); }else { $(".skin_grid2 .reviewArea .imgBox .next").show(); } }) }, 10); } } } function makeImgTags(row) { var imgs = []; if (row.rhimg && (/^.*\.(jpg|jpeg|png|gif|bmp)$/i).test(row.rhimg)) { imgs.push('<img src="'+row.rhimg+'" alt="" />'); } if (row.attach && row.attach.length > 0) { for (var i=0; i<row.attach.length; i++) { var att_img = row.attach[i]; if (typeof att_img.att_path == "string" && (/^.*\.(jpg|jpeg|png|gif|bmp)$/i).test(att_img.att_path)) { imgs.push('<img src="'+att_img.att_path+'" alt="" />'); } } } return imgs; } function _IE8_width_fix(tr) { if ($.browser.msie && $.browser.version == 8) { $(tr).find("img").each(function(){ $tr = $(this).closest("tr"); $(this).hide().load(function(){ if (500 <= $(this).width()) { $(this).css({"max-width":"none", "width":"500px", "height":"auto"}); } $(this).show(); }); }); } } function hideElem() { if (gdetail === true) { $('.skin_grid2 .photoreview .is_detail').remove(); } if (guse_point !== true) { $('.skin_grid2 .photoreview .is_rating').remove(); } } function makeCell(c) { var tmpl = []; tmpl.push('<tr id="preview'+c.no+'" class="rv_list">'); tmpl.push('<td class="rating"><img src="http://shop1.untapped.cafe24.com/img/ico_point_'+c.rpoint+'.png" alt="'+c.rpoint+' Point" /></td>'); tmpl.push('<td class="subject elp"><a class="preview_detail" href="'+c.no+'">'+c.rsub+'</a></td>'); tmpl.push('<td class="cont"><a class="preview_detail" href="'+c.no+'">'+c.rcont+'</a></td>'); tmpl.push('<td class="info"><span class="writer">'+c.rwriter+'</span><span class="date">'+c.rdate+'</span></a></td>'); tmpl.push('<td class="img" style="background-image:url('+c.rimg+')"><a class="preview_detail" href="'+c.no+'"></a></td>'); return tmpl.join(''); } $(".skin_grid2 .xans-photoreview-display .prv_table .subject .photoreview.list").each(function(k,v) { var writer = $(this).find(".skin_grid2 .writer").html(); var dat = $(this).find(".skin_grid2 .date").html(); $(this).find(".skin_grid2 .writer").remove(); $(this).find(".skin_grid2 .date").remove(); $(this).html($(this).text()); $(this).parent().append("<span class='writer'>" + writer + "</span>"); $(this).parent().append("<span class='date'>" + dat + "</span>"); }); }); $(document).ready(function(){ if($(".skin_grid2 .photoreview-outputNumber").length > 0) { var count = "4"; setTimeout(function() { $(".skin_grid2 .photoreview-outputNumber option").eq(0).val(count); $(".skin_grid2 .photoreview-outputNumber option").eq(0).attr("selected",true); $(".skin_grid2 .photoreview-outputNumber").change(); }, 10); }; });<file_sep>$(window).scroll(function(){ if($(document).scrollTop() > 1000) { $('.fixOpt').addClass('fixed'); } else { $('.fixOpt').removeClass('fixed'); } if(($(document).height() - $(document).scrollTop()) < 1500) { $('.fixOpt').hide(); } else { $('.fixOpt').show(); } }); $('.fixOpt_btn').click(function() { $(this).toggleClass('closed'); $('.fixOpt_cont').toggleClass('opened'); });<file_sep>function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length,c.length); } return ""; } function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires; } function couponClose(){ if($("input[name='chkbox']").is(":checked") ==true){ setCookie("close","N",1); } $("#popup_idio").css("opacity","0"); $("#popup_idio").css("z-index","-1"); } $(document).ready(function(){ cookiedata = document.cookie; if(cookiedata.indexOf("close=N")<0){ $("#popup_idio").attr('class', 'opened') }else{ $("#popup_idio").css("opacity","0"); $("#popup_idio").css("z-index","-1"); } $("#popup_btn_close").click(function(){ couponClose(); }); }); $('.popup-slider').slick({ dots: true, infinite: true, autoplay: true, pauseOnHover: false, pauseOnFocus: false, speed: 500, fade: true, arrows: false, cssEase: 'linear' });<file_sep>$(document).scroll(function(){ var _stop = 39; if ($("#topBnr").hasClass("opened")) _stop = $("#topBnr").height() + 39; if ($(this).scrollTop() >= _stop) { $('.headerWrap').addClass('headerWrap-fixed'); $("#contents").css("padding-top",$(".headerWrap").height()); } else { $('.headerWrap').removeClass('headerWrap-fixed'); $("#contents").css("padding-top",""); } }); $(function() { $('.menu_btn').click(function() { if (!$('.btn_wrapper').hasClass('clicked')) { $('.nav').addClass('opened'); $('.nav_cover').stop(true).fadeIn(200); } else { $('.nav').removeClass('opened'); $('.nav_cover').stop(true).fadeOut(200); } }); $('.nav_cover').click(function() { $('.nav').removeClass('opened'); $('.nav_cover').stop(true).fadeOut(200); }); }); /* 검색 */ $('.btn_sch').click(function() { $('.schArea').stop().fadeToggle(100); }); $('.sch_close').click(function() { $('.schArea').stop().fadeToggle(100); }); $('.sch_cover').click(function() { $('.schArea').stop().fadeToggle(100); });<file_sep>[24] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [25] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [26] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [27] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [28] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [29] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [30] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [31] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [32] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [33] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [36] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [37] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [34] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [35] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [38] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [39] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [40] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [41] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F" [23] use_image = "F" use_top_image = "F" use_b_image = "F" use_category_image_mobile = "F" use_top_image_mobile = "F" use_banner_image_mobile = "F"
25bbb5a4d8a4601e54836ad11c5e0d36a3d544d5
[ "JavaScript", "HTML", "Markdown", "INI" ]
19
JavaScript
the-bold/onepercent-cafe24
c5b9f05e5aa760b733156e3c4f936467934a5462
b2ed1dc65e9d6bd7bc8ace1736644d229e078866
refs/heads/master
<repo_name>acv-huynq/chirp<file_sep>/app/views/parts/report/report_definition_peregrine.php <label for="type" class="label06">Station<span class="danger"> *</span><br /><span>空港名</span></label> <div class="label07"> <select id="station" name="station" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($station_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('station', $report_info->station) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="added_by" class="label06">Position<br /><span>役職</span></label> <div class="label07"> <input id="position" name="position" type="text" class="inputbox" value="<?= HTML::entities(Input::old('position', $report_info->position)) ?>" maxlength="30" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <label for="reported_by" class="label06">Department<br /><span>部署名</span></label> <div class="label07"> <input id="department" name="department" type="text" class="inputbox" value="<?= HTML::entities(Input::old('department', $report_info->department)) ?>" maxlength="30" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="reported_by" class="label06">Reported By<span class="danger"> *</span><br /><span>起票者</span></label> <div class="label07"> <input id="reported_by" name="reported_by" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('reported_by', $report_info->reported_by)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <file_sep>/app/controllers/PreviewController.php <?php /** * プレビュー画面 */ class PreviewController extends BaseController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * プレビュー画面表示 */ function getIndex() { $error_message_list = Session::get('error_message_list'); $report_no = Session::get('_report_no'); $report_class = Session::get('_report_class'); $modified = Session::get('_modified'); // エラーがある場合 if(count($error_message_list)) { return View::make('preview') ->with('error_message_list', $error_message_list) ->with('header_title', '- ' . Config::get('const.REPORT_CLASS_NAME')[$report_class]); } $report_info = $this->getReportInfo($report_no); $report_info->attach_file_list = $this->getAttacheFileList($report_no); $related_report_arr = []; if(strlen($report_info->related_report_no)) { $related_report_arr[] = $report_info->related_report_no; } if(strlen($report_info->related_report_no_2)) { $related_report_arr[] = $report_info->related_report_no_2; } $report_info->related_report_list = implode(', ', $related_report_arr); return View::make('preview') ->with('error_message_list', $error_message_list) ->with('header_title', '- ' . Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_class]) ->with('report_title', '- ' . Config::get('const.REPORT_CLASS_NAME')[$report_class]) ->nest('parts_preview', Config::get('const.previewViews')[$report_class], ['report_info' => $report_info]); } /** * レポート情報取得 * @param $report_no * @return レポート情報 */ protected function getReportInfo($report_no){ throw new Exception('サブクラスで実装すること!'); } /** * 添付ファイル一覧取得 * @param unknown $report_no */ function getAttacheFileList($report_no){ $result = DB::select(Config::get('sql.SELECT_REPORT_ATTACHE_FILE_LIST'), [$report_no]); $attach_file_arr = []; foreach($result as $attach_file) { $attach_file_arr[] = $attach_file->file_name; } return implode(', ', $attach_file_arr); } } <file_sep>/app/views/error.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp - ERROR</title> <?= HTML::style('resources/bootstrap/css/bootstrap.min.css') ?> <?= HTML::style('resources/css/jquery-ui.min.css') ?> <?= HTML::style('resources/css/awesome-bootstrap-checkbox.css') ?> <?= HTML::style('resources/bower_components/Font-Awesome/css/font-awesome.css') ?> <?= HTML::style('resources/css/pnotify.custom.min.css') ?> <?= HTML::style('resources/css/extends-bootstrap.css') ?> <?= HTML::style('resources/css/common.css') ?> <?= HTML::style('resources/css/style.css') ?> <?= HTML::script('resources/js/jquery-1.11.2.min.js') ?> <?= HTML::script('resources/js/jquery-ui.min.js') ?> <?= HTML::script('resources/bootstrap/js/bootstrap.min.js') ?> <?= HTML::script('resources/js/bootbox.js') ?> <?= HTML::script('resources/js/jquery.blockUI.js') ?> <?= HTML::script('resources/js/pnotify.custom.min.js') ?> <?= HTML::script('resources/js/common.js') ?> <script type="text/javascript"> disableBrowserBack(); </script> </head> <body> <nav class="navbar navbar-peach"> <div class="container-fluid"> <div id="main"> <p id="logo"></p> <h1>Chirp</h1> </div> </div> </nav> <div class="container-fluid"> <div class="title">エラーが発生しました。</div> <div class="message"> <p><a href="/p/chirp">ログインページ</a>から、やり直してください。</p> </div> </div> </body> </html> <file_sep>/app/views/parts/preview/preview_penguin.php <table id="" class="table" border="0" cellpadding="2" style="width: 100%; text-align: left; table-layout:fixed; word-wrap: break-word;"> <tbody> <tr> <td class="preview_header"><div class="preview_header_al">Own Department Only</div>他部門非公開</td> <td class="preview_data"><?php echo ($report_info->own_department_only_flag === '1' ? 'On' : 'Off')?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report No</div>レポート番号</td> <td class="preview_data"><?=HTML::entities($report_info->report_no)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Station</div>起票部署</td> <td class="preview_data"><?=HTML::entities($report_info->station)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report Title</div>レポート件名</td> <td class="preview_data"><?=HTML::entities($report_info->report_title)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Line</div>回線</td> <td class="preview_data"><?=HTML::entities($report_info->line)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">First Contact</div>入電日時</td> <td class="preview_data"><?=HTML::entities($report_info->first_contatct_date)?> <?=HTML::entities($report_info->first_contact_time)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Last Contact</div>最終通話日時</td> <td class="preview_data"><?=HTML::entities($report_info->last_contact_date)?> <?=HTML::entities($report_info->last_contact_time)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Category</div>カテゴリ</td> <td class="preview_data"><?=HTML::entities($report_info->category_name)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Sub Category</div>サブカテゴリ</td> <td class="preview_data"><?=HTML::entities($report_info->sub_category)?><?=HTML::entities($report_info->sub_category_other)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Contents</div>クレーム内容</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->contents))?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Correspondence</div>対応内容</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->correspondence))?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Attachments</div>添付ファイル</td> <td class="preview_data"><?=HTML::entities($report_info->attach_file_list)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Related Report</div>関連レポート</td> <td class="preview_data"><?=HTML::entities($report_info->related_report_list)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Remarks</div>備考</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->free_comment))?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Phone Number ①</div>電話番号 ①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Phone Number ②</div>電話番号 ②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2)?></td> </tr> <?php if($report_info->pax_info_2_flg || $report_info->pax_info_3_flg): ?> <tr> <td class="preview_header"><div class="preview_header_al">#2 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Phone Number ①</div>電話番号 ①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Phone Number ②</div>電話番号 ②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname_3)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname_3)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd_3)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday_3)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Phone Number ①</div>電話番号 ①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1_3)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Phone Number ②</div>電話番号 ②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2_3)?></td> </tr> <?php endif; ?> <tr> <td class="preview_header"><div class="preview_header_al">#1 PNR</div>予約番号</td> <td class="preview_data"><?=HTML::entities($report_info->record_locator)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Flight Date</div>フライト日</td> <td class="preview_data"><?=HTML::entities($report_info->departure_date)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Flight No</div>便名</td> <td class="preview_data"><?=HTML::entities($report_info->flight_number)?></td> </tr> <?php if($report_info->flight_info_2_flg): ?> <tr> <td class="preview_header"><div class="preview_header_al">#2 PNR</div>予約番号</td> <td class="preview_data"><?=HTML::entities($report_info->record_locator_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Flight Date</div>フライト日</td> <td class="preview_data"><?=HTML::entities($report_info->departure_date_2)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Flight No</div>便名</td> <td class="preview_data"><?=HTML::entities($report_info->flight_number_2)?></td> </tr> <?php endif; ?> <tr> <td class="preview_header"><div class="preview_header_al">Phoenix Class</div>Phoenixカテゴリ</td> <td class="preview_data"><?=HTML::entities($report_info->phoenix_class)?></td> </tr> <tr style="border-bottom: 1px solid #ddd;"> <td class="preview_header"><div class="preview_header_al">Phoenix Memo</div>Phoenixメモ</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->phoenix_memo))?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report Status</div>レポートステータス</td> <td class="preview_data"><?=HTML::entities($report_info->report_status_name)?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Created</div>作成日</td> <td class="preview_data"><?=HTML::entities($report_info->create_timestamp)?> JST</td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Modified</div>更新日</td> <td class="preview_data"><?=HTML::entities($report_info->update_timestamp)?> JST</td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Reported By</div>起票者</td> <td class="preview_data"><?=HTML::entities($report_info->reported_by)?></td> </tr> </tbody> </table> <file_sep>/app/views/parts/report/category.php <?php if(count($category_list)){ ?> <div id="category_area" class="form-horizontal"> <label class="label01">Category<br /><span>カテゴリ</span></label> <input type="hidden" id="category_list_count" name="category_list_count" value="<?php echo count($category_list)?>"/> <div class="label04"> <?php foreach($category_list as $index =>$data) { ?> <div class="col-md-6"> <div class="checkbox checkbox-inline"> <?php $check_value = null; foreach ($select_categoly_info as $categoly_info ){ if($categoly_info->report_type == Input::old('report_type',$report_info->report_type) && $categoly_info->category == $data->code2){ $check_value = 'on'; break; } } ?> <input id="category_<?= HTML::entities($index + 1) ?>" name="category_<?= HTML::entities($index + 1) ?>" type="checkbox" <?php echo Input::old('category_' . $index + 1, $check_value) != null ? 'checked="checked"' : '' ?> value="<?= HTML::entities($data->code2) ?>" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> <label for="category_<?= HTML::entities($index + 1) ?>"></label> </div> <?= HTML::entities($data->code2 . ' ' . $data->value2) ?> </div> <?php } ?> </div> <?php if($category_option === 'MR'){ ?> <label for="mr" class="label01">MR<span>メディカルレポート</span></label> <div class="label04"> <textarea name="mr" id="mr" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea"<?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" placeholder="※救急車要請・ドクターコールの有無・非常用装備品・医療医薬品の使用状況を記入 Ambulance Request ・Doctor call・ Use of Emergency Equipment, Medical Equipment"><?= HTML::entities(Input::old('mr', $report_info->mr)) ?></textarea> </div> <?php } ?> </div> <?php } ?> <file_sep>/app/views/parts/report/report_alert_button.php <?php if(unserialize(Session::get('SESSION_KEY_CHIRP_USER'))->userInfo->report_name == 'PEREGRINE'): ?> <script> function alertButton() { $('button').prop("disabled", true); $('a').addClass("avoid-clicks"); $.ajax({ type: 'POST', url: '/p/chirp/report/alert-setting', dataType: 'text', data: { '_report_no':$('#_report_no').val(), '_report_class':$('#_report_class').val(), '_mode':$('#_mode').val(), '_report_alert':$('#_report_alert').val() } }) // 通信成功 .done(function(data, textStatus, jqXHR){ // 正常 if(data.length > 0 && data === "1") { if($('input[name="report_alert"]').val() == '0') { alert('アラート設定しました'); $('#alert_me').removeClass('btn-lgray') .addClass('btn-pink'); $('input[name="report_alert"]').val(1); } else { alert('アラート設定を解除しました。'); $('#alert_me').removeClass('btn-pink') .addClass('btn-lgray'); $('input[name="report_alert"]').val(0); } // 例外発生 } else { // 2016/4/4 #12 何を以て排他エラーとしているのかわからない為、コメントとする。 // alert('<?php echo Config::get('message.EXCLUSIVE_ERROR'); ?>'); alert('ステータスの変更に失敗しました'); } }) // 通信失敗 .fail(function(jqXHR, textStatus, errorThrown) { alert('ステータスの変更に失敗しました'); }) .always(function(data, textStatus, errorThrown){ $('button').prop("disabled", false); $('a').removeClass("avoid-clicks"); }); } </script> <div class="row" style="margin-bottom:10px;"> <div class="col-md-12 <?=$role_manage_info->report_alert_hidden; ?>"> <input type="hidden" name="report_alert" id="_report_alert" value="<?= $report_alert ?>"> <button type="button" id="alert_me" class="btn <?php if($report_alert): ?>btn-pink<?php else: ?>btn-lgray<?php endif; ?> btn-xs pull-right alert_button" onclick="alertButton();">Alert Me</button> </div> </div> <?php endif; ?><file_sep>/app/extentions/SystemCodeManager.php <?php use Illuminate\Support\Facades\Facade; class SystemCodeManager extends Facade { protected static function getFacadeAccessor() { return 'SystemCodeManager'; } }<file_sep>/app/extentions/CommonGateway/CommonCheckLogic.php <?php namespace CommonGateway { use DB; use Config; class CommonCheckLogic { /** * 未入力チェック * @param string $value * @return boolean チェック結果(true:未入力、false:入力あり) */ public function isEmpty($value){ return ($value == null || trim($value) == ''); } /** * 未入力チェック(どちらか一方のみ) * @param string $value * @return boolean チェック結果(true:どちらか一方のみ未入力、false:双方入力あり or 双方未入力) */ public function isEitherEmpty($value1, $value2){ return ($this->isEmpty($value1) && !$this->isEmpty($value2)) || ($this->isEmpty($value2) && !$this->isEmpty($value1)); } /** * 数値チェック * @param int $value * @return boolean チェック結果(true:半角数字、false:半角数字以外) * @return boolean チェック結果(true:数値、false:数値以外) */ public function isNumeric($value, $ignoreEmpty) { if($ignoreEmpty && $this->isEmpty($value)){ return true; } return is_numeric($value); } /** * 半角数字チェック * @param string $value * @return boolean チェック結果(true:半角数字、false:半角数字以外) */ public function isHalfNumeric($value) { return preg_match("/^[0-9]+$/", $value); } /** * 半角数字チェック(固定桁数) * @param string $value * @param int $length * @param boolean $ignoreEmpty 空文字無視フラグ * @return boolean チェック結果(true:半角数字、false:半角数字以外) */ public function isHalfNumericAndLength($value, $length, $ignoreEmpty) { if($ignoreEmpty && $this->isEmpty($value)){ return true; } return preg_match("/^[0-9]+$/", $value) && strlen($value) == $length; } /** * 便名のフォーマットチェック * @param unknown $value * @param boolean $ignoreEmpty 空文字無視フラグ */ public function checkFlightNumber($value, $ignoreEmpty){ if($ignoreEmpty && $this->isEmpty($value)){ return true; } return preg_match("/^MM\d{4}+$/", $value); } /** * 半角英数字チェック * @param string $value * @param boolean $ignoreEmpty 空文字無視フラグ * @return boolean チェック結果(true:半角英数字、false:半角英数字以外) */ public function isHalfAlphaNumeric($value, $ignoreEmpty){ if($ignoreEmpty && $this->isEmpty($value)){ return true; } return preg_match("/^[a-zA-Z0-9]+$/", $value); } /** * 日付チェック * @param string $date 日付文字列 * @param boolean $ignoreEmpty 空文字無視フラグ * @return boolean チェック結果 */ public function isDate($date, $ignoreEmpty) { if($ignoreEmpty && $this->isEmpty($date)){ return true; } // 区切り文字で年、月、日を分ける $array = explode('/', $date); if(count($array) == 3) { $year = intval($array[0]); $month = intval($array[1]); $day = intval($array[2]); } else { return false; } // 年月日の文字数が正しいか if(mb_strlen($year) != 4) { return false; } if(mb_strlen($month) != 2 && mb_strlen($month) != 1) { return false; } if(mb_strlen($day) != 2 && mb_strlen($day) != 1) { return false; } // 日付として正しいかどうか return checkdate ($month,$day,$year); } /** * メール送信先の選択が正しいかどうか * @param unknown $mode * @param unknown $button_name * @param unknown $checks * @return boolean */ public function checkSendMail($mode, $button_name, $checks){ $reult = true; switch ($mode){ case 'confirm': if($button_name === 'passback' && $checks[2] === 'on'){ $reult = false; } if($button_name === 'confirm' && $checks[0] === 'on'){ $reult = false; } break; case 'close': if($button_name === 'passback' && $checks[0] === 'on'){ $reult = false; } break; case 'inquiry': if($button_name === 'inquiry'){ $reult = false; for($i=0;$i < count($checks)-1; $i++){ if($checks[$i] === 'on'){ $reult = true; break; } } } break; default: break; } return $reult; } /** * レポート存在チェック * @param unknown $report_no レポート番号 * @param boolean $ignoreEmpty 空文字無視フラグ */ function isExsistsReport($report_no, $ignoreEmpty){ if($ignoreEmpty && $this->isEmpty($report_no)){ return true; } $result = DB::selectOne(Config::get('sql.EXSISTS_REPORT'),[$report_no, 1]); return $result->count > 0; } } } <file_sep>/app/controllers/TopController.php <?php /** * トップ画面 */ class TopController extends BaseController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * トップ画面表示 */ function getIndex() { Session::forget('SESSION_KEY_REPORT_DATA'); Session::forget('SESSION_KEY_PREV_REPORT_PARAM'); // モード(初期表示 or 検索)を取得 $_mode = Session::get('_mode'); if(! $_mode){ $_mode = 'init'; } // 照会レポート取得 ※管理者、承認者のみ $inquiryReport = []; $userRole = $this->user->userInfo->user_role; if($userRole == 1 || $userRole == 2){ $inquiryReport = $this->getInquiryReport(); } // 最新レポート取得 $newReport = $this->getNewReport(); // 検索条件・レポート取得 $searchCondition = new stdClass(); $searchCondition->free_word = ''; $searchCondition->report_class = Config::get('const.REPORT_CLASS_LIST')[$this->user->userInfo->report_name][0]['code']; $searchCondition->create_date_from = ''; $searchCondition->create_date_to = ''; $searchCondition->reporting_date_from = ''; $searchCondition->reporting_date_to = ''; $searchCondition->flight_date_from = ''; $searchCondition->flight_date_to = ''; $searchCondition->status = ''; $searchCondition->category = ''; $searchCondition->station = ''; $searchCondition->area = ''; $searchCondition->assessment = ''; $searchCondition->first_name = ''; $searchCondition->last_name = ''; $searchCondition->record_locator = ''; $searchReport = []; if($_mode == 'search_success' || $_mode == 'search_error'){ // フラッシュデータより取得 $session_condition = Session::get('search_report_condition'); if(count($session_condition)) { $searchCondition = $session_condition; } $searchReport = Session::get('search_report_list'); } // レポート種別取得 $report_class_list = SystemCodeManager::getReportClass(); $this->settingReportClassList($report_class_list); // レポートステータス取得 $report_status_list = SystemCodeManager::getReportStatus(); // エリア取得 $area_list = SystemCodeManager::getArea(0); // カテゴリ取得 $category_list = []; $category_list[1] = SystemCodeManager::getCategory(1); $category_list[2] = SystemCodeManager::getCategory(2); $category_list[3] = SystemCodeManager::getCategory(3); $report_type_list = SystemCodeManager::getReportType(4); $category_list[4] = []; foreach($report_type_list as $report_type) { $category_list[4] = array_merge($category_list[4], SystemCodeManager::getCategory(4, $report_type->code2)); } // ボタン取得 $button_list = Config::get('const.REPORT_CLASS_LIST')[$this->user->userInfo->report_name]; return View::make('top') ->nest('parts_common_header', 'parts.common.header',['header_title' => '- ' . $this->user->userInfo->report_name, 'login_button_hidden' => '']) ->nest('parts_common_error', 'parts.common.error',['error_message_list' => Session::get('error_message_list')]) ->nest('new_report_view', Config::get('const.topViews')[$this->user->userInfo->report_name], ['new_report_list' => $newReport, 'button_list' => $button_list]) ->with('header_title', '- ' . $this->user->userInfo->report_name) ->with('inquiry_report_list', $inquiryReport) ->with('search_report_condition', $searchCondition) ->with('search_report_list', $searchReport) ->with('report_class_list',$report_class_list) ->with('report_status_list', $report_status_list) ->with('area_list', $area_list) ->with('category_list', $category_list) ->with('_mode', $_mode); } private function settingReportClassList($report_class_list){ $selfClass = Config::get('const.REPORT_CLASS_LIST')[$this->user->userInfo->report_name]; foreach ($report_class_list as $row) { // 起票者の場合 if($this->user->isCreator()){ $row->disable = 'disabled="disabled"'; for($i=0;$i < count($selfClass);$i++){ if($row->code2 == $selfClass[$i]['code']){ $row->disable = ''; break; } } }else{ $row->disable = ''; } } } /** * 検索ボタン押下時の処理 */ function postSearch(){ // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->userInfo->login_id, $this->user->getReportName() . ':トップ画面', 'レポート検索', ''); $search_free_word = Input::get('search_free_word'); $search_report_class = Input::get('search_report_class'); $search_create_date_from = Input::get('search_create_date_from'); $search_create_date_to = Input::get('search_create_date_to'); $search_reporting_date_from = Input::get('search_reporting_date_from'); $search_reporting_date_to = Input::get('search_reporting_date_to'); $search_flight_date_from = Input::get('search_flight_date_from'); $search_flight_date_to = Input::get('search_flight_date_to'); $search_status = Input::get('search_status'); $search_category = Input::get('search_category'); $search_station = Input::get('search_station'); $search_area = Input::get('search_area'); $search_assessment = Input::get('search_assessment'); $search_first_name = Input::get('search_first_name'); $search_last_name = Input::get('search_last_name'); $search_record_locator = Input::get('search_record_locator'); $searchCondition = new stdClass(); $searchCondition->free_word = $search_free_word; $searchCondition->report_class = $search_report_class; $searchCondition->create_date_from = $search_create_date_from; $searchCondition->create_date_to = $search_create_date_to; $searchCondition->reporting_date_from = $search_reporting_date_from; $searchCondition->reporting_date_to = $search_reporting_date_to; $searchCondition->flight_date_from = $search_flight_date_from; $searchCondition->flight_date_to = $search_flight_date_to; $searchCondition->status = $search_status; $searchCondition->category = $search_category; $searchCondition->station = $search_station; $searchCondition->area = $search_area; $searchCondition->assessment = $search_assessment; $searchCondition->first_name = $search_first_name; $searchCondition->last_name = $search_last_name; $searchCondition->record_locator = $search_record_locator; // フリーワード、検索日付のいずれかは必須入力 if(CommonCheckLogic::isEmpty($search_free_word) && CommonCheckLogic::isEmpty($search_create_date_from) && CommonCheckLogic::isEmpty($search_create_date_to) && CommonCheckLogic::isEmpty($search_reporting_date_from) && CommonCheckLogic::isEmpty($search_reporting_date_to) && CommonCheckLogic::isEmpty($search_flight_date_from) && CommonCheckLogic::isEmpty($search_flight_date_to) && CommonCheckLogic::isEmpty($search_status) && CommonCheckLogic::isEmpty($search_category) && CommonCheckLogic::isEmpty($search_station) && CommonCheckLogic::isEmpty($search_area) && CommonCheckLogic::isEmpty($search_assessment) && CommonCheckLogic::isEmpty($search_first_name) && CommonCheckLogic::isEmpty($search_last_name) && CommonCheckLogic::isEmpty($search_record_locator) ){ $this->error_message_list[] = 'フリーワード、検索日付、検索項目のいずれかの指定が必須です。'; } // 日付相関チェック if(CommonCheckLogic::isEitherEmpty($search_create_date_from, $search_create_date_to)){ $this->error_message_list[] = 'Create Dateを指定する場合、From Toは双方指定が必須です。'; } if(CommonCheckLogic::isEitherEmpty($search_reporting_date_from, $search_reporting_date_to)){ $this->error_message_list[] = 'Reporting Dateを指定する場合、From Toは双方指定が必須です。'; } if(CommonCheckLogic::isEitherEmpty($search_flight_date_from, $search_flight_date_to)){ $this->error_message_list[] = 'Flight Dateを指定する場合、From Toは双方指定が必須です。'; } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($search_create_date_from, true) ){ $this->error_message_list[] = 'Create Date(From Date)はYYYY/MM/DDで入力してください。'; } if(! CommonCheckLogic::isDate($search_create_date_to, true) ){ $this->error_message_list[] = 'Create Date(To Date)はYYYY/MM/DDで入力してください。'; } if(! CommonCheckLogic::isDate($search_reporting_date_from, true) ){ $this->error_message_list[] = 'Reporting Date(From Date)はYYYY/MM/DDで入力してください。'; } if(! CommonCheckLogic::isDate($search_reporting_date_to, true) ){ $this->error_message_list[] = 'Reporting Date(To Date)はYYYY/MM/DDで入力してください。'; } if(! CommonCheckLogic::isDate($search_flight_date_from, true) ){ $this->error_message_list[] = 'Flight Date(From Date)はYYYY/MM/DDで入力してください。'; } if(! CommonCheckLogic::isDate($search_flight_date_to, true) ){ $this->error_message_list[] = 'Flight Date(To Date)はYYYY/MM/DDで入力してください。'; } // エラーがある場合 if($this->hasError()){ return Redirect::to('/top') ->with('error_message_list', $this->error_message_list) ->with('search_report_condition', $searchCondition) ->withInput() ->with('search_report_list', []) ->with('_mode', 'search_error'); } // 検索レポート取得 $searchReport = $this->getSearchReport($searchCondition); // エラーがある場合 if($this->hasError()){ return Redirect::to('/top') ->with('error_message_list', $this->error_message_list) ->with('search_report_condition', $searchCondition) ->withInput() ->with('search_report_list', []) ->with('_mode', 'search_error'); } return Redirect::to('/top') ->with('error_message_list', $this->error_message_list) ->with('search_report_condition', $searchCondition) ->withInput() ->with('search_report_list', $searchReport) ->with('_mode', 'search_success'); } /** * 新規ボタン押下時の処理 */ function postAdd(){ // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->userInfo->login_id, $this->user->getReportName() . ':トップ画面', Config::get('const.REPORT_CLASS_NAME')[Input::get('_selected_report_class')] . ':新規作成', ''); return Redirect::to('/report') ->with('_mode', 'edit') ->with('_report_no','') ->with('_report_status','') ->with('_report_class',Input::get('_selected_report_class')); } /** * レポート選択時の処理 */ function postSelect(){ // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->userInfo->login_id, $this->user->getReportName() . ':トップ画面', Input::get('_inquiry_mode') === 'on' ? 'レポート照会' : 'レポート選択', Input::get('_selected_report_no')); // レポートアクセス制御チェック $check_result = DataManager::checkAccessControl(Input::get('_selected_report_no'), Input::get('_inquiry_mode')); if($check_result->result_code === false){ // エラーメッセージ設定 $this->error_message_list[] = $check_result->error_message; } // エラーがある場合 if($this->hasError()){ return Redirect::to('/top') ->with('error_message_list', $this->error_message_list) ->withInput() ->with('search_report_list', []) ->with('_mode', 'search_error'); } // レポート参照 または 回答画面を開く $reporter_mode = $this->user->isCreator(); // 起票者モード $otherdept_mode = $check_result->otherdept_mode; // 他部門モード if(Input::get('_inquiry_mode') === 'on'){ $inqmode = 'answer'; }else if($otherdept_mode){ $inqmode = 'other'; }else{ $inqmode = 'reference'; } return Redirect::to('/report') // ->with('_mode', (Input::get('_inquiry_mode') == 'on' ? 'answer' : 'reference')) ->with('_mode', $inqmode) ->with('_report_no',Input::get('_selected_report_no')) ->with('_report_status', Input::get('_selected_report_status')) ->with('_report_class',Input::get('_selected_report_class')); } /** * レポートプレビュー時の処理 */ function postPreview() { // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->userInfo->login_id, $this->user->getReportName() . ':トップ画面', 'レポートプレビュー', Input::get('_selected_report_no')); // レポートアクセス制御チェック $check_result = DataManager::checkAccessControl(Input::get('_selected_report_no')); if($check_result->result_code === false){ // エラーメッセージ設定 $this->error_message_list[] = $check_result->error_message; } return Redirect::to('/preview') ->with('error_message_list', $this->error_message_list) ->with('_report_no',Input::get('_selected_report_no')) ->with('_report_status', Input::get('_selected_report_status')) ->with('_report_class',Input::get('_selected_report_class')); } /** * アラート設定ボタン押下時 */ function postAlert() { // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->userInfo->login_id, $this->user->getReportName() . ':トップ画面', 'アラート設定', ''); return Redirect::to('/alert'); } /** * 照会レポート取得処理 */ protected function getInquiryReport(){ throw new Exception('未実装'); } /** * 最新レポート取得処理 */ protected function getNewReport(){ throw new Exception('未実装'); } /** * 検索レポート取得処理 */ protected function getSearchReport($searchCondition){ $sqlString = ''; $whereString = ''; $bindParam = []; $report_name = $this->user->userInfo->report_name; $reporter_mode = $this->user->isCreator(); $bindParam[] = $searchCondition->report_class; Log::info($searchCondition->report_class); $bindParam[] = '1'; // ログインユーザ:他部門指定時は公開レポートのみ $search_reportName = Config::get('const.REPORT_CLASS_NAME')[$searchCondition->report_class]; if($report_name !== $search_reportName){ $whereString .= 'and t1.own_department_only_flag <> 1 '; } // ログインユーザ:PEREGRINE部門(起票者)の場合、自空港のみ限定 if($reporter_mode && 'PEREGRINE' === $report_name){ // 指定レポート:PEACOCK if(Config::get('const.REPORT_CLASS.PEACOCK') == $searchCondition->report_class){ $whereString .= 'and false '; // 空港情報がないため検索不可 }else{ $station = $this->user->userInfo->station; if(empty($station)){ $station = ''; // 自空港未設定の場合 } $whereString .= 'and t2.station = ? '; $bindParam[] = $station; } } // report種別モード $search_mode = ''; if(Config::get('const.REPORT_CLASS.PENGUIN') == $searchCondition->report_class){ $search_mode = 'PENGUIN'; }else if(Config::get('const.REPORT_CLASS.PEREGRINE_Incident') == $searchCondition->report_class || Config::get('const.REPORT_CLASS.PEREGRINE_Irregularity') == $searchCondition->report_class){ $search_mode = 'PEREGRINE'; }else if (Config::get('const.REPORT_CLASS.PEACOCK') == $searchCondition->report_class){ $search_mode = 'PEACOCK'; } // SQL本文 if($search_mode == 'PENGUIN'){ $sqlString = Config::get('sql.SELECT_SEARCH_REPORT_PENGUIN'); }else if($search_mode == 'PEREGRINE'){ $sqlString = Config::get('sql.SELECT_SEARCH_REPORT_PEREGRINE'); }else if ($search_mode == 'PEACOCK'){ $sqlString = Config::get('sql.SELECT_SEARCH_REPORT_PEACOCK'); } if(! CommonCheckLogic::isEmpty($searchCondition->free_word) ){ if($search_mode == 'PENGUIN'){ $whereString .= 'and (t1.report_no like ? or t2.flight_number like ? or t2.flight_number_2 like ? or t1.contents like ?) '; $bindParam[] = '%' . $searchCondition->free_word . '%'; $bindParam[] = '%' . $searchCondition->free_word . '%'; $bindParam[] = '%' . $searchCondition->free_word . '%'; $bindParam[] = '%' . $searchCondition->free_word . '%'; }else{ $whereString .= 'and (t1.report_no like ? or t2.flight_number like ? or t1.contents like ?) '; $bindParam[] = '%' . $searchCondition->free_word . '%'; $bindParam[] = '%' . $searchCondition->free_word . '%'; $bindParam[] = '%' . $searchCondition->free_word . '%'; } } if(! CommonCheckLogic::isEmpty($searchCondition->create_date_from) ){ $whereString = $whereString . ' and DATE_FORMAT(t1.create_timestamp, \'%Y/%m/%d\') between ? and ?'; $bindParam[] = $searchCondition->create_date_from; $bindParam[] = $searchCondition->create_date_to; } if(! CommonCheckLogic::isEmpty($searchCondition->reporting_date_from) ){ if($search_mode == 'PENGUIN'){ $whereString = $whereString . ' and DATE_FORMAT(t2.first_contatct_date, \'%Y/%m/%d\') between ? and ?'; }else{ $whereString = $whereString . ' and DATE_FORMAT(t2.reporting_date, \'%Y/%m/%d\') between ? and ?'; } $bindParam[] = $searchCondition->reporting_date_from; $bindParam[] = $searchCondition->reporting_date_to; } if(! CommonCheckLogic::isEmpty($searchCondition->flight_date_from) ){ if($search_mode == 'PENGUIN'){ //レポート種別PENGUINの場合、搭乗日2も対象 $whereString = $whereString . ' and (DATE_FORMAT(t2.departure_date, \'%Y/%m/%d\') between ? and ?'; $whereString = $whereString . ' or DATE_FORMAT(t2.departure_date_2, \'%Y/%m/%d\') between ? and ? )'; $bindParam[] = $searchCondition->flight_date_from; $bindParam[] = $searchCondition->flight_date_to; $bindParam[] = $searchCondition->flight_date_from; $bindParam[] = $searchCondition->flight_date_to; }else{ $whereString = $whereString . ' and DATE_FORMAT(t2.departure_date, \'%Y/%m/%d\') between ? and ?'; $bindParam[] = $searchCondition->flight_date_from; $bindParam[] = $searchCondition->flight_date_to; } } if(! CommonCHeckLogic::isEmpty($searchCondition->status)) { $whereString .= ' and t1.report_status = ?'; $bindParam[] = $searchCondition->status; } if(! CommonCheckLogic::isEmpty($searchCondition->category)) { if($this->user->userInfo->report_name == 'PEACOCK') { $whereString .= ' and t1.report_no IN (select report_no from select_category_info where category = ?)'; } else { $whereString .= ' and t2.category = ?'; } $bindParam[] = $searchCondition->category; } if(! CommonCheckLogic::isEmpty($searchCondition->station)) { $search_station = str_replace(' ', ',', trim($searchCondition->station)); $whereString .= ' and FIND_IN_SET(t2.station, ?)'; $bindParam[] = $search_station; } if(! CommonCheckLogic::isEmpty($searchCondition->area)) { $whereString .= ' and t2.area = ?'; $bindParam[] = $searchCondition->area; } if(! CommonCheckLogic::isEmpty($searchCondition->assessment)) { $whereString .= ' and assessment = ?'; $bindParam[] = $searchCondition->assessment; } if(! CommonCheckLogic::isEmpty($searchCondition->first_name)) { $first_name = "%{$searchCondition->first_name}%"; $whereString .= ' and (t1.firstname LIKE ? or t1.firstname_2 LIKE ? or t1.firstname_3 LIKE ?)'; $bindParam[] = $first_name; $bindParam[] = $first_name; $bindParam[] = $first_name; } if(! CommonCheckLogic::isEmpty($searchCondition->last_name)) { $last_name = "%{$searchCondition->last_name}%"; $whereString .= ' and (t1.lastname LIKE ? or t1.lastname_2 LIKE ? or t1.lastname_3 LIKE ?)'; $bindParam[] = $last_name; $bindParam[] = $last_name; $bindParam[] = $last_name; } if(! CommonCheckLogic::isEmpty($searchCondition->record_locator)) { $whereString .= ' and (record_locator = ? or record_locator_2 = ? or record_locator_3 = ?)'; $bindParam[] = $searchCondition->record_locator; $bindParam[] = $searchCondition->record_locator; $bindParam[] = $searchCondition->record_locator; } $countSqlString = preg_replace ('/select.*from/','select count(t1.report_no) count from',$sqlString); $result = DB::selectOne($countSqlString . $whereString,$bindParam); if($result->count == 0){ $this->error_message_list[] = '検索条件に該当するレポートはありませんでした。'; return null; } if($result->count > 100){ $this->error_message_list[] = '検索結果が100件を超えています。検索範囲を絞り込み再検索してください。'; return null; } $result = DB::select( $sqlString . $whereString . ' order by t1.update_timestamp desc', $bindParam ); return $result; } } <file_sep>/app/controllers/BaseController.php <?php class BaseController extends Controller { /** * 認証要求フラグ(認証が必要な場合はtrue) */ protected $requireAuth = true; /** * ユーザー情報 */ protected $user; /** * エラーメッセージの一覧 * @var unknown */ protected $error_message_list; /** * コンストラクタ */ function __construct() { $this->beforeFilter(function() { $this->error_message_list = Session::get('error_message_list'); if($this->error_message_list == null){ $this->error_message_list = []; } if($this->requireAuth){ // ログイン済みの場合 if($this->isLogin() ){ // ユーザー情報取得 $this->user = unserialize(Session::get('SESSION_KEY_CHIRP_USER')); // ログインしてない場合 }else{ return Redirect::to('/auth/redirect'); // return View::make('timeout'); } } }); } /** * コントローラーにより使用されるレイアウトの設定. * * @return void */ protected function setupLayout() { if ( ! is_null($this->layout)) { $this->layout = View::make($this->layout); } } /** * ログイン済みチェック */ protected function isLogin(){ return Session::has('SESSION_KEY_CHIRP_USER'); } /** * エラー存在チェック */ protected function hasError(){ return count($this->error_message_list) > 0; } /** * 起票者かどうかチェック * @return boolean チェック結果 */ protected function isCreator(){ return intVal($this->user->userInfo->user_role) === Config::get('const.USER_ROLE.REPORTER'); } } <file_sep>/app/views/parts/report/related_report_area.php <label for="related_report_no" class="label01_2">Related Report<br><span>関連レポート<br />※このレポートに関連する Report Noを記載して下さい<br /> Related report No to this report.</span></label> <div class="label04"> <div class="label02"> <input id="related_report_no" name="related_report_no" type="text" class="inputbox" placeholder="ex. CTYO2015-00001" value="<?= HTML::entities(Input::old('related_report_no', $report_info->related_report_no)) ?>" maxlength="14" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="row col-md-1 text-left report_link"> <?php if($_mode != 'relation' && $report_info->related_report_class){?> <a href="javascript:void(0)" onclick="selectRelatedReport('<?= HTML::entities($report_info->related_report_no) ?>', '<?= HTML::entities($report_info->related_report_class) ?>')"><span class="glyphicon glyphicon-file" style="font-size:150%"></span></a> <?php } ?> </div> <div class="label02"> <input id="related_report_no_2" name="related_report_no_2" type="text" class="inputbox" placeholder="ex. NKIX2015-00001" value="<?= HTML::entities(Input::old('related_report_no_2', $report_info->related_report_no_2)) ?>" maxlength="14" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="row col-md-1 text-left report_link"> <?php if($_mode != 'relation' && $report_info->related_report_class_2){?> <a href="javascript:void(0)" onclick="selectRelatedReport('<?= HTML::entities($report_info->related_report_no_2) ?>', '<?= HTML::entities($report_info->related_report_class_2) ?>')"><span class="glyphicon glyphicon-file" style="font-size:150%"></span></a> <?php } ?> </div> <div class="clearfix"></div> <p class="<?= HTML::entities($role_manage_info->related_report_area_hidden) ?>">[Reference reports of other department / 参考他部門レポート]</p> <ul class="<?= HTML::entities($role_manage_info->related_report_area_hidden) ?>" id="rerated_report_list"> <?php foreach($related_report_list as $data) { ?> <li class="rerated_report"> <div class="row col-md-12"> <?php if($_mode == 'relation'){?> <p><?= HTML::entities($data->report_no) ?> <?= HTML::entities($data->report_title) ?></p> <?php }else{?> <a href="javascript:void(0)" onclick="selectRelatedReport('<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_class) ?>')"><?= HTML::entities($data->report_no) ?> <?= HTML::entities($data->report_title) ?></a> <?php } ?> </div> </li> <?php } ?> </ul> </div> <div class="clearfix"></div> <script> function selectInputRelatedReport(id){ var value = $(id).val(); if(value == ''){ return false; } selectRelatedReport($(id).val(), null); } function selectRelatedReport(report_no, report_class){ $('button').prop("disabled", true); $('a').addClass("avoid-clicks"); var form = document.forms.mainForm; form.setAttribute("action", '/p/chirp/report/related-report'); var data = { 'related_report_no':report_no, 'related_report_class':report_class }; for (var paramName in data) { var input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', paramName); input.setAttribute('value', data[paramName]); form.appendChild(input); } form.submit(); /* if (modeValue == "edit" || modeValue == "confirm" || modeValue == "close") { var form = document.forms.mainForm; form.setAttribute("action", '/p/chirp/report/related-report'); var data = { 'related_report_no':report_no, 'related_report_class':report_class }; for (var paramName in data) { var input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', paramName); input.setAttribute('value', data[paramName]); form.appendChild(input); } form.submit(); } else { // フォーム生成 var form = document.createElement("form"); form.setAttribute("action", '/p/chirp/report/related-report'); form.setAttribute("method", "post"); form.style.display = "none"; document.body.appendChild(form); var data = { '_mode': $('#_mode').val(), '_report_no': $('#_report_no').val(), '_report_class':$('#_report_class').val(), 'related_report_no':report_no, 'related_report_class':report_class }; for (var paramName in data) { var input = document.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', paramName); input.setAttribute('value', data[paramName]); form.appendChild(input); } form.submit(); } */ } </script><file_sep>/app/controllers/ErrorController.php <?php /** * エラー画面 */ class ErrorController extends BaseController { /** * コンストラクタ */ function __construct() { $this->requireAuth = false; parent::__construct(); } /** * エラー画面表示 */ function getIndex() { return View::make('error'); } } <file_sep>/app/views/preview.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp <?=HTML::entities($header_title)?></title> <link media="all" type="text/css" rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/jquery-ui.min.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/awesome-bootstrap-checkbox.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/bower_components/Font-Awesome/css/font-awesome.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/pnotify.custom.min.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/extends-bootstrap.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/common.css"> <link media="all" type="text/css" rel="stylesheet" href="resources/css/style.css"> <script src="resources/js/jquery-1.11.2.min.js"></script> <script src="resources/js/jquery-ui.min.js"></script> <script src="resources/bootstrap/js/bootstrap.min.js"></script> <script src="resources/js/bootbox.js"></script> <script src="resources/js/jquery.blockUI.js"></script> <script src="resources/js/pnotify.custom.min.js"></script> <script src="resources/js/common.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <style> #print_title { color: #999999; font-size: 24px; padding: 10px 0 0 180px; text-align: left; } .preview_header { width: 30%; } .preview_header_al { font-weight: bold; } .preview_data { width: 70%; vertical-align: middle !important; } </style> <script> </script> </head> <body> <div style="text-align: center; width: 800px; margin: auto;"> <div style="height: 60px; margin-top: 10px;"> <img src="resources/css/images/peach-logo.png" style="float: left;"><h2 id="print_title">Chirp <?=HTML::entities($report_title)?></h2> </div> <?php if(count($error_message_list)): ?> <div class="row"> <div class="col-md-12" style="margin-bottom: 100px;"> <?php if(count($error_message_list) > 0){ ?> <div class="alert alert-danger"> <button class="close" data-dismiss="alert">&#215;</button> <ul> <?php foreach($error_message_list as $message) { ?> <li> <?php echo $message ?> </li> <?php } ?> </ul> </div> <?php } ?> </div> </div> <?php else: ?> <?=$parts_preview ?> <?php endif; ?> <div class="col-md-10"> <div class="form-group"> <button type="button" class="btn btn-lgray col-md-offset-1" onclick="window.close();">&nbsp;Close&nbsp;</button> <?php if(count($error_message_list) == 0): ?><button type="button" class="btn btn-lgray col-md-offset-1" onclick="print();">&nbsp;Print&nbsp;</button><?php endif; ?> </div> </div> </div> </body> </html> <file_sep>/app/views/parts/report/report_definition_peacock.php <label for="type" class="label06">Report Type<span class="danger"> *</span><span>レポート種別</span></label> <div class="label07"> <select id="report_type" name="report_type" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($report_type_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('report_type', $report_info->report_type) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="flight_report_no" class="label06">Flight Report No<span>フライトレポート番号</span></label> <div class="label07"> <input type="text" name="flight_report_no" id="flight_report_no" class="inputbox" value="<?= HTML::entities(Input::old('flight_report_no', $report_info->flight_report_no)) ?>" maxlength="6" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> </div> <label for="reported_by" class="label06">Reported By<span class="danger"> *</span><span>起票者</span></label> <div class="label07"> <input id="reported_by" name="reported_by" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('reported_by', $report_info->reported_by)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="added_by" class="label06">Added By<span>スタッフ補記担当</span></label> <div class="label07"> <input id="added_by" name="added_by" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('added_by', $report_info->added_by)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <file_sep>/app/views/parts/report/report_penguin.php <label for="report_title" class="label01">Report Title<span class="danger"> *</span><span>レポート件名</span></label> <div class="label03"> <input id="report_title" name="report_title" type="text" class="inputbox" value="<?= HTML::entities(Input::old('report_title', $report_info->report_title)) ?>" maxlength="180" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="clearfix"> <label for="type" class="label01">Line<span>回線</span></label> <div class="label02"> <select id="line" name="line" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($line_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('line', $report_info->line) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> </div> <div class="clearfix"> <label for="first_contatct_date" class="label01">First Contact<span>入電日時</span></label> <div class="label02"> <input id="first_contatct_date" name="first_contatct_date" type="text" class="inputbox datepicker" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('first_contatct_date', $report_info->first_contatct_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <div class="label02"> <input id="first_contact_time" name="first_contact_time" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('first_contact_time', $report_info->first_contact_time)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="last_contact_date" class="label01">Last Contact<span>最終通話日時</span></label> <div class="label02"> <input id="last_contact_date" name="last_contact_date" type="text" class="inputbox datepicker" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('last_contact_date', $report_info->last_contact_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="label02"> <input id="last_contact_time" name="last_contact_time" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('last_contact_time', $report_info->last_contact_time)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="category" class="label01">Category<span>カテゴリ</span></label> <div class="label02"> <select id="category" name="category" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($category_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('category', $report_info->category) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> </div> <label for="sub_category" class="label01">Sub Category<span>サブカテゴリ</span></label> <div class="label02"> <select id="sub_category" name="sub_category" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($sub_category_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('sub_category', $report_info->sub_category) == $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <div class="label05"> <div class="checkbox checkbox-inline form-inline text-right"> <input id="sub_category_other_check" name="sub_category_other_check" type="checkbox" style="max-width: 60px;" <?php echo Input::old('sub_category_other', $report_info->sub_category_other) == '' ? '' : 'checked="checked"' ?> <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> <label for="sub_category_other_check"></label> </div> <div>Other<br /><span>その他</span></div> </div> <div class="label02"> <input id="sub_category_other" name="sub_category_other" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('sub_category_other', $report_info->sub_category_other)) ?>" maxlength="70" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="contents" class="label01">Contents<span>クレーム内容</span></label> <div class="label04"> <textarea name="contents" id="contents" cols="100" rows="10" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('contents', $report_info->contents)) ?></textarea> </div> <label for="correspondence" class="label01">Correspondence<span>対応内容</span></label> <div class="label04"> <textarea name="correspondence" id="correspondence" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('correspondence', $report_info->correspondence)) ?></textarea> </div> <file_sep>/vendor/dsdevbe/ldap-connector/src/Dsdevbe/LdapConnector/LdapUserProvider.php <?php namespace Dsdevbe\LdapConnector; use adLDAP\adLDAP; use adLDAP\adLDAPException; use Illuminate\Auth\UserInterface; use Illuminate\Auth\UserProviderInterface; class LdapUserProvider implements UserProviderInterface{ /** * Configuration to connect to LDAP. * * @var string */ protected $config; /** * Stores connection to LDAP. * * @var adLDAP */ protected $adldap; /** * Creates a new LdapUserProvider and connect to Ldap * * @param array $config * @return void */ public function __construct($config) { $this->config = $config; $this->connectLdap(); } /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return \Illuminate\Auth\UserInterface|null */ public function retrieveById($identifier) { $info = $this->adldap->user()->infoCollection($identifier); if($info) { return new LdapUser($this->fetchObject($info)); } } /** * Retrieve a user by by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return \Illuminate\Auth\UserInterface|null */ public function retrieveByToken($identifier, $token) { // TODO: Implement retrieveByToken() method. } /** * Update the "remember me" token for the given user in storage. * * @param \Illuminate\Auth\UserInterface $user * @param string $token * @return void */ public function updateRememberToken(UserInterface $user, $token) { // TODO: Implement updateRememberToken() method. } /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Auth\UserInterface|null */ public function retrieveByCredentials(array $credentials) { if($this->adldap->user()->info($credentials['username'])) { return new LdapUser($credentials); } } /** * Validate a user against the given credentials. * * @param \Illuminate\Auth\UserInterface $user * @param array $credentials * @return bool */ public function validateCredentials(UserInterface $user, array $credentials) { $username = $credentials['username']; $password = $credentials['<PASSWORD>']; return $this->adldap->authenticate($username, $password); } /** * Converts infocollection object to array. * * @param $object * @return array */ public function fetchObject($object) { $arr = array( 'username' => $object->samaccountname, 'displayname' => $object->displayname, 'email' => $object->mail, 'memberof' => $object->memberof ); return $arr; } /** * Connect to LDAP * * @throws \Exception */ public function connectLdap() { try { $this->adldap = new adLDAP($this->config); } catch(adLDAPException $e) { throw new \Exception($e->getMessage()); } } }<file_sep>/app/controllers/LoginController.php <?php /** * ログイン画面 */ class LoginController extends BaseController { /** * コンストラクタ */ function __construct() { $this->requireAuth = true; parent::__construct(); } /** * ログイン画面表示 */ function getIndex() { return View::make('login') ->nest('parts_common_header', 'parts.common.header',['header_title' => '', 'login_button_hidden' => 'hidden-element']) ->nest('parts_common_error', 'parts.common.error',['error_message_list' => Session::get('error_message_list')]); } /** * ログイン処理 */ function postLogin(){ // 操作履歴ログ出力 DataManager::registerOperationLog( Input::get('login_id'), 'ログイン画面', 'ログイン', ''); // TESTロジック START // $userInfo = DataManager::getUserInfo(Input::get("login_id")); // if( ! $userInfo ){ // return Redirect::to('/') // ->with('error_message_list', ['User Name/Passwordの認証に失敗しました。']); // } // $user = new ChirpUser($userInfo); // Session::put('SESSION_KEY_CHIRP_USER', serialize($user)); // return Redirect::to('/top'); // TESTロジック END // 入力チェック if(CommonCheckLogic::isEmpty(Input::get('login_id'))) { $this->error_message_list[] = 'User Nameは必須です。'; } if(CommonCheckLogic::isEmpty(Input::get('password'))) { $this->error_message_list[] = 'PassWordは必須です。'; } // エラーがある場合 if($this->hasError()){ return Redirect::to('/') ->with('error_message_list',$this->error_message_list); } // LDAP認証 // if(LdapAuth::auth(Input::get("login_id"), Input::get("password"))){ if(true){ // ユーザー情報を取得 $userInfo = DataManager::getUserInfo(Input::get("login_id")); if($userInfo ){ // ユーザーオブジェクトをセッションに格納 $user = new ChirpUser($userInfo); Session::put('SESSION_KEY_CHIRP_USER', serialize($user)); }else{ $this->error_message_list[] = 'chirpアカウントが存在しません。'; } }else{ $this->error_message_list[] = 'User Name/Passwordの認証に失敗しました。'; } // エラーがある場合 if($this->hasError()){ return Redirect::to('/') ->with('error_message_list',$this->error_message_list); } return Redirect::to('/top'); } /** * ログアウト処理 */ function postLogout(){ $this->user = unserialize(Session::get('SESSION_KEY_CHIRP_USER')); // セッションタイムアウト時はログ出力しない(userが取得できない為) if ($this->user) { // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), '-', 'ログアウト', ''); } // セッションからユーザーオブジェクトを削除 Session::forget('SESSION_KEY_CHIRP_USER'); Session::forget('SESSION_KEY_REPORT_DATA'); return Redirect::to('/'); } } <file_sep>/app/extentions/CommonGateway/SystemCodeManager.php <?php namespace CommonGateway { use DB; use Log; class SystemCodeManager { private static $sql = 'select t2.code2, t2.value2 from mst_system_code_category t1 inner join mst_system_code t2 on t1.code1 = t2.code1 where t1.code1 = ? and (t2.report_class = ? or t2.report_class = "0") order by t2.disp_order'; /** * コンストラクタ */ function __construct() { } /** * 性別取得 */ function getGender(){ $result = DB::select( self::$sql, ['gender', 0] ); return $result; } /** * レポートタイプ取得 */ function getReportType($reportClass){ $result = DB::select( self::$sql, ['Report Type', $reportClass] ); return $result; } /** * レポート種別取得 */ function getReportClass(){ $result = DB::select( self::$sql, ['Report Class', 0] ); return $result; } /** * Ship No取得 */ function getShipNo($reportClass){ $result = DB::select( self::$sql, ['Ship No', $reportClass] ); return $result; } /** * Sector取得 */ function getSector($reportClass){ $result = DB::select( self::$sql, ['Sector', $reportClass] ); return $result; } /** * Phoenix class取得 */ function getPhoenixClass ($reportClass){ $result = DB::select( self::$sql, ['Phoenix class', $reportClass] ); return $result; } /** * カテゴリ取得 */ function getCategory($reportClass, $categoryOption = null){ $key = 'Category'; if($categoryOption){ $key = $key . ' ' . $categoryOption; } $result = DB::select( self::$sql, [$key, $reportClass] ); return $result; } /** * Station取得 */ function getStation ($reportClass){ $result = DB::select( self::$sql, ['Station', $reportClass] ); return $result; } /** * Line取得 */ function getLine ($reportClass){ $result = DB::select( self::$sql, ['Line', $reportClass] ); return $result; } /** * Sub category取得 */ function getSubCategory ($reportClass){ $result = DB::select( self::$sql, ['Sub Category', $reportClass] ); return $result; } /** * DLA CODE取得 */ function getDLACode ($reportClass){ $result = DB::select( self::$sql, ['DLA Code', $reportClass] ); return $result; } /** * Weather取得 */ function getWeather ($reportClass){ $result = DB::select( self::$sql, ['Weather', $reportClass] ); return $result; } /** * Area取得 */ function getArea ($reportClass){ $result = DB::select( self::$sql, ['Area', $reportClass] ); return $result; } /** * Factor取得 */ function getFactor ($reportClass){ $result = DB::select( self::$sql, ['Factor', $reportClass] ); return $result; } /** * Influence on Safety取得 */ function getInfluenceOnSafety ($reportClass){ $result = DB::select( self::$sql, ['Influence on Safety', $reportClass] ); return $result; } /** * Frequency取得 */ function getFrequency ($reportClass){ $result = DB::select( self::$sql, ['Frequency', $reportClass] ); return $result; } /** * Report Status取得 */ function getReportStatus (){ $result = DB::select( self::$sql, ['Report Status', 0] ); return $result; } } }<file_sep>/app/views/parts/report/report_status_area.php <label class="label06">Report No<br /><span>レポート番号</span></label> <label class="label07"><?= HTML::entities($report_info->report_no) ?></label> <label class="label06">Report Status<br /><span>レポートステータス</span></label> <label class="label07"><?= HTML::entities($report_info->report_status_name) ?></label> <label class="label06">Created<br /><span>作成日</span></label> <label class="label07"><?= HTML::entities($report_info->create_timestamp) ?> JST</label> <label class="label06">Modified<br /><span>更新日</span></label> <label class="label07" id="report_modified"><?= HTML::entities($report_info->update_timestamp) ?> JST</label> <file_sep>/app/views/parts/report/flight_info_peacock.php <script> $(function(){ $('#departure_date').on('change', function(){ $('#reporting_date').text(''); var array = $(this).val().split('/'); if(array.length != 3){ return; } var date = new Date($(this).val()); if( date.getFullYear() == parseInt(array[0]) && date.getMonth()+1 == parseInt(array[1]) && date.getDate() == parseInt(array[2])){ $('#reporting_date').text($(this).val()); } }); }); </script> <label for="departure_date" class="label01">Flight Date<br /><span>フライト日</span></label> <div class="label02"> <input type="text" id="departure_date" name="departure_date" class="inputbox datepicker" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('departure_date',$report_info->departure_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="Flight_No" class="label01">Flight No<br /><span>便名 ※MMXXXX(ex. MM0001)</span></label> <div class="label02"> <input type="text" id="flight_number" name="flight_number" class="inputbox" placeholder="MMXXXX(ex. MM0001)" value="<?= HTML::entities(Input::old('flight_number', $report_info->flight_number)) ?>" maxlength="6" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="Ship_No" class="label01">Ship No<br /><span>機番</span></label> <div class="label02"> <select id="ship_no" name="ship_no" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($ship_no_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('ship_no', $report_info->ship_no) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="Sector" class="label01">Sector<br /><span>区間</span></label> <div class="label02"> <select id="origin_rcd" name="origin_rcd" class="inputbox02" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($sector_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('origin_rcd', $report_info->origin_rcd) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> <p class="form-control-static">→</p> <select id="destination_rcd" name="destination_rcd" class="inputbox02" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($sector_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('destination_rcd', $report_info->destination_rcd) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="etd" class="label01">ETD<br /><span>出発予定時間</span></label> <div class="label02"> <input id="etd" name="etd" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('etd', $report_info->etd)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <label for="eta" class="label01">ETA<br /><span>到着予定時間</span></label> <div class="label02"> <input id="eta" name="eta" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('eta', $report_info->eta)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="atd" class="label01">ATD<br /><span>実出発時間</span></label> <div class="label02"> <input id="atd" name="atd" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('atd', $report_info->atd)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="ata" class="label01">ATA<br /><span>実到着時間</span></label> <div class="label02"> <input id="ata" name="ata" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('ata', $report_info->ata)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="pax_onboard" class="label01">PAX Onboard<br /><span>旅客数</span></label> <div class="label02"> <input id="pax_onboard" name="pax_onboard" type="text" class="inputbox" value="<?= HTML::entities(Input::old('pax_onboard', $report_info->pax_onboard)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="pax_detail" class="label01_2">PAX Remarks Code & Seat No<br /><span>配慮を要する旅客のコード・座席番号</span></label> <div class="label02"> <input id="pax_detail" name="pax_detail" type="text" class="inputbox" value="<?= HTML::entities(Input::old('pax_detail', $report_info->pax_detail)) ?>" maxlength="15" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="clearfix"></div> <label for="crew_cp" class="label01">CREW CP<br /><span>CP氏名</span></label> <div class="label02"> <input id="crew_cp" name="crew_cp" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('crew_cp', $report_info->crew_cp)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="crew_cap" class="label01">CREW CAP<br /><span>CAP氏名</span></label> <div class="label02"> <input id="crew_cap" name="crew_cap" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('crew_cap', $report_info->crew_cap)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="crew_r1" class="label01">CREW R1<br /><span>R1氏名</span></label> <div class="label02"> <input id="crew_r1" name="crew_r1" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('crew_r1', $report_info->crew_r1)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="crew_l2" class="label01">CREW L2<br /><span>L2氏名</span></label> <div class="label02"> <input id="crew_l2" name="crew_l2" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('crew_l2', $report_info->crew_l2)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="crew_r2" class="label01">CREW R2<br /><span>R2氏名</span></label> <div class="label02"> <input id="crew_r2" name="crew_r2" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('crew_r2', $report_info->crew_r2)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <file_sep>/resources/js/common.js function disableBrowserBack(){ //History API が使えるブラウザかどうかをチェック if( window.history && window.history.pushState ){ //. ブラウザ履歴に1つ追加 history.pushState( "nohb", null, "" ); $(window).on( "popstate", function(event){ //. このページで「戻る」を実行 if( !event.originalEvent.state ){ //. もう一度履歴を操作して終了 history.pushState( "nohb", null, "" ); return; } }); } } function exec(formObj, action){ //showIndicator(true, 0.4); $('button').prop("disabled", true); $('a').addClass("avoid-clicks"); $(formObj).attr('action', action); $(formObj).submit(); } function execWithConfirm(formObj, action, message){ if(confirm(message)){ $('button').prop("disabled", true); $('a').addClass("avoid-clicks"); $(formObj).attr('action', action); $(formObj).submit(); } } function execCancel(formObj, action, message){ var mode = $('#_mode').val(); if( mode == 'reference' || mode == 'other' || mode == 'relation' ){ exec(formObj, action); }else{ execWithConfirm(formObj, action, message); } } /** * テーブルレイアウト設定 */ function settingTable(selector, pageLength, ordering, info, paging){ $(function(){ $(selector).dataTable({ // 件数表示 "info":info, // 表示件数 "pageLength": pageLength, // 検索 "searching":false, "autoWidth":true, // 表示件数変更 "lengthChange":false, // ソート "ordering":ordering, "order":[], "processing":true, // ページング "paging":paging // "language": { // "processing": "処理中...", // "lengthMenu": "_MENU_ 件表示", // "emptyTable": "データはありません", // "zeroRecords": "データはありません。", // "info": " _TOTAL_ 件中 _START_ から _END_ まで表示", // "infoEmpty": " 0 件中 0 から 0 まで表示", // "infoFiltered": "(全 _MAX_ 件より抽出)", // "infoPostFix": "", // "search": "検索:", // "url": "", // "paginate": { // "first": "先頭", // "previous": "前", // "next": "次", // "last": "最終" // } // } }); }); } function showDialog(){ $(function(){ $('#groupEditModal').modal('show'); }); } // //function settingDialog(){ // // $(function(){ // // ダイアログ表示前にJavaScriptで操作する // $('#groupEditModal').on('show.bs.modal', function (event) { // var button = $(event.relatedTarget); // var data = button.data; // }); // }); //} var l; function showLaddaIndicator(data){ var ajaxStatus = data.status; switch(ajaxStatus){ case "begin": l = Ladda.create( document.querySelector( '.ladda-button' ) ); l.start(); console.log('ajax:begin'); break; case "complete": l.stop(); console.log('ajax:complete'); break; case "success": console.log('ajax:success'); break; } } function showActivityIndicator(data){ var ajaxStatus = data.status; switch(ajaxStatus){ case "begin": console.log('ajax:begin'); showBlockIndicator(); break; case "complete": console.log('ajax:complete'); hideIndicator(); break; case "success": console.log('ajax:success'); break; } } var isShow = false; function setConfirm(selector, message){ $(function(){ $(document).on('click',selector,function(event) { if(!isShow){ var ajaxEvent = event; isShow = true; bootbox.dialog({ message:message, title: '確認', closeButton: false, locale:'ja', buttons: { CANCEL: { label: 'キャンセル', className: "btn-gray btn-lg btn-block bootboxButton", colClassName:'col-md-4 col-md-offset-2', callback: function() { isShow = false; bootbox.hideAll(); } }, OK: { label: "OK", className: "btn-signage btn-lg btn-block bootboxButton", colClassName:'col-md-4', callback: function() { isShow = false; bootbox.hideAll(); //var id = $(selector).attr('id'); //document.getElementById(id).click(); jsf.ajax.request(event.target, event, { execute:'@form', render: '@form', onevent:showActivityIndicator } ); //event.preventDefault(); } } } }); } event.preventDefault(); }); }); } /** * インジケータを表示する(ブロックあり、背景:黒) */ function showBlockIndicator(){ showIndicator(true, 0.4); } /** * インジケータを表示する(ブロックあり、背景:白) */ function showBlockWhiteIndicator(){ showIndicator(true, 0); } /** * インジケータを表示する(ブロックなし) */ function showNoBlockIndicator(){ showIndicator(false, 0); } /** * インジケータを表示する * @param isBlock ブロックするかどうか(default:true) * @param overlayOpacity 背景の透過率(default:0.4) */ function showIndicator(isBlock, overlayOpacity){ $(function(){ $.blockUI.defaults.css = {}; $.blockUI({ message: '<div class="container">' + '<div class="row">' + '<div class="col-md-12 text-center">' + '<img src="/resources/js/img/ajax-loader.gif"/>' + '</div>' + '</div>' + '</div>', showOverlay:isBlock, css: { padding: 0, margin: 0, top:'30%', left:0, width:'100%', cursor: 'wait' }, overlayCSS: { backgroundColor: '#000', opacity: overlayOpacity, cursor: 'wait' } }); }); } /** * インジケータを非表示にする * @param callback コールバック */ function hideIndicator(callback){ $(function(){ $.unblockUI(); if(callback != null){ callback(); } }); } /** * 行選択時の処理 * @param callback コールバック * @returns {Boolean} */ function OnEditClick(callback){ callback(); return false; } /** * 確認ダイアログ表示 * @param button ボタン * @param message メッセージ * @param callback コールバック * @param validate バリデート */ function showConfirm(button, message, callback, validate){ $(button).prop('disabled', true); if(validate != null){ if(!validate()){ $(button).prop('disabled', false); return false; } } bootbox.dialog({ message:message, title: '確認', closeButton: false, locale:'ja', buttons: { CANCEL: { label: 'キャンセル', className: "btn-gray btn-lg btn-block bootboxButton", colClassName:'col-md-4 col-md-offset-2', callback: function() { $(button).prop('disabled', false); bootbox.hideAll(); } }, OK: { label: "OK", className: "btn-signage btn-lg btn-block bootboxButton", colClassName:'col-md-4', callback: function() { $(button).prop('disabled', false); callback(); } } } }); return false; } /** * 確認ダイアログ表示 * @param message メッセージ * @param callback コールバック */ function showFunctionConfirm(message, callback){ bootbox.dialog({ message:message, title: '確認', closeButton: false, locale:'ja', buttons: { CANCEL: { label: 'キャンセル', className: "btn-gray btn-lg btn-block bootboxButton", colClassName:'col-md-4 col-md-offset-2', callback: function() { bootbox.hideAll(); } }, OK: { label: "OK", className: "btn-signage btn-lg btn-block bootboxButton", colClassName:'col-md-4', callback: function() { callback(); } } } }); return false; } /** * コメント入力ダイアログ表示 * @param button ボタン */ function showCommentDialog(button, reportNo, reportClass, _mode){ $(button).prop('disabled', true); var reportName; switch (reportClass) { case '1': reportName = 'PENGUIN'; break; case '3': reportName = 'PEREGRINE_Incident'; break; case '2': reportName = 'PEREGRINE_Irregularity'; break; case '4': reportName = 'PEACOCK'; break; default: break; } var html = '<nav class="navbar navbar-peach">' + '<div class="container-fluid">' + '<div id="main">' + '<p id="logo"></p>' + '<h1>Chirp - ' + reportName + '</h1>' + '</div>' + '</div>' + '</nav>' + '<div class="row">' + '<div id="modal_error" class="col-md-12">' + '</div>' + '</div>' + '<div class="well">' + '<form onsubmit="return false;">' + '<div class="form-horizontal">' + '<div class="form-group">' + '<label for="Comments" class="col-md-3 control-label text-right">Comments</label>' + '<div class="col-md-8">' + '<textarea type="text" name="modal_comment" id="modal_comment" cols="100" rows="5" class="form-control no-resize-horizontal-textarea" maxlength="1500"></textarea>' + '</div>' + '</div>' + '</div>' + '<div class="form-horizontal">' + '<div class="form-group">' + '<label for="Author" class="col-md-3 control-label text-right">Author</label>' + '<div class="col-md-8">' + '<input type="text" name="modal_author" id="modal_author" class="form-control" maxlength="40">' + '</div>' + '</div>' + '</div>' + '</form>' + '</div>' + '</div>'; bootbox.dialog({ message:html, closeButton: false, locale:'ja', buttons: { CANCEL: { label: 'Cancel', className: "btn-pink btn-sm btn-block bootboxButton", colClassName:'col-md-2 col-md-offset-3', callback: function() { $(button).prop('disabled', false); bootbox.hideAll(); } }, OK: { label: "Save", className: "btn-pink btn-sm btn-block bootboxButton", colClassName:'col-md-2 col-md-offset-2', callback: function() { $('#modal_error').html(''); var comment = $('#modal_comment').val(); var author = $('#modal_author').val(); if(comment.trim() == '' || author == ''){ $('#modal_error').html('<div class="alert alert-danger"><button class="close" data-dismiss="alert">&#215;</button><ul><li>CommentsとAuthorは入力必須です。</li></ul></div>'); return false; }else{ $(button).prop('disabled', false); $.ajax({ type: 'POST', url: '/p/chirp/report/add-comment', dataType: 'html', data:{ 'modal_comment':comment, 'modal_author':author, 'modal_report_no':reportNo, '_report_class':reportClass, '_mode':_mode } }) .done(function(data, textStatus, jqXHR){ $('#comment').html(data); }) .fail(function(jqXHR, textStatus, errorThrown) { alert('コメント登録に失敗しました'); }) .always(function(data, textStatus, errorThrown){ }); } } } } }); return false; } /** * アップロードプログレスダイアログ表示 * @param button ボタン * @param callback コールバック */ function showUploadProgressDialog(data){ var html = '<div class="row">' + '<div class="col-md-12">' + '<h2></h2>'+ '<div class="progress">'+ '<div class="progress-bar progress-bar-info" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">'+ '</div>'+ '</div>'+ '</div>' + '</div>' var jqXHR; bootbox.dialog({ message:html, title: '処理中...', closeButton: false, locale:'ja', buttons: { CANCEL: { label: 'キャンセル', className: "btn-gray btn-lg btn-block bootboxButton", colClassName:'col-md-4 col-md-offset-4', callback: function() { jqXHR.abort(); bootbox.hideAll(); } } } }); jqXHR = data.submit(); return false; } /** * アップロードプログレスダイアログ設定 * @param apiUrl APIのURL * @param listUrl 一覧画面のURL */ function setUploadProgress(apiUrl, listUrl){ $(function () { $('#selectFile').on('click', function() { $('#upload_file').trigger('click'); }); $('#upload_file').change(function() { $('#selectedFile').val($(this).val()); }); $('#upload_file').fileupload({ url:apiUrl, dataType: 'json', autoUpload : false, add: function (e, data) { $('#uploadButton').on('click',function () { showUploadProgressDialog(data); return false; }); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('.progress-bar').css( 'width', progress + '%' ); $('.progress-bar').html(progress + '%'); }, done: function (data, textStatus, jqXHR ) { bootbox.hideAll(); location.replace(listUrl); }, fail: function(jqXHR, textStatus, errorThrown) { if (textStatus.errorThrown === 'abort') { console.log('File Upload has been canceled'); }else{ console.log('upload error!'); } $('.progress-bar').css('width','0%'); $('.progress-bar').html('0%'); bootbox.hideAll(); //location.reload(); } }); }); } /** * メッセージダイアログ表示 * @param message メッセージ */ function showMessageDialog(message){ bootbox.dialog({ message:message, title: '確認', closeButton: false, locale:'ja', buttons: { OK: { label: "OK", className: "btn-signage btn-lg btn-block bootboxButton", colClassName:'col-md-4 col-md-offset-4', callback: function() { bootbox.hideAll(); } } } }); }<file_sep>/app/views/report.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp <?= HTML::entities($header_title) ?></title> <?= HTML::style('resources/bootstrap/css/bootstrap.min.css') ?> <?= HTML::style('resources/css/jquery-ui.min.css') ?> <?= HTML::style('resources/css/awesome-bootstrap-checkbox.css') ?> <?= HTML::style('resources/bower_components/Font-Awesome/css/font-awesome.css') ?> <?= HTML::style('resources/css/pnotify.custom.min.css') ?> <?= HTML::style('resources/css/extends-bootstrap.css') ?> <?= HTML::style('resources/css/common.css') ?> <?= HTML::style('resources/css/style.css') ?> <?= HTML::style('resources/css/new_style.css') ?> <?= HTML::script('resources/js/jquery-1.11.2.min.js') ?> <?= HTML::script('resources/js/jquery-ui.min.js') ?> <?= HTML::script('resources/bootstrap/js/bootstrap.min.js') ?> <?= HTML::script('resources/js/bootbox.js') ?> <?= HTML::script('resources/js/jquery.blockUI.js') ?> <?= HTML::script('resources/js/pnotify.custom.min.js') ?> <?= HTML::script('resources/js/common.js') ?> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script> disableBrowserBack(); function loadcategory(){ // エラー時に前回データ取得不能エリア(category,MR)のデータ回復 // category <?php $category_listSize = Input::old('category_list_count', 0); ?> <?php for ($index = 0; $index < $category_listSize; $index++){ $item_caterory = Input::old("category_".($index + 1), null); if($item_caterory != null){ ?> $('#category_<?=($index + 1)?>').prop('checked', true); // ON にする <?php }else{ ?> $('#category_<?=($index + 1)?>').prop('checked', false); // OFF にする <?php } } ?> // MR <?php $mr_content = Input::old("mr", null); if($mr_content !== null){ ?> $('#mr').val('<?=$mr_content?>'); <?php } ?> } function clearcategory(){ $('div#category_area :checkbox') .prop('checked', false); // OFF にする $('#mr') .val(''); // 空欄 にする } function errorcategory(){ var err_title = $('#category .container-fluid .title').text(); var pattern = "エラー"; if (err_title.match(pattern)) { location.href = '/p/chirp/error'; } } // 追加お客様情報存在チェック function checkAdditionalPaxinfo(){ var addtionData = false; $('.additional-pax-info'+':text').each(function(i) { var inputData = $(this).val(); if(inputData){ // データあり addtionData = true; } }); $('.additional-pax-info'+':selected').each(function(i) { var inputData = $(this).val(); if(inputData){ // データあり addtionData = true; } }); // 追加お客様情報あり(表示) if(addtionData){ $('#collapsePaxInfo').collapse('show'); } } // 追加予約情報存在チェック function checkAdditionalResavationinfo(){ var addtionData = false; $('.additional-resavation-info'+':text').each(function(i) { var inputData = $(this).val(); if(inputData){ // データあり addtionData = true; } }); // 追加予約情報あり(表示) if(addtionData){ $('#collapseResavationInfo').collapse('show'); } } function downloadFile(formObj, action, file_seq){ $('#_file_seq').val(file_seq); $(formObj).attr('action', action); $(formObj).submit(); } function getReportType(){ $.ajax({ type: 'POST', url: '/p/chirp/report/change', dataType: 'html', data:{ 'report_type':$('#report_type').val(), '_report_class':$('#_report_class').val(), '_report_status':$('#_report_status').val(), '_mode':$('#_mode').val() } }) .done(function(data, textStatus, jqXHR){ $('#category').html(data); }) .fail(function(jqXHR, textStatus, errorThrown) { alert('カテゴリ取得に失敗しました'); }) .always(function(data, textStatus, errorThrown){ }); } function getComment(){ $.ajax({ type: 'POST', url: '/p/chirp/report/comment', dataType: 'html', data:{ 'report_no':$('#_report_no').val(), '_report_class':$('#_report_class').val() } }) .done(function(data, textStatus, jqXHR){ $('#comment').html(data); }) .fail(function(jqXHR, textStatus, errorThrown) { alert('コメント取得に失敗しました'); }) .always(function(data, textStatus, errorThrown){ }); } $(function(){ $(".datepicker").datepicker(); $(window).load(function () { if($('#_report_class').val() == 1){ if($('#sub_category_other_check').prop('checked')){ $('#sub_category').prop('disabled', true); }else{ $('#sub_category_other').prop('disabled', true); } } if($('#_report_class').val() == 4){ getReportType(); } <?php if(count($error_message_list) <= 0){ ?> if($('#_mode').val() == 'inquiry'){ var position = $("#Inquiry").offset().top; $(window).scrollTop(position); } <?php }?> getComment(); if($('#_has_additional_pax_info').val() == 1){ $('#collapsePaxInfo').collapse('show'); } if($('#_has_additional_resavation_info').val() == 1){ $('#collapseResavationInfo').collapse('show'); } // 追加お客様情報チェック checkAdditionalPaxinfo(); // 追加予約情報チェック checkAdditionalResavationinfo(); // Ajax取得時間を遅延させて実行 setTimeout(function() { errorcategory(); loadcategory(); }, 1000); }); $('#sub_category_other_check').on('change', function(){ if($(this).prop('checked')){ $('#sub_category').val(''); $('#sub_category').prop('disabled', true); $('#sub_category_other').prop('disabled', false); }else{ $('#sub_category').prop('disabled', false); $('#sub_category_other').val(''); $('#sub_category_other').prop('disabled', true); } }); $(".attache-file").on('change', function() { var index = $(this).data('attach-file-index'); var value = $(this).val(); if(value == ''){ return; } $('#dummy_file_' + index).text(value); }); $(".attache-file-clear").on('click', function() { var index = $(this).data('attach-file-index'); $('#attach_file_' + index).val(''); $('#dummy_file_' + index).text('ファイル未選択'); }); $(".attache-file-delete").on('click', function() { var index = $(this).data('attach-file-index'); var seq = $(this).data('attach-file-seq'); $('#delete_file_' + index).val(seq); var parent = $(this).parents('li');//.addClass('hidden-element'); parent.addClass('hidden-element'); }); $("#report_type").on('change',function () { $.ajax({ type: 'POST', url: '/p/chirp/report/change', dataType: 'html', data:{ 'report_type':$(this).val(), '_report_class':$('#_report_class').val(), '_report_status':$('#_report_status').val(), '_mode':$('#_mode').val() } }) .done(function(data, textStatus, jqXHR){ $('#category').html(data); }) .fail(function(jqXHR, textStatus, errorThrown) { alert('カテゴリ取得に失敗しました'); }) .always(function(data, textStatus, errorThrown){ }); // カテゴリエリアの全消去 // Ajax取得時間を遅延させて実行 setTimeout(function() { errorcategory(); clearcategory(); }, 500); return false; }); $('#collapseAttachFile').on('shown.bs.collapse', function () { $('#attachFileIcon').removeClass('glyphicon-plus'); $('#attachFileIcon').addClass('glyphicon-minus'); }) $('#collapseAttachFile').on('hidden.bs.collapse', function () { $('.additional-attach-file').val(''); $('.additional-attach-file-label').text('ファイル未選択'); $('#attachFileIcon').removeClass('glyphicon-minus'); $('#attachFileIcon').addClass('glyphicon-plus'); }) $('#collapsePaxInfo').on('shown.bs.collapse', function () { $('#paxInfoIcon').removeClass('glyphicon-plus'); $('#paxInfoIcon').addClass('glyphicon-minus'); }) $('#collapsePaxInfo').on('hidden.bs.collapse', function () { $('.additional-pax-info').val(''); $('.additional-pax-info').attr("selected",false); $('#paxInfoIcon').removeClass('glyphicon-minus'); $('#paxInfoIcon').addClass('glyphicon-plus'); }) $('#collapseResavationInfo').on('shown.bs.collapse', function () { if($('#record_locator_2').val() + $('#departure_date_2').val() + $('#flight_number_2').val() == ''){ $('#flight_number_2').val('MM'); } $('#resavationInfoIcon').removeClass('glyphicon-plus'); $('#resavationInfoIcon').addClass('glyphicon-minus'); }) $('#collapseResavationInfo').on('hidden.bs.collapse', function () { $('.additional-resavation-info').val(''); $('.additional-resavation-info').attr("selected",false); $('#resavationInfoIcon').removeClass('glyphicon-minus'); $('#resavationInfoIcon').addClass('glyphicon-plus'); }) }); </script> </head> <body> <!-- ヘッダー --> <?= $parts_common_header ?> <div class="container-fluid" style="font-size:97%"> <form id="mainForm" action="" method="post" enctype="multipart/form-data"> <input type="hidden" id="_mode" name="_mode" value="<?= HTML::entities($_mode) ?>"/> <input type="hidden" id="_report_no" name="_report_no" value="<?= HTML::entities($report_info->report_no) ?>"/> <input type="hidden" id="_report_class" name="_report_class" value="<?= HTML::entities($report_info->report_class) ?>"/> <input type="hidden" id="_report_status" name="_report_status" value="<?= HTML::entities($report_info->report_status) ?>"/> <input type="hidden" id="_file_seq" name="_file_seq" value=""/> <input type="hidden" id="_modified" name="_modified" value="<?= HTML::entities($report_info->update_timestamp) ?>"/> <input type="hidden" id="_has_additional_pax_info" name="_has_additional_pax_info" value="<?= HTML::entities($report_info->has_additional_pax_info) ?>"/> <input type="hidden" id="_has_additional_reservation_info" name="_has_additional_reservation_info" value="<?= HTML::entities($report_info->has_additional_reservation_info) ?>"/> <!-- エラーメッセージ表示エリア --> <?= $parts_common_error ?> <!-- レポート個別アラートボタンエリア --> <?= $parts_report_alert_button ?> <div id="content" class="clearfix"> <div class="left_side"> <?php if(strlen(trim($parts_flight_info_area))): ?> <div class="form_cate clearfix"> <div class="cate_title">Flight Information</div> <!-- フライト個別エリア --> <?= $parts_flight_info_area ?> </div> <?php endif; ?> <div class="form_cate clearfix"> <div class="cate_title">Report Information</div> <!-- レポート個別エリア --> <?= $parts_report_individuals_area ?> <!-- 添付ファイル --> <?= $parts_report_attached_file_area ?> <!-- 関連レポートエリア --> <?= $parts_report_related_report_area ?> <!-- 備考欄エリア --> <?= $parts_remarks_area ?> </div> <!-- 予約情報エリア --> <?php if($report_info->report_class == 1){ ?> <div class="form_cate clearfix"> <div class="cate_title">Reservation Information</div> <?= $parts_resavation_info_area ?> </div> <?php }?> </div> <div class="right_side"> <div class="form_cate clearfix"> <div class="cate_title">Report Definition</div> <!-- 設定エリア --> <?= $parts_report_config_area ?> <!-- レポートステータスエリア --> <?php if($report_info->report_no){ ?> <?= $parts_report_status_area ?> <?php }?> <!-- レポート定義個別エリア --> <?= $parts_report_definition_area ?> </div> <?php if(strlen(trim($parts_report_inquiry_area))): ?> <div class="form_cate clearfix <?= HTML::entities($role_manage_info->comment_area_hidden) ?>"> <div id="Inquiry" class="cate_title">Inquiry</div> <!-- 照会エリア --> <?= $parts_report_inquiry_area ?> </div> <?php endif; ?> <div class="form_cate clearfix"> <div class="cate_title">PAX Information</div> <!-- お客様情報エリア --> <?= $parts_report_pax_info_area ?> <!-- Phoenixエリア --> <?= $parts_report_phoenix_area ?> </div> </div> </div> <div id="pagetop"> <a href="#top">▲Page Top</a> </div> <div id="footer"> <!-- メール送信先選択エリア --> <?= $parts_report_send_mail_area ?> <!-- ボタンエリア --> <?= $parts_report_button_area ?> </div> </form> </div> </body> </html><file_sep>/app/views/parts/common/header.php <form id="headerForm" action="/p/chirp/logout" method="post"> <nav class="navbar navbar-peach"> <div class="container-fluid"> <div id="main"> <p id="logo"></p> <h1>Chirp <?= HTML::entities($header_title) ?> <button id="logoutButton" type="submit" class="btn navbar-btn btn-pink pull-right <?php echo $login_button_hidden ?>" onclick="return confirm('ログアウトします。よろしいですか?');">Log out</button> </h1> </div> </div> </nav> </form><file_sep>/app/extentions/MailManager.php <?php use Illuminate\Support\Facades\Facade; class MailManager extends Facade { protected static function getFacadeAccessor() { return 'MailManager'; } }<file_sep>/app/views/top.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp <?= HTML::entities($header_title) ?></title> <?= HTML::style('resources/bootstrap/css/bootstrap.min.css') ?> <?= HTML::style('resources/css/jquery-ui.min.css') ?> <?= HTML::style('resources/css/dataTables.bootstrap.css') ?> <?= HTML::style('resources/css/awesome-bootstrap-checkbox.css') ?> <?= HTML::style('resources/bower_components/Font-Awesome/css/font-awesome.css') ?> <?= HTML::style('resources/css/extends-bootstrap.css') ?> <?= HTML::style('resources/css/common.css') ?> <?= HTML::style('resources/css/style.css') ?> <?= HTML::script('resources/js/jquery-1.11.2.min.js') ?> <?= HTML::script('resources/js/jquery-ui.min.js') ?> <?= HTML::script('resources/bootstrap/js/bootstrap.min.js') ?> <?= HTML::script('resources/js/bootbox.js') ?> <?= HTML::script('resources/js/jquery.blockUI.js') ?> <?= HTML::script('resources/js/jquery.dataTables.min.js') ?> <?= HTML::script('resources/js/dataTables.bootstrap.js') ?> <?= HTML::script('resources/js/common.js') ?> <?= HTML::script('resources/js/jquery.narrows.min.js') ?> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script type="text/javascript"> disableBrowserBack(); settingTable('#inqueryReportTable',1000,false, false, false); settingTable('#newReportTable',6, true, true, true); settingTable('#newReportTable2',6, true, true, true); settingTable('#searchReportTable',10, false, true, true); $(function(){ $(".datepicker").datepicker(); if($('#_mode').val() == 'search_success'){ var position = $("#reportSearch").offset().top; $(window).scrollTop(position); } var first_flg = true; $('#search_report_class').change(function() { var report_class = $(this).val(); /** カテゴリ初期化 **/ if(first_flg == false) { $('#search_category').val(''); } /** レポート種別による設定 **/ if(report_class == '2' || report_class == '3') { $('#search_area').prop('disabled', false); $('#search_assessment').prop('disabled', false); } else { $('#search_area').val(''); $('#search_area').prop('disabled', true); $('#search_assessment').val(''); $('#search_assessment').prop('disabled', true); } if(report_class == '4') { $('#search_station').val(''); $('#search_station').prop('disabled', true); } else { $('#search_station').prop('disabled', false); } first_flg = false; }); $('#search_report_class').change(); $("#search_report_class").narrows("#search_category"); }); function addReport(formObj, action, report_class){ $('#_selected_report_class').val(report_class); $('#_selected_report_status').val(''); $('#_selected_report_no').val(''); $('button').prop("disabled", true); $('tr').addClass("avoid-clicks"); $(formObj).attr('action', action); $(formObj).submit(); } function selectInquiryReport(formObj, action, report_class, report_no, report_status){ $('#_selected_report_class').val(report_class); $('#_selected_report_status').val(report_status); $('#_selected_report_no').val(report_no); $('#_inquiry_mode').val('on'); $('tr').addClass("avoid-clicks"); $('button').prop("disabled", true); $(formObj).attr('action', action); $(formObj).submit(); } function selectReport(formObj, action, report_class, report_no, report_status){ $('#_selected_report_class').val(report_class); $('#_selected_report_status').val(report_status); $('#_selected_report_no').val(report_no); $('#_inquiry_mode').val('off'); $('button').prop("disabled", true); $('tr').addClass("avoid-clicks"); $(formObj).attr('action', action); $(formObj).submit(); } function selectPreview(formObj, action, report_class, report_no, report_status) { $('#_selected_report_class').val(report_class); $('#_selected_report_status').val(report_status); $('#_selected_report_no').val(report_no); $(formObj).attr('action', action); $(formObj).attr('target', 'preview'); $(formObj).submit(); $(formObj).removeAttr('target'); } function alertSetting(formObj, href) { $('button').prop("disabled", true); $('tr').addClass("avoid-clicks"); $(formObj).attr('action', href); $(formObj).submit(); } </script> </head> <body> <?= $parts_common_header ?> <div class="container-fluid"> <form id="mainForm" action="" method="post"> <input type="hidden" id="_mode" name="_mode" value="<?php echo $_mode ?>" /> <input type="hidden" id="_selected_report_no" name="_selected_report_no" value="" /> <input type="hidden" id="_selected_report_class" name="_selected_report_class" value="" /> <input type="hidden" id="_selected_report_status" name="_selected_report_status" value="" /> <input type="hidden" id="_inquiry_mode" name="_inquiry_mode" value="" /> <?= $parts_common_error ?> <?php if(unserialize(Session::get('SESSION_KEY_CHIRP_USER'))->userInfo->report_name == 'PEREGRINE' && !unserialize(Session::get('SESSION_KEY_CHIRP_USER'))->isCreator()): ?> <div class="row"> <div class="col-md-12"> <div class="form-group pull-right"> <button type="button" class="btn btn-pink btn-xs" onclick="addReport(document.forms.mainForm, '/p/chirp/top/alert')">&nbsp;Alert Setting&nbsp;</button> </div> </div> </div> <?php endif; ?> <?php if(unserialize(Session::get('SESSION_KEY_CHIRP_USER'))->userInfo->user_role != 0 ){?> <div class="row"> <div class="col-md-4"> <div class="row"> <div class="col-md-1 pull-left"> <span style="background-color: #CE019E;font-size:150%">&nbsp;</span> </div> <div class="col-md-10 text-left"> <span style="font-size:150%"><strong>Inquiry</strong></span> </div> </div> </div> </div> <div class="row row-margin-bottom-80"> <div class="col-md-12"> <table id="inqueryReportTable" class="table table-bordered table-hover" border="1" cellpadding="2" bordercolor="#000000"> <thead> <tr class="gray"> <th>Date</th> <th>Report No</th> <th>Reported By</th> <th>Inquired From</th> </tr> </thead> <tbody> <?php foreach($inquiry_report_list as $data) { ?> <tr onclick="selectInquiryReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"> <td><?= HTML::entities($data->inquiry_timestamp) ?></td> <td><?= HTML::entities($data->report_no) ?></td> <td><?= HTML::entities($data->reported_by) ?></td> <td><?= HTML::entities($data->inquery_from) ?></td> </tr> <?php } ?> </tbody> </table> </div> </div> <?php } ?> <?= $new_report_view ?> <div id="reportSearch" class="row"> <div class="col-md-4"> <div class="row"> <div class="col-md-1 pull-left"> <span style="background-color: #CE019E;font-size:150%">&nbsp;</span> </div> <div class="col-md-10 text-left"> <span style="font-size:150%"><strong>Search</strong></span> </div> </div> </div> </div> <div class="row" style="margin-top: 10px;"> <div class="col-md-4"> <?= Form::text('search_free_word', Input::old('search_free_word', $search_report_condition->free_word), ['id' => 'search_free_word', 'class' => 'form-control input-sm', 'placeholder' => 'Keywords(including Report No,Flight No or Contents)']) ?> </div> <div class="col-md-3"> <select id="search_report_class" name="search_report_class" class="form-control"> <?php foreach($report_class_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('search_report_class', $search_report_condition->report_class) == $data->code2 ? 'selected="selected"' : '' ?> <?= HTML::entities($data->disable) ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> </div> <div class="row"> <div class="col-md-4"> <div class="row"> <label class="col-md-12 control-label text-left">Created Date</label> </div> <div class="row"> <div class="col-md-5"> <?= Form::text('search_create_date_from', Input::old('search_create_date_from', $search_report_condition->create_date_from), ['id' => 'search_create_date_from', 'class' => 'form-control datepicker', 'placeholder' => 'From Date','maxlength' => '10']) ?> </div> <div class="col-md-1"> <font size="+2.5">-</font> </div> <div class="col-md-5"> <?= Form::text('search_create_date_to', Input::old('search_create_date_to', $search_report_condition->create_date_to), ['id' => 'search_create_date_to', 'class' => 'form-control datepicker', 'placeholder' => 'To Date','maxlength' => '10']) ?> </div> </div> </div> <div class="col-md-4"> <div class="row"> <label class="col-md-12 control-label text-left">Reporting Date</label> </div> <div class="row"> <div class="col-md-5"> <?= Form::text('search_reporting_date_from', Input::old('search_reporting_date_from', $search_report_condition->reporting_date_from), ['id' => 'search_reporting_date_from', 'class' => 'form-control datepicker', 'placeholder' => 'From Date','maxlength' => '10']) ?> </div> <div class="col-md-1"> <font size="+2.5">-</font> </div> <div class="col-md-5"> <?= Form::text('search_reporting_date_to', Input::old('search_reporting_date_to', $search_report_condition->reporting_date_to), ['id' => 'search_reporting_date_to', 'class' => 'form-control datepicker', 'placeholder' => 'To Date','maxlength' => '10']) ?> </div> </div> </div> <div class="col-md-4"> <div class="row"> <label class="col-md-12 control-label text-left">Flight Date</label> </div> <div class="row"> <div class="col-md-5"> <?= Form::text('search_flight_date_from', Input::old('search_flight_date_from', $search_report_condition->flight_date_from), ['id' => 'search_flight_date_from', 'class' => 'form-control datepicker', 'placeholder' => 'From Date','maxlength' => '10']) ?> </div> <div class="col-md-1"> <font size="+2.5">-</font> </div> <div class="col-md-5"> <?= Form::text('search_flight_date_to', Input::old('search_flight_date_to', $search_report_condition->flight_date_to), ['id' => 'search_flight_date_to', 'class' => 'form-control datepicker', 'placeholder' => 'To Date','maxlength' => '10']) ?> </div> </div> </div> <div class="col-md-12"> <div class="row"> <label class="col-md-2 control-label text-left">Report Status</label> <label class="col-md-2 control-label text-left">Category</label> <label class="col-md-2 control-label text-left">Station</label> <label class="col-md-2 control-label text-left">Area</label> <label class="col-md-2 control-label text-left">Assessment</label> </div> <div class="row"> <div class="col-md-2"> <select id="search_status" name="search_status" class="form-control" > <option class="additional-conditions" value=""></option> <?php foreach($report_status_list as $report_status):?> <option class="additional-conditions" <?php echo Input::old('search_status', $search_report_condition->status) == $report_status->code2 ? 'selected="selected"' : '' ?> value="<?= HTML::entities($report_status->code2)?>" ><?= HTML::entities($report_status->value2) ?></option> <?php endforeach; ?> </select> </div> <div class="col-md-2"> <select id="search_category" name="search_category" class="form-control" > <option class="additional-conditions" value="" data-report-class="0"></option> <?php foreach($category_list as $report_class => $data): ?> <?php foreach($data as $category): ?> <?php if($report_class != '4'): ?> <option class="additional-conditions" value="<?=$category->code2?>" <?php echo Input::old('search_category', $search_report_condition->category) == $category->code2 ? 'selected="selected"' : '' ?> data-search_report_class="<?=$report_class?>"><?=HTML::entities($category->value2)?></option> <?php else: ?> <option class="additional-conditions" value="<?=$category->code2?>" <?php echo Input::old('search_category', $search_report_condition->category) == $category->code2 ? 'selected="selected"' : '' ?> data-search_report_class="<?=$report_class?>"><?=HTML::entities($category->code2)?> <?=$category->value2?></option> <?php endif; ?> <?php endforeach; ?> <?php endforeach; ?> </select> </div> <div class="col-md-2"> <input id="search_station" class="form-control additional-conditions" name="search_station" type="text" placeholder="ex. KIX CTS" value="<?=$search_report_condition->station ?>"> </div> <div class="col-md-2"> <select id="search_area" name="search_area" class="form-control" > <option class="additional-conditions" value=""></option> <?php foreach($area_list as $area): ?> <option class="additional-conditions" <?php echo Input::old('search_area', $search_report_condition->area) == $area->code2 ? 'selected="selected"' : '' ?> value="<?=HTML::entities($area->code2) ?>" ><?=HTML::entities($area->value2) ?></option> <?php endforeach; ?> </select> </div> <div class="col-md-2"> <select id="search_assessment" name="search_assessment" class="form-control " > <option class="additional-conditions" value=""></option> <option class="additional-conditions" <?php echo Input::old('search_assessment', $search_report_condition->assessment) == 'Level A' ? 'selected="selected"' : '' ?> value="Level A" >Level A</option> <option class="additional-conditions" <?php echo Input::old('search_assessment', $search_report_condition->assessment) == 'Level B' ? 'selected="selected"' : '' ?> value="Level B" >Level B</option> <option class="additional-conditions" <?php echo Input::old('search_assessment', $search_report_condition->assessment) == 'Level C' ? 'selected="selected"' : '' ?> value="Level C" >Level C</option> <option class="additional-conditions" <?php echo Input::old('search_assessment', $search_report_condition->assessment) == 'Level D' ? 'selected="selected"' : '' ?> value="Level D" >Level D</option> </select> </div> </div> <div class="row"> <label class="col-md-12 control-label text-left">PAX Information</label> </div> <div class="row"> <div class="col-md-2"> <input id="search_first_name" class="form-control additional-conditions" placeholder="First Name" maxlength="40" name="search_first_name" type="text" value="<?=$search_report_condition->first_name ?>"> </div> <div class="col-md-2"> <input id="search_last_name" class="form-control additional-conditions" placeholder="Last Name" maxlength="40" name="search_last_name" type="text" value="<?=$search_report_condition->last_name ?>"> </div> <div class="col-md-2"> <input id="search_record_locator" class="form-control additional-conditions" placeholder="PNR" maxlength="7" name="search_record_locator" type="text" value="<?=$search_report_condition->record_locator ?>"> </div> </div> </div> <div class="col-md-12"><h3></h3></div> <div class="col-md-12"> <button type="button" class="btn btn-lgray center-block" onclick="exec(this.form, '/p/chirp/top/search')">&nbsp;&nbsp;Search&nbsp;&nbsp;</button> </div> <div class="col-md-12"><h2></h2></div> </div> <div class="row"> <div class="col-md-12"><p></p></div> <div class="col-md-12"><p></p></div> </div> <div class="row row-margin-bottom-80"> <div class="col-md-12"> <table id="searchReportTable" class="table table-bordered table-hover" border="1" cellpadding="2" bordercolor="#000000"> <thead> <tr class="gray"> <th>Report Status</th> <th>Reporting Date</th> <th>Report No</th> <th>Report Title</th> <th>Flight No</th> <th>Inquiry Status</th> <th>Preview</th> </tr> </thead> <tbody> <?php foreach($search_report_list as $data): ?> <tr> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->report_status_name) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->reporting_date) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->report_no) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->report_title) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->flight_number) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><?= HTML::entities($data->inquiry_status) ?></td> <td><button type="button" class="btn btn-lgray center-block btn-xs" onclick="selectPreview(document.forms.mainForm, '/p/chirp/top/preview', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>', '<?= HTML::entities($data->report_status) ?>')"><span id="PreviewIcon" class="glyphicon glyphicon-zoom-in"></span></button></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </form> </div><!-- container --> </body> </html><file_sep>/app/config/const.php <?php return[ // ldap認証 'ldap_host_1' => '10.1.144.11', 'ldap_port_1' => '389', 'ldap_host_2' => '10.1.144.12', 'ldap_port_2' => '389', 'ldap_server_count' => 2, 'ldap_domain' => 'apj\\', // 送信元メール 'from_emal' => '<EMAIL>', 'from_emal_name' => 'Chirp', // トップ画面の最新レポート表示部 'topViews' => [ 'PEACOCK' => 'parts.top.new_report_peacock', 'PENGUIN' => 'parts.top.new_report_penguin', 'PEREGRINE' => 'parts.top.new_report_peregrine' ], // レポート画面の個別部 'reportViews' => [ '1' => 'parts.report.report_penguin', '2' => 'parts.report.report_peregrine', '3' => 'parts.report.report_peregrine', '4' => 'parts.report.report_peacock' ], // プレビュー画面の個別部 'previewViews' => [ '1' => 'parts.preview.preview_penguin', '2' => 'parts.preview.preview_peregrine', '3' => 'parts.preview.preview_peregrine', '4' => 'parts.preview.preview_peacock' ], // トップ画面コントローラ 'topControllers' => [ 'PEACOCK' => 'TopControllerPEACOCK', 'PENGUIN' => 'TopControllerPENGUIN', 'PEREGRINE' => 'TopControllerPEREGRINE' ], // レポート画面コントローラ 'reportControllers' => [ 'PEACOCK' => 'ReportControllerPEACOCK', 'PENGUIN' => 'ReportControllerPENGUIN', 'PEREGRINE' => 'ReportControllerPEREGRINE' ], // プレビュー画面コントローラ 'previewControllers' => [ 'PEACOCK' => 'PreviewControllerPEACOCK', 'PENGUIN' => 'PreviewControllerPENGUIN', 'PEREGRINE' => 'PreviewControllerPEREGRINE' ], // レポート種別 'REPORT_CLASS_LIST' => [ 'PENGUIN' => [ ['code' => 1, 'value' => 'New Item'] ], 'PEREGRINE' => [ ['code' => 2, 'value' => 'New Item'], ['code' => 3, 'value' => 'New Item'] ], 'PEACOCK' => [ ['code' => 4, 'value' => 'New Item'] ] ], // レポート種別 'REPORT_CLASS' => [ 'PENGUIN' => 1, 'PEREGRINE_Incident' => 3, 'PEREGRINE_Irregularity' => 2, 'PEACOCK' => 4, ], // レポート種別名 'REPORT_CLASS_NAME' => [ 1 => 'PENGUIN', 3 => 'PEREGRINE_Incident', 2 => 'PEREGRINE_Irregularity', 4 => 'PEACOCK', ], // レポート種別名 'REPORT_CLASS_BASIC_NAME' => [ 1 => 'PENGUIN', 2 => 'PEREGRINE', 3 => 'PEREGRINE', 4 => 'PEACOCK', ], // レポートコード名 'REPORT_CLASS_BASIC_CODE' => [ 'PENGUIN' => 1, 'PEREGRINE' => 2, 'PEREGRINE' => 3, 'PEACOCK' => 4, ], // レポートステータス 'REPORT_STATUS' => [ 'CREATED' => 0, 'SUBMITTED' => 1, 'CONFIRMED' => 2, 'CLOSE' => 3, 'PASSBACK_SUBMITTED' => 4, 'RESUBMIT' => 5, 'PASSBACK_CONFIRMED' => 6, 'RECONFIRM' => 7 ], // 照会ステータス 'INQUIRY_STATUS' => [ 'INQUIRY' => 1, 'ANSWER' => 2, 'ANSWER_READ' => 3, ], // 変更画面判定 'EDIT_MODE_OF_STATUS' => [ 0 => 'edit', 1 => 'confirm', 2 => 'close', 3 => 'edit', 4 => 'edit', 5 => 'confirm', 6 => 'confirm', 7 => 'close' ], // ユーザー権限 'USER_ROLE' => [ 'REPORTER' => 0, 'MANAGER' => 1, 'APPROVER' => 2, 'ALL' => 99 ], // メール区分 'MAIL_KBN' => [ 'Submit' => 1, 'Confirm' => 2, 'Close' => 3, 'Passback' => 4, 'InquirySave' => 5, 'AnswerToInquiry' => 6, 'AlertCreated' => 7, 'AlertUpdated' => 8, ], 'REPORT_MODE_NAME' => [ 'reference' => 'レポート参照画面', 'edit' => 'レポート変更画面', 'confirm' => 'レポート確認画面', 'close' => 'レポート承認画面', 'inquiry' => 'レポート照会画面', 'answer' => 'レポート回答画面', 'other' => 'レポート参照(他部門)画面', 'relation' => 'レポート参照(関連)画面' ], 'ALERT_MAIL_TIMING' => [ 'CREATED' => 1, 'CREATED_AND_UPDATED' => 2 ] ];<file_sep>/app/extentions/CommonGateway/MailManager.php <?php namespace CommonGateway { use DB; use Mail; use Config; use Log; use Swift_Mailer; use Swift_SmtpTransport; use Swift_Message; use Exception; class MailManager { /** * コンストラクタ */ function __construct() { } /** * メール送信 * @param $report_no * @param $report_name * @param $user_role * @param $mail_kbn * @param $replace_array [key,value](keyをvalueへ置換) * @return boolean */ function send($report_no, $report_name, $user_role, $mail_kbn, $replace_array){ // レポート情報取得 $sqlString = 'SELECT t1.email, t2.title, t2.body ' .'FROM mst_mail_manage t1 ' .'inner join mst_mail_contents t2 ' .'on t1.report_name = t2.report_name and t1.user_role = t2.user_role ' .'WHERE t1.report_name = ? and t1.user_role = ? and t2.mail_kbn = ? '; $result = DB::selectOne( $sqlString, [Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_name], $user_role, $mail_kbn] ); if($result == null){ return false; } // 送信元メールアドレス $mail_from = Config::get('const.from_emal'); $mail_from_name = Config::get('const.from_emal_name'); // 送信先メールアドレス $mail_to = $result->email; // 起票者宛の場合はメール送信先をユーザー情報から取得 if ($user_role == Config::get('const.USER_ROLE.REPORTER')) { // レポート情報取得 $sqlString = 'SELECT t2.email as rep_email ' .'FROM report_basic_info t1 ' .'inner join mst_user_info t2 ' .'on t1.create_user_id = t2.login_id ' .'WHERE t1.report_no = ?'; $result2 = DB::selectOne( $sqlString, [$report_no] ); if($result2 == null){ return false; } $mail_to = $result2->rep_email ; } $mail_to_name = '';//名称未定 // タイトル・本文の文字置換 $mail_title = $result->title; $mail_body = $result->body; foreach($replace_array as $key => $value){ $pattern = '/'.$key.'/'; $replacement = $value; $mail_title = preg_replace($pattern, $replacement, $mail_title); $mail_body = preg_replace($pattern, $replacement, $mail_body); } // メール内容 $mail_content = [ 'mail_from' => $mail_from, 'mail_from_name' => $mail_from_name, 'mail_to' => explode(',',$mail_to), // 'mail_to' => "$mail_to", 'mail_to_name' => $mail_to_name, 'mail_subject' => $mail_title, ]; try{ // メール送信 $send_result = Mail::send( ['text' => 'emails.empty'], ['mail_body' => $mail_body], function($e) use ($mail_content) { $e->to($mail_content['mail_to']) // $e->to($mail_content['mail_to'], $mail_content['mail_to_name']) ->from($mail_content['mail_from'], $mail_content['mail_from_name']) ->subject($mail_content['mail_subject']); } ); }catch(Exception $e){ // サーバ接続エラー時(予備サーバへ再送信) $send_result = $this->reserveSend($mail_content, $mail_body); } return $send_result; } /** * メール送信(予備) * @param unknown $mail_content * @param unknown $mail_body */ function reserveSend($mail_content, $mail_body, $address_method = 'setTo'){ // メール設定 // $transport = Swift_SmtpTransport::newInstance('smtp.sendgrid.net', 587, 'tls') $transport = Swift_SmtpTransport::newInstance(Config::get('mail2.host'), Config::get('mail2.port'), Config::get('mail2.encryption')) ->setUsername(Config::get('mail2.username')) ->setPassword(Config::get('mail2.password')); $mailer = Swift_Mailer::newInstance($transport); // メッセージ作成 $message = Swift_Message::newInstance() ->setSubject($mail_content['mail_subject']) ->$address_method($mail_content['mail_to']) ->setFrom($mail_content['mail_from'], $mail_content['mail_from_name']) ->setBody($mail_body); // メール送信 // $message->toString(); $send_result = $mailer->send($message); } /** * アラートメール送信 * @param unknown $user_list * @param unknown $report_name * @param unknown $mail_kbn */ function alertMail($user_list, $mail_kbn, $replace_array) { // 宛先メールアドレス取得 $user_result = DB::table('mst_user_info') ->distinct() ->select(['report_name', 'email']) ->whereIn('login_id', $user_list) ->get(); $mail_group = array(); foreach($user_result as $user) { $mail_group[$user->report_name][] = $user->email; } // 送信先の部署ことにメールを送信 foreach($mail_group as $report_name => $mail_to) { // メールの内容を取得 $mail_content_result = DB::table('mst_mail_contents') ->select(['title', 'body']) ->where('report_name', $report_name) ->where('mail_kbn', $mail_kbn) ->where('user_role', Config::get('const.USER_ROLE.ALL')) ->first(); // タイトル・本文の文字置換 $mail_title = $mail_content_result->title; $mail_body = $mail_content_result->body; foreach($replace_array as $key => $value){ $pattern = '/'.$key.'/'; $replacement = $value; $mail_title = preg_replace($pattern, $replacement, $mail_title); $mail_body = preg_replace($pattern, $replacement, $mail_body); } // 送信元メールアドレス $mail_from = Config::get('const.from_emal'); $mail_from_name = Config::get('const.from_emal_name'); // メール内容 $mail_content = [ 'mail_from' => $mail_from, 'mail_from_name' => $mail_from_name, 'mail_to' => $mail_to, 'mail_subject' => $mail_title, ]; try{ // メール送信 $send_result = Mail::send( ['text' => 'emails.empty'], ['mail_body' => $mail_body], function($e) use ($mail_content) { $e->bcc($mail_content['mail_to']) ->from($mail_content['mail_from'], $mail_content['mail_from_name']) ->subject($mail_content['mail_subject']); } ); }catch(Exception $e){ // サーバ接続エラー時(予備サーバへ再送信) $send_result = $this->reserveSend($mail_content, $mail_body, 'setBcc'); } } return $send_result; } } }<file_sep>/app/views/parts/report/report_peregrine.php <script> var riskLevel = { 'Insignificant' : { '1':'Level A', '2':'Level A', '3':'Level A', '4':'Level B' }, 'Minor' : { '1':'Level A', '2':'Level B', '3':'Level B', '4':'Level C' }, 'Moderate' : { '1':'Level A', '2':'Level C', '3':'Level D', '4':'Level D' }, 'Major' : { '1':'Level B', '2':'Level D', '3':'Level D', '4':'Level D' }, }; var dayOfWeek = ['SUN','MON','TUE','WED','THU','FRI','SAT']; function calculateRisk(){ var result = '' var influence_on_safety = $('#influence_on_safety').val(); var frequency = $('#frequency').val(); if(influence_on_safety != '' && frequency != ''){ var risk = riskLevel[influence_on_safety][frequency]; if(typeof risk !== "undefined"){ result = risk; } } $('#assessment_level').text(result); $('#assessment').val(result); } function calculateDLATTL(){ var sum = 0; var dla_time = parseInt($('#dla_time').val()); var dla_time_2 = parseInt($('#dla_time_2').val()); var dla_time_3 = parseInt($('#dla_time_3').val()); if(dla_time != '' && !isNaN(dla_time)){ sum += dla_time; } if(dla_time_2 != '' && !isNaN(dla_time_2)){ sum += dla_time_2; } if(dla_time_3 != '' && !isNaN(dla_time_3)){ sum += dla_time_3; } $('#dla_ttl_label').text(sum); $('#dla_ttl').val(sum); } function calculateDayOfWeek(obj){ $('#day_of_week_label').text(''); $('#day_of_week').val(''); var d = new Date($(obj).val()); var result = dayOfWeek[d.getDay()]; $('#day_of_week_label').text(result); $('#day_of_week').val(result); } $(function(){ $(window).load(function () { calculateRisk(); calculateDLATTL(); calculateDayOfWeek('#reporting_date'); }); $('#reporting_date').on('change', function(){ calculateDayOfWeek(this); }); $('#influence_on_safety').on('change', function(){ calculateRisk(); }); $('#frequency').on('change', function(){ calculateRisk(); }); $('.dla_times').on('change', function(){ calculateDLATTL(); }); }); </script> <label for="report_title" class="label01">Report Title<span class="danger"> *</span><br /><span>レポート件名</span></label> <div class="label03"> <input id="report_title" name="report_title" type="text" class="inputbox" placeholder="Area/Category/Flight No" value="<?= HTML::entities(Input::old('report_title', $report_info->report_title)) ?>" maxlength="180" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="reporting_date" class="label01">Reporting Date<br /><span>報告日</span></label> <div class="label02"> <input id="reporting_date" name="reporting_date" type="text" class="inputbox datepicker" value="<?= HTML::entities(Input::old('reporting_date', $report_info->reporting_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <div class="label02"> <div class="row"> <input type="hidden" id="day_of_week" name="day_of_week" value="<?= HTML::entities($report_info->day_of_week) ?>" /> <label id="day_of_week_label" class="form-control-static text-left col-md-2"><?= HTML::entities($report_info->day_of_week) ?></label> </div> </div> <div class="clearfix"></div> <label for="area" class="label01">Area<br /><span>場所</span></label> <div class="label02"> <select id="area" name="area" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($area_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('area', $report_info->area) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <div class="clearfix"></div> <label for="category" class="label01">Category<br /><span>区分</span></label> <div class="label02"> <select id="category" name="category" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($category_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('category', $report_info->category) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <div class="clearfix"></div> <label for="contents" class="label01">Contents<br /><span>報告内容</span></label> <div class="label04"> <textarea name="contents" id="contents" cols="100" rows="10" class="inputbox03 no-resize-horizontal-textarea" maxlength="1500" <?= HTML::entities($role_manage_info->other_input_disabled) ?>><?= HTML::entities(Input::old('contents', $report_info->contents)) ?></textarea> </div> <label for="factor" class="label01">Factor<br /><span>要因</span></label> <div class="label02"> <select id="factor" name="factor" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($factor_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('factor', $report_info->factor) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <div class="clearfix"></div> <label for="staff_comment" class="label01">Measures to Prevent Recurrence<br /><span>再発防止策</span></label> <div class="label04"> <textarea name="measures_to_revent_recurrence" id="measures_to_revent_recurrence" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('measures_to_revent_recurrence', $report_info->measures_to_revent_recurrence)) ?></textarea> </div> <label for="staff_comment" class="label01">Staff Comment<br /><span>担当者記入欄</span></label> <div class="label04"> <textarea name="staff_comment" id="staff_comment" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" maxlength="1500" <?= HTML::entities($role_manage_info->other_input_disabled) ?>><?= HTML::entities(Input::old('staff_comment', $report_info->staff_comment)) ?></textarea> </div> <label for="approve_comment" class="label01">Approver Comment<br /><span>承認者記入欄</span></label> <div class="label04"> <textarea name="approve_comment" id="approve_comment" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('approve_comment', $report_info->approve_comment)) ?></textarea> </div> <div class="clearfix"></div> <label class="label01_2">Risk Assessment<br /><span>リスク評価<br>※リスク評価員記入欄<br>For risk assessment member only</span></label> <label for="influence_on_safety" class="label05">Influence on Safety<br /><span>安全への影響度</span></label> <div class="label05_2"> <select id="influence_on_safety" name="influence_on_safety" class="inputbox" style="color: #000;" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($influence_on_safety_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('influence_on_safety', $report_info->influence_on_safety) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="frequency" class="label05">Frequency<br /><span>発生頻度</span></label> <div class="label05_2"> <select id="frequency" name="frequency" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($frequency_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('frequency', $report_info->frequency) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <div class="row"> <input type="hidden" id="assessment" name="assessment" value="<?= HTML::entities($report_info->assessment) ?>" /> <label id="assessment_label" class="label05">Assessment<br /><span>評価</span></label> <label id="assessment_level" class="label05"><?= HTML::entities($report_info->assessment) ?></label> </div> <file_sep>/app/controllers/PreviewControllerPENGUIN.php <?php /** * * プレビュー画面(PENGUIN) * */ class PreviewControllerPENGUIN extends PreviewController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see PreviewController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_PREVIEW_PENGUIN'),['1','1', 'Sub Category' ,$report_no, '1']); } } <file_sep>/app/views/emails/empty.php <?= $mail_body ?> <file_sep>/app/views/parts/report/report_peacock.php <label for="report_title" class="label01">Report Title<span class="danger"> *</span><br /><span>レポート件名</span></label> <div class="label03"> <input id="report_title" name="report_title" type="text" class="inputbox" value="<?= HTML::entities(Input::old('report_title', $report_info->report_title)) ?>" maxlength="180" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="reporting_date" class="label01">Reporting Date<br /><span>事象発生日</span></label> <label id="reporting_date" class="label02"><?= HTML::entities($report_info->reporting_date) ?></label> <div class="clearfix"></div> <div id="category"></div> <label for="contents" class="label01">Contents<br /><span>内容</span></label> <div class="label04"> <textarea name="contents" id="contents" cols="100" rows="10" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('contents', $report_info->contents)) ?></textarea> </div> <label for="staff_comment" class="label01">Staff Comment<br /><span>スタッフ補記</span></label> <div class="label04"> <textarea name="staff_comment" id="staff_comment" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" ><?= HTML::entities(Input::old('staff_comment', $report_info->staff_comment)) ?></textarea> </div> <file_sep>/app/controllers/TopControllerPENGUIN.php <?php /** * トップ画面(PENGUIN) */ class TopControllerPENGUIN extends TopController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * 照会レポート取得処理 * @see TopController::getInquiryReport() */ protected function getInquiryReport(){ return DB::select( Config::get('sql.SELECT_INQUIRY_REPORT_PENGUIN'), [ Config::get('const.INQUIRY_STATUS.INQUIRY'), '1' ] ); } /** * 最新レポート取得処理 * @see TopController::getNewReport() */ protected function getNewReport(){ $result = DB::select( Config::get('sql.SELECT_NEW_REPORT_PENGUIN'), [ Config::get('const.REPORT_CLASS.PENGUIN'), // PENGUINのみ Config::get('const.REPORT_STATUS.CLOSE'), // 承認済以外 '1' ] ); return $result; } } <file_sep>/app/views/alert.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp <?= HTML::entities($header_title) ?></title> <?= HTML::style('resources/bootstrap/css/bootstrap.min.css') ?> <?= HTML::style('resources/css/jquery-ui.min.css') ?> <?= HTML::style('resources/css/awesome-bootstrap-checkbox.css') ?> <?= HTML::style('resources/bower_components/Font-Awesome/css/font-awesome.css') ?> <?= HTML::style('resources/css/pnotify.custom.min.css') ?> <?= HTML::style('resources/css/extends-bootstrap.css') ?> <?= HTML::style('resources/css/common.css') ?> <?= HTML::style('resources/css/style.css') ?> <?= HTML::style('resources/css/new_style.css') ?> <?= HTML::script('resources/js/jquery-1.11.2.min.js') ?> <?= HTML::script('resources/js/jquery-ui.min.js') ?> <?= HTML::script('resources/bootstrap/js/bootstrap.min.js') ?> <?= HTML::script('resources/js/bootbox.js') ?> <?= HTML::script('resources/js/jquery.blockUI.js') ?> <?= HTML::script('resources/js/pnotify.custom.min.js') ?> <?= HTML::script('resources/js/common.js') ?> <link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" rel="stylesheet" /> <script> disableBrowserBack(); function buttonClick(buttonType) { var $_html; var $_message; var $report_class = $("#_report_class").val(); switch(buttonType){ case "cancel": $_message = "アラート条件の編集を破棄します。よろしいですか?\n" + "Are you sure you want to discard the editing of alert condition?"; break; case "save": $_message = "アラート条件を保存します。よろしいですか?\n" + "Are you sure you want to save the alert condition?"; break; default: $_message = ""; } var $confirm = true; $_html = "/p/chirp/alert/" + buttonType; if ($_message != "") { $confirm = confirm($_message); } if ($confirm) { $('#mainForm').attr('action', $_html) .submit(); } } $(function(){ $(window).load(function () { $('#formClear').click(function() { $('input[type="radio"]').removeAttr('checked'); $('input[type="checkbox"]').removeAttr('checked'); }); }); }); </script> </head> <!-- アラート設定画面 PEREGRINE --> <body> <?= $parts_common_header ?> <div class="container-fluid"> <form id="mainForm" action="" method="post" enctype="multipart/form-data"> <!-- エラーメッセージ表示エリア --> <?= $parts_common_error ?> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-2 pull-left text-left"> <label class="text-left" style="font-size:150%;" ><strong>Alert Condition</strong></label><br><span style="margin-bottom: 5px">通知条件</span> </div> <div class="col-md-1"> <button type="button" class="btn btn-xs btn-lgray clear-condition pull-left" id="formClear">Clear</button> </div> </div> </div> <div class="alert_area form-horizontal"> <div class="form-group"> <div class="col-md-2 text-left"> <label class="control-label" style="margin-bottom: 5px">Alert on</label><br><span>通知設定</span> </div> <div class="row col-md-9 text-left"> <div class="radio" style="margin-left: 15px;"> <input type="radio" name="timing" value="1" id="created" <?php if(Input::old('timing', $alert_setting['timing']) == '1'): ?>checked="checked"<?php endif; ?>> <label for="created">created</label><br><span style="margin-top: 5px;margin-left: 5px">新規作成時</span> </div> <div class="radio" style="margin-left: 15px;"> <input type="radio" name="timing" value="2" id="created_and_updated" <?php if(Input::old('timing', $alert_setting['timing']) == '2'): ?>checked="checked"<?php endif; ?>> <label for="created_and_updated">created and updated</label><br><span style="margin-top: 5px;margin-left: 5px">新規作成時と更新時</span> </div> </div> </div> </div> <div id="station_area" class="form-horizontal"> <div class="form-group"> <div class="col-md-2 text-left"> <label class="control-label" style="margin-bottom: 5px">Station</label><br><span>空港名</span> </div> <div class="row col-md-9 text-left"> <?php $input_station = (array)Input::old('station', $alert_setting['station']); ?> <?php foreach($station_list as $station): ?> <div class="col-md-3"> <div class="checkbox checkbox-inline"> <input id="station_<?= HTML::entities($station->code2) ?>" name="station[]" type="checkbox" value="<?= HTML::entities($station->code2) ?>" <?php if(in_array($station->code2, $input_station)): ?>checked="checked"<?php endif; ?>> <label for="station_<?= HTML::entities($station->code2) ?>"></label> </div> <?= HTML::entities($station->value2) ?> </div> <?php endforeach; ?> </div> </div> </div> <div class="row row-margin-top-80"> <div class="form-group"> <div class="col-md-1"></div> <div class="col-md-10"> <button type="button" class="btn btn-pink" onclick="buttonClick('cancel')">&nbsp;Cancel&nbsp;</button> <button type="button" class="btn btn-pink col-md-offset-1" onclick="buttonClick('save')">&nbsp;&nbsp;Apply&nbsp;&nbsp;</button> </div> </div> </div> </form> </div> </body> </html><file_sep>/app/views/parts/report/attached_file_area.php <label class="label01">Attachments<br /><span>添付ファイル</span></label> <div class="label04 <?= HTML::entities($role_manage_info->add_attach_file_button_hidden) ?>"> <input type="file" id="attach_file_1" name="attach_file_1" data-attach-file-index="1" class="attache-file" style="display: none;"> <button type="button" class="btn btn-lgray btn-xs add-attachfile" onclick="$('#attach_file_1').click();"> Select </button> <label id="dummy_file_1" class="control-label <?= HTML::entities($role_manage_info->add_attach_file_button_hidden) ?>" style="padding-left:10px;">ファイル未選択</label> <button type="button" class="btn btn-lgray btn-xs pull-right attache-file-clear" data-attach-file-index="1"> <strong>×</strong> </button> <div class="clearfix"></div> </div> <div class="label04"> <div class="<?= HTML::entities($role_manage_info->add_attach_file_button_hidden) ?>"> <button type="button" class="btn btn-lgray btn-xs" data-toggle="collapse" data-target="#collapseAttachFile" > <span id="attachFileIcon" class="glyphicon glyphicon-plus"></span> Attach File </button> <div id="collapseAttachFile" class="collapse <?= HTML::entities($role_manage_info->add_attach_file_button_hidden) ?>"> <?php for($index = 2; $index <= 5;$index++) { ?> <input type="file" id="attach_file_<?php echo $index ?>" name="attach_file_<?php echo $index ?>" data-attach-file-index="<?php echo $index ?>" class="attache-file additional-attach-file" style="display: none;"> <button type="button" class="btn btn-lgray btn-xs add-attachfile" onclick="$('#attach_file_<?php echo $index ?>').click();"> Select </button> <label id="dummy_file_<?php echo $index ?>" class="control-label additional-attach-file-label" style="padding-left:10px;">ファイル未選択</label> <button type="button" class="btn btn-lgray btn-xs pull-right attache-file-clear" data-attach-file-index="<?php echo $index ?>"> <strong>×</strong> </button> <div class="clearfix"></div> <?php } ?> </div> </div> <input type="hidden" id="attache_file_count" name="attache_file_count" value="<?php echo count($attach_file_list) ?>"/> <ul id="attache_file_list"> <?php foreach($attach_file_list as $index => $data) { ?> <li class="attache_file"> <a href="javascript:void(0)" onclick="downloadFile(document.forms.mainForm, '/p/chirp/report/download', <?= HTML::entities($data->file_seq) ?>);" ><?= HTML::entities($data->file_name) ?></a> <button type="button" class="btn btn-lgray btn-xs pull-right attache-file-delete <?= HTML::entities($role_manage_info->delete_attach_file_button_hidden) ?>" data-attach-file-index="<?= HTML::entities($index + 1) ?>" data-attach-file-seq="<?= HTML::entities($data->file_seq) ?>"> <strong>×</strong> </button> <input type="hidden" id="delete_file_<?= HTML::entities($index + 1) ?>" name="delete_file_<?= HTML::entities($index + 1) ?>" value=""/> </li> <?php } ?> </ul> </div> <div class="clearfix"></div> <file_sep>/app/views/login.php <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta http-equiv="Content-Language" content="ja" /> <meta http-equiv="content-script-type" content="text/javascript" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title>Chirp - Login</title> <?= HTML::style('resources/bootstrap/css/bootstrap.min.css') ?> <?= HTML::style('resources/css/jquery-ui.min.css') ?> <?= HTML::style('resources/css/awesome-bootstrap-checkbox.css') ?> <?= HTML::style('resources/bower_components/Font-Awesome/css/font-awesome.css') ?> <?= HTML::style('resources/css/pnotify.custom.min.css') ?> <?= HTML::style('resources/css/extends-bootstrap.css') ?> <?= HTML::style('resources/css/common.css') ?> <?= HTML::style('resources/css/style.css') ?> <?= HTML::script('resources/js/jquery-1.11.2.min.js') ?> <?= HTML::script('resources/js/jquery-ui.min.js') ?> <?= HTML::script('resources/bootstrap/js/bootstrap.min.js') ?> <?= HTML::script('resources/js/bootbox.js') ?> <?= HTML::script('resources/js/jquery.blockUI.js') ?> <?= HTML::script('resources/js/pnotify.custom.min.js') ?> <?= HTML::script('resources/js/common.js') ?> </head> <!-- ログイン画面 --> <body> <?= $parts_common_header ?> <div class="container-fluid"> <form id="loginForm" action="/login/login" method="post" style="margin-top: 40px;"> <?= $parts_common_error ?> <div class="row"> <div class="form-group col-md-10 col-md-offset-2"> <label for="login_id" class="col-md-3 control-label text-right">User Name</label> <div class="col col-md-4"> <input type="text" name="login_id" id="login_id" class="form-control" maxlength="8"> </div> </div> <div class="form-group col-md-10 col-md-offset-2"> <label for="password" class="col-md-3 control-label text-right">Password</label> <div class="col col-md-4"> <input type="<PASSWORD>" name="password" id="password" class="form-control"> </div> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <button id="loginButton" type="submit" class="btn navbar-btn btn-pink">Log in</button> </div> </div> </form> </div><!-- container --> </body> </html><file_sep>/app/views/parts/report/flight_info_peregrine.php <label for="Flight_Date" class="label01">Flight Date<br /><span>フライト日</span></label> <div class="label02"> <input type="text" id="departure_date" name="departure_date" class="inputbox datepicker" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('departure_date',$report_info->departure_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="Flight_No" class="label01">Flight No<br /><span>便名 ※MMXXXX(ex. MM0001)</span></label> <div class="label02"> <input type="text" id="flight_number" name="flight_number" class="inputbox" placeholder="MMXXXX(ex. MM0001)" value="<?= HTML::entities(Input::old('flight_number', $report_info->flight_number)) ?>" maxlength="6" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="Ship_No" class="label01">Ship No<br /><span>機番</span></label> <div class="label02"> <select id="ship_no" name="ship_no" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($ship_no_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('ship_no', $report_info->ship_no) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="Sector" class="label01">Sector<br /><span>区間</span></label> <div class="label02"> <select id="origin_rcd" name="origin_rcd" class="inputbox02" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($sector_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('origin_rcd', $report_info->origin_rcd) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> <p class="form-control-static">→</p> <select id="destination_rcd" name="destination_rcd" class="inputbox02" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($sector_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('destination_rcd', $report_info->destination_rcd) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="etd" class="label01">STD<br /><span>出発時間</span></label> <div class="label02"> <input id="std" name="std" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('std', $report_info->std)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <label for="sta" class="label01">STA<br /><span>到着時間</span></label> <div class="label02"> <input id="sta" name="sta" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('sta', $report_info->sta)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="etd" class="label01">ETD<br /><span>出発予定時間</span></label> <div class="label02"> <input id="etd" name="etd" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('etd', $report_info->etd)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?> /> </div> <label for="eta" class="label01">ETA<br /><span>到着予定時間</span></label> <div class="label02"> <input id="eta" name="eta" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('eta', $report_info->eta)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="atd" class="label01">ATD<br /><span>実出発時間</span></label> <div class="label02"> <input id="atd" name="atd" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('atd', $report_info->atd)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="ata" class="label01">ATA<br /><span>実到着時間</span></label> <div class="label02"> <input id="ata" name="ata" type="text" class="inputbox" placeholder="HHMM(ex. 0700)" value="<?= HTML::entities(Input::old('ata', $report_info->ata)) ?>" maxlength="4" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="dla_code" class="label01">#1 DLA Code<br /><span>遅延コード1</span></label> <div class="label02"> <select id="dla_code" name="dla_code" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($dla_code_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('dla_code', $report_info->dla_code) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="dla_time" class="label01">#1 DLA Time<br /><span>遅延時間1</span></label> <div class="label02"> <input id="dla_time" name="dla_time" type="text" class="inputbox02 dla_times" value="<?= HTML::entities(Input::old('dla_time', $report_info->dla_time)) ?>" style="text-align: right;" maxlength="3" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <p class="text">min</p> </div> <label for="dla_code_2" class="label01">#2 DLA Code<br /><span>遅延コード2</span></label> <div class="label02"> <select id="dla_code_2" name="dla_code_2" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($dla_code_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('dla_code_2', $report_info->dla_code_2) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="dla_time_2" class="label01">#2 DLA Time<br /><span>遅延時間2</span></label> <div class="label02"> <input id="dla_time_2" name="dla_time_2" type="text" class="inputbox02 dla_times" value="<?= HTML::entities(Input::old('dla_time_2', $report_info->dla_time_2)) ?>" style="text-align: right;" maxlength="3" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <p class="text">min</p> </div> <label for="dla_code_3" class="label01">#3 DLA Code<br /><span>遅延コード3</span></label> <div class="label02"> <select id="dla_code_3" name="dla_code_3" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($dla_code_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('dla_code_3', $report_info->dla_code_3) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="dla_time_3" class="label01">#3 DLA Time<br /><span>遅延時間3</span></label> <div class="label02"> <input id="dla_time_3" name="dla_time_3" type="text" class="inputbox02 dla_times" value="<?= HTML::entities(Input::old('dla_time_3', $report_info->dla_time_3)) ?>" style="text-align: right;" maxlength="3" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <p class="text">min</p> </div> <label for="gate_spot" class="label01">Gate(Spot)<br /><span>ゲート(スポット)</span></label> <div class="label02"> <input id="gate_spot" name="gate_spot" type="text" class="inputbox" value="<?= HTML::entities(Input::old('gate_spot', $report_info->gate_spot)) ?>" maxlength="8" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="dla_ttl" class="label01">DLA TTL<br /><span>遅延合計時間</span></label> <div class="label02"> <input id="dla_ttl" name="dla_ttl" type="hidden" class="inputbox" value="<?= HTML::entities($report_info->dla_ttl) ?>" maxlength="3"/> <label id="dla_ttl_label" class="control-label"><?= HTML::entities($report_info->dla_ttl) ?></label> <p class="text">min</p> </div> <label for="pax_in" class="label01">PAX IN<br /><span>到着旅客数</span></label> <div class="label02"> <input id="pax_in" name="pax_in" type="text" class="inputbox" value="<?= HTML::entities(Input::old('pax_in', $report_info->pax_in)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="pax_out" class="label01">PAX OUT<br /><span>出発旅客数</span></label> <div class="label02"> <input id="pax_out" name="pax_out" type="text" class="inputbox" value="<?= HTML::entities(Input::old('pax_out', $report_info->pax_out)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php if($report_info->report_class == 3) {?> <label for="weather" class="label01">Weather<br /><span>天候</span></label> <div class="label02"> <select id="weather" name="weather" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($weather_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('weather', $report_info->weather) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <?php } ?> <file_sep>/app/extentions/CommonGateway/DataManager.php <?php namespace CommonGateway { use DB; use Log; use Config; use DateUtil; use PDOException; use CommonCheckLogic; use Input; use App; use Session; class DataManager { /** * コンストラクタ */ function __construct() { } /** * データ登録 * @param unknown $sql * @param unknown $data * @throws PDOException * @return boolean */ function insertWithCheckDuplicate($sql, $data){ try{ // レポート基本情報登録 $count = DB::insert( $sql, $data ); return false; }catch(PDOException $e){ // キー重複 if($e->getCode() === '23000'){ return true; } throw $e; } return false; } /** * ユーザー情報取得 */ function getUserInfo($login_id){ $result = DB::selectOne( Config::get('sql.SELECT_USER_INFO'), [$login_id] ); return $result; } /** * 添付ファイル登録 * @param string $report_no レポート番号 * @param datetime $create_timestamp 日時 */ function saveAttachFile($report_no, $create_timestamp){ for($i = 1; $i <= 5; $i++){ $attach_file = Input::file('attach_file_' . $i); if($attach_file){ $data = [ $report_no, $attach_file->getClientOriginalName(), file_get_contents($attach_file->getRealPath()), $create_timestamp, $report_no ]; DB::insert(Config::get('sql.INSERT_REPORT_ATTACHE_FILE'), $data); } } } /** * 添付ファイル削除 * @param string $report_no レポート番号 */ function deleteAttachFile($report_no){ $count = Input::get('attache_file_count'); for($i = 1; $i <= $count; $i++){ $file_seq = Input::get('delete_file_' . $i); if($file_seq){ DB::delete(Config::get('sql.DELETE_REPORT_ATTACHE_FILE'), [$report_no, $file_seq]); } } } /** * 選択カテゴリ情報取得 * @param string $report_no レポート番号 */ function getSelectCategoryInfo($report_no){ return DB::select(Config::get('sql.SELECT_SELECT_CATEGORY_INFO'), [$report_no]); } /** * 選択カテゴリ情報削除 * @param string $report_no レポート番号 */ function deleteSelectCategoryInfo($report_no){ DB::delete(Config::get('sql.DELETE_SELECT_CATEGORY_INFO'), [$report_no]); } /** * 選択カテゴリ情報登録 * @param string $report_no レポート番号 * @param int $report_type レポート種別 */ function saveSelectCategoryInfo($report_no, $report_type){ $count = Input::get('category_list_count'); for($i = 1; $i <= $count; $i++){ $category = Input::get('category_' . $i); if($category){ $data = [ $report_no, $report_type, $category ]; DB::insert(Config::get('sql.INSERT_SELECT_CATEGORY_INFO'), $data); } } } /** * コメント連番採番 * @param string $report_no * @return コメント連番 */ function createCommentSeq($report_no){ return DB::selectOne(Config::get('sql.SELECT_MAX_COMMENT_SEQ'),[$report_no])->comment_seq; } /** * ファイル連番採番 * @param string $report_no * @return ファイル連番 */ function createFileSeq($report_no){ return DB::selectOne(Config::get('sql.SELECT_MAX_FILE_SEQ'), [$report_no])->file_seq; } /** * コメント一覧取得 * @param string $report_no レポート番号 * @param int $report_seq レポート連番 */ function getCommentList($report_no){ return DB::select(Config::get('sql.SELECT_REPORT_COMMENT'),[$report_no]); } /** * レポート番号採番 */ function getReportNoAndSeq($report_class, $option, $departure_date = ''){ $reportNo = 1; $searchKey; $reportNoPrefix = ''; $businessYear = $this->getBusinessYear($departure_date); switch ($report_class){ // PENGUIN case 1: // StationがCRの場合 if($option === 'CR'){ $searchKey = 'HQ' . $option . $businessYear . '-%'; $reportNoPrefix = 'HQ' . $option; // TYO, FUKの場合 }else{ $searchKey = 'C' . $option . $businessYear . '-%'; $reportNoPrefix = 'C' . $option; } break; // PEREGRINE Irregularity case 2: $searchKey = 'R' . $option . $businessYear . '-%'; $reportNoPrefix = 'R' . $option; break; // PEREGRINE Incident case 3: $searchKey = 'N' . $option . $businessYear . '-%'; $reportNoPrefix = 'N' . $option; break; // PEACOCK case 4: $searchKey = 'CA' . $option . $businessYear . '-%'; $reportNoPrefix = 'CA' . $option; break; default: throw Exception('Invalid Argument report class:' . $report_class . ' option:' . $option ); } $report_seq = DB::selectOne(Config::get('sql.SELECT_MAX_REPORT_SEQ'),[$searchKey])->report_seq; $report_seq = $this->formatNumber($report_seq, '05'); return [$reportNoPrefix . $businessYear . '-' . $report_seq, $report_seq]; } /** * 年度取得 */ private function getBusinessYear($departure_date){ if(!empty($departure_date)) { $standard_date = $departure_date; } else { $standard_date = date("Y/m/d"); } $year = date('Y', strtotime($standard_date)); $month = date('n', strtotime($standard_date)); if($month < 4){ $year--; } return $this->formatNumber($year, '04'); } /** * 値を指定桁にフォーマットする * @param string $value 値 * @param string $lengthValue 指定桁 * @return 指定桁の値 */ private function formatNumber($value, $lengthValue){ return sprintf('%' . $lengthValue . 'd', $value); } /** * 権限管理情報取得 */ function getRoleManageinfo($mode, $user_role, $report_status){ switch($report_status) { case Config::get('const.REPORT_STATUS.PASSBACK_SUBMITTED'): $report_status = Config::get('const.REPORT_STATUS.CREATED'); break; case Config::get('const.REPORT_STATUS.RESUBMIT'): case Config::get('const.REPORT_STATUS.PASSBACK_CONFIRMED'): $report_status = Config::get('const.REPORT_STATUS.SUBMITTED'); break; case Config::get('const.REPORT_STATUS.RECONFIRM'): $report_status = Config::get('const.REPORT_STATUS.CONFIRMED'); break; } $result = DB::selectOne( "select " . 'id, ' ."case when edit_button_hidden = '1' then 'hidden-element' else '' end edit_button_hidden," ."case when cancel_button_hidden = '1' then 'hidden-element' else '' end cancel_button_hidden," ."case when save_button_hidden = '1' then 'hidden-element' else '' end save_button_hidden," ."case when submit_button_hidden = '1' then 'hidden-element' else '' end submit_button_hidden," ."case when confirm_button_hidden = '1' then 'hidden-element' else '' end confirm_button_hidden," ."case when close_button_hidden = '1' then 'hidden-element' else '' end close_button_hidden," ."case when inquiry_button_hidden = '1' then 'hidden-element' else '' end inquiry_button_hidden," ."case when inquiry_save_button_hidden = '1' then 'hidden-element' else '' end inquiry_save_button_hidden," ."case when answer_save_button_hidden = '1' then 'hidden-element' else '' end answer_save_button_hidden," ."case when passback_button_hidden = '1' then 'hidden-element' else '' end passback_button_hidden," ."case when delete_button_hidden = '1' then 'hidden-element' else '' end delete_button_hidden," ."case when comment_button_hidden = '1' then 'hidden-element' else '' end comment_button_hidden," ."case when reservation_info_button_hidden = '1' then 'hidden-element' else '' end reservation_info_button_hidden," ."case when pax_info_button_hidden = '1' then 'hidden-element' else '' end pax_info_button_hidden," ."case when add_attach_file_button_hidden = '1' then 'hidden-element' else '' end add_attach_file_button_hidden," ."case when delete_attach_file_button_hidden = '1' then 'hidden-element' else '' end delete_attach_file_button_hidden," ."case when send_mail_creator_hidden = '1' and send_mail_administrator_group_hidden = '1' and send_mail_approver_group_hidden = '1' and send_mail_inquiry_from_administrator_group_hidden = '1' and send_mail_inquiry_to_administrator_group_hidden = '1' then 'hidden-element' else '' end send_mail_area_hidden, " ."case when send_mail_creator_hidden = '1' then 'hidden-element' else '' end send_mail_creator_hidden," ."case when send_mail_administrator_group_hidden = '1' then 'hidden-element' else '' end send_mail_administrator_group_hidden," ."case when send_mail_approver_group_hidden = '1' then 'hidden-element' else '' end send_mail_approver_group_hidden," ."case when send_mail_inquiry_from_administrator_group_hidden = '1' then 'hidden-element' else '' end send_mail_inquiry_from_administrator_group_hidden," ."case when send_mail_inquiry_from_administrator_group_hidden = '1' then '' else 'checked=\"checked\"' end send_mail_inquiry_from_administrator_group_checked," ."case when send_mail_inquiry_to_administrator_group_hidden = '1' then 'hidden-element' else '' end send_mail_inquiry_to_administrator_group_hidden," ."case when remarks_disabled = '1' then 'disabled=\"disabled\"' else '' end remarks_disabled," ."case when other_input_disabled = '1' then 'disabled=\"disabled\"' else '' end other_input_disabled," ."case when comment_area_hidden = '1' then 'hidden-element' else '' end comment_area_hidden," ."case when related_report_area_hidden = '1' then 'hidden-element' else '' end related_report_area_hidden, " ."case when answer_read_hidden = '1' then 'hidden-element' else '' end answer_read_hidden, " ."case when report_alert_hidden = '1' then 'hidden-element' else '' end report_alert_hidden " ." from mst_role_manage " ."where mode = ? and user_role = ? and report_status = ?", [$mode, $user_role, $report_status] ); return $result; } /** * 操作履歴登録 * * @param string $loginId ログインID * @param string $screenName 画面名 * @param string $action アクション * @param int $reportNo レポート番号 */ function registerOperationLog($loginId, $screenName, $action, $reportNo){ Log::info('[loginId=' . $loginId . '] - [screenName=' . $screenName . '] - [action=' . $action . '] - [reportNo=' . $reportNo . ']'); DB::insert( 'insert into operation_history (operation_timestamp,login_id,screen_name,action,report_no) ' .' values(?,?,?,?,?)', [ DateUtil::getCurrentTimestamp(), $loginId, $screenName, $action, $reportNo] ); } /** * ブランクをNULLに置換する * @param array $array 置換対象リスト * @return 置換済リスト: */ function replaceEmptyToNull($array) { $result = []; foreach($array as $item) { if(trim($item) == '') { array_push($result,NULL); } else { array_push($result,$item); } } return $result; } /** * アクセス制御チェック処理 * @param $report_no レポートNO * @param $inquiry_flg 照会フラグ(on/on以外) * @return $result[stdClass] * result_code(true:OK false:エラー) * error_message(エラーメッセージ) * otherdept_mode(他部門モード true:他部門 false:自部門) */ function checkAccessControl($report_no, $inquiry_flg = 'off'){ App::bind('checkAccessControlResult', 'stdClass'); $result = app('checkAccessControlResult'); // 結果クラス // 結果初期値 $result->result_code = true; $result->error_message = ''; // ユーザー情報取得 $userData = unserialize(Session::get('SESSION_KEY_CHIRP_USER')); // レポート情報取得 $sqlString = 'SELECT report_class, peacock_inquiry_status, penguin_inquiry_status, peregrine_inquiry_status, own_department_only_flag, delete_flag, t2.station ' . 'FROM report_basic_info AS t1 ' . 'LEFT OUTER JOIN report_info_peregrine AS t2 ON t1.report_no = t2.report_no ' . 'WHERE t1.report_no = ? '; $checkresult = DB::selectOne( $sqlString, [$report_no] ); //レポート情報 $report_class = $checkresult->report_class; $own_flg = $checkresult->own_department_only_flag; $del_fig = $checkresult->delete_flag; $report_name = $userData->userInfo->report_name; $inquiry_status = ''; if('PEACOCK' === $report_name){ $inquiry_status = $checkresult->peacock_inquiry_status; }else if('PENGUIN' === $report_name){ $inquiry_status = $checkresult->penguin_inquiry_status; }else if('PEREGRINE' === $report_name){ $inquiry_status = $checkresult->peregrine_inquiry_status; } $inquiry_mode = $inquiry_flg == 'on'; // 照会モード $otherdept_mode = Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_class] != $report_name; // 他部門モード $reporter_mode = Config::get('const.USER_ROLE.REPORTER') === intVal($userData->userInfo->user_role); // 起票者モード if($del_fig === '1'){ // 照会・リポートリンク(削除済) $result->result_code = false; $result->error_message = '選択したレポートはすでに削除されています。'; }else if($inquiry_mode){ // 照会リンク if($inquiry_status === '2'){ // 回答済 $result->result_code = false; $result->error_message = '選択したレポートはすでに回答されています。'; } }else if(!$inquiry_mode){ // レポートリンク // ログインユーザ:起票者の場合、他部門・非公開はエラー if(($reporter_mode && $otherdept_mode) || ($otherdept_mode && $own_flg === '1')){ $result->result_code = false; $result->error_message = '選択したレポートへの参照権限がありません。'; } else if ($reporter_mode && 'PEREGRINE' === $report_name) { if ($userData->userInfo->station !== $checkresult->station){ $result->result_code = false; $result->error_message = '選択したレポートへの参照権限がありません。'; } } } // 他部門モード $result->otherdept_mode = $otherdept_mode; return $result; } /** * レポート個別アラート設定判定 * @param unknown $login_id * @param unknown $report_no */ function isReportAlert($login_id, $report_no) { $cnt = DB::table('alert_mail_condition') ->where('login_id', $login_id) ->where('report_no', $report_no) ->count(); return $cnt; } } }<file_sep>/app/views/parts/report/flight_info_penguin.php <?php // PENGUINにフライト情報はありません <file_sep>/app/extentions/LdapAuth.php <?php use Illuminate\Support\Facades\Facade; class LdapAuth extends Facade { protected static function getFacadeAccessor() { return 'LdapAuth'; } }<file_sep>/app/controllers/ReportControllerPEREGRINE.php <?php /** * レポート画面(PEREGRINE) */ class ReportControllerPEREGRINE extends ReportController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see ReportController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_REPORT_INFO_PEREGRINE'),['1','1', $report_no, '1']); } /** * 空のレポート情報取得 * @see ReportController::getEmptyReportInfo() */ protected function getEmptyReportInfo($report_class){ $emptyData = new stdClass(); $emptyData->report_no = ''; $emptyData->report_seq = ''; $emptyData->report_class = $report_class; $emptyData->own_department_only_flag = ''; $emptyData->has_additional_pax_info = 0; $emptyData->has_additional_reservation_info = 0; $emptyData->report_status_name = ''; $emptyData->report_status = Config::get('const.REPORT_STATUS.CREATED'); $emptyData->day_of_week = ''; $emptyData->reported_by = ''; $emptyData->report_title = ''; $emptyData->contents = ''; $emptyData->confirmor_id = ''; $emptyData->approver_id = ''; $emptyData->peacock_inquiry_status = ''; $emptyData->peacock_inquiry_timestamp = ''; $emptyData->penguin_inquiry_status = ''; $emptyData->penguin_inquiry_timestamp = ''; $emptyData->peregrine_inquiry_status = ''; $emptyData->peregrine_inquiry_timestamp = ''; $emptyData->old_report_no = ''; $emptyData->related_report_no = ''; $emptyData->related_report_class = ''; $emptyData->related_report_no_2 = ''; $emptyData->related_report_class_2 = ''; $emptyData->firstname = ''; $emptyData->lastname = ''; $emptyData->title_rcd = ''; $emptyData->birthday = ''; $emptyData->phone_number1 = ''; $emptyData->phone_number2 = ''; $emptyData->record_locator = ''; $emptyData->firstname_2 = ''; $emptyData->lastname_2 = ''; $emptyData->title_rcd_2 = ''; $emptyData->birthday_2 = ''; $emptyData->phone_number1_2 = ''; $emptyData->phone_number2_2 = ''; $emptyData->record_locator_2 = ''; $emptyData->firstname_3 = ''; $emptyData->lastname_3 = ''; $emptyData->title_rcd_3 = ''; $emptyData->birthday_3 = ''; $emptyData->phone_number1_3 = ''; $emptyData->phone_number2_3 = ''; $emptyData->record_locator_3 = ''; $emptyData->phoenix_class = ''; $emptyData->phoenix_memo = ''; $emptyData->free_comment = ''; $emptyData->delete_flag = ''; $emptyData->create_user_id = ''; $emptyData->create_timestamp = ''; $emptyData->update_user_id = ''; $emptyData->update_timestamp = ''; $emptyData->station = $this->user->getStation(); $emptyData->department = ''; $emptyData->position = ''; $emptyData->departure_date = ''; $emptyData->flight_number = 'MM'; $emptyData->ship_no = ''; $emptyData->origin_rcd = ''; $emptyData->destination_rcd = ''; $emptyData->gate_spot = ''; $emptyData->weather = ''; $emptyData->std = ''; $emptyData->sta = ''; $emptyData->etd = ''; $emptyData->eta = ''; $emptyData->atd = ''; $emptyData->ata = ''; $emptyData->dla_code = ''; $emptyData->dla_time = ''; $emptyData->dla_code_2 = ''; $emptyData->dla_time_2 = ''; $emptyData->dla_code_3 = ''; $emptyData->dla_time_3 = ''; $emptyData->dla_ttl = ''; $emptyData->pax_in = ''; $emptyData->pax_out = ''; $emptyData->reporting_date = ''; $emptyData->day_of_week = ''; $emptyData->area = ''; $emptyData->category = ''; $emptyData->factor = ''; $emptyData->measures_to_revent_recurrence = ''; $emptyData->influence_on_safety = ''; $emptyData->frequency = ''; $emptyData->staff_comment = ''; $emptyData->approve_comment = ''; $emptyData->assessment = ''; return $emptyData; } /** * レポート個別情報取得 * @see ReportController::getIndividualsInfo() */ protected function getIndividualsInfo($report_no, $report_class){ // Stationリスト取得 $station_list = SystemCodeManager::getStation($report_class); // Ship Noリスト取得 $ship_no_list = SystemCodeManager::getShipNo($report_class); // Sectorリスト取得 $sector_list = SystemCodeManager::getSector($report_class); // DLA CODEリスト取得 $dla_code_list = SystemCodeManager::getDLACode($report_class); // Weatherリスト取得 $weather_list = SystemCodeManager::getWeather($report_class); // Areaリスト取得 $area_list = SystemCodeManager::getArea($report_class); // カテゴリリスト取得 $category_list = SystemCodeManager::getCategory($report_class); // Factor取得 $factor_list = SystemCodeManager::getFactor($report_class); // Infuluence on Safety取得 $influence_on_safety_list = SystemCodeManager::getInfluenceOnSafety($report_class); // Frequency取得 $frequency_list = SystemCodeManager::getFrequency($report_class); return [ 'station_list' => $station_list, 'ship_no_list' => $ship_no_list, 'sector_list' => $sector_list, 'dla_code_list' => $dla_code_list, 'weather_list' => $weather_list, 'area_list' => $area_list, 'category_list' => $category_list, 'factor_list' => $factor_list, 'influence_on_safety_list' => $influence_on_safety_list, 'frequency_list' => $frequency_list ]; } /** * レポート登録 * @see ReportController::insertReport() */ protected function insertReport($status){ $_mode = Input::get('_mode'); $timestamp = DateUtil::getCurrentTimestamp(); $report_class = Input::get('_report_class'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $peacock_inquiry_status = (Input::get('peacock_inquiry_status') === 'on' ? '1' : '0'); $peacock_inquiry_timestamp = (Input::get('peacock_inquiry_status') === 'on' ? $timestamp : null); $penguin_inquiry_status = (Input::get('penguin_inquiry_status') === 'on' ? '1' : '0'); $penguin_inquiry_timestamp = (Input::get('penguin_inquiry_status') === 'on' ? $timestamp :null); $peregrine_inquiry_status = (Input::get('peregrine_inquiry_status') === 'on' ? '1' : '0'); $peregrine_inquiry_timestamp = (Input::get('peregrine_inquiry_status') === 'on' ? $timestamp : null); $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $delete_flag = '0'; $create_user_id = $this->user->getLoginId(); $create_timestamp = $timestamp; $update_user_id = $this->user->getLoginId(); $update_timestamp = $timestamp; $station = Input::get('station'); $department = Input::get('department'); $position = Input::get('position'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $ship_no = Input::get('ship_no'); $origin_rcd = Input::get('origin_rcd'); $destination_rcd = Input::get('destination_rcd'); $gate_spot = Input::get('gate_spot'); $weather = Input::get('weather'); $std = Input::get('std'); $sta = Input::get('sta'); $etd = Input::get('etd'); $eta = Input::get('eta'); $atd = Input::get('atd'); $ata = Input::get('ata'); $dla_code = Input::get('dla_code'); $dla_time = CommonCheckLogic::isEmpty(Input::get('dla_time')) ? null : Input::get('dla_time'); $dla_code_2 = Input::get('dla_code_2'); $dla_time_2 = CommonCheckLogic::isEmpty(Input::get('dla_time_2')) ? null : Input::get('dla_time_2'); $dla_code_3 = Input::get('dla_code_3'); $dla_time_3 = CommonCheckLogic::isEmpty(Input::get('dla_time_3')) ? null : Input::get('dla_time_3'); $dla_ttl = Input::get('dla_ttl'); $pax_in = Input::get('pax_in'); $pax_out = Input::get('pax_out'); $reporting_date = Input::get('reporting_date'); $day_of_week = Input::get('day_of_week'); $area = Input::get('area'); $category = Input::get('category'); $factor = Input::get('factor'); $measures_to_revent_recurrence = Input::get('measures_to_revent_recurrence'); $influence_on_safety = Input::get('influence_on_safety'); $frequency = Input::get('frequency'); $approve_comment = Input::get('approve_comment'); $assessment = Input::get('assessment'); $staff_comment = Input::get('staff_comment'); // 必須入力チェック if(CommonCheckLogic::isEmpty($station)){ $this->error_message_list[] = 'Station' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = 'Flight NoはMM+4桁の数字で入力してください。'; } // 半角英数チェック if(! CommonCheckLogic::isHalfAlphaNumeric($gate_spot, true) ){ $this->error_message_list[] = 'Gate(Spot)は半角英数字で入力してください。'; } // 数字チェック if(! CommonCheckLogic::isHalfNumericAndLength($std, 4, true) ){ $this->error_message_list[] = 'STDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($sta, 4, true) ){ $this->error_message_list[] = 'STAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($etd, 4, true) ){ $this->error_message_list[] = 'ETDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($atd, 4, true) ){ $this->error_message_list[] = 'ATDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($eta, 4, true) ){ $this->error_message_list[] = 'ETAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($ata, 4, true) ){ $this->error_message_list[] = 'ATAは4桁の数値で入力してください。'; } // 数値チェック if(! CommonCheckLogic::isNumeric($dla_time, true) ){ $this->error_message_list[] = '#1 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_time_2, true) ){ $this->error_message_list[] = '#2 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_time_3, true) ){ $this->error_message_list[] = '#3 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_ttl, true) ){ $this->error_message_list[] = 'DLA TTLは数値で入力してください。'; } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($reporting_date, true) ){ $this->error_message_list[] = 'Reporting Date' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date, true) ){ $this->error_message_list[] = 'Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // エラーがある場合 if($this->hasError()){ return null; } $result = DataManager::getReportNoAndSeq($report_class, $station, $departure_date); $report_no = $result[0]; $report_seq = $result[1]; $dla_ttl = intVal($dla_time) + intVal($dla_time_2) + intVal($dla_time_3); $data =[ $report_no, $report_seq, $report_class, $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $peacock_inquiry_status, $peacock_inquiry_timestamp, $penguin_inquiry_status, $penguin_inquiry_timestamp, $peregrine_inquiry_status, $peregrine_inquiry_timestamp, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $delete_flag, $create_user_id, $create_timestamp, $update_user_id, $update_timestamp ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報登録 while(DataManager::insertWithCheckDuplicate(Config::get('sql.INSERT_REPORT_BASIC_INFO'), $data)){ $result = DataManager::getReportNoAndSeq($report_class, $report_type, $departure_date); $report_no = $result[0]; $report_seq = $result[1]; $data[0] = $report_no; $data[1] = $report_seq; } $data = [ $report_no, $station, $department, $position, $departure_date, $flight_number, $ship_no, $origin_rcd, $destination_rcd, $gate_spot, $weather, $std, $sta, $etd, $eta, $atd, $ata, $dla_code, $dla_time, $dla_code_2, $dla_time_2, $dla_code_3, $dla_time_3, $dla_ttl, $pax_in, $pax_out, $reporting_date, $day_of_week, $area, $category, $factor, $measures_to_revent_recurrence, $influence_on_safety, $frequency, $approve_comment, $assessment, $staff_comment ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報登録 DB::insert(Config::get('sql.INSERT_REPORT_PEREGRINE'), $data); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); return $report_no; } /** * レポート更新 * @see ReportController::updateReport() */ protected function updateReport($status, $is_passback){ $_mode = Input::get('_mode'); $modified = Input::get('_modified'); $timestamp = DateUtil::getCurrentTimestamp(); $report_no = Input::get('_report_no'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $create_user_id = $this->user->userInfo->login_id; $create_timestamp = $timestamp; $update_user_id = $this->user->userInfo->login_id; $update_timestamp = $timestamp; $station = Input::get('station'); $department = Input::get('department'); $position = Input::get('position'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $ship_no = Input::get('ship_no'); $origin_rcd = Input::get('origin_rcd'); $destination_rcd = Input::get('destination_rcd'); $gate_spot = Input::get('gate_spot'); $weather = Input::get('weather'); $std = Input::get('std'); $sta = Input::get('sta'); $etd = Input::get('etd'); $eta = Input::get('eta'); $atd = Input::get('atd'); $ata = Input::get('ata'); $dla_code = Input::get('dla_code'); $dla_time = CommonCheckLogic::isEmpty(Input::get('dla_time')) ? null : Input::get('dla_time'); $dla_code_2 = Input::get('dla_code_2'); $dla_time_2 = CommonCheckLogic::isEmpty(Input::get('dla_time_2')) ? null : Input::get('dla_time_2'); $dla_code_3 = Input::get('dla_code_3'); $dla_time_3 = CommonCheckLogic::isEmpty(Input::get('dla_time_3')) ? null : Input::get('dla_time_3'); $dla_ttl = Input::get('dla_ttl'); $pax_in = Input::get('pax_in'); $pax_out = Input::get('pax_out'); $reporting_date = Input::get('reporting_date'); $day_of_week = Input::get('day_of_week'); $area = Input::get('area'); $category = Input::get('category'); $factor = Input::get('factor'); $measures_to_revent_recurrence = Input::get('measures_to_revent_recurrence'); $influence_on_safety = Input::get('influence_on_safety'); $frequency = Input::get('frequency'); $approve_comment = Input::get('approve_comment'); $assessment = Input::get('assessment'); $staff_comment = Input::get('staff_comment'); // 変更かつ承認済みの場合 if($_mode === 'edit' && $status == Config::get('const.REPORT_STATUS.CLOSE')){ $data =[ $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO_ONLY_REMARKS'), $data) == 0){ return false; } }else{ // 必須入力チェック if(CommonCheckLogic::isEmpty($station)){ $this->error_message_list[] = 'Station' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = 'Flight NoはMM+4桁の数字で入力してください。'; } // 半角英数チェック if(! CommonCheckLogic::isHalfAlphaNumeric($gate_spot, true) ){ $this->error_message_list[] = 'Gate(Spot)は半角英数字で入力してください。'; } // 数字チェック if(! CommonCheckLogic::isHalfNumericAndLength($std, 4, true) ){ $this->error_message_list[] = 'STDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($sta, 4, true) ){ $this->error_message_list[] = 'STAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($etd, 4, true) ){ $this->error_message_list[] = 'ETDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($atd, 4, true) ){ $this->error_message_list[] = 'ATDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($eta, 4, true) ){ $this->error_message_list[] = 'ETAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($ata, 4, true) ){ $this->error_message_list[] = 'ATAは4桁の数値で入力してください。'; } // 数値チェック if(! CommonCheckLogic::isNumeric($dla_time, true) ){ $this->error_message_list[] = '#1 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_time_2, true) ){ $this->error_message_list[] = '#2 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_time_3, true) ){ $this->error_message_list[] = '#3 DLA TIMEは数値で入力してください。'; } if(! CommonCheckLogic::isNumeric($dla_ttl, true) ){ $this->error_message_list[] = 'DLA TTLは数値で入力してください。'; } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($reporting_date, true) ){ $this->error_message_list[] = 'Reporting Date' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date, true) ){ $this->error_message_list[] = 'Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // メール送信先チェック parent::checkSendMail($is_passback); // エラーがある場合 if($this->hasError()){ return true; } $dla_ttl = intVal($dla_time) + intVal($dla_time_2) + intVal($dla_time_3); // セッションから現在のレポート情報を取得 $old_report_info = $this->getSessionReportInfo(); // 差戻しの場合 if($is_passback){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $old_report_info->approver_id; }else{ // 確認処理の場合 if($status == Config::get('const.REPORT_STATUS.CONFIRMED')){ $confirmor_id = $update_user_id; $approver_id = $old_report_info->approver_id; } // 承認処理の場合 if($status == Config::get('const.REPORT_STATUS.CLOSE')){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $update_user_id; } } $data =[ $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO'), $data) == 0){ return false; } $data = [ $station, $department, $position, $departure_date, $flight_number, $ship_no, $origin_rcd, $destination_rcd, $gate_spot, $weather, $std, $sta, $etd, $eta, $atd, $ata, $dla_code, $dla_time, $dla_code_2, $dla_time_2, $dla_code_3, $dla_time_3, $dla_ttl, $pax_in, $pax_out, $reporting_date, $day_of_week, $area, $category, $factor, $measures_to_revent_recurrence, $influence_on_safety, $frequency, $approve_comment, $assessment, $staff_comment, $report_no, ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報更新 DB::update(Config::get('sql.UPDATE_REPORT_PEREGRINE'), $data); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); } return true; } function getAlertUserList($report_no, $alert_timing = NULL) { $station = DB::table('report_info_peregrine') ->select('station') ->where('report_no', $report_no) ->first(); $db = DB::table('alert_mail_condition') ->distinct() ->select(['login_id']) ->where(function($query) use($report_no, $station) { $query->where('report_no', $report_no) ->orWhere('station', $station->station); }); if(!is_null($alert_timing)) { $db = $db->where('alert_timing', $alert_timing); } $result = $db->get(); $ret = []; foreach($result as $row) { $ret[] = $row->login_id; } return $ret; } } <file_sep>/vendor/dsdevbe/ldap-connector/README.md # Ldap-connector Provides an solution for authentication users with LDAP for Laravel 4.2.x ## Installation 1. Install this package through Composer: ```js composer require dsdevbe/ldap-connector:1.* ``` 1. Change the authentication driver in the Laravel config to use the ldap driver. You can find this in the following file `app/config/auth.php` ```php 'driver' => 'ldap', ``` 1. Create a new configuration file `ldap.php` in the configuration folder of Laravel `app/config/ldap.php` and modify to your needs. ```php <?php return array( 'account_suffix' => "@domain.local", 'domain_controllers' => array("192.168.0.1", "dc02.domain.local"), // Load balancing domain controllers 'base_dn' => 'DC=domain,DC=local', 'admin_username' => 'dummy', // Just needs to be an valid account to query other users if they exists 'admin_password' => '<PASSWORD>' ); ``` 1. Once this is done you arrived at the final step and you will need to add a service provider. Open `app/config/app.php`, and add a new item to the providers array. ```php 'Dsdevbe\LdapConnector\LdapConnectorServiceProvider' ``` ## Usage The LDAP plugin is an extension of the AUTH class and will act the same as normal usage with Eloquent driver. ```php if (Auth::attempt(array('username' => $email, 'password' => $password))) { return Redirect::intended('dashboard'); } ``` You can find more examples on [Laravel Auth Documentation](http://laravel.com/docs/security#authenticating-users) on using the `Auth::` function.<file_sep>/app/controllers/PreviewControllerPEACOCK.php <?php /** * * プレビュー画面(PEACOCK) * */ class PreviewControllerPEACOCK extends PreviewController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see PreviewController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_PREVIEW_PEACOCK'),['1','1', $report_no, '1']); } } <file_sep>/app/views/parts/report/config_area.php <label for="secret" class="label06">Own Department Only<br /><span>他部門非公開</span></label> <div class="label07"> <div class="checkbox checkbox-inline"> <input type="checkbox" id="own_department_only_flag" name="own_department_only_flag" <?php echo (Input::old('own_department_only_flag',$report_info->own_department_only_flag) === '1' || Input::old('own_department_only_flag',$report_info->own_department_only_flag) === 'on') ? 'checked="checked"' : '' ?> <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <label for="own_department_only_flag"></label> </div> </div> <file_sep>/app/controllers/ReportControllerPEACOCK.php <?php /** * レポート画面(PEACOCK) */ class ReportControllerPEACOCK extends ReportController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see ReportController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_REPORT_INFO_PEACOCK'),['1','1', $report_no, '1']); } /** * 空のレポート情報取得 * @see ReportController::getEmptyReportInfo() */ protected function getEmptyReportInfo($report_class){ $emptyData = new stdClass(); $emptyData->report_no = ''; $emptyData->report_seq = ''; $emptyData->report_class = $report_class; $emptyData->own_department_only_flag = ''; $emptyData->has_additional_pax_info = 0; $emptyData->has_additional_reservation_info = 0; $emptyData->report_status_name = ''; $emptyData->report_status = Config::get('const.REPORT_STATUS.CREATED'); $emptyData->day_of_week = ''; $emptyData->reported_by = ''; $emptyData->report_title = ''; $emptyData->contents = ''; $emptyData->confirmor_id = ''; $emptyData->approver_id = ''; $emptyData->peacock_inquiry_status = ''; $emptyData->peacock_inquiry_timestamp = ''; $emptyData->penguin_inquiry_status = ''; $emptyData->penguin_inquiry_timestamp = ''; $emptyData->peregrine_inquiry_status = ''; $emptyData->peregrine_inquiry_timestamp = ''; $emptyData->old_report_no = ''; $emptyData->related_report_no = ''; $emptyData->related_report_class = ''; $emptyData->related_report_no_2 = ''; $emptyData->related_report_class_2 = ''; $emptyData->firstname = ''; $emptyData->lastname = ''; $emptyData->title_rcd = ''; $emptyData->birthday = ''; $emptyData->phone_number1 = ''; $emptyData->phone_number2 = ''; $emptyData->record_locator = ''; $emptyData->firstname_2 = ''; $emptyData->lastname_2 = ''; $emptyData->title_rcd_2 = ''; $emptyData->birthday_2 = ''; $emptyData->phone_number1_2 = ''; $emptyData->phone_number2_2 = ''; $emptyData->record_locator_2 = ''; $emptyData->firstname_3 = ''; $emptyData->lastname_3 = ''; $emptyData->title_rcd_3 = ''; $emptyData->birthday_3 = ''; $emptyData->phone_number1_3 = ''; $emptyData->phone_number2_3 = ''; $emptyData->record_locator_3 = ''; $emptyData->phoenix_class = ''; $emptyData->phoenix_memo = ''; $emptyData->free_comment = ''; $emptyData->delete_flag = ''; $emptyData->create_user_id = ''; $emptyData->create_timestamp = ''; $emptyData->update_user_id = ''; $emptyData->update_timestamp = ''; $emptyData->report_type = ''; $emptyData->flight_report_no = ''; $emptyData->added_by = ''; $emptyData->departure_date = ''; $emptyData->flight_number = 'MM'; $emptyData->ship_no = ''; $emptyData->origin_rcd = ''; $emptyData->destination_rcd = ''; $emptyData->etd = ''; $emptyData->atd = ''; $emptyData->eta = ''; $emptyData->ata = ''; $emptyData->crew_cp = ''; $emptyData->crew_cap = ''; $emptyData->crew_r1 = ''; $emptyData->crew_l2 = ''; $emptyData->crew_r2 = ''; $emptyData->pax_onboard = ''; $emptyData->pax_detail = ''; $emptyData->mr = ''; $emptyData->staff_comment = ''; $emptyData->reporting_date = ''; return $emptyData; } /** * レポート個別情報取得 * @see ReportController::getIndividualsInfo() */ protected function getIndividualsInfo($report_no, $report_class){ // Ship Noリスト取得 $ship_no_list = SystemCodeManager::getShipNo($report_class); // Sectorリスト取得 $sector_list = SystemCodeManager::getSector($report_class); // レポートタイプ取得 $report_type_list = SystemCodeManager::getReportType($report_class); // 選択カテゴリ情報取得 $select_categoly_info = DataManager::getSelectCategoryInfo($report_no); return [ 'report_type_list' => $report_type_list, 'ship_no_list' => $ship_no_list, 'sector_list' => $sector_list, 'select_categoly_info' => $select_categoly_info ]; } /** * レポート登録 * @see ReportController::insertReport() */ protected function insertReport($status,$new_report_no=''){ $_mode = Input::get('_mode'); $timestamp = DateUtil::getCurrentTimestamp(); $report_class = Input::get('_report_class'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $peacock_inquiry_status = (Input::get('peacock_inquiry_status') === 'on' ? '1' : '0'); $peacock_inquiry_timestamp = (Input::get('peacock_inquiry_status') === 'on' ? $timestamp : null); $penguin_inquiry_status = (Input::get('penguin_inquiry_status') === 'on' ? '1' : '0'); $penguin_inquiry_timestamp = (Input::get('penguin_inquiry_status') === 'on' ? $timestamp :null); $peregrine_inquiry_status = (Input::get('peregrine_inquiry_status') === 'on' ? '1' : '0'); $peregrine_inquiry_timestamp = (Input::get('peregrine_inquiry_status') === 'on' ? $timestamp : null); $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $delete_flag = '0'; $create_user_id = $this->user->getLoginId(); $create_timestamp = $timestamp; $update_user_id = $this->user->getLoginId(); $update_timestamp = $timestamp; $report_type = Input::get('report_type'); $flight_report_no = Input::get('flight_report_no'); $added_by = Input::get('added_by'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $ship_no = Input::get('ship_no'); $origin_rcd = Input::get('origin_rcd'); $destination_rcd = Input::get('destination_rcd'); $etd = Input::get('etd'); $atd = Input::get('atd'); $eta = Input::get('eta'); $ata = Input::get('ata'); $crew_cp = Input::get('crew_cp'); $crew_cap = Input::get('crew_cap'); $crew_r1 = Input::get('crew_r1'); $crew_l2 = Input::get('crew_l2'); $crew_r2 = Input::get('crew_r2'); $pax_onboard = Input::get('pax_onboard'); $pax_detail = Input::get('pax_detail'); $mr = Input::get('mr'); $staff_comment = Input::get('staff_comment'); $reporting_date = $departure_date; // 必須入力チェック if(CommonCheckLogic::isEmpty($report_type)){ $this->error_message_list[] = 'Report Type' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date, true) ){ $this->error_message_list[] = 'Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } // 数字チェック if(! CommonCheckLogic::isHalfNumericAndLength($etd, 4, true) ){ $this->error_message_list[] = 'ETDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($atd, 4, true) ){ $this->error_message_list[] = 'ATDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($eta, 4, true) ){ $this->error_message_list[] = 'ETAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($ata, 4, true) ){ $this->error_message_list[] = 'ATAは4桁の数値で入力してください。'; } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = 'Flight NoはMM+4桁の数字で入力してください。'; } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // エラーがある場合 if($this->hasError()){ return null; } $result = DataManager::getReportNoAndSeq($report_class, $report_type, $departure_date); $report_no = $result[0]; $report_seq = $result[1]; $data =[ $report_no, $report_seq, $report_class, $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $peacock_inquiry_status, $peacock_inquiry_timestamp, $penguin_inquiry_status, $penguin_inquiry_timestamp, $peregrine_inquiry_status, $peregrine_inquiry_timestamp, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $delete_flag, $create_user_id, $create_timestamp, $update_user_id, $update_timestamp ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報登録 while(DataManager::insertWithCheckDuplicate(Config::get('sql.INSERT_REPORT_BASIC_INFO'), $data)){ $result = DataManager::getReportNoAndSeq($report_class, $report_type, $departure_date); $report_no = $result[0]; $report_seq = $result[1]; $data[0] = $report_no; $data[1] = $report_seq; } $data = [ $report_no, $report_type, $flight_report_no, $added_by, $departure_date, $flight_number, $ship_no, $origin_rcd, $destination_rcd, $etd, $atd, $eta, $ata, $crew_cp, $crew_cap, $crew_r1, $crew_l2, $crew_r2, $pax_onboard, $pax_detail, $mr, $staff_comment, $reporting_date ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報登録 DB::insert(Config::get('sql.INSERT_REPORT_PEACOCK'), $data); // カテゴリ情報削除・登録 DataManager::deleteSelectCategoryInfo($report_no); DataManager::saveSelectCategoryInfo($report_no, $report_type); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); return $report_no; } /** * レポート更新 * @see ReportController::updateReport() */ protected function updateReport($status, $is_passback){ $_mode = Input::get('_mode'); $modified = Input::get('_modified'); $timestamp = DateUtil::getCurrentTimestamp(); $report_no = Input::get('_report_no'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $create_user_id = $this->user->userInfo->login_id; $create_timestamp = $timestamp; $update_user_id = $this->user->userInfo->login_id; $update_timestamp = $timestamp; $report_type = Input::get('report_type'); $flight_report_no = Input::get('flight_report_no'); $added_by = Input::get('added_by'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $ship_no = Input::get('ship_no'); $origin_rcd = Input::get('origin_rcd'); $destination_rcd = Input::get('destination_rcd'); $etd = Input::get('etd'); $atd = Input::get('atd'); $eta = Input::get('eta'); $ata = Input::get('ata'); $crew_cp = Input::get('crew_cp'); $crew_cap = Input::get('crew_cap'); $crew_r1 = Input::get('crew_r1'); $crew_l2 = Input::get('crew_l2'); $crew_r2 = Input::get('crew_r2'); $pax_onboard = Input::get('pax_onboard'); $pax_detail = Input::get('pax_detail'); $mr = Input::get('mr'); $staff_comment = Input::get('staff_comment'); $reporting_date = $departure_date; // 変更かつ承認済みの場合 if($_mode === 'edit' && $status == Config::get('const.REPORT_STATUS.CLOSE')){ $data =[ $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO_ONLY_REMARKS'), $data) == 0){ return false; } }else{ // 必須入力チェック if(CommonCheckLogic::isEmpty($report_type)){ $this->error_message_list[] = 'Report Type' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date, true) ){ $this->error_message_list[] = 'Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } // 数字チェック if(! CommonCheckLogic::isHalfNumericAndLength($etd, 4, true) ){ $this->error_message_list[] = 'ETDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($atd, 4, true) ){ $this->error_message_list[] = 'ATDは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($eta, 4, true) ){ $this->error_message_list[] = 'ETAは4桁の数値で入力してください。'; } if(! CommonCheckLogic::isHalfNumericAndLength($ata, 4, true) ){ $this->error_message_list[] = 'ATAは4桁の数値で入力してください。'; } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = 'Flight NoはMM+4桁の数字で入力してください。'; } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // メール送信先チェック parent::checkSendMail($is_passback); // エラーがある場合 if($this->hasError()){ return true; } // セッションから現在のレポート情報を取得 $old_report_info = $this->getSessionReportInfo(); // 差戻しの場合 if($is_passback){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $old_report_info->approver_id; }else{ // 確認処理の場合 if($status == Config::get('const.REPORT_STATUS.CONFIRMED')){ $confirmor_id = $update_user_id; $approver_id = $old_report_info->approver_id; } // 承認処理の場合 if($status == Config::get('const.REPORT_STATUS.CLOSE')){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $update_user_id; } } $data =[ $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO'), $data) == 0){ return false; } $data = [ $report_type, $flight_report_no, $added_by, $departure_date, $flight_number, $ship_no, $origin_rcd, $destination_rcd, $etd, $atd, $eta, $ata, $crew_cp, $crew_cap, $crew_r1, $crew_l2, $crew_r2, $pax_onboard, $pax_detail, $mr, $staff_comment, $reporting_date, $report_no ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報更新 DB::update(Config::get('sql.UPDATE_REPORT_PEACOCK'), $data); // カテゴリ情報削除・登録 DataManager::deleteSelectCategoryInfo($report_no); DataManager::saveSelectCategoryInfo($report_no, $report_type); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); } return true; } } <file_sep>/app/extentions/CommonGateway/DateUtil.php <?php namespace CommonGateway { class DateUtil { /** * コンストラクタ */ function __construct() { } /** * 現在日時を取得する */ function getCurrentTimestamp(){ return date("Y-m-d H:i:s"); } } } <file_sep>/app/extentions/ChirpUser.php <?php class ChirpUser{ public $userInfo; /* * コンストラクタ */ function __construct($userInfo) { $this->userInfo = $userInfo; } /** * 起票者かどうかを返す * @return boolean */ function isCreator(){ return intVal($this->userInfo->user_role) === Config::get('const.USER_ROLE.REPORTER'); } /** * ログインID取得 */ function getLoginId(){ return $this->userInfo->login_id; } /** * Station取得 */ function getStation(){ return $this->userInfo->station; } /** * レポート名取得 */ function getReportName(){ return $this->userInfo->report_name; } } <file_sep>/app/views/parts/report/comment.php <table class="table table-hover"> <tbody> <?php foreach($comment_list as $data) { ?> <tr> <td> <ul id="commentListUl" class="commentList skinBorderList"> <li> <div class="blogComment"> <div class="commentHeader"> <?= HTML::entities($data->comment_seq) ?> </div> <div class="commentBody"><?= HTML::entities($data->comment) ?></div> <div class="commentFooter text-right"> <span class="commentAuthor"><?= HTML::entities($data->author) ?></span> <span> from </span> <span class="commentFrom"><?= HTML::entities($data->report_name) ?></span> <span class="commentTime skinWeakColor"><time><?= HTML::entities($data->create_timestamp) ?></time></span> </div> </div> </li> </ul> </td> </tr> <?php } ?> </tbody> </table> <file_sep>/app/views/parts/report/pax_info_area.php <label for="firstname" class="label06">#1 First Name<br /><span>名前</span></label> <div class=label07> <input id="firstname" name="firstname" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('firstname', $report_info->firstname)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="lastname" class="label06">#1 Last Name<br /><span>苗字</span></label> <div class="label07"> <input id="lastname" name="lastname" type="text" class="inputbox" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('lastname', $report_info->lastname)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label class="label06">#1 Gender<br /><span>性別</span></label> <div class="label07"> <select id="title_rcd" name="title_rcd" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($gender_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('title_rcd', $report_info->title_rcd) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="birthday" class="label06">#1 Birthday<br /><span>生年月日</span></label> <div class="label07"> <input id="birthday" name="birthday" type="text" class="inputbox" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('birthday', $report_info->birthday)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="phone_number1" class="label06">#1 Phone Number<br /><span>電話番号</span></label> <?php if($report_info->report_class != 1): ?> <div class="label07_2"> <input id="phone_number1" name="phone_number1" type="text" class="inputbox" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1', $report_info->phone_number1)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2" name="phone_number2" type="text" class="inputbox" value="<?= HTML::entities(Input::old('phone_number2', $report_info->phone_number2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="record_locator" class="label06">#1 PNR<br /><span>予約番号</span></label> <div class="label07" style="margin-bottom:50px;"> <input id="record_locator" name="record_locator" type="text" class="inputbox" value="<?= HTML::entities(Input::old('record_locator', $report_info->record_locator)) ?>" maxlength="7" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php else: ?> <div class="label07_2" style="margin-bottom:50px;"> <input id="phone_number1" name="phone_number1" type="text" class="inputbox" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1', $report_info->phone_number1)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2" name="phone_number2" type="text" class="inputbox" value="<?= HTML::entities(Input::old('phone_number2', $report_info->phone_number2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php endif;?> <div class="row <?= HTML::entities($role_manage_info->pax_info_button_hidden) ?>"> <div class="col-md-2 text-left" style="margin-left:12px; margin-bottom:15px;"> <button type="button" class="btn btn-lgray btn-xs" data-toggle="collapse" data-target="#collapsePaxInfo"> <span id="paxInfoIcon" class="glyphicon glyphicon-plus"></span> PAX Information </button> </div> </div> <div id="collapsePaxInfo" class="collapse"> <label for="firstname_2" class="label06">#2 First Name<br /><span>名前</span></label> <div class="label07"> <input id="firstname_2" name="firstname_2" type="text" class="inputbox additional-pax-info" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('firstname_2', $report_info->firstname_2)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="lastname_2" class="label06">#2 Last Name<br /><span>苗字</span></label> <div class="label07"> <input id="lastname_2" name="lastname_2" type="text" class="inputbox additional-pax-info" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('lastname_2', $report_info->lastname_2)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label class="label06">#2 Gender<br /><span>性別</span></label> <div class="label07"> <select id="title_rcd_2" name="title_rcd_2" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($gender_list as $data) { ?> <option class="additional-pax-info" value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('title_rcd_2', $report_info->title_rcd_2) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="birthday_2" class="label06">#2 Birthday<br /><span>生年月日</span></label> <div class="label07"> <input id="type" name="birthday_2" type="text" class="inputbox additional-pax-info" placeholder="YYYY/MM/DD" value="<?= HTML::entities(Input::old('birthday_2', $report_info->birthday_2)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="phone_number1_2" class="label06">#2 Phone Number<br /><span>電話番号</span></label> <?php if($report_info->report_class != 1): ?> <div class="label07_2"> <input id="phone_number1_2" name="phone_number1_2" type="text" class="inputbox additional-pax-info" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1_2', $report_info->phone_number1_2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2_2" name="phone_number2_2" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('phone_number2_2', $report_info->phone_number2_2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="record_locator_2" class="label06">#2 PNR<br /><span>予約番号</span></label> <div class="label07" style="margin-bottom:50px;"> <input id="record_locator_2" name="record_locator_2" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('record_locator_2', $report_info->record_locator_2)) ?>" maxlength="7" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php else: ?> <div class="label07_2" style="margin-bottom:50px;"> <input id="phone_number1_2" name="phone_number1_2" type="text" class="inputbox additional-pax-info" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1_2', $report_info->phone_number1_2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2_2" name="phone_number2_2" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('phone_number2_2', $report_info->phone_number2_2)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php endif; ?> <label for="firstname_3" class="label06">#3 First Name<br /><span>名前</span></label> <div class="label07"> <input id="firstname_3" name="firstname_3" type="text" class="inputbox additional-pax-info" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('firstname_3', $report_info->firstname_3)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="lastname_3" class="label06">#3 Last Name<br /><span>苗字</span></label> <div class="label07"> <input id="lastname_3" name="lastname_3" type="text" class="inputbox additional-pax-info" placeholder="Alphabet only" value="<?= HTML::entities(Input::old('lastname_3', $report_info->lastname_3)) ?>" maxlength="40" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label class="label06">#3 Gender<br /><span>性別</span></label> <div class="label07"> <select id="title_rcd_3" name="title_rcd_3" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($gender_list as $data) { ?> <option class="additional-pax-info" value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('title_rcd_3', $report_info->title_rcd_3) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="birthday_3" class="label06">#3 Birthday<br /><span>生年月日</span></label> <div class="label07"> <input id="birthday_3" name="birthday_3" type="text" class="inputbox additional-pax-info" placeholder="YYYY/MM/DD" value="<?= Input::old('birthday_3', HTML::entities($report_info->birthday_3)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="phone_number1_3" class="label06">#3 Phone Number<br /><span>電話番号</span></label> <?php if($report_info->report_class != 1): ?> <div class="label07_2"> <input id="phone_number1_3" name="phone_number1_3" type="text" class="inputbox additional-pax-info" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1_3', $report_info->phone_number1_3)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2_3" name="phone_number2_3" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('phone_number2_3', $report_info->phone_number2_3)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <label for="record_locator_3" class="label06">#3 PNR<br /><span>予約番号</span></label> <div class="label07" style="margin-bottom:50px;"> <input id="record_locator_3" name="record_locator_3" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('record_locator_3', $report_info->record_locator_3)) ?>" maxlength="7" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php else: ?> <div class="label07_2" style="margin-bottom:50px;"> <input id="phone_number1_3" name="phone_number1_3" type="text" class="inputbox additional-pax-info" style="margin-bottom:10px;" value="<?= HTML::entities(Input::old('phone_number1_3', $report_info->phone_number1_3)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> <input id="phone_number2_3" name="phone_number2_3" type="text" class="inputbox additional-pax-info" value="<?= HTML::entities(Input::old('phone_number2_3', $report_info->phone_number2_3)) ?>" maxlength="20" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> <?php endif; ?> <div class="clearfix"></div> </div><file_sep>/app/config/message.php <?php return [ // 排他例外 'EXCLUSIVE_ERROR' => '他のユーザーにより変更されています。レポート選択からやり直してください。', // 日付フォーマットエラー 'DATE_FORMAT_ERROR' => 'はYYYY/MM/DDで入力してください。', // 必須入力エラー 'REQUIRED_ERROR' => 'の入力は必須です。', ];<file_sep>/app/views/parts/preview/preview_peacock.php <table id="" class="table" border="0" cellpadding="2" style="width: 100%; text-align: left; table-layout:fixed; word-wrap: break-word;"> <tbody> <tr> <td class="preview_header"><div class="preview_header_al">Own Department Only</div>他部門非公開</td> <td class="preview_data"><?php echo ($report_info->own_department_only_flag === '1' ? 'On' : 'Off')?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report No</div>レポート番号</td> <td class="preview_data"><?=HTML::entities($report_info->report_no) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report Type</div>レポート種別</td> <td class="preview_data"><?=HTML::entities($report_info->report_type) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Flight Report No</div>フライトレポート番号</td> <td class="preview_data"><?=HTML::entities($report_info->flight_report_no) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Flight Date</div>フライト日</td> <td class="preview_data"><?=HTML::entities($report_info->departure_date) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Flight No</div>便名</td> <td class="preview_data"><?=HTML::entities($report_info->flight_number) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Ship No</div>機番</td> <td class="preview_data"><?=HTML::entities($report_info->ship_no) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Sector</div>区間</td> <td class="preview_data"><?php if($report_info->origin_rcd || $report_info->destination_rcd): ?><?=HTML::entities($report_info->origin_rcd) ?> → <?=HTML::entities($report_info->destination_rcd) ?><?php endif; ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">ETD</div>出発予定時間</td> <td class="preview_data"><?=HTML::entities($report_info->etd) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">ETA</div>到着予定時間</td> <td class="preview_data"><?=HTML::entities($report_info->eta) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">ATD</div>実出発時間</td> <td class="preview_data"><?=HTML::entities($report_info->atd) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">ATA</div>実到着時間</td> <td class="preview_data"><?=HTML::entities($report_info->ata) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">PAX Onboard</div>旅客数</td> <td class="preview_data"><?=HTML::entities($report_info->pax_onboard) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">PAX Remarks Code & Seat No</div>配慮を要する旅客のコード、座席番号</td> <td class="preview_data"><?=HTML::entities($report_info->pax_detail) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">CREW CP</div>CP氏名</td> <td class="preview_data"><?=HTML::entities($report_info->crew_cp) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">CREW CAP</div>CAP氏名</td> <td class="preview_data"><?=HTML::entities($report_info->crew_cap) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">CREW R1</div>R1氏名</td> <td class="preview_data"><?=HTML::entities($report_info->crew_r1) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">CREW L2</div>L2氏名</td> <td class="preview_data"><?=HTML::entities($report_info->crew_l2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">CREW R2</div>R2氏名</td> <td class="preview_data"><?=HTML::entities($report_info->crew_r2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report Title</div>標題</td> <td class="preview_data"><?=HTML::entities($report_info->report_title) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Reporting Date</div>起票日</td> <td class="preview_data"><?=HTML::entities($report_info->reporting_date) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Category</div>カテゴリ</td> <td class="preview_data"><?=HTML::entities($report_info->category_name) ?></td> </tr> <?php if($report_info->report_type == 'MR'): ?> <tr> <td class="preview_header"><div class="preview_header_al">MR</div>メディカルレポート</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->mr)) ?></td> </tr> <?php endif; ?> <tr> <td class="preview_header"><div class="preview_header_al">Contents</div>内容</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->contents)) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Staff Comment</div>スタッフ補記</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->staff_comment)) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Added By</div>スタッフ補記担当者名</td> <td class="preview_data"><?=HTML::entities($report_info->added_by) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Attachments</div>添付ファイル</td> <td class="preview_data"><?=HTML::entities($report_info->attach_file_list) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Related Report</div>関連レポート</td> <td class="preview_data"><?=HTML::entities($report_info->related_report_list) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Remarks</div>備考</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->free_comment)) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Phone Number ①</div>電話番号 ①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 Phone Number ②</div>電話番号 ②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#1 PNR</div>予約番号</td> <td class="preview_data"><?=HTML::entities($report_info->record_locator) ?></td> </tr> <?php if($report_info->pax_info_2_flg || $report_info->pax_info_3_flg): ?> <tr> <td class="preview_header"><div class="preview_header_al">#2 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Phone Number ①</div>電話番号 ①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 Phone Number ②</div>電話番号 ②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#2 PNR</div>予約番号</td> <td class="preview_data"><?=HTML::entities($report_info->record_locator_2) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 First Name</div>名前</td> <td class="preview_data"><?=HTML::entities($report_info->firstname_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Last Name</div>苗字</td> <td class="preview_data"><?=HTML::entities($report_info->lastname_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Gender</div>性別</td> <td class="preview_data"><?=HTML::entities($report_info->title_rcd_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Birthday</div>生年月日</td> <td class="preview_data"><?=HTML::entities($report_info->birthday_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Phone Number ①</div>電話番号①</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number1_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 Phone Number ②</div>電話番号②</td> <td class="preview_data"><?=HTML::entities($report_info->phone_number2_3) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">#3 PNR</div>予約番号</td> <td class="preview_data"><?=HTML::entities($report_info->record_locator_3) ?></td> </tr> <?php endif; ?> <tr> <td class="preview_header"><div class="preview_header_al">Phoenix Class</div>Phoenixカテゴリ</td> <td class="preview_data"><?=HTML::entities($report_info->phoenix_class) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Phoenix Memo</div>Phoenixメモ</td> <td class="preview_data"><?=nl2br(HTML::entities($report_info->phoenix_memo)) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Report Status</div>レポートステータス</td> <td class="preview_data"><?=HTML::entities($report_info->report_status_name) ?></td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Created</div>作成日</td> <td class="preview_data"><?=HTML::entities($report_info->create_timestamp) ?> JST</td> </tr> <tr> <td class="preview_header"><div class="preview_header_al">Modified</div>更新日</td> <td class="preview_data"><?=HTML::entities($report_info->update_timestamp) ?> JST</td> </tr> <tr style="border-bottom: 1px solid #ddd;"> <td class="preview_header"><div class="preview_header_al">Reported By</div>起票者</td> <td class="preview_data"><?=HTML::entities($report_info->reported_by) ?></td> </tr> </tbody> </table> <file_sep>/app/views/parts/report/send_mail_area.php <div class="<?= HTML::entities($role_manage_info->send_mail_area_hidden) ?>"> <div class="sendmail clearfix"> <label for="Send Mail" class="label08">Send Mail<br /><span>照会メール送信</span></label> <div class="label08 <?= HTML::entities($role_manage_info->send_mail_creator_hidden) ?>"> <div class="checkbox checkbox-inline"> <input id="send_mail_creator" name="send_mail_creator" type="checkbox" <?php echo(Input::old('send_mail_creator','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="send_mail_creator">Reporter<br />起票者</label> </div> </div> <div class="label08 <?= HTML::entities($role_manage_info->send_mail_administrator_group_hidden) ?>"> <div class="checkbox checkbox-inline"> <input id="send_mail_administrator_group" name="send_mail_administrator_group" type="checkbox" <?php echo(Input::old('send_mail_administrator_group','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="send_mail_administrator_group">Peach Person in charge<br />Peach担当者</label> </div> </div> <div class="label08 <?= HTML::entities($role_manage_info->send_mail_approver_group_hidden) ?>"> <div class="checkbox checkbox-inline"> <input id="send_mail_approver_group" name="send_mail_approver_group" type="checkbox" <?php echo(Input::old('send_mail_approver_group','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="send_mail_approver_group">Approver<br />承認者</label> </div> </div> <div class="label08 <?= HTML::entities($role_manage_info->send_mail_inquiry_from_administrator_group_hidden) ?>"> <div class="checkbox checkbox-inline"> <input id="send_mail_inquiry_from_administrator_group" name="send_mail_inquiry_from_administrator_group" type="checkbox" <?php echo(Input::old('send_mail_inquiry_from_administrator_group','')) === 'on' ? 'checked="checked"' : (count($error_message_list) > 0 ? '' : HTML::entities($role_manage_info->send_mail_inquiry_from_administrator_group_checked)) ?> /> <label for="send_mail_inquiry_from_administrator_group">Inquire From<br />照会元</label> </div> </div> <div class="label08 <?= HTML::entities($role_manage_info->send_mail_inquiry_to_administrator_group_hidden) ?>"> <div class="checkbox checkbox-inline"> <input id="send_mail_inquiry_to_administrator_group" name="send_mail_inquiry_to_administrator_group" type="checkbox" <?php echo(Input::old('send_mail_inquiry_to_administrator_group','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="send_mail_inquiry_to_administrator_group">Inquire To<br />照会先</label> </div> </div> </div> </div><file_sep>/app/views/parts/report/resavation_info_area.php <?php if($report_info->report_class == 1){ ?> <div class="clearfix"> <label for="record_locator" class="label01">#1 PNR<span>予約番号</span></label> <div class="label02"> <input id="record_locator" name="record_locator" type="text" class="form-control" value="<?= HTML::entities(Input::old('record_locator', $report_info->record_locator)) ?>" maxlength="7" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="departure_date" class="label01 datepicker">#1 Flight Date<span>フライト日</span></label> <div class="label02"> <input id="departure_date" name="departure_date" type="text" class="form-control datepicker" value="<?= HTML::entities(Input::old('departure_date', $report_info->departure_date)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="flight_number" class="label01">#1 Flight No<span>便名 ※MMxxxx(ex. MM0001)</span></label> <div class="label02"> <input id="flight_number" name="flight_number" type="text" class="form-control" value="<?= HTML::entities(Input::old('flight_number', $report_info->flight_number)) ?>" maxlength="6" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="row <?= HTML::entities($role_manage_info->reservation_info_button_hidden) ?>"> <div class="col-md-2 text-left" style="margin-left:12px; margin-bottom:15px;"> <button type="button" class="btn btn-lgray btn-xs" data-toggle="collapse" data-target="#collapseResavationInfo"> <span id="resavationInfoIcon" class="glyphicon glyphicon-plus"></span> Reservation Information </button> </div> </div> <div id="collapseResavationInfo" class="collapse"> <div class="clearfix"> <label for="record_locator_2" class="label01">#2 PNR<span>予約番号</span></label> <div class="label02"> <input id="record_locator_2" name="record_locator_2" type="text" class="form-control additional-resavation-info" value="<?= HTML::entities(Input::old('record_locator_2', $report_info->record_locator_2)) ?>" maxlength="7" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="departure_date_2" class="label01 datepicker">#2 Flight Date<span>フライト日</span></label> <div class="label02"> <input id="departure_date_2" name="departure_date_2" type="text" class="form-control additional-resavation-info datepicker" value="<?= HTML::entities(Input::old('departure_date_2', $report_info->departure_date_2)) ?>" maxlength="10" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> <div class="clearfix"> <label for="flight_number_2" class="label01">#2 Flight No<span>便名 ※MMxxxx(ex. MM0001)</span></label> <div class="label02"> <input id="flight_number_2" name="flight_number_2" type="text" class="form-control additional-resavation-info" value="<?= HTML::entities(Input::old('flight_number_2', $report_info->flight_number_2)) ?>" maxlength="6" <?= HTML::entities($role_manage_info->other_input_disabled) ?>/> </div> </div> </div> <?php } ?><file_sep>/app/extentions/HtmlAttributeControl.php <?php /** * HTML属性制御クラス * 画面・レポートステータス・ユーザー権限により属性をコントロールする */ class HtmlAttributeControl{ protected $edit_button_hidden; protected $cancel_button_hidden; protected $save_button_hidden; protected $submit_button_hidden; protected $confirm_button_hidden; protected $close_button_hidden; protected $inquiry_button_hidden; protected $inquiry_save_button_hidden; protected $answer_save_button_hidden; protected $passback_button_hidden; protected $delete_button_hidden; protected $comment_button_hidden; protected $reservation_info_button_hidden; protected $pax_info_button_hidden; protected $send_mail_creator_hidden; protected $send_mail_administrator_group_hidden; protected $send_mail_approver_group_hidden; protected $send_mail_inquiry_from_administrator_group_hidden; protected $send_mail_inquiry_to_administrator_group_hidden; protected $inquire_to_hidden; /** * コンストラクタ */ function __construct() { } protected function __set($key, $value){ $this->$key = $value; } public function __get($key){ return $this->$key; } } <file_sep>/vendor/composer/autoload_classmap.php <?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'AlertController' => $baseDir . '/app/controllers/AlertController.php', 'AuthenAPIController' => $baseDir . '/app/controllers/AuthenAPIController.php', 'BaseController' => $baseDir . '/app/controllers/BaseController.php', 'DatabaseSeeder' => $baseDir . '/app/database/seeds/DatabaseSeeder.php', 'ErrorController' => $baseDir . '/app/controllers/ErrorController.php', 'IlluminateQueueClosure' => $vendorDir . '/laravel/framework/src/Illuminate/Queue/IlluminateQueueClosure.php', 'LoginController' => $baseDir . '/app/controllers/LoginController.php', 'Normalizer' => $vendorDir . '/patchwork/utf8/src/Normalizer.php', 'PreviewController' => $baseDir . '/app/controllers/PreviewController.php', 'PreviewControllerPEACOCK' => $baseDir . '/app/controllers/PreviewControllerPEACOCK.php', 'PreviewControllerPENGUIN' => $baseDir . '/app/controllers/PreviewControllerPENGUIN.php', 'PreviewControllerPEREGRINE' => $baseDir . '/app/controllers/PreviewControllerPEREGRINE.php', 'ReportController' => $baseDir . '/app/controllers/ReportController.php', 'ReportControllerPEACOCK' => $baseDir . '/app/controllers/ReportControllerPEACOCK.php', 'ReportControllerPENGUIN' => $baseDir . '/app/controllers/ReportControllerPENGUIN.php', 'ReportControllerPEREGRINE' => $baseDir . '/app/controllers/ReportControllerPEREGRINE.php', 'SessionHandlerInterface' => $vendorDir . '/symfony/http-foundation/Resources/stubs/SessionHandlerInterface.php', 'TestCase' => $baseDir . '/app/tests/TestCase.php', 'TopController' => $baseDir . '/app/controllers/TopController.php', 'TopControllerPEACOCK' => $baseDir . '/app/controllers/TopControllerPEACOCK.php', 'TopControllerPENGUIN' => $baseDir . '/app/controllers/TopControllerPENGUIN.php', 'TopControllerPEREGRINE' => $baseDir . '/app/controllers/TopControllerPEREGRINE.php', 'User' => $baseDir . '/app/models/User.php', 'Whoops\\Module' => $vendorDir . '/filp/whoops/src/deprecated/Zend/Module.php', 'Whoops\\Provider\\Zend\\ExceptionStrategy' => $vendorDir . '/filp/whoops/src/deprecated/Zend/ExceptionStrategy.php', 'Whoops\\Provider\\Zend\\RouteNotFoundStrategy' => $vendorDir . '/filp/whoops/src/deprecated/Zend/RouteNotFoundStrategy.php', ); <file_sep>/app/extentions/CommonGateway/LdapAuth.php <?php namespace CommonGateway { use Log; use Config; use Exception; /** * LDAP認証クラス. * php.ini の php_ldap.dll のコメントアウトを解除すること * C:\xampp\php\libsasl.ddlをC:\xampp\apache\binに配置 */ class LdapAuth { private $ldapconn; /** * コンストラクタ */ function __construct() { Log::info("LdapAuth new"); } /** * LDAP認証 * @param string $user ユーザーID * @param string $pass パスワード * @return boolean 認証結果 */ public function auth($user, $pass) { $result = false; for($i = 1 ; $i <= Config::get('const.ldap_server_count'); $i++){ try{ $host = Config::get('const.ldap_host_' . $i); $port = Config::get('const.ldap_port_' . $i); // LDAP接続 $this->ldapconn = ldap_connect($host, $port); if($this->ldapconn){ ldap_set_option($this->ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option ($this->ldapconn, LDAP_OPT_REFERRALS, 0); ldap_set_option($this->ldapconn, LDAP_OPT_NETWORK_TIMEOUT, 5); // バインド $ldapbind = ldap_bind($this->ldapconn, Config::get('const.ldap_domain') . $user, $pass); // バインド解除 ldap_unbind($this->ldapconn); $result = true; break; } }catch(Exception $e){ // nop } try{ // 切断 if($this->ldapconn){ ldap_close($this->ldapconn); } }catch(Exception $e){ // nop } } return $result; } } }<file_sep>/app/controllers/AlertController.php <?php /** * アラート設定画面 */ class AlertController extends BaseController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * アラート設定画面表示 */ function anyIndex() { $header_title = '- ' . $this->user->userInfo->report_name; $station_list = $this->getStationList(); $alert_setting = $this->getAlertSetting(); return View::make('alert') // ヘッダーエリア ->nest('parts_common_header', 'parts.common.header', ['header_title' => $header_title . ' Alert', 'login_button_hidden' => '']) // エラーメッセージ表示エリア ->nest('parts_common_error', 'parts.common.error', ['error_message_list' => Session::get('error_message_list')]) ->with('header_title', $header_title) ->with('station_list', $station_list) ->with('alert_setting', $alert_setting); } /** * キャンセル */ function postCancel() { // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), 'アラート設定画面', 'キャンセル', ''); return Redirect::to('/top'); } /** * 保存 */ function postSave() { // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), 'アラート設定画面', '保存', ''); // リクエストパラメータ取得 $timing = Input::get('timing'); $station = Input::get('station'); // ログインID取得 $login_id = $this->user->userInfo->login_id; // エラーチェック if(strlen($timing) == 0 && count($station)) { $this->error_message_list[] = "通知設定を選択してください\n" . "Select the Alert on"; } elseif(strlen($timing) > 0 && count($station) == 0) { $this->error_message_list[] = "空港名を選択してください\n" . "Check the Station(s)"; } if($this->hasError()) { return Redirect::to('/alert') ->with('error_message_list', $this->error_message_list) ->withInput(Input::only('timing','station')); } // トランザクション開始 DB::transaction(function() use ($login_id, $timing, $station) { DB::table('alert_mail_condition') ->where('login_id', $login_id) ->where('report_no', '') ->delete(); if(strlen($timing) > 0) { foreach($station as $val) { DB::table('alert_mail_condition') ->insert([ 'login_id' => $login_id, 'station' => $val, 'alert_timing' => $timing ]); } } }); return Redirect::to('/top'); } /** * 空港名取得 * @return unknown */ function getStationList() { $result = DB::table('mst_system_code') ->distinct() ->select(['code2', 'value2']) ->where('code1', 'Station') ->whereIn('report_class', ['2', '3']) ->orderBy('disp_order') ->get(); return $result; } /** * アラート設定状態取得 */ function getAlertSetting() { $result = DB::table('alert_mail_condition') ->select(['station', 'alert_timing']) ->where('login_id', $this->user->userInfo->login_id) ->where('report_no', '') ->get(); $station = []; foreach($result as $val) { $station[] = $val->station; } $alert_setting = []; if(count($result)) { $alert_setting = [ 'timing' => $result[0]->alert_timing, 'station' => $station ]; } else { $alert_setting = [ 'timing' => Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED'), 'station' => [] ]; } return $alert_setting; } }<file_sep>/app/extentions/RoleManager.php <?php use Illuminate\Support\Facades\Facade; class RoleManager extends Facade { protected static function getFacadeAccessor() { return 'RoleManager'; } }<file_sep>/app/views/parts/common/error.php <div class="row"> <div class="col-md-12"> <?php if(count($error_message_list) > 0){ ?> <div class="alert alert-danger"> <button class="close" data-dismiss="alert">&#215;</button> <ul> <?php foreach($error_message_list as $message) { ?> <li> <?php echo nl2br($message) ?> </li> <?php } ?> </ul> </div> <?php } ?> </div> </div><file_sep>/app/views/parts/report/remarks_area.php <label for="free_comment" class="label01">Remarks<span>備考</span></label> <div class="label04"> <textarea id="free_comment" name="free_comment" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->remarks_disabled) ?> maxlength="1500"><?= HTML::entities(Input::old('free_comment', $report_info->free_comment)) ?></textarea> </div> <file_sep>/app/controllers/ReportControllerPENGUIN.php <?php /** * レポート画面(PENGIN) */ class ReportControllerPENGUIN extends ReportController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see ReportController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_REPORT_INFO_PENGUIN'),['1','1', 'Sub Category' ,$report_no, '1']); } /** * 空のレポート情報取得 * @see ReportController::getEmptyReportInfo() */ protected function getEmptyReportInfo($report_class){ $emptyData = new stdClass(); $emptyData->report_no = ''; $emptyData->report_seq = ''; $emptyData->report_class = $report_class; $emptyData->own_department_only_flag = ''; $emptyData->has_additional_pax_info = 0; $emptyData->has_additional_reservation_info = 0; $emptyData->report_status_name = ''; $emptyData->report_status = Config::get('const.REPORT_STATUS.CREATED'); $emptyData->day_of_week = ''; $emptyData->reported_by = ''; $emptyData->report_title = ''; $emptyData->contents = ''; $emptyData->confirmor_id = ''; $emptyData->approver_id = ''; $emptyData->peacock_inquiry_status = ''; $emptyData->peacock_inquiry_timestamp = ''; $emptyData->penguin_inquiry_status = ''; $emptyData->penguin_inquiry_timestamp = ''; $emptyData->peregrine_inquiry_status = ''; $emptyData->peregrine_inquiry_timestamp = ''; $emptyData->old_report_no = ''; $emptyData->related_report_no = ''; $emptyData->related_report_class = ''; $emptyData->related_report_no_2 = ''; $emptyData->related_report_class_2 = ''; $emptyData->firstname = ''; $emptyData->lastname = ''; $emptyData->title_rcd = ''; $emptyData->birthday = ''; $emptyData->phone_number1 = ''; $emptyData->phone_number2 = ''; $emptyData->record_locator = ''; $emptyData->firstname_2 = ''; $emptyData->lastname_2 = ''; $emptyData->title_rcd_2 = ''; $emptyData->birthday_2 = ''; $emptyData->phone_number1_2 = ''; $emptyData->phone_number2_2 = ''; $emptyData->record_locator_2 = ''; $emptyData->firstname_3 = ''; $emptyData->lastname_3 = ''; $emptyData->title_rcd_3 = ''; $emptyData->birthday_3 = ''; $emptyData->phone_number1_3 = ''; $emptyData->phone_number2_3 = ''; $emptyData->record_locator_3 = ''; $emptyData->phoenix_class = ''; $emptyData->phoenix_memo = ''; $emptyData->free_comment = ''; $emptyData->delete_flag = ''; $emptyData->create_user_id = ''; $emptyData->create_timestamp = ''; $emptyData->update_user_id = ''; $emptyData->update_timestamp = ''; $emptyData->station = $this->user->getStation(); $emptyData->line = ''; $emptyData->first_contatct_date = ''; $emptyData->first_contact_time = ''; $emptyData->last_contact_date = ''; $emptyData->last_contact_time = ''; $emptyData->category = ''; $emptyData->sub_category = ''; $emptyData->correspondence = ''; $emptyData->departure_date = ''; $emptyData->flight_number = 'MM'; $emptyData->departure_date_2 = ''; $emptyData->flight_number_2 = ''; $emptyData->day_of_week = ''; $emptyData->sub_category_other = ''; return $emptyData; } /** * レポート個別情報取得 * @see ReportController::getIndividualsInfo() */ protected function getIndividualsInfo($report_no, $report_class){ // Stationリスト取得 $station_list = SystemCodeManager::getStation($report_class); // Lineリスト取得 $line_list = SystemCodeManager::getLine($report_class); // カテゴリリスト取得 $category_list = SystemCodeManager::getCategory($report_class); // サブカテゴリリスト取得 $sub_categoly_list = SystemCodeManager::getSubCategory($report_class); return [ 'station_list' => $station_list, 'line_list' => $line_list, 'category_list' => $category_list, 'sub_category_list' => $sub_categoly_list ]; } /** * レポート登録 * @see ReportController::insertReport() */ protected function insertReport($status){ $_mode = Input::get('_mode'); $timestamp = DateUtil::getCurrentTimestamp(); $report_class = Input::get('_report_class'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $peacock_inquiry_status = (Input::get('peacock_inquiry_status') === 'on' ? '1' : '0'); $peacock_inquiry_timestamp = (Input::get('peacock_inquiry_status') === 'on' ? $timestamp : null); $penguin_inquiry_status = (Input::get('penguin_inquiry_status') === 'on' ? '1' : '0'); $penguin_inquiry_timestamp = (Input::get('penguin_inquiry_status') === 'on' ? $timestamp :null); $peregrine_inquiry_status = (Input::get('peregrine_inquiry_status') === 'on' ? '1' : '0'); $peregrine_inquiry_timestamp = (Input::get('peregrine_inquiry_status') === 'on' ? $timestamp : null); $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $delete_flag = '0'; $create_user_id = $this->user->getLoginId(); $create_timestamp = $timestamp; $update_user_id = $this->user->getLoginId(); $update_timestamp = $timestamp; $station = Input::get('station'); $line = Input::get('line'); $first_contatct_date = Input::get('first_contatct_date'); $first_contact_time = Input::get('first_contact_time'); $last_contact_date = Input::get('last_contact_date'); $last_contact_time = Input::get('last_contact_time'); $category = Input::get('category'); $sub_category = Input::get('sub_category'); if(!$sub_category){ $sub_category = Input::get('sub_category_other'); } $correspondence = Input::get('correspondence'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $departure_date_2 = Input::get('departure_date_2'); $flight_number_2 = Input::get('flight_number_2'); $day_of_week = Input::get('day_of_week'); // 必須入力チェック if(CommonCheckLogic::isEmpty($station)){ $this->error_message_list[] = 'Station' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($first_contatct_date, true) ){ $this->error_message_list[] = 'First Contact' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($last_contact_date, true) ){ $this->error_message_list[] = 'Last Contact' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date, true) ){ $this->error_message_list[] = '#1 Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($departure_date_2, true) ){ $this->error_message_list[] = '#2 Flight Date' . Config::get('message.DATE_FORMAT_ERROR'); } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = '#1 Flight NoはMM+4桁の数字で入力してください。'; } if(! CommonCheckLogic::checkFlightNumber($flight_number_2, true) ){ $this->error_message_list[] = '#2 Flight NoはMM+4桁の数字で入力してください。'; } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // エラーがある場合 if($this->hasError()){ return null; } $result = DataManager::getReportNoAndSeq($report_class, $station, $first_contatct_date); $report_no = $result[0]; $report_seq = $result[1]; $data =[ $report_no, $report_seq, $report_class, $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $peacock_inquiry_status, $peacock_inquiry_timestamp, $penguin_inquiry_status, $penguin_inquiry_timestamp, $peregrine_inquiry_status, $peregrine_inquiry_timestamp, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $delete_flag, $create_user_id, $create_timestamp, $update_user_id, $update_timestamp ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報登録 while(DataManager::insertWithCheckDuplicate(Config::get('sql.INSERT_REPORT_BASIC_INFO'), $data)){ $result = DataManager::getReportNoAndSeq($report_class, $report_type, $first_contatct_date); $report_no = $result[0]; $report_seq = $result[1]; $data[0] = $report_no; $data[1] = $report_seq; } $data = [ $report_no, $station, $line, $first_contatct_date, $first_contact_time, $last_contact_date, $last_contact_time, $category, $sub_category, $correspondence, $departure_date, $flight_number, $departure_date_2, $flight_number_2, $day_of_week ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報登録 DB::insert(Config::get('sql.INSERT_REPORT_PENGUIN'), $data); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); return $report_no; } /** * レポート更新 * @see ReportController::updateReport() */ protected function updateReport($status, $is_passback){ $_mode = Input::get('_mode'); $modified = Input::get('_modified'); $timestamp = DateUtil::getCurrentTimestamp(); $report_no = Input::get('_report_no'); $own_department_only_flag = (Input::get('own_department_only_flag') === 'on' ? '1' : '0'); $report_status = $status; $day_of_week = null; $reported_by = Input::get('reported_by');; $report_title = Input::get('report_title'); $contents = Input::get('contents'); $confirmor_id = null; $approver_id = null; $old_report_no = Input::get('old_report_no'); $related_report_no = Input::get('related_report_no'); $related_report_no_2 = Input::get('related_report_no_2'); $firstname = Input::get('firstname'); $lastname = Input::get('lastname'); $title_rcd = Input::get('title_rcd'); $birthday = Input::get('birthday'); $phone_number1 = Input::get('phone_number1'); $phone_number2 = Input::get('phone_number2'); $record_locator = Input::get('record_locator'); $firstname_2 = Input::get('firstname_2'); $lastname_2 = Input::get('lastname_2'); $title_rcd_2 = Input::get('title_rcd_2'); $birthday_2 = Input::get('birthday_2'); $phone_number1_2 = Input::get('phone_number1_2'); $phone_number2_2 = Input::get('phone_number2_2'); $record_locator_2 = Input::get('record_locator_2'); $firstname_3 = Input::get('firstname_3'); $lastname_3 = Input::get('lastname_3'); $title_rcd_3 = Input::get('title_rcd_3'); $birthday_3 = Input::get('birthday_3'); $phone_number1_3 = Input::get('phone_number1_3'); $phone_number2_3 = Input::get('phone_number2_3'); $record_locator_3 = Input::get('record_locator_3'); $phoenix_class = Input::get('phoenix_class'); $phoenix_memo = Input::get('phoenix_memo'); $free_comment = Input::get('free_comment'); $create_user_id = $this->user->userInfo->login_id; $create_timestamp = $timestamp; $update_user_id = $this->user->userInfo->login_id; $update_timestamp = $timestamp; $station = Input::get('station'); $line = Input::get('line'); $first_contatct_date = Input::get('first_contatct_date'); $first_contact_time = Input::get('first_contact_time'); $last_contact_date = Input::get('last_contact_date'); $last_contact_time = Input::get('last_contact_time'); $category = Input::get('category'); $sub_category = Input::get('sub_category'); if(!$sub_category){ $sub_category = Input::get('sub_category_other'); } $correspondence = Input::get('correspondence'); $departure_date = Input::get('departure_date'); $flight_number = Input::get('flight_number'); $departure_date_2 = Input::get('departure_date_2'); $flight_number_2 = Input::get('flight_number_2'); $day_of_week = Input::get('day_of_week'); // 変更かつ承認済みの場合 if($_mode === 'edit' && $status == Config::get('const.REPORT_STATUS.CLOSE')){ $data =[ $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO_ONLY_REMARKS'), $data) == 0){ return false; } }else{ // 必須入力チェック if(CommonCheckLogic::isEmpty($station)){ $this->error_message_list[] = 'Station' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($reported_by)){ $this->error_message_list[] = 'Report by' . Config::get('message.REQUIRED_ERROR'); } if(CommonCheckLogic::isEmpty($report_title)){ $this->error_message_list[] = 'Report Title' . Config::get('message.REQUIRED_ERROR'); } // 日付フォーマットチェック if(! CommonCheckLogic::isDate($birthday, true) ){ $this->error_message_list[] = '#1 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_2, true) ){ $this->error_message_list[] = '#2 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } if(! CommonCheckLogic::isDate($birthday_3, true) ){ $this->error_message_list[] = '#3 Birthday' . Config::get('message.DATE_FORMAT_ERROR'); } // MM + 数値チェック if(! CommonCheckLogic::checkFlightNumber($flight_number, true) ){ $this->error_message_list[] = '#1 Flight NoはMM+4桁の数字で入力してください。'; } if(! CommonCheckLogic::checkFlightNumber($flight_number_2, true) ){ $this->error_message_list[] = '#2 Flight NoはMM+4桁の数字で入力してください。'; } // 関連レポート存在チェック if( ! CommonCheckLogic::isExsistsReport($related_report_no, true)){ $this->error_message_list[] = '#1 Related Reportが存在しません。'; } if( ! CommonCheckLogic::isExsistsReport($related_report_no_2, true)){ $this->error_message_list[] = '#2 Related Reportが存在しません。'; } // メール送信先チェック parent::checkSendMail($is_passback); // エラーがある場合 if($this->hasError()){ return true; } // セッションから現在のレポート情報を取得 $old_report_info = $this->getSessionReportInfo(); // 差戻しの場合 if($is_passback){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $old_report_info->approver_id; }else{ // 確認処理の場合 if($status == Config::get('const.REPORT_STATUS.CONFIRMED')){ $confirmor_id = $update_user_id; $approver_id = $old_report_info->approver_id; } // 承認処理の場合 if($status == Config::get('const.REPORT_STATUS.CLOSE')){ $confirmor_id = $old_report_info->confirmor_id; $approver_id = $update_user_id; } } $data =[ $own_department_only_flag, $report_status, $day_of_week, $reported_by, $report_title, $contents, $confirmor_id, $approver_id, $old_report_no, $related_report_no, $related_report_no_2, $firstname, $lastname, $title_rcd, $birthday, $phone_number1, $phone_number2, $record_locator, $firstname_2, $lastname_2, $title_rcd_2, $birthday_2, $phone_number1_2, $phone_number2_2, $record_locator_2, $firstname_3, $lastname_3, $title_rcd_3, $birthday_3, $phone_number1_3, $phone_number2_3, $record_locator_3, $phoenix_class, $phoenix_memo, $free_comment, $update_user_id, $update_timestamp, $report_no, $modified ]; $data = DataManager::replaceEmptyToNull($data); // レポート基本情報更新 if(DB::update(Config::get('sql.UPDATE_REPORT_BASIC_INFO'), $data) == 0){ return false; } $data = [ $station, $line, $first_contatct_date, $first_contact_time, $last_contact_date, $last_contact_time, $category, $sub_category, $correspondence, $departure_date, $flight_number, $departure_date_2, $flight_number_2, $day_of_week, $report_no ]; $data = DataManager::replaceEmptyToNull($data); // レポート固有情報更新 DB::update(Config::get('sql.UPDATE_REPORT_PENGUIN'), $data); // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // 添付ファイル削除 DataManager::deleteAttachFile($report_no); } return true; } } <file_sep>/app/views/parts/top/new_report_peacock.php <div class="row"> <div class="col-md-4 text-left"> <div class="row"> <div class="col-md-1 pull-left"> <span style="background-color: #CE019E;font-size:150%">&nbsp;</span> </div> <div class="col-md-10 text-left"> <span style="font-size:150%"><strong>PEACOCK</strong></span> </div> </div> </div> </div> <div class="row row-margin-bottom-80"> <div class="col-md-12"> <table id="newReportTable" class="table table-bordered table-hover" border="1" cellpadding="2" bordercolor="#000000"> <thead> <tr class="gray"> <th>Report Status</th> <th>Report No</th> <th>Report Title</th> <th>Flight Date</th> <th>Flight No</th> <th>Ship No</th> <th>Modified</th> <th>Inquiry Status</th> <th>Preview</th> </tr> </thead> <tbody> <?php foreach($new_report_list as $data) { ?> <tr> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->report_status_name) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->report_no) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->report_title) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->departure_date) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->flight_number) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->ship_no) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->update_timestamp) ?></td> <td onclick="selectReport(document.forms.mainForm, '/p/chirp/top/select', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><?= HTML::entities($data->inquiry_status) ?></td> <td><button type="button" class="btn btn-lgray center-block btn-xs" onclick="selectPreview(document.forms.mainForm, '/p/chirp/top/preview', '<?= HTML::entities($data->report_class) ?>', '<?= HTML::entities($data->report_no) ?>')"><span id="PreviewIcon" class="glyphicon glyphicon-zoom-in"></span></button></td> </tr> <?php } ?> </tbody> </table> </div> <div class="col-md-12"> <div class="form-group"> <?php foreach($button_list as $data) { ?> <button type="button" class="btn btn-pink" onclick="addReport(document.forms.mainForm, '/p/chirp/top/add', <?= HTML::entities($data['code']) ?>)"><?= HTML::entities($data['value']) ?></button> <?php } ?> </div> </div> </div> <file_sep>/app/controllers/ReportController.php <?php /** * レポート画面 */ class ReportController extends BaseController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート画面表示 */ function getIndex() { $mode = Session::get('_mode'); $report_no = Session::get('_report_no'); $report_class = Session::get('_report_class'); $modified = Session::get('_modified'); $report_info; $attach_file_list; $gender_list; $phoenix_class_list; $related_report_list; $individuals_info; // 関連レポート表示またはリダイレクトの場合 if($mode != 'relation' && Session::has('SESSION_KEY_REPORT_DATA')){ // セッションから情報取得 $data = Session::get('SESSION_KEY_REPORT_DATA'); $report_info = $data['report_info']; $attach_file_list = $data['attach_file_list']; $gender_list = $data['gender_list']; $phoenix_class_list = $data['phoenix_class_list']; $related_report_list = $data['related_report_list']; $individuals_info = $data['individuals_info']; // 初期表示の場合 }else{ // レポート情報取得 if($report_no){ $report_info = $this->getReportInfo($report_no); }else{ $report_info = $this->getEmptyReportInfo($report_class); } // 添付ファイル一覧取得 $attach_file_list = $this->getAttacheFileList($report_no); // 性別リスト取得 $gender_list = SystemCodeManager::getGender(); // Phoenix class取得 $phoenix_class_list = SystemCodeManager::getPhoenixClass($report_class); // 関連レポート取得 $related_report_list = $this->getRelatedReportList($report_info); // レポート個別情報取得 $individuals_info = $this->getIndividualsInfo($report_no, $report_class); $data = [ 'report_info' => $report_info, 'attach_file_list' => $attach_file_list, 'gender_list' => $gender_list, 'phoenix_class_list' => $phoenix_class_list, 'related_report_list' => $related_report_list, 'individuals_info' => $individuals_info ]; if($mode != 'relation'){ Session::put('SESSION_KEY_REPORT_DATA', $data); }else{ Session::put('SESSION_KEY_RELATION_REPORT_DATA', $data); } } // 権限情報取得 $role_manage_info = DataManager::getRoleManageinfo($mode, $this->user->userInfo->user_role, $report_info->report_status); // レポート個別アラート設定取得 $report_alert = DataManager::isReportAlert($this->user->userInfo->login_id, $report_no); $individuals_data = [ 'report_info' => $report_info, 'role_manage_info' => $role_manage_info ]; foreach ($individuals_info as $key => $value){ $individuals_data[$key] = $value; } return View::make('report') // ヘッダーエリア ->nest('parts_common_header', 'parts.common.header', ['header_title' => '- ' . Config::get('const.REPORT_CLASS_NAME')[$report_class], 'login_button_hidden' => '']) // エラーメッセージ表示エリア ->nest('parts_common_error', 'parts.common.error', ['error_message_list' => Session::get('error_message_list')]) // レポート個別アラートボタンエリア ->nest('parts_report_alert_button', 'parts.report.report_alert_button', ['report_alert' => $report_alert, 'role_manage_info' => $role_manage_info]) // 設定エリア ->nest('parts_report_config_area', 'parts.report.config_area', ['report_info' => $report_info, 'role_manage_info' => $role_manage_info]) // レポートステータスエリア ->nest('parts_report_status_area', 'parts.report.report_status_area', ['report_info' => $report_info]) // レポート個別エリア ->nest('parts_report_individuals_area', Config::get('const.reportViews')[$report_class], $individuals_data) // フライト個別エリア ->nest('parts_flight_info_area', str_replace('report_', 'flight_info_', Config::get('const.reportViews')[$report_class]), $individuals_data) // レポート定義個別エリア ->nest('parts_report_definition_area', str_replace('report_', 'report_definition_', Config::get('const.reportViews')[$report_class]), $individuals_data) // 添付ファイルエリア ->nest('parts_report_attached_file_area', 'parts.report.attached_file_area', [ 'attach_file_list' => $attach_file_list, 'role_manage_info' => $role_manage_info]) // 照会エリア ->nest('parts_report_inquiry_area', 'parts.report.inquiry_area', ['report_info' => $report_info, '_mode' => $mode, 'role_manage_info' => $role_manage_info]) // 関連レポートエリア ->nest('parts_report_related_report_area', 'parts.report.related_report_area', ['_mode' => $mode, 'report_info' => $report_info, 'role_manage_info' => $role_manage_info, 'related_report_list' => $related_report_list]) // 備考欄エリア ->nest('parts_remarks_area', 'parts.report.remarks_area', ['_mode' => $mode, 'report_info' => $report_info, 'role_manage_info' => $role_manage_info]) // 客様情報エリア ->nest('parts_report_pax_info_area', 'parts.report.pax_info_area', ['report_info' => $report_info, 'gender_list' => $gender_list, 'role_manage_info' => $role_manage_info]) // 予約情報エリア ->nest('parts_resavation_info_area', 'parts.report.resavation_info_area', ['report_info' => $report_info, 'gender_list' => $gender_list, 'role_manage_info' => $role_manage_info]) // Phoenixエリア ->nest('parts_report_phoenix_area', 'parts.report.phoenix_area', ['report_info' => $report_info, 'phoenix_class_list' => $phoenix_class_list, 'role_manage_info' => $role_manage_info]) // メール送信先選択エリア ->nest('parts_report_send_mail_area', 'parts.report.send_mail_area', ['role_manage_info' => $role_manage_info, 'error_message_list' => Session::get('error_message_list')]) // ボタンエリア ->nest('parts_report_button_area', 'parts.report.button_area', ['role_manage_info' => $role_manage_info]) ->with('header_title', '- ' . $this->user->userInfo->report_name) ->with('_mode', $mode) ->with('error_message_list',Session::get('error_message_list')) ->with('role_manage_info', $role_manage_info) ->with('report_info', $report_info); } /** * 添付ファイル一覧取得 * @param unknown $report_no */ function getAttacheFileList($report_no){ return DB::select(Config::get('sql.SELECT_REPORT_ATTACHE_FILE_LIST'), [$report_no]); } /** * 添付ファイルダウンロード */ function postDownload(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $file_seq = Input::get('_file_seq'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '添付ファイルダウンロード:' . $file_seq, $report_no); $result = DB::selectOne(Config::get('sql.SELECT_REPORT_ATTACHE_FILE'), [$report_no, $file_seq]); if(!$result) { $this->error_message_list[] = '該当ファイルは削除されています。'; } // $ua = $_SERVER['HTTP_USER_AGENT']; // if (strstr($ua, 'MSIE') && !strstr($ua, 'Opera')) { // $file_name = str_replace( ' ', '_', $file_name ); // log::info($file_name); // } else { // $file_name = '"' . $file_name . '"'; // } // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } $file_name = $result->file_name; // レスポンスヘッダに「Transfer-Encoding=chunked」が設定されるので、「Content-Length」は設定しない return Response::make($result->file, 200) ->header('Content-Type', 'application/octet-stream') // ->header('Content-disposition', 'attachment; filename=' . urlencode($result->file_name)); // ->header('Content-disposition', 'attachment; filename=' . rawurlencode($result->file_name)); ->header('Content-disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($result->file_name)); // ->header('Content-disposition', 'attachment; filename=' . $file_name); } /** * カテゴリ選択 */ function postChange(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_type = Input::get('report_type'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); // カテゴリ取得 $category_list = SystemCodeManager::getCategory($report_class, $report_type); // 権限情報取得 $role_manage_info = DataManager::getRoleManageinfo($mode, $this->user->userInfo->user_role, $report_status); if($mode != 'relation'){ $report_info = $this->getSessionReportInfo(); }else{ $report_info = $this->getSessionRelationReportInfo(); } if($mode != 'relation'){ $select_categoly_info = $this->getSessionIndividualsInfo()['select_categoly_info']; }else{ $select_categoly_info = $this->getSessionRelationIndividualsInfo()['select_categoly_info']; } return View::make('parts.report.category') ->with('category_option', $report_type) ->with('category_list', $category_list) ->with('report_info', $report_info) ->with('select_categoly_info', $select_categoly_info) ->with('role_manage_info', $role_manage_info); } /** * 変更ボタン押下時の処理 */ function postEdit(){ $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $modified = Input::get('_modified'); $report_status = Input::get('_report_status'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '変更', $report_no); return Redirect::to('/report') ->with('_mode', Config::get('const.EDIT_MODE_OF_STATUS')[$report_status]) ->with('_report_no', $report_no) ->with('_report_class', $report_class); } /** * キャンセルボタン押下時の処理 */ function postCancel(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], 'キャンセル', $report_no); if($mode == 'relation'){ $data = Session::pull('SESSION_KEY_PREV_REPORT_PARAM'); return Redirect::to('/report') ->with('_mode', $data['mode']) ->with('_report_no', $data['report_no']) ->with('_report_class', $data['report_class']); } return Redirect::to('/top'); } /** * 保存ボタン押下時の処理 */ function postSave(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '保存', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { if($report_no){ $status = $report_status; // レポート更新 if(! $this->updateReport($status, false)){ $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); } }else{ // レポート登録 $this->insertReport(Config::get('const.REPORT_STATUS.CREATED')); } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } elseif($report_status == Config::get('const.REPORT_STATUS.CLOSE')) { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 提出ボタン押下時の処理 */ function postSubmit(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '提出', $report_no); DB::transaction(function() use ($mode,&$report_no,$report_class,&$report_status,$modified) { if($report_no){ switch($report_status) { case Config::get('const.REPORT_STATUS.CREATED'): $report_status = Config::get('const.REPORT_STATUS.SUBMITTED'); break; case Config::get('const.REPORT_STATUS.PASSBACK_SUBMITTED'): $report_status = Config::get('const.REPORT_STATUS.RESUBMIT'); break; } // レポート更新 if( ! $this->updateReport($report_status,false)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.Submit')); } } }else{ // レポート登録 $report_status = Config::get('const.REPORT_STATUS.SUBMITTED'); $new_report_no = $this->insertReport($report_status); // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($new_report_no, $report_class, Config::get('const.MAIL_KBN.Submit')); } $report_no = $new_report_no; } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { if($report_status == Config::get('const.REPORT_STATUS.SUBMITTED')) { $alert_timing = NULL; $mail_kbn = Config::get('const.MAIL_KBN.AlertCreated'); } else { $alert_timing = Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED'); $mail_kbn = Config::get('const.MAIL_KBN.AlertUpdated'); } $user_list = $this->getAlertUserList($report_no, $alert_timing); $this->alertMail($report_no, $user_list, $mail_kbn); } return Redirect::to('/top'); } /** * 関連レポート選択時の処理 */ function postRelatedReport(){ // 呼び出し元レポート情報をセッションに格納 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '関連レポート選択', $report_no); $data =[ 'mode' => $mode, 'report_no' => $report_no, 'report_class' => $report_class, ]; Session::put('SESSION_KEY_PREV_REPORT_PARAM', $data); // 関連レポート情報取得キー $related_report_no = Input::get('related_report_no'); $related_report_class = Input::get('related_report_class'); $checkAccessControlResult = DataManager::checkAccessControl($related_report_no); // 参照NGの場合 if( ! $checkAccessControlResult->result_code ){ $this->error_message_list[] = $checkAccessControlResult->error_message; return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } return Redirect::to('/report') ->with('_mode', 'relation') ->with('_report_no',$related_report_no) ->with('_report_class',$related_report_class); } /** * 確認ボタン押下時の処理 */ function postConfirm(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '確認', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { if($report_no){ switch($report_status) { case Config::get('const.REPORT_STATUS.SUBMITTED'): case Config::get('const.REPORT_STATUS.RESUBMIT'): $report_status = Config::get('const.REPORT_STATUS.CONFIRMED'); break; case Config::get('const.REPORT_STATUS.PASSBACK_CONFIRMED'): $report_status = Config::get('const.REPORT_STATUS.RECONFIRM'); break; } // レポート更新 if(! $this->updateReport($report_status,false)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.Confirm')); } } } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 承認ボタン押下時の処理 */ function postClose(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '承認', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { if($report_no){ // レポート更新 if( ! $this->updateReport(Config::get('const.REPORT_STATUS.CLOSE'),false)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.Close')); } } } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 照会入力ボタン押下時の処理 */ function postInquiry(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '照会入力', $report_no); return Redirect::to('/report') ->with('_mode', 'inquiry') ->with('_report_no', $report_no) ->with('_report_class', $report_class); } /** * 照会実施ボタン押下時の処理 */ function postInquirySave(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '照会実施', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { $param_names = [ 'PEACOCK' => ['penguin_inquiry_status','peregrine_inquiry_status','penguin_inquiry_timestamp','peregrine_inquiry_timestamp'], 'PENGUIN' => ['peregrine_inquiry_status','peacock_inquiry_status','peregrine_inquiry_timestamp','peacock_inquiry_timestamp'], 'PEREGRINE' => ['penguin_inquiry_status','peacock_inquiry_status','penguin_inquiry_timestamp','peacock_inquiry_timestamp'] ]; $parame = $param_names[$this->user->userInfo->report_name]; $inquiry_status1 = (Input::get($parame[0]) === 'on' ? Config::get('const.INQUIRY_STATUS.INQUIRY') : null); $inquiry_status2 = (Input::get($parame[1]) === 'on' ? Config::get('const.INQUIRY_STATUS.INQUIRY') : null); if( CommonCheckLogic::isEmpty($inquiry_status1) && CommonCheckLogic::isEmpty($inquiry_status2)){ $this->error_message_list[] = '照会先が選択されていません'; }else{ // セッションから現在のレポート情報を取得 $report_info = (array)$this->getSessionReportInfo(); $old_inquiry_status1 = $report_info[$parame[0]]; $old_inquiry_status2 = $report_info[$parame[1]]; $old_inquiry_timestamp1 = $report_info[$parame[2]]; $old_inquiry_timestamp2 = $report_info[$parame[3]]; $timestamp = DateUtil::getCurrentTimestamp(); $inquiry_timestamp1 = $timestamp; $inquiry_timestamp2 = $timestamp; // チェックされていない場合は現在の値で更新 if(CommonCheckLogic::isEmpty($inquiry_status1)){ $inquiry_status1 = $old_inquiry_status1; $inquiry_timestamp1 = $old_inquiry_timestamp1; } // チェックされていない場合は現在の値で更新 if(CommonCheckLogic::isEmpty($inquiry_status2)){ $inquiry_status2 = $old_inquiry_status2; $inquiry_timestamp2 = $old_inquiry_timestamp2; } $data = [ $inquiry_status1, $inquiry_timestamp1, $inquiry_status2, $inquiry_timestamp2, $this->user->userInfo->login_id, $timestamp, $report_no, $modified ]; if($report_no){ // レポート更新 if( ! DB::update(Config::get('sql.EXECUTE_INQUIRY.' . $this->user->userInfo->report_name),$data)){ $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.InquirySave')); } } } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 回答ボタン押下時の処理 */ function postAnswerToInquiry(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '回答', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { if($report_no){ $timestamp = DateUtil::getCurrentTimestamp(); $data = [ Config::get('const.INQUIRY_STATUS')['ANSWER'], $timestamp, $this->user->userInfo->login_id, $timestamp, $report_no, $modified ]; // レポート更新 if( ! DB::update(Config::get('sql.EXECUTE_ANSWER_TO_INQUIRY')[$this->user->userInfo->report_name],$data)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // 添付ファイル登録 DataManager::saveAttachFile($report_no, $timestamp); // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.AnswerToInquiry')); } } } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 回答閲覧済ボタン押下(Ajax) */ function postAnswerRead() { // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '回答閲覧済', $report_no); $modified = DB::transaction(function() use ($mode,$report_no,$report_class,$modified) { if($report_no){ $param_names = [ 'PEACOCK' => ['penguin_inquiry_status','peregrine_inquiry_status','penguin_inquiry_timestamp','peregrine_inquiry_timestamp'], 'PENGUIN' => ['peregrine_inquiry_status','peacock_inquiry_status','peregrine_inquiry_timestamp','peacock_inquiry_timestamp'], 'PEREGRINE' => ['penguin_inquiry_status','peacock_inquiry_status','penguin_inquiry_timestamp','peacock_inquiry_timestamp'] ]; $parame = $param_names[$this->user->userInfo->report_name]; // セッションから現在のレポート情報を取得 $report_info = (array)$this->getSessionReportInfo(); $old_inquiry_status1 = $report_info[$parame[0]]; $old_inquiry_status2 = $report_info[$parame[1]]; $old_inquiry_timestamp1 = $report_info[$parame[2]]; $old_inquiry_timestamp2 = $report_info[$parame[3]]; $timestamp = DateUtil::getCurrentTimestamp(); $inquiry_timestamp1 = $old_inquiry_timestamp1; $inquiry_timestamp2 = $old_inquiry_timestamp2; $inquiry_status1 = $old_inquiry_status1; $inquiry_status2 = $old_inquiry_status2; // 回答済みのもののみ回答閲覧済に変更する if($inquiry_status1 == Config::get('const.INQUIRY_STATUS')['ANSWER']) { $inquiry_status1 = Config::get('const.INQUIRY_STATUS')['ANSWER_READ']; $inquiry_timestamp1 = $timestamp; } if($inquiry_status2 == Config::get('const.INQUIRY_STATUS')['ANSWER']) { $inquiry_status2 = Config::get('const.INQUIRY_STATUS')['ANSWER_READ']; $inquiry_timestamp2 = $timestamp; } $data = [ $inquiry_status1, $inquiry_timestamp1, $inquiry_status2, $inquiry_timestamp2, $this->user->userInfo->login_id, $timestamp, $report_no, $modified ]; // レポート更新 if( ! DB::update(Config::get('sql.EXECUTE_INQUIRY')[$this->user->userInfo->report_name],$data)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // 添付ファイル登録: 2016/4/5 不要ではあるが意図が不明である為コメント //DataManager::saveAttachFile($report_no, $timestamp); // エラーがない場合 if( ! $this->hasError()){ // セッションから情報取得 $data = Session::get('SESSION_KEY_REPORT_DATA'); $data['report_info']->update_timestamp = $timestamp; Session::put('SESSION_KEY_REPORT_DATA', $data); return $timestamp; // メール送信 //$this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.AnswerToInquiry')); } } } }); // エラーがない場合 if(!$this->hasError()){ $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); return str_replace('-', '/', $modified); } // 2016/04/05 エラー時返却値追加 return "0"; } protected function executeAnswerToInquery(){ throw new Exception('未実装'); } /** * 差戻ボタン押下時の処理 */ function postPassback(){ $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '差戻し', $report_no); DB::transaction(function() use ($mode,$report_no,$report_class,$report_status,$modified) { if($report_no){ // レポート更新 switch($report_status) { case Config::get('const.REPORT_STATUS.SUBMITTED'): case Config::get('const.REPORT_STATUS.RESUBMIT'): case Config::get('const.REPORT_STATUS.PASSBACK_CONFIRMED'): $report_status = Config::get('const.REPORT_STATUS.PASSBACK_SUBMITTED'); break; case Config::get('const.REPORT_STATUS.CONFIRMED'): case Config::get('const.REPORT_STATUS.RECONFIRM'): $report_status = Config::get('const.REPORT_STATUS.PASSBACK_CONFIRMED'); break; } if( ! $this->updateReport($report_status, true)){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); }else{ // エラーがない場合 if( ! $this->hasError()){ // メール送信 $this->sendMail($report_no, $report_class, Config::get('const.MAIL_KBN.Passback')); } } } }); // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } else { $user_list = $this->getAlertUserList($report_no, Config::get('const.ALERT_MAIL_TIMING.CREATED_AND_UPDATED')); $this->alertMail($report_no, $user_list, Config::get('const.MAIL_KBN.AlertUpdated')); } return Redirect::to('/top'); } /** * 削除ボタン押下時の処理 */ function postDelete(){ // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_no = Input::get('_report_no'); $report_class = Input::get('_report_class'); $report_status = Input::get('_report_status'); $modified = Input::get('_modified'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], '削除', $report_no); if($report_no){ // レポート更新 if( ! DB::update( Config::get('sql.LOGICAL_DELETE_REPORT_BASIC_INFO'), [ '1', $this->user->userInfo->login_id, DateUtil::getCurrentTimestamp(), $report_no, $modified ])){ // 排他エラー $this->error_message_list[] = Config::get('message.EXCLUSIVE_ERROR'); } } // エラーがある場合 if($this->hasError()){ return Redirect::to('/report') ->with('error_message_list', $this->error_message_list) ->with('_mode',$mode) ->with('_report_no',$report_no) ->with('_report_class',$report_class) ->with('_modified',$modified) ->withInput(Input::all()); } return Redirect::to('/top'); } /** * コメント追加ボタン押下時の処理(AJAX) */ function postAddComment(){ // リクエストパラメータ取得 $report_no = Input::get('modal_report_no'); $comment = Input::get('modal_comment'); $author = Input::get('modal_author'); $report_class = input::get('_report_class'); $mode = input::get('_mode'); $timestamp = date("Y-m-d H:i:s"); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], 'コメント追加', $report_no); $data = [ $report_no, $comment, $author, $this->user->userInfo->report_name, $timestamp, $report_no ]; DB::insert(Config::get('sql.INSERT_REPORT_COMMENT'),$data); // コメント一覧取得 $comment_list = DataManager::getCommentList($report_no); // TODO:取得失敗時の処理 return View::make('parts.report.comment') ->with('comment_list', $comment_list); } /** * コメント取得(AJAX) */ function postComment(){ // リクエストパラメータ取得 $report_no = Input::get('report_no'); // コメント一覧取得 $comment_list = DataManager::getCommentList($report_no); // TODO:取得失敗時の処理 return View::make('parts.report.comment') ->with('comment_list', $comment_list); } /** * セッションからレポート情報を取得 * @return unknown */ protected function getSessionReportInfo(){ $data = Session::get('SESSION_KEY_REPORT_DATA'); return $data['report_info']; } /** * セッションからレポート固有情報を取得 * @return unknown */ protected function getSessionIndividualsInfo(){ $data = Session::get('SESSION_KEY_REPORT_DATA'); return $data['individuals_info']; } /** * セッションから関連レポート情報を取得 * @return unknown */ protected function getSessionRelationReportInfo(){ $data = Session::get('SESSION_KEY_RELATION_REPORT_DATA'); return $data['report_info']; } /** * セッションから関連レポート固有情報を取得 * @return unknown */ protected function getSessionRelationIndividualsInfo(){ $data = Session::get('SESSION_KEY_RELATION_REPORT_DATA'); return $data['individuals_info']; } /** * レポート情報取得 * @param $report_no * @return レポート情報 */ protected function getReportInfo($report_no){ throw new Exception('サブクラスで実装すること!'); } /** * 空のレポート情報取得 * @return レポート情報 * @throws Exception */ protected function getEmptyReportInfo($report_class){ throw new Exception('サブクラスで実装すること!'); } /** * 関連レポート取得 * @param unknown $reportInfo */ protected function getRelatedReportList($report_info){ $data; switch ($report_info->report_class){ case Config::get('const.REPORT_CLASS.PENGUIN'): $data = [ $report_info->departure_date, $report_info->flight_number, $report_info->departure_date, $report_info->flight_number, $report_info->departure_date_2, $report_info->flight_number_2, $report_info->departure_date_2, $report_info->flight_number_2, $report_info->report_no, $report_info->departure_date, $report_info->flight_number, $report_info->departure_date_2, $report_info->flight_number_2, $report_info->departure_date, $report_info->flight_number, $report_info->departure_date_2, $report_info->flight_number_2 ]; break; case Config::get('const.REPORT_CLASS.PEREGRINE_Incident'): case Config::get('const.REPORT_CLASS.PEREGRINE_Irregularity'): case Config::get('const.REPORT_CLASS.PEACOCK'): $data = [ $report_info->departure_date, $report_info->flight_number, $report_info->report_no, $report_info->departure_date, $report_info->flight_number, $report_info->departure_date, $report_info->flight_number, $report_info->departure_date, $report_info->flight_number ]; break; default: return []; } return DB::select( Config::get('sql.SELECT_RELATED_REPORT_LIST')[Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_info->report_class]], $data); } /** * レポート個別情報取得 * @param string $report_no レポート番号 * @param int $report_class レポート種別 * @throws Exception */ protected function getIndividualsInfo($report_no, $report_class){ throw new Exception('サブクラスで実装すること!'); } /** * レポート登録 * @param int $status ステータス */ protected function insertReport($status){ throw new Exception('サブクラスで実装すること!'); } /** * レポート更新 * @param int $status ステータス * @param boolean 差戻しフラグ(true:差戻しの場合) */ protected function updateReport($status, $is_passback){ throw new Exception('サブクラスで実装すること!'); } /** * メール送信処理 */ function sendMail($report_no, $report_class, $report_kbn){ $send_checkList = [ 0 => Input::get('send_mail_creator') === 'on' ? true : false, 1 => Input::get('send_mail_administrator_group') === 'on' ? true : false, 2 => Input::get('send_mail_approver_group') === 'on' ? true : false, 3 => Input::get('send_mail_inquiry_from_administrator_group') === 'on' ? true : false, 4 => Input::get('send_mail_inquiry_to_administrator_group') === 'on' ? true : false, ]; $inquiry_checkList = [ 1 => Input::get('penguin_inquiry_status') === 'on' ? true : false, 2 => Input::get('peregrine_inquiry_status') === 'on' ? true : false, 4 => Input::get('peacock_inquiry_status') === 'on' ? true : false, ]; $report_title = input::get('report_title'); if (!$report_title) { $report_info = $this->getSessionReportInfo(); $report_title = $report_info->report_title; } foreach($send_checkList as $role => $check){ if($check === false){ continue; } if($role == 3){ // 照会元→管理者宛て $role = 1; } if($role == 4){ // 照会先 foreach($inquiry_checkList as $toReport_class => $check){ // 照会先→管理者宛て $role = 1; if($check === false){ continue; } MailManager::send( $report_no, $toReport_class, $role, $report_kbn, [ '@repono@'=>$report_no, '@title@'=>$report_title ] ); } }else{ // 照会先以外 MailManager::send( $report_no, $report_class, $role, $report_kbn, [ '@repono@'=>$report_no, '@title@'=>$report_title ] ); } } } /** * 送信先チェック */ function checkSendMail($is_passback){ $mode = Input::get('_mode'); $send_mail_creator = Input::get('send_mail_creator') === 'on' ? true : false; $send_mail_administrator_group = Input::get('send_mail_administrator_group') === 'on' ? true : false; $send_mail_approver_group = Input::get('send_mail_approver_group') === 'on' ? true : false; $send_mail_inquiry_from_administrator_group = Input::get('send_mail_inquiry_from_administrator_group') === 'on' ? true : false; $send_mail_inquiry_to_administrator_group_hidden = Input::get('send_mail_inquiry_to_administrator_group_hidden') === 'on' ? true : false; if ($is_passback) { // 差戻し時 if($mode == 'confirm' && $send_mail_approver_group){ $this->error_message_list[] = "差戻し時に承認者にメールを送信することは出来ません。"; } if($mode == 'close' && $send_mail_creator){ $this->error_message_list[] = "差戻し時に起票者にメールを送信することは出来ません。"; } } else if ($mode == 'confirm') { // 確認時 if($mode == 'confirm' && $send_mail_creator){ $this->error_message_list[] = "確認時に起票者にメールを送信することは出来ません。"; } } } /** * レポート個別アラート設定(Ajax) */ function postAlertSetting() { // リクエストパラメータ取得 $mode = Input::get('_mode'); $report_class = Input::get('_report_class'); $report_no = Input::get('_report_no'); $report_alert = Input::get('_report_alert'); // 操作履歴ログ出力 DataManager::registerOperationLog( $this->user->getLoginId(), Config::get('const.REPORT_CLASS_NAME')[$report_class] . ':' . Config::get('const.REPORT_MODE_NAME')[$mode], 'レポート個別アラート設定' . ($report_alert ? 'Off' : 'On'), $report_no); // #12 2016/4/4 変数未参照問題対応 $result = "0"; $result = DB::transaction(function() use ($report_no, $report_alert) { if($report_alert){ $result = DB::table('alert_mail_condition') ->where('login_id', $this->user->userInfo->login_id) ->where('report_no', $report_no) ->delete(); } else { $result = DB::table('alert_mail_condition') ->insert([ 'login_id' => $this->user->userInfo->login_id, 'report_no' => $report_no, 'alert_timing' => Config::get('const.ALERT_MAIL_TIMING')['CREATED_AND_UPDATED'], ]); } return $result; }); return "".$result; } function getAlertUserList($report_no, $alert_timing = NULL) { if(is_null($alert_timing)) { $alert_timing = Config::get('ALERT_TIMING.CREATED_AND_UPDATED'); } $result = DB::table('alert_mail_condition') ->distinct() ->select(['login_id']) ->where('report_no', $report_no) ->where('alert_timing', $alert_timing) ->get(); $ret = array(); foreach($result as $row) { $ret[] = $row->login_id; } return $ret; } function alertMail($report_no, $user_list, $mail_kbn) { if(count($user_list)) { $report_title = input::get('report_title'); if (!$report_title) { $report_info = $this->getSessionReportInfo(); $report_title = $report_info->report_title; } MailManager::alertMail($user_list, $mail_kbn, ['@repono@'=>$report_no,'@title@'=>$report_title]); } } } <file_sep>/app/controllers/TopControllerPEREGRINE.php <?php /** * トップ画面(PEREGRINE) */ class TopControllerPEREGRINE extends TopController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * 照会レポート取得処理 * @see TopController::getInquiryReport() */ protected function getInquiryReport(){ return DB::select( Config::get('sql.SELECT_INQUIRY_REPORT_PEREGRINE'), [ Config::get('const.INQUIRY_STATUS.INQUIRY'), '1' ] ); } /** * 最新レポート取得処理 * @see TopController::getNewReport() */ protected function getNewReport(){ // PEREGRINEは2テーブル $station = $this->user->userInfo->station; $sqlString = Config::get('sql.SELECT_NEW_REPORT_PEREGRINE'); $whereString = ''; $orderString = 'order by t1.update_timestamp desc '; $bindParam_Incident = [ Config::get('const.REPORT_CLASS.PEREGRINE_Incident'), // PEREGRINE_Incidentのみ Config::get('const.REPORT_STATUS.CLOSE'), // 承認済以外 '1' ]; $bindParam_Irregularity = [ Config::get('const.REPORT_CLASS.PEREGRINE_Irregularity'), // PEREGRINE_Irregularityのみ Config::get('const.REPORT_STATUS.CLOSE'), // 承認済以外 '1' ]; if($this->user->isCreator()){ // 起票者の場合 $whereString = 'and t2.station = ? '; $bindParam_Incident[] = $station; $bindParam_Irregularity[] = $station; } // PEREGRINE_Incident $result['Incident'] = DB::select( $sqlString.$whereString.$orderString, $bindParam_Incident ); // PEREGRINE_Irregularity $result['Irregularity'] = DB::select( $sqlString.$whereString.$orderString, $bindParam_Irregularity ); return $result; } } <file_sep>/vendor/dsdevbe/ldap-connector/src/Dsdevbe/LdapConnector/LdapConnectorServiceProvider.php <?php namespace Dsdevbe\LdapConnector; use Illuminate\Auth\Guard; use Illuminate\Support\ServiceProvider; use LdapManager; use Exception; class LdapConnectorServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { $this->package('dsdevbe/ldap-connector'); \Auth::extend('ldap', function($app) { $provider = new LdapUserProvider($this->getConfig()); return new Guard($provider, $app['session.store']); }); } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('auth'); } /** * Get ldap configuration * * @return array */ public function getConfig() { if(!$this->app['config']['ldap']) throw new Exception('LDAP config not found. Check if app/config/ldap.php exists.'); return $this->app['config']['ldap']; } } <file_sep>/app/views/parts/report/phoenix_area.php <label for="phoenix_class" class="label06">Phoenix Class<br /><span>Phoenixカテゴリ</span></label> <div class="label07"> <select id="phoenix_class" name="phoenix_class" class="inputbox" <?= HTML::entities($role_manage_info->other_input_disabled) ?>> <option value=""></option> <?php foreach($phoenix_class_list as $data) { ?> <option value="<?= HTML::entities($data->code2) ?>" <?php echo Input::old('phoenix_class', $report_info->phoenix_class) === $data->code2 ? 'selected="selected"' : '' ?>><?= HTML::entities($data->value2) ?></option> <?php } ?> </select> </div> <label for="phoenix_memo" class="label06">Phoenix Memo<br /><span>Phoenixメモ</span></label> <div class="label07_2"> <textarea id="phoenix_memo" name="phoenix_memo" cols="100" rows="5" class="inputbox03 no-resize-horizontal-textarea" <?= HTML::entities($role_manage_info->other_input_disabled) ?> maxlength="1500" placeholder="※black/special登録内容の補足記事欄 Additional explanation about black/special"><?= HTML::entities(Input::old('phoenix_memo', $report_info->phoenix_memo)) ?></textarea> </div> <file_sep>/app/views/parts/report/inquiry_area.php <?php if($report_info->report_no){ ?> <script> function answerRead(report_no, report_class, mode) { $('#answer_read').prop('disabled', true); $.ajax({ type: 'POST', url: '/p/chirp/report/answer-read', dataType: 'text', data: { '_report_no':$('#_report_no').val(), '_report_class':$('#_report_class').val(), '_mode':$('#_mode').val(), '_modified':$('#_modified').val() } }) // 通信成功 .done(function(data, textStatus, jqXHR){ // 正常 if(data.length > 0 && data.match(/^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}$/)) { $('#report_modified').text(data + ' JST'); alert('回答閲覧済に変更しました'); $('#answer_read').hide(); $('#_modified').val(data); // 排他エラー } else if (data.length > 0 && data === '0' ){ alert('<?php echo Config::get('message.EXCLUSIVE_ERROR'); ?>'); // 例外発生 } else { alert('ステータスの変更に失敗しました'); $('#answer_read').removeAttr('disabled'); } }) // 通信失敗 .fail(function(jqXHR, textStatus, errorThrown) { alert('ステータスの変更に失敗しました'); $('#answer_read').removeAttr('disabled'); }) .always(function(data, textStatus, errorThrown){ }); } </script> <div class="form-horizontal <?= HTML::entities($role_manage_info->comment_area_hidden) ?>"> <label class="label06">Inquiry<br /><span>他部門照会</span></label> <div class="label07_2"> <div style="word-wrap: break-word;max-height:300px;overflow: auto; margin-bottom: 5px;"> <div id="comment" style="margin: 0px;padding: 0px"></div> </div> <div class="clearfix"> <?php if($report_info->answer_read_button): ?> <button type="button" class="btn btn-lgray btn-xs viewed <?php echo $role_manage_info->answer_read_hidden ?>" onclick="answerRead();" id="answer_read">回答閲覧済</button> <?php endif; ?> </div> <button type="button" class="btn btn-pink pull-left <?php echo $role_manage_info->comment_button_hidden ?>" onclick="return showCommentDialog(this, '<?php echo $report_info->report_no ?>', '<?php echo $report_info->report_class ?>', '<?php echo $_mode ?>')">Comment</button> </div> </div> <?php } ?> <?php if($_mode === 'inquiry'){ ?> <label for="Send Mail" class="label06">Inquire To<br><span>照会先</span></label> <div class="label07"> <?php if($report_info->report_class != 1){ ?> <div class="checkbox checkbox-inline"> <input id="penguin_inquiry_status" name="penguin_inquiry_status" type="checkbox" <?php echo(Input::old('penguin_inquiry_status','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="penguin_inquiry_status">PENGUIN</label> </div> <?php } ?> <?php if($report_info->report_class != 2 && $report_info->report_class != 3){ ?> <div class="checkbox checkbox-inline"> <input id="peregrine_inquiry_status" name="peregrine_inquiry_status" type="checkbox" <?php echo(Input::old('peregrine_inquiry_status','')) === 'on' ? 'checked="checked"' : '' ?> /> <label for="peregrine_inquiry_status">PEREGRINE</label> </div> <?php } ?> <?php if($report_info->report_class != 4){ ?> <div class="checkbox checkbox-inline"> <input id="peacock_inquiry_status" name="peacock_inquiry_status" type="checkbox" <?php echo(Input::old('peacock_inquiry_status','')) === 'on' ? 'checked="checked"' : '' ?>/> <label for="peacock_inquiry_status">PEACOCK</label> </div> <?php } ?> </div> <?php } ?> <file_sep>/app/extentions/CommonGateway/RoleManager.php <?php namespace CommonGateway { use DB; class RoleManager { /** * コンストラクタ */ function __construct() { } } }<file_sep>/app/controllers/TopControllerPEACOCK.php <?php /** * トップ画面(PEACOCK) */ class TopControllerPEACOCK extends TopController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * 照会レポート取得処理 * @see TopController::getInquiryReport() */ protected function getInquiryReport(){ return DB::select( Config::get('sql.SELECT_INQUIRY_REPORT_PEACOCK'), [ Config::get('const.INQUIRY_STATUS.INQUIRY'), '1' ] ); } /** * 最新レポート取得処理 * @see TopController::getNewReport() */ protected function getNewReport(){ $result = DB::select( Config::get('sql.SELECT_NEW_REPORT_PEACOCK'), [ Config::get('const.REPORT_CLASS.PEACOCK'), // PEACOCKのみ Config::get('const.REPORT_STATUS.CLOSE'), // 承認済以外 '1' ] ); return $result; } } <file_sep>/app/extentions/CommonServiceProvider.php <?php use Illuminate\Support\ServiceProvider; class CommonServiceProvider extends ServiceProvider { public function register() { // AD認証 $this->app->bindShared('LdapAuth', function() {return new CommonGateway\LdapAuth;}); // DBアクセス $this->app->bindShared('DataManager', function() {return new CommonGateway\DataManager;}); // メール送信 $this->app->bindShared('MailManager', function() {return new CommonGateway\MailManager;}); // システムコード $this->app->bindShared('SystemCodeManager', function() {return new CommonGateway\SystemCodeManager;}); // 共通チェック $this->app->bindShared('CommonCheckLogic', function() {return new CommonGateway\CommonCheckLogic;}); // 日付ユーティリティ $this->app->bindShared('DateUtil', function() {return new CommonGateway\DateUtil;}); } } <file_sep>/app/start/global.php <?php /* |-------------------------------------------------------------------------- | Laravelクラスローダーの登録 |-------------------------------------------------------------------------- | | Composerを使用することに加え、コントローラーとモデルをロードするために | Laravelのクラスローダーを使用することもできます。Composerを更新しなくても | 「グローバル」な名前空間にあなたのクラスを設置しておくのに便利です。 | */ ClassLoader::addDirectories(array( app_path().'/commands', app_path().'/controllers', app_path().'/models', app_path().'/database/seeds', app_path().'/extentions', )); /* |-------------------------------------------------------------------------- | アプリケーションエラーログ |-------------------------------------------------------------------------- | | 素晴らしいMonologライブラリーの上に構築されたアプリケーションのために | ここではエラーログの設定を行なっています。デフォルトでは、一つの | 基本的なログファイルを作成し、使用します。 | */ //Log::useFiles('/home/chirp-admin/chirplogs/laravel.log', 'error'); Log::useDailyFiles(storage_path() . '/logs/laravel.log', 30, 'debug'); /* |-------------------------------------------------------------------------- | アプリケーションエラーハンドラー |-------------------------------------------------------------------------- | | ここではアプリケーションでエラーが発生した場合の、エラーの処理(ログしたり、 | カスタムビューで特定のエラーを表示したりするなどを含む)を定義します。 | 異なったタイプの例外を処理するために多くのエラーハンドラーを登録することも | できます。もし、何もリターンしなれば、デフォルトのエラービューが表示され、 | それにはデバッグ中であれば詳細なスタックトレースも含まれます。 | */ App::error(function(Exception $exception, $code) { Log::error($exception . "\nurl=" . Request::url()); Log::info(Request::url()); // return Response::View('error'); }); /* |-------------------------------------------------------------------------- | メンテナンスモードハンドラー |-------------------------------------------------------------------------- | | Artisanコマンドの"down"でメンテナンスモードにすることができます。 | このアプリケーションにふさわしいメンテナンスモードでの | 表示をここで定義してください。 | */ App::down(function() { return Response::make("Be right back!", 503); }); DB::listen(function($sql, $bindings, $time) { Log::info($sql); }); /* |-------------------------------------------------------------------------- | フィルターファイルの読み込み |-------------------------------------------------------------------------- | | 以下でアプリケーションのフィルターファイルを読み込んでいます。 | これによりルートとフィルターを同じルーティングファイルに押しこまずに | 分けて保存できるようになりました。 | */ require app_path().'/filters.php'; // サービスプロバイダ登録 App::register('CommonServiceProvider'); <file_sep>/app/controllers/PreviewControllerPEREGRINE.php <?php /** * * プレビュー画面(PEREGRINE) * */ class PreviewControllerPEREGRINE extends PreviewController { /** * コンストラクタ */ function __construct() { parent::__construct(); } /** * レポート情報取得 * @see PreviewController::getReportInfo() */ protected function getReportInfo($report_no){ return DB::selectOne(Config::get('sql.SELECT_PREVIEW_PEREGRINE'),['1','1', $report_no, '1']); } } <file_sep>/app/routes.php <?php /* |-------------------------------------------------------------------------- | アプリケーションルート |-------------------------------------------------------------------------- | | このファイルでアプリケーションの全ルートを定義します。 | 方法は簡単です。対応するURIをLaravelに指定してください。 | そしてそのURIに対応する実行コードをクロージャーで指定します。 | */ /* * Check authen */ Route::controller('/auth', 'AuthenAPIController'); /* * レポート画面 */ Route::controller('/report', getReportController()); /* * トップ画面 */ Route::controller('/top', getTopController()); /* * プレビュー画面 */ Route::controller('/preview', getPreviewController()); /** * アラート設定画面 */ Route::controller('/alert', 'AlertController'); /* * ログイン画面 */ Route::controller('/', 'LoginController'); // /* // * ルートの場合はリダイレクト // */ // Route::get('/', function() // { // return Redirect::To('/'); // }); function getTopController(){ // ユーザー情報取得 $user = unserialize(Session::get('SESSION_KEY_CHIRP_USER')); if($user){ return Config::get('const.topControllers')[$user->userInfo->report_name]; } // return 'ErrorController'; return Config::get('const.topControllers')['PEACOCK']; } function getReportController(){ $report_class = Session::get('_report_class'); if(!$report_class){ $report_class = Input::get('_report_class'); } if($report_class){ return Config::get('const.reportControllers')[Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_class]]; } return 'ErrorController'; } function getPreviewController() { $report_class = Session::get('_report_class'); if(!$report_class){ $report_class = Input::get('_report_class'); } if($report_class) { return Config::get('const.previewControllers')[Config::get('const.REPORT_CLASS_BASIC_NAME')[$report_class]]; } return 'ErrorController'; }
fcb6535f8f27d98bcabea57b1ecd4bd170a23a92
[ "JavaScript", "Markdown", "PHP" ]
72
PHP
acv-huynq/chirp
185319e29f0425022f73af9d98994bf8f1c7326e
2a29785d245f8e1238ee89fb446a9b2b8663ebb9
refs/heads/master
<repo_name>MuhammadMia/AirSim<file_sep>/Unreal/Plugins/AirSim/Source/FlyingPawn.cpp #include "AirSim.h" #include "FlyingPawn.h" #include "AirBlueprintLib.h" #include "common/CommonStructs.hpp" #include "MultiRotorConnector.h" void AFlyingPawn::initialize() { Super::initialize(); } void AFlyingPawn::initializeForPlay() { //get references of components so we can use later setupComponentReferences(); //set stencil IDs setStencilIDs(); setupInputBindings(); } void AFlyingPawn::setStencilIDs() { TArray<AActor*> foundActors; UAirBlueprintLib::FindAllActor<AActor>(this, foundActors); TArray<UStaticMeshComponent*> components; int stencil = 0; for (AActor* actor : foundActors) { actor->GetComponents(components); if (components.Num() == 1) { components[0]->SetRenderCustomDepth(true); components[0]->CustomDepthStencilValue = (stencil++) % 256; components[0]->MarkRenderStateDirty(); } } } const AFlyingPawn::RCData& AFlyingPawn::getRCData() { return rc_data; } void AFlyingPawn::reset() { Super::reset(); rc_data = RCData(); rc_data.switch1 = rc_data.switch2 = rc_data.switch3 = 1; } APIPCamera* AFlyingPawn::getFpvCamera() { return fpv_camera_; } void AFlyingPawn::setRotorSpeed(int rotor_index, float radsPerSec) { if (rotor_index >= 0 && rotor_index < rotor_count) rotating_movements_[rotor_index]->RotationRate.Yaw = radsPerSec * 180.0f / M_PIf * RotatorFactor; } std::string AFlyingPawn::getVehicleName() { return std::string(TCHAR_TO_UTF8(*VehicleName)); } void AFlyingPawn::setupComponentReferences() { fpv_camera_ = Cast<APIPCamera>( (UAirBlueprintLib::GetActorComponent<UChildActorComponent>(this, TEXT("LeftPIPCamera")))->GetChildActor()); for (auto i = 0; i < 4; ++i) { rotating_movements_[i] = UAirBlueprintLib::GetActorComponent<URotatingMovementComponent>(this, TEXT("Rotation") + FString::FromInt(i)); } } void AFlyingPawn::inputEventThrottle(float val) { rc_data.throttle = val; UAirBlueprintLib::LogMessage(TEXT("Throttle: "), FString::SanitizeFloat(val), LogDebugLevel::Informational); } void AFlyingPawn::inputEventYaw(float val) { rc_data.yaw = val; UAirBlueprintLib::LogMessage(TEXT("Yaw: "), FString::SanitizeFloat(val), LogDebugLevel::Informational); } void AFlyingPawn::inputEventPitch(float val) { rc_data.pitch = -val; UAirBlueprintLib::LogMessage(TEXT("Pitch: "), FString::SanitizeFloat(val), LogDebugLevel::Informational); } void AFlyingPawn::inputEventRoll(float val) { rc_data.roll = val; UAirBlueprintLib::LogMessage(TEXT("Roll: "), FString::SanitizeFloat(val), LogDebugLevel::Informational); } void AFlyingPawn::inputEventArmDisArm() { rc_data.switch5 = rc_data.switch5 <= 0 ? 1 : 0; UAirBlueprintLib::LogMessage(TEXT("Arm/Disarm"), FString::SanitizeFloat(rc_data.switch5), LogDebugLevel::Informational); } void AFlyingPawn::setupInputBindings() { this->EnableInput(this->GetWorld()->GetFirstPlayerController()); UAirBlueprintLib::BindAxisToKey("InputEventThrottle", EKeys::Gamepad_LeftY, this, &AFlyingPawn::inputEventThrottle); UAirBlueprintLib::BindAxisToKey("InputEventYaw", EKeys::Gamepad_LeftX, this, &AFlyingPawn::inputEventYaw); UAirBlueprintLib::BindAxisToKey("InputEventPitch", EKeys::Gamepad_RightY, this, &AFlyingPawn::inputEventPitch); UAirBlueprintLib::BindAxisToKey("InputEventRoll", EKeys::Gamepad_RightX, this, &AFlyingPawn::inputEventRoll); UAirBlueprintLib::BindActionToKey("InputEventArmDisArm", EKeys::Gamepad_LeftTrigger, this, &AFlyingPawn::inputEventArmDisArm); }
3ed945e2911a0893bb9a88d42e64c62ef5bf7597
[ "C++" ]
1
C++
MuhammadMia/AirSim
72d2a5b6ba3b195628073086c8ebeaf9be460fbd
4625bd9d1a1c4a56af6fbc076c5803c7fd6f5473
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Destroy : MonoBehaviour { public float seconds = 5f; IEnumerator waitndestroy() { yield return new WaitForSeconds(seconds); GameObject.Destroy(transform.gameObject); } private void Awake() { StartCoroutine(waitndestroy()); } } <file_sep># temp-name <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraPositioner : MonoBehaviour { public Transform playerCam; public Transform orientation; private void Update() { Debug.DrawRay(playerCam.position, playerCam.forward * 2, Color.red); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class ServerHandle { public static void WelcomeReceived(int _fromClient, Packet _packet) { int _clientIdCheck = _packet.ReadInt(); string _username = _packet.ReadString(); Debug.Log($"{Server.clients[_fromClient].tcp.socket.Client.RemoteEndPoint} connected successfully and is now player {_fromClient}."); if (_fromClient != _clientIdCheck) { Debug.Log($"Player \"{_username}\" (ID: {_fromClient}) has assumed the wrong client ID ({_clientIdCheck})!"); } Server.clients[_fromClient].SendIntoGame(_username); } public static void PlayerMovement(int _fromClient, Packet _packet) { bool[] _inputs = new bool[8]; _inputs = DecodeByte(_packet.ReadByte()); Quaternion _camRotation = _packet.ReadQuaternion(); Quaternion _orientation = _packet.ReadQuaternion(); int _tick = _packet.ReadInt(); //pass data to player instance to queue later Server.clients[_fromClient].player.QueueIncomingInputPack(_inputs, _camRotation, _orientation, _tick); } static public bool[] DecodeByte(byte _2decode) { bool[] _inputs = new bool[8]; //_inputs[7] => W //_inputs[6] => S //_inputs[5] => D //_inputs[4] => A //_inputs[3] => LEFT_CTRL //_inputs[2] => SPACE //_inputs[1] => LEFT_MOUSE //_inputs[0] => G //======================== if (_2decode - 128 >= 0) { _inputs[7] = true; _2decode -= 128; } else { _inputs[7] = false; } //======================== if (_2decode - 64 >= 0) { _inputs[6] = true; _2decode -= 64; } else { _inputs[6] = false; } //======================== if (_2decode - 32 >= 0) { _inputs[5] = true; _2decode -= 32; } else { _inputs[5] = false; } //======================== if (_2decode - 16 >= 0) { _inputs[4] = true; _2decode -= 16; } else { _inputs[4] = false; } //======================== if (_2decode - 8 >= 0) { _inputs[3] = true; _2decode -= 8; } else { _inputs[3] = false; } //======================== if (_2decode - 4 >= 0) { _inputs[2] = true; _2decode -= 4; } else { _inputs[2] = false; } //======================== if (_2decode - 2 >= 0) { _inputs[1] = true; _2decode -= 2; } else { _inputs[1] = false; } //======================== if (_2decode - 1 >= 0) { _inputs[0] = true; } else { _inputs[0] = false; } //======================== return _inputs; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class LocalCameraController : MonoBehaviour { public static LocalCameraController instance; public Transform playerCam; public Transform orientation; //Rotation and look private float xRotation; private float sensitivity = 50f; private float sensMultiplier = 1f; private float desiredX; private void Awake() { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; if (instance == null) { instance = this; } else if (instance != this) { Debug.Log("Instance already exists, destroying object!"); Destroy(this); } } void Update() { Look(); } private void Look() { float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.fixedDeltaTime * sensMultiplier; float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.fixedDeltaTime * sensMultiplier; //Find current look rotation Vector3 rot = playerCam.transform.localRotation.eulerAngles; desiredX = rot.y + mouseX; //Rotate, and also make sure we dont over- or under-rotate. xRotation -= mouseY; xRotation = Mathf.Clamp(xRotation, -90f, 90f); //Perform the rotations playerCam.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0); orientation.transform.localRotation = Quaternion.Euler(0, desiredX, 0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class PlayerController : MonoBehaviour { [HideInInspector] public InputPack inputs; [HideInInspector] public ServerSnapshot currentServerSnapshot; public ClientState currentClientState; [SerializeField] private int currentTick = 0; private Queue<ClientState> clientStateBuffer = new Queue<ClientState>(); private Queue<InputPack> inputHistory = new Queue<InputPack>(); public Queue<ServerSnapshot> snapshots = new Queue<ServerSnapshot>(); [HideInInspector] public Vector3 posError; [SerializeField] float posErrorMagnitude; public float posErrorTolerance = 3f; Vector3 fixedPosError; Vector3 lastSnapshotPos; private int lastRecievedTick = 0; ClientInputPredictor predictor; InputMover inputMover; //DEBUG public GameObject serverPlayer; public GameObject serverPos; public GameObject playerPos; public GameObject playerPosTrack; Vector3 beforeInputMoving; Vector3 afterInputMoving; private void Awake() { InitializeData(); } private void Update() { Instantiate(playerPosTrack, transform.position, Quaternion.identity); } private void FixedUpdate() { Debug.Log($"CURRENT TICK: {currentTick}"); UpdateInputPack(); predictor.inputs = DecodeByte(inputs.input); SendInputToServer(inputs); predictor.Movement(); StoreClientState(); handlePosErrorIfSnapshotsAvailable(); #region DEBUG serverPlayer.transform.position = lastSnapshotPos; posErrorMagnitude = posError.magnitude; #endregion Debug.Log($"================== End of tick {currentTick} ===================="); currentTick++; } /// <summary>Sends player input to the server.</summary> private void SendInputToServer(InputPack _pack) { ClientSend.PlayerMovement(_pack); } public byte ByteInput() { byte input = 0; if (Input.GetKey(KeyCode.W)) input += 1; if (Input.GetKey(KeyCode.S)) input += 2; if (Input.GetKey(KeyCode.D)) input += 4; if (Input.GetKey(KeyCode.A)) input += 8; if (Input.GetKey(KeyCode.LeftControl)) input += 16; if (Input.GetKey(KeyCode.Space)) input += 32; if (Input.GetKey(KeyCode.Mouse0)) input += 64; if (Input.GetKey(KeyCode.G)) input += 128; return input; } public struct InputPack { public byte input; public Quaternion camRotation; public Quaternion orientation; public int tick; } public struct ClientState { public Vector3 position; public int tick; } public struct ServerSnapshot { public Vector3 position; public Quaternion camRotation; public Quaternion orientation; public Vector3 velocity; public int tick; } private void UpdateInputPack() { inputs.input = ByteInput(); inputs.camRotation = LocalCameraController.instance.playerCam.rotation; inputs.orientation = LocalCameraController.instance.orientation.rotation; inputs.tick = currentTick; inputHistory.Enqueue(inputs); } private void DequeueDeprecatedInputPacks() { if (inputHistory.Count != 0) { while (inputHistory.Peek().tick < lastRecievedTick) { inputHistory.Dequeue(); } } else { Debug.LogError("IDK WTF HAPPENED"); } } private void StoreClientState() { currentClientState.position = transform.position; currentClientState.tick = currentTick; clientStateBuffer.Enqueue(currentClientState); } private void StoreClientState(int _tick) { currentClientState.position = transform.position; currentClientState.tick = _tick; clientStateBuffer.Enqueue(currentClientState); } private void InitializeData() { posError = Vector3.zero; predictor = GetComponent<ClientInputPredictor>(); inputMover = GetComponent<InputMover>(); #region DEBUG serverPlayer = GameObject.FindGameObjectWithTag("ServerPlayerDebug"); lastSnapshotPos = Vector3.zero; #endregion } private void handlePosErrorIfSnapshotsAvailable() { ServerSnapshot snapshot; ClientState state; if (snapshots.Count > 0 && clientStateBuffer.Count > 0) { snapshot = snapshots.Dequeue(); state = clientStateBuffer.Peek(); while (snapshots.Count > 1) { snapshot = snapshots.Dequeue(); Debug.LogWarning($"Dequeued deprecated server snapshots"); } while (state.tick < snapshot.tick) { if (clientStateBuffer.Count != 0) { state = clientStateBuffer.Dequeue(); Debug.Log($"Dequeued deprecated clientStates"); } else { Debug.LogError($"RAN OUT OF CLIENT PACKS?"); } } if (state.tick != snapshot.tick) { Debug.LogError("Critcal error: comparing wrong ticks"); } if (lastRecievedTick + 1 != snapshot.tick) { Debug.LogError($"Missed {currentTick - lastRecievedTick} tick(s)"); } Debug.Log($"COMPARING: client: {state.tick}; server: {snapshot.tick}"); Debug.Log($"AVAILABLE SNAPSHOTS: client: {clientStateBuffer.Count}; server: {snapshots.Count}"); lastSnapshotPos = snapshot.position; lastRecievedTick = snapshot.tick; posError = calculatePosError(state.position, snapshot.position); if (posError.sqrMagnitude > posErrorTolerance * posErrorTolerance) { Debug.LogError("Input prediction error"); DequeueDeprecatedInputPacks(); UnityEngine.Debug.DrawLine(state.position, snapshot.position, Color.green, 144f); Instantiate(playerPos, state.position, Quaternion.identity); Instantiate(serverPos, snapshot.position, Quaternion.identity); Physics.autoSimulation = false; transform.position = snapshot.position; predictor.orientation.rotation = snapshot.orientation; predictor.playerCam.rotation = snapshot.camRotation; predictor.rb.velocity = snapshot.velocity; clientStateBuffer.Clear(); //StoreClientState(snapshot.tick); Queue<InputPack> inputHistory2exec = new Queue<InputPack>(inputHistory); InputPack currentInputPack; beforeInputMoving = snapshot.position; while (inputHistory2exec.Count != 0) { Vector3 prevPos = transform.position; currentInputPack = inputHistory2exec.Dequeue(); Debug.LogWarning($"Executing physStep no. {currentInputPack.tick}"); inputMover.Movement(currentInputPack); Physics.Simulate(Time.fixedDeltaTime); StoreClientState(currentInputPack.tick); //UnityEngine.Debug.DrawLine(prevPos, transform.position, Color.yellow, 144f); } UnityEngine.Debug.DrawLine(beforeInputMoving, transform.position, Color.red, 144f); afterInputMoving = transform.position; Physics.autoSimulation = true; } } else { if(snapshots.Count == 0) { Debug.LogWarning($"No usable snapshots: tick {currentTick}"); } if(clientStateBuffer.Count == 0) { Debug.LogError($"Ran out of clientstates (cringe) tick: {currentTick}"); } } } private Vector3 calculatePosError(Vector3 _clientPos, Vector3 _serverPos) { return _serverPos - _clientPos; } static public bool[] DecodeByte(byte _2decode) { bool[] _inputs = new bool[8]; //_inputs[7] => W //_inputs[6] => S //_inputs[5] => D //_inputs[4] => A //_inputs[3] => LEFT_CTRL //_inputs[2] => SPACE //_inputs[1] => LEFT_MOUSE //_inputs[0] => G //======================== if (_2decode - 128 >= 0) { _inputs[7] = true; _2decode -= 128; } else { _inputs[7] = false; } //======================== if (_2decode - 64 >= 0) { _inputs[6] = true; _2decode -= 64; } else { _inputs[6] = false; } //======================== if (_2decode - 32 >= 0) { _inputs[5] = true; _2decode -= 32; } else { _inputs[5] = false; } //======================== if (_2decode - 16 >= 0) { _inputs[4] = true; _2decode -= 16; } else { _inputs[4] = false; } //======================== if (_2decode - 8 >= 0) { _inputs[3] = true; _2decode -= 8; } else { _inputs[3] = false; } //======================== if (_2decode - 4 >= 0) { _inputs[2] = true; _2decode -= 4; } else { _inputs[2] = false; } //======================== if (_2decode - 2 >= 0) { _inputs[1] = true; _2decode -= 2; } else { _inputs[1] = false; } //======================== if (_2decode - 1 >= 0) { _inputs[0] = true; } else { _inputs[0] = false; } //======================== return _inputs; } }
04d6122f88c072d20c510a473cd51872fce749f3
[ "Markdown", "C#" ]
6
C#
spicymuffin/temp-name
4f1b1f254e60bee34891c8160be5f14e5be3d194
eff1bc602f1642237ddf027fbe116db9092db92f
refs/heads/master
<file_sep>library(lubridate) #clean data bikerental<-read.table(file="/Users/linahu/Documents/Developer/Bike\ Sharing/train.csv",sep=",",header=TRUE); summary(bikerental) bikerental$weather<-as.factor(bikerental$weather) bikerental$holiday<-as.factor(bikerental$holiday) bikerental$workingday<- as.factor(bikerental$workingday) bikerental$season<-as.factor(bikerental$season) bikerental$datetime<-as.character(bikerental$datetime) bikerental$datetime<-strptime(bikerental$datetime, format ='%Y-%m-%d %H:%M:%S') #create date variable bikerental$hour = hour(bikerental$datetime) #todo: # split the training/test data (use the last 1 day of each month of the training set as the test data) #linear model with or without datetime lm1<-lm(count~holiday+season+weather+workingday+temp+atemp+humidity+windspeed, data=bikerental ) lm2<-lm(count~datetime+holiday+season+weather+workingday+temp+atemp+humidity+windspeed, data=bikerental) lm3<-lm(count~hour+holiday+season+weather+workingday+temp+atemp+humidity+windspeed, data=bikerental) # linear model with interaction terms lm4<-lm(count~hour+holiday+season+weather+workingday+temp+atemp+humidity+windspeed+holiday*season+workingday*season+weather*holiday, data=bikerental) # to do: # partition data based on categorical fields #time series library(xts) bikerentalxts<-as.xts(x=bikerental[,"count"],order.by=bikerental[,"datetime"]) plot(bikerentalxts[(1:100),])
9fad5a6bfff30a57a840191b7cc7929dc8a50e1e
[ "R" ]
1
R
himexia/BikeSharingDemand
075e8fb155d8bdf41cb4af5f900f7d256d04751b
6ceef5fe3b74da8179fcc950ee07959953ecf7e3
refs/heads/master
<file_sep><?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /** * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2012, POW! Corp. * @license MIT * @version 1.3.1 */ $config['apikey'] = ''; $config['secure'] = false; ?>
98bb9307f9286aa611241b7c842d045a4b88783c
[ "PHP" ]
1
PHP
nyfagel/codeigniter-mailchimp-spark
50e387c31bdd304a18caebd5fb2b97e7e78dde5a
a29a6b9076e8901d5e5ed3fd1b38e195fa791347
refs/heads/master
<file_sep>import numpy import pandas from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.model_selection import KFold import utils targetClass = 2 data = utils.getDataset(targetClass) data = utils.MapLabels(targetClass,data) data = utils.preprocess(data) model = LogisticRegression(solver='saga') # model = LinearSVC() kf = KFold(n_splits=10, random_state=43, shuffle=True) vectorizer = TfidfVectorizer(min_df=5, max_df=0.8, sublinear_tf=True, use_idf=True, ngram_range=(1, 2)) accurs = [] conf_matrix = [] cms = [] tp = [] tn = [] fp = [] fn = [] for train_index, test_index in kf.split(data): X_train, X_test = data.iloc[train_index]['Comment'], data.iloc[test_index]['Comment'] y_train, y_test = data.iloc[train_index]['Label'], data.iloc[test_index]['Label'] train_vectors = vectorizer.fit_transform(X_train) test_vectors = vectorizer.transform(X_test) print("Training Data") model.fit(train_vectors, y_train) prediction = model.predict(test_vectors) accur = accuracy_score(y_test, prediction) print("Score ",accur) accurs.append(accur) cm = confusion_matrix(y_test, prediction, labels=[0, 1]) cms.append(cm) # tp,tn,fp,fn = confusion_matrix(y_test,prediction) # print("TP ",tp) # print("TN ",tn) # conf_matrix.append(matrix) print(pandas.np.mean(accurs)) print("CMS") print(sum(cms)) print(numpy.average(cms, axis=0)) # print(pandas.np.mean(conf_matrix)) # filename = 'finalized_logistic.sav' # joblib.dump(clf_svc, filename)<file_sep>import numpy import pandas from nltk import WordNetLemmatizer from nltk.corpus import stopwords from sklearn.model_selection import learning_curve def getDataset(targetClass): if (targetClass == 5): return getFiveClassedDataset() elif (targetClass == 3): return getThreeClassedDataset() elif (targetClass == 2): return getTwoClassedDataset() def getFiveClassedDataset(): return pandas.read_csv('dataset/Dataset.csv') def getThreeClassedDataset(): return pandas.read_csv('dataset/Dataset_Tertiary_Labels.csv') def getTwoClassedDataset(): return pandas.read_csv('dataset/Dataset_Binary_Labels.csv') def MapLabels(targetClass,data): if(targetClass==5): data['Label'] = data.Label.map( {'Highly Negative': 0, 'Negative': 1, 'Neutral': 2, 'Positive': 3, 'Highly Positive': 4}) return data elif (targetClass == 3): data['Label'] = data.Label.map({ 'Negative': 0, 'Neutral': 1, 'Positive': 2}) return data elif (targetClass == 2): data['Label'] = data.Label.map({ 'Negative': 0, 'Positive': 1}) return data def preprocess(data): stop_words = set(stopwords.words('english')) listStop = list(stop_words) wordnet_lemmatizer = WordNetLemmatizer() data['Comment'] = data['Comment'].replace(to_replace='http\S+', value=' ', regex=True) # Removing urls data['Comment'] = data['Comment'].replace(to_replace='[^A-Za-z]+', value=' ', regex=True) # Removing special characters data['Comment'] = data['Comment'].apply( lambda x: ' '.join([word for word in x.split() if word not in (listStop)])) # Removing stop words #region Not using the hidden part # data['Comment'] = data['Comment'].apply(lambda x: ' '.join([word for word, pos in pos_tag(x.split()) if not pos == 'NNP']))# Removing NNP # data['Comment'] = data['Comment'].apply(lambda x: ' '.join([replaceWord(stem(word.lower())) for word in x.split()]))# Replacing common mis-spelled/same meaning words # data['Comment'] = data['Comment'].replace(to_replace='\d+', value=' ', regex=True) # Removing numbers #endregion data['Comment'] = data['Comment'].apply(lambda x: wordnet_lemmatizer.lemmatize(x)) return data commonDict = {'the': 'the', 'be': 'be', 'and': 'and', 'of': 'of', 'a': 'a', 'in': 'in', 'to': 'to', 'have': 'have', 'it': 'it', 'i': 'i', 'that': 'that', 'for': 'for', 'you': 'you', 'he': 'he', 'with': 'with', 'on': 'on', 'do': 'do', 'say': 'say', 'this': 'this', 'they': 'they', 'is': 'is', 'an': 'an', 'at': 'at', 'but': 'but', 'we': 'we', 'his': 'his', 'from': 'from', 'not': 'not', 'by': 'by', 'she': 'she', 'or': 'or', 'as': 'as', 'what': 'what', 'go': 'go', 'their': 'their', 'can': 'can', 'who': 'who', 'get': 'get', 'if': 'if', 'would': 'would', 'her': 'her', 'all': 'all', 'my': 'my', 'make': 'make', 'about': 'about', 'know': 'know', 'will': 'will', 'up': 'up', 'one': 'one', 'time': 'time', 'has': 'has', 'been': 'been', 'there': 'there', 'year': 'year', 'so': 'so', 'think': 'think', 'when': 'when', 'which': 'which', 'them': 'them', 'some': 'some', 'me': 'me', 'people': 'people', 'take': 'take', 'out': 'out', 'into': 'into', 'just': 'just', 'see': 'see', 'him': 'him', 'your': 'your', 'come': 'come', 'could': 'could', 'now': 'now', 'than': 'than', 'like': 'like', 'other': 'other', 'how': 'how', 'then': 'then', 'its': 'its', 'our': 'our', 'two': 'two', 'more': 'more', 'these': 'these', 'want': 'want', 'way': 'way', 'look': 'look', 'first': 'first', 'also': 'also', 'new': 'new', 'because': 'because', 'day': 'day', 'use': 'use', 'no': 'no', 'man': 'man', 'find': 'find', 'here': 'here', 'thing': 'thing', 'give': 'give', 'many': 'many', 'well': 'well', 'was': 'was', 'are': 'are', 'were': 'were', 'rrb': 'rrb', 'lrb': 'lrb', 'had': 'had', 'did': 'did', 'be':'be', 'where': 'where', 'those': 'those', 'through': 'through', 'though': 'though', 'while':'while', 'should': 'should', 've':'ve', 'ca':'ca', 'am':'am'}; def isCommon(word): if commonDict.get(word, None): return True return False customDict = {'film':'movie', 'movi':'movie', 'veri':'very', 'charact': 'character', 'stori': 'story', 'onli':'only', 'realli':'really', 'littl':'little', 'comedi':'comedy', 'ani':'any', 'tri': 'try', 'anoth':'another', 'pictur':'movie', 'beauti': 'beautiful', 'alway':'always', 'howev':'however', 'becom':'become', 'someth':'something', 'funni':'funny', 'befor':'before', 'everi':'every', 'whi': 'why', 'believ': 'believe', 'pretti': 'pretty', 'noth':'nothing', 'seri':'serial', 'favotir':'favorite', 'famili':'family', 'especi':'especially', 'probabl':'probably', 'minut':'minute', 'cours':'course', 'complet':'complete', 'surpris':'surprise'} def replaceWord(word): result = customDict.get(word, None) if (result != None): return result return word posDict = {'CC':'CC', 'CD':'CD', 'DT':'DT', 'EX': 'EX', 'FW': 'FW', 'LS':'LS','MD':'MD', 'PDT':'PDT', 'POS':'POS', 'PRP': 'PRP', 'SYM': 'SYM', 'RP':'RP','TO':'TO', 'UH':'UH', 'WDT':'WDT', 'WP': 'WP', 'WRB': 'WRB'} def isAllowedPOS(pos): if posDict.get(pos, None): return True return False # def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, # n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): # """ # Generate a simple plot of the test and training learning curve. # # Parameters # ---------- # estimator : object type that implements the "fit" and "predict" methods # An object of that type which is cloned for each validation. # # title : string # Title for the chart. # # X : array-like, shape (n_samples, n_features) # Training vector, where n_samples is the number of samples and # n_features is the number of features. # # y : array-like, shape (n_samples) or (n_samples, n_features), optional # Target relative to X for classification or regression; # None for unsupervised learning. # # ylim : tuple, shape (ymin, ymax), optional # Defines minimum and maximum yvalues plotted. # # cv : int, cross-validation generator or an iterable, optional # Determines the cross-validation splitting strategy. # Possible inputs for cv are: # - None, to use the default 3-fold cross-validation, # - integer, to specify the number of folds. # - An object to be used as a cross-validation generator. # - An iterable yielding train/test splits. # # For integer/None inputs, if ``y`` is binary or multiclass, # :class:`StratifiedKFold` used. If the estimator is not a classifier # or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. # # Refer :ref:`User Guide <cross_validation>` for the various # cross-validators that can be used here. # # n_jobs : integer, optional # Number of jobs to run in parallel (default 1). # """ # plot.figure() # plt.title(title) # if ylim is not None: # plt.ylim(*ylim) # plt.xlabel("Training examples") # plt.ylabel("Score") # train_sizes, train_scores, test_scores = learning_curve( # estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) # train_scores_mean = numpy.mean(train_scores, axis=1) # train_scores_std = numpy.std(train_scores, axis=1) # test_scores_mean = numpy.mean(test_scores, axis=1) # test_scores_std = numpy.std(test_scores, axis=1) # plt.grid() # # plt.fill_between(train_sizes, train_scores_mean - train_scores_std, # train_scores_mean + train_scores_std, alpha=0.1, # color="r") # plt.fill_between(train_sizes, test_scores_mean - test_scores_std, # test_scores_mean + test_scores_std, alpha=0.1, color="g") # plt.plot(train_sizes, train_scores_mean, 'o-', color="r", # label="Training score") # plt.plot(train_sizes, test_scores_mean, 'o-', color="g", # label="Cross-validation score") # # plt.legend(loc="best") # return plt <file_sep># Sentiment analysis The SAR14 IMDB movie review dataset (Download from http://tabilab.cmpe.boun.edu.tr/datasets/review_datasets/SAR14.zip) was used. The data consisted of a detailed review and its respective rating. All the reviews had a rating, ranging from 1 to 10. We decided to generate 3 models based on these ratings. A Binary class model, where all the reviews with the rating of 1 to 5 are label as Negative and all the reviews with the rating of 6 to 10 are Positive. A Tertiary class model, where all the reviews with the rating of 1 to 3 are Negative, all the reviews with the rating of 4 to 6 are Neutral and all the reviews with the rating of 7 to 10 are Positive. A Five class model, where all the reviews with the rating of 1 to 2 are Highly Negative, all the reviews with the rating of 3 to 4 are Negative, all the reviews with the rating of 5 to 6 are Neutral, all the reviews with the rating of 7 to 8 are Positive, and all the reviews with the rating of 9 to 10 are Highly Positive. Code for the same can be found in the GenerateDataset file. When running the models make sure the generated CSVs are within a "dataset" folder. A detailed analysis has been provided in the report titled Sentiment Analysis # License Copyright 2019 <NAME>, <NAME>, <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>import pandas from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.metrics import accuracy_score from sklearn.model_selection import KFold from sklearn.multiclass import OneVsOneClassifier from sklearn.pipeline import Pipeline from sklearn.svm import LinearSVC import utils targetClass = 3 data = utils.getDataset(targetClass) data = utils.MapLabels(targetClass,data) data = utils.preprocess(data) model = Pipeline([ ('vect', CountVectorizer(lowercase = True,max_features = 4000,ngram_range=(1, 2))), ('tfidf', TfidfTransformer()), ('clf', OneVsOneClassifier(LinearSVC())), ]) kf = KFold(n_splits=10, random_state=43, shuffle=True) accurs = [] conf_matrix = [] tp = [] tn = [] fp = [] fn = [] for train_index, test_index in kf.split(data): X_train, X_test = data.iloc[train_index]['Comment'], data.iloc[test_index]['Comment'] y_train, y_test = data.iloc[train_index]['Label'], data.iloc[test_index]['Label'] model.fit(pandas.np.asarray(X_train), pandas.np.asarray(y_train)) prediction = model.predict(X_test) accur = accuracy_score(y_test, prediction) print("Score ", accur) accurs.append(accur) # tp,tn,fp,fn = confusion_matrix(y_test,prediction) # print("TP ",tp) # print("TN ",tn) # conf_matrix.append(matrix) print(pandas.np.mean(accurs)) # print(pandas.np.mean(conf_matrix)) # filename = 'finalized_logistic.sav' # joblib.dump(clf_svc, filename)
1ae4e438f1b7cd8216e7c733ac87024d5d9091fe
[ "Markdown", "Python" ]
4
Python
nawabhussain/sentiment_analysis
9664664e09f480fa9eb5a6bda3cd8d97d6e9fecc
9085399f64b99ee0f70bf4af88c4b3ebb82918cd
refs/heads/master
<repo_name>Flames-Of-Exile/FOE_Backend<file_sep>/migrations/versions/283f5f053505_.py """empty message Revision ID: 283f5f053505 Revises: 341063e49c43 Create Date: 2020-11-19 18:47:59.230119 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '283f5f053505' down_revision = '341063e49c43' branch_labels = None depends_on = None def upgrade(): op.execute("ALTER TYPE resource ADD VALUE 'BEAR'") op.execute("ALTER TYPE resource ADD VALUE 'GRYPHON'") def downgrade(): pass<file_sep>/tests/test_campaigns.py import json from .setup import BasicTests, Method from models import Campaign class CampaignTests(BasicTests): def test_list(self): response = self.request('/api/campaigns', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertIn(self.DEFAULT_CAMPAIGN.to_dict(), data) def test_retrieve(self): response = self.request('/api/campaigns/1', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_CAMPAIGN.to_dict(), response.get_json()) def test_query_name_found(self): response = self.request('/api/campaigns/q?name=campaign_name', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_CAMPAIGN.to_dict(), response.get_json()) def test_query_name_not_found(self): response = self.request('/api/campaigns/q?name=bad_name', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 404) def test_create_success(self): campaign = Campaign('new', '/mediafiles/campaigns/file.jpg') campaign.id = 2 response = self.create_campaign(self.DEFAULT_TOKEN, 'new', 'file.jpg', 'false') self.assertEqual(response.status_code, 201) self.assertEqual(campaign.to_dict(), response.get_json()) def test_create_fail_unique_name(self): response = self.create_campaign(self.DEFAULT_TOKEN, 'campaign_name', 'file.jpg', 'false') self.assertEqual(response.status_code, 400) self.assertIn(b'duplicate key value violates unique constraint "campaigns_name_key"', response.data) def test_create_fail_unique_filename(self): response = self.create_campaign(self.DEFAULT_TOKEN, 'new', 'campaign.png', 'false') self.assertEqual(response.status_code, 400) self.assertIn(b'duplicate key value violates unique constraint "campaigns_image_key"', response.data) def test_create_fail_invalid_extension(self): response = self.create_campaign(self.DEFAULT_TOKEN, 'new', 'file.pdf', 'false') self.assertEqual(response.status_code, 400) self.assertIn(b'invalid file type', response.data) def test_update(self): data = json.dumps({ 'is_default': True, 'is_archived': False, 'name': 'updated_name' }) response = self.request('/api/campaigns/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) self.assertDictContainsSubset({'is_default': True, 'is_archived': False, 'name': 'updated_name', 'image': '/mediafiles/campaigns/campaign.png'}, response.get_json()) def test_list_archived(self): data = json.dumps({ 'is_default': False, 'is_archived': True, 'name': 'campaign_name' }) self.request('/api/campaigns/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/campaigns/archived', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertDictContainsSubset({'is_default': False, 'is_archived': True, 'name': 'campaign_name', 'image': '/mediafiles/campaigns/campaign.png'}, data[0]) def test_list_no_archived(self): data = json.dumps({ 'is_default': False, 'is_archived': True, 'name': 'campaign_name' }) self.request('/api/campaigns/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/campaigns', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.get_json()), 0) def test_list_default_first(self): self.create_campaign(self.DEFAULT_TOKEN, 'default_campaign', 'default_campaign.jpg', 'true') self.create_campaign(self.DEFAULT_TOKEN, 'newest_campaign', 'newest_campaign.jpg', 'false') response = self.request('/api/campaigns', headers={'Authorization': self.DEFAULT_TOKEN}) data = response.get_json() self.assertEqual(response.status_code, 200) self.assertEqual(len(data), 3) self.assertEqual(data[0]['name'], 'default_campaign') self.assertEqual(data[1]['name'], 'newest_campaign') <file_sep>/permissions.py from functools import wraps from flask import Response from flask_jwt_extended import get_jwt_identity from models import User, Guild def is_active(user): if not user.is_active: return Response('account is locked', status=403) if not user.guild.is_active: return Response('guild is locked', status=403) if not user.discord_confirmed: return Response('has not confirmed account on discord', status=403) def is_administrator(func): @wraps(func) def wrapper(*args, **kwargs): user = User.query.get(get_jwt_identity()['id']) response = is_active(user) if response is not None: return response if user.role not in [User.Role.ADMIN]: return Response('requires administrator account', status=403) return func(*args, **kwargs) return wrapper def is_verified(func, **kwargs): @wraps(func) def wrapper(*args, **kwargs): user = User.query.get(get_jwt_identity()['id']) response = is_active(user) if response is not None: return response if user.role not in [User.Role.VERIFIED, User.Role.ADMIN]: return Response('requires verified account', status=403) return func(*args, **kwargs) return wrapper def is_discord_bot(func, **kwargs): @wraps(func) def wrapper(*args, **kwargs): user = User.query.get(get_jwt_identity()['id']) if not user.username == 'DiscordBot': return Response('only discord bot is allowed access', status=403) return func(*args, **kwargs) return wrapper def is_guild_leader(func, **kwargs): @wraps(func) def wrapper(*args, **kwargs): user = User.query.get(get_jwt_identity()['id']) response = is_active(user) if response is not None: return response if user.role not in [User.Role.GUILD_LEADER, User.Role.ADMIN]: return Response('requires Guild leader account', status=403) return func(*args, **kwargs) return wrapper # def is_alliance_member(func, **kwargs): # @wraps(func) # def wrapper(*args, **kwargs): # user = User.query.get(get_jwt_identity()['id']) # response = is_active(user) # if response is not None: # return response # if user.role not in [User.Role.ALLIANCE_MEMBER, User.Role.GUILD_LEADER, User.Role.VERIFIED, User.Role.ADMIN]: # return Response('requires active verified account', status=403) # guild = Guild.query.first_or_404(id == user.guild) # if guild.name != 'Flames of Exile': # return Response('requires a Flames of Exile account', status=403) # return func(*args, **kwargs) # return wrapper <file_sep>/manage.py import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from passlib.hash import sha256_crypt from app import create_app, socketio from config import main_config from models import db, Guild, User import socketevents # noqa: F401 app = create_app(main_config) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) @manager.command def create_admin(): foe_guild = Guild('Flames of Exile') db.session.add(foe_guild) db.session.commit foe_guild = db.session.query(Guild).filter_by(name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt(os.environ['BOT_PASSWORD']), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit() @manager.command def run(): socketio.run(app, host='0.0.0.0', port=5000, use_reloader=True, debug=True) # @manager.command # def migrate_media(): # from models import Campaign # os.chdir('mediafiles') # os.mkdir('campaigns') # os.chdir('campaigns') # for campaign in Campaign.query.all(): # os.rename(f'/usr/src/app{campaign.image}', f'/usr/src/app/mediafiles/campaigns/{campaign.image.split("/")[2]}') # os.mkdir(campaign.name.replace(' ', '_')) # os.chdir(campaign.name) # for world in campaign.worlds: # os.rename(f'/usr/src/app{world.image}', # f'/usr/src/app/mediafiles/campaigns/{campaign.name.replace(" ", "_")}/{world.image.split("/")[2]}') # os.mkdir(world.name) if __name__ == '__main__': manager.run() <file_sep>/requirements.txt # run pip install -r requirements.txt from FOE_Backend whith your venv active to install requirements eventlet==0.30.0 flask==1.1.2 flask_cors==3.0.9 Flask-JWT-Extended==3.25.0 Flask-Migrate==2.5.2 Flask-Script==2.0.6 Flask-SocketIO==5.1.0 Flask-SqlAlchemy==2.4.1 gunicorn==20.0.4 itsdangerous==1.1.0 passlib==1.7.4 Psycopg2==2.8.3 SQLAlchemy-serializer==1.3.4.2 requests pytz <file_sep>/migrations/versions/3ae558098c29_.py """empty message Revision ID: 3ae558098c29 Revises: <PASSWORD> Create Date: 2020-11-21 16:38:09.851671 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3ae558098c29' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): op.execute("ALTER TYPE resource ADD VALUE 'URGU'") op.execute("ALTER TYPE resource ADD VALUE 'ELEMENTALS'") op.execute("ALTER TYPE resource ADD VALUE 'SATYR'") op.execute("ALTER TYPE resource ADD VALUE 'ARACOIX'") op.execute("ALTER TYPE resource ADD VALUE 'UNDERHILL'") op.execute("ALTER TYPE resource ADD VALUE 'ENBARRI'") op.execute("ALTER TYPE resource ADD VALUE 'THRALLS'") op.execute("ALTER TYPE resource ADD VALUE 'SUNELF'") def downgrade(): pass<file_sep>/tests/test_pins.py import json from .setup import BasicTests, Method from models import Pin, User class PinTests(BasicTests): def test_list(self): response = self.request('/api/pins', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertIn(self.DEFAULT_PIN.to_dict(), data) def test_retrieve(self): response = self.request('/api/pins/1', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_PIN.to_dict(), response.get_json()) def test_create_success(self): response = self.create_pin(self.DEFAULT_TOKEN, 5, 5, Pin.Symbol.ANIMAL.value, Pin.Resource.WOLF.value, 1, 1, 1) self.assertEqual(response.status_code, 201) data = response.get_json() self.assertDictContainsSubset({'position_x': 5.0, 'position_y': 5.0, 'symbol': Pin.Symbol.ANIMAL.value, 'resource': Pin.Resource.WOLF.value}, data) def test_create_fail_invalid_world(self): response = self.create_pin(self.DEFAULT_TOKEN, 5, 5, Pin.Symbol.ANIMAL.value, Pin.Resource.WOLF.value, 2) self.assertEqual(response.status_code, 400) self.assertIn(b'violates foreign key constraint "pins_world_id_fkey"', response.data) def test_update(self): data = { 'position_x': 2.0, 'position_y': 2.5, 'symbol': Pin.Symbol.GRAVE.value, 'resource': Pin.Resource.HUMAN.value, 'rank': 10, 'name': 'some name', 'amount': 4, 'respawn': 30, 'notes': 'some notes', 'x_cord': 'x', 'y_cord': 2 } old_pin = self.DEFAULT_PIN.to_dict() response = self.request('/api/pins/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, json.dumps(data)) self.assertEqual(response.status_code, 200) edit_details = (f"position_x changed from {old_pin['position_x']} to {data['position_x']}\n" f"position_y changed from {old_pin['position_y']} to {data['position_y']}\n" f"symbol changed from {old_pin['symbol']} to {data['symbol']}\n" f"resource changed from {old_pin['resource']} to {data['resource']}\n" f"rank changed from {old_pin['rank']} to {data['rank']}\n" f"name changed from {old_pin['name']} to {data['name']}\n" f"amount changed from {old_pin['amount']} to {data['amount']}\n" f"respawn changed from {old_pin['respawn']} to {data['respawn']}\n" f"notes changed from {old_pin['notes']} to {data['notes']}\n" f"x_cord changed from {old_pin['x_cord']} to {data['x_cord']}\n" f"y_cord changed from {old_pin['y_cord']} to {data['y_cord']}\n") res_data = response.get_json() self.assertEqual(res_data['edits'][1]['details'], edit_details) self.assertEqual(res_data['edits'][1]['user']['id'], 1) self.assertDictContainsSubset(data, res_data) def test_delete(self): response = self.request('/api/pins/1', Method.DELETE, {'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) response = self.request('/api/pins', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(len(response.get_json()), 0) def test_delete_fail(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.VERIFIED.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "1qaz!QAZ").get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/pins/1', Method.DELETE, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'only the creator or an admin can delete a pin', response.data) <file_sep>/views/users.py import re import os import traceback import requests import logging import sys from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import create_access_token, create_refresh_token, decode_token, get_jwt_identity, jwt_required from passlib.hash import sha256_crypt from sqlalchemy.exc import IntegrityError from discord_token import confirm_token, generate_confirmation_token from models import db, User, Guild from permissions import is_discord_bot, is_verified, is_guild_leader from logger import get_logger log = logging.getLogger('discord') log.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) log.addHandler(handler) users = Blueprint('users', __name__, url_prefix='/api/users') _SITE_TOKEN = os.getenv('SITE_TOKEN') _BASE_URL = os.getenv('FRONTEND_URL') BOT_URL = os.getenv('BOT_URL') + '/bot' VERIFY_SSL = bool(int(os.getenv('VERIFY_SSL'))) log = get_logger(__name__) @users.route('', methods=['GET']) @jwt_required @is_verified def ListUsers(): return jsonify([user.to_dict() for user in User.query.all()]) @users.route('', methods=['POST']) def CreateUser(): json = request.json validation_result = PassComplexityCheck(json['password']) if validation_result['password_ok'] is False: response = jsonify(validation_result) response.status_code = 400 return response try: newUser = User( json['username'] or None, sha256_crypt.encrypt(json['password']) or None, json['guild_id'] ) db.session.add(newUser) db.session.commit() log.info(json) del json['password'] if json['currentMember'] is False: json['SITE_TOKEN'] = _SITE_TOKEN log.info(json) requests.post(BOT_URL + "/application", json=json, verify=VERIFY_SSL) data = {} data['user'] = newUser.to_dict() data['token'] = create_access_token(identity=newUser.to_dict()) data = jsonify(data) data.set_cookie('refresh_token', create_refresh_token(identity=newUser.to_dict()), httponly=True, secure=True) data.status_code = 201 return data except IntegrityError as error: return Response(error.args[0], status=400) @users.route('/login', methods=['POST']) def Login(): json = request.json try: user = User.query.filter_by(username=json['username']).first() if sha256_crypt.verify(json['password'], user.password): data = {} data['user'] = user.to_dict() data['token'] = create_access_token(identity=user.to_dict()) response = jsonify(data) response.set_cookie('refresh_token', create_refresh_token(identity=user.to_dict()), httponly=True, secure=True) return response else: return Response('invalid username/password', status=400) except (IntegrityError, AttributeError): log.warning(traceback.format_exc()) return Response('invalid username/password', status=400) @users.route('/<id>', methods=['GET']) @jwt_required @is_verified def RetrieveUser(id=0): return jsonify(User.query.get_or_404(id).to_dict()) @users.route('/<id>', methods=['PATCH']) @jwt_required def UpdateUser(id=0): user = User.query.get_or_404(id) if (get_jwt_identity()['id'] != int(id)): return Response('can only update your own account', status=403) try: json = request.json if 'password' in json.keys(): user.password = <PASSWORD>(json['password']) or None user.theme = User.Theme(json['theme']) or None db.session.commit() return jsonify(user.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @users.route('/<id>', methods=['PUT']) @jwt_required @is_guild_leader def AdminUpdateUser(id=0): user = User.query.get_or_404(id) if get_jwt_identity()['id'] == int(id): return Response('cannot update your own account', status=403) admin = User.query.get_or_404(get_jwt_identity()['id']) try: if admin.role not in [User.Role.ADMIN]: if admin.guild != user.guild: return Response('must be in the guild you are atempting to edit', status=403) json = request.json if ('password' in json.keys()): user.password = <PASSWORD>(json['password']) if user.guild_id != json['guild_id']: user.guild_id = json['guild_id'] data = {'user': user.discord, 'guildTag': Guild.query.filter_by(id=json['guild_id']).first_or_404().nickname} log.warning(data) requests.post(BOT_URL + '/updateUser', json=data, verify=VERIFY_SSL) user.is_active = json['is_active'] if User.Role(json['role']) == User.Role.ADMIN: if admin.role in [User.Role.ADMIN]: user.role = User.Role(json['role']) else: user.role = User.Role(json['role']) or None db.session.commit() return jsonify(user.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @users.route('/refresh', methods=['GET']) def RefreshSession(): refresh_token = request.cookies.get('refresh_token') user = User.query.get(decode_token(refresh_token)['identity']['id']) user = user.to_dict() data = {} data['user'] = user data['token'] = create_access_token(identity=user) return jsonify(data) @users.route('/logout', methods=['GET']) def Logout(): response = Response("") response.delete_cookie('refresh_token') return response @users.route('/confirm', methods=['PUT']) @jwt_required @is_discord_bot def ConfirmDiscord(): json = request.json user = User.query.filter_by(username=json['username']).first_or_404() token = json['token'] if user.discord_confirmed is True: return Response('user has already confirmed their discord', status=400) username = confirm_token(token) if username == user.username: try: user.discord_confirmed = True user.discord = json['discord'] if json['member']: user.role = User.Role('verified') db.session.commit() except IntegrityError as error: return Response(error.args[0], status=400) return jsonify(user.to_dict()) return Response('invalid user/token', status=400) @users.route('/discord-token', methods=['GET']) @jwt_required def ResendConfirmation(): user = User.query.get(get_jwt_identity()['id']) if user.discord_confirmed is True: return Response('user has already confirmed their discord', status=400) token = generate_confirmation_token(user.username) return jsonify({'token': token}) @users.route('/discord/<discord_id>', methods=['GET']) @jwt_required @is_discord_bot def GetUserByDiscord(discord_id=0): user = User.query.filter_by(discord=discord_id).first_or_404() return jsonify(user.to_dict()) @users.route('/discordRoles/<discord_id>', methods=['PATCH']) @jwt_required @is_discord_bot def Revoke_user_Access(discord_id=0): user = User.query.filter_by(discord=discord_id).first_or_404() json = request.json try: if 'is_active' in json: user.is_active = json['is_active'] if 'role' in json: user.role = User.Role(json['role']) db.session.commit() return jsonify(user.to_dict()), 200 except IntegrityError: return jsonify('could not complete the requested action'), 400 @users.route('/password-reset/<discord_id>', methods=['PATCH']) @jwt_required @is_discord_bot def ResetPassword(discord_id=0): user = User.query.filter_by(discord=discord_id).first_or_404() json = request.json validation_result = PassComplexityCheck(json['password']) if validation_result['password_ok'] is False: response = jsonify(validation_result) response.status_code = 400 return response user.password = <PASSWORD>(json['password']) db.session.commit() return jsonify(user.to_dict()) @users.route('/alliance/vouch', methods=['PATCH']) @jwt_required @is_discord_bot def vouch_for_member(): json = request.json log.warning(type(json['diplo'])) diplo = User.query.filter_by(discord=str(json['diplo'])).first_or_404() user = User.query.filter_by(discord=str(json['target_user'])).first_or_404() if diplo.guild_id == user.guild_id or diplo.role == User.Role.ADMIN: user.role = User.Role.ALLIANCE_MEMBER user.is_active = True log.warning(user.guild.id) db.session.commit() guild = Guild.query.filter_by(id=user.guild_id).first_or_404() guild_tag = guild.nickname user_dict = user.to_dict() user_dict['guild_tag'] = guild_tag response = jsonify(user_dict) response.status_code = 200 return response return jsonify('must be member of same guild to manage'), 403 @users.route('/alliance/endvouch', methods=['PATCH']) @jwt_required @is_discord_bot def endvouch_for_member(): json = request.json diplo = User.query.filter_by(discord=str(json['diplo'])).first_or_404() user = User.query.filter_by(discord=str(json['target_user'])).first_or_404() if diplo.guild_id == user.guild_id or diplo.role == User.Role.ADMIN: user.is_active = False user.role = User.Role.GUEST db.session.commit() response = jsonify(user.to_dict()) response.status_code = 200 return response return jsonify('must be member of same guild to manage'), 403 def PassComplexityCheck(password): # calculating the length length_error = (len(password) < 8) # searching for digits digit_error = re.search(r"\d", password) is None # searching for uppercase uppercase_error = re.search(r"[A-Z]", password) is None # searching for lowercase lowercase_error = re.search(r"[a-z]", password) is None # searching for symbols symbol_error = re.search(r"\W", password) is None # overall result password_ok = not (length_error or digit_error or uppercase_error or lowercase_error or symbol_error) return { 'password_ok': password_ok, 'length_error': length_error, 'digit_error': digit_error, 'uppercase_error': uppercase_error, 'lowercase_error': lowercase_error, 'symbol_error': symbol_error, } <file_sep>/socketevents.py import functools from flask import request, jsonify from flask_jwt_extended import decode_token from flask_socketio import disconnect, emit from jwt.exceptions import DecodeError import pytz from models import Campaign, User, Event from app import socketio from logger import get_logger timezone = pytz.utc log = get_logger(__name__) def requires_authentication(function): @functools.wraps(function) def wrapper(*args, **kwargs): refresh_token = request.cookies.get('refresh_token') try: user = User.query.get(decode_token(refresh_token)['identity']['id']) except DecodeError: disconnect() return False if (not user.is_active or not user.guild.is_active or not user.discord_confirmed or user.role not in [User.Role.VERIFIED, User.Role.ADMIN]): disconnect() return False return function(*args, **kwargs) return wrapper @requires_authentication @socketio.on('connect') def on_connect(): pass @requires_authentication @socketio.on('campaign-update') def handle_campaign_update(): data = [campaign.to_dict() for campaign in Campaign.query.filter_by(is_archived=False) .order_by(Campaign.is_default.desc(), Campaign.id.desc()).all()] emit('campaign-update', data, broadcast=True) @requires_authentication @socketio.on('calendar-update') def handle_calendar_update(): log.info('socket calendar-update') events = Event.query.order_by(Event.active.desc()).order_by(Event.date).all() for event in events: event.date = timezone.localize(event.date) return jsonify([event.to_dict() for event in events]) <file_sep>/README.md # FOE_Backend This is the start of the Python Backend of the Flames of Exile Web Service ## To get set up and ready to contribute to the project follow the steps below ### To set up project first set up a virtual environment If you don't know how to do that 1. In your terminal run the python venv command (replaceing 'name_of_environment' with the desired name of your environment) from one level over the root of your project. `python -m venv [name_of_environment]` 2. Navigate down into your new virtual enviroment folder then into the scripts sub folder. 3. run the activate script from your terminal ### Install the required packages to your virtual environment. This will need to be repeated any time new required packages are added to the project. 1. From inside your virtual enviroment navigate into the FOE_Backend folder and in your terminal run `python -m install -r requirements.txt` This will add any needed packages for the project. ## To run the application development server. 1. Navigate to the FOE_Backend folder from inside your virtual environment. 2. run `flask run` in your terminal. 4. This will start the development server. Any time you make changes to the server you will need to restart it for it to serve the most up to date content.<file_sep>/tests/setup.py import enum import io import json import unittest import datetime from passlib.hash import sha256_crypt from app import create_app from config import test_config from models import db, Campaign, Edit, Guild, Pin, User, World, Event class Method(enum.Enum): DELETE = 'delete' GET = 'get' PATCH = 'patch' POST = 'post' PUT = 'put' class BasicTests(unittest.TestCase): def setUp(self): app = create_app(test_config) with app.app_context(): db.drop_all() db.create_all() self.app = app.test_client() self.app_context = app.app_context() self.app_context.push() guild = Guild('Flames of Exile') db.session.add(guild) db.session.commit() foe_guild = db.session.query(Guild).filter_by(name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit() campaign = Campaign('campaign_name', '/mediafiles/campaigns/campaign.png', True) db.session.add(campaign) db.session.commit() world = World('world_name', '/mediafiles/campaigns/campaign_name/world.png', 1, 1, 1, 1) db.session.add(world) db.session.commit() pin = Pin(1, 1, Pin.Symbol.ANIMAL, Pin.Resource.WOLF, 1, 1, '', 1, 1, 'notes', 1, 1) db.session.add(pin) db.session.commit() edit = Edit("", 1, 1) db.session.add(edit) db.session.commit() event = Event('event', 'game', datetime.datetime.now().isoformat(), 'note') db.session.add(event) db.session.commit() self.DEFAULT_GUILD = guild self.DEFAULT_USER = admin self.DEFAULT_CAMPAIGN = campaign self.DEFAULT_WORLD = world self.DEFAULT_PIN = pin self.DEFAULT_TOKEN = f'Bearer {self.login("DiscordBot", "admin").get_json()["token"]}' self.DEFAULT_EVENT = event self.maxDiff = None self.assertEqual(app.debug, False) def tearDown(self): self.app_context.pop() def request(self, url, method=Method.GET, headers={}, data={}, content_type='application/json'): if method is Method.DELETE: return self.app.delete(url, follow_redirects=True, headers=headers) if method is Method.GET: return self.app.get(url, follow_redirects=True, headers=headers) if method is Method.PATCH: return self.app.patch(url, data=data, follow_redirects=True, content_type=content_type, headers=headers) if method is Method.PUT: return self.app.put(url, data=data, follow_redirects=True, content_type=content_type, headers=headers) if method is Method.POST: return self.app.post(url, data=data, follow_redirects=True, content_type=content_type, headers=headers) def login(self, username, password): data = json.dumps({'username': username, 'password': <PASSWORD>}) return self.request('/api/users/login', Method.POST, {}, data) def register(self, username, password, guild_id, currentMember): data = json.dumps({'username': username, 'password': <PASSWORD>, 'guild_id': guild_id, 'currentMember': currentMember}) return self.request('/api/users', Method.POST, {}, data) def logout(self): return self.request('/api/users/logout') def create_campaign(self, token, name, filename, is_default): data = {'name': name, 'is_default': is_default, 'file': (io.BytesIO(b'mockdata'), filename)} headers = {'Authorization': token} return self.request('/api/campaigns', Method.POST, headers, data, 'multipart/form-data') def create_world(self, token, name, filename, center_lng, center_lat, radius, campaign_id): data = {'name': name, 'campaign_id': campaign_id, 'file': (io.BytesIO(b'mockdata'), filename), 'center_lng': center_lng, 'center_lat': center_lat, 'radius': radius} headers = {'Authorization': token} return self.request('/api/worlds', Method.POST, headers, data, 'multipart/form-data') def create_pin(self, token, position_x, position_y, symbol, resource, world_id, rank=0, name='', amount=0, respawn=0, notes='', x_cord=1, y_cord=1): data = json.dumps({ 'position_x': position_x, 'position_y': position_y, 'symbol': symbol, 'resource': resource, 'world_id': world_id, 'rank': rank, 'name': name, 'amount': amount, 'respawn': respawn, 'notes': notes, 'x_cord': x_cord, 'y_cord': y_cord }) headers = {'Authorization': token} return self.request('/api/pins', Method.POST, headers, data) def create_guild(self, token, name): data = json.dumps({'name': name}) headers = {'Authorization': token} return self.request('/api/guilds', Method.POST, headers, data) def create_event(self, name, game, date, note, token): data = json.dumps({ 'name': name, 'game': game, 'date': date, 'note': note }) headers = {'Authorization': token} return self.request('/api/calendar', Method.POST, headers, data) def edit_event(self, id, name, game, date, note, token): data = json.dumps({ 'name': name, 'game': game, 'date': date, 'note': note }) headers = {'Authorization': token} return self.request(f'/api/calendar/{id}', Method.PATCH, headers, data) <file_sep>/tests/test_discord.py from .setup import BasicTests from discord_token import confirm_token, generate_confirmation_token class DiscordTests(BasicTests): def test_generate_token_generates_string(self): username = "test" token = generate_confirmation_token(username) self.assertEqual(type(token), str) self.assertNotEqual(token, username) def test_confirm_token_success(self): username = "test" token = generate_confirmation_token(username) result = confirm_token(token) self.assertEqual(result, username) def test_confirm_token_fail_incorrect_username(self): username = "test" token = generate_confirmation_token("not_test") result = confirm_token(token) self.assertNotEqual(username, result) def test_confirm_token_fail_expiration(self): username = "test" token = generate_confirmation_token(username) result = confirm_token(token, -1) self.assertFalse(result) <file_sep>/tests/test_socket.py import json import unittest from flask_socketio import SocketIO from passlib.hash import sha256_crypt from app import create_app from config import test_config from models import db, Campaign, Guild, User from socketevents import handle_campaign_update, on_connect class SocketTests(unittest.TestCase): def setUp(self): app = create_app(test_config) with app.app_context(): db.drop_all() db.create_all() self.app = app self.test_client = app.test_client() self.app_context = app.app_context() self.app_context.push() self.socketio = SocketIO(app) self.socketio.on_event('connect', on_connect) self.socketio.on_event('campaign-update', handle_campaign_update) guild = Guild('Flames of Exile') db.session.add(guild) db.session.commit() foe_guild = db.session.query(Guild).filter_by(name='Flames of Exile').first() admin = User('DiscordBot', sha256_crypt.encrypt('admin'), foe_guild.id, User.Role.ADMIN) admin.discord_confirmed = True db.session.add(admin) db.session.commit() campaign = Campaign('campaign_name', '/mediafiles/campaign.png', True) db.session.add(campaign) db.session.commit() self.campaign = campaign.to_dict() self.maxDiff = None self.assertEqual(app.debug, False) def tearDown(self): self.app_context.pop() def test_connection_rejected_without_authentication(self): self.test_client.get('/api/users/logout') socketio_test_client = self.socketio.test_client(self.app, flask_test_client=self.test_client) self.assertFalse(socketio_test_client.is_connected()) def test_connection_success_with_authentication(self): data = json.dumps({'username': 'DiscordBot', 'password': '<PASSWORD>'}) self.test_client.post('/api/users/login', data=data, follow_redirects=True, content_type='application/json') socketio_test_client = self.socketio.test_client(self.app, flask_test_client=self.test_client) self.assertTrue(socketio_test_client.is_connected()) def test_campaign_update(self): data = json.dumps({'username': 'DiscordBot', 'password': '<PASSWORD>'}) self.test_client.post('/api/users/login', data=data, follow_redirects=True, content_type='application/json') socketio_test_client = self.socketio.test_client(self.app, flask_test_client=self.test_client) socketio_test_client.emit('campaign-update') data = socketio_test_client.get_received()[0]['args'][0] self.assertIn(self.campaign, data) <file_sep>/tests/test_calendar.py import json from datetime import datetime from .setup import BasicTests, Method class CalendarTests(BasicTests): def test_get_all_events(self): response = self.request('/api/calendar', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertIn(self.DEFAULT_EVENT.to_dict(), data) def test_delete_event(self): response = self.request('/api/calendar/1', Method.DELETE, headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 204) def test_create_event_fail_game(self): data = json.dumps({ 'name': 'name', 'date': datetime.now().isoformat(), 'note': 'note' }) headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar', Method.POST, headers, data) self.assertEqual(response.status_code, 400) def test_create_event_fail_name(self): data = json.dumps({ 'game': 'game', 'date': datetime.now().isoformat(), 'note': 'note' }) headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar', Method.POST, headers, data) self.assertEqual(response.status_code, 400) def test_create_event_fail_date(self): data = json.dumps({ 'name': 'name', 'game': 'game', 'note': 'note' }) headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar', Method.POST, headers, data) self.assertEqual(response.status_code, 400) def test_create_event_fail_note(self): data = json.dumps({ 'name': 'name', 'game': 'game', 'date': datetime.now().isoformat(), }) headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar', Method.POST, headers, data) self.assertEqual(response.status_code, 400) def test_create_event(self): response = self.create_event('name', 'game', datetime.now().isoformat(), 'note', self.DEFAULT_TOKEN) self.assertEqual(response.status_code, 201) def test_edit_name(self): data = self.DEFAULT_EVENT.to_dict() data['name'] = 'edit' headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar/1', Method.PATCH, headers=headers, data=json.dumps(data)) self.assertEqual(response.status_code, 201) self.assertEqual(response.json['name'], 'edit') def test_edit_game(self): data = self.DEFAULT_EVENT.to_dict() data['game'] = 'edit' headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar/1', Method.PATCH, headers=headers, data=json.dumps(data)) self.assertEqual(response.status_code, 201) self.assertEqual(response.json['game'], 'edit') def test_edit_date(self): data = self.DEFAULT_EVENT.to_dict() date = datetime.now().isoformat() data['date'] = date headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar/1', Method.PATCH, headers=headers, data=json.dumps(data)) datea = date.split('.')[0][:-3].split('T') datea = datea[0] + ' ' + datea[1] dateb = response.json['date'] self.assertEqual(response.status_code, 201) self.assertEqual(dateb, datea) def test_edit_note(self): data = self.DEFAULT_EVENT.to_dict() data['note'] = 'edit' headers = {'Authorization': self.DEFAULT_TOKEN} response = self.request('/api/calendar/1', Method.PATCH, headers=headers, data=json.dumps(data)) self.assertEqual(response.status_code, 201) self.assertEqual(response.json['note'], 'edit') <file_sep>/tests/test_auth.py from .setup import BasicTests from models import User from passlib.hash import sha256_crypt class AuthTests(BasicTests): def test_login_success(self): response = self.login('DiscordBot', 'admin') self.assertEqual(response.status_code, 200) data = response.get_json() self.assertIn('token', data) self.assertEqual(self.DEFAULT_USER.to_dict(), data['user']) self.assertIn('Set-Cookie', response.headers) def test_login_fails(self): response = self.login('DiscordBot', '<PASSWORD>') self.assertEqual(response.status_code, 400) self.assertIn(b'invalid username/password', response.data) self.assertNotIn('Set-Cookie', response.headers) response = self.login('wrongusername', 'admin') self.assertEqual(response.status_code, 400) self.assertIn(b'invalid username/password', response.data) self.assertNotIn('Set-Cookie', response.headers) response = self.login('', '') self.assertEqual(response.status_code, 400) self.assertIn(b'invalid username/password', response.data) self.assertNotIn('Set-Cookie', response.headers) def test_register_success(self): user = User('new', sha256_crypt.encrypt('1qaz!QAZ'), self.DEFAULT_GUILD.id, User.Role.GUEST) user.id = 2 response = self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 201) user.guild = self.DEFAULT_GUILD data = response.get_json() self.assertIn('token', data) self.assertEqual(user.to_dict(), data['user']) self.assertIn('Set-Cookie', response.headers) def test_register_fail_unique_username(self): response = self.register('DiscordBot', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) self.assertIn(b'Key (username)=(DiscordBot) already exists.', response.data) self.assertNotIn('Set-Cookie', response.headers) def test_register_fail_empty_username(self): response = self.register('', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) self.assertIn(b'null value in column "username" violates not-null constraint', response.data) self.assertNotIn('Set-Cookie', response.headers) def test_register_fail_empty_password(self): response = self.register('new', '', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) self.assertNotIn('Set-Cookie', response.headers) def test_logout(self): response = self.logout() self.assertIn('refresh_token=;', response.headers['Set-Cookie']) def test_password_complexity_length_fail(self): response = self.register('new', '1qaz!QA', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 1) self.assertIn('length_error', marked_errors) def test_password_complexity_digit_fail(self): response = self.register('new', 'qqaz!QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 1) self.assertIn('digit_error', marked_errors) def test_password_complexity_lowercase_fail(self): response = self.register('new', '1QAZ!QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 1) self.assertIn('lowercase_error', marked_errors) def test_password_complexity_uppercase_fail(self): response = self.register('new', '1qaz!qaz', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 1) self.assertIn('uppercase_error', marked_errors) def test_password_complexity_symbol_fail(self): response = self.register('new', '1qaz1QAZ', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 1) self.assertIn('symbol_error', marked_errors) def test_password_complexity_multi_fail(self): response = self.register('new', '1qaz', self.DEFAULT_GUILD.id, True) self.assertEqual(response.status_code, 400) data = response.get_json() marked_errors = list(filter(lambda key: data[key] is True, data.keys())) self.assertEqual(len(marked_errors), 3) self.assertIn('length_error', marked_errors) self.assertIn('uppercase_error', marked_errors) self.assertIn('symbol_error', marked_errors) def test_refresh_success(self): response = self.request('/api/users/refresh') self.assertEqual(response.status_code, 200) data = response.get_json() self.assertIn('token', data) self.assertEqual(self.DEFAULT_USER.to_dict(), data['user']) def test_refresh_no_cookie_fail(self): self.logout() response = self.request('/api/users/refresh') self.assertEqual(response.status_code, 422) self.assertIn(b'Invalid token type.', response.data) <file_sep>/tests/test_worlds.py import json from .setup import BasicTests, Method from models import World class WorldTests(BasicTests): def test_list(self): response = self.request('/api/worlds', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertIn(self.DEFAULT_WORLD.to_dict(), data) def test_retrieve(self): response = self.request('/api/worlds/1', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_WORLD.to_dict(), response.get_json()) def test_create_success(self): world = World('new', '/mediafiles/campaigns/campaign_name/file.jpg', 1, 1, 1, 1) world.id = 2 world = world.to_dict() del world['campaign'] response = self.create_world(self.DEFAULT_TOKEN, 'new', 'file.jpg', 1, 1, 1, 1) self.assertEqual(response.status_code, 201) json = response.get_json() self.assertDictContainsSubset(world, json) def test_create_fail_unique_filename(self): response = self.create_world(self.DEFAULT_TOKEN, 'new', 'world.png', 1, 1, 1, 1) self.assertEqual(response.status_code, 400) self.assertIn(b'duplicate key value violates unique constraint "worlds_image_key"', response.data) def test_create_fail_invalid_extension(self): response = self.create_world(self.DEFAULT_TOKEN, 'new', 'file.pdf', 1, 1, 1, 1) self.assertEqual(response.status_code, 400) self.assertIn(b'invalid file type', response.data) def test_create_fail_invalid_campaign(self): response = self.create_world(self.DEFAULT_TOKEN, 'new', 'file.jpg', 1, 1, 1, 2) self.assertEqual(response.status_code, 400) self.assertIn(b"object has no attribute 'name'", response.data) def test_update(self): data = json.dumps({ 'name': 'updated_name', 'campaign_id': 1, 'center_lat': 1, 'center_lng': 1, 'radius': 1 }) response = self.request('/api/worlds/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertDictContainsSubset({'name': 'updated_name'}, data) def test_query_name(self): response = self.request(f'/api/worlds/q?campaign={self.DEFAULT_CAMPAIGN.name}&world={self.DEFAULT_WORLD.name}', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_WORLD.to_dict(), response.get_json()) <file_sep>/app.py import os from flask import Flask from flask_cors import CORS from flask_jwt_extended import JWTManager from flask_socketio import SocketIO socketio = SocketIO() def create_app(config): app = Flask(__name__) CORS(app) app.config.update(config) from models import db db.init_app(app) from views.campaigns import campaigns from views.guilds import guilds from views.pins import pins from views.users import users from views.worlds import worlds from views.calendar import calendar app.register_blueprint(campaigns) app.register_blueprint(guilds) app.register_blueprint(pins) app.register_blueprint(users) app.register_blueprint(worlds) app.register_blueprint(calendar) JWTManager(app) socketio.init_app(app, cors_allowed_origins=os.environ['FRONTEND_URL']) return app if __name__ == '__main__': app = create_app() <file_sep>/models.py import datetime import enum from flask_sqlalchemy import SQLAlchemy from sqlalchemy_serializer import SerializerMixin db = SQLAlchemy() class User(db.Model, SerializerMixin): __tablename__ = 'users' class Role(enum.Enum): GUEST = 'guest' VERIFIED = 'verified' ADMIN = 'admin' GUILD_LEADER = 'guild_leader' ALLIANCE_MEMBER = 'alliance_member' class Theme(enum.Enum): DEFAULT = 'default' BLUE_RASPBERRY = 'blue_raspberry' SEABREEZE = 'seabreeze' CARTOGRAPHY = 'cartography' PUMPKIN_SPICE = 'pumpkin_spice' RED = 'red' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(), nullable=False, unique=True) password = db.Column(db.String(), nullable=False) discord = db.Column(db.String(), unique=True) is_active = db.Column(db.Boolean(), nullable=False) role = db.Column(db.Enum(Role), nullable=False) theme = db.Column(db.Enum(Theme), nullable=False) discord_confirmed = db.Column(db.Boolean(), nullable=False) edits = db.relationship('Edit', backref='user', lazy=True) guild_id = db.Column(db.Integer, db.ForeignKey('guilds.id'), nullable=False) serialize_only = ('id', 'username', 'is_active', 'role', 'theme', 'edits.id', 'discord_confirmed', 'guild.id', 'guild.name', 'guild.is_active') def __init__(self, username, password, guild_id, role=Role.GUEST): self.username = username self.password = <PASSWORD> self.discord = None self.is_active = True self.role = role self.theme = User.Theme.DEFAULT self.discord_confirmed = False self.guild_id = guild_id def __repr__(self): return f'{self.id}: {self.username}' class Campaign(db.Model, SerializerMixin): __tablename__ = 'campaigns' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(), nullable=False, unique=True) image = db.Column(db.String(), nullable=False, unique=True) worlds = db.relationship('World', backref='campaign', lazy=True) is_default = db.Column(db.Boolean()) is_archived = db.Column(db.Boolean()) serialize_rules = ('-worlds.campaign',) def __init__(self, name, image, is_default=False): self.name = name self.image = image self.is_default = is_default self.is_archived = False def __repr__(self): return f'{self.id}: {self.name}' class World(db.Model, SerializerMixin): __tablename__ = 'worlds' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(), nullable=False) image = db.Column(db.String(), nullable=False, unique=True) center_lat = db.Column(db.Float, nullable=False) center_lng = db.Column(db.Float, nullable=False) radius = db.Column(db.Float, nullable=False) campaign_id = db.Column(db.Integer, db.ForeignKey('campaigns.id'), nullable=False) pins = db.relationship('Pin', backref='world', lazy=True) __table_args__ = (db.UniqueConstraint('name', 'campaign_id', name='campaign_name'),) serialize_rules = ('-campaign_id', '-pins.world') def __init__(self, name, image, center_lat, center_lng, radius, campaign_id): self.name = name self.image = image self.center_lat = center_lat self.center_lng = center_lng self.radius = radius self.campaign_id = campaign_id def __repr__(self): return f'{self.id}: {self.name}' class Pin(db.Model, SerializerMixin): __tablename__ = "pins" class Symbol(enum.Enum): STONE = 'stone' STONE_MOTHERLODE = 'stone-motherlode' ORE = 'ore' ORE_MOTHERLODE = 'ore-motherlode' WOOD = 'wood' ANIMAL = 'animal' ANIMAL_BOSS = 'animal-boss' MOB = 'mob' MOB_BOSS = 'mob-boss' WELL = 'well' GRAVE = 'grave' TACTICAL_HOUSE = 'tactical-house' TACTICAL_FIRE = 'tactical-fire' TACTICAL_FISH = 'tactical-fish' class Resource(enum.Enum): YEW = 'yew' BIRCH = 'birch' ASH = 'ash' OAK = 'oak' SPRUCE = 'spruce' COPPER = 'copper' TIN = 'tin' IRON = 'iron' SILVER = 'silver' AURELIUM = 'aurelium' GRANITE = 'granite' LIMESTONE = 'limestone' TRAVERTINE = 'travertine' SLATE = 'slate' MARBLE = 'marble' SPIDER = 'spider' PIG = 'pig' CAT = 'cat' AUROCH = 'auroch' ELK = 'elk' WOLF = 'wolf' GRYPHON = 'gryphon' BEAR = 'bear' HUMAN = 'human' ELVEN = 'elven' MONSTER = 'monster' STONEBORN = 'stoneborn' GUINECIAN = 'guinecian' URGU = 'urgu' ELEMENTALS = 'elementals' SATYR = 'satyr' ARACOIX = 'aracoix' THRALLS = 'thralls' UNDERHILL = 'underhill' ENBARRI = 'enbarri' SUNELF = 'sun elf' NA = 'na' id = db.Column(db.Integer, primary_key=True) position_x = db.Column(db.Float, nullable=False) position_y = db.Column(db.Float, nullable=False) symbol = db.Column(db.Enum(Symbol), nullable=False) resource = db.Column(db.Enum(Resource), nullable=False) rank = db.Column(db.Integer) name = db.Column(db.String()) amount = db.Column(db.Integer) notes = db.Column(db.String()) respawn = db.Column(db.Integer) world_id = db.Column(db.Integer, db.ForeignKey('worlds.id'), nullable=False) edits = db.relationship('Edit', backref='pin', lazy=True, cascade='all, delete') x_cord = db.Column(db.String(1)) y_cord = db.Column(db.Float) serialize_rules = ('-edits.pin',) def __init__(self, position_x, position_y, symbol, resource, world_id, rank, name, amount, respawn, notes, x_cord, y_cord): self.position_x = position_x self.position_y = position_y self.symbol = symbol self.resource = resource self.world_id = world_id self.rank = rank self.name = name self.amount = amount self.respawn = respawn self.notes = notes self.x_cord = x_cord self.y_cord = y_cord def __repr__(self): return f'{self.id}: {self.symbol} - {self.position_x}/{self.position_y}' class Edit(db.Model, SerializerMixin): __tablename__ = "edits" id = db.Column(db.Integer, primary_key=True) details = db.Column(db.String()) date_time = db.Column(db.DateTime(), nullable=False) pin_id = db.Column(db.Integer, db.ForeignKey('pins.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) serialize_rules = ('-pin_id', '-user_id') def __init__(self, details, pin_id, user_id): self.details = details self.pin_id = pin_id self.user_id = user_id self.date_time = datetime.datetime.utcnow() def __repr__(self): return f'{self.id}: {self.details} - {self.datetime}' class Guild(db.Model, SerializerMixin): __tablename__ = "guilds" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(), nullable=False, unique=True) is_active = db.Column(db.Boolean(), nullable=False) users = db.relationship('User', backref='guild', lazy=True) nickname = db.Column(db.String()) serialize_rules = ('-users.guild', '-users.email') def __init__(self, name, nickname=None): self.name = name self.is_active = True self.nickname = nickname def __repr__(self): return f'{self.id}: {self.name} - {self.is_active} - {self.nickname}' class Event(db.Model, SerializerMixin): __tablename__ = "event" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(), nullable=False) game = db.Column(db.String(), nullable=False) date = db.Column(db.DateTime(), nullable=False) note = db.Column(db.String()) active = db.Column(db.Boolean) def __init__(self, name, game, date, note=None, active=True): self.name = name self.game = game self.date = date self.note = note self.active = active <file_sep>/views/campaigns.py import os from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import jwt_required from sqlalchemy.exc import IntegrityError from werkzeug.utils import secure_filename from models import db, Campaign from permissions import is_administrator, is_verified from upload import allowed_file campaigns = Blueprint('campaigns', __name__, url_prefix='/api/campaigns') @campaigns.route('', methods=['GET']) @jwt_required @is_verified def ListCampaigns(): return jsonify([campaign.to_dict() for campaign in Campaign.query.filter_by(is_archived=False) .order_by(Campaign.is_default.desc(), Campaign.id.desc()).all()]) @campaigns.route('', methods=['POST']) @jwt_required @is_verified def CreateCampaign(): if 'file' not in request.files: return Response('no file found', status=400) file = request.files['file'] if not allowed_file(file.filename): return Response('invalid file type', status=400) try: newCampaign = Campaign(request.form['name'] or None, f'/mediafiles/campaigns/{secure_filename(file.filename)}') if request.form['is_default'] == 'true': old_default = Campaign.query.filter_by(is_default=True).all() for camp in old_default: camp.is_default = False newCampaign.is_default = True db.session.add(newCampaign) db.session.commit() os.makedirs(f'/usr/src/app/mediafiles/campaigns/{newCampaign.name.replace(" ", "_")}', exist_ok=True) file.save(f'/usr/src/app{newCampaign.image}') data = jsonify(newCampaign.to_dict()) data.status_code = 201 return data except IntegrityError as error: return Response(error.args[0], status=400) @campaigns.route('/<id>', methods=['GET']) @jwt_required @is_verified def RetrieveCampaign(id=0): return jsonify(Campaign.query.get_or_404(id).to_dict()) @campaigns.route('/<id>', methods=['PATCH']) @jwt_required @is_administrator def UpdateCampaign(id=0): campaign = Campaign.query.get_or_404(id) try: json = request.json oldName = campaign.name campaign.name = json['name'] or None campaign.is_archived = json['is_archived'] if json['is_default'] is True: old_default = Campaign.query.filter_by(is_default=True).all() for camp in old_default: camp.is_default = False campaign.is_default = True else: campaign.is_default = False db.session.commit() os.rename(f'/usr/src/app/mediafiles/campaigns/{oldName}', f'/usr/src/app/mediafiles/campaigns/{campaign.name}') for world in campaign.worlds: world.image = world.image.replace(oldName, campaign.name) db.session.commit() return jsonify(campaign.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @campaigns.route('/q', methods=['GET']) @jwt_required @is_verified def NameQuery(): name = request.args.get('name') return jsonify(Campaign.query.filter_by(name=name).first_or_404().to_dict()) @campaigns.route('/archived', methods=['GET']) @jwt_required @is_verified def ListArchived(): return jsonify([campaign.to_dict() for campaign in Campaign.query.filter_by(is_archived=True) .order_by(Campaign.id.desc()).all()]) <file_sep>/migrations/versions/341063e49c43_.py """empty message Revision ID: 341063e49c43 Revises: Create Date: 2020-11-16 22:38:12.462726 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('campaigns', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('image', sa.String(), nullable=False), sa.Column('is_default', sa.Boolean(), nullable=True), sa.Column('is_archived', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('image'), sa.UniqueConstraint('name') ) op.create_table('guilds', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('is_active', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(), nullable=False), sa.Column('password', sa.String(), nullable=False), sa.Column('discord', sa.String(), nullable=True), sa.Column('is_active', sa.Boolean(), nullable=False), sa.Column('role', sa.Enum('GUEST', 'VERIFIED', 'ADMIN', name='role'), nullable=False), sa.Column('theme', sa.Enum('DEFAULT', 'BLUE_RASPBERRY', 'SEABREEZE', 'CARTOGRAPHY', 'PUMPKIN_SPICE', 'RED', name='theme'), nullable=False), sa.Column('discord_confirmed', sa.Boolean(), nullable=False), sa.Column('guild_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['guild_id'], ['guilds.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('discord'), sa.UniqueConstraint('username') ) op.create_table('worlds', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('image', sa.String(), nullable=False), sa.Column('center_lat', sa.Float(), nullable=False), sa.Column('center_lng', sa.Float(), nullable=False), sa.Column('radius', sa.Float(), nullable=False), sa.Column('campaign_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['campaign_id'], ['campaigns.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('image') ) op.create_table('pins', sa.Column('id', sa.Integer(), nullable=False), sa.Column('position_x', sa.Float(), nullable=False), sa.Column('position_y', sa.Float(), nullable=False), sa.Column('symbol', sa.Enum('STONE', 'STONE_MOTHERLODE', 'ORE', 'ORE_MOTHERLODE', 'WOOD', 'ANIMAL', 'ANIMAL_BOSS', 'MOB', 'MOB_BOSS', 'WELL', 'GRAVE', 'TACTICAL_HOUSE', 'TACTICAL_FIRE', 'TACTICAL_FISH', name='symbol'), nullable=False), sa.Column('resource', sa.Enum('YEW', 'BIRCH', 'ASH', 'OAK', 'SPRUCE', 'COPPER', 'TIN', 'IRON', 'SILVER', 'AURELIUM', 'GRANITE', 'LIMESTONE', 'TRAVERTINE', 'SLATE', 'MARBLE', 'SPIDER', 'PIG', 'CAT', 'AUROCH', 'ELK', 'WOLF', 'HUMAN', 'ELVEN', 'MONSTER', 'STONEBORN', 'GUINECIAN', 'NA', name='resource'), nullable=False), sa.Column('rank', sa.Integer(), nullable=True), sa.Column('name', sa.String(), nullable=True), sa.Column('amount', sa.Integer(), nullable=True), sa.Column('notes', sa.String(), nullable=True), sa.Column('respawn', sa.Integer(), nullable=True), sa.Column('world_id', sa.Integer(), nullable=False), sa.Column('x_cord', sa.String(length=1), nullable=True), sa.Column('y_cord', sa.Float(), nullable=True), sa.ForeignKeyConstraint(['world_id'], ['worlds.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('edits', sa.Column('id', sa.Integer(), nullable=False), sa.Column('details', sa.String(), nullable=True), sa.Column('date_time', sa.DateTime(), nullable=False), sa.Column('pin_id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['pin_id'], ['pins.id'], ), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('edits') op.drop_table('pins') op.drop_table('worlds') op.drop_table('users') op.drop_table('guilds') op.drop_table('campaigns') # ### end Alembic commands ###<file_sep>/logger.py import logging from flask.logging import default_handler def get_logger(name): log = logging.getLogger(name) log.addHandler(default_handler) log.setLevel(logging.WARNING) return log <file_sep>/views/pins.py from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import get_jwt_identity, jwt_required from sqlalchemy.exc import IntegrityError from models import db, Edit, Pin, User from permissions import is_verified pins = Blueprint('pins', __name__, url_prefix='/api/pins') @pins.route('', methods=['GET']) @jwt_required @is_verified def ListPins(): return jsonify([pin.to_dict() for pin in Pin.query.all()]) @pins.route('', methods=['POST']) @jwt_required @is_verified def CreatePin(): json = request.json try: newPin = Pin( json['position_x'], json['position_y'], Pin.Symbol(json['symbol']), Pin.Resource(json['resource']), json['world_id'] or None, json['rank'], json['name'], json['amount'], json['respawn'], json['notes'], json['x_cord'], json['y_cord'] ) db.session.add(newPin) db.session.commit() newEdit = Edit(json['notes'], newPin.id, get_jwt_identity()['id']) db.session.add(newEdit) db.session.commit() data = jsonify(newPin.to_dict()) data.status_code = 201 return data except IntegrityError as error: return Response(error.args[0], status=400) @pins.route('/<id>', methods=['GET']) @jwt_required @is_verified def RetrievePin(id=0): return jsonify(Pin.query.get_or_404(id).to_dict()) @pins.route('/<id>', methods=['PATCH']) @jwt_required @is_verified def UpdatePin(id=0): pin = Pin.query.get_or_404(id) user = get_jwt_identity() if (User.Role(user['role']) not in [User.Role.ADMIN, User.Role.VERIFIED]) and (user['id'] != pin.edits[0].user_id): return Response('only the creator or an admin can edit a pin', status=403) try: json = request.json details = '' PROPERTY_LIST = ['position_x', 'position_y', 'symbol', 'resource', 'rank', 'name', 'amount', 'respawn', 'notes', 'x_cord', 'y_cord'] for prop in PROPERTY_LIST: old_value = getattr(pin, prop) enum = False if hasattr(old_value, 'value'): old_value = old_value.value enum = True if old_value != json[prop]: details += f'{prop} changed from {old_value} to {json[prop]}\n' if enum is True: if json[prop] in [item.value for item in Pin.Symbol]: setattr(pin, prop, Pin.Symbol(json[prop])) elif json[prop] in [item.value for item in Pin.Resource]: setattr(pin, prop, Pin.Resource(json[prop])) else: setattr(pin, prop, json[prop]) db.session.commit() newEdit = Edit(details, pin.id, get_jwt_identity()['id']) db.session.add(newEdit) db.session.commit() return jsonify(pin.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @pins.route('/<id>', methods=['DELETE']) @jwt_required @is_verified def DeletePin(id=0): pin = Pin.query.get_or_404(id) creator_id = pin.edits[0].user_id user = get_jwt_identity() if User.Role(user['role']) == User.Role.ADMIN or user['id'] == creator_id: db.session.delete(pin) db.session.commit() return Response('pin deleted', status=200) return Response('only the creator or an admin can delete a pin', status=403) <file_sep>/tests/test_permissions.py import json from .setup import BasicTests, Method from models import User class PermissionsTests(BasicTests): def test_jwt_required(self): response = self.request('/api/users') self.assertEqual(response.status_code, 401) self.assertIn(b'Missing Authorization Header', response.data) def test_bogus_jwt(self): token = 'Bearer <PASSWORD>' response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 422) def test_verified_required_rejects_guest(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': False}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'requires verified account', response.data) def test_verified_required_accepts_verified(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.VERIFIED.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "1qaz!QAZ").get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 200) def test_verified_required_accepts_admin(self): response = self.request('/api/users', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) def test_admin_required_rejects_guest(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users/1', Method.PUT, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'requires Guild leader account', response.data) def test_admin_required_rejects_verified(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.VERIFIED.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "<PASSWORD>").get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users/1', Method.PUT, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'requires Guild leader account', response.data) def test_admin_required_accepts_admin(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.VERIFIED.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) response = self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) def test_locked_account(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.ADMIN.value, 'is_active': False, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "1qaz!QAZ").get_json()["token"]}' response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'account is locked', response.data) response = self.request('/api/users/1', Method.PUT, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'account is locked', response.data) def test_locked_guild(self): self.create_guild(self.DEFAULT_TOKEN, 'new') self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.ADMIN.value, 'is_active': True, 'guild_id': 2}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) data = json.dumps({'name': 'new', 'is_active': False}) self.request('/api/guilds/2', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "1qaz!QAZ").get_json()["token"]}' response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'guild is locked', response.data) response = self.request('/api/users/1', Method.PUT, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'guild is locked', response.data) def test_unconfirmed_account(self): self.register('new', '1<PASSWORD>', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.ADMIN.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "<PASSWORD>").get_json()["token"]}' response = self.request('/api/users', headers={'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'has not confirmed account on discord', response.data) response = self.request('/api/users/1', Method.PUT, {'Authorization': token}) self.assertEqual(response.status_code, 403) self.assertIn(b'has not confirmed account on discord', response.data) def test_is_discord_bot_allows_bot(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'discord': 'fakedata', 'token': response.get_json()['token'], 'username': 'new', 'member': True}) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) def test_is_discord_bot_disallows_others(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'role': User.Role.ADMIN.value, 'is_active': True, 'guild_id': self.DEFAULT_GUILD.id}) self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.login("new", "<PASSWORD>").get_json()["token"]}' response = self.request('/api/users/confirm', Method.PUT, {'Authorization': token}, data) self.assertEqual(response.status_code, 403) self.assertIn(b'only discord bot is allowed access', response.data) <file_sep>/views/worlds.py import os from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import jwt_required from sqlalchemy.exc import IntegrityError from werkzeug.utils import secure_filename from models import db, Campaign, World from permissions import is_administrator, is_verified from upload import allowed_file worlds = Blueprint('worlds', __name__, url_prefix='/api/worlds') @worlds.route('', methods=['GET']) @jwt_required @is_verified def ListWorlds(): return jsonify([world.to_dict() for world in World.query.all()]) @worlds.route('', methods=['POST']) @jwt_required @is_verified def CreateWorld(): if 'file' not in request.files: return Response('no file found', status=400) file = request.files['file'] if not allowed_file(file.filename): return Response('invalid file type', status=400) try: campaignName = Campaign.query.get(request.form['campaign_id']).name.replace(' ', '_') newWorld = World( request.form['name'] or None, f'/mediafiles/campaigns/{campaignName}/{secure_filename(file.filename)}', request.form['center_lat'], request.form['center_lng'], request.form['radius'], request.form['campaign_id'] or None ) db.session.add(newWorld) db.session.commit() os.makedirs(f'/usr/src/app/mediafiles/campaigns/{campaignName}/{newWorld.name.replace(" ", "_")}', exist_ok=True) file.save(f'/usr/src/app{newWorld.image}') data = jsonify(newWorld.to_dict()) data.status_code = 201 return data except (IntegrityError, AttributeError) as error: return Response(error.args[0], status=400) @worlds.route('/<id>', methods=['GET']) @jwt_required @is_verified def RetrieveWorld(id=0): return jsonify(World.query.get_or_404(id).to_dict()) @worlds.route('/<id>', methods=['PATCH']) @jwt_required @is_administrator def UpdateWorld(id=0): world = World.query.get_or_404(id) try: json = request.json oldName = world.name world.name = json['name'] or None world.center_lat = json['center_lat'] world.center_lng = json['center_lng'] world.radius = json['radius'] db.session.commit() campaignName = Campaign.query.get(world.campaign_id).name.replace(' ', '_') os.rename(f'/usr/src/app/mediafiles/campaigns/{campaignName}/{oldName}', f'/usr/src/app/mediafiles/campaigns/{campaignName}/{world.name}') return jsonify(world.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @worlds.route('/q', methods=['GET']) @jwt_required @is_verified def NameQuery(): campaign_name = request.args.get('campaign') world_name = request.args.get('world') return jsonify(World.query.join(Campaign) .filter(Campaign.name == campaign_name, World.name == world_name) .first_or_404().to_dict()) <file_sep>/unit_test.py import unittest import tests.test_auth import tests.test_campaigns import tests.test_discord import tests.test_guild import tests.test_permissions import tests.test_pins import tests.test_socket import tests.test_users import tests.test_worlds import tests.test_calendar def main(): suite = unittest.TestLoader().loadTestsFromModule(tests.test_auth) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_campaigns)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_discord)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_guild)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_permissions)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_pins)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_socket)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_users)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_worlds)) suite.addTests(unittest.TestLoader().loadTestsFromModule(tests.test_calendar)) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == "__main__": main() <file_sep>/discord_token.py from flask import current_app from itsdangerous import URLSafeTimedSerializer from itsdangerous.exc import BadTimeSignature, BadSignature def generate_confirmation_token(username): serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) return serializer.dumps(username, salt=current_app.config['SECURITY_PASSWORD_SALT']) def confirm_token(token, expiration=3600): serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY']) try: username = serializer.loads( token, salt=current_app.config['SECURITY_PASSWORD_SALT'], max_age=expiration ) except (BadTimeSignature, BadSignature): return False return username <file_sep>/tests/test_users.py import json from .setup import BasicTests, Method from models import User class UserTests(BasicTests): def test_list(self): response = self.request('/api/users', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) data = response.get_json() self.assertEqual(len(data), 1) self.assertIn(self.DEFAULT_USER.to_dict(), data) def test_retrieve(self): response = self.request('/api/users/1', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_USER.to_dict(), response.get_json()) def test_patch_update_self(self): data = json.dumps({'theme': User.Theme.SEABREEZE.value}) response = self.request('/api/users/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) self.assertIn(b'"theme":"seabreeze"', response.data) def test_patch_update_password(self): data = json.dumps({'theme': User.Theme.DEFAULT.value, 'password': '<PASSWORD>'}) response = self.request('/api/users/1', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) self.assertEqual(self.DEFAULT_USER.to_dict(), response.get_json()) response = self.login('DiscordBot', '<PASSWORD>') self.assertEqual(response.status_code, 200) def test_patch_update_other(self): response = self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) response = self.request('/api/users/2', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 403) self.assertIn(b'can only update your own account', response.data) def test_put_update_self(self): response = self.request('/api/users/1', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 403) self.assertIn(b'cannot update your own account', response.data) def test_put_update_other(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'is_active': True, 'role': User.Role.VERIFIED.value, 'guild_id': self.DEFAULT_GUILD.id}) response = self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) self.assertIn(b'"is_active":true', response.data) self.assertIn(b'"role":"verified"', response.data) def test_put_update_password(self): self.register('new', '1qaz!QAZ', self.DEFAULT_GUILD.id, True) data = json.dumps({'is_active': True, 'role': User.Role.GUEST.value, 'password': <PASSWORD>', 'guild_id': self.DEFAULT_GUILD.id}) response = self.request('/api/users/2', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) response = self.login('new', '!QAZ1qaz') self.assertEqual(response.status_code, 200) def test_confirm_discord_success(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) self.assertIn(b'"discord_confirmed":true', response.data) def test_confirm_discord_fail_already_confirmed(self): token = f'Bearer {self.register("new", "1<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 400) self.assertIn(b'user has already confirmed their discord', response.data) def test_confirm_discord_fail_invalid_token(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': 'badvalue', 'username': 'new', 'discord': 'dummyvalue'}) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 400) self.assertIn(b'invalid user/token', response.data) def test_confirm_discord_fail_username_not_found(self): token = f'Bearer {self.register("new", "1<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'badusername', 'discord': 'dummyvalue'}) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 404) def test_confirm_discord_fail_unique_id(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) token = f'Bearer {self.register("new2", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new2', 'discord': 'dummyvalue', 'member': False}) response = self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 400) self.assertIn(b'Key (discord)=(dummyvalue) already exists.', response.data) def test_discord_set_member_status_verified(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data=data) response = self.request('/api/users/2', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.get_json()['role'], 'verified') def test_discord_set_member_status_guest(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': False}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data=data) response = self.request('/api/users/2', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.get_json()['role'], 'guest') def test_discord_revoke_member(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data=data) data = json.dumps({'token': response.get_json()['token'], 'discord': 'dummyvalue', 'is_active': False, 'role': 'guest'}) self.request('/api/users/discordRoles/dummyvalue', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data=data) response = self.request('/api/users/discord/dummyvalue', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.get_json()['role'], 'guest') self.assertEqual(response.get_json()['is_active'], False) def test_discord_grant_member(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'dummyvalue', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) data = json.dumps({'token': response.get_json()['token'], 'discord': 'dummyvalue', 'is_active': True, 'role': 'admin'}) self.request('/api/users/discordRoles/dummyvalue', Method.PATCH, headers={'Authorization': self.DEFAULT_TOKEN}, data=data) response = self.request('/api/users/discord/dummyvalue', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.get_json()['role'], 'admin') self.assertEqual(response.get_json()['is_active'], True) def test_send_discord_token_success(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) self.assertEqual(response.status_code, 200) self.assertIn('token', response.get_json().keys()) def test_send_discord_token_fail(self): response = self.request('/api/users/discord-token', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 400) self.assertIn(b'user has already confirmed their discord', response.data) def test_discord_whoami(self): token = f'Bearer {self.register("new", "<PASSWORD>", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'test', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) response = self.request('/api/users/discord/test', headers={'Authorization': self.DEFAULT_TOKEN}) self.assertEqual(response.status_code, 200) self.assertDictContainsSubset({'username': 'new', 'discord_confirmed': True}, response.get_json()) def test_discord_password_reset_success(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'test', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) data = json.dumps({'password': '!<PASSWORD>'}) response = self.request('/api/users/password-reset/test', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 200) response = self.login('new', '!QAZ1qaz') self.assertEqual(response.status_code, 200) def test_discord_password_reset_fail(self): token = f'Bearer {self.register("new", "1qaz!QAZ", self.DEFAULT_GUILD.id, True).get_json()["token"]}' response = self.request('/api/users/discord-token', headers={'Authorization': token}) data = json.dumps({'token': response.get_json()['token'], 'username': 'new', 'discord': 'test', 'member': True}) self.request('/api/users/confirm', Method.PUT, {'Authorization': self.DEFAULT_TOKEN}, data) data = json.dumps({'password': '<PASSWORD>'}) response = self.request('/api/users/password-reset/test', Method.PATCH, {'Authorization': self.DEFAULT_TOKEN}, data) self.assertEqual(response.status_code, 400) response = self.login('new', 'badpass') self.assertEqual(response.status_code, 400) <file_sep>/config.py import os main_config = {} main_config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False main_config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'] main_config['SECRET_KEY'] = os.environ['SECRET_KEY'] main_config['JWT_ACCESS_TOKEN_EXPIRES'] = 300 # 5 minutes main_config['JWT_REFRESH_TOKEN_EXPIRES'] = 86400 # 1 day main_config['SECURITY_PASSWORD_SALT'] = os.environ['SECURITY_PASSWORD_SALT'] test_config = {} test_config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False test_config['SECRET_KEY'] = "SUPER-SECRET" test_config['JWT_ACCESS_TOKEN_EXPIRES'] = 300 # 5 minutes test_config['JWT_REFRESH_TOKEN_EXPIRES'] = 86400 # 1 day test_config['SECURITY_PASSWORD_SALT'] = '<PASSWORD>' test_config['TESTING'] = True test_config['WTF_CSRF_ENABLED'] = False test_config['DEBUG'] = False test_config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://flamesofexile:flamesofexile@test-db:5432/flamesofexile' <file_sep>/views/guilds.py from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import jwt_required from sqlalchemy.exc import IntegrityError import requests import os from models import db, Guild, User from permissions import is_administrator, is_discord_bot from logger import get_logger log = get_logger(__name__) BOT_URL = os.getenv('BOT_URL') + '/bot' VERIFY_SSL = bool(int(os.getenv('VERIFY_SSL'))) guilds = Blueprint('guilds', __name__, url_prefix='/api/guilds') @guilds.route('', methods=['GET']) def ListGuilds(): guild_list = [Guild.query.filter_by(name='Flames of Exile').first().to_dict()] guild_list += [guild.to_dict() for guild in Guild.query.filter(Guild.name != 'Flames of Exile') .order_by(Guild.is_active.desc(), Guild.name).all()] return jsonify(guild_list) @guilds.route('', methods=['POST']) @jwt_required @is_administrator def CreateGuild(): json = request.json try: if 'nickname' in json: newGuild = Guild(json['name'], json['nickname']) else: newGuild = Guild(json['name']) db.session.add(newGuild) db.session.commit() data = jsonify(newGuild.to_dict()) data.status_code = 201 return data except IntegrityError as error: return Response(error.args[0], status=400) @guilds.route('/<id>', methods=['GET']) def RetrieveGuild(id=0): return jsonify(Guild.query.get_or_404(id).to_dict()) @guilds.route('/<id>', methods=['PATCH']) @jwt_required @is_administrator def UpdateGuild(id=0): guild = Guild.query.get_or_404(id) if guild.name == 'Flames of Exile': return Response('no editing the main guild', status=400) json = request.json try: guild.name = json['name'] or None if 'nickname' in json: guild.nickname = json['nickname'] guild.is_active = json['is_active'] db.session.add(guild) db.session.commit() users = [user.discord for user in User.query.filter_by(guild_id=guild.id).all()] data = {'users': users, 'guildTag': guild.nickname} log.warning(data) requests.post(BOT_URL + '/guild', json=data, verify=VERIFY_SSL) return jsonify(guild.to_dict()) except IntegrityError as error: return Response(error.args[0], status=400) @guilds.route('/q', methods=['GET']) def NameQuery(): name = request.args.get('name') return jsonify(Guild.query.filter_by(name=name).first_or_404().to_dict()) @guilds.route('/burn', methods=['PATCH']) @jwt_required @is_discord_bot def burn_guild(): guild = Guild.query.filter_by(name=request.json['guild']).first_or_404() guild.is_active = False db.session.commit() users = [int(user.discord) for user in guild.users] return jsonify(users) @guilds.route('/unburn', methods=['PATCH']) @jwt_required @is_discord_bot def unburn_guild(): guild = Guild.query.filter_by(name=request.json['guild']).first_or_404() guild.is_active = True db.session.commit() users = [int(user.discord) for user in guild.users] return jsonify(users) <file_sep>/views/calendar.py from flask import Blueprint, jsonify, request, Response from flask_jwt_extended import jwt_required import logging import os import sys import datetime import pytz from datetime import timedelta from models import db, Event from permissions import is_administrator, is_verified, is_discord_bot log = logging.getLogger(__name__) log.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) log.addHandler(handler) BOT_URL = os.getenv('BOT_URL') + '/bot' VERIFY_SSL = os.getenv('VERIFY_SSL') timezone = pytz.utc calendar = Blueprint('calendar', __name__, url_prefix='/api/calendar') @calendar.route('', methods=['GET']) @jwt_required @is_verified def get_all_events(): events = Event.query.order_by(Event.active.desc()).order_by(Event.date).all() for event in events: event.date = timezone.localize(event.date) log.info(f'{event.name}:{event.date}') return jsonify([event.to_dict() for event in events]) @calendar.route('', methods=['POST']) @jwt_required @is_administrator def create_new_event(): if 'name' not in request.json: return Response('name not found', status=400) if 'game' not in request.json: return Response('game not found', status=400) if 'date' not in request.json: return Response('when not found', status=400) if 'note' not in request.json: return Response('note not found', status=400) event = request.json log.info(event['date']) log.info(type(event['date'])) new_event = Event(event['name'], event['game'], event['date'], event['note']) db.session.add(new_event) db.session.commit() data = jsonify(new_event.to_dict()) data.status_code = 201 return data @calendar.route('/<id>', methods=['PATCH']) @jwt_required @is_administrator def alter_event(id): event = Event.query.filter_by(id=id).first_or_404() json = request.json if 'name' in json: event.name = json['name'] if 'game' in json: event.game = json['game'] if 'date' in json: event.date = json['date'] log.info(event.date) if 'note' in json: event.note = json['note'] log.info(json['date']) db.session.commit() data = jsonify(event.to_dict()) data.status_code = 201 return data @calendar.route('/<id>', methods=['DELETE']) @jwt_required @is_administrator def remove_event(id): event = Event.query.filter_by(id=id).first_or_404() db.session.delete(event) db.session.commit() data = jsonify(event.to_dict()) data.status_code = 204 return data @calendar.route('/getevents', methods=['GET']) @jwt_required @is_discord_bot def notify_events(): day = datetime.datetime.now() log.info(day) events = Event.query.filter_by(active=True).all() todays_events = [] for event in events: if event.date.date() < day.date(): event.active = False elif event.date < day + timedelta(hours=24): # event.date = pytz.utc(event.date) todays_events.append(event.to_dict()) db.session.commit() data = jsonify(todays_events) data.status_code = 200 return data @calendar.route('/allevents', methods=['GET']) @jwt_required @is_verified def get_events(): day = datetime.datetime.now() log.info(day) events = Event.query.filter_by(active=True).all() upcoming_events = [] for event in events: if event.date.date() < day.date(): event.active = False else: # event.date = pytz.utc(event.date) upcoming_events.append(event.to_dict()) db.session.commit() data = jsonify(upcoming_events) data.status_code = 200 return data <file_sep>/migrations/versions/4774e041c352_.py """empty message Revision ID: 4774e041c352 Revises: <PASSWORD> Create Date: 2021-08-29 01:05:49.574113 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '4774e041c352' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('event', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('game', sa.String(), nullable=False), sa.Column('date', sa.DateTime(), nullable=False), sa.Column('note', sa.String(), nullable=True), sa.Column('active', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.add_column('guilds', sa.Column('nickname', sa.String(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('guilds', 'nickname') op.drop_table('event') # ### end Alembic commands ###
e0ff7281af1122f7535e316dc3dc762bd04dbede
[ "Markdown", "Python", "Text" ]
31
Python
Flames-Of-Exile/FOE_Backend
f4e6bec2dde843cdc1842d0c5336096079cc8a31
32e236442c044b19c6f56c98ff0dde38c59c1882
refs/heads/master
<repo_name>chr15m/cf-c64-emu-with-fx<file_sep>/instructions.md ## USB keyboard * bottom row keys = play note * > = octave up * < = octave down * t = square wave * y = sawtooth wave ## KORG nanoKontrol2 ### Channel layout * Audio in left * Audio in right * C64 synth emulator * ? * ? * FX (volume) * FX (select) * C64 synth loop ### Indicators * Stop button light = beat * Play button light = sync ### Buttons * Marker buttons = retrigger selected channels * Play button tap = tap sync ### Channels 1-3 * Slider = volume * S = route to FX * M = select for retrigger * R = ? ### Channel 3 (C64) * Knob 3 = Reverb * Knob 4 = Synth tuning / pitch bend ### Channels 6 & 7 (FX) * Knob 6 = fx parameter 1 * Knob 7 = fx parameter 2 * R 7 = FX active ### Channel 8 (C64 loop) * Slider = volume * S = route to FX * R = Loop C64 bars on * Knob 8 = C64 filter cutoff <file_sep>/sync #!/bin/sh if [ "$1" = "" ] then echo "`basename $0` IP-OR-HOST" echo "e.g. spaceghost.local" else rsync -avz --exclude='.git/' ./ pi@$1:~/c64-emu-with-fx fi <file_sep>/trigger-high-sync.py #!/usr/bin/env python from sys import argv import socket from time import time, sleep import RPi.GPIO as GPIO sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) debug = "--debug" in argv GPIO.setmode(GPIO.BCM) GPIO.setup(15, GPIO.IN, GPIO.PUD_DOWN) def makecallback(hello): def got(*args, **kwargs): #print "got", args, kwargs now = time() last = hello["last"] if now - last > 0.01: if debug: print "bang", now - last sock.sendto("bang;\n", ("127.0.0.1", 42242)) #else: # print "skipped" hello["last"] = now return got GPIO.add_event_detect(15, GPIO.RISING) GPIO.add_event_callback(15, makecallback({"last": time()})) while 1: sleep(0.1) <file_sep>/README.md Raspberry Pi low-fi live performance tool. ![Setup](./setup.jpg) See the [instructions](./instructions.md) for korg nano 2 interface. Launch is from crontab (see crontab.txt). <file_sep>/picore-install.sh #!/bin/sh # install packages we need tce-load -wi alsa alsa-oss-dev alsa-utils python python-RPi.GPIO puredata bash # install boot script grep -v cf-c64-emu-with-fx /opt/bootlocal.sh > /tmp/bootlocal.sh echo '/sbin/modprobe snd_seq; cd /home/tc/cf-c64-emu-with-fx; ./launch &' >> /tmp/bootlocal.sh sudo sh -c 'cat /tmp/bootlocal.sh > /opt/bootlocal.sh' # persist changes to disk filetool.sh -b <file_sep>/launch #!/bin/bash pd=`command -v pd || command -v /usr/bin/pd || command -v /usr/local/bin/pd` # mixer bash ./mixer-settings # midi connect ( /bin/sleep 10; ./korg-led-extrnal-mode.sh /usr/bin/aconnect nanoKONTROL2:0 "Pure Data":0 /usr/bin/aconnect "Pure Data":2 nanoKONTROL2:0 /usr/bin/aconnect Nooder-1:0 "Pure Data":1 # /usr/bin/aconnect 24:0 128:0; # /usr/bin/aconnect 28:0 128:0; # /usr/bin/aconnect 128:2 24:0; # /usr/bin/aconnect 128:2 28:0; # /usr/bin/aconnect 16:0 128:1; ) & # gba serial watcher #./gba-sync-serial.py & ./trigger-high-sync.py & gbapid=$! if [ "$1" != "--gui" ] then guiflag="-nogui" else guiflag="" shift fi if [ "$1" == "--record" ] then recordflag="-open _record.pd" else recordflag="" fi $pd $guiflag -alsamidi -mididev 0,1 "$recordflag" -open _main.pd & pdpid=$! # trap exit and kill daemons trap "kill $pdpid; kill $gbapid; trap - SIGTERM; exit" SIGTERM SIGINT EXIT wait "$pdpid" <file_sep>/mixer-settings #!/bin/sh for c in `seq 2` do echo "Audio settings - trying card $c"; mix="amixer -c$c -q set" $mix "PCM Capture Source" "Line" $mix "Mic" 95% unmute done <file_sep>/gba-sync-serial.py #!/usr/bin/env python import serial import socket from sys import argv # ser = serial.Serial('/dev/serial0', baudrate=38400) ser = serial.Serial('/dev/serial0', baudrate=31250) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print "Connected:", ser message = [0, 0, 0] while True: i = 0 while i < 3: data = ord(ser.read(1)) # read a byte if data >> 7 != 0: i = 0 # status byte! this is the beginning of a midi message! message[i] = data i += 1 if i == 2 and message[0] >> 4 == 12: # program change: don't wait for a message[2] = 0 # third byte: it has only 2 bytes i = 3 messagetype = message[0] >> 4 messagechannel = (message[0] & 15) + 1 note = message[1] if len(message) > 1 else None velocity = message[2] if len(message) > 2 else None #if messagetype == 9: # Note on # print 'Note on' #elif messagetype == 8: # Note off # print 'Note off' #elif messagetype == 12: # Program change # print 'Program change' #else: # print "message", messagetype, messagechannel, note, velocity if "--debug" in argv: print "message", messagetype, messagechannel, note, velocity sock.sendto(" ".join([hex(x) for x in message]) + ";\n", ("127.0.0.1", 42242))
d2d067073a203c618e4a6a995c201454f7179938
[ "Markdown", "Python", "Shell" ]
8
Markdown
chr15m/cf-c64-emu-with-fx
dd917523a1cfe79f34be00e4b6925f325ed3f523
a08c1c92109b28ad11c020d434ad6920c2667d42
refs/heads/master
<repo_name>3otes/frontend-nanodegree-arcade-game<file_sep>/js/app.js // Enemies our player must avoid let Enemy = function (x, y) { let enemies = ['images/char-boy.png', 'images/enemy-bug.png']; this.sprite = enemies[Math.floor((Math.random() * 2))]; this.x = x; this.y = y; this.speed = Math.floor((Math.random() * 3) + 1); }; Enemy.prototype.update = function (dt) { this.x += 1 + this.speed; if (this.x > 500) { this.x = -100; } }; // Draw the enemy on the screen, required method for game Enemy.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; //Player let Player = function() { this.players = ['images/char-pink-girl.png', 'images/char-cat-girl.png', 'images/char-horn-girl.png', 'images/char-princess-girl.png' ] this.sprite = this.players[0]; this.x = 200; this.y = 405; this.level = 0; this.won = false; }; Player.prototype.update = function (dt) { // Collision detection for (let enemy of allEnemies) { let deltax = this.x - enemy.x - 15; let deltay = this.y - enemy.y - 20; let distance = Math.sqrt(deltax * deltax + deltay * deltay); if (distance < 56) { this.x = 200; this.y = 405; if (this.level > 0){ this.level -= 1; this.sprite = this.players[this.level]; } } } // Did player win if (this.y < 10) { if (this.level === 3){ this.won = true; //go to the next level } else { this.level += 1; this.sprite = this.players[this.level]; this.x = 200; this.y = 405; allEnemies = [ new Enemy(-200, 65), new Enemy(-150, 145), new Enemy(-100, 230) ]; } } else if (this.y > 405) { this.y = 405; } else if (this.x < 0) { this.x = 0; } else if (this.x > 400) { this.x = 400; } }; Player.prototype.render = function() { ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; Player.prototype.handleInput = function (dt) { switch (dt) { case "up": this.y -= 83; break; case "down": this.y += 83; break; case "left": this.x -= 100; break; case "right": this.x += 100; break; } }; // Place all enemy objects in an array called allEnemies // Place the player object in a letiable called player let allEnemies = [ new Enemy(-200, 65), new Enemy(-150, 145), new Enemy(-100, 230) ]; let player = new Player(); // This listens for key presses and sends the keys to your // Player.handleInput() method. You don't need to modify this. document.addEventListener('keyup', function(e) { let allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); }); <file_sep>/README.md # frontend-nanodegree-arcade-game ## Table of Contents * [Introduction](#introduction) * [Rubric](#rubric) * [Contributing](#contributing) * [Code-explained](#code-explained) * [HTML](#html) * [CSS](#css) * [Java-Script](#java-script) * [Play-game](#play-game) ## Introduction Provided with visual assets and a game loop engine this project involved using these tools to add a number of entities to the game including the player characters, and enemies to recreate a simplified version of the classic arcade game Frogger. ## Rubric Using this [rubric](https://review.udacity.com/#!/projects/2696458597/rubric) I wrote some **object-oriented** - functions to work with the existing code provided. more on the help available: For detailed instructions on how to get started, check out this [guide](https://docs.google.com/document/d/1v01aScPjSWCCWQLIpFqvg3-vXLH2e8_SZQKC8jNO0Dc/pub?embedded=true). [Table of Contents](#table-of-contents) ## Contributing **PLEASE DO NOT CONTRIBUTE TO THIS PROJECT AS IT IS A COMPLETED TEST** [Table of Contents](#table-of-contents) ## Code-explained So to understand the code let's start with the files that make up this game. * HTML * CSS * JavaScript [Table of Contents](#table-of-contents) ## HTML For this project the HTML was limited, as the game itself uses JavaScript. I made some additions to the HTML purely for my own project to match the styling of my other projects. [Table of Contents](#table-of-contents) ## CSS The CSS file provided basically centered the page content. It was not a requirement for this project to change the CSS but to match the styling of my other projects I added some of their styles. This presented somewhat of a challenge as the styling for the game itself was not in the CSS but was appended to the document body using JavaScript. To simply get around this I just changed "min-height: 605px;" and "margin: 363px 0 0 0px;" for the .deck style and set "position: absolute;" with a "z-index: -1;" so that the canvas created in JavaScript is on top of the background. ``` .deck { width: 660px; min-height: 605px; margin: 363px 0 0 0px; background-color: rgba(28, 38, 47, 0.7); position: absolute; z-index: -1; } ``` [Table of Contents](#table-of-contents) ## Java-Script The project came with most of the work done in that it already had 3 JavaScript files. app.js, engine.js, and resources.js. Everything was already laid out, and with the help of the many many tutorials it was just a matter of filling in the blanks already provided in the app.js file. Ok it was not that easy, but compared to what I thought it was going to be Udacity really simplified it. To explain what is happening in app.js, I found [this](https://discussions.udacity.com/t/i-dont-understand-how-to-code-classic-arcade-game/527836/2?u=solittletime) very helpful in getting started, and [this](https://matthewcranford.com/arcade-game-walkthrough-part-6-collisions-win-conditions-and-game-resets/) very helpful to make the game pause at the end. [Table of Contents](#table-of-contents) ## Play-game [HERE](http://www.encoreservices.co.za/udacity/ClassicArcadeGame/index.html) is a link to the game hosted by Encore Services, have fun and please let me know if you encounter any bugs. This game is not built to be responsive across different devices. [Table of Contents](#table-of-contents)
5bf39e44cbd0f540c4139faab96e1550a7a5fb2f
[ "JavaScript", "Markdown" ]
2
JavaScript
3otes/frontend-nanodegree-arcade-game
bbc4da8813be646413d25a49b1f4cf79ea9af161
132fc46632de9b0d1676538880303d874a393781
refs/heads/master
<file_sep># libhmap Libhmap is a string -> object hashmap with intermediate unique ID. ## Usage ``` struct object { hmap_header_t header; /* sizeof(hmap_header_t) == 8 */ /* user-defined member follows header */ int member1; int member2; /* ... */ }; /* create hashmap with initial size 128 */ hmap_t *h = hmap_init( sizeof(struct object), HMAP_PARAMS(.hmap_size = 128)); /* reserve area for key0 */ uint32_t id = hmap_get_id(h, "key0", strlen("key0")); /* get pointer to the reserved area for the object */ struct object *obj = hmap_get_object(h, id); /* reverse mapping from id to key */ struct hmap_key_s key = hmap_get_key(h, id); /* cleanup */ hmap_clean(h); ``` ## License MIT <file_sep>#! /usr/bin/env python # encoding: utf-8 def options(opt): opt.load('compiler_c') def configure(conf): conf.load('ar') conf.load('compiler_c') conf.env.append_value('CFLAGS', '-O3') conf.env.append_value('CFLAGS', '-std=c99') conf.env.append_value('CFLAGS', '-march=native') conf.env.append_value('OBJ_HMAP', ['hmap.o']) def build(bld): bld.objects(source = 'hmap.c', target = 'hmap.o') bld.stlib( source = ['unittest.c'], target = 'hmap', use = bld.env.OBJ_HMAP) bld.program( source = ['unittest.c'], target = 'unittest', use = bld.env.OBJ_HMAP, defines = ['TEST'])
164848668330b22dcd3326ac17a5ba8568d83a41
[ "Markdown", "Python" ]
2
Markdown
ocxtal/libhmap
7dbf4bc6f80990b4bc646ce0d1d39c94a2436755
06fc253dec8b601cae756108b74f0f49e8947146
refs/heads/master
<repo_name>pacoyx/web-api-aspnet-core-3-base<file_sep>/Contracts/IEntidadRepository.cs using Entities.Models; using System; using System.Collections.Generic; using System.Text; namespace Contracts { public interface IEntidadRepository : IRepositoryBase<Entidad> { IEnumerable<Entidad> GetAllEntidades(); Entidad GetEntidadById(Guid entidadId); Entidad GetEntidadWithDetails(Guid entidadId); void CreateEntidad(Entidad owner); void UpdateEntidad(Entidad owner); void DeleteEntidad(Entidad owner); } } <file_sep>/apiBaseCore.Tests/UnitTest1.cs using apiBaseCore.Controllers; using System; using Xunit; namespace apiBaseCore.Tests { public class UnitTest1 { [Fact] public void Test1() { HomeController home = new HomeController(); string result = home.GetEmployeeName(1); Assert.Equal("Jignesh", result); } } } <file_sep>/Notifications/SlackClient.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace Notifications { public class SlackClient : IDisposable { private readonly Uri _uri; private readonly Encoding _encoding = new UTF8Encoding(); string urlWithAccessToken = "https://slack.com"; //string token = "<KEY>"; string token = ""; public SlackClient() { _uri = new Uri(urlWithAccessToken); } public void Dispose() { } //Post a message using simple strings public string PostMessage(string text, string username = null, string channel = null) { Payload payload = new Payload() { Channel = channel, Username = username, Text = text }; return PostMessage(payload); } public string PostMessage(Payload payload) { string payloadJson = JsonConvert.SerializeObject(payload); using (var client = new HttpClient()) { client.BaseAddress = _uri; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); var pairs = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("channel", payload.Channel), new KeyValuePair<string, string>("text", payload.Text) }; var content = new FormUrlEncodedContent(pairs); var response = client.PostAsync("/api/chat.postMessage", content).Result; if (response.IsSuccessStatusCode) { return "Mensaje enviado"; } else { return response.IsSuccessStatusCode.ToString(); } } } } public class Payload { [JsonProperty("channel")] public string Channel { get; set; } [JsonProperty("username")] public string Username { get; set; } [JsonProperty("text")] public string Text { get; set; } } } <file_sep>/apiBaseCore/Dockerfile FROM mcr.microsoft.com/dotnet/core/aspnet:3.0-buster-slim AS base WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/core/sdk:3.0-buster AS build WORKDIR /src COPY ["apiBaseCore/apiBaseCore.csproj", "apiBaseCore/"] RUN dotnet restore "apiBaseCore/apiBaseCore.csproj" COPY . . WORKDIR "/src/apiBaseCore" RUN dotnet build "apiBaseCore.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "apiBaseCore.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "apiBaseCore.dll"]<file_sep>/Entities/DataTransferObjects/EntidadDto.cs using System; using System.Collections.Generic; using System.Text; namespace Entities.DataTransferObjects { public class EntidadDto { public Guid Id { get; set; } public string EntidadId { get; set; } public string Descripcion { get; set; } public int Estado { get; set; } public int Prioridad { get; set; } } } <file_sep>/Entities/Models/Entidad.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Entities.Models { public class Entidad { public Guid Id { get; set; } [Required(ErrorMessage = "Codigo es requerido")] public string EntidadId { get; set; } public string Descripcion { get; set; } public int Estado { get; set; } public int Prioridad { get; set; } } } <file_sep>/apiBaseCore/Controllers/EntidadController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using AutoMapper; using Contracts; using Entities.DataTransferObjects; using Entities.Models; using Microsoft.AspNetCore.Authorization; namespace apiBaseCore.Controllers { [Route("api/entidad")] [ApiController] public class EntidadController : ControllerBase { private ILoggerManager _logger; private IRepositoryWrapper _repository; private IMapper _mapper; public EntidadController(ILoggerManager logger, IRepositoryWrapper repository, IMapper mapper) { _logger = logger; _repository = repository; _mapper = mapper; } [HttpGet, Authorize(Roles = "Manager")] public IActionResult GetAllEntidades() { try { var entidads = _repository.Entidad.GetAllEntidades(); _logger.LogInfo($"Retorno todas las entidades de la BD."); var entidadsResult = _mapper.Map<IEnumerable<EntidadDto>>(entidads); return Ok(entidadsResult); } catch (Exception ex) { _logger.LogError($"Something went wrong inside GetAllEntidades action: {ex.Message}"); return StatusCode(500, "Internal server error"); } } } }<file_sep>/Repository/EntidadRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using Contracts; using Entities.Models; using Microsoft.EntityFrameworkCore; namespace Repository { public class EntidadRepository : RepositoryBase<Entidad>, IEntidadRepository { public EntidadRepository(RepositoryContext repositoryContext) : base(repositoryContext) { } public void CreateEntidad(Entidad entidad) { Create(entidad); } public void DeleteEntidad(Entidad entidad) { Delete(entidad); } public IEnumerable<Entidad> GetAllEntidades() { return FindAll() .OrderBy(ow => ow.Descripcion) .ToList(); } public Entidad GetEntidadById(Guid entidadId) { return FindByCondition(owner => owner.Id.Equals(entidadId)) .FirstOrDefault(); } public Entidad GetEntidadWithDetails(Guid entidadId) { throw new NotImplementedException(); } public void UpdateEntidad(Entidad entidad) { Update(entidad); } } } <file_sep>/ProtectionData/UtilityTools.cs using System; using System.Collections.Generic; using System.Text; using CryptoHelper; namespace ProtectionData { public class UtilityTools { // Method for hashing the password public string HashPassword(string password) { return Crypto.HashPassword(password); } // Method to verify the password hash against the given password public bool VerifyPassword(string hash, string password) { return Crypto.VerifyHashedPassword(hash, password); } } } <file_sep>/README.md # web-api-aspnet-core-3-base Proyecto en ASP .NET COre 3 Desarrollado en capas con abstracciones e interfaces. Tomando como base cuanta buenas practicas de desarrollo en API's Web Librerias base en este proyecto: - Loggins con NLOG - Notificaciones con Slack - Entity Framework CRUD - Docker para Linux - Encriptacion de datos - Cors - Swagger - Documentacion de API'S - JWT - Json Web Token <file_sep>/Entities/Migrations/20191119214323_actualizarID.cs using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Entities.Migrations { public partial class actualizarID : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_account_owner_OwnerId", table: "account"); migrationBuilder.DropPrimaryKey( name: "PK_owner", table: "owner"); migrationBuilder.DropPrimaryKey( name: "PK_account", table: "account"); migrationBuilder.DropColumn( name: "OwnerId", table: "owner"); migrationBuilder.DropColumn( name: "AccountId", table: "account"); migrationBuilder.AddColumn<Guid>( name: "Id", table: "owner", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.AddColumn<Guid>( name: "Id", table: "account", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.AddPrimaryKey( name: "PK_owner", table: "owner", column: "Id"); migrationBuilder.AddPrimaryKey( name: "PK_account", table: "account", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_account_owner_OwnerId", table: "account", column: "OwnerId", principalTable: "owner", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_account_owner_OwnerId", table: "account"); migrationBuilder.DropPrimaryKey( name: "PK_owner", table: "owner"); migrationBuilder.DropPrimaryKey( name: "PK_account", table: "account"); migrationBuilder.DropColumn( name: "Id", table: "owner"); migrationBuilder.DropColumn( name: "Id", table: "account"); migrationBuilder.AddColumn<Guid>( name: "OwnerId", table: "owner", type: "uniqueidentifier", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.AddColumn<Guid>( name: "AccountId", table: "account", type: "uniqueidentifier", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000")); migrationBuilder.AddPrimaryKey( name: "PK_owner", table: "owner", column: "OwnerId"); migrationBuilder.AddPrimaryKey( name: "PK_account", table: "account", column: "AccountId"); migrationBuilder.AddForeignKey( name: "FK_account_owner_OwnerId", table: "account", column: "OwnerId", principalTable: "owner", principalColumn: "OwnerId", onDelete: ReferentialAction.Cascade); } } } <file_sep>/apiBaseCore/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Notifications; namespace apiBaseCore.Controllers { [Route("api/home")] [ApiController] public class HomeController : ControllerBase { [HttpPost , Route("testslack")] public string TestSlack() { using (var client = new SlackClient()) { string msj = "testiando notificacion slack"; string canalSlack = "#cashflow_testing"; return client.PostMessage(msj, "", canalSlack); } } public string GetEmployeeName(int empId) { string name; if (empId == 1) { name = "Jignesh"; } else if (empId == 2) { name = "Rakesh"; } else { name = "Not Found"; } return name; } } }
0eedd53b7029fb6134a92a042ac4b6f8a7cbf4c5
[ "Markdown", "C#", "Dockerfile" ]
12
C#
pacoyx/web-api-aspnet-core-3-base
76f5d6e3326dcaef4312e9f8843bbf0e43e4ce40
4f771a2a09d2462cb8b40a5d401b4628aeeee2b4
refs/heads/master
<repo_name>Smallworldz/Shopping-Cart<file_sep>/app/Http/Controllers/OrderController.php <?php namespace App\Http\Controllers; use App\Order; use Illuminate\Http\Request; use Auth; use App\Cart; use App\Category; use App\Http\Requests; class OrderController extends Controller { public function myorder(){ $id = Auth::user()->id; $parent = Category::with('children')->where('category_id',0)->get()->toArray(); $order_details = Order::where('user_id',$id)->get(); $quantity = Cart::where('user_id',$id)->where('order_id','!=',0)->get()->toArray(); $no_quantity= 0; foreach($quantity as $key => $value){ $no_quantity = $no_quantity + $value['quantity']; } return view('order')->with('orders',$order_details)->with('message',$parent)->with('quantity',$no_quantity); } public function order_details($order_id){ $parent = Category::with('children')->where('category_id',0)->get()->toArray(); $cart_details = Cart::with('products')->where('order_id',$order_id)->get()->toArray(); return view('order_details')->with('order_details',$cart_details)->with('message',$parent); } } <file_sep>/app/Http/Controllers/CartController.php <?php namespace App\Http\Controllers; use App\Cart; use App\Order; use App\Product; use Illuminate\Http\Request; use App\Category; use DB; use Auth; use App\User; use App\Http\Requests; class CartController extends Controller { public function cart(Request $request){ $user_id = $request['user_id']; $product_id = $request['product_id']; $quantity = $request['quantity']; $price = $request['product_price']; $old_quantity = Cart::where('user_id',$user_id)->get()->toArray(); $false =false; if($old_quantity == null){ echo "Null"; } else { foreach ($old_quantity as $key => $value) { if ($value['product_id'] == $product_id) { $quantity = $quantity + $value['quantity']; $updatequantity = DB::table('carts')->where('product_id', $product_id)->update(array('quantity' => $quantity)); $false = true; } } } if ($false == false){ $insert_cart = Cart::create(['user_id'=>$user_id ,'product_id'=>$product_id,'quantity'=>$quantity,'product_price'=>$price]); } } public function cartdelete(Request $request){ $product_id = $request['product_id']; $user_id = $request['user_id']; $deletion = Cart::where('user_id',$user_id)->where('product_id',$product_id)->delete(); print_r($deletion); } public function mycart(){ $cart = Cart::with('products')->where('order_id',0)->get(); $parent = Category::with('children')->where('category_id',0)->get()->toArray(); return view('mycart')->with('message',$parent)->with('cart',$cart); } public function update_quantity(Request $request){ $cart_id = $request['id']; $quantity = $request['quantity']; $update = DB::table('carts')->where('id',$cart_id)->update(array('quantity' => $quantity)); } public function checkout($total){ $id = Auth::user()->id; $userdetails = User::find($id)->get(); $cart = Cart::with('products')->get(); $parent = Category::with('children')->where('category_id',0)->get()->toArray(); return view('checkout')->with('cart',$cart)->with('message',$parent)->with('user',$userdetails)->with('total',$total); } public function order_place(Request $request){ $name=$request['name']; $email = $request['email']; $mobile = $request['mobile']; $address = $request['address']; $zipcode = $request['zipcode']; $city = $request['city']; $user_id = $request['user_id']; $total =$request['total']; $insertion = Order::create(['address'=>$address,'email'=>$email,'mobile'=>$mobile,'user_id'=>$user_id,'mobile'=>$mobile,'total'=>$total]); $order = $insertion['id']; $updation = DB::table('carts')->where('user_id',$user_id)->where('order_id',0)->update(array('order_id' => $order)); return redirect()->route('shopping.thank_you'); } public function thanks(){ $parent = Category::with('children')->where('category_id',0)->get()->toArray(); return view('thank_you')->with('message',$parent); } } <file_sep>/app/Http/Controllers/ProductController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Product; use App\Category; use App\Http\Requests; class ProductController extends Controller { public function product($id){ $products = Product::where('category_id',$id)->get()->toArray(); $parent = Category::with('children')->where('category_id',0)->get()->toArray(); return view('subcategory')->with('products',$products)->with('message',$parent); // return view('product'); // dd($products); } public function viewproduct($id){ $parent = Category::with('children')->where('category_id',0)->get()->toArray(); $product_details =Product::find($id)->toArray(); return view('product')->with('products',$product_details)->with('message',$parent); } } <file_sep>/app/Product.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Cart; class Product extends Model { public function cart(){ return $this->belongsTo(Cart::class); } public function carts(){ return $this->hasOne(Cart::class); } } <file_sep>/resources/assets/js/script.js $(document).ready(function () { $(".cart-login").click(function () { $("#notlogin").modal('hide'); $("#login").modal('show'); }) $("a#addtocart").click(function (e) { e.preventDefault(); var user_id = log_user_id; var pro_id = $(this).attr('product-id'); var product_price = $(this).attr('price'); console.log(pro_id+" "+user_id+" "+product_price); $.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } }); $.ajax({ type:'POST', url:'/cart', data:{user_id:user_id,product_id:pro_id,quantity:1,product_price:product_price}, success:function () { console.log("Succefull"); alert("Item have been added to Your Cart"); }, error:function () { console.log("ERROR"); } }); }); $("a#deletefromcart").click(function (e) { e.preventDefault(); var user_id = log_user_id; var pro_id = $(this).attr('product-id'); console.log(pro_id+" "+user_id); $.ajaxSetup({ headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') } }); $.ajax({ type:'POST', url:'/cartdelete', data:{user_id:user_id,product_id:pro_id}, success:function () { location.reload(); }, error:function () { console.log("ERROR"); } }); }); $("a.update_quantity").click(function (e) { e.preventDefault(); var quantity = $(this).closest('.quantity_value').find('.quantity').val(); console.log(parent); var card_id = $(this).attr('cart_id'); console.log(quantity+" "+card_id); $.ajax({ type:'GET', url:'/update_quantity', data:{id:card_id,quantity:quantity}, success:function () { console.log("Succefully"); location.reload(); }, error:function () { console.log("Error Cart"); } }); }); $('#list').click(function(event){ event.preventDefault(); $('#products .item').addClass('list-group-item'); }); $('#grid').click(function(event){ event.preventDefault(); $('#products .item').removeClass('list-group-item'); $('#products .item').addClass('grid-group-item'); }); }); $(document).ready(function () { var scroll = $(window).scrollTop(); var height1 = $(document).height(); var win = $(window).height(); console.log(scroll); }); $(document).ready(function () { $("#register_form").validate({ rules:{ name:"required", email:"required", user_password:"<PASSWORD>", mobile:"required", dob:"required", address:"required", zipcode:"required", city:"required" }, messages:{ name:"Please enter Your name", email:"Please enter Your ", user_password:"<PASSWORD>", mobile:"Please enter Your mobile", dob:"Please enter Your DOB", address:"Please enter Your Address", zipcode:"Please enter Your City", city:"Please enter Your City" } }); $(".registration").click(function (event) { event.preventDefault(); $("#register_form").valid(); }); }); <file_sep>/app/Http/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ use App\Category; use App\User; use Illuminate\Http\Response; Route::get('/',['as'=>'shopping.home','uses'=>'UserController@home' ]); Route::any('home',['as'=>'shopping.home','uses'=>'UserController@home']); Route::post('register',['as'=>'shopping.register','uses'=>'RegisterController@register']); Route::post('login',['as'=>'shopping.login','uses'=>'RegisterController@login']); Route::get('logout',['as'=>'shopping.logout','uses'=>'UserController@signout']); Route::get('subcategory/{product_id}',['as'=>'shopping.subcategory','uses'=>'ProductController@product']); Route::post('cart',['as'=>'shopping.cart','uses'=>'CartController@cart']); Route::post('cartdelete',['as'=>'shoppind.cartdelete','uses'=>'CartController@cartdelete']); Route::get('/mycart',['as'=>'shopping.mycart','uses'=>'CartController@mycart']); Route::get('/update_quantity',['as'=>'shopping.update_quanity','uses'=>'CartController@update_quantity']); Route::get('/order/{total}',['as'=>'shopping.order','uses'=>'CartController@checkout']); Route::post('/myorder',['as'=>'shopping.order_place','uses'=>'CartController@order_place']); Route::get('/thank_you',['as'=>'shopping.thank_you','uses'=>'CartController@thanks']); Route::get('/myorderdetails',['as'=>'shopping.myorderdetails','uses'=>'OrderController@myorder']); Route::get('/myorder/{order_id}',['as'=>'shopping.order_details','uses'=>'OrderController@order_details']); Route::get('/product/{product_id}',['as'=>'shopping.product','uses'=>'ProductController@viewproduct']); Route::post('submit',function (){ $validator = Validator::make( array( 'name'=> Request::get('name') ), array( 'name'=>'required|max:5' ) ); if($validator->fails()){ return response()->json([ 'success'=>false, 'errors'=>$validator->errors()->toArray() ]); } return response()->json(['success'=>true]); }); Route::get('/fetch_data',['as'=>'shopping.fetch_data','uses'=>'UserController@fetch_data']);<file_sep>/app/Http/Controllers/RegisterController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\Http\Requests\LoginRequest; use App\Http\Requests; use Illuminate\Support\Facades\Auth; class RegisterController extends Controller { public function register(Requests\RegisterRequest $registerRequest) { $name=$registerRequest['name']; $email = $registerRequest['email']; $password = <PASSWORD>($registerRequest['user_password']); $gender = $registerRequest['gender']; $mobile = $registerRequest['mobile']; $dob=$registerRequest['dob']; $address = $registerRequest['address']; $zipcode = $registerRequest['zipcode']; $city = $registerRequest['city']; // dd($registerRequest->all()); $insertion = User::create(['name'=>$name,'email'=>$email,'password'=>$password,'mobile'=>$mobile,'gender'=>$gender,'DOB'=>$dob,'address'=>$address,'zipcode'=>$zipcode,'city'=>$city]); Auth::login($insertion); return redirect()->route('shopping.home'); } public function login(LoginRequest $loginRequest){ $email_id = $loginRequest['emailid']; $login_password=$loginRequest['login_password']; //dd($loginRequest->toArray()); if (Auth::attempt(['email' => $email_id, 'password' => $login_password])) { return redirect()->intended('home'); } else{ dd("Not Successful"); } } }<file_sep>/app/Cart.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Product; class Cart extends Model { protected $fillable = ['user_id','product_id','quantity','product_price']; public function products(){ return $this->hasMany(Product::class,'id','product_id'); } } <file_sep>/app/Http/Controllers/UserController.php <?php namespace App\Http\Controllers; use App\Product; use App\Cart; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Category; use App\Http\Requests; class UserController extends Controller { public function signout(){ Auth::logout(); return redirect()->route('shopping.home'); } public function home(Request $request) { $parent = Category::with('children')->where('category_id',0)->get()->toArray(); $product = Product::with('carts')->take(6)->get()->toArray(); return view('home')->with('message',$parent)->with('product',$product); } public function fetch_data(Request $request){ $quantity = $request['quantity']; $offset = $request['offset']; $data = Product::with('carts')->skip($offset)->take(5)->get()->toArray(); return response($data); } }
510d0f40583d25f2545adb7d15d2f6d9d3086d35
[ "JavaScript", "PHP" ]
9
PHP
Smallworldz/Shopping-Cart
6febc53113369923191a777cec8ca50ba6930702
f4e203f473e040593da87633159f8c572b84baaf
refs/heads/master
<repo_name>andrzejmroz1999/ZadanieRekrutacyjne<file_sep>/Calendar.cs using System; using System.Collections.Generic; using System.Text; namespace ZadanieRekrutacyjne { class Calendar { public class working_hours { public DateTime start = new DateTime(); public DateTime end = new DateTime(); } public class planned_meeting { public List<DateTime> start = new List<DateTime>(); public List<DateTime> end = new List<DateTime>(); } } } <file_sep>/Program.cs using System; using System.Collections.Generic; namespace ZadanieRekrutacyjne { class Program { static void Main(string[] args) { //Wejście int meeting_duration = 30; Calendar.working_hours working_hours1 = new Calendar.working_hours(); working_hours1.start = working_hours1.start.AddHours(8).AddMinutes(0); working_hours1.end = working_hours1.end.AddHours(19).AddMinutes(55); Calendar.working_hours working_hours2 = new Calendar.working_hours(); working_hours2.start = working_hours2.start.AddHours(10).AddMinutes(0); working_hours2.end = working_hours2.end.AddHours(18).AddMinutes(30); //Planowane Spotkania - Kalendarz1 Calendar.planned_meeting planned_meeting1 = new Calendar.planned_meeting(); planned_meeting1.start.Add(new DateTime().AddHours(9).AddMinutes(0)); planned_meeting1.end.Add(new DateTime().AddHours(10).AddMinutes(30)); planned_meeting1.start.Add(new DateTime().AddHours(12).AddMinutes(0)); planned_meeting1.end.Add(new DateTime().AddHours(13).AddMinutes(0)); planned_meeting1.start.Add(new DateTime().AddHours(16).AddMinutes(0)); planned_meeting1.end.Add(new DateTime().AddHours(18).AddMinutes(0)); //Planowane Spotkania - Kalendarz2 Calendar.planned_meeting planned_meeting2 = new Calendar.planned_meeting(); planned_meeting2.start.Add(new DateTime().AddHours(10).AddMinutes(0)); planned_meeting2.end.Add(new DateTime().AddHours(11).AddMinutes(30)); planned_meeting2.start.Add(new DateTime().AddHours(12).AddMinutes(30)); planned_meeting2.end.Add(new DateTime().AddHours(14).AddMinutes(30)); planned_meeting2.start.Add(new DateTime().AddHours(14).AddMinutes(30)); planned_meeting2.end.Add(new DateTime().AddHours(15).AddMinutes(0)); planned_meeting2.start.Add(new DateTime().AddHours(16).AddMinutes(0)); planned_meeting2.end.Add(new DateTime().AddHours(17).AddMinutes(0)); //Algorytm Calendar.working_hours working_hours_merge = new Calendar.working_hours(); if (working_hours1.start.CompareTo(working_hours2.start) > 0) { working_hours_merge.start = working_hours_merge.start.AddHours(get_hours(working_hours1.start.ToString("HH:mm"))).AddMinutes(get_minutes(working_hours1.start.ToString("HH:mm"))); } else { working_hours_merge.start = working_hours_merge.start.AddHours(get_hours(working_hours2.start.ToString("HH:mm"))).AddMinutes(get_minutes(working_hours2.start.ToString("HH:mm"))); } if (working_hours1.end.CompareTo(working_hours2.end) < 0) { working_hours_merge.end = working_hours_merge.end.AddHours(get_hours(working_hours1.end.ToString("HH:mm"))).AddMinutes(get_minutes(working_hours1.end.ToString("HH:mm"))); } else { working_hours_merge.end = working_hours_merge.end.AddHours(get_hours(working_hours2.end.ToString("HH:mm"))).AddMinutes(get_minutes(working_hours2.end.ToString("HH:mm"))); } var merged_calendar = get_merged_calendar(planned_meeting1, planned_meeting2); var normalized_calendar = get_optimized_calendar(merged_calendar); var adjusted_calendar = get_working_hours(normalized_calendar, working_hours_merge); var available_slots = get_available_time_slots(adjusted_calendar, meeting_duration); //Wyjscie if (available_slots.start.Count == 0) { Console.WriteLine("Brak wolnych slotów czasowych"); } for (int i = 0; i < available_slots.start.Count; ++i) { Console.WriteLine(available_slots.start[i].ToString("HH:mm") + " - " + available_slots.end[i].ToString("HH:mm")); } Console.ReadLine(); } public static int get_hours(string time) { string[] pom = time.Split(":"); int hours = int.Parse(pom[0]); return Convert.ToInt32(hours); } public static int get_minutes(string time) { string[] pom = time.Split(":"); int minutes = int.Parse(pom[1]); return Convert.ToInt32(minutes); } public static int get_minutes_value(string time) { string[] pom = time.Split(":"); int hours = int.Parse(pom[0]); int minutes = int.Parse(pom[1]); return Convert.ToInt32(hours) * 60 + Convert.ToInt32(minutes); } public static int compare_times(string t1, string t2) { int p1 = get_minutes_value(t1); int p2 = get_minutes_value(t2); if (p1 >= p2) { return 1; } else if (p2 >= p1) { return -1; } return 0; } // Zakładam że oba kalendarze są posortowane chronologicznie public static Calendar.planned_meeting get_merged_calendar(Calendar.planned_meeting planned_meeting1, Calendar.planned_meeting planned_meeting2) { Calendar.planned_meeting planned_meeting_merge = new Calendar.planned_meeting(); var i = 0; var j = 0; while (i < planned_meeting1.start.Count && j < planned_meeting2.start.Count) { if (compare_times(planned_meeting1.start[i].ToString("HH:mm"), planned_meeting2.start[j].ToString("HH:mm")) == -1) { planned_meeting_merge.start.Add(planned_meeting1.start[i]); planned_meeting_merge.end.Add(planned_meeting1.end[i]); i += 1; } else { planned_meeting_merge.start.Add(planned_meeting2.start[j]); planned_meeting_merge.end.Add(planned_meeting2.end[j]); j += 1; } } while (i < planned_meeting1.start.Count) { planned_meeting_merge.start.Add(planned_meeting1.start[i]); planned_meeting_merge.end.Add(planned_meeting1.end[i]); i += 1; } while (j < planned_meeting2.start.Count) { planned_meeting_merge.start.Add(planned_meeting2.start[j]); planned_meeting_merge.end.Add(planned_meeting2.end[j]); j += 1; } return planned_meeting_merge; } public static Calendar.planned_meeting get_optimized_calendar(Calendar.planned_meeting merged_calendar) { Calendar.planned_meeting planned_meeting = new Calendar.planned_meeting(); planned_meeting.start.Add(merged_calendar.start[0]); planned_meeting.end.Add(merged_calendar.end[0]); int i = 0; while (i < merged_calendar.start.Count) { var pom1_start = planned_meeting.start[planned_meeting.start.Count - 1]; var pom1_end = planned_meeting.end[planned_meeting.end.Count - 1]; planned_meeting.start.RemoveAt(planned_meeting.start.Count - 1); planned_meeting.end.RemoveAt(planned_meeting.end.Count - 1); var start_time1 = pom1_start; var end_time1 = pom1_end; var pom2_start = merged_calendar.start[i]; var pom2_end = merged_calendar.end[i]; var start_time2 = pom2_start; var end_time2 = pom2_end; if (compare_times(end_time1.ToString("HH:mm"), start_time2.ToString("HH:mm")) == 1) { if (compare_times(end_time1.ToString("HH:mm"), end_time2.ToString("HH:mm")) == 1) { planned_meeting.start.Add(start_time1); planned_meeting.end.Add(end_time1); } else { planned_meeting.start.Add(start_time1); planned_meeting.end.Add(end_time2); } } else { planned_meeting.start.Add(start_time1); planned_meeting.end.Add(end_time1); planned_meeting.start.Add(merged_calendar.start[i]); planned_meeting.end.Add(merged_calendar.end[i]); } i += 1; } return planned_meeting; } public static Calendar.planned_meeting get_available_time_slots(Calendar.planned_meeting original_calendar, int duration) { Calendar.planned_meeting planned_meeting = new Calendar.planned_meeting(); int i = 0; while (i < original_calendar.start.Count - 1) { var end_time1 = original_calendar.end[i]; var pom2_start = original_calendar.start[i + 1]; var start_time2 = pom2_start; var p1 = get_minutes_value(end_time1.ToString("HH:mm")); var p2 = get_minutes_value(start_time2.ToString("HH:mm")); if (p1 != p2 && p2 - p1 >= duration) { planned_meeting.start.Add(end_time1); planned_meeting.end.Add(start_time2); } i += 1; } return planned_meeting; } public static Calendar.planned_meeting get_working_hours(Calendar.planned_meeting calendar, Calendar.working_hours working_hours) { var pom1_start = calendar.start[0]; var start_time = pom1_start; var pom2_end = calendar.end[calendar.end.Count - 1]; var end_time = pom2_end; if (compare_times(start_time.ToString("HH:mm"), working_hours.start.ToString("HH:mm")) == -1) { int i = 0; while (i < calendar.start.Count) { if (compare_times(calendar.end[i].ToString("HH:mm"), working_hours.start.ToString("HH:mm")) == -1) { calendar.start.RemoveAt(i); calendar.end.RemoveAt(i); } else break; } } if (compare_times(end_time.ToString("HH:mm"), working_hours.end.ToString("HH:mm")) != -1) { int i = calendar.start.Count - 1; while (i >= 0) { if (compare_times(calendar.start[i].ToString("HH:mm"), working_hours.end.ToString("HH:mm")) != -1) { calendar.end.RemoveAt(i); calendar.start.RemoveAt(i); } i--; } } if (calendar.start.Count > 0 && compare_times(calendar.start[0].ToString("HH:mm"), working_hours.start.ToString("HH:mm")) == -1) { calendar.start[0] = working_hours.start; } if (compare_times(end_time.ToString("HH:mm"), working_hours.end.ToString("HH:mm")) == -1) { calendar.start.Add(working_hours.end); calendar.end.Add(new DateTime().AddHours(23).AddMinutes(59)); int i = calendar.start.Count - 1; while (i >= 1) { if (compare_times(calendar.end[i].ToString("HH:mm"), calendar.start[i].ToString("HH:mm")) == -1) { calendar.end[i] = calendar.end[i - 1]; } i--; } } else if (calendar.start.Count > 0 && compare_times(calendar.end[calendar.start.Count - 1].ToString("HH:mm"), working_hours.end.ToString("HH:mm")) != -1) { calendar.end[calendar.start.Count - 1] = working_hours.end; } return calendar; } } }
9328c4f7566887ff51741257bd7f82685a8df037
[ "C#" ]
2
C#
andrzejmroz1999/ZadanieRekrutacyjne
0873cac8411fc98198aae9c33aa5eee7432e0e56
a578bcb84658600c2397e5b4ba75d7902f8066c1
refs/heads/master
<repo_name>kazqvaizer/celery-sqlalchemy-boilerplate<file_sep>/Pipfile [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] black = "*" ipython = "*" ipdb = "*" isort = "*" flake8 = "*" flake8-isort = "*" flake8-black = "*" [packages] alembic = "*" celery = "*" envparse = "*" flower = "*" psycopg2-binary = "*" pytest = "*" pytest-cov = "*" pytest-env = "*" pytest-freezegun = "*" pytest-mock = "*" redis = "*" requests = "*" requests-mock = "*" sentry-sdk = "*" sqlalchemy = "*" sqlalchemy-utils = "*" [requires] python_version = "3.10" [pipenv] allow_prereleases = true <file_sep>/docker-compose.yml version: '3.8' services: postgres: image: postgres:latest ports: - 5432:5432 environment: POSTGRES_HOST_AUTH_METHOD: trust redis: image: redis:latest ports: - 6379:6379 <file_sep>/.env.example SQLALCHEMY_DATABASE_URI=postgresql://[email protected]:5432/postgres CELERY_BACKEND=redis://0.0.0.0:6379/7 <file_sep>/src/app/models.py from sqlalchemy import Column, Integer from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class ExampleModel(Base): __tablename__ = "example" id = Column(Integer, primary_key=True) <file_sep>/src/app/tasks.py from app.celery import celery from app.db import session_scope from app.models import ExampleModel @celery.task def example_task(): with session_scope() as session: session.add(ExampleModel()) <file_sep>/src/tests/conftest.py import pytest from alembic.command import upgrade as alembic_upgrade from alembic.config import Config as AlembicConfig from envparse import env as environment from sqlalchemy import create_engine from sqlalchemy.engine.url import make_url from sqlalchemy.orm import sessionmaker from sqlalchemy_utils import create_database, database_exists, drop_database @pytest.fixture(scope="session", autouse=True) def env(): environment.read_envfile() return environment @pytest.fixture(scope="session", autouse=True) def engine(env): db_url = make_url(env("SQLALCHEMY_DATABASE_URI")) db_url = db_url.set(database=f"{db_url.database}_test") engine = create_engine(db_url) if not database_exists(engine.url): create_database(engine.url) yield engine drop_database(engine.url) @pytest.fixture(scope="session", autouse=True) def connection(engine): connection = engine.connect() alembic_config = AlembicConfig("alembic.ini") alembic_config.attributes["connection"] = connection alembic_upgrade(alembic_config, "head") yield connection connection.close() @pytest.fixture def session(mocker, connection): transaction = connection.begin() session = sessionmaker()(bind=connection) mocker.patch("sqlalchemy.orm.session.sessionmaker.__call__", return_value=session) yield session session.close() transaction.rollback() <file_sep>/src/app/celery.py import sentry_sdk from celery import Celery from celery.schedules import crontab from envparse import env from sentry_sdk.integrations.celery import CeleryIntegration env.read_envfile() sentry_sdk.init(env("SENTRY_SDN", default=None), integrations=[CeleryIntegration()]) celery = Celery("app", broker=env("CELERY_BACKEND")) celery.autodiscover_tasks(lambda: ("app",)) celery.conf.beat_schedule = { "example_task": {"task": "app.tasks.example_task", "schedule": crontab(minute="*")} } <file_sep>/README.md # celery-sqlalchemy-boilerplate [![build](https://github.com/kazqvaizer/celery-sqlalchemy-boilerplate/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/kazqvaizer/celery-sqlalchemy-boilerplate/actions/workflows/main.yml) Boilerplate for services with Celery, SQLAlchemy, Docker, Alembic and Pytest. ## Why Here is a stable way to run scheduled or triggered tasks in python using celery. This boilerplate will fit any integration purpose when you need to synchronize resources or databases. Current project is pytest friendly. It is very easy to start writing tests for your code here. ## How to start Copy whole project and remove or rewrite all dummy code with `example` in it. There is an example migration file in `migrations/versions/` directory, so you may want to remove it also. To set up your environment locally you need to define `SQLALCHEMY_DATABASE_URI` and `CELERY_BACKEND` parameters in `.env` file. Check `.env.example` as an example. ## Dependencies Install pipenv ``` pip install pipenv ``` Then run ``` pipenv install ``` ## Code your project Create celery tasks inside `src/app/tasks.py` files as usual: ``` from app.celery import celery from app.db import session_scope @celery.task def example_task(): with session_scope() as session: my_celery_task_logic(session) ``` Extend `src/app/celery.py` with schedule for your tasks: ``` from celery.schedules import crontab celery.conf.beat_schedule = { "example_task": { "task": "app.tasks.example_task", "schedule": crontab(minute="*") } } ``` ## Tests There are ready-to-use database fixtures which can greatly help with testing your code in near to production way. Don't forget to run your database, e.g. with `docker-compose up -d` command. To run tests: ``` cd src && pytest ``` ## Code style and linters Run all-in-one command: ``` isort . && black . && flake8 ``` ## Migrations This boilerplate uses Alembic to run and create new migrations. To auto-generate migrations: ``` alembic revision --autogenerate -m "Some migration name" ``` To run migration (with database on): ``` cd src && alembic upgrade head ``` To run migration in prod compose: ``` docker-compose -f docker-compose.prod.yml run celery alembic upgrade head ``` <file_sep>/src/tests/test_example_task.py from app.models import ExampleModel from app.tasks import example_task def test_creates_new_entry(session): example_task() assert session.query(ExampleModel).count() == 1 def test_creates_new_entry_as_many_times_as_task_called(session): for _ in range(3): example_task() assert session.query(ExampleModel).count() == 3 <file_sep>/Dockerfile FROM python:3.10-slim ENV PIP_NO_CACHE_DIR false ENV DOCKER_PIPENV_VERSION 2021.11.23 WORKDIR /src COPY Pipfile Pipfile.lock / RUN pip install --upgrade pip && \ pip install --no-cache-dir pipenv==${DOCKER_PIPENV_VERSION} && \ pipenv install --deploy --system --clear COPY ./src /src <file_sep>/src/tests/test_app_db.py from app.db import Session, engine def test_engine_configured(env): assert str(engine.url) == env("SQLALCHEMY_DATABASE_URI") def test_session_configured(env): session = Session() assert str(session.bind.engine.url) == env("SQLALCHEMY_DATABASE_URI") <file_sep>/.flake8 [flake8] max-line-length = 88 exclude = venv, .git
30d48c31ab2058f2bb191f11efe3050218c2f2b9
[ "YAML", "TOML", "Markdown", "INI", "Python", "Dockerfile", "Shell" ]
12
TOML
kazqvaizer/celery-sqlalchemy-boilerplate
41cef9cf156b854e9734a04501c618977e934568
e6b1837ba9f4bea2a4034a546e28e1c146bfd80a
refs/heads/master
<repo_name>grooveappdev/travis01<file_sep>/index.js require('dotenv').config() const fs = require("fs"); const _ = require("lodash"); const ShodanRequest = require("./lib/ShodanRequest"); const ShodanElasticSearch = require("./lib/ShodanElasticSearch"); const GoogleBigQuery = require("./lib/BigQuery"); const config = require('./config.json'); const shodanReq = new ShodanRequest({ shodanToken: process.env.SHODAN_TOKEN, minTime: 2000, maxConcurrent: 8 }); const shodanES = new ShodanElasticSearch({ host: config.esHost, requestTimeout: 180000 }); const bigQuery = new GoogleBigQuery(); const UNUSED_PROPERTIES = [ "http.html", "http.favicon", "ssl.cert.serial", "ssl.chain", "ssl.dhparams.generator" ]; const EDIT_PROPERTIES = [ 'CategoryRank.Rank', 'CountryRank.Rank', 'GlobalRank.Rank', ]; const key = 'csrftoken'; const keywords = [key, 'country:GB', 'port:443']; const domains = [ 'pipelineservicesuk.com', 'mobile.shearer-candles.com', 'plscivilengineering.com', 'enigmapowertrain.co.uk', 'niconat.net', 'graphic.plc.uk', 'iprojects.costain.com', 'millerextra.com', 'blackmore.co.uk', 'walkerhamill.com', ] bigQuery.initClient().then(() => { const data = [ { hostId: '3', hostName: 'c' }, { hostId: '4', hostName: 'd' } ] const bigQueryData = bigQuery.parseBigQueryData(data); bigQuery.insertData('van_test', 'extra', bigQueryData).then(res => { console.log('ok', res) }).catch(err => { console.log('err', err) }) }); // Promise.all(domains.map(d => shodanReq.exploreDomain(d, EDIT_PROPERTIES).then(extra => { // extra.hostId = d; // return extra; // }))) // .then(data => { // console.log('DONE'); // const bigQueryData = bigQuery.parseBigQueryData(data); // bigQuery.initClient().then(() => { // bigQuery.insertDataAsChunk('van_test', 'extra', bigQueryData, 100).then(res => { // console.log(res); // fs.writeFile( // "./bigquery.json", // JSON.stringify(res), // "utf8", // () => console.log("done bigquery.json") // ); // }).catch(err => { // fs.writeFile( // "./bigquery.json", // JSON.stringify(err), // "utf8", // () => console.log("done bigquery.json") // ); // }) // }); // fs.writeFile( // "./data.json", // JSON.stringify(data), // "utf8", // () => console.log("done data.json") // ); // }); // shodanReq.exploreDomain('pipelineservicesuk.com', EDIT_PROPERTIES) // .then(data => { // console.log('DONE'); // fs.writeFile( // "./data.json", // JSON.stringify(data), // "utf8", // () => console.log("done data.json") // ); // // const finalData = shodanReq.purifyData(data, key, UNUSED_PROPERTIES); // // const bigQueryData = bigQuery.parseBigQueryData(finalData); // // bigQuery.initClient().then(() => { // // bigQuery.insertDataAsChunk('van_test', 'shodan', bigQueryData, 100).then(res => { // // console.log(res); // // fs.writeFile( // // "./bigquery.json", // // JSON.stringify(res), // // "utf8", // // () => console.log("done bigquery.json") // // ); // // }).catch(err => { // // fs.writeFile( // // "./bigquery.json", // // JSON.stringify(err), // // "utf8", // // () => console.log("done bigquery.json") // // ); // // }) // // }); // }); // shodanES.client.search({ // index: 'shodan_host', // type: 'host', // body: { // query: { // wildcard: { "groove.business_domain": "*uk" } // match, term, match_all, wildcard // }, // } // },function (error, response, status) { // if (error){ // console.log("search error: "+error) // } // else { // // console.log("--- Response ---"); // // console.log(response); // console.log("--- Hits ---"); // console.log(response.hits.hits.length) // // response.hits.hits.forEach(function(hit){ // // console.log(hit); // // }) // } // }); // shodanES // .createIndexIfNotExist("shodan_host") // .then(() => { // return shodanES.client // .reindex({ // body: { // source: { // index: config.esIndexName, // query: { // "match_all": {} // } // }, // dest: { // index: "shodan_host" // }, // }, // }) // .then(res => { // console.log('res', res) // }) // .catch(err => console.log("error", err)); // }); <file_sep>/run/initKeyword.js const SQS = require('../lib/AwsSqs'); const config = require('../config.json'); const awsSqs = new SQS(); const keywords = [ 'csrftoken', 'mod_wsgi', 'gunicorn', 'django_language', 'wsgi', 'django' ]; awsSqs.createQueue(config.queueKeywordName).then(res => { var params = { entries: keywords, groupId: 'keyword', queueUrl: res.QueueUrl }; return awsSqs.sendMessageBatch(params).then(data => { console.log("Sent message with payload", data); }); });<file_sep>/schema/shodan.js const SCHEMA = [ { name: 'hostId', type: 'STRING', mode: 'REQUIRED' }, { name: 'asn', type: 'STRING', }, { name: 'data', type: 'STRING', }, { name: 'hash', type: 'STRING', }, { name: 'info', type: 'STRING', }, { name: 'ip_str', type: 'STRING', }, { name: 'isp', type: 'STRING', }, { name: 'org', type: 'STRING', }, { name: 'os', type: 'STRING', }, { name: 'port', type: 'STRING', }, { name: 'product', type: 'STRING', }, { name: 'timestamp', type: 'STRING', }, { name: 'transport', type: 'STRING', }, { name: 'version', type: 'STRING', }, { name: 'cpe', type: 'STRING', mode: 'REPEATED', }, { name: 'domains', type: 'STRING', mode: 'REPEATED', }, { name: 'tags', type: 'STRING', mode: 'REPEATED' }, { name: 'http', type: 'RECORD', fields: [ { name: 'host', type: 'STRING', }, { name: 'html_hash', type: 'STRING', }, { name: 'location', type: 'STRING', }, { name: 'redirects', type: 'RECORD', mode: 'REPEATED', fields: [ { name: 'host', type: 'STRING', }, { name: 'data', type: 'STRING', }, { name: 'location', type: 'STRING', }, ] }, { name: 'server', type: 'STRING', }, { name: 'title', type: 'STRING', }, ] }, { name: 'location', type: 'RECORD', fields: [ { name: 'area_code', type: 'STRING', }, { name: 'city', type: 'STRING', }, { name: 'country_code', type: 'STRING', }, { name: 'country_code3', type: 'STRING', }, { name: 'country_name', type: 'STRING', }, { name: 'dma_code', type: 'STRING', }, { name: 'latitude', type: 'STRING', }, { name: 'longitude', type: 'STRING', }, { name: 'postal_code', type: 'STRING', }, { name: 'region_code', type: 'STRING', }, ] }, { name: 'ssl', type: 'RECORD', fields: [ { name: 'cert', type: 'RECORD', fields: [ { name: 'expired', type: 'BOOLEAN', }, { name: 'expires', type: 'STRING', }, { name: 'fingerprint', type: 'RECORD', fields: [ { name: 'sha1', type: 'STRING', }, { name: 'sha256', type: 'STRING', }, ], }, { name: 'issued', type: 'STRING', }, { name: 'issuer', type: 'RECORD', fields: [ { name: 'C', type: 'STRING', }, { name: 'CN', type: 'STRING', }, { name: 'L', type: 'STRING', }, { name: 'O', type: 'STRING', }, { name: 'OU', type: 'STRING', }, { name: 'ST', type: 'STRING', }, ], }, { name: 'pubkey', type: 'RECORD', fields: [ { name: 'bits', type: 'STRING', }, { name: 'type', type: 'STRING', }, ], }, { name: 'sig_alg', type: 'STRING', }, { name: 'subject', type: 'RECORD', fields: [ { name: 'C', type: 'STRING', }, { name: 'CN', type: 'STRING', }, { name: 'L', type: 'STRING', }, { name: 'O', type: 'STRING', }, { name: 'OU', type: 'STRING', }, { name: 'ST', type: 'STRING', }, { name: 'businessCategory', type: 'STRING', }, { name: 'emailAddress', type: 'STRING', }, ], }, { name: 'version', type: 'STRING', }, ] }, { name: 'cipher', type: 'RECORD', fields: [ { name: 'bits', type: 'STRING', }, { name: 'name', type: 'STRING', }, { name: 'version', type: 'STRING', }, ] }, { name: 'dhparams', type: 'RECORD', fields: [ { name: 'bits', type: 'STRING', }, { name: 'fingerprint', type: 'STRING', }, { name: 'prime', type: 'STRING', }, { name: 'public_key', type: 'STRING', }, ] }, { name: 'tlsext', type: 'RECORD', mode: 'REPEATED', fields: [ { name: 'id', type: 'STRING', }, { name: 'name', type: 'STRING', }, ] }, { name: 'versions', type: 'STRING', mode: 'REPEATED', }, ] }, { name: 'business_domain', type: 'STRING', }, { name: 'httpComponents', type: 'STRING', mode: 'REPEATED', }, { name: 'vulns', type: 'RECORD', fields: [ { name: 'all', type: 'STRING', mode: 'REPEATED', }, { name: 'verified', type: 'STRING', mode: 'REPEATED', }, ] }, ]; module.exports = SCHEMA;<file_sep>/lib/ShodanRequest.js const request = require("request-promise"); const Bottleneck = require('bottleneck'); const shodan = require("shodan-client"); const fs = require("fs"); const _ = require("lodash"); const KeyObject = require('./KeyObject'); const SimilarWeb = require('./SimilarWeb'); const Contact = require('./Contact'); const Wappalyzer = require('./Wappalyzer'); const similarWeb = new SimilarWeb({ maxConcurrent: 2, maxRetry: 2 }); class ShodanRequest { constructor(options) { this.minTime = options.minTime || 0; this.maxConcurrent = options.maxConcurrent || null; this.shodanToken = options.shodanToken || ''; this.limiter = new Bottleneck({ minTime: this.minTime, maxConcurrent: this.maxConcurrent }); } createPageArray(pageCount) { const pageArr = []; for (let page = 1; page <= pageCount; page += 1) { pageArr.push(page); } return pageArr; } getHostCount(query, searchOpts = {}) { return shodan.count(query, this.shodanToken, searchOpts).then(result => result.total || 0); } _getHostPerPage(query, searchOpts = {}, page) { if (page) { return shodan.search(query, this.shodanToken, { ...searchOpts, page }).then(result => { if (result.matches) { return Promise.resolve({ page, hosts: result.matches, error: null, }); } else { console.log('error', page, 'No Data'); return Promise.resolve({ page, hosts: null, error: 'No Data' }); } }).catch(error => { console.log('error', page, error); return Promise.resolve({ page, hosts: null, error }); }); } else { console.log('error', page, 'No Page'); return Promise.resolve({ page, hosts: null, error: 'No Page' }); } } _getHostWithRetry(query, searchOpts = {}, page, retry = 0, time = 0, errorPage) { if (time > retry) { return errorPage; } else { if (time > 0) { console.log(`retry ${time} time on page ${page}`); } return this._getHostPerPage(query, searchOpts, page).then(hostPage => { if (hostPage.error === null) { return hostPage; } else { return this._getHostWithRetry(query, searchOpts, page, retry, time + 1, hostPage); } }); } } getHosts(query, searchOpts = {}, retry = 0) { const shodanHostPageSet = {}; return this.getHostCount(query, searchOpts).then(count => { console.log('count', count) const pageCount = Math.ceil(count / 100); const pageArray = this.createPageArray(pageCount); const getHostsRequests = pageArray.map(page => this.limiter.schedule(() => { return this._getHostWithRetry(query, searchOpts, page, retry); })); return Promise.all(getHostsRequests).then(hostPageArr => { hostPageArr.map(entry => { shodanHostPageSet[entry.page] = entry; }); return shodanHostPageSet; }); }); } purifyData(data, keyword, unusedProps) { const hostArraySet = Object.values(data).map(entry => entry.hosts); const hostArraySetSuccessful = hostArraySet.filter(item => { return _.isEmpty(item) === false; }); const hostList = _.flatten(hostArraySetSuccessful); console.log('host data', hostList.length) const finalHostList = []; const domainList = []; hostList.map(host => { const finalHost = KeyObject.deleteKeysFromObject(host, unusedProps); finalHost.hostId = `shodan_${keyword}_${host.ip_str}_${host.port}`; const domain = KeyObject.getPropertyByKeyPath(host, 'ssl.cert.subject.CN'); if (typeof domain === 'string') { const finalDomain = domain.replace('*.', '').replace('www.', ''); finalHost.business_domain = finalDomain; finalHost.business_domain_extract_by_cert = 1; domainList.push(finalDomain); } else { finalHost.business_domain = null; finalHost.business_domain_extract_by_cert = 0; } const vulnsObj = KeyObject.vulnsChecker(finalHost); if (vulnsObj) { finalHost.vulns = { all: vulnsObj.vulnsList, verified: vulnsObj.vulnsVerified }; } finalHost.httpComponents = KeyObject.httpComponentsChecker(finalHost); finalHostList.push(finalHost); }); // fs.writeFile( // "./domains.json", // JSON.stringify(domainList), // "utf8", // () => console.log("done domains.json") // ); console.log('before', hostArraySet.length, '- after', hostArraySetSuccessful.length); console.log('final data', finalHostList.length); return finalHostList; } exploreDomain_old(domain, editProps) { return new Promise((resolve, reject) => { const partialHost = {}; partialHost.groove = {}; if (typeof domain === 'string') { const promiseDomainInfo = similarWeb.getDomainInfo(domain).then(info => { console.log('done domain', domain); partialHost.groove.similar_web = info; partialHost.groove.domain_info_extract_by_similar_web = 1; editProps.forEach(props => { KeyObject.editPropertyByKeyPath(partialHost, props, 999999999, oldValue => !oldValue); }); }).catch(err => { console.log('error domain', err.statusCode ? err.statusCode : err); }); const promiseContact = Contact.searchContactFromWebsite(domain).then(contact => { console.log('done contact', contact); partialHost.groove.contact = contact; }).catch(err => { console.log('error contact', err.message); }); const promiseWhois = Contact.getDomainRegisterInfoFromWhois(domain).then(contact => { partialHost.groove.whois = contact; }).catch(err => { console.log('error whois', err.message); }); const promiseWap = Wappalyzer.detectTechnologies(domain).then(techList => { const wappalyzer = techList.map(tech => { const categories = tech.categories && tech.categories.map(category => { return Object.keys(category).map(key => `(${key}) ${category[key]}`).join(', '); }); return { ...tech, categories } }); partialHost.groove.wappalyzer = wappalyzer; }).catch(err => { console.log('error wappalyzer', err.message); }); Promise.all([ promiseDomainInfo, promiseContact, promiseWhois, promiseWap ]).then(() => { resolve(partialHost); }); } else { resolve({}); } }); } exploreDomain(domain, editProps) { return new Promise((resolve, reject) => { let extraInfo = {}; if (typeof domain === 'string') { const promiseDomainInfo = similarWeb.getDomainInfo(domain).then(info => { console.log('done domain', domain); extraInfo = { ...extraInfo, ...info } editProps.forEach(props => { KeyObject.editPropertyByKeyPath(extraInfo, props, 999999999, oldValue => !oldValue); }); }).catch(err => { console.log('error domain', err.statusCode ? err.statusCode : err); }); const promiseContact = Contact.searchContactFromWebsite(domain).then(contact => { console.log('done contact', contact); extraInfo = { ...extraInfo, contact } }).catch(err => { console.log('error contact', err.message); }); // const promiseWhois = Contact.getDomainRegisterInfoFromWhois(domain).then(contact => { // partialHost.groove.whois = contact; // }).catch(err => { // console.log('error whois', err.message); // }); const promiseWap = Wappalyzer.detectTechnologies(domain).then(techList => { const wappalyzer = techList.map(tech => { const categories = tech.categories && tech.categories.map(category => { return Object.keys(category).map(key => `(${key}) ${category[key]}`).join(', '); }); return { ...tech, categories } }); extraInfo = { ...extraInfo, wappalyzer } }).catch(err => { console.log('error wappalyzer', err.message); }); Promise.all([ promiseDomainInfo, promiseContact, // promiseWhois, promiseWap ]).then(() => { resolve(extraInfo); }); } else { resolve({}); } }); } } module.exports = ShodanRequest;<file_sep>/run/esDelete.js const ShodanElasticSearch = require("../lib/ShodanElasticSearch"); const config = require('../config.json'); const shodanES = new ShodanElasticSearch({ host: config.esHost, requestTimeout: 180000 }); // client.cluster.health({},function(err, resp, status) { // console.log("-- Client Health --", resp); // }); // client.deleteByQuery({ // index: 'shodan_host', // type: 'host', // body: { // query: { 'match_all': {} } // } // },function(err,resp,status) { // console.log(err, resp); // }); shodanES.deleteIndex(config.esIndexName).then(() => console.log('Indexes have been deleted!'));<file_sep>/lib/AwsSqs.js const AWS = require('aws-sdk'); require('dotenv').config(); const uuid = require('uuid/v4'); const _ = require("lodash"); const Bottleneck = require('bottleneck'); AWS.config.update({ "accessKeyId": process.env.AWS_ACCESS_KEY, "secretAccessKey": process.env.AWS_SECRET_KEY, "region": "ap-southeast-1" }); class AwsSqs { constructor() { this.sqs = new AWS.SQS({ apiVersion: '2012-11-05' }); } convertToBody(message) { if (_.isNil(message)) { throw new Error('Message must not be empty'); } if (typeof message === 'object') { return JSON.stringify(message); } return typeof message.toString === 'function' ? message.toString() : message; } parseMessage(body) { try { return JSON.parse(body); } catch(err) { return body; } } createQueue(queueName) { return new Promise((resolve, reject) => { const createQueueParams = { QueueName: queueName, Attributes: { FifoQueue: 'true', ContentBasedDeduplication: 'true' } } this.sqs.createQueue(createQueueParams, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } deleteQueue(queueUrl) { return new Promise((resolve, reject) => { var params = { QueueUrl: queueUrl }; this.sqs.deleteQueue(params, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } sendMessage({ body, groupId, queueUrl }) { return new Promise((resolve, reject) => { const messageParams = { QueueUrl: queueUrl, MessageBody: this.convertToBody(body), MessageDeduplicationId: uuid(), MessageGroupId: groupId } this.sqs.sendMessage(messageParams, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } _sendMessageBatch({ entries, groupId, queueUrl, distributeGroup }) { return new Promise((resolve, reject) => { const distributor = 10; let index = 0; const messageEntries = entries.map(entry => { index = index > distributor - 1 ? 1 : index + 1; const id = uuid(); const groupDistributed = distributeGroup ? `${groupId}_${index}` : groupId; return { Id: id, MessageBody: this.convertToBody(entry), MessageDeduplicationId: id, MessageGroupId: groupDistributed, } }); var messageParams = { Entries: messageEntries, QueueUrl: queueUrl }; this.sqs.sendMessageBatch(messageParams, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } sendMessageBatch({ entries, groupId, queueUrl, distributeGroup = false }) { const entriesChunk = _.chunk(entries, 10); const limiter = new Bottleneck({ maxConcurrent: 2 }); return Promise.all(entriesChunk.map(chunk => { const params = { entries: chunk, groupId, queueUrl, distributeGroup } return limiter.schedule(() => this._sendMessageBatch(params)); })); } deleteMessage({ receiptHandle, queueUrl }) { return new Promise((resolve, reject) => { const deleteParams = { QueueUrl: queueUrl, ReceiptHandle: receiptHandle }; this.sqs.deleteMessage(deleteParams, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } receiveMessage(queueUrl) { const that = this; return new Promise((resolve, reject) => { const params = { QueueUrl: queueUrl, AttributeNames: ['All'], MessageAttributeNames: ['All'], MaxNumberOfMessages: 1, VisibilityTimeout: 180, WaitTimeSeconds: 20 }; this.sqs.receiveMessage(params, (err, result) => { if (err) { return reject(err); } else { if (result && result.Messages && result.Messages[0]) { const message = result.Messages[0]; message.ack = () => that.deleteMessage({ receiptHandle: message.ReceiptHandle, queueUrl }); return resolve(message); } return reject(new Error('Queue Empty')) } }); }); } getMessageCount(queueUrl) { return new Promise((resolve, reject) => { var params = { QueueUrl: queueUrl, AttributeNames: [ 'ApproximateNumberOfMessages' ] }; this.sqs.getQueueAttributes(params, (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }); } } module.exports = AwsSqs;<file_sep>/run/esCount.js const ShodanElasticSearch = require("../lib/ShodanElasticSearch"); const config = require('../config.json'); const shodanES = new ShodanElasticSearch({ host: config.esHost, requestTimeout: 180000 }); // client.cluster.health({},function(err, resp, status) { // console.log("-- Client Health --", resp); // }); shodanES.count(config.esIndexName, 'host').then(count => console.log("count", count));<file_sep>/run/awsSqsReceiver.js const SQS = require('../lib/AwsSqs'); const config = require('../config.json'); const awsSqs = new SQS(); const queueURL = `${config.queueHost}/keyword.fifo`; awsSqs.receiveMessage(queueURL).then(data => { console.log(data); data.ack().then(() => console.log('ok')); }).catch(err => console.log(err.message)) <file_sep>/sample.js const _ = require("lodash"); const request = require("request-promise"); const shodan = require("shodan-client"); const fs = require("fs"); const Bottleneck = require('bottleneck'); const ShodanRequest = require('./ShodanRequest'); new ShodanRequest({ shodanToken: '<KEY>', minTime: 3000, maxConcurrent: 4 }).getHosts('csrftoken country:GB port:443', { timeout: 60000 }).then(res => { fs.writeFile('./data.json', JSON.stringify(res), 'utf8', () => console.log('done', res)); }); var elasticsearch = require("elasticsearch"); const client = new elasticsearch.Client({ host: "http://localhost:9200" }); const limiter = new Bottleneck({ minTime: 500, maxConcurrent: 5 }); const pro = (name) => new Promise(res => { setTimeout(() => res(name), 3000); }); const sche = (name) => limiter.schedule(() => { const arr = [pro(name),pro(name),pro(name),pro(name)] return Promise.all(arr); }); // sche('TQV').then(res => console.log(res)) // sche('TQV').then(res => console.log(res)) // sche('TQV').then(res => console.log(res)) // sche('TQV').then(res => console.log(res)) // sche('TQV').then(res => console.log(res)) // const AWS = require('aws-sdk'); // AWS.config.loadFromPath(options.config.keyFilename); // AWS.config.update({ region: options.config.region }); // const awsS3 = new AWS.S3(); // var options = { // uri: 'https://api.shodan.io/shodan/host/search?key=<KEY>ZRRKAj&query=csrftoken', // json: true, // }; // request(options).then(data => { // fs.writeFile('./data.json', JSON.stringify(data), 'utf8', () => console.log('done', data.matches.length)); // }); const shodanSearch = () => { } const bulkBuilder = data => { const bulk = []; data.map(match => { bulk.push({ index: { _index: "shodan_ip", _type: "host", _id: `shodan_${match.ip_str}_${match.port}` } }); bulk.push(match); }); return bulk; }; // 100 records per request const searchOpts = { timeout: 60000, page: 17 }; // shodan.search('csrftoken country:GB port:443', 'Uya3hUc1ocXUhRSxm9aqyA8xPLZRRKAj', searchOpts).then(res => { // const matches = res.matches; // // const data = { // // matches, // // facets: res.facets // // } // // const infos = res.matches.map(match => match.ip_str); // // res.matches = {}; // console.log(res) // // const body = bulkBuilder(matches); // // client.bulk({ // // body // // }, function (err, resp) { // // console.log(err, resp) // // }); // // fs.writeFile('./data.json', JSON.stringify(infos), 'utf8', () => console.log('done', matches.length)); // }) // client.cluster.health({},function(err, resp, status) { // console.log("-- Client Health --", resp); // }); // client.indices.create({ // index: 'shodan_ip' // },function(err,resp,status) { // if(err) { // console.log(err); // } // else { // console.log("create",resp); // } // }); // client.index({ // index: 'shodan_ip', // type: 'host', // body: {} // },function(err,resp,status) { // console.log(resp); // }); // client.count( // { // index: "shodan_ip", // type: "host", // body: { // query: { 'match': { 'port' : 443} } // } // }, // function(err, resp, status) { // console.log("host", resp); // } // ); // client.search({ // index: 'shodan_ip', // type: 'host', // body: { // query: { // match: { "isp": "Czech" } // }, // } // },function (error, response,status) { // if (error){ // console.log("search error: "+error) // } // else { // console.log("--- Response ---"); // console.log(response); // console.log("--- Hits ---"); // response.hits.hits.forEach(function(hit){ // console.log(hit); // }) // } // }); // client.get({ // index: 'shodan_ip', // type: 'host', // id: 'QWkeU2oBpY6_f4WjVqnZ' // }, function (error, response) { // console.log(response); // }); // client.deleteByQuery({ // index: 'shodan_ip', // type: 'host', // body: { // query: { 'match_all': {} } // } // },function(err,resp,status) { // console.log(err, resp); // }); // console.log("lodash", _.isEmpty(2)); // console.log("TEST TRAVIS"); shodanES.client.indices.delete({ index: 'van_test' }, function(err, res) { if (err) { console.error(err.message); } else { console.log('Indexes have been deleted!'); } }); <file_sep>/lib/SimilarWeb.js const Bottleneck = require('bottleneck'); const _ = require("lodash"); // const fs = require("fs"); const request = require("request-promise"); const TorAgent = require('toragent'); class SimilarWeb { constructor(options) { this.minTime = options.minTime || 0; this.maxConcurrent = options.maxConcurrent || null; this.maxRetry = options.maxRetry || 0; this.agent = null; this.limiter = new Bottleneck({ minTime: this.minTime, maxConcurrent: this.maxConcurrent }); } initAgent() { return TorAgent.create().then(agent => { this.agent = agent; return agent; }); } _getDomainInfo(domain, time = 0, error) { const maxRetry = this.maxRetry; if (time > maxRetry || (error && error.statusCode < 500)) { return Promise.reject(error); } else { if (time > 0) { console.log(`retry ${time} time on domain ${domain}`); } // return this.agent.rotateAddress().then(() => { // }); return request({ uri: `https://api.similarweb.com/SimilarWebAddon/${domain}/all`, json: true, // resolveWithFullResponse: true, // agent: this.agent, timeout: 30000, headers: { 'Referer': 'chrome-extension://hoklmmgfnpapgjgcpechhaamimifchmp/panel/panel.html' }, }).catch(err => { return this._getDomainInfo(domain, time + 1, err); }); } } getDomainInfo(domain) { // return this._getDomainInfo(domain, 0); return this.limiter.schedule(() => { return this._getDomainInfo(domain, 0); }); } destroyAgent() { if (this.agent) { return this.agent.destroy(); } return Promise.resolve(); } } // const similar = new SimilarWeb({ // minTime: 100, // maxConcurrent: 20, // maxRetry: 5 // }); // similar.initAgent().then(() => { // console.log('create agent') // similar.getDomainInfo('www.unisalt-uk.com').then(res => console.log('info1', res.statusCode, res.body)); // // similar.getDomainInfo('google.com').then(info => console.log('info1', info)); // // similar.getDomainInfo('google.com').then(info => console.log('info2', info)); // }); module.exports = SimilarWeb;<file_sep>/run/exploreDomain.js require('dotenv').config() const fs = require("fs"); const _ = require("lodash"); const ShodanElasticSearch = require("../lib/ShodanElasticSearch"); const ShodanRequest = require("../lib/ShodanRequest"); const GoogleBigQuery = require("../lib/BigQuery"); const SQS = require('../lib/AwsSqs'); const config = require('../config.json'); const schema = require('../schema/extra') console.log('TESTTTTT') const awsSqs = new SQS(); const shodanES = new ShodanElasticSearch({ host: config.esHost, requestTimeout: 180000 }); const shodanReq = new ShodanRequest({ shodanToken: process.env.SHODAN_TOKEN, minTime: 2000, maxConcurrent: 8 }); const bigQuery = new GoogleBigQuery(); const EDIT_PROPERTIES = [ 'CategoryRank.Rank', 'CountryRank.Rank', 'GlobalRank.Rank', ]; const queueURL = `${config.queueHost}/${config.queueDomainName}`; awsSqs.receiveMessage(queueURL).then(message => { console.log('receive', message); const domainChunk = awsSqs.parseMessage(message.Body); bigQuery.initClient() .then(() => { return bigQuery.createTableIfNotExist('testing', 'extra', schema); }) .then(() => { return Promise.all(domainChunk.map(chunk => { return shodanReq.exploreDomain(chunk.domain, EDIT_PROPERTIES).then(extraInfo => { extraInfo.hostId = chunk.hostId; return extraInfo; }) })) }) .then(extraInfoList => { const bigQueryData = bigQuery.parseBigQueryData(extraInfoList); return bigQuery.insertDataAsChunk('testing', 'extra', bigQueryData, 100).then(res => { console.log(res); fs.writeFile( "./bigquery.json", JSON.stringify(res), "utf8", () => console.log("done bigquery.json") ); }).catch(err => { fs.writeFile( "./bigquery.json", JSON.stringify(err), "utf8", () => console.log("done bigquery.json") ); }) }).then(() => { console.log('update completed') message.ack().then(() => { console.log('message ACK'); process.exit(0); }); }); }).catch(err => console.log(err.message))<file_sep>/lib/KeyObject.js const DOT_SEPARATOR = "."; const _ = require("lodash"); const vulnsKeyword = 'vulns'; const vulnsChecker = obj => { const vulns = obj[vulnsKeyword]; const vulnsList = []; const vulnsVerified = []; if (vulns !== null && typeof vulns === 'object') { Object.keys(vulns).map(key => { vulnsList.push(key); if (vulns[key] && vulns[key].verified) { vulnsVerified.push(key); } }); delete obj[vulnsKeyword]; return { vulnsList, vulnsVerified } } return false; } const componentsKeyword = 'http.components'; const httpComponentsChecker = obj => { const components = getPropertyByKeyPath(obj, componentsKeyword); if (components !== null && typeof components === 'object') { deletePropertyByKeyPath(obj, componentsKeyword); return Object.keys(components); } return []; } const editPropertyByKeyPath = (obj, paths, value, condition) => { const pathArr = paths.split(DOT_SEPARATOR); let virtual = obj; const lastAttributeIndex = pathArr.length - 1; for (let i = 0; i < lastAttributeIndex; i += 1) { const path = pathArr[i]; virtual = virtual[path]; if (typeof virtual !== "object" || virtual === null) { return false; } } if ( (typeof condition === "function" && condition(virtual[pathArr[lastAttributeIndex]]) === true) || condition === undefined ) { virtual[pathArr[lastAttributeIndex]] = value; return true; } return false; }; const getPropertyByKeyPath = (obj, paths) => { const pathArr = paths.split(DOT_SEPARATOR); let virtual = obj; const lastAttributeIndex = pathArr.length - 1; for (let i = 0; i < lastAttributeIndex; i += 1) { const path = pathArr[i]; virtual = virtual[path]; if (typeof virtual !== "object" || virtual === null) { return undefined; } } return virtual[pathArr[lastAttributeIndex]]; }; const deletePropertyByKeyPath = (obj, paths) => { const pathArr = paths.split(DOT_SEPARATOR); let virtual = obj; const lastAttributeIndex = pathArr.length - 1; for (let i = 0; i < lastAttributeIndex; i += 1) { const path = pathArr[i]; virtual = virtual[path]; if (typeof virtual !== "object" || virtual === null) { return false; } } delete virtual[pathArr[lastAttributeIndex]]; return true; }; const deleteKeysFromObject = function(object, keys, options) { if (_.isEmpty(object)) { return object; } let keysToDelete; const isDeep = true; if (_.isUndefined(options) == false) { if (_.isBoolean(options.copy)) { isDeep = options.copy; } } let finalObject; if (isDeep) { finalObject = _.clone(object, isDeep); } else { finalObject = object; } if (typeof finalObject === "undefined") { throw new Error("undefined is not a valid object."); } if (arguments.length < 2) { throw new Error("provide at least two parameters: object and list of keys"); } if (Array.isArray(keys)) { keysToDelete = keys; } else { keysToDelete = [keys]; } keysToDelete.forEach(function(paths) { if (paths.indexOf(DOT_SEPARATOR) != -1) { deletePropertyByKeyPath(finalObject, paths); } else if (typeof paths === "string") { delete finalObject[paths]; } }); return finalObject; }; module.exports = { getPropertyByKeyPath, deletePropertyByKeyPath, deleteKeysFromObject, editPropertyByKeyPath, vulnsChecker, httpComponentsChecker }; <file_sep>/lib/Wappalyzer.js const Bottleneck = require('bottleneck'); const Wappalyzer = require('wappalyzer'); const fs = require("fs"); const urlFormat = rawUrl => { if (/^https:\/\//.test(rawUrl) || /^http:\/\//.test(rawUrl)) { return rawUrl; } return `https://${rawUrl}`; } const OPTIONS = { debug: false, delay: 300, maxDepth: 2, maxUrls: 1, htmlMaxCols: 2000, htmlMaxRows: 2000, maxWait: 11000, recursive: true, userAgent: 'Wappalyzer' }; const limiter = new Bottleneck({ maxConcurrent: 15 }); const detectTechnologies = url => limiter.schedule(() => { return new Wappalyzer(urlFormat(url), OPTIONS).analyze() .then(json => { const result = json && json.applications ? json.applications : []; return result; }) .catch(error => { return []; }); }); module.exports = { detectTechnologies } // const urls = require('../domains.json') // Promise.all(urls.map(url => detectTechnologies(url))).then(res => { // fs.writeFile( // "./data.json", // JSON.stringify(res), // "utf8", // () => { // console.log("done data.json"); // // process.exit(0); // } // ); // });<file_sep>/README.md # Travis ## Travis CI
d5f60e208d2e258ca8fedd170063b1a0f339b6d4
[ "JavaScript", "Markdown" ]
14
JavaScript
grooveappdev/travis01
f2a5eab08d45a43e916a3ad6a3e6d7f30973028d
9e03f099f83dabad05698a1198026fded7b465bb
refs/heads/master
<repo_name>Pushpendra7767/Decision-Tree<file_sep>/companydata DT final 2 decision tree.py # import pacakages import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.svm import SVC from sklearn.linear_model import LinearRegression import matplotlib.pylab as plt import seaborn as sns from sklearn.linear_model import Ridge from sklearn.datasets import load_boston from sklearn.linear_model import Ridge, RidgeCV from sklearn.metrics import mean_squared_error # print dataset. comydata = pd.read_csv("C:\\Users\\ACER\\Desktop\\scrap\\Decision tree\\CompanyData.csv") comydata.head() colnames = list(comydata.columns) # Convert string into unique integer values. comydata.loc[comydata['ShelveLoc']=='Good','ShelveLoc']=0 comydata.loc[comydata['ShelveLoc']=='Bad','ShelveLoc']=1 comydata.loc[comydata['ShelveLoc']=='Medium','ShelveLoc']=2 comydata.loc[comydata['Urban']=='Yes','Urban']=1 comydata.loc[comydata['Urban']=='No','Urban']=0 comydata.loc[comydata['US']=='Yes','US']=1 comydata.loc[comydata['US']=='No','US']=0 # plot histogram plt.hist(comydata['Urban'],edgecolor='k') plt.grid(axis='y') plt.show() # check skewnee & kurtosis # graph plot comydata['Sales'].skew() comydata['Sales'].kurt() plt.hist(comydata['Sales'],edgecolor='k') sns.distplot(comydata['Sales'],hist=False) plt.boxplot(comydata['Sales']) comydata['CompPrice'].skew() comydata['CompPrice'].kurt() plt.hist(comydata['CompPrice'],edgecolor='k') sns.distplot(comydata['CompPrice'],hist=False) plt.boxplot(comydata['CompPrice']) # split train & test dataset x = comydata.drop(['Sales'],axis=1) y = comydata['Sales'] X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.33, random_state=42) # implement linear regression and plot graph. comydata1 = LinearRegression() comydata1.fit(X_train,Y_train) pred = comydata1.predict(X_test) comydata1.score(X_train,Y_train) x_l = range(len(X_test)) plt.scatter(x_l, Y_test, s=5, color="green", label="original") plt.plot(x_l, pred, lw=0.8, color="black", label="predicted") plt.legend() plt.show() # implement rigid regression & plt scatter graph. alphas = [0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1,0.5, 1] for a in alphas: model = Ridge(alpha=a, normalize=True).fit(X_train,Y_train) score = model.score(X_train,Y_train) pred_y = model.predict(X_test) mse = mean_squared_error(Y_test, pred_y) print("Alpha:{0:.6f}, R2:{1:.3f}, MSE:{2:.2f}, RMSE:{3:.2f}" .format(a, score, mse, np.sqrt(mse))) # print ypred, score, mse ridge_mod=Ridge(alpha=0.01, normalize=True).fit(X_train,Y_train) ypred = ridge_mod.predict(X_test) score = model.score(X_test,Y_test) mse = mean_squared_error(Y_test,ypred) print("R2:{0:.3f}, MSE:{1:.2f}, RMSE:{2:.2f}" .format(score, mse,np.sqrt(mse))) # plot scatter diagram x_ax = range(len(X_test)) plt.scatter(x_ax, Y_test, s=5, color="blue", label="original") plt.plot(x_ax, ypred, lw=0.8, color="red", label="predicted") plt.legend() plt.show() <file_sep>/fraudcheck DT final.py # import pacakages import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import matplotlib.pylab as plt import seaborn as sns # print dataset. frcheck = pd.read_csv("C:\\Users\\ACER\\Desktop\\scrap\\Decision tree\\Fraudcheck.csv") frcheck.head() colnames = list(frcheck.columns) # Convert string into unique integer values. frcheck.loc[frcheck['Undergrad']=='YES','Undergrad']=1 frcheck.loc[frcheck['Undergrad']=='NO','Undergrad']=0 frcheck.loc[frcheck['Marital.Status']=='Single','Marital.Status']=1 frcheck.loc[frcheck['Marital.Status']=='Married','Marital.Status']=2 frcheck.loc[frcheck['Marital.Status']=='Divorced','Marital.Status']=3 frcheck.loc[frcheck['Urban']=='YES','Urban']=1 frcheck.loc[frcheck['Urban']=='NO','Urban']=0 frcheck.loc[frcheck['Taxable.Income']<=30000,'Taxable.Income']=1 frcheck.loc[frcheck['Taxable.Income']>30000,'Taxable.Income']=0 # plot histogram plt.hist(frcheck['Urban'],edgecolor='k') plt.grid(axis='y') plt.show() # check skewnee & kurtosis # graph plot frcheck['City.Population'].skew() frcheck['City.Population'].kurt() plt.hist(frcheck['City.Population'],edgecolor='k') sns.distplot(frcheck['City.Population'],hist=False) plt.boxplot(frcheck['City.Population']) frcheck['Work.Experience'].skew() frcheck['Work.Experience'].kurt() plt.hist(frcheck['Work.Experience'],edgecolor='k') sns.distplot(frcheck['Work.Experience'],hist=False) plt.boxplot(frcheck['Work.Experience']) # count values frcheck['Taxable.Income'].value_counts() # split train & test dataset y = frcheck['Taxable.Income'] x = frcheck.drop(['Taxable.Income'],axis=1) X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.33, random_state=42) # implement decission tree classifier # criterion = 'entropy',class_weight='balanced' fr1 = DecisionTreeClassifier(criterion = 'entropy',class_weight='balanced',) fr1.fit(X_train,Y_train) pred = fr1.predict(X_test) accuracy_score(Y_test,pred) confusion_matrix(Y_test,pred,labels=[1,0]) # criterion = 'gini',class_weight='balanced',splitter='random',max_features='int' fr2 = DecisionTreeClassifier(criterion = 'gini',class_weight='balanced',splitter='random',max_features='int') fr2.fit(X_train,Y_train) pred = fr2.predict(X_test) accuracy_score(Y_test,pred) confusion_matrix(Y_test,pred,labels=[1,0]) # Bagging classifier # max_samples=0.5,max_features=1.0,n_estimators=10 fr4 = BaggingClassifier(DecisionTreeClassifier(),max_samples=0.5,max_features=1.0,n_estimators=10) fr4.fit(X_train,Y_train) pred4 = fr4.predict(X_test) accuracy_score(Y_test,pred4) confusion_matrix(Y_test,pred4,labels=[1,0]) # max_samples=0.5,max_features=1.0,n_estimators=10,random_state='int' fr5 = BaggingClassifier(DecisionTreeClassifier(),max_samples=0.5,max_features=1.0,n_estimators=10,random_state='int') fr5.fit(X_train,Y_train) pred4 = fr5.predict(X_test) accuracy_score(Y_test,pred4) confusion_matrix(Y_test,pred4,labels=[1,0])
7f7a96aa1c17cdb7c0ddb4163d7d17941b657d3f
[ "Python" ]
2
Python
Pushpendra7767/Decision-Tree
73ef087b52386b0551603fabd75aab23054a319d
9e552fafccbce1b0e76303fab1f15358efca0a23
refs/heads/master
<repo_name>mcanwoo/yii2-exercise<file_sep>/commands/ImportController.php <?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace app\commands; use yii\console\Controller; use app\models\User; use app\models\Loan; /** * This command echoes the first argument that you have entered. * * This command is provided as an example for you to learn how to create console commands. * * @author <NAME> <<EMAIL>> * @since 2.0 */ class ImportController extends Controller { /** * This command echoes what you have entered as the message. * @param string $message the message to be echoed. */ public function actionLoans() { $loans = json_decode( file_get_contents("./loans.json"), true); foreach ($loans as $loan) { $model = new Loan; // Create New record for each element in loan $model->id = $loan['id']; $model->user_id = $loan['user_id']; $model->amount = $loan['amount']; $model->interest = $loan['interest']; $model->duration = $loan['duration']; $model->campaign = $loan['campaign']; $model->status = $loan['status']; $model->start_date = date("Y-m-d", $loan['start_date']); $model->end_date = date("Y-m-d", $loan['end_date']); $model->save(); } echo "Records Added Successfully"; } public function actionUsers() { $users =file_get_contents("./users.json"); $usersArr = json_decode($users, true); foreach ($usersArr as $user) { $model = new User(); $model->first_name = $user["first_name"]; $model->last_name = $user["last_name"]; $model->id = $user["id"]; $model->email = $user["email"]; $model->personal_code = $user["personal_code"]; $model->phone = $user["phone"]; $model->active = $user["active"]; $model->dead = $user["dead"]; $model->lang = $user["lang"]; $model->save(); } echo "Records Successfully added!"; } } <file_sep>/views/Loan/_form.php <?php use yii\helpers\Html; use yii\widgets\ActiveForm; use kartik\date\DatePicker; /* @var $this yii\web\View */ /* @var $model app\models\Loan */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="loan-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'user_id')->textInput() ?> <?= $form->field($model, 'amount')->textInput() ?> <?= $form->field($model, 'interest')->textInput() ?> <?= $form->field($model, 'duration')->textInput() ?> <?= $form->field($model, 'start_date')->widget(DatePicker::classname(), [ 'options' => ['autocomplete'=>'off'], 'pluginOptions' => [ 'format' => 'yyyy-MM-dd', 'todayHighlight' => true ] ]) ?> <?= $form->field($model, 'end_date')->widget(DatePicker::classname(), [ 'options' => ['autocomplete'=>'off'], 'pluginOptions' => [ 'format' => 'yyyy-MM-dd', 'todayHighlight' => true ] ]) ?> <?= $form->field($model, 'status')->checkbox()->label('Active') ?> <?= $form->field($model, 'campaign')->textInput() ?> <div class="form-group"> <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> </div> <script type="text/javascript"> if (document.title.includes("Create")) {elem = document.getElementsByClassName('field-loan-status')[0]; elem.parentNode.removeChild(elem); } </script><file_sep>/models/Loan.php <?php namespace app\models; use Yii; /** * This is the model class for table "loan". * * @property int $id * @property int $user_id * @property string $amount * @property string $interest * @property int $duration * @property string $start_date * @property string $end_date * @property int $campaign * @property bool $status */ class Loan extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'loan'; } /** * {@inheritdoc} */ public function rules() { return [ [['user_id', 'amount', 'interest', 'duration', 'start_date', 'end_date', 'campaign'], 'required'], [['user_id', 'duration', 'campaign'], 'default', 'value' => null], [['user_id', 'duration', 'campaign'], 'integer'], [['amount', 'interest'], 'number'], [['start_date', 'end_date'], 'safe'], [['status'], 'boolean'], [['status'], 'default', 'value'=> true], ["user_id", "exist", "targetClass" => "\app\models\User", "targetAttribute" => "id","message"=>"User Not Found"], ]; // Here we are validating that user is in our database (last rule) } public static function total() // I have created this function to call it when I need to calculate total amount of loans {. // there's an Example in loancontroller's index function $Loans = Loan::find()->all(); $total=0; foreach ($Loans as $Loan) { $total += $Loan->amount; } return $total; } public function getUser() { // Each loan belongs to one user return $this->hasOne(User::className(), ['id' => 'user_id']); } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'user_id' => 'User ID', 'amount' => 'Amount', 'interest' => 'Interest', 'duration' => 'Duration', 'start_date' => 'Start Date', 'end_date' => 'End Date', 'campaign' => 'Campaign', 'status' => 'Status', ]; } } <file_sep>/models/User.php <?php namespace app\models; /** * Class User * * @package app\models */ class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { public function rules() { return [ [['first_name', 'email', 'phone', 'last_name','personal_code'], 'required'], ['personal_code', 'integer'], [['first_name','last_name'], 'match', 'pattern'=>'/^[a-zA-ZñÑáéíóúñÁÉÍÓÚÑ\s]+$/'], ['phone','integer'], ['email','email'], ['active', 'boolean'], ['dead', 'boolean'], ['lang', 'string'] ]; } // I wanted to validate that first name doesn't include any numbers or characters public static function tableName() { return 'user'; } // Our table in database public function getLoans() { // An user can have many loans return $this->hasMany(Loan::className(), ['user_id' => 'id']); } /** * {@inheritdoc} */ public static function findIdentity($id) { return isset(self::$users[$id]) ? new static(self::$users[$id]) : null; } /** * {@inheritdoc} */ public static function findIdentityByAccessToken($token, $type = null) { foreach (self::$users as $user) { if ($user['accessToken'] === $token) { return new static($user); } } return null; } /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { foreach (self::$users as $user) { if (strcasecmp($user['username'], $username) === 0) { return new static($user); } } return null; } /** * {@inheritdoc} */ public function age() { $date = new \DateTime(substr($this->personal_code, 5,2)."-".substr($this->personal_code, 3, 2) ."-" . strval(18 + ceil(substr($this->personal_code, 0, 1)/2-1)) . substr($this->personal_code, 1, 2)); $now = new \DateTime(); $interval = $now->diff($date); return $interval->y; } public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getAuthKey() { return $this->authKey; } /** * {@inheritdoc} */ public function validateAuthKey($authKey) { return $this->authKey === $authKey; } /** * Validates password * * @param string $password password to validate * @return bool if password provided is valid for current user */ public function validatePassword($password) { return $this->password === $password; } } <file_sep>/views/User/index.php <?php use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\Breadcrumbs; use app\models\Loan; /* @var $this yii\web\View */ /* @var $searchModel app\models\UserSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Users'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-index"> <p><?php ?></p> <h1><?= Html::encode($this->title) ?></h1> <?= Breadcrumbs::widget([ //using breadcrumb for User 'links' => [ ['label' => 'Create User', 'url' => 'index.php?r=user/create', ], ['label' => 'Show Users', 'url' => 'index.php?r=user/index', ]] ]) ?> <?= GridView::widget([ // using GridView widget 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'first_name:ntext', 'last_name:ntext', 'email:ntext', 'personal_code', 'phone', 'active:boolean', 'dead:boolean', 'lang:ntext', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div> <file_sep>/views/User/user_view.php <?php use yii\helpers\Html; use yii\widgets\ActiveForm; use app\models\Loan; ?> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'first_name'); ?> <?= $form->field($model, 'last_name'); ?> <?= $form->field($model, 'email'); ?> <?= $form->field($model, 'personal_code'); ?> <?= $form->field($model, 'phone'); ?> <?= $form->field($model, 'active'); ?> <?= $form->field($model, 'dead'); ?> <?= $form->field($model, 'lang'); ?> <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model-> isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?> <?php ActiveForm::end(); ?> <?php $loans = User::find()->where(['id'=>'7472'])->one()->loans; echo "<h1>string</h1>"; foreach ($loans as $loan) { echo $loan->id; } ?><file_sep>/views/Loan/index.php <?php use yii\helpers\Html; use yii\grid\GridView; use app\models\Loan; use yii\widgets\LinkPager; use yii\widgets\Breadcrumbs; //use Yii; /* @var $this yii\web\View */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Loans'; ?> <?= Breadcrumbs::widget([ // I used breadcrumb as a sub-navbar 'links' => [ ['label' => 'Create Loan', 'url' => 'index.php?r=loan/create', ], ['label' => 'Show Loans', 'url' => 'index.php?r=loan/index', ]] ]) ?> <div class="loan-index"> <?= GridView::widget([ // I used yii GridView widget to display data in order 'filterModel' => $searchModel, 'options' => ['class'=>'ctn'], 'summary' => '<p class="summary">Total amount: <strong class="total">'.$total.' €</strong></p>', 'rowOptions' => ['class'=> 'td'], 'filterRowOptions' => ['class'=>'filterrow'], 'captionOptions' => ['class'=>'caps'], 'headerRowOptions' => ['class'=>'headerrow'], 'tableOptions' => ['class'=>'table'], 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'user_id', 'amount', 'interest', 'duration', 'start_date', 'end_date', 'campaign', 'status:boolean', ['class' => 'yii\grid\ActionColumn'] ], ]); ?> </div> <script type="text/javascript"> // Injected Javascript When built-in customization not enough rows = document.getElementsByClassName('td'); var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); for (var i = rows.length - 1; i >= 0; i--) { if (rows[i].cells[4].innerHTML<10) {rows[i].className="td yellow"} // first colored the rows with yellow if their interest is lower than 10 } for (var i = rows.length - 1; i >= 0; i--) { if (rows[i].cells[7].innerHTML>date) {rows[i].className="td red"} // then colored it to red when there's still time to end date } for (var i = rows.length - 1; i >= 0; i--) { if (rows[i].cells[9].innerHTML=="No") {rows[i].className="td deactive"} //then I colored it to Gray if its status is 0 } // Below I relocated the search inputs to give it similar look to your example boxes = document.getElementById('w0-filters'); sum = document.getElementsByClassName("summary")[0]; sum.appendChild(boxes); tops = document.getElementsByTagName("INPUT"); tops[0].placeholder = "id"; tops[1].placeholder = "user id"; tops[2].placeholder = "Amount"; tops[3].placeholder = "interest"; tops[4].placeholder = "duration"; tops[5].placeholder = "Start Date"; tops[6].placeholder = "End Date"; tops[7].placeholder = "campaign"; // tops[8].placeholder = "Status"; </script>
6f214de128bb1da15cd195b601fa4e4252b0218f
[ "PHP" ]
7
PHP
mcanwoo/yii2-exercise
a019c4be7a3f03e2c2c12c0592a6bd1478dbb46e
09946ceb48abb4435fe22ec81e6d7d517ac615f1
refs/heads/master
<file_sep><?php define('HOST','localhost'); define('USER','root'); define('PASSWORD','<PASSWORD>'); define('DATABASE','hall');
d52c62e87bc3e2e5ca38f9ef297cd45274652b8b
[ "PHP" ]
1
PHP
modamania/hall.art
17cef558a44ffb72e74b6c15db114e91c7b0fb34
d5fd60ed6d17238f8fbdce53da877e8f8e6a62f1
refs/heads/master
<repo_name>KingArthur0902/experiment<file_sep>/src/main/java/com/threadblocked/experiment/module/spring/support/ScopeRequestTestBean.java package com.threadblocked.experiment.module.spring.support; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; /** * Created by ArthurTsang on 7/24/16. */ @Scope(value = "request",proxyMode = ScopedProxyMode.TARGET_CLASS) @Component public class ScopeRequestTestBean { private Integer count = 0; public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.threadblocked</groupId> <artifactId>experiment</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>experiment Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <spring.version>4.2.4.RELEASE</spring.version> <jdk.version>1.8</jdk.version> <slf4j.version>1.7.13</slf4j.version> <logback.version>1.1.3</logback.version> <jackson.version>2.4.6</jackson.version> <hibernate-validator.version>5.0.3.Final</hibernate-validator.version> <aspectj.version>1.7.4</aspectj.version> <druid.version>1.0.20</druid.version> <hibernate.version>5.0.7.Final</hibernate.version> <mysql.connector>5.1.38</mysql.connector> <ehcache.core.version>2.6.11</ehcache.core.version> </properties> <dependencies> <!--web begin--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!--web end--> <!--spring dependency begin--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <!--spring dependency end--> <!--aop start--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> <scope>runtime</scope> </dependency> <!--aop end--> <!--transation start--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <!--transation end--> <!--datasource start--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector}</version> </dependency> <!--datasource end--> <!--cache start--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernate.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> <exclusion> <artifactId>ehcache-core</artifactId> <groupId>net.sf.ehcache</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>${ehcache.core.version}</version> <scope>compile</scope> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <!--cache end--> <!--log start--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>runtime</scope> </dependency> <!-- 代码直接调用log4j会被桥接到slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!-- 代码直接调用common-logging会被桥接到slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!-- 代码直接调用java.util.logging会被桥接到slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> <scope>runtime</scope> </dependency> <!--log end--> <!-- JSON begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-joda</artifactId> <version>${jackson.version}</version> </dependency> <!-- JSON end --> <!-- File Upload start--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <!-- File Upload end--> <!--temp start--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${hibernate-validator.version}</version> <exclusions> <exclusion> <artifactId>jboss-logging</artifactId> <groupId>org.jboss.logging</groupId> </exclusion> </exclusions> </dependency> <!--temp end--> <!--test start--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--test end--> <!--email start--> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <!--email end--> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-framework-bom</artifactId> <version>${spring.version}</version> <type>pom</type> <scope>import</scope> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> <repositories> <repository> <id>oschina-repository</id> <url>http://maven.oschina.net/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <build> <finalName>experiment</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <showWarnings>true</showWarnings> </configuration> </plugin> <plugin> <groupId>org.zeroturnaround</groupId> <artifactId>jrebel-maven-plugin</artifactId> <version>1.1.5</version> <executions> <execution> <id>generate-rebel-xml</id> <phase>process-resources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/support/BeanPostProcessorTestBean.java package com.threadblocked.experiment.module.spring.support; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * 对ioc的拓展,对每个bean的实例都会调用下面的两个方法 * 可以有多个实现,用order进行排序 * Created by ArthurTsang on 7/24/16. */ public class BeanPostProcessorTestBean implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("Bean '" + beanName + "' created : " + bean.toString()); return bean; } } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/service/EmailService.java package com.threadblocked.experiment.module.spring.service; /** * Created by ArthurTsang on 8/10/16. */ public interface EmailService { void testEmail(); } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/vo/ConversionVo.java package com.threadblocked.experiment.module.spring.vo; import java.util.Date; /** * Created by ArthurTsang on 7/17/16. */ public class ConversionVo { //@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } private String a; private Integer b; public String getA() { return a; } public void setA(String a) { this.a = a; } public Integer getB() { return b; } public void setB(Integer b) { this.b = b; } } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/controller/ValidatorTestController.java package com.threadblocked.experiment.module.spring.controller; import com.threadblocked.experiment.module.spring.vo.ValidateVo; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; /** * Created by ArthurTsang on 7/20/16. */ @Controller @RequestMapping(value = "/validate") public class ValidatorTestController { @RequestMapping(value = "/test1") public void testValidate1(@Valid ValidateVo vo, BindingResult result){ if(result.hasErrors()){ System.out.println("error"); return; } System.out.println("normal"); } } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/service/JdbcTestService.java package com.threadblocked.experiment.module.spring.service; /** * Created by ArthurTsang on 8/6/16. */ public interface JdbcTestService { void getRowCount(); void getAAACount(); void getName(); void getUser(Integer id); void getUsers(); void addUser(); } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/controller/ExperimentExceptionHandler.java package com.threadblocked.experiment.module.spring.controller; import org.springframework.beans.ConversionNotSupportedException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; /** * Created by ArthurTsang on 7/19/16. */ @ControllerAdvice public class ExperimentExceptionHandler { @ExceptionHandler({ ConversionNotSupportedException.class }) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ModelAndView handleServiceException(HttpServletRequest request, Exception ex) { ModelAndView mv = new ModelAndView("error/error"); HashMap<String, Object> map = new HashMap<>(); map.put("errorCode","aaa"); map.put("errorMsg","bbb"); mv.addAllObjects(map); return mv; } } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/controller/AspectTestController.java package com.threadblocked.experiment.module.spring.controller; import com.threadblocked.experiment.module.spring.service.AspectTestSerivce; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by ArthurTsang on 7/31/16. */ @RequestMapping(value = "/aspect") @RestController public class AspectTestController { @Autowired private AspectTestSerivce aspectTestSerivce; @RequestMapping(value = "test1") public void testAspect1(){ aspectTestSerivce.testAspect(); } @RequestMapping(value = "test2") public void testAspect2(){ aspectTestSerivce.testAround(); } @RequestMapping(value = "test3") public void testAspect3(){ aspectTestSerivce.testXmlAspect(); } @RequestMapping(value = "test4") public void testAspect4(){ aspectTestSerivce.testXmlAround(); } } <file_sep>/src/main/java/com/threadblocked/experiment/module/spring/support/LiftCircleCallbackTestBean.java package com.threadblocked.experiment.module.spring.support; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * Created by ArthurTsang on 7/24/16. */ @Component public class LiftCircleCallbackTestBean implements InitializingBean, DisposableBean { private String name; /** * 注解实现初始化实例后的回调,推荐使用 */ @PostConstruct private void aaa(){ name = "Hello"; System.out.println(name); } /** * 实现接口来标明初始化实例后的回调,不推荐使用(耦合代码) * @throws Exception */ @Override public void afterPropertiesSet() throws Exception { name = "world"; System.out.println(name); } /** * 需要手动开启,配置default-init-method 或者 init-method */ public void init(){ name = "haha"; System.out.println(name); } /** * 注解实现销毁实例前的回调,推荐使用 */ @PreDestroy public void bbb(){ System.out.println("destroy 111111111111"); } /** * 实现接口来标明销毁实例前的回调,不推荐使用(耦合代码) * @throws Exception */ @Override public void destroy() throws Exception { System.out.println("destroy 22222222222"); } /** * 需要手动开启,配置default-destroy-method 或者 destroy-method */ public void dddd(){ System.out.println("destroy 3333333333"); } } <file_sep>/README.md ## description 这是我的一块试验田<file_sep>/src/main/java/com/threadblocked/experiment/module/spring/controller/EmailTestController.java package com.threadblocked.experiment.module.spring.controller; import com.threadblocked.experiment.module.spring.service.EmailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Created by ArthurTsang on 8/10/16. */ @RestController @RequestMapping(value = "/email") public class EmailTestController { @Autowired private EmailService emailService; @RequestMapping(value = "/test1") public void test1(){ emailService.testEmail(); } }
53c9ff669048897dabd7a3275aa1e8b42d8dc946
[ "Markdown", "Java", "Maven POM" ]
12
Java
KingArthur0902/experiment
d6a3f0326eed9e3a301ba9259ef5787d0ba55d5b
b323c8f6230492143e710041cccf77ff221b68ab
refs/heads/main
<repo_name>Liamkneblik/Assignment_1<file_sep>/scripts/script.js let darkThemeButton = document.querySelector(".DarkTheme"); let cancelButton = document.querySelector(".Cancel"); let newNoteButton = document.querySelector(".NewNote"); let saveButton = document.querySelector('.Save'); let navSect = document.querySelector('nav ul'); let note1 = { title: "note one", body: "some text 1" } let note2 = { title: "note two", body: "some text 2" } let notesArray = [note1, note2] function darkTheme(){ let navItems = document.querySelector(' nav'); let mainItems = document.querySelector('main'); let textarea = document.querySelector('.textarea') let darkButton = document.querySelector('.DarkTheme'); navItems.classList.toggle("dark_theme"); mainItems.classList.toggle('dark_theme'); textarea.classList.toggle('dark_theme'); darkButton.classList.toggle('light_theme'); if (darkButton.classList.contains('light_theme')){ darkButton.innerHTML = 'Light Theme' } else{ darkButton.innerHTML = 'Dark Theme' } } function cancelBtn(){ let textarea = document.querySelector(".textarea"); let botBtns = document.querySelector(".bottom") textarea.style.display = "none"; botBtns.style.display = "none"; } function newNoteBtn(){ let textarea = document.querySelector(".textarea"); let botBtns = document.querySelector(".bottom") if (textarea.style.display === "block"){ textarea.value = '' } if(textarea.style.display === "none"){ textarea.value = 'this is a placeholder' } textarea.style.display = "block"; botBtns.style.display = "Flex"; } function saveBtn(){ let textarea = document.querySelector(".textarea"); let textcontent = textarea.value.split('\n') let condensText = '' for(line of textcontent){ if(!(line === textcontent[0])){ condensText += String(line) + " " } } let note3 = {title: `${textcontent[0]}`, body: `${condensText}` } let newNote = document.createElement('li') newNote.innerHTML = `${note3.title}` let navSect = document.querySelector('nav ul') navSect.appendChild(newNote) notesArray.push(note3) navSect.addEventListener('click', loadNote) } function loadNote(evnt){ console.log(evnt) console.log(notesArray) let textarea = document.querySelector('.textarea') for(note of notesArray){ if (evnt.target.innerHTML === note.title) textarea.value = note.title + "\n" + note.body } } navSect.addEventListener('click', loadNote); darkThemeButton.addEventListener('click', darkTheme); cancelButton.addEventListener("click", cancelBtn) newNoteButton.addEventListener("click", newNoteBtn) saveButton.addEventListener("click", saveBtn)
50b7f92c2c66b2c68fad62a9a7e2bafce0ce0984
[ "JavaScript" ]
1
JavaScript
Liamkneblik/Assignment_1
db016d094db5000328664772b6e6344025affa04
ba358d89cae78b31936bbece7d69b4121ae6efdd
refs/heads/master
<file_sep>var swiper = new Swiper('.blog-slider', { spaceBetween: 30, effect: 'fade', loop: true, mousewheel: { invert: false, }, // autoHeight: true, pagination: { el: '.blog-slider__pagination', clickable: true, } }); // var news = '<div class="blog-slider__item swiper-slide">'+ // '<div class="blog-slider__img">'+ // '<img src="'++'" alt="">'+ // '</div>'+ // '<div class="blog-slider__content">'+ // '<span class="blog-slider__code">'+ +'</span>'+ // '<div class="blog-slider__title">'+ +'</div>'+ // '<div class="blog-slider__text">'+ +'</div>'+ // '<a href="#" class="blog-slider__button">'+ +'</a>'+ // '</div>'+ //'</div>';<file_sep># realestate bitrix
2343df75ae54a2ee97dedbfdb6675a4b94e3079c
[ "JavaScript", "Markdown" ]
2
JavaScript
ValWV/realestate
e6bcbc76b4fbfe778c6ab84e646a8e4b1ce454c7
4290cc63e20ebbd2b01169d605ff8f81c021f4b1
refs/heads/master
<repo_name>Joseuiltom/jogo-da-forca<file_sep>/jogo_forca.py #importa a função para escolher uma das palavras from random import choice #importa o modulo tkinter from tkinter import * #importa o partial from functools import partial #escolhe qual dos temas vai ser sorteado temas = ['animais','comidas',] tema = choice(temas) #escolhe qual palavra vai ser sorteada animais = ['soinho','galinha','vaca','gato','girafa'] comidas = ['melancia','peixe','manga','bolacha','feijao'] if tema == 'animais': palavra = choice(animais) elif tema == 'comidas': palavra = choice(comidas) palavra2 = palavra palavra = list(palavra.upper()) palavra_aux = [] palavra_aux2 = palavra.copy() for letra in range(len(palavra)): palavra_aux.append('_') existentes = [] errados = [] #cria a lista com nossas letras alfabeto = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] #cria a classe do nosso programa class jogo_forca(object): """ classe que contém todo o nosso programa. e a sua logica """ #inicializa nossos atributos def __init__(self,i): #atributo para verificar se a palavra ja foi terminada self.aux = False #cria o frame que contem o texto com o tema do jogo self.frame1 = Frame(i) self.frame1['bg'] = 'white' self.frame1['pady'] = 10 self.frame1.pack() #cria o frame que contém a imagen do jogo da forca self.frame2 = Frame(i) self.frame2['pady'] = 20 self.frame2['bg'] = 'white' self.frame2.pack() #frame com as palavras existentes erradas self.frame_letras = Frame(i) self.frame_letras['pady'] = 10 self.frame_letras['bg'] = 'white' self.frame_letras.pack() #cria o frame do texto com as letras da palavra escolhida self.frame3 = Frame(i) self.frame3['bg'] = 'white' self.frame3.pack() #frame dos botões self.frame4 = Frame(i) self.frame4['bg'] = 'white' self.frame4['pady'] = 10 self.frame4.pack() #cria a frame com o resultado das ações do usuário self.frame5 = Frame(i) self.frame5['bg'] = 'white' self.frame5.pack() #cria nossos sprites para ser ultilizados no nosso jogo self.sprite1 = PhotoImage(file='imagens/imagem_1.ppm') self.sprite2 = PhotoImage(file='imagens/imagem_2.ppm') self.sprite3 = PhotoImage(file='imagens/imagem_3.ppm') self.sprite4 = PhotoImage(file='imagens/imagem_4.ppm') self.sprite5 = PhotoImage(file='imagens/imagem_5.ppm') self.sprite6 = PhotoImage(file='imagens/imagem_6.ppm') self.sprite7 = PhotoImage(file='imagens/imagem_7.ppm') #widget do tema do jogo self.texto_tema = Label(self.frame1,text=f'Tema:\n{tema} ',fg='green',bg='white',font=('Verdana',20,'bold')) self.texto_tema.pack() #widget da imagem do jogo da forca self.imagem1 = Label(self.frame2) self.imagem1['image'] = self.sprite1 self.imagem1.imagem = self.sprite1 self.imagem1.pack(side=LEFT) #widget das palavras existentes e as erradas self.texto_ex = Label(self.frame_letras,text=f'Existentes: {existentes}',bg='white',fg='green',font=('Verdana',15,'bold')) self.texto_ex.pack(side=LEFT) self.texto_er = Label(self.frame_letras,text=f'Errados: {errados}',bg='white',fg='green',font=('Verdana',15,'bold')) self.texto_er.pack(side=LEFT) self.mudar_ex() self.mudar_er() #widget do texto da palavra escolhida letras = '' for letra in palavra_aux: letras += letra + ' ' self.texto1 = Label(self.frame3,text=letras,fg='green',bg='white',font=('Verdana',25,'bold')) self.texto1.pack() #cria os nossos botões self.cont = 0 for i in range(len(alfabeto)): if i % 5 == 0: subframe = Frame(self.frame4) subframe['padx'] = 5 subframe['bg'] = 'white' subframe.pack() a = Button(subframe,text=alfabeto[i],fg='green',width=10,command=partial(self.inserir,alfabeto[i])) a.pack(side=LEFT) #cria o widget do texto do resultado das ações do usuário self.texto2 = Label(self.frame5,text='',bg='white',fg='green',font=('Verdana',25,'bold')) self.texto2.pack() #cria o metodo para inserir a palavra digitada def inserir(self,letra): if self.cont >= 6 or letra in existentes or '_' not in palavra_aux: return if letra in palavra: for caractere in range(0,len(palavra)): if letra == palavra[caractere]: palavra_aux[caractere] = letra self.mudar() existentes.append(letra) self.mudar_ex() if '_' not in palavra_aux: self.texto2['text'] = 'Parabéns você ganhou!' else: self.cont += 1 errados.append(letra) self.mudar_er() if self.cont == 1: self.imagem1['image'] = self.sprite2 self.imagem1.imagem = self.sprite2 elif self.cont == 2: self.imagem1['image'] = self.sprite3 self.imagem1.imagem = self.sprite3 elif self.cont == 3: self.imagem1['image'] = self.sprite4 self.imagem1.imagem = self.sprite4 elif self.cont == 4: self.imagem1['image'] = self.sprite5 self.imagem1.imagem = self.sprite5 elif self.cont == 5: self.imagem1['image'] = self.sprite6 self.imagem1.imagem = self.sprite6 elif self.cont == 6: self.imagem1['image'] = self.sprite7 self.imagem1.imagem = self.sprite7 self.texto2['text'] = f'Você perdeu!! a palavra era {palavra2}' self.texto2['fg'] = 'red' #metodo para mudar o texto da palavra def mudar(self): letras = '' for letra in palavra_aux: letras += letra + ' ' self.texto1['text'] = letras def mudar_ex(self): self.texto_ex['text'] = f'Existentes: {existentes}' def mudar_er(self): self.texto_er['text'] = f'Errados: {errados}' #cria as nossa janela e define as coisas iniciais janela = Tk() jogo_forca(janela) janela.title('Jogo da forca') janela.geometry('800x600') janela['bg'] = 'white' janela.mainloop() <file_sep>/README.md # jogo-da-forca jogo da foca em python com tkinter.
036f0a73d06b6d06bb90f4e6804ff9975e50fa95
[ "Markdown", "Python" ]
2
Python
Joseuiltom/jogo-da-forca
fc82319442215d4a1869643c5c1c6389722a8611
47cc68ba05e1dc3f303f2545d5fb9de1afb8850b
refs/heads/master
<repo_name>CegepTR-CHM-Cours/AdventureWorksServices<file_sep>/src/Programmation3.AdventureWorks.Model/SalesTaxRate.cs namespace Programmation3.AdventureWorks.Model { public class SalesTaxRate { public int SalesTaxRateID { get; set; } public int StateProvinceID { get; set; } public decimal TaxRate { get; set; } public string Name { get; set; } } }<file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/ShippingCalculatorService.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Domain { public class ShippingCalculatorService : IShippingCalculatorService { public decimal Compute([NotNull]IEnumerable<CartItem> items, [NotNull]ShipMethod shipMethod) { var shippingCost = shipMethod.ShipBase; shippingCost += shipMethod.ShipRate * items.Sum(x => x.Quantity); return Math.Round(shippingCost, 2); } } } <file_sep>/src/Programmation3.AdventureWorks.Model/ShipMethod.cs using System; namespace Programmation3.AdventureWorks.Model { public class ShipMethod { public int ShipMethodID { get; set; } public string Name { get; set; } public decimal ShipBase { get; set; } public decimal ShipRate { get; set; } public Guid rowguid { get; set; } public DateTime ModifiedDate { get; set; } } }<file_sep>/src/Programmation3.AdventureWorks.Domain/ISubTotalCalculatorService.cs using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain { public interface ISubTotalCalculatorService { decimal Compute(IEnumerable<CartItem> items); } } <file_sep>/src/Programmation3.AdventureWorks/Controllers/ShipMethodsController.cs using Microsoft.AspNet.Mvc; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Framework.Internal; using System.Collections; namespace Programmation3.AdventureWorks.Controllers { public class ShipMethodsController : RepoController<IShipMethodsRepository, ShipMethod, int> { public ShipMethodsController(IShipMethodsRepository repository) : base(repository) { } [HttpGet("DefaultDataStructure")] public override IEnumerable<ShipMethod> Get() { return base.Get(); } [HttpGet] public IEnumerable GetSimple() { return base.Get().Select(x => new { Id = x.ShipMethodID, Name = x.Name }); } } } <file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/ProductRepository.cs using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Data.EF { public class ProductRepository : DefaultRepository<Product, int>, IProductRepository { public ProductRepository([NotNull] ApplicationDbContext dbContext) : base(dbContext, (dbSet, productID) => dbSet.FirstOrDefault(x => x.ProductID == productID)) { } } } <file_sep>/src/Programmation3.AdventureWorks/DI/AWDataCompositionExtensions.cs using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Data.Entity; using Microsoft.Framework.DependencyInjection; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Data.EF; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.DI { public static class AWDataCompositionExtensions { /// <summary> /// Compose Data with EntityFramework implementation. /// </summary> /// <param name="services"></param> public static void AddAWData(this IServiceCollection services) { var provider = services.BuildServiceProvider(); var awConfig = provider.GetService<IAWConfigService>(); var connectionString = awConfig.DefaultConnectionString; services.AddEntityFramework() .AddSqlServer() .AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString)); services.AddScoped<IStatesRepository, StatesRepository>(); services.AddScoped<ICountriesRepository, CountriesRepository>(); services.AddScoped<IShipMethodsRepository, ShipMethodsRepository>(); services.AddScoped<IProductRepository, ProductRepository>(); services.AddScoped<ISalesTaxRatesRepository, SalesTaxRatesRepository>(); } public static void UseAWData(this IApplicationBuilder app, IHostingEnvironment env) { } } } <file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/StatesRepository.cs using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Data.EF { public class StatesRepository : DefaultRepository<State, int>, IStatesRepository { public StatesRepository([NotNull] ApplicationDbContext dbContext) : base(dbContext, (dbSet, stateProvinceID) => dbSet.FirstOrDefault(x => x.StateProvinceID == stateProvinceID)) { } } } <file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/CountriesRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Programmation3.AdventureWorks.Model; namespace Programmation3.AdventureWorks.Data.EF { public class CountriesRepository : DefaultRepository<Country, string>, ICountriesRepository { public CountriesRepository(ApplicationDbContext dbContext) : base(dbContext, (dbSet, countryRegionCode) => dbSet.FirstOrDefault(x => x.CountryRegionCode == countryRegionCode)) { } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Model/OrderCost.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain.Model { public class OrderCost { public decimal Shipping { get; set; } public decimal SubTotal { get; set; } public IEnumerable<TaxeCost> Taxes { get; set; } public decimal Total { get; set; } } } <file_sep>/src/Programmation3.AdventureWorks.Model/State.cs using System; namespace Programmation3.AdventureWorks.Model { public class State { public int StateProvinceID { get; set; } public string StateProvinceCode { get; set; } public string CountryRegionCode { get; set; } public virtual Country Country { get; set; } public bool IsOnlyStateProvinceFlag { get; set; } public string Name { get; set; } public int TerritoryID { get; set; } public Guid rowguid { get; set; } public DateTime ModifiedDate { get; set; } } }<file_sep>/src/Programmation3.AdventureWorks.Model/Product.cs namespace Programmation3.AdventureWorks.Model { public class Product { public int ProductID { get; set; } public decimal ListPrice { get; set; } } }<file_sep>/src/Programmation3.AdventureWorks.Domain/IShippingCalculatorService.cs using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain { public interface IShippingCalculatorService { decimal Compute(IEnumerable<CartItem> items, ShipMethod shipMethod); } } <file_sep>/src/Programmation3.AdventureWorks/Controllers/CountriesController.cs using Microsoft.AspNet.Mvc; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Controllers { public class CountriesController : RepoController<ICountriesRepository, Country, string> { private readonly ICountryService CountryService; public CountriesController(ICountriesRepository repository, ICountryService countryService) : base(repository) { CountryService = countryService; } // GET: api/countries/with/states [HttpGet("with/states")] public virtual IEnumerable GetCountriesWithStates() { return CountryService .GetCountriesWithStates() .Select(x => new { Code = x.CountryRegionCode, Name = x.Name }) .ToArray(); } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Mocks/ProductRepositoryMock.cs using Programmation3.AdventureWorks.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Programmation3.AdventureWorks.Model; namespace Programmation3.AdventureWorks.Tests.Mocks { public class ProductRepositoryMock : RepositoryMock<Product, int>, IProductRepository { public ProductRepositoryMock(params Product[] all) : base((product, id) => product.ProductID == id, all) { } } } <file_sep>/src/Programmation3.AdventureWorks.Data/IRepository.cs using System.Collections.Generic; namespace Programmation3.AdventureWorks.Data { public interface IRepository<TEntity, TKey> where TEntity : class { IEnumerable<TEntity> All { get; } void Add(TEntity entity); void Delete(TEntity entity); TEntity Find(TKey key); void Update(TEntity entity); } }<file_sep>/src/Programmation3.AdventureWorks.Data/IStatesRepository.cs using Programmation3.AdventureWorks.Model; namespace Programmation3.AdventureWorks.Data { public interface IStatesRepository : IRepository<State, int> { } }<file_sep>/test/Programmation3.AdventureWorks.Tests/Mocks/StatesRepositoryMock.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Tests.Mocks { public class StatesRepositoryMock : RepositoryMock<State, int>, IStatesRepository { public StatesRepositoryMock(params State[] all) : base((state, id) => state.StateProvinceID == id, all) { } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/DbSubTotalCalculatorServiceTests.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Tests.Mocks; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests { public class DbSubTotalCalculatorServiceTests { [Fact] public void SubTotalMustBeRoundedDown() { // Arrange var productRepoMock = new ProductRepositoryMock(new Product() { ProductID = 1, ListPrice = 9.9900001M }); var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 } }; var service = new DbSubTotalCalculatorService(productRepoMock); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(19.98M, subTotal); } [Fact] public void ComputeOneProduct() { // Arrange var productRepoMock = new ProductRepositoryMock(new Product() { ProductID = 1, ListPrice = 9.99M }); var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 } }; var service = new DbSubTotalCalculatorService(productRepoMock); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(19.98M, subTotal); } [Fact] public void ComputeManyProducts() { // Arrange var productRepoMock = new ProductRepositoryMock(new Product() { ProductID = 1, ListPrice = 9.99M }, new Product() { ProductID = 2, ListPrice = 15M }); var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 }, new CartItem() { ProductId = 2, Quantity = 1 } }; var service = new DbSubTotalCalculatorService(productRepoMock); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(34.98M, subTotal); } } } <file_sep>/src/Programmation3.AdventureWorks.Data/IShipMethodsRepository.cs using Programmation3.AdventureWorks.Model; namespace Programmation3.AdventureWorks.Data { public interface IShipMethodsRepository : IRepository<ShipMethod, int> { } }<file_sep>/src/Programmation3.AdventureWorks/AWConfigService.cs using Microsoft.Framework.Configuration; using Microsoft.Framework.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks { public sealed class AWConfigService: IAWConfigService { private readonly IConfiguration Configuration; public AWConfigService([NotNull]IConfiguration configuration) { Configuration = configuration; } public string DefaultConnectionString { get { return Configuration.Get("Data:DefaultConnection:ConnectionString"); } } } public interface IAWConfigService { string DefaultConnectionString { get; } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/OrderCostService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Programmation3.AdventureWorks.Domain.Model; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Domain { public class OrderCostService : IOrderCostService { private ITaxeCalculatiorService TaxeCalculationService { get; } private ISubTotalCalculatorService SubTotalCalculatorService { get; } private IShippingCalculatorService ShippingCalculatorService { get; } public OrderCostService([NotNull]ITaxeCalculatiorService taxeCalculationService, [NotNull]ISubTotalCalculatorService subTotalCalculatorService, [NotNull]IShippingCalculatorService shippingCalculatorService) { TaxeCalculationService = taxeCalculationService; SubTotalCalculatorService = subTotalCalculatorService; ShippingCalculatorService = shippingCalculatorService; } public OrderCost ComputeShippingCost([NotNull]ShipMethod shipMethod, [NotNull]Cart shoppingCart, [NotNull]State deliveryState) { var cost = new OrderCost(); cost.SubTotal = SubTotalCalculatorService.Compute(shoppingCart.Items); cost.Shipping = ShippingCalculatorService.Compute(shoppingCart.Items, shipMethod); cost.Taxes = TaxeCalculationService.Compute(deliveryState, cost.SubTotal); cost.Total = cost.SubTotal + cost.Shipping + cost.Taxes.Sum(x => x.Cost); return cost; } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/ICountryService.cs using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain { public interface ICountryService { IEnumerable<Country> GetCountriesWithStates(); } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Mocks/CountriesRepositoryMock.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Tests.Mocks { public class CountriesRepositoryMock : RepositoryMock<Country, string>, ICountriesRepository { public CountriesRepositoryMock(params Country[] all) : base((country, code) => country.CountryRegionCode == code, all) { } } } <file_sep>/src/Programmation3.AdventureWorks/Controllers/RepoController.cs using Microsoft.AspNet.Mvc; using Programmation3.AdventureWorks.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Controllers { [Route("api/[controller]")] public abstract class RepoController<TRepository, TEntity, TKey> : Controller where TRepository : IRepository<TEntity, TKey> where TEntity : class { protected readonly TRepository Repository; public RepoController(TRepository repository) { Repository = repository; } // GET: api/[ControllerName] [HttpGet] public virtual IEnumerable<TEntity> Get() { return Repository.All.ToArray(); } // GET api/[ControllerName]/5 [HttpGet("{key}")] public virtual TEntity Get(TKey key) { return Repository.Find(key); } //// POST api/[ControllerName] //[HttpPost] //public virtual void Post([FromBody]TEntity address) //{ // throw new NotSupportedException(); //} //// PUT api/[ControllerName]/5 //[HttpPut("{key}")] //public virtual void Put(TKey key, [FromBody]TEntity address) //{ // throw new NotSupportedException(); //} //// DELETE api/[ControllerName]/5 //[HttpDelete("{key}")] //public virtual void Delete(TKey key) //{ // throw new NotSupportedException(); //} } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/StaticSubTotalCalculatorService.cs using Microsoft.Framework.Internal; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain { public class StaticSubTotalCalculatorService : ISubTotalCalculatorService { public decimal Compute([NotNull]IEnumerable<CartItem> items) { return Math.Round(items.Sum(x => x.Price * x.Quantity), 2); } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/ShippingCalculatorServiceTests.cs using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Tests.Mocks; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests { public class ShippingCalculatorServiceTests { [Fact] public void ShippingCostMustBeRounded() { // Arrange var shipMethod = new ShipMethod() { ShipBase = 10.00001M, ShipRate = 2.00001M }; var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 } }; var service = new ShippingCalculatorService(); // Act var shippingCost = service.Compute(cartItems, shipMethod); // Assert Assert.Equal(14M, shippingCost); } [Fact] public void ComputeOneProduct() { // Arrange var shipMethod = new ShipMethod() { ShipBase = 10M, ShipRate = 2M }; var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 } }; var service = new ShippingCalculatorService(); // Act var shippingCost = service.Compute(cartItems, shipMethod); // Assert Assert.Equal(14M, shippingCost); } [Fact] public void ComputeManyProducts() { // Arrange var shipMethod = new ShipMethod() { ShipBase = 10M, ShipRate = 2M }; var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2 }, new CartItem() { ProductId = 2, Quantity = 1 } }; var service = new ShippingCalculatorService(); // Act var shippingCost = service.Compute(cartItems, shipMethod); // Assert Assert.Equal(16M, shippingCost); } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Model/TaxeCost.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain.Model { public class TaxeCost { public decimal Amount { get; set; } public decimal Cost { get; set; } public string Name { get; set; } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/StaticSubTotalCalculatorServiceTests.cs using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests.Domain { public class StaticSubTotalCalculatorServiceTests { [Fact] public void SubTotalMustBeRoundedDown() { // Arrange var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2, Price = 9.9912M } }; ISubTotalCalculatorService service = CreateService(); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(19.98M, subTotal); } [Fact] public void ComputeOneProduct() { // Arrange var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2, Price = 9.99M } }; ISubTotalCalculatorService service = CreateService(); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(19.98M, subTotal); } [Fact] public void ComputeManyProducts() { // Arrange var cartItems = new List<CartItem>() { new CartItem() { ProductId = 1, Quantity = 2, Price = 9.99M }, new CartItem() { ProductId = 2, Quantity = 1, Price = 15M } }; ISubTotalCalculatorService service = CreateService(); // Act var subTotal = service.Compute(cartItems); // Assert Assert.Equal(34.98M, subTotal); } private static ISubTotalCalculatorService CreateService() { return new StaticSubTotalCalculatorService(); } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/TaxeCalculationServiceTests.cs using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Tests.Mocks; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests.Domain { public class TaxeCalculationServiceTests { public const string TaxeRateName = "Test taxe rate"; private SalesTaxRatesRepositoryMock MakeSalesTaxRatesRepositoryMock(params SalesTaxRate[] additionalTaxes) { var repository = new SalesTaxRatesRepositoryMock(new SalesTaxRate[] { new SalesTaxRate() { Name = TaxeRateName, SalesTaxRateID = 1, StateProvinceID = 1, TaxRate = 10 } }.Concat(additionalTaxes).ToArray()); return repository; } [Fact] public void TaxeRateMustBeRounded() { // Arrange const string SecondTaxeName = "Weird taxe rate"; var service = new TaxeCalculationService(MakeSalesTaxRatesRepositoryMock(new SalesTaxRate() { Name = SecondTaxeName, SalesTaxRateID = 2, StateProvinceID = 1, TaxRate = 0.000012M })); var state = new State() { StateProvinceID = 1 }; var taxableSubTotal = 15M; // Act var taxes = service.Compute(state, taxableSubTotal); // Assert Assert.Equal(2, taxes.Count()); Assert.Equal(TaxeRateName, taxes.First().Name); Assert.Equal(SecondTaxeName, taxes.Skip(1).First().Name); Assert.Equal(1.5M, taxes.Sum(x => x.Cost)); } [Fact] public void ComputeOneTaxeRate() { // Arrange var service = new TaxeCalculationService(MakeSalesTaxRatesRepositoryMock()); var state = new State() { StateProvinceID = 1 }; var taxableSubTotal = 15M; // Act var taxes = service.Compute(state, taxableSubTotal); // Assert Assert.Equal(1, taxes.Count()); Assert.Equal(TaxeRateName, taxes.First().Name); Assert.Equal(1.5M, taxes.Sum(x => x.Cost)); } [Fact] public void ComputeManyTaxeRate() { const string SecondTaxeRateName = "Test taxe rate 2"; // Arrange var service = new TaxeCalculationService(MakeSalesTaxRatesRepositoryMock(new SalesTaxRate[] { new SalesTaxRate() { Name = SecondTaxeRateName, SalesTaxRateID = 2, StateProvinceID = 1, TaxRate = 20 } })); var state = new State() { StateProvinceID = 1 }; var taxableSubTotal = 15M; // Act var taxes = service.Compute(state, taxableSubTotal); // Assert Assert.Equal(2, taxes.Count()); Assert.Equal(TaxeRateName, taxes.First().Name); Assert.Equal(SecondTaxeRateName, taxes.Skip(1).First().Name); Assert.Equal(4.5M, taxes.Sum(x => x.Cost)); } [Fact] public void ComputeNoState() { // Arrange var service = new TaxeCalculationService(MakeSalesTaxRatesRepositoryMock()); var taxableSubTotal = 15M; // Act var taxes = service.Compute(null, taxableSubTotal); // Assert Assert.Equal(0, taxes.Count()); } [Fact] public void ComputeStateWithoutTax() { // Arrange var state = new State() { StateProvinceID = 2 }; var service = new TaxeCalculationService(MakeSalesTaxRatesRepositoryMock()); var taxableSubTotal = 15M; // Act var taxes = service.Compute(state, taxableSubTotal); // Assert Assert.Equal(0, taxes.Count()); } } } <file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/SalesTaxRatesRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Programmation3.AdventureWorks.Model; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Data.EF { public class SalesTaxRatesRepository : DefaultRepository<SalesTaxRate, int>, ISalesTaxRatesRepository { public SalesTaxRatesRepository([NotNull] ApplicationDbContext dbContext) : base(dbContext, (dbSet, salesTaxRateID) => dbSet.FirstOrDefault(x => x.SalesTaxRateID == salesTaxRateID)) { } public IEnumerable<SalesTaxRate> FindBy(State state) { return this.All.Where(x => x.StateProvinceID == state.StateProvinceID); } } } <file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/DefaultRepository.cs using Microsoft.Data.Entity; using Microsoft.Framework.Internal; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Data.EF { public class DefaultRepository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity : class { protected readonly DbSet<TEntity> Set; protected readonly Func<DbSet<TEntity>, TKey, TEntity> FindDelegate; public DefaultRepository([NotNull]DbContext dbContext, [NotNull]Func<DbSet<TEntity>, TKey, TEntity> findDelegate) { Set = dbContext.Set<TEntity>(); FindDelegate = findDelegate; } public virtual IEnumerable<TEntity> All { get { return Set; } } public virtual TEntity Find(TKey key) { return FindDelegate(Set, key); } public virtual void Add(TEntity entity) { Set.Add(entity); } public virtual void Update(TEntity entity) { Set.Update(entity); } public virtual void Delete(TEntity entity) { Set.Remove(entity); } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/TaxeCalculationService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Domain.Model; using Programmation3.AdventureWorks.Data; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Domain { public class TaxeCalculationService : ITaxeCalculatiorService { private ISalesTaxRatesRepository SalesTaxRatesRepository { get; } public TaxeCalculationService(ISalesTaxRatesRepository salesTaxRatesRepository) { SalesTaxRatesRepository = salesTaxRatesRepository; } public IEnumerable<TaxeCost> Compute(State state, decimal taxableSubTotal) { if (state == null) { yield break; } var rates = SalesTaxRatesRepository.FindBy(state); foreach (var rate in rates) { yield return new TaxeCost() { Name = rate.Name, Amount = rate.TaxRate, Cost = Math.Round(taxableSubTotal * rate.TaxRate / 100, 2) }; } } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/CountryService.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Data; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Domain { public class CountryService : ICountryService { private readonly ICountriesRepository CountriesRepository; private readonly IStatesRepository StatesRepository; public CountryService([NotNull]ICountriesRepository countriesRepository, [NotNull]IStatesRepository statesRepository) { CountriesRepository = countriesRepository; StatesRepository = statesRepository; } public IEnumerable<Country> GetCountriesWithStates() { var countryCodeWithStates = StatesRepository.All .Select(x => x.CountryRegionCode) .Distinct() .ToArray(); var countriesWithStates = CountriesRepository.All .Where(c => countryCodeWithStates.Contains(c.CountryRegionCode)); return countriesWithStates; } } } <file_sep>/test/Programmation3.AdventureWorks.Tests/Mocks/SalesTaxRatesRepositoryMock.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Tests.Mocks { public class SalesTaxRatesRepositoryMock : RepositoryMock<SalesTaxRate, int>, ISalesTaxRatesRepository { public SalesTaxRatesRepositoryMock(params SalesTaxRate[] all) : base((entity, id) => entity.SalesTaxRateID == id, all) { } public IEnumerable<SalesTaxRate> FindBy(State state) { return InternalAll.Where(x => x.StateProvinceID == state.StateProvinceID); } } } <file_sep>/src/Programmation3.AdventureWorks/DI/AWDomainCompositionExtensions.cs using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Framework.DependencyInjection; using Programmation3.AdventureWorks.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.DI { public static class AWDomainCompositionExtensions { public static void AddAWDomain(this IServiceCollection services) { services.AddTransient<IShippingCalculatorService, ShippingCalculatorService>(); services.AddTransient<IOrderCostService, OrderCostService>(); //services.AddTransient<ISubTotalCalculatorService, DbSubTotalCalculatorService>(); services.AddTransient<ISubTotalCalculatorService, StaticSubTotalCalculatorService>(); services.AddTransient<ITaxeCalculatiorService, TaxeCalculationService>(); services.AddTransient<ICountryService, CountryService>(); } public static void UseAWDomain(this IApplicationBuilder app, IHostingEnvironment env) { } } } <file_sep>/src/Programmation3.AdventureWorks.Data/ISalesTaxRatesRepository.cs using Programmation3.AdventureWorks.Model; using System.Collections.Generic; namespace Programmation3.AdventureWorks.Data { public interface ISalesTaxRatesRepository : IRepository<SalesTaxRate, int> { IEnumerable<SalesTaxRate> FindBy(State state); } }<file_sep>/src/Programmation3.AdventureWorks.Data.EntityFramework/ShipMethodsRepository.cs using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Data.Entity; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Data.EF { public class ShipMethodsRepository : DefaultRepository<ShipMethod, int>, IShipMethodsRepository { public ShipMethodsRepository([NotNull] ApplicationDbContext dbContext) : base(dbContext, (dbSet, shipMethodID) => dbSet.FirstOrDefault(x => x.ShipMethodID == shipMethodID)) { } } } <file_sep>/src/Programmation3.AdventureWorks.Data/ICountriesRepository.cs using Programmation3.AdventureWorks.Model; namespace Programmation3.AdventureWorks.Data { public interface ICountriesRepository : IRepository<Country, string> { } }<file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/OrderCostServiceTests.cs using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Tests.Mocks; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests { public class OrderCostServiceTests { private OrderCostService MakeOrderCostService() { var salesTaxRatesRepositoryMock = new SalesTaxRatesRepositoryMock(new SalesTaxRate() { SalesTaxRateID = 1, StateProvinceID = 1, TaxRate = 10 }); var productRepositoryMock = new ProductRepositoryMock( new Product() { ListPrice = 100, ProductID = 1 }, new Product() { ListPrice = 1000, ProductID = 2 } ); var taxeCalculationService = new TaxeCalculationService(salesTaxRatesRepositoryMock); var subTotalCalculatorService = new DbSubTotalCalculatorService(productRepositoryMock); var shippingCalculatorService = new ShippingCalculatorService(); var service = new OrderCostService(taxeCalculationService, subTotalCalculatorService, shippingCalculatorService); return service; } [Fact] public void ComputeOneProduct() { // Arrange var state = new State() { StateProvinceID = 1 }; var shipMethod = new ShipMethod() { ShipMethodID = 1, ShipBase = 10, ShipRate = 5 }; var cart = new Cart() { Items = new CartItem[] { new CartItem() { ProductId = 1, Quantity = 1 } } }; var service = MakeOrderCostService(); // Act var total = service.ComputeShippingCost(shipMethod, cart, state); // Assert Assert.Equal(100, total.SubTotal); Assert.Equal(15, total.Shipping); Assert.Equal(1, total.Taxes.Count()); Assert.Equal(125, total.Total); } [Fact] public void ComputeManyProducts() { // Arrange var state = new State() { StateProvinceID = 1 }; var shipMethod = new ShipMethod() { ShipMethodID = 1, ShipBase = 10, ShipRate = 5 }; var cart = new Cart() { Items = new CartItem[] { new CartItem() { ProductId = 1, Quantity = 1 }, new CartItem() { ProductId = 2, Quantity = 2 } } }; var service = MakeOrderCostService(); // Act var total = service.ComputeShippingCost(shipMethod, cart, state); // Assert Assert.Equal(2100, total.SubTotal); Assert.Equal(25, total.Shipping); Assert.Equal(1, total.Taxes.Count()); Assert.Equal(2335, total.Total); } [Fact] public void ComputeNoState() { // Arrange var shipMethod = new ShipMethod() { ShipMethodID = 1, ShipBase = 10, ShipRate = 5 }; var cart = new Cart() { Items = new CartItem[] { new CartItem() { ProductId = 1, Quantity = 1 } } }; var service = MakeOrderCostService(); // Act var total = service.ComputeShippingCost(shipMethod, cart, null); // Assert Assert.Equal(100, total.SubTotal); Assert.Equal(15, total.Shipping); Assert.Equal(0, total.Taxes.Count()); Assert.Equal(115, total.Total); } } } <file_sep>/src/Programmation3.AdventureWorks/Startup.cs using System; using System.Collections.Generic; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Framework.DependencyInjection; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.DI; using Programmation3.AdventureWorks.Model; using Microsoft.Framework.Runtime; using Microsoft.Framework.Configuration; //using Programmation3.AdventureWorks.DI; namespace Programmation3.AdventureWorks { public class Startup { private readonly IConfiguration Configuration; public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var configurationBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath); configurationBuilder.AddJsonFile("config.json"); configurationBuilder.AddEnvironmentVariables(); Configuration = configurationBuilder.Build(); } // This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddInstance(Configuration); services.AddSingleton<IAWConfigService, AWConfigService>(); services.AddMvc(); services.AddAWData(); services.AddAWDomain(); } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); app.Use(async (httpContext, next) => { httpContext.Response.Headers.Append("Access-Control-Allow-Origin", "*"); httpContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type, x-xsrf-token" }); httpContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET" }); await next(); }); // Add MVC to the request pipeline. app.UseMvc(); // Configure AdventureWorks services app.UseAWData(env); app.UseAWDomain(env); } } }<file_sep>/src/Programmation3.AdventureWorks.Model/Country.cs using System; using System.Collections.Generic; namespace Programmation3.AdventureWorks.Model { public class Country { public string CountryRegionCode { get; set; } public string Name { get; set; } public DateTime ModifiedDate { get; set; } public virtual ICollection<State> States { get; set; } } }<file_sep>/test/Programmation3.AdventureWorks.Tests/Domain/CountryServiceTests.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Tests.Mocks; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Programmation3.AdventureWorks.Tests.Domain { public class CountryServiceTests { public CountryServiceTests() { } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(5)] public void GetCountriesWithStates(int expectedCountries) { // Arrange ICountryService serviceUnderTest = CreateCountryService(expectedCountries); // Act var countries = serviceUnderTest.GetCountriesWithStates(); // Assert Assert.NotNull(countries); Assert.Equal(expectedCountries, countries.Count()); } private ICountryService CreateCountryService(int expectedCountries) { int totalCountries = 10; var states = new List<State>(); var countries = new List<Country>(); for (var i = 0; i < totalCountries; i++) { var country = new Country() { CountryRegionCode = string.Format("C{0}", i), ModifiedDate = DateTime.Now, Name = string.Format("Country {0}", i) }; countries.Add(country); if (i < expectedCountries) { states.Add(new State() { CountryRegionCode = country.CountryRegionCode }); } } var countriesRepository = new CountriesRepositoryMock( countries.ToArray() ); var statesRepository = new StatesRepositoryMock( states.ToArray() ); var service = new CountryService(countriesRepository, statesRepository); return service; } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Model/ShippingRate.cs using Programmation3.AdventureWorks.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Domain.Model { public class ShippingRate { public virtual ShipMethod ShipMethod { get; set; } } } <file_sep>/src/Programmation3.AdventureWorks/Controllers/OrdersController.cs using Microsoft.AspNet.Mvc; using Microsoft.Framework.Internal; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Domain; using Programmation3.AdventureWorks.Domain.Model; using Programmation3.AdventureWorks.Model; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Controllers { [Route("api/[controller]")] public class OrdersController : Controller { private IShipMethodsRepository ShipMethodsRepository { get; } private IOrderCostService OrderCostService { get; } private IStatesRepository StatesRepository { get; } public OrdersController([NotNull]IShipMethodsRepository shipMethodsRepository, [NotNull]IStatesRepository statesRepository, [NotNull]IOrderCostService orderCostService) { ShipMethodsRepository = shipMethodsRepository; StatesRepository = statesRepository; OrderCostService = orderCostService; } // By ID // GET api/orders/compute/1/63/?items[0].ProductId=906&items[0].Quantity=2 // GET api/orders/compute/1/63/?items[0].ProductId=906&items[0].Quantity=2&items[1].ProductId=907&items[1].Quantity=1 // GET api/orders/compute/1/null/?items[0].ProductId=906&items[0].Quantity=2&items[1].ProductId=907&items[1].Quantity=1 // // By Price // GET api/orders/compute/1/63/?items[0].Price=9.99&items[0].Quantity=2&items[1].Price=15&items[1].Quantity=1 /// <summary> /// /// </summary> /// <param name="shipMethodId">The shipping method primary key.</param> /// <param name="stateId">The shipping address state id, if any.</param> /// <param name="cart">The shipping cart definition, used to compute totals.</param> /// <returns></returns> [HttpGet("[action]/{shipMethodId}/{stateId}")] public virtual OrderCost Compute(int shipMethodId, int? stateId, [FromQuery]Cart cart) { if (cart == null) { throw new ArgumentNullException("cart"); } if (cart.Items == null) { throw new ArgumentNullException("cart.items"); } var shippingMethod = ShipMethodsRepository.Find(shipMethodId); var state = stateId.HasValue ? StatesRepository.Find(stateId.Value) : default(State); var cost = OrderCostService.ComputeShippingCost(shippingMethod, cart, state); return cost; } } } <file_sep>/src/Programmation3.AdventureWorks/Controllers/StatesController.cs using Microsoft.AspNet.Mvc; using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Controllers { public class StatesController : RepoController<IStatesRepository, State, int> { public StatesController(IStatesRepository repository) : base(repository) { } // GET: api/states/in/CA [HttpGet("in/{code}")] public virtual IEnumerable GetStatesByCountry(string code) { return Repository.All .Where(s => s.CountryRegionCode == code) .Select(x => new { Id = x.StateProvinceID, Code = x.StateProvinceCode, Name = x.Name }) .ToArray(); } } } <file_sep>/src/Programmation3.AdventureWorks.Domain/Implementations/DbSubTotalCalculatorService.cs using Programmation3.AdventureWorks.Data; using Programmation3.AdventureWorks.Model; using Programmation3.AdventureWorks.Domain.Model; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Framework.Internal; namespace Programmation3.AdventureWorks.Domain { public class DbSubTotalCalculatorService : ISubTotalCalculatorService { private IProductRepository ProductRepository { get; } public DbSubTotalCalculatorService([NotNull]IProductRepository productRepository) { ProductRepository = productRepository; } public decimal Compute([NotNull]IEnumerable<CartItem> items) { var productsID = items.Select(p => p.ProductId).ToArray(); var products = ProductRepository.All .Where(p => productsID.Contains(p.ProductID)) .Select(p => new { ProductID = p.ProductID, ListPrice = p.ListPrice, Quatity = items.FirstOrDefault(i => i.ProductId == p.ProductID).Quantity }); decimal subTotal = 0; foreach (var product in products) { subTotal += product.ListPrice * product.Quatity; } return Math.Round(subTotal, 2); } } } <file_sep>/README.md # AdventureWorksServices WEB API services that, for exemple, compute shopping cart totals. The services are built to be consumed in JavaScript in my PHP3 classes context. This project is also an exploration project of the new DNX Core, ASP.NET 5, MVC6, EF7, etc. beta frameworks. ## AdventureWorks database The Model is a partial implementation of the AdventureWorks2014 database, that can be found at <http://msftdbprodsamples.codeplex.com/> ## API **Temporary Host: programmation3.azurewebsites.net** *(this will be taken offline at the end of the session)*. ### Countries To get a list of countries that have states, send the following GET request: **http://{host}/api/countries/with/states** > <http://programmation3.azurewebsites.net/api/countries/with/states> To get all countries, send the following GET request: **http://{host}/api/countries** > <http://programmation3.azurewebsites.net/api/countries> To get a single country, send the following GET request: **http://{host}/api/countries/{CountryRegionCode}** > <http://programmation3.azurewebsites.net/api/countries/CA> ### States & provinces To get all states & provinces, send the following GET request: **http://{host}/api/states** > <http://programmation3.azurewebsites.net/api/states> To get a single state or province, send the following GET request: **http://{host}/api/states/{StateProvinceID}** > <http://programmation3.azurewebsites.net/api/states/63> To get all states of a country, send the following GET request: **http://{host}/api/states/in/{CountryRegionCode}** > <http://programmation3.azurewebsites.net/api/states/in/CA> > <http://programmation3.azurewebsites.net/api/states/in/US> ### Shipping methods To get all shipping methods, send the following GET request: **http://{host}/api/shipmethods** or **http://{host}/api/shipmethods/defaultdatastructure** In a simplified data structure form: > <http://programmation3.azurewebsites.net/api/shipmethods> In their complete form: > <http://programmation3.azurewebsites.net/api/shipmethods/defaultdatastructure> To get a single state or province, send the following GET request: **http://{host}/api/shipmethods/{ShipMethodID}** > <http://programmation3.azurewebsites.net/api/shipmethods/2> ### Orders calculation To compute sub-total, shipping and tax rates, send the following GET request: **http://{host}/api/orders/compute/{shipMethodId}/{stateId}/?{items}** The {items} array represent the shopping cart items and should be sent in this format: * (1 item): items[0].Price=9.99&items[0].Quantity=2 * (2 items): items[0].Price=9.99&items[0].Quantity=2&items[1].Price=15&items[1].Quantity=1 > <http://programmation3.azurewebsites.net/api/orders/compute/1/63/?items[0].Price=9.990000001&items[0].Quantity=2&items[1].Price=15.0002335&items[1].Quantity=1> <file_sep>/test/Programmation3.AdventureWorks.Tests/Mocks/RepositoryMock.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Programmation3.AdventureWorks.Tests.Mocks { public class RepositoryMock<TEntity, TKey> { protected List<TEntity> InternalAll { get; } protected Func<TEntity, TKey, bool> FindDelegate { get; } public RepositoryMock(Func<TEntity, TKey, bool> findDelegate, params TEntity[] all) { InternalAll = new List<TEntity>(all); } public IEnumerable<TEntity> All { get { return InternalAll; } } public void Add(TEntity entity) { InternalAll.Add(entity); } public void Delete(TEntity entity) { InternalAll.Remove(entity); } public TEntity Find(TKey key) { return InternalAll.FirstOrDefault(x => FindDelegate(x, key)); } public void Update(TEntity entity) { } } }<file_sep>/README.fr.md # AdventureWorksServices Les services de l'API Web qui, par exemple, calculent le total d'un panier. Les services sont conçus pour être consommés en JavaScript dans le contexte de mon cours de programmation PHP3. Ce projet est aussi un projet d'exploration de DNX, ASP.NET 5, MVC6, EF7, etc. beta. ## Base de données AdventureWorks Le modèle est une mise en œuvre partielle de la base de données AdventureWorks2014, qui peut être trouvé à l'adresse <http://msftdbprodsamples.codeplex.com/> ## API **Host Temporaire: programmation3.azurewebsites.net** *(sera mis hors ligne à la fin de la session)*. ### Pays Pour obtenir une liste des pays qui ont des états, envoyez la requête GET suivante: **http://{host}/api/countries/with/states** > <Http://programmation3.azurewebsites.net/api/countries/with/states> Pour obtenir tous les pays, envoyez la requête GET suivante: **http://{host}/api/countries** > <Http://programmation3.azurewebsites.net/api/countries> Pour obtenir un seul pays, envoyez la requête GET suivante: **http://{host}/api/countries/{CountryRegionCode}** > <Http://programmation3.azurewebsites.net/api/countries/CA> ### États et provinces Pour obtenir tous les États et provinces, envoyez la requête GET suivante: **http://{host}/api/states** > <Http://programmation3.azurewebsites.net/api/states> Pour obtenir un seul état ou province, envoyez la requête GET suivante: **http://{host}/api/states/{StateProvinceID}** > <Http://programmation3.azurewebsites.net/api/states/63> Pour obtenir tous les Etats d'un pays, d'envoyer la requête GET suivante: **http://{host}/api/states/in/{CountryRegionCode}** > <Http://programmation3.azurewebsites.net/api/states/in/CA> > <Http://programmation3.azurewebsites.net/api/states/in/US> ### Méthodes d'envoi Pour obtenir toutes les méthodes d'expédition, envoyez la requête GET suivante: **http://{host}/api/shipmethods** or **http://{host}/api/shipmethods/defaultdatastructure** Dans une forme de structure de données simplifiée: > <Http://programmation3.azurewebsites.net/api/shipmethods> Dans leur forme complète: > <Http://programmation3.azurewebsites.net/api/shipmethods/defaultdatastructure> Pour obtenir un seul état ou province, envoyez la requête GET suivante: **http://{host}/api/shipmethods/{ShipMethodID}** > <Http://programmation3.azurewebsites.net/api/shipmethods/2> ### Calcul des commandes Pour calculer le sous-total, les tarifs d'expédition et fiscales, envoyer la requête GET suivante: **http://{host}/api/orders/compute/{shipMethodId}/{stateId}/?{items}** Le tableau {items} représentent les articles du panier et doit être envoyé dans ce format: * (1 article): items[0].Price=9.99&items[0].Quantity=2 * (2 articles): items[0].Price=9.99&items[0].Quantity=2&items[1].Price=15&items[1].Quantity=1 > <http://programmation3.azurewebsites.net/api/orders/compute/1/63/?items[0].Price=9.990000001&items[0].Quantity=2&items[1].Price=15.0002335&items[1].Quantity=1>
b8e7d50930d6da892c9e81fde7869d9f00f032e3
[ "Markdown", "C#" ]
50
C#
CegepTR-CHM-Cours/AdventureWorksServices
428e9bb0492f837b6bc4553c8a064fa14bf0dc0e
93dfb3cf7eafc7dccb7b394fa66109a5c025f27a
refs/heads/master
<file_sep>package resolvableType; import java.util.List; import java.util.Map; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2019/12/17 17:02 * @Version: 1.0 */ public class BaseDao<T> { private T t; private Map<String,T> tt; int insert(T t){ return 0; } List<T> findList(){ return null; } } <file_sep>package com.alibaba.dubbo.rpc; /** * @Author: yyl * @Date: 2019/3/6 21:03 */ public class MyTest2 { } <file_sep>package type; /** * 父接口 * @Author: yyl * @Date: 2019/1/21 10:27 */ public interface IParent<T> { } <file_sep>package id; import java.net.ServerSocket; /** * @author yang.yonglian * @version 1.0.0 * @Description * @createTime 2020-09-17 */ public class MyTest1 { public static void main(String[] args) throws Exception{ ServerSocket server = new ServerSocket(800); while(server.accept()!=null){ } } } <file_sep>package serviceloader; /** * @Author: yyl * @Date: 2018/11/21 18:05 */ public class MyService2 implements MyInterface{ @Override public void test1() { System.out.println("test2"); } } <file_sep>package mydao; import lombok.Data; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-09-18 */ @TableName("student") @Data public class Student { @TableField private Long id; @TableField("cnname") private String name; @TableField private String sex; @TableField private String note; } <file_sep>package weakReference; import java.lang.ref.WeakReference; public class TestWeakReference { public static void main(String[] args) { Car car = new Car(22200,"sliver"); WeakReference<Car> wr = new WeakReference<Car>(car); int i=0; while(true) { if(wr.get()!=null) { i++; System.out.println("Object is alive for "+i+" loops - "+wr); }else { System.out.println(i); System.out.println("Object has been collected."); break; } } } } <file_sep>package redis; import org.redisson.Redisson; import org.redisson.api.RLock; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-12-10 */ public class MyTest3 { public static void main(String[] args) { RLock redisson = Redisson.create().getLock(""); redisson.lock(); redisson.unlock(); } } <file_sep><?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>com.yyl</groupId> <artifactId>other-knowledge</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.0.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.8.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.41</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version> </dependency> <dependency> <groupId>io.reactivex</groupId> <artifactId>rxjava</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.22.0-GA</version> <scope>compile</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.6.4</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.9</version> </dependency> <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-recipes</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.50.Final</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version> </dependency> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.11.1</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <!--一个打包插件,使用 mvn install assembly:assembly 编译 会在target目录下生成--> <!-- -with-dependency的jar包 使用 java -cp jar package.class 就可以执行对应类的--> <!--main方法 这种打包的方式有点麻烦--> <!--<plugin>--> <!--<artifactId>maven-assembly-plugin</artifactId>--> <!--<configuration>--> <!--<descriptorRefs>--> <!--<descriptorRef>jar-with-dependencies</descriptorRef>--> <!--</descriptorRefs>--> <!--</configuration>--> <!--</plugin>--> <!--也是assembly的一种打包方式,可以指定main函数类,直接install,命令行 运行java -jar xx.jar--> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>create-executable-jar</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptorRefs> <descriptorRef> jar-with-dependencies </descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>xmlbean.XmlBeanUtil</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>package cglib; import collection.sourcecode.HashMap; import org.springframework.cglib.proxy.Enhancer; import java.util.Map; /** * @Author: yyl * @Date: 2019/1/23 15:00 */ public class MyTest4 { /** * spring aop的生成方式拦截测试,不拦截方法的内部调用 * @param args */ public static void main(String[] args){ //注意这里的被代理对象 Dao dao = new Dao(); SpringDaoProxy daoProxy = new SpringDaoProxy(dao); Enhancer enhancer = new Enhancer(); enhancer.setInterceptDuringConstruction(false); enhancer.setSuperclass(Dao.class); enhancer.setCallback(daoProxy); Dao dao1 = (Dao)enhancer.create(); //方法内部调用无效,关键原因在于SpringDaoProxy的回调方法 System.out.println(dao1.select()); System.out.println(dao1.update()); Map<String,Object> map = new HashMap<>(); String ss = (String)map.get("ss"); } } <file_sep>package javassist; /** * @Author: yyl * @Date: 2019/3/6 16:02 */ public class MyBean { public void say(String ss){ System.out.println(" i say "+ss); } } <file_sep>//package com.alibaba.dubbo.common.bytecode; // //import java.lang.reflect.InvocationHandler; // ///** // * @Author: yyl // * @Date: 2019/3/24 15:23 // */ //public class proxy0 implements org.apache.dubbo.demo.DemoService,com.alibaba.dubbo.rpc.service.EchoService{ // public proxy0(){ // // } // public static java.lang.reflect.Method[] methods; // private InvocationHandler handler; // public proxy0(java.lang.reflect.InvocationHandler arg0){ // handler = $1; // } // // public java.lang.String sayHello(java.lang.String arg0) throws java.lang.Exception { // Object[] args = new Object[1]; // args[0] = ($w) $1; // Object ret = handler.invoke(this, methods[0], args); // return (java.lang.String) ret; // } // // public java.lang.Object $echo(java.lang.Object arg0) { // Object[] args = new Object[1]; // args[0] = ($w) $1; // Object ret = handler.invoke(this, methods[1], args); // return (java.lang.Object) ret; // } //} <file_sep>package zookeeper; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; /** * @Description: 基于zk实现分布式锁 * @Author: yang.yonglian * @CreateDate: 2020/3/5 11:04 * @Version: 1.0 */ public class MyTest1 { public static void main(String[] args) { new Thread(()->test1()).start(); new Thread(()->test1()).start(); } public static void test1() { try{ String lockNode = "/gx_wlw_lock_node"; DistributedLockUtils.doLockWork("127.0.0.1:2181",lockNode, ()->{ Thread.sleep(2000); System.out.println("---------------------"); }); }catch (Exception e){ throw new RuntimeException(e); } } } <file_sep>package resolvableType; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2019/12/17 17:07 * @Version: 1.0 */ public class PeronDao extends BaseDao<Person>{ } <file_sep>package thread; import org.junit.Test; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-10-12 */ public class MyTest1 { @Test public void test1() throws Exception{ Thread t1 = new Thread(()->{ sleep(1000); System.out.println("t1线程执行完毕"); }); t1.start(); Thread t2 = new Thread(()->{ try{ t1.join(); System.out.println("t2线程执行完毕"); }catch (Exception e){ throw new RuntimeException(e); } }); t2.start(); sleep(5000); } private void sleep(int time){ try{ Thread.sleep(time); }catch (Exception e){ throw new RuntimeException(e); } } } <file_sep>package beanInfo; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.util.Date; /** * @Author: yyl * @Date: 2019/1/10 11:00 */ @ToString @Setter @Getter @AllArgsConstructor public class Person { private String name; private int age; private Date birthday= new Date(); } <file_sep>//package com.alibaba.dubbo.common.bytecode; // //import java.lang.reflect.InvocationHandler; // ///** // * @Author: yyl // * @Date: 2019/3/24 15:32 // */ //public class Proxy1 extends Proxy{ // public Proxy1(){ // // } // @Override // public Object newInstance(InvocationHandler handler) { // return new com.alibaba.dubbo.common.bytecode.proxy0($1); // } //} <file_sep>package com.alibaba.dubbo.rpc; /** * @Author: provider * @Date: 2019/2/21 14:24 */ public class DemoServiceImpl implements DemoService { public String sayHello(String name) throws Exception{ // Thread.sleep(2000); return "hello "+name; } } <file_sep>package resolvableType; import org.springframework.context.annotation.Configuration; import org.springframework.core.ResolvableType; import org.springframework.stereotype.Component; import org.springframework.util.ReflectionUtils; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2020/1/9 10:52 * @Version: 1.0 */ public class MyTest1 { public static void main(String[] args) { ResolvableType type = ResolvableType.forField(ReflectionUtils.findField(PersonService.class,"baseDao"),1,PersonService.class); ResolvableType type1 = ResolvableType.forClass(PeronDao.class); System.out.println(type.isAssignableFrom(type1)); System.out.println(Configuration.class.isAnnotationPresent(Component.class));; } } <file_sep>package cglib; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * * @Author: yyl * @Date: 2019/1/16 14:26 */ public class DaoProxyBeanFactoryAware implements MethodInterceptor { /** * 动态代理的方法,相当于JDK的InvocationHandler的invoke方法 * @param obj cglib生成的代理对象 * @param method 调用方法 * @param args 被代理方法参数 * @param methodProxy 调用父类方法的代理 * @return * @throws Throwable */ @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { Field field = ReflectionUtils.findField(obj.getClass(),"$$beanFactory"); field.set(obj,args[0]); //这里需要判断下,如果代理对象的父类也就是被代理的对象未实现BeanFactoryAware //那么就不需要执行器父类方法,也就是setBeanFactory方法 if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) { return methodProxy.invokeSuper(obj, args); } return null; } } <file_sep>package resolvableType; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2020/1/9 10:56 * @Version: 1.0 */ public class Animal { } <file_sep>package netty; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-11-02 */ public class MyTest1 { } <file_sep>package netty; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-10-20 */ public class HttpClient { public static void main(String[] args) throws Exception{ String ss = HttpUtils.doGet("http://127.0.0.1:8083/ssss"); System.out.println(ss); } } <file_sep>package resolvableType; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2019/12/17 17:07 * @Version: 1.0 */ public class Person { } <file_sep>package socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; /** * @Author yang.yonglian * @ClassName: socket * @Description: TODO(这里描述) * @Date 2019/6/3 0003 */ public class Client { public static void main(String[] args) throws Exception{ Socket socket = new Socket("127.0.0.1",8888); PrintWriter out = new PrintWriter(socket.getOutputStream(),true); out.println("hello socket"); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String s = in.readLine(); System.out.println("receive msg from server:"+s); out.println("hei hei"); } } <file_sep>package resolvableType; import java.util.List; /** * @Description: TODO * @Author: yang.yonglian * @CreateDate: 2020/1/9 11:12 * @Version: 1.0 */ public class BaseService<T> { private BaseDao<T> baseDao; public int insert(T t){ return baseDao.insert(t); } public List<T> findList(){ return baseDao.findList(); } } <file_sep>package serviceloader; /** * @Author: yyl * @Date: 2018/11/21 18:05 */ public class MyService1 implements MyInterface{ @Override public void test1() { System.out.println("test1"); } } <file_sep>package cglib; import org.springframework.cglib.proxy.Enhancer; /** * @Author: yyl * @Date: 2019/1/16 14:24 */ public class MyTest1 { /** * spring-cglib的使用 * 通用写法 * @param args */ public static void main(String[] args){ DaoProxy daoProxy = new DaoProxy(); //创建一个增强器 Enhancer enhancer = new Enhancer(); //设置要代理的父类 enhancer.setSuperclass(Dao.class); //设置动态代理的回调方法 enhancer.setCallback(daoProxy); //构造函数不拦截方法,默认为true enhancer.setInterceptDuringConstruction(false); Dao dao = (Dao)enhancer.create(); //这里可以看到方法内部的调用也会触发回调方法 //这里的方法内部调用会触发动态代理是因为被代理对象是由cglib生成的,在拦截方法中 //明确执行了methodProxy.invokeSuper(o,objects); 也就是被代理对象的方法,此时的o是由cglib生成的代理对象 //所以方法内部调用时的this对象仍然是代理对象,所以基于cglib的动态代理的方法内部调用能触发 //基于cglib的AOP不能实现原因 查看MyTest4 System.out.println(dao.select()); System.out.println(dao.update()); } } <file_sep>package switchs; /** * @author yang.yonglian * @version 1.0.0 * @Description switch case 使用 * @createTime 2020-09-11 */ public class MyTest1 { /** * switch case一旦case匹配,就会顺序执行后面的程序代码,而不管后面的case是否匹配, * 直到遇见break * @param args */ public static void main(String[] args) { int num = 2; switch (num) { case 1: ++num; case 2: ++num; case 3: num+=2; default: num+=3; break; } System.out.println(num); } } <file_sep>package mydao; import JdbcUtil.JdbcUtil; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.reflection.MetaObject; import org.apache.ibatis.reflection.SystemMetaObject; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import java.util.stream.Collectors; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-09-18 */ public class BaseDao<T> { @Getter @Setter @ToString static class FieldInfo{ private String column; private Field field; } @Getter @Setter @ToString static class TableInfo{ private String tableName; private List<FieldInfo> fieldInfos; private String allColumn; private Class resultType; } private static Map<Class,TableInfo> tableInfoMap = new ConcurrentHashMap<>(); protected List<T> query(String whereCondition, Consumer<PreparedStatement> consumer) { PreparedStatement ps = null; ResultSet rs = null; Connection connection = null; try { Class<T> clazz = findClass(); TableInfo tableInfo = getTableInfo(clazz); String sqlStr = "select " +tableInfo.getAllColumn()+" from "+ tableInfo.getTableName(); if(StringUtils.isNotBlank(whereCondition)){ sqlStr+=" "+whereCondition; } connection = JdbcUtil.getConn(); ps = connection.prepareStatement(sqlStr); rs = doQuery(ps,consumer); return handleResult(rs,tableInfo); }catch (Exception e){ throw new RuntimeException(e); } finally{ try{ if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if(connection!=null){ connection.close(); } }catch (Exception e){ throw new RuntimeException(); } } } private TableInfo getTableInfo(Class<T> clazz){ if(!tableInfoMap.containsKey(clazz)){ synchronized (tableInfoMap){ if(!tableInfoMap.containsKey(clazz)){ System.out.println("getTableInfo:"+clazz.getName()); TableInfo tableInfo = new TableInfo(); List<String> fieldNames = new ArrayList<>(); List<FieldInfo> fieldInfos = new ArrayList<>(); TableName tableName = clazz.getAnnotation(TableName.class); tableInfo.setTableName(tableName.value()); Class currentClazz = clazz; while(currentClazz!=Object.class){ Field[] fields = clazz.getDeclaredFields(); for(Field field:fields){ //存在属性名相同的默认取子类的 if(!fieldNames.contains(field.getName())&&field.isAnnotationPresent(TableField.class)){ TableField tableField = field.getAnnotation(TableField.class); FieldInfo fieldInfo = new FieldInfo(); String column = tableField.value(); if(StringUtils.isEmpty(column)){ column = field.getName(); } fieldInfo.setColumn(column); fieldInfo.setField(field); fieldInfos.add(fieldInfo); } } currentClazz = currentClazz.getSuperclass(); } tableInfo.setFieldInfos(fieldInfos); String allColumn = fieldInfos.stream().map(FieldInfo::getColumn).collect(Collectors.joining(",")); tableInfo.setAllColumn(allColumn); tableInfo.setResultType(clazz); tableInfoMap.put(clazz,tableInfo); } } } return tableInfoMap.get(clazz); } private ResultSet doQuery(PreparedStatement ps, Consumer<PreparedStatement> consumer) throws SQLException{ if(consumer!=null){ consumer.accept(ps); } return ps.executeQuery(); } private List<T> handleResult(ResultSet rs, TableInfo tableInfo) throws Exception{ List<T> list = new ArrayList<>(); while (rs.next()){ T resultInstance = (T)tableInfo.getResultType().newInstance(); List<FieldInfo> fieldInfos = tableInfo.getFieldInfos(); for(int i=0;i<fieldInfos.size();i++){ FieldInfo fieldInfo = fieldInfos.get(i); Field field = fieldInfo.getField(); Method method = rs.getClass().getMethod("get"+field.getType().getSimpleName(),int.class); method.setAccessible(true); Object propertyValue = method.invoke(rs,i+1); if(propertyValue!=null){ field.setAccessible(true); field.set(resultInstance,propertyValue); } } list.add(resultInstance); } return list; } private Class<T> findClass(){ Class search = this.getClass(); Type genericSuperclass = search.getGenericSuperclass(); if (genericSuperclass instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; if(parameterizedType.getActualTypeArguments().length!=1){ throw new RuntimeException(this.getClass()+" getGenericSuperclass length is not 1"); } Type targetClass = parameterizedType.getActualTypeArguments()[0]; if(targetClass instanceof Class){ return (Class)targetClass; } } return null; } public static Map<Class, TableInfo> getTableInfoMap() { return tableInfoMap; } } <file_sep>package cglib; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.cglib.core.SpringNamingPolicy; import org.springframework.cglib.proxy.Enhancer; import org.springframework.util.ReflectionUtils; import java.lang.reflect.Field; /** * @Author: yyl * @Date: 2019/1/16 17:36 */ public class MyTest3 { /** * cglib动态生成属性测试 * @param args */ public static void main(String[] args) throws Exception{ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setInterfaces(new Class<?>[] {BeanFactoryAware.class}); enhancer.setUseFactory(false); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); //设置回调器,这个回调器,这个拦截方法不能直接调用被代理的方法 enhancer.setCallback(new DaoProxyBeanFactoryAware()); //设置BeanFactoryAware生成器,可以看到这里指定了生成的属性名为$$beanFactory enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(BeanFactoryAware.class.getClassLoader())); //设置代理接口 enhancer.setInterfaces(new Class[]{BeanFactoryAware.class}); Dao dao = (Dao)enhancer.create(); if(dao instanceof BeanFactoryAware){ ((BeanFactoryAware) dao).setBeanFactory(new DefaultListableBeanFactory()); } //调用BeanFactoryFactoryAware接口的setBeanFactory方法时,会在父类生成属性$$beanFactory Field field = ReflectionUtils.findField(dao.getClass(),"$$beanFactory"); System.out.println(field.get(dao)); } } <file_sep>package mydao; import lombok.Data; /** * @author yang.yonglian * @version 1.0.0 * @Description TODO * @createTime 2020-09-18 */ @TableName("grade") @Data public class Grade { @TableField("student_id") private String studentId; @TableField private String name; } <file_sep>package redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.ResourceBundle; /** * @Classname JedisUtil * @Description TODO * @Date 2019/3/10 16:26 * @Created by wuhaitao */ public class JedisUtil { private static JedisPool jedisPool = null; static { //使用ResourceBundle类读取配置文件 ResourceBundle resourceBundle = ResourceBundle.getBundle("jedis"); //拿到数据信息 String host = resourceBundle.getString("jedis.host"); int port = Integer.parseInt(resourceBundle.getString("jedis.port")); int maxTotal = Integer.parseInt(resourceBundle.getString("jedis.maxTotal")); int maxIdle = Integer.parseInt(resourceBundle.getString("jedis.maxIdle")); //设置配置信息 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxTotal(maxTotal); //初始化 jedisPool = new JedisPool(jedisPoolConfig, host, port); } //获取redis操作对象 public static Jedis getJedis() { return jedisPool.getResource(); } }<file_sep>package classloader; /** * @Author: yyl * @Date: 2018/9/21 17:00 */ public class MyTest1 { public static void main(String[] args){ System.out.println(System.getProperty("sun.boot.class.path")); } public void test2(){ System.out.println("hello world"); } }
20c15dc928daae82b5220eecc3fdb70593e54efb
[ "Java", "Maven POM" ]
34
Java
yylstudy/otherknowledge
15dbe0df249db37806746e20ed5b53b97ec91f18
263995b4eb35f3dcbc0f1404f2848e17b20f83d4
refs/heads/master
<repo_name>AlexGeControl/Auto-Car-01-Vision-02-Traffic-Sign-Classification<file_sep>/traffic_sign_classification/preprocessors/preprocess.py # Set up session: import numpy as np import cv2 # Sklearn transformer interface: from sklearn.base import TransformerMixin class Preprocessor(TransformerMixin): """ Traffic sign classification image preprocessing """ def __init__( self, grayscale = False ): self.grayscale = grayscale def transform(self, X): """ """ return np.array( [self._transform(x) for x in X] ) def fit(self, X, y=None): return self def set_params(self, **kwargs): self.__dict__.update(kwargs) def _transform(self, X): """ Convert image to YUV color space, then equalize its histogram: """ # Parse image dimensions: H, W, C = X.shape # Convert to YUV: YUV = cv2.cvtColor(X, cv2.COLOR_RGB2YUV) # Extract Y channel and equalize its histogram: Y = cv2.split(YUV)[0] return cv2.equalizeHist(Y).reshape((H, W, 1)) <file_sep>/traffic_sign_classification/utils/visualization/visualize.py import numpy as np import matplotlib.pyplot as plt def draw_image_mosaic(images, size): """ Draw image mosaic consists of given image samples """ # Initialize canvas: plt.figure(figsize=(size,size)) # Turn off axes: plt.gca().set_axis_off() N = len(images) image_mosaic = np.vstack( [np.hstack(images[np.random.choice(N, size)]) for _ in range(size)] ) if image_mosaic.shape[-1] == 1: H, W, _ = image_mosaic.shape image_mosaic.reshape((H, W)) image_mosaic = np.dstack( tuple([image_mosaic] * 3) ) plt.imshow(image_mosaic) plt.show() def draw_label_distributions(class_counts, num_classes): """ Visualize label distributions by subsets """ # Parse label counts: class_counts = class_counts / np.sum(class_counts, axis = 1, keepdims=True) (counts_train, counts_valid, counts_test) = class_counts classes = np.arange(num_classes) width = 0.30 fig, ax = plt.subplots(figsize=(16,9)) legend_train = ax.bar( classes - 1.5*width, counts_train, width, color='r' ) legend_valid = ax.bar( classes - 0.5*width, counts_valid, width, color='g' ) legend_test = ax.bar( classes + 0.5*width, counts_test, width, color='b' ) # add some text for labels, title and axes ticks ax.set_ylabel('Percentange') ax.set_title('Percentage by Subset') ax.set_xticks(classes) ax.legend( (legend_train[0], legend_valid[0], legend_test[0]), ('Train', 'Dev', 'Test') ) plt.show() def draw_top_k(image, labels, probs): """ Visualize top K predictions """ fig, axes = plt.subplots(1, 2) # Parse data: N = len(labels) label_pos = np.arange(N) # Top K predictions: axes[0].barh( label_pos, probs, color='green' ) axes[0].set_yticks(label_pos) axes[0].set_yticklabels(labels) axes[0].invert_yaxis() # labels read top-to-bottom axes[0].set_xlabel('Probability') axes[0].set_title("Top {}".format(N)) # Input image: axes[1].imshow(image) axes[1].set_axis_off() axes[1].set_title("Web Image") plt.show() <file_sep>/traffic_sign_classification/utils/dataset/__init__.py __author__ = '<NAME>, <EMAIL>' # Configuration file: from .dataset import Dataset <file_sep>/README.md # README ### Technical Report for Traffic Sign Classification using CNN --- **Build a Traffic Sign Recognition Project** The goals of this project are the following: * Load the German [Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset) * Explore, summarize and visualize the data set * Design, train and test a model architecture * Use the model to make predictions on new images * Analyze the softmax probabilities of the new images * Summarize the results with a written report --- ### Data Set Summary & Exploration #### 1. Provide a basic summary of the data set. * The size of training set is **34799(67.13%)** * The size of the validation set is **4410(8.51%)** * The size of test set is **12630(24.36%)** * The shape of a traffic sign image is **(32, 32, 3)** * The number of unique classes/labels in the data set is **43** #### 2. Include an exploratory visualization of the dataset. Here are my exploratory visualization of the data set. First is the image mosaicing consisting of 16*16 random samples from training dataset. <img src="writeup_images/01-exploratory-visualization-a-image-sample-mosaicing.png" width="100%" alt="Image Sample Mosaicing" /> From this figure we know that **there is a significant variance between different samples in lightness**. It is a good hint that **normalization steps such as histogram equalization and per image standardization are needed for image pre-processing** Next comes the label histogram by subsets(training/validation/test). Here I follow Andrew Ng's notation and call validation set as dev set. <img src="writeup_images/01-exploratory-visualization-b-label-distribution-by-subset.png" width="100%" alt="Label Distribution by Subset" /> From the above visualization we know that the three subsets have approximately the same distribution. It indicates that the three sets could be directly used for network building and evaluation. --- ### Design and Test a Model Architecture --- #### 1. Describe how you preprocessed the image data. What techniques were chosen and why did you choose these techniques? Consider including images showing the output of each preprocessing technique. My whole pre-processing procedure goes as follows: 1. Convert image to YUV color space 2. Extract Y-channel component and equalize its histogram 3. Generate random images by applying Euclidean transform to training set images The first two steps are implemented as a sklearn Transformer which is included in [traffic_sign_classification.preprocessors.Preprocessor]('traffic_sign_classification/preprocessors/preprocess.py') The code snippet is as follows: ```python class Preprocessor(TransformerMixin): """ Traffic sign classification image preprocessing """ def __init__( self, grayscale = False ): self.grayscale = grayscale def transform(self, X): """ """ return np.array( [self._transform(x) for x in X] ) def fit(self, X, y=None): return self def set_params(self, **kwargs): self.__dict__.update(kwargs) def _transform(self, X): """ Convert image to YUV color space, then equalize its histogram: """ # Parse image dimensions: H, W, C = X.shape # Convert to YUV: YUV = cv2.cvtColor(X, cv2.COLOR_RGB2YUV) # Extract Y channel and equalize its histogram: Y = cv2.split(YUV)[0] return cv2.equalizeHist(Y).reshape((H, W, 1)) ``` The normalized images are as follows: <img src="writeup_images/02-preprocessing-a-image-normalization.png" width="100%" alt="Normalized Images" /> I choose to use grayscale only, since I think what matters for traffic sign recognition is only the shape of the symbol on the image. The random image generator comes from Keras. Below is the code snippet: ```python from keras.preprocessing.image import ImageDataGenerator image_data_generator = ImageDataGenerator( width_shift_range = 0.25, height_shift_range = 0.25, zoom_range = 0.25, fill_mode='nearest' ) ``` I generate random data, because at the first iteration, the network attained zero-loss after about 10000 iterations. However, it could only achieve 92% accuracy on validation set. Since the network show no signs of overfitting, this indicates the network suffers from the lack of training data and random samples should be generated to boost the network's performance. Here only translation and scaling transforms are used. I think they are the only reasonable transforms to apply considering the scene in which the data is generated. #### 2. Describe what your final model architecture looks like including model type, layers, layer sizes, connectivity, etc. Consider including a diagram and/or table describing the final model. Below is the architectural view from Tensorboard. It's slight modification of LeNet-5, with increased depth for conv layer and widened fully connected layers. <img src="writeup_images/03-model-architecture.png" width="100%" alt="Network Architecture" /> Here is the table for detailed parameters of the network: | Layer | Description | |:------------:|:----------------------------------------------------------------:| | input | placeholders for input features, labels and dropout control | | standardize | per image standardization | | conv1 | kernel: 5x5x32, stride: 1x1, padding: 'SAME', activation: 'ReLU' | | pool1 | max pooling, kernel: 2x2, stride: 2x2 | | conv2 | kernel: 5x5x64, stride: 1x1, padding: 'SAME', activation: 'ReLU'| | pool2 | max pooling, kernel: 2x2, stride: 2x2 | | flattened | fully connected layer input | | fc1 | x1024, activation: 'ReLU' | | fc2 | 1024x512, activation: 'ReLU' | | dropout | keep prob: 0.50 | | logits | 512x43, activation: 'ReLU' | #### 3. Describe how you trained your model. The discussion can include the type of optimizer, the batch size, number of epochs and any hyperparameters such as learning rate. The configuration for network training is as follows: 1. Optimizer: Adams. Adams always performs better! 2. Learning Rate: piecewise constant learning rate scheduling is used: ```python BOUNDARIES = [ 20000, 40000, 60000 ] LEARNING_RATES = [ 1e-3, 1e-4, 1e-5, 1e-6 ] learning_rate = tf.train.piecewise_constant( global_step, BOUNDARIES, LEARNING_RATES ) ``` 3. Batch Size: 512 4. Checkpoint Step: 2000 5. Max Iterations: 80000 #### 4. Describe the approach taken for finding a solution and getting the validation set accuracy to be at least 0.93. Include in the discussion the results on the training, validation and test sets and where in the code these were calculated. My final model results were: * training set accuracy of 100.00% * validation set accuracy of 98.03% * test set accuracy of 96.10% The code snippet for performance evaluation is as follows: ```python X_test_transformed = preprocessor.transform(X_test) with tf.Session() as sess: saver.restore(sess, conf.model_checkpoints.format("final")) # Training set: NUM_BATCHES = int(np.ceil(M_SAMPLES / BATCH_SIZE)) train_accuracy = 0.0 for batch in range(NUM_BATCHES): X_train_transformed_batch = X_train_transformed[batch*BATCH_SIZE: (batch + 1)*BATCH_SIZE] y_train_batch = y_train[batch*BATCH_SIZE: (batch + 1)*BATCH_SIZE] train_accuracy_batch = accuracy.eval( feed_dict = { X: X_train_transformed_batch, y: y_train_batch, is_training: False } ) train_accuracy += len(X_train_transformed_batch) * train_accuracy_batch train_accuracy /= M_SAMPLES # Valid set: valid_accuracy = accuracy.eval( feed_dict = { X: X_valid_transformed, y: y_valid, is_training: False } ) # Test set: test_accuracy = accuracy.eval( feed_dict = { X: X_test_transformed, y: y_test, is_training: False } ) print("[Train Accuracy]: {:3.2f}".format(100*train_accuracy)) print("[Valid Accuracy]: {:3.2f}".format(100*valid_accuracy)) print("[Test Accuracy]: {:3.2f}".format(100*test_accuracy)) ``` Here the training set is evaluated using a batch-by-batch approach to avoid memory error. I use an iterative approach to reach the above final result: 1. In the first iteration, I used the above network without dropout and learning rate scheduling and attained 0.00 loss on training and 92% accuracy on validation set after about 10,000 iterations. There is no sign of overfitting (consistent performance on training & validation set) so I think this bottleneck is caused by the network's hunger for training data So I use image generator from Keras to generate more training data for network. 2. In the second iteration, I increased max iteration to 60,000 and included learning rate scheduling for further optimization. Besides, dropout layer is added before softmax output layer so as to boost the generalization ability of the network. The final model is slightly overfitted, in that there is a gap betweeen training set performance and that of validation set. The results also indicates that there might be a discrepancy between training & testing set distribution since the model's performance on validation set is consistently superior than that of testing set. However, since the model has already attained a similar performance with human being, which is a good proxy of Bayesian error And, I don't have the patience to further fine tune the model :) I choose this model as my final model for traffic sign classifier. --- ### Test a Model on New Images --- #### 1. Choose five German traffic signs found on the web and provide them in the report. For each image, discuss what quality or qualities might be difficult to classify. Here are five German traffic signs that I found on the web: <img src="writeup_images/04-web-images.png" width="100%" alt="More Traffic Signs from Web" /> I think the first four images will be easy to classify while the last will be difficult since it contains two stacked traffic signs. #### 2. Discuss the model's predictions on these new traffic signs and compare the results to predicting on the test set. At a minimum, discuss what the predictions were, the accuracy on these new predictions, and compare the accuracy to the accuracy on the test set. Here are the results of the prediction: | Image | Prediction | |:-----------------------:|:---------------------------------:| | 01-Stop | Stop | | 02-Speed-Limit-100 km/h | Speed limit (30km/h) | | 03-Yield | Yield | | 04-General-Caution | General caution | | 05-Pedestrians | Speed limit (70km/h) | The model was able to correctly guess 4 of the 5 traffic signs, which gives an accuracy of 80%. Although this is not as good as its performance on test dataset(96%), I think this is really a decent performance since the fifth model is significant different than that of training set. The pedestrians sign has triangle borders inside the training set while this one has round border. #### 3. Describe how certain the model is when predicting on each of the five new images by looking at the softmax probabilities for each prediction. Provide the top 5 softmax probabilities for each image along with the sign type of each probability. Below is the visualization of top-5 predictions of the above images <img src="writeup_images/05-top-5-01-stop.png" width="100%" alt="Top 5, Stop" /> <img src="writeup_images/05-top-5-02-speed-limit-30.png" width="100%" alt="Top 5, Speed Limit 30" /> <img src="writeup_images/05-top-5-03-yield.png" width="100%" alt="Top 5, Yield" /> <img src="writeup_images/05-top-5-04-general-caution.png" width="100%" alt="Top 5, General Caution" /> <img src="writeup_images/05-top-5-05-pedestrians.png" width="100%" alt="Top 5, Pedestrians" /> From the fifth visualization we know that the round border has been learned as a feature for speed limit sign prediction. It is the round border that caused the false prediction of the fifth image. <file_sep>/traffic_sign_classification/utils/dataset/dataset.py # Set up session: import pickle import numpy as np import pandas as pd class Dataset: def __init__( self, train_pickle, valid_pickle, test_pickle, label_encoding ): # Load dataset: with open(train_pickle, mode='rb') as f: self.train = pickle.load(f) with open(valid_pickle, mode='rb') as f: self.valid = pickle.load(f) with open(test_pickle, mode='rb') as f: self.test = pickle.load(f) # Load label encoding: self.label_encoding = pd.read_csv(label_encoding) # Dataset dimensions: (_, H, W, C) = self.train["features"].shape self.IMAGE_SIZE = (H, W, C) self.N_CLASSES = len(self.label_encoding) def get_label_name( self, labels ): """ Get label names: """ return self.label_encoding.ix[labels, 'SignName'].values def __str__(self): M_TRAIN = self.train["features"].shape[0] M_VALID = self.valid["features"].shape[0] M_TEST = self.test["features"].shape[0] SIZES = np.array([M_TRAIN, M_VALID, M_TEST]) feature_size_summary = "Number of training/validation/testing examples = {}".format( repr(tuple(SIZES)) ) percentange = 100.0 * SIZES / SIZES.sum() feature_percentange_summary = "Training/validation/testing percentange sizes = ({:2.2f}, {:2.2f}, {:2.2f})".format( percentange[0], percentange[1], percentange[2] ) feature_sample_summary = "Image data shape = {}".format( repr( self.IMAGE_SIZE ) ) label_summary = "Number of classes = {}".format(self.N_CLASSES) return "{}\n{}\n{}\n{}\n".format( feature_size_summary, feature_percentange_summary, feature_sample_summary, label_summary )
acaba5733f93a7e50e9255d5866fcce3b7979090
[ "Markdown", "Python" ]
5
Python
AlexGeControl/Auto-Car-01-Vision-02-Traffic-Sign-Classification
a16ab1206f4e26bf76326061ed2c777ffd8c0aed
691ea4d5b5fe6ad867c15f93f9258dc39b9ce414
refs/heads/master
<repo_name>Neuro17/my-exams<file_sep>/lib/config/passport.js 'use strict'; var mongoose = require('mongoose'), User = mongoose.model('User'), passport = require('passport'), LocalStrategy = require('passport-local').Strategy, GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var configAuth = require('./auth'); /** * Passport configuration */ passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { User.findOne({ _id: id }, '-salt -hashedPassword', function(err, user) { // don't ever give out the password or salt done(err, user); }); }); // add other strategies for more authentication flexibility passport.use(new LocalStrategy({ usernameField: 'email', passwordField: '<PASSWORD>' // this is the virtual field on the model }, function(email, password, done) { User.findOne({ email: email.toLowerCase() }, function(err, user) { if (err) return done(err); if (!user) { return done(null, false, { message: 'This email is not registered.' }); } if (!user.authenticate(password)) { return done(null, false, { message: 'This password is not correct.' }); } return done(null, user); }); } )); passport.use(new GoogleStrategy({ clientID : configAuth.googleAuth.clientID, clientSecret : configAuth.googleAuth.clientSecret, callbackURL : configAuth.googleAuth.callbackURL, passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not) }, function(req, token, refreshToken, profile, done) { // asynchronous process.nextTick(function() { // check if the user is already logged in if (!req.user) { User.findOne({ 'google.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { // if there is a user id already but no token (user was linked at one point and then removed) if (!user.google.token) { user.google.token = token; user.google.name = profile.displayName; user.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email user.save(function(err) { if (err) throw err; return done(null, user); }); } return done(null, user); } else { console.log(profile.name.given_name); var newUser = new User({ "google.id" : profile.id, "google.token" : token, "first_name" : profile.name.givenName, "last_name" : profile.name.familyName, "email" : (profile.emails[0].value || '').toLowerCase(),// pull the first email "provider" : "google" }); /*newUser.google.id = profile.id; newUser.google.token = token; newUser.first_name = profile.given_name; New newUser.email = (profile.emails[0].value || '').toLowerCase();// pull the first email newUser.provider = "google"*/ newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); } else { // user already exists and is logged in, we have to link accounts var user = req.user; // pull the user out of the session user.google.id = profile.id; user.google.token = token; user.google.name = profile.displayName; user.google.email = (profile.emails[0].value || '').toLowerCase(); // pull the first email user.save(function(err) { if (err) throw err; return done(null, user); }); } }); })); module.exports = passport; <file_sep>/app/scripts/controllers/main.js 'use strict'; angular.module('myExamsApp').controller('MainCtrl', function MainCtrl($scope, $rootScope, MainFactory) { /* Vecchio modo. - le richieste http non vanno fatte qui ma nel Factory */ /*$http.get('/api/awesomeThings').success(function(awesomeThings) { $scope.awesomeThings = awesomeThings; });*/ /* prova usando restangular e rilegando tutta la logica al Factory, in modo che il controller il servizio possa essere riutilizzato tra diversi controller se necessario */ MainFactory.getAwesomeThings() .then(function() { $scope.awesomeThings = MainFactory.awesomeThings; }); //MainFactory.getMe(); }); <file_sep>/app/scripts/services/googleAuth.js 'use strict'; angular.module('myExamsApp') .factory('GoogleAuth', function ($resource) { return $resource('/auth/google'); });<file_sep>/app/scripts/services/main.js 'use strict'; angular.module('myExamsApp').factory('MainFactory', function MainFactory($location, Restangular) { MainFactory.awesomeThings = []; MainFactory.getAwesomeThings = function() { return Restangular.all('awesomeThings').getList() .then(function(awesomeThings) { MainFactory.awesomeThings = awesomeThings; }) } // esempio di funzionalità di restangular... andrà cancellato MainFactory.getMe = function() { return Restangular.one('users','me').get() .then(function(me) { MainFactory.me = me; console.log(MainFactory.me); }); } return MainFactory; }) <file_sep>/README.md my-exams ======== <file_sep>/app/scripts/services/settings.js 'use strict'; angular.module('myExamsApp').factory('SettingsFactory', function SettingsFactory($location, Restangular){ // TO-DO SettingsFactory.getMe = function() { return Restangular.all('users').one('me').get() .then(function(me) { console.log(me); me.username = 'Neuro'; me.put(); }) } return SettingsFactory; })
ea9e191472fb350ea122c050f40bd2f26457cb5c
[ "JavaScript", "Markdown" ]
6
JavaScript
Neuro17/my-exams
b44cad37d782ae9fd6ce20854ed94bac95192381
90258a8168827240cf75b478b6dfc6dd6dd6d0c8
refs/heads/main
<repo_name>knocklabs/knock-php<file_sep>/src/Api/Messages.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Messages extends AbstractApi { /** * @param array $params * @param array $headers * @return array * @throws Exception */ public function list(array $params = [], array $headers = []): array { if (array_key_exists('trigger_data', $params)) { $params['trigger_data'] = json_encode($params['trigger_data']); } $url = $this->url('/messages'); return $this->getRequest($url, $params, $headers); } /** * @param string $messageId * @param array $headers * @return array * @throws Exception */ public function get(string $messageId, array $headers = []): array { $url = $this->url('/messages/%s', $messageId); return $this->getRequest($url, [], $headers); } /** * @param string $messageId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getActivities(string $messageId, array $params = [], array $headers = []): array { if (array_key_exists('trigger_data', $params)) { $params['trigger_data'] = json_encode($params['trigger_data']); } $url = $this->url('/messages/%s/activities', $messageId); return $this->getRequest($url, $params, $headers); } /** * @param string $messageId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getEvents(string $messageId, array $params = [], array $headers = []): array { $url = $this->url('/messages/%s/events', $messageId); return $this->getRequest($url, $params, $headers); } /** * @param string $messageId * @param array $headers * @return array * @throws Exception */ public function getContent(string $messageId, array $headers = []): array { $url = $this->url('/messages/%s/content', $messageId); return $this->getRequest($url, [], $headers); } /** * @param string $messageId * @param string $status * @param array $headers * @return array * @throws Exception */ public function updateStatus(string $messageId, string $status, array $headers = []): array { $url = $this->url('/messages/%s/%s', $messageId, $status); return $this->putRequest($url, [], $headers); } /** * @param string $messageId * @param string $status * @param array $headers * @return array * @throws Exception */ public function undoStatus(string $messageId, string $status, array $headers = []): array { $url = $this->url('/messages/%s/%s', $messageId, $status); return $this->deleteRequest($url, [], $headers); } /** * @param string $status * @param array $messageIds * @param array $headers * @return array * @throws Exception */ public function batchChangeStatus(string $status, array $messageIds, array $headers = []): array { $url = $this->url('/messages/batch/%s', $status); return $this->postRequest($url, ['message_ids' => $messageIds], $headers); } /** * @param string $channel * @param string $status * @param array $body * @param array $headers * @return array * @throws Exception */ public function bulkUpdateChannelStatus(string $channel, string $status, array $body, array $headers = []): array { $url = $this->url('/channels/%s/messages/bulk/%s', $channel, $status); return $this->postRequest($url, $body, $headers); } } <file_sep>/src/Exception/ValidationFailedException.php <?php namespace Knock\KnockSdk\Exception; class ValidationFailedException extends ClientErrorException { } <file_sep>/src/HttpClient/Plugins/ExceptionThrower.php <?php namespace Knock\KnockSdk\HttpClient\Plugins; use Http\Client\Common\Plugin; use Http\Promise\Promise; use Knock\KnockSdk\Exception\ClientErrorException; use Knock\KnockSdk\Exception\ExceptionInterface; use Knock\KnockSdk\Exception\NotFoundException; use Knock\KnockSdk\Exception\RuntimeException; use Knock\KnockSdk\Exception\ServerErrorException; use Knock\KnockSdk\Exception\UnauthorizedException; use Knock\KnockSdk\Exception\ValidationFailedException; use Knock\KnockSdk\HttpClient\Message\ResponseMediator; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; class ExceptionThrower implements Plugin { /** * Handle the request and return the response coming from the next callable. * * @param RequestInterface $request * @param callable $next * @param callable $first * * @return Promise * @throws ExceptionInterface */ public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise { return $next($request)->then(function (ResponseInterface $response): ResponseInterface { $status = $response->getStatusCode(); if (400 <= $status && 600 > $status) { throw self::createException($status, ResponseMediator::getErrorMessage($response) ?? $response->getReasonPhrase()); } return $response; }); } /** * Create an exception from a status code and error message. * * @param int $status * @param string $message * * @return ExceptionInterface */ protected static function createException(int $status, string $message): ExceptionInterface { if (401 === $status) { return new UnauthorizedException($message, $status); } if (404 === $status) { return new NotFoundException($message, $status); } if (422 === $status) { return new ValidationFailedException($message, $status); } if (400 <= $status && 499 >= $status) { return new ClientErrorException($message, $status); } if (500 <= $status && 599 >= $status) { return new ServerErrorException($message, $status); } return new RuntimeException($message, $status); } } <file_sep>/src/HttpClient/Utils/JsonArray.php <?php namespace Knock\KnockSdk\HttpClient\Utils; use function json_decode; use function json_encode; use const JSON_ERROR_NONE; use function json_last_error; use function json_last_error_msg; use Knock\KnockSdk\Exception\RuntimeException; use function sprintf; final class JsonArray { /** * Decode a JSON string into a PHP array. * * @param string $json * * @return array * @throws RuntimeException * */ public static function decode(string $json): array { /** @var scalar|array|null */ $data = json_decode($json, true); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException(sprintf('json_decode error: %s', json_last_error_msg())); } if (! \is_array($data)) { throw new RuntimeException(sprintf('json_decode error: Expected JSON of type array, %s given.', \get_debug_type($data))); } return $data; } /** * Encode a PHP array into a JSON string. * * @param array $value * * @return string * @throws RuntimeException * */ public static function encode(array $value): string { $json = json_encode($value); if (JSON_ERROR_NONE !== json_last_error()) { throw new RuntimeException(sprintf('json_encode error: %s', json_last_error_msg())); } /** @var string */ return $json; } } <file_sep>/src/HttpClient/Plugins/Authentication.php <?php namespace Knock\KnockSdk\HttpClient\Plugins; use Http\Client\Common\Plugin; use Http\Promise\Promise; use Psr\Http\Message\RequestInterface; class Authentication implements Plugin { protected string $token; /** * @param string $token * * @return void */ public function __construct(string $token) { $this->token = $token; } /** * Handle the request and return the response coming from the next callable. * * @param RequestInterface $request * @param callable $next * @param callable $first * * @return Promise */ public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise { $request = $request->withHeader('Authorization', sprintf('Bearer %s', $this->token)); return $next($request); } } <file_sep>/src/Exception/NotFoundException.php <?php namespace Knock\KnockSdk\Exception; class NotFoundException extends ClientErrorException { } <file_sep>/src/Exception/ErrorException.php <?php namespace Knock\KnockSdk\Exception; use ErrorException as BaseErrorException; class ErrorException extends BaseErrorException implements ExceptionInterface { } <file_sep>/src/Exception/ClientErrorException.php <?php namespace Knock\KnockSdk\Exception; class ClientErrorException extends ErrorException { } <file_sep>/src/Api/Users.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Users extends AbstractApi { /** * @param string $userId * @param array $body * @param array $headers * @return array * @throws Exception */ public function identify(string $userId, array $body = [], array $headers = []): array { $url = $this->url('/users/%s', $userId); return $this->putRequest($url, $body, $headers); } /** * @param array $params * @param array $headers * @return array * @throws Exception */ public function list(array $params = [], array $headers = []): array { $url = $this->url('/users'); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $params * @param array $headers * @return array * @throws Exception */ public function get(string $userId, array $params = [], array $headers = []): array { $url = $this->url('/users/%s', $userId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getMessages(string $userId, array $params = [], array $headers = []): array { if (array_key_exists('trigger_data', $params)) { $params['trigger_data'] = json_encode($params['trigger_data']); } $url = $this->url('/users/%s/messages', $userId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getSchedules(string $userId, array $params = [], array $headers = []): array { $url = $this->url('/users/%s/schedules', $userId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getSubscriptions(string $userId, array $params = [], array $headers = []): array { $url = $this->url('/users/%s/subscriptions', $userId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $body * @param array $headers * @return array|string * @throws Exception */ public function delete(string $userId, array $body = [], array $headers = []) { $url = $this->url('/users/%s', $userId); return $this->deleteRequest($url, $body, $headers); } /** * @param string $toUserId * @param string $fromUserId * @param array $headers * @return array * @throws Exception */ public function merge(string $toUserId, string $fromUserId, array $headers = []): array { $url = $this->url('/users/%s/merge', $toUserId); return $this->postRequest($url, ['from_user_id' => $fromUserId], $headers); } /** * @param array $users * @param array $headers * @return array * @throws Exception */ public function bulkIdentify(array $users = [], array $headers = []): array { $url = $this->url('/users/bulk/identify'); return $this->postRequest($url, ['users' => $users], $headers); } /** * @param array $userIds * @param array $headers * @return array * @throws Exception */ public function bulkDelete(array $userIds = [], array $headers = []): array { $url = $this->url('/users/bulk/delete'); return $this->postRequest($url, ['user_ids' => $userIds], $headers); } /** * @param string $userId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getPreferences(string $userId, array $params = [], array $headers = []): array { $url = $this->url('/users/%s/preferences', $userId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param string $preferenceId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getPreference(string $userId, string $preferenceId, array $params = [], array $headers = []): array { $url = $this->url('/users/%s/preferences/%s', $userId, $preferenceId); return $this->getRequest($url, $params, $headers); } /** * @param string $userId * @param array $body * @param string $preferenceSetId * @param array $headers * @return array * @throws Exception */ public function setPreferences( string $userId, array $body = [], string $preferenceSetId = 'default', array $headers = [] ): array { $url = $this->url('/users/%s/preferences/%s', $userId, $preferenceSetId); return $this->putRequest($url, $body, $headers); } /** * @param array $body * @param array $headers * @return array * @throws Exception */ public function bulkSetPreferences(array $body, array $headers = []): array { $url = $this->url('/users/bulk/preferences'); return $this->postRequest($url, $body, $headers); } /** * @param string $userId * @param string $channelId * @param array $headers * @return array * @throws Exception */ public function getChannelData(string $userId, string $channelId, array $headers = []): array { $url = $this->url('/users/%s/channel_data/%s', $userId, $channelId); return $this->getRequest($url, [], $headers); } /** * @param string $userId * @param string $channelId * @param array $body * @param array $headers * @return array * @throws Exception */ public function setChannelData(string $userId, string $channelId, array $body, array $headers = []): array { $body = ['data' => $body]; $url = $this->url('/users/%s/channel_data/%s', $userId, $channelId); return $this->putRequest($url, $body, $headers); } /** * @param string $userId * @param string $channelId * @param array $headers * @return array|string * @throws Exception */ public function unsetChannelData(string $userId, string $channelId, array $headers = []) { $url = $this->url('/users/%s/channel_data/%s', $userId, $channelId); return $this->deleteRequest($url, [], $headers); } } <file_sep>/tests/Unit/ClientTest.php <?php namespace Tests\Unit; use Knock\KnockSdk\Api\BulkOperations; use Knock\KnockSdk\Api\Feeds; use Knock\KnockSdk\Api\Messages; use Knock\KnockSdk\Api\Objects; use Knock\KnockSdk\Api\Users; use Knock\KnockSdk\Api\Workflows; use Tests\TestCase; class ClientTest extends TestCase { /** * @test * @dataProvider provider */ public function will_return_provided_class_names($methodName, $className) { $this->assertInstanceOf($className, $this->client->$methodName()); } public function provider(): array { return [ ['bulkOperations', BulkOperations::class], ['feeds', Feeds::class], ['messages', Messages::class], ['objects', Objects::class], ['users', Users::class], ['workflows', Workflows::class], ]; } } <file_sep>/tests/Unit/HttpClient/Utils/QueryStringBuilderTest.php <?php namespace Tests\Unit\HttpClient\Utils; use Knock\KnockSdk\HttpClient\Utils\QueryStringBuilder; use PHPUnit\Framework\TestCase; use function sprintf; class QueryStringBuilderTest extends TestCase { /** * @dataProvider queryStringProvider * * @param array $query * @param string $expected */ public function testBuild(array $query, string $expected): void { $this->assertSame(sprintf('?%s', $expected), QueryStringBuilder::build($query)); } public function queryStringProvider() { yield 'key value pairs' => [ [ 'per_page' => 30, ], 'per_page=30', ]; } } <file_sep>/tests/Unit/Api/ApiTest.php <?php namespace Tests\Unit\Api; use function array_merge; use Knock\KnockSdk\Client; use Knock\KnockSdk\HttpClient\Builder; use PHPUnit\Framework\MockObject\MockObject; use Psr\Http\Client\ClientInterface; use Tests\TestCase; abstract class ApiTest extends TestCase { /** * @return string */ abstract protected function getApiClass(): string; protected function getApiMock(array $methods = []): MockObject { $httpClient = $this->getMockBuilder(ClientInterface::class) ->onlyMethods(['sendRequest']) ->getMock(); $httpClient ->expects($this->any()) ->method('sendRequest'); $builder = new Builder($httpClient); $client = new Client('xxx', $builder); return $this->getMockBuilder($this->getApiClass()) ->onlyMethods(array_merge(['getRequest', 'postRequest', 'deleteRequest', 'putRequest'], $methods)) ->setConstructorArgs([$client]) ->getMock(); } /** * @param $path * * @return mixed */ public function getContent($path) { $content = file_get_contents($path); return json_decode($content, true); } } <file_sep>/README.md # Knock PHP library ## Documentation See the [documentation](https://docs.knock.app) for PHP usage examples. ## Installation ```bash composer require knocklabs/knock-php php-http/guzzle7-adapter ``` ## Configuration To use the library you must provide a secret API key, provided in the Knock dashboard. ```php use Knock\KnockSdk\Client; $client = new Client('sk_12345'); ``` ## Usage ### Identifying users ```php $client->users()->identify('jhammond', [ 'name' => '<NAME>', 'email' => '<EMAIL>', ]); ``` ### Sending notifies (triggering workflows) ```php $client->notify('dinosaurs-loose', [ // user id of who performed the action 'actor' => 'dnedry', // list of user ids for who should receive the notification 'recipients' => ['jhammond', 'agrant', 'imalcolm', 'esattler'], // data payload to send through 'data' => [ 'type' => 'trex', 'priority' => 1, ], // an optional identifier for the tenant that the notifications belong to 'tenant' => 'jurassic-park', // an optional key to provide to cancel a notify 'cancellation_key' => '<KEY>', ]); ``` ### Retrieving users ```php $client->users()->get('jhammond'); ``` ### Deleting users ```php $client->users()->delete('jhammond'); ``` ### Preferences ```php $client->users()->setPreferences('jhammond', [ 'channel_types' => [ 'email' => true, 'sms' => false, ], 'workflows' => [ 'dinosaurs-loose' => [ 'email' => false, 'in_app_feed': true, ] ] ]); ``` ### Getting and setting channel data ```php $knock->users()->setChannelData('jhammond', '5a88728a-3ecb-400d-ba6f-9c0956ab252f', [ 'tokens' => [ $apnsToken ], }); $knock->users()->getChannelData('jhammond', '5a88728a-3ecb-400d-ba6f-9c0956ab252f'); ``` ### Canceling workflows ```php $client->workflows()->cancel('dinosaurs-loose', [ 'cancellation_key' => '<KEY>' // optionally you can specify recipients here 'recipients' => ['jhammond'], ]); ``` ### Signing JWTs You can use the `firebase/php-jwt` package to [sign JWTs easily](https://github.com/firebase/php-jwt). You will need to generate an environment specific signing key, which you can find in the Knock dashboard. If you're using a signing token you will need to pass this to your client to perform authentication. You can read more about [client-side authentication here](https://docs.knock.app/client-integration/authenticating-users). ```php use Firebase\JWT\JWT; $privateKey = env('KNOCK_SIGNING_KEY'); $encoded = JWT::encode(['sub' => 'jhammond'], $privateKey, 'RS256'); ``` ## Test To run tests, first run `composer` in the terminal. Once compiled, you can run `phpunit tests/` to run the suite. <file_sep>/src/HttpClient/Builder.php <?php namespace Knock\KnockSdk\HttpClient; use Http\Client\Common\HttpMethodsClient; use Http\Client\Common\HttpMethodsClientInterface; use Http\Client\Common\Plugin; use Http\Client\Common\PluginClientFactory; use Http\Discovery\Psr17FactoryDiscovery; use Http\Discovery\Psr18ClientDiscovery; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; use Psr\Http\Message\StreamFactoryInterface; use Psr\Http\Message\UriFactoryInterface; class Builder { /** * @var ClientInterface */ protected ClientInterface $httpClient; /** * @var RequestFactoryInterface */ protected RequestFactoryInterface $requestFactory; /** * @var StreamFactoryInterface */ protected StreamFactoryInterface $streamFactory; /** * @var UriFactoryInterface */ protected UriFactoryInterface $uriFactory; /** * @var array */ protected $plugins = []; /** * @var HttpMethodsClientInterface|null */ protected $pluginClient; public function __construct( ClientInterface $httpClient = null, RequestFactoryInterface $requestFactory = null, StreamFactoryInterface $streamFactory = null, UriFactoryInterface $uriFactory = null ) { $this->httpClient = $httpClient ?: Psr18ClientDiscovery::find(); $this->requestFactory = $requestFactory ?? Psr17FactoryDiscovery::findRequestFactory(); $this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory(); $this->uriFactory = $uriFactory ?? Psr17FactoryDiscovery::findUriFactory(); } /** * @return HttpMethodsClientInterface */ public function getHttpClient(): HttpMethodsClientInterface { if (null === $this->pluginClient) { $plugins = $this->plugins; $this->pluginClient = new HttpMethodsClient( (new PluginClientFactory())->createClient($this->httpClient, $plugins), $this->requestFactory, $this->streamFactory ); } return $this->pluginClient; } /** * Get the request factory. * * @return RequestFactoryInterface */ public function getRequestFactory(): RequestFactoryInterface { return $this->requestFactory; } /** * Get the stream factory. * * @return StreamFactoryInterface */ public function getStreamFactory(): StreamFactoryInterface { return $this->streamFactory; } /** * Get the URI factory. * * @return UriFactoryInterface */ public function getUriFactory(): UriFactoryInterface { return $this->uriFactory; } /** * Add a new plugin to the end of the plugin chain. * * @param Plugin $plugin * * @return void */ public function addPlugin(Plugin $plugin): void { $this->plugins[] = $plugin; $this->pluginClient = null; } /** * Remove a plugin by its fully qualified class name (FQCN). * * @param string $fqcn * * @return void */ public function removePlugin(string $fqcn): void { foreach ($this->plugins as $idx => $plugin) { if ($plugin instanceof $fqcn) { unset($this->plugins[$idx]); $this->pluginClient = null; } } } } <file_sep>/src/Api/Feeds.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Feeds extends AbstractApi { /** * @param string $userId * @param string $feedId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getUserFeed(string $userId, string $feedId, array $params = [], array $headers = []): array { if (array_key_exists('trigger_data', $params)) { $params['trigger_data'] = json_encode($params['trigger_data']); } $url = $this->url('/users/%s/feeds/%s', $userId, $feedId); return $this->getRequest($url, $params, $headers); } } <file_sep>/tests/Unit/HttpClient/Message/ResponseMediatorTest.php <?php namespace Tests\Unit\HttpClient\Message; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; use Knock\KnockSdk\Exception\RuntimeException; use Knock\KnockSdk\HttpClient\Message\ResponseMediator; use PHPUnit\Framework\TestCase; class ResponseMediatorTest extends TestCase { /** @test */ public function get_content(): void { $response = new Response( 200, ['Content-Type' => 'application/json'], Utils::streamFor('{"foo": "bar"}') ); $this->assertSame(['foo' => 'bar'], ResponseMediator::getContent($response)); } /** @test */ public function get_content_not_json(): void { $response = new Response( 200, [], Utils::streamFor('foobar') ); $this->assertSame('foobar', ResponseMediator::getContent($response)); } /** @test */ public function get_content_invalid_json(): void { $response = new Response( 200, ['Content-Type' => 'application/json'], Utils::streamFor('foobar') ); $this->expectException(RuntimeException::class); $this->expectExceptionMessage('json_decode error: Syntax error'); ResponseMediator::getContent($response); } /** @test */ public function get_error_message_invalid_json(): void { $response = new Response( 200, ['Content-Type' => 'application/json'], Utils::streamFor('foobar') ); $this->assertNull(ResponseMediator::getErrorMessage($response)); } } <file_sep>/src/Client.php <?php namespace Knock\KnockSdk; use Http\Client\Common\HttpMethodsClientInterface; use Http\Client\Common\Plugin\AddHostPlugin; use Http\Client\Exception; use Knock\KnockSdk\Api\BulkOperations; use Knock\KnockSdk\Api\Feeds; use Knock\KnockSdk\Api\Messages; use Knock\KnockSdk\Api\Objects; use Knock\KnockSdk\Api\Users; use Knock\KnockSdk\Api\Workflows; use Knock\KnockSdk\HttpClient\Builder; use Knock\KnockSdk\HttpClient\Plugins\Authentication; use Knock\KnockSdk\HttpClient\Plugins\ExceptionThrower; class Client { /** * @var string */ protected string $host = 'https://api.knock.app'; /** * @var string */ protected string $prefix = '/v1'; /** * The HTTP client builder. * * @var Builder */ protected Builder $httpClientBuilder; /** * @param string $token * @param Builder|null $httpClientBuilder */ public function __construct(string $token, Builder $httpClientBuilder = null) { $this->httpClientBuilder = $builder = $httpClientBuilder ?? new Builder(); $builder->addPlugin(new ExceptionThrower()); $builder->addPlugin(new Authentication($token)); $this->setHost($this->host); } /** * @param string $url * @return void */ public function setHost(string $url): void { $uri = $this->getHttpClientBuilder()->getUriFactory()->createUri($url); $this->getHttpClientBuilder()->removePlugin(AddHostPlugin::class); $this->getHttpClientBuilder()->addPlugin(new AddHostPlugin($uri)); } /** * @param string $prefix * @return void */ public function setPrefix(string $prefix) { $this->prefix = $prefix; } /** * @return string */ public function getPrefix() { return $this->prefix; } /** * Get the HTTP client. * * @return HttpMethodsClientInterface */ public function getHttpClient(): HttpMethodsClientInterface { return $this->getHttpClientBuilder()->getHttpClient(); } /** * Get the HTTP client builder. * * @return Builder */ protected function getHttpClientBuilder(): Builder { return $this->httpClientBuilder; } /** * @return BulkOperations */ public function bulkOperations(): BulkOperations { return new BulkOperations($this); } /** * @return Feeds */ public function feeds(): Feeds { return new Feeds($this); } /** * @return Messages */ public function messages(): Messages { return new Messages($this); } /** * @return Objects */ public function objects(): Objects { return new Objects($this); } /** * @return Users */ public function users(): Users { return new Users($this); } /** * @return Workflows */ public function workflows(): Workflows { return new Workflows($this); } /** * @param string $key * @param array $body * @param array $headers * @return array * @throws Exception */ public function notify(string $key, array $body, array $headers = []): array { return $this->workflows()->trigger($key, $body, $headers); } } <file_sep>/tests/Unit/Api/ObjectsTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Objects; class ObjectsTest extends ApiTest { /** @test */ public function will_get_object() { $collection = 'projects'; $id = 'project-1'; $expected = $this->getContent(sprintf('%s/data/responses/object.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('getRequest') ->with(sprintf('/objects/%s/%s', $collection, $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->get($collection, $id)); } /** @test */ public function will_get_object_messages() { $collection = 'projects'; $id = 'project-1'; $expected = $this->getContent(sprintf('%s/data/responses/messages.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('getRequest') ->with(sprintf('/objects/%s/%s/messages', $collection, $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->getMessages($collection, $id)); } /** @test */ public function will_set_object() { $collection = 'projects'; $id = 'project-1'; $expected = $this->getContent(sprintf('%s/data/responses/object.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('putRequest') ->with(sprintf('/objects/%s/%s', $collection, $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->set($collection, $id, [])); } /** @test */ public function will_delete_object() { $collection = 'projects'; $id = 'project-1'; $expected = ''; $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('deleteRequest') ->with(sprintf('/objects/%s/%s', $collection, $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->delete($collection, $id)); } /** @test */ public function will_bulk_set_objects() { $collection = 'projects'; $objectsData = [ [ 'id' => 'project-1', 'name' => 'Project one', ], ]; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('postRequest') ->with(sprintf('/objects/%s/bulk/set', $collection)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->bulkSet($collection, $objectsData)); } /** @test */ public function will_bulk_delete_objects() { $collection = 'projects'; $objectIds = [ 'project-1', 'project-2', ]; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('postRequest') ->with(sprintf('/objects/%s/bulk/delete', $collection)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->bulkDelete($collection, $objectIds)); } /** @test */ public function will_get_object_preferences() { $collection = 'projects'; $objectId = 'project-1'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('getRequest') ->with(sprintf('/objects/%s/%s/preferences', $collection, $objectId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->getPreferences($collection, $objectId)); } /** @test */ public function will_get_object_preference() { $collection = 'projects'; $objectId = 'project-1'; $preferenceId = '5c53b316-91f7-454f-ab27-66d111282685'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('getRequest') ->with(sprintf('/objects/%s/%s/preferences/%s', $collection, $objectId, $preferenceId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->getPreference($collection, $objectId, $preferenceId)); } /** @test */ public function will_set_object_preference() { $collection = 'projects'; $objectId = 'project-1'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('putRequest') ->with(sprintf('/objects/%s/%s/preferences/%s', $collection, $objectId, 'default')) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->setPreferences($collection, $objectId, [])); } /** @test */ public function will_get_object_channel_data() { $collection = 'projects'; $objectId = 'project-1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = $this->getContent(sprintf('%s/data/responses/channel-data.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('getRequest') ->with(sprintf('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->getChannelData($collection, $objectId, $channelId)); } /** @test */ public function will_set_object_channel_data() { $collection = 'projects'; $objectId = 'project-1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = $this->getContent(sprintf('%s/data/responses/channel-data.json', __DIR__)); $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('putRequest') ->with(sprintf('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->setChannelData($collection, $objectId, $channelId, [])); } /** @test */ public function will_unset_object_channel_data() { $collection = 'projects'; $objectId = 'project-1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = ''; $objects = $this->getApiMock(); $objects->expects($this->once()) ->method('deleteRequest') ->with(sprintf('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $objects->unsetChannelData($collection, $objectId, $channelId)); } protected function getApiClass(): string { return Objects::class; } } <file_sep>/src/Api/Tenants.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Tenants extends AbstractApi { /** * @param array $params * @param array $headers * @return array * @throws Exception */ public function list(array $params = [], array $headers = []): array { $url = $this->url('/tenants'); return $this->getRequest($url, $params, $headers); } /** * @param string $tenantId * @param array $headers * @return array * @throws Exception */ public function get(string $tenantId, array $headers = []): array { $url = $this->url('/tenants/%s', $tenantId); return $this->getRequest($url, [], $headers); } /** * @param string $tenantId * @param array $body * @param array $headers * @return array * @throws Exception */ public function set(string $tenantId, array $body, array $headers = []): array { $url = $this->url('/tenants/%s', $tenantId); return $this->putRequest($url, $body, $headers); } /** * @param string $tenantId * @param array $headers * @return array|string * @throws Exception */ public function delete(string $tenantId, array $headers = []) { $url = $this->url('/tenants/%s', $tenantId); return $this->deleteRequest($url, [], $headers); } } <file_sep>/CONTRIBUTING.md # Contributing ## Getting Started 1. Install [asdf](https://asdf-vm.com) 2. Install the asdf PHP plugin ```bash asdf plugin add php https://github.com/asdf-community/asdf-php.git # Visit that repository to see installation prerequisites ``` 3. Run `asdf install` to install the version of PHP specified in the [.tool-versions](.tool-versions) file 4. Run `composer install` to install dependencies Note that installing PHP via ASDF requires a number of dependencies. Instructions are in the [asdf-php plugin](https://github.com/asdf-community/asdf-php.git) repository. The instructions steps may fail, and are highly sensitive to your local environment. If you are having difficulty running tests or other functions, you can alternatively commit and push to a branch and let GitHub Actions run the tests & formatting for you. Future improvements to this repository could include using Docker to encapsulate the environment and dependencies for running tests & other tools. ## Running tests `./vendor/bin/phpunit` ## Formatting `./vendor/bin/php-cs-fixer fix` ## Linting `./vendor/bin/phpstan analyse` <file_sep>/src/Exception/RuntimeException.php <?php namespace Knock\KnockSdk\Exception; use RuntimeException as BaseRuntimeException; class RuntimeException extends BaseRuntimeException implements ExceptionInterface { } <file_sep>/tests/Unit/Api/BulkOperationsTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\BulkOperations; class BulkOperationsTest extends ApiTest { /** @test */ public function will_get_bulk_operation() { $id = 'b4f6f61e-3634-4e80-af0d-9c83e9acc6f3'; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $bulkOperations = $this->getApiMock(); $bulkOperations->expects($this->once()) ->method('getRequest') ->with(sprintf('/bulk_operations/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $bulkOperations->get($id)); } protected function getApiClass(): string { return BulkOperations::class; } } <file_sep>/src/Api/Workflows.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Workflows extends AbstractApi { /** * @param string $key * @param array $body * @param array $headers * @return array * @throws Exception */ public function trigger(string $key, array $body, array $headers = []): array { $url = $this->url('/workflows/%s/trigger', $key); return $this->postRequest($url, $body, $headers); } /** * @param string $key * @param array $body * @param array $headers * @return array|string * @throws Exception */ public function cancel(string $key, array $body, array $headers = []) { $url = $this->url('/workflows/%s/cancel', $key); return $this->postRequest($url, $body, $headers); } /** * @param string $key * @param array $schedule_attrs * @param array $headers * @return array * @throws Exception */ public function createSchedules(string $key, array $schedule_attrs, array $headers = []): array { $url = $this->url('/schedules'); $schedule_attrs['workflow'] = $key; return $this->postRequest($url, $schedule_attrs, $headers); } /** * @param array $schedule_ids * @param array $schedule_attrs * @param array $headers * @return array * @throws Exception */ public function updateSchedules(array $schedule_ids, array $schedule_attrs, array $headers = []): array { $url = $this->url('/schedules'); $schedule_attrs['schedule_ids'] = $schedule_ids; return $this->putRequest($url, $schedule_attrs, $headers); } /** * @param array $schedule_ids * @param array $headers * @return array * @throws Exception */ public function deleteSchedules(array $schedule_ids, array $headers = []): array { $url = $this->url('/schedules'); $body = ['schedule_ids' => $schedule_ids]; return $this->deleteRequest($url, $body, $headers); } /** * @param string $key * @param array $params * @param array $headers * @return array * @throws Exception */ public function listSchedules(string $key, array $params = [], array $headers = []): array { $params['workflow'] = $key; $url = $this->url('/schedules'); return $this->getRequest($url, $params, $headers); } } <file_sep>/src/HttpClient/Message/ResponseMediator.php <?php namespace Knock\KnockSdk\HttpClient\Message; use function is_array; use Knock\KnockSdk\Exception\RuntimeException; use Knock\KnockSdk\HttpClient\Utils\JsonArray; use Psr\Http\Message\ResponseInterface; class ResponseMediator { /** * The content type header. * * @var string */ public const CONTENT_TYPE_HEADER = 'Content-Type'; /** * The JSON content type identifier. * * @var string */ public const JSON_CONTENT_TYPE = 'application/json'; /** * The octet stream content type identifier. * * @var string */ public const STREAM_CONTENT_TYPE = 'application/octet-stream'; /** * The multipart form data content type identifier. * * @var string */ public const MULTIPART_CONTENT_TYPE = 'multipart/form-data'; /** * Return the response body as a string or JSON array if content type is JSON. * * @param ResponseInterface $response * * @return array|string */ public static function getContent(ResponseInterface $response) { $body = (string)$response->getBody(); if (! \in_array($body, ['', 'null', 'true', 'false'], true) && 0 === \strpos($response->getHeaderLine(self::CONTENT_TYPE_HEADER), self::JSON_CONTENT_TYPE)) { return JsonArray::decode($body); } return $body; } /** * Get the error message from the response if present. * * @param ResponseInterface $response * * @return string|null */ public static function getErrorMessage(ResponseInterface $response): ?string { try { $content = self::getContent($response); } catch (RuntimeException $e) { return null; } if (! is_array($content)) { return null; } if (isset($content['message'])) { $message = $content['message']; return $message; } return null; } } <file_sep>/src/Exception/ServerErrorException.php <?php namespace Knock\KnockSdk\Exception; class ServerErrorException extends ErrorException { } <file_sep>/tests/Unit/Api/UsersTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Users; class UsersTest extends ApiTest { /** @test */ public function will_identify_user() { $id = 'user_1'; $expected = $this->getContent(sprintf('%s/data/responses/user.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('putRequest') ->with(sprintf('/users/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->identify($id)); } /** @test */ public function will_get_user_messages() { $id = '96300c2a-a7cf-438c-a260-ea4aabe5fdde'; $expected = $this->getContent(sprintf('%s/data/responses/user-messages.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('getRequest') ->with(sprintf('/users/%s/messages', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->getMessages($id)); } /** @test */ public function will_get_user() { $id = 'user_1'; $expected = $this->getContent(sprintf('%s/data/responses/user.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('getRequest') ->with('/users/user_1') ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->get($id)); } /** @test */ public function will_delete_user() { $id = 'user_1'; $expected = ''; $users = $this->getApiMock(); $users->expects($this->once()) ->method('deleteRequest') ->with('/users/user_1') ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->delete($id)); } /** @test */ public function will_merge_users() { $toUserId = 'bce76d3f-b8a1-49ba-9f9a-d8d346f352c8'; $fromUserId = 'd99fb23a-413c-4c32-9565-5ea3f10c691d'; $expected = $this->getContent(sprintf('%s/data/responses/user.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('postRequest') ->with(sprintf('/users/%s/merge', $toUserId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->merge($toUserId, $fromUserId)); } /** @test */ public function will_bulk_identify_users() { $userData = [ [ 'id' => '6711d4b6-7e8f-4c84-8388-47eec3be89d6', ], ]; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('postRequest') ->with('/users/bulk/identify') ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->bulkIdentify($userData)); } /** @test */ public function will_bulk_delete_users() { $userIds = [ '69687856-7f7a-47f9-9d7a-76f1d916cc18', ]; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('postRequest') ->with('/users/bulk/delete') ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->bulkDelete($userIds)); } /** @test */ public function will_get_user_preferences() { $userId = '69687856-7f7a-47f9-9d7a-76f1d916cc18'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('getRequest') ->with(sprintf('/users/%s/preferences', $userId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->getPreferences($userId)); } /** @test */ public function will_get_user_preference() { $userId = '69687856-7f7a-47f9-9d7a-76f1d916cc18'; $preferenceId = '9493171f-12ea-4fac-bb34-bcc7fa9c5d3f'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('getRequest') ->with(sprintf('/users/%s/preferences/%s', $userId, $preferenceId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->getPreference($userId, $preferenceId)); } /** @test */ public function will_set_user_preference() { $userId = '69687856-7f7a-47f9-9d7a-76f1d916cc18'; $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('putRequest') ->with(sprintf('/users/%s/preferences/%s', $userId, 'default')) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->setPreferences($userId, [])); } /** @test */ public function will_bulk_set_user_preferences() { $expected = $this->getContent(sprintf('%s/data/responses/preference-set.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('postRequest') ->with(sprintf('/users/bulk/preferences')) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->bulkSetPreferences([])); } /** @test */ public function will_get_user_channel_data() { $userId = 'user_1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = $this->getContent(sprintf('%s/data/responses/channel-data.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('getRequest') ->with(sprintf('/users/%s/channel_data/%s', $userId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->getChannelData($userId, $channelId)); } /** @test */ public function will_set_user_channel_data() { $userId = 'user_1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = $this->getContent(sprintf('%s/data/responses/channel-data.json', __DIR__)); $users = $this->getApiMock(); $users->expects($this->once()) ->method('putRequest') ->with(sprintf('/users/%s/channel_data/%s', $userId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->setChannelData($userId, $channelId, [])); } /** @test */ public function will_unset_user_channel_data() { $userId = 'user_1'; $channelId = 'ad2e1aab-76ae-4463-98c2-83488a841710'; $expected = ''; $users = $this->getApiMock(); $users->expects($this->once()) ->method('deleteRequest') ->with(sprintf('/users/%s/channel_data/%s', $userId, $channelId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $users->unsetChannelData($userId, $channelId)); } protected function getApiClass(): string { return Users::class; } } <file_sep>/src/Exception/UnauthorizedException.php <?php namespace Knock\KnockSdk\Exception; class UnauthorizedException extends ClientErrorException { } <file_sep>/tests/Unit/Api/TenantsTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Tenants; class TenantsTest extends ApiTest { /** @test */ public function will_list_tenants() { $expected = $this->getContent(sprintf('%s/data/responses/tenants.json', __DIR__)); $tenants = $this->getApiMock(); $tenants->expects($this->once()) ->method('getRequest') ->with('/tenants') ->will($this->returnValue($expected)); $this->assertEquals($expected, $tenants->list()); } /** @test */ public function will_get_tenant() { $id = 'tenant-123'; $expected = $this->getContent(sprintf('%s/data/responses/tenant.json', __DIR__)); $tenants = $this->getApiMock(); $tenants->expects($this->once()) ->method('getRequest') ->with(sprintf('/tenants/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $tenants->get($id)); } /** @test */ public function will_set_tenant() { $id = 'tenant-123'; $expected = $this->getContent(sprintf('%s/data/responses/tenant.json', __DIR__)); $tenants = $this->getApiMock(); $tenants->expects($this->once()) ->method('putRequest') ->with(sprintf('/tenants/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $tenants->set($id, [])); } /** @test */ public function will_delete_tenant() { $id = 'tenant-123'; $expected = ''; $tenants = $this->getApiMock(); $tenants->expects($this->once()) ->method('deleteRequest') ->with(sprintf('/tenants/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $tenants->delete($id)); } protected function getApiClass(): string { return Tenants::class; } } <file_sep>/tests/Unit/Api/MessagesTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Messages; class MessagesTest extends ApiTest { /** @test */ public function will_list_messages() { $expected = $this->getContent(sprintf('%s/data/responses/messages.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('getRequest') ->with('/messages') ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->list()); } /** @test */ public function will_get_message() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $expected = $this->getContent(sprintf('%s/data/responses/message.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('getRequest') ->with(sprintf('/messages/%s', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->get($id)); } /** @test */ public function will_get_message_activities() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $expected = $this->getContent(sprintf('%s/data/responses/message-activities.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('getRequest') ->with(sprintf('/messages/%s/activities', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->getActivities($id)); } /** @test */ public function will_get_message_events() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $expected = $this->getContent(sprintf('%s/data/responses/message-events.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('getRequest') ->with(sprintf('/messages/%s/events', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->getEvents($id)); } /** @test */ public function will_get_message_content() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $expected = $this->getContent(sprintf('%s/data/responses/message-content.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('getRequest') ->with(sprintf('/messages/%s/content', $id)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->getContent($id)); } /** @test */ public function will_update_message_status() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $status = 'read'; $expected = $this->getContent(sprintf('%s/data/responses/message.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('putRequest') ->with(sprintf('/messages/%s/%s', $id, $status)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->updateStatus($id, $status)); } /** @test */ public function will_undo_message_status() { $id = '3961db0c-4202-475d-a5a2-32b4579425d1'; $status = 'read'; $expected = $this->getContent(sprintf('%s/data/responses/message.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('deleteRequest') ->with(sprintf('/messages/%s/%s', $id, $status)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->undoStatus($id, $status)); } /** @test */ public function will_bulk_update_message_status() { $status = 'read'; $messageIds = [ '8800f3fe-8b0d-47e1-a469-d17a27849d53', '85575f79-f186-4fd5-8bc6-ffdef78ab080', ]; $expected = $this->getContent(sprintf('%s/data/responses/messages.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('postRequest') ->with(sprintf('/messages/batch/%s', $status)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->batchChangeStatus($status, $messageIds)); } /** @test */ public function will_bulk_channel_status() { $channel = '3961db0c-4202-475d-a5a2-32b4579425d1'; $status = 'read'; $expected = $this->getContent(sprintf('%s/data/responses/bulk-operation.json', __DIR__)); $messages = $this->getApiMock(); $messages->expects($this->once()) ->method('postRequest') ->with(sprintf('/channels/%s/messages/bulk/%s', $channel, $status)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $messages->bulkUpdateChannelStatus($channel, $status, [])); } protected function getApiClass(): string { return Messages::class; } } <file_sep>/src/Exception/ExceptionInterface.php <?php namespace Knock\KnockSdk\Exception; use Http\Client\Exception; interface ExceptionInterface extends Exception { } <file_sep>/src/Api/BulkOperations.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class BulkOperations extends AbstractApi { /** * @param string $operationId * @param array $headers * @return array * @throws Exception */ public function get(string $operationId, array $headers = []): array { $url = $this->url('/bulk_operations/%s', $operationId); return $this->getRequest($url, [], $headers); } } <file_sep>/tests/Unit/HttpClient/BuilderTest.php <?php namespace Tests\Unit\HttpClient; use Http\Client\Common\HttpMethodsClientInterface; use Http\Client\Common\Plugin; use Knock\KnockSdk\HttpClient\Builder; use PHPUnit\Framework\TestCase; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\RequestFactoryInterface; class BuilderTest extends TestCase { /** * @var Builder */ protected Builder $builder; public function setUp(): void { parent::setUp(); $this->builder = new Builder( $this->createMock(ClientInterface::class), $this->createMock(RequestFactoryInterface::class), ); } public function test_add_plugin_should_invalidate_http_client(): void { $client = $this->builder->getHttpClient(); $this->builder->addPlugin($this->createMock(Plugin::class)); $this->assertNotSame($client, $this->builder->getHttpClient()); } public function test_remove_plugin_should_invalidate_http_client(): void { $this->builder->addPlugin($this->createMock(Plugin::class)); $client = $this->builder->getHttpClient(); $this->builder->removePlugin(Plugin::class); $this->assertNotSame($client, $this->builder->getHttpClient()); } public function test_http_client_should_be_a_http_methods_client(): void { $this->assertInstanceOf(HttpMethodsClientInterface::class, $this->builder->getHttpClient()); } } <file_sep>/tests/Unit/Api/FeedsTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Feeds; class FeedsTest extends ApiTest { /** @test */ public function will_return_feeds_for_user() { $userId = 'user_1'; $feedId = '970f36fd-147a-4a7d-88f2-1b6550b15e0c'; $expected = $this->getContent(sprintf('%s/data/responses/feed.json', __DIR__)); $feeds = $this->getApiMock(); $feeds->expects($this->once()) ->method('getRequest') ->with(sprintf('/users/%s/feeds/%s', $userId, $feedId)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $feeds->getUserFeed($userId, $feedId)); } protected function getApiClass(): string { return Feeds::class; } } <file_sep>/tests/TestCase.php <?php namespace Tests; use Http\Discovery\Psr18ClientDiscovery; use Http\Discovery\Strategy\MockClientStrategy; use Knock\KnockSdk\Client; use Knock\KnockSdk\HttpClient\Builder; use PHPUnit\Framework\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { protected Client $client; protected Builder $builder; public function setUp(): void { parent::setUp(); Psr18ClientDiscovery::prependStrategy(MockClientStrategy::class); $this->builder = new Builder(); $this->client = new Client('xxx', $this->builder); } } <file_sep>/src/HttpClient/Utils/QueryStringBuilder.php <?php namespace Knock\KnockSdk\HttpClient\Utils; use function count; use League\Uri\Components\Query; use function sprintf; final class QueryStringBuilder { /** * Encode a query as a query string according to RFC 3986. * * @param array $query * @return string */ public static function build(array $query): string { if (0 === count($query)) { return ''; } return sprintf('?%s', Query::createFromParams($query)); } } <file_sep>/src/Api/AbstractApi.php <?php namespace Knock\KnockSdk\Api; use function array_filter; use function array_merge; use function count; use Http\Client\Exception; use Knock\KnockSdk\Client; use Knock\KnockSdk\HttpClient\Message\ResponseMediator; use Knock\KnockSdk\HttpClient\Utils\JsonArray; use Knock\KnockSdk\HttpClient\Utils\QueryStringBuilder; use Psr\Http\Message\ResponseInterface; use function sprintf; abstract class AbstractApi { /** * @var Client */ protected Client $client; /** * Create a new API instance. * * @param Client $client * * @return void */ public function __construct(Client $client) { $this->client = $client; } /** * Send a GET request with query params and return the raw response. * * @param string $uri * @param array $params * @param array<string,string> $headers * * @return ResponseInterface * @throws Exception * */ protected function getAsResponse(string $uri, array $params = [], array $headers = []): ResponseInterface { return $this->client->getHttpClient()->get($this->prepareUri($uri, $params), $headers); } /** * @param string $uri * @param array<string,mixed> $params * @param array<string,string> $headers * @return array|string * @throws Exception */ protected function getRequest(string $uri, array $params = [], array $headers = []) { $response = $this->getAsResponse($uri, $params, $headers); return ResponseMediator::getContent($response); } /** * @param string $uri * @param array<string,mixed> $body * @param array<string,string> $headers * @return array|string * @throws Exception */ protected function postRequest(string $uri, array $body = [], array $headers = []) { $body = self::prepareJsonBody($body); if (null !== $body) { $headers = self::addJsonContentType($headers); } $response = $this->client->getHttpClient()->post($this->prepareUri($uri), $headers, $body); return ResponseMediator::getContent($response); } /** * @param string $uri * @param array<string,mixed> $body * @param array<string,string> $headers * @return array|string * @throws Exception */ protected function putRequest(string $uri, array $body = [], array $headers = []) { $body = self::prepareJsonBody($body); if (null !== $body) { $headers = self::addJsonContentType($headers); } $response = $this->client->getHttpClient()->put($this->prepareUri($uri), $headers, $body ?? ''); return ResponseMediator::getContent($response); } /** * @param string $uri * @param array<string,mixed> $body * @param array<string,string> $headers * @return array|string * @throws Exception */ protected function deleteRequest(string $uri, array $body = [], array $headers = []) { $body = self::prepareJsonBody($body); if (null !== $body) { $headers = self::addJsonContentType($headers); } $response = $this->client->getHttpClient()->delete($this->prepareUri($uri), $headers, $body ?? ''); return ResponseMediator::getContent($response); } /** * Generate URL from base url and given endpoint. * * @param string $endpoint * @param array $replacements * * @return string */ protected function url(string $endpoint, ...$replacements): string { return vsprintf($endpoint, $replacements); } /** * Prepare the request URI. * * @param string $uri * @param array $query * * @return string */ protected function prepareUri(string $uri, array $query = []): string { $query = array_filter($query, function ($value): bool { return null !== $value; }); return sprintf( '%s%s%s', $this->client->getPrefix(), $uri, QueryStringBuilder::build($query) ); } /** * Add the JSON content type to the headers if one is not already present. * * @param array<string,string> $headers * * @return array<string,string> */ private static function addJsonContentType(array $headers): array { return array_merge([ResponseMediator::CONTENT_TYPE_HEADER => ResponseMediator::JSON_CONTENT_TYPE], $headers); } /** * Prepare the request JSON body. * * @param array<string,mixed> $params * * @return string|null */ private static function prepareJsonBody(array $params): ?string { $params = array_filter($params, function ($value): bool { return null !== $value; }); if (0 === count($params)) { return null; } return JsonArray::encode($params); } } <file_sep>/tests/Unit/Api/WorkflowsTest.php <?php namespace Tests\Unit\Api; use Knock\KnockSdk\Api\Workflows; class WorkflowsTest extends ApiTest { /** @test */ public function will_trigger_workflow() { $key = 'new-comment'; $expected = $this->getContent(sprintf('%s/data/responses/workflow-trigger.json', __DIR__)); $workflows = $this->getApiMock(); $workflows->expects($this->once()) ->method('postRequest') ->with(sprintf('/workflows/%s/trigger', $key)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $workflows->trigger($key, [])); } /** @test */ public function will_trigger_workflow_with_idempotency_key() { $key = 'new-comment'; $expected = $this->getContent(sprintf('%s/data/responses/workflow-trigger.json', __DIR__)); $headers = ['Idempotency-Key' => '12345']; $workflows = $this->getApiMock(); $workflows->expects($this->once()) ->method('postRequest') ->with(sprintf('/workflows/%s/trigger', $key), [], $headers) ->will($this->returnValue($expected)); $this->assertEquals($expected, $workflows->trigger($key, [], $headers)); } /** @test */ public function will_cancel_workflow() { $key = 'new-comment'; $expected = ''; $workflows = $this->getApiMock(); $workflows->expects($this->once()) ->method('postRequest') ->with(sprintf('/workflows/%s/cancel', $key)) ->will($this->returnValue($expected)); $this->assertEquals($expected, $workflows->cancel($key, [])); } protected function getApiClass(): string { return Workflows::class; } } <file_sep>/src/Api/Objects.php <?php namespace Knock\KnockSdk\Api; use Http\Client\Exception; class Objects extends AbstractApi { /** * @param string $collection * @param array $headers * @return array * @throws Exception */ public function list(string $collection, array $params = [], array $headers = []): array { $url = $this->url('/objects/%s', $collection); return $this->getRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $headers * @return array * @throws Exception */ public function get(string $collection, string $objectId, array $headers = []): array { $url = $this->url('/objects/%s/%s', $collection, $objectId); return $this->getRequest($url, [], $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getMessages(string $collection, string $objectId, array $params = [], array $headers = []): array { if (array_key_exists('trigger_data', $params)) { $params['trigger_data'] = json_encode($params['trigger_data']); } $url = $this->url('/objects/%s/%s/messages', $collection, $objectId); return $this->getRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getSchedules(string $collection, string $objectId, array $params = [], array $headers = []): array { $url = $this->url('/objects/%s/%s/schedules', $collection, $objectId); return $this->getRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $body * @param array $headers * @return array * @throws Exception */ public function set(string $collection, string $objectId, array $body, array $headers = []): array { $url = $this->url('/objects/%s/%s', $collection, $objectId); return $this->putRequest($url, $body, $headers); } /** * @param string $collection * @param string $objectId * @param array $headers * @return array|string * @throws Exception */ public function delete(string $collection, string $objectId, array $headers = []) { $url = $this->url('/objects/%s/%s', $collection, $objectId); return $this->deleteRequest($url, [], $headers); } /** * @param string $collection * @param array $objects * @param array $headers * @return array * @throws Exception */ public function bulkSet(string $collection, array $objects, array $headers = []): array { $url = $this->url('/objects/%s/bulk/set', $collection); return $this->postRequest($url, ['objects' => $objects], $headers); } /** * @param string $collection * @param array $objectIds * @param array $headers * @return array * @throws Exception */ public function bulkDelete(string $collection, array $objectIds, array $headers = []): array { $url = $this->url('/objects/%s/bulk/delete', $collection); return $this->postRequest($url, ['object_ids' => $objectIds], $headers); } /** * @param string $collection * @param string $objectId * @param array $headers * @return array * @throws Exception */ public function getPreferences(string $collection, string $objectId, array $headers = []): array { $url = $this->url('/objects/%s/%s/preferences', $collection, $objectId); return $this->getRequest($url, [], $headers); } /** * @param string $collection * @param string $objectId * @param string $preferenceId * @param array $headers * @return array * @throws Exception */ public function getPreference(string $collection, string $objectId, string $preferenceId, array $headers = []): array { $url = $this->url('/objects/%s/%s/preferences/%s', $collection, $objectId, $preferenceId); return $this->getRequest($url, $headers); } /** * @param string $collection * @param string $objectId * @param string $preferenceSetId * @param array $body * @param array $headers * @return array * @throws Exception */ public function setPreferences( string $collection, string $objectId, array $body, string $preferenceSetId = 'default', array $headers = [] ): array { $url = $this->url('/objects/%s/%s/preferences/%s', $collection, $objectId, $preferenceSetId); return $this->putRequest($url, $body, $headers); } /** * @param string $collection * @param string $objectId * @param string $channelId * @param array $headers * @return array * @throws Exception */ public function getChannelData(string $collection, string $objectId, string $channelId, array $headers = []): array { $url = $this->url('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId); return $this->getRequest($url, [], $headers); } /** * @param string $collection * @param string $objectId * @param string $channelId * @param array $body * @param array $headers * @return array * @throws Exception */ public function setChannelData( string $collection, string $objectId, string $channelId, array $body, array $headers = [] ): array { $body = ['data' => $body]; $url = $this->url('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId); return $this->putRequest($url, $body, $headers); } /** * @param string $collection * @param string $objectId * @param string $channelId * @param array $headers * @return array|string * @throws Exception */ public function unsetChannelData( string $collection, string $objectId, string $channelId, array $headers = [] ) { $url = $this->url('/objects/%s/%s/channel_data/%s', $collection, $objectId, $channelId); return $this->deleteRequest($url, [], $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function listSubscriptions(string $collection, string $objectId, array $params = [], array $headers = []): array { $url = $this->url('/objects/%s/%s/subscriptions', $collection, $objectId); return $this->getRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function getSubscriptions(string $collection, string $objectId, array $params = [], array $headers = []): array { $params['mode'] = 'recipient'; $url = $this->url('/objects/%s/%s/subscriptions', $collection, $objectId); return $this->getRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function addSubscriptions(string $collection, string $objectId, array $params = [], array $headers = []): array { $url = $this->url('/objects/%s/%s/subscriptions', $collection, $objectId); return $this->postRequest($url, $params, $headers); } /** * @param string $collection * @param string $objectId * @param array $params * @param array $headers * @return array * @throws Exception */ public function deleteSubscriptions(string $collection, string $objectId, array $params = [], array $headers = []): array { $url = $this->url('/objects/%s/%s/subscriptions', $collection, $objectId); return $this->deleteRequest($url, $params, $headers); } }
41772541a1ef13d1969425179a843bccecb76203
[ "Markdown", "PHP" ]
38
PHP
knocklabs/knock-php
67fbf6d1d1995c85a33f0ce7ac7a74dfbd7ebcc1
3c07c5454370df6352c84fbb9ad558406ad85e04
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Mail\VisitorContact; use App\Models\Post; use App\Models\Category; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Session; class WebsiteController extends Controller { public function index() { /* $categories = Category::orderBy('name', 'ASC')->where('is_published', '1')->get(); $posts = Post::orderBy('id', 'DESC')->where('post_type', 'post')->where('is_published', '1')->paginate(5);*/ //return view('website.index', compact('posts', 'categories')); return view('website.index'); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | 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('/', 'App\Http\Controllers\InicioController@load')->name('inicio'); Route::get('/results', 'App\Http\Controllers\InicioController@results')->name('results'); Route::get('/watch/{id}', 'App\Http\Controllers\InicioController@watch')->name('watch'); Auth::routes(); Route::get('/blog','App\Http\Controllers\WebsiteController@index')->name('index'); Route::get('category/{slug}', 'App\Http\Controllers\WebsiteController@category')->name('category'); Route::get('post/{slug}', 'App\Http\Controllers\WebsiteController@post')->name('post'); Route::get('page/{slug}', 'App\Http\Controllers\WebsiteController@page')->name('page'); Route::get('contact', 'App\Http\Controllers\WebsiteController@showContactForm')->name('contact.show'); Route::post('contact', 'App\Http\Controllers\WebsiteController@submitContactForm')->name('contact.submit'); Route::get('/home','App\Http\Controllers\HomeController@index')->name('home'); Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () { Route::resource('categories', 'CategoryController'); Route::resource('posts', 'PostController'); Route::resource('pages', 'PageController'); Route::resource('galleries', 'GalleryController'); }); <file_sep><?php namespace Database\Factories; use App\Models\User; use App\Models\Post; use App\Models\CategoryPost; use Illuminate\Database\Eloquent\Factories\Factory; use Faker\Generator as Faker; use Illuminate\Support\Str; class UserFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = User::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name, 'email' => $this->faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => bcrypt('<PASSWORD>'), 'remember_token' => Str::random(10), ]; } } /* class PostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string *//* protected $model = Post::class; /** * Define the model's default state. * * @return array *//* public function definition() { $title = $this->faker->unique()->sentence; $isPublished = ['1', '0']; return [ 'user_id' => rand(1, 5), 'title' => $title, 'slug' => str_slug($title), 'sub_title' => $this->faker->sentence, 'details' => $this->faker->paragraph, 'post_type' => 'post', 'is_published' => $isPublished[rand(0, 1)], 'created_at' => now(), 'updated_at' => now(), ]; } } class CategoryPostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string *//* protected $model = CategoryPost::class; /** * Define the model's default state. * * @return array *//* public function definition() { return [ 'category_id' => rand(1, 5), 'post_id' => rand(1, 100), 'created_at' => now(), 'updated_at' => now(), ]; } } $factory->define(App\Models\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => bcrypt('<PASSWORD>'), 'remember_token' => Str::random(10), ]; }); $factory->define(App\Models\Post::class, function (Faker $faker) { $title = $faker->unique()->sentence; $isPublished = ['1', '0']; return [ 'user_id' => rand(1, 5), 'title' => $title, 'slug' => str_slug($title), 'sub_title' => $faker->sentence, 'details' => $faker->paragraph, 'post_type' => 'post', 'is_published' => $isPublished[rand(0, 1)], 'created_at' => now(), 'updated_at' => now(), ]; }); $factory->define(App\Models\CategoryPost::class, function (Faker $faker) { return [ 'category_id' => rand(1, 5), 'post_id' => rand(1, 100), 'created_at' => now(), 'updated_at' => now(), ]; }); */<file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\File; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; class InicioController extends Controller { public function load() { if (session('search_query')) { $videoLists = $this->_videoLists(session('search_query')); } else { $videoLists = $this->_videoLists('only in new york'); } return view('inicio', compact('videoLists')); } public function results(Request $request) { session(['search_query' => $request->search_query]); $videoLists = $this->_videoLists($request->search_query); return view('results', compact('videoLists')); } public function watch($id) { $singleVideo = $this->_singleVideo($id); if (session('search_query')) { $videoLists = $this->_videoLists(session('search_query')); } else { $videoLists = $this->_videoLists('fails'); } return view('watch', compact('singleVideo', 'videoLists')); } protected function _videoLists($keywords) { $part = 'snippet'; $country = 'BD'; $apiKey = config('services.youtube.api_key'); $maxResults = 12; $youTubeEndPoint = config('services.youtube.search_endpoint'); $type = 'video'; $url = "$youTubeEndPoint?part=$part&maxResults=$maxResults&regionCode=$country&type=$type&key=$apiKey&q=$keywords"; $response = Http::get($url); $results = json_decode($response); File::put(storage_path() . '/app/public/results.json', $response->body()); return $results; } protected function _singleVideo($id) { $apiKey = config('services.youtube.api_key'); $part = 'snippet'; $url = "https://www.googleapis.com/youtube/v3/videos?part=$part&id=$id&key=$apiKey"; $response = Http::get($url); $results = json_decode($response); File::put(storage_path() . '/app/public/single.json', $response->body()); return $results; } }
2455dac7664decf243664bdc4c7d4857db18c054
[ "PHP" ]
4
PHP
ArielTheGreat/ProyectoFinalDeCurso
bc34328a8bc02f63e59a81738d6106f92fb7e38e
d7f1fd36785e6025c4e8939dbfc4d212040e72b0
refs/heads/master
<file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include<stdio.h> #include<math.h> #include "Unit1.h" #include "Unit2.h" #include "Unit3.h" #include <stdlib.h> #define OVERFLOW -2 #define INIT_SIZE 10000 //存储空间初始分配量 #define INCREMENT 10 //存储空间分配增量 static int LINE; //全局变量行值 static int SAMPLE; //全局变量列值 static int bonum; //全局变量波段数 int min; int max; float tcon; //边缘点判断所需形参 typedef struct{ int r; //迷宫中r行c列的位置 //!!!!!!敲黑板!!因为读取输出像素点是xy格式的,所以maze.adr[列值][行值] int c; }PostType; typedef struct{ PostType seat;//当前坐标 int di; //往下一坐标的方向 }SElemType; //栈内元素类型 typedef struct{ SElemType* base; SElemType* top; int stackSize; }Stack; //栈类型 void InitStack(Stack &S){ //构造空栈S S.base=(SElemType*)malloc(INIT_SIZE *sizeof(SElemType)); if(!S.base) exit(OVERFLOW);//存储分配失败 S.top=S.base; S.stackSize=INIT_SIZE; } int StackEmpty(Stack S){ //判断空栈 if(S.top==S.base) return 1; return 0; } void Push(Stack &S,SElemType e){//入栈 if(S.top-S.base >=S.stackSize){//栈满,加空间 S.base=(SElemType *)realloc(S.base,(S.stackSize+INCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); //存储分配失败 S.top=S.base+S.stackSize; S.stackSize+=INCREMENT; } *S.top++=e; } int Pop(Stack &S,SElemType &e){//出栈 if(S.top==S.base) return 0; e=*--S.top; return 1; } typedef struct{ int r; int c; char adr[2000][2000]; }MazeType; //迷宫类型 MazeType maze; //定义全局自定义变量迷宫maze MazeType addup; void FootPrint(MazeType &maze,PostType curpos)//标记 { maze.adr[curpos.r][curpos.c]='%'; } PostType NextPos(PostType &curpos,int i){ //探索下一位置并返回下一位置(cpos)的坐标 PostType cpos; cpos=curpos; switch(i){ //1.2.3分别表示右、下、左、上方向 case 1 : cpos.r+=1; break; case 2 : cpos.c+=1; break; case 4 : cpos.c-=1; break; case 3 : cpos.r-=1; break; default: exit(0); } return cpos; } //根据大小判断的方法:MazePath int MazePath(MazeType &maze,PostType start,MazeType &addup){ Stack S; PostType curpos; int area=0; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]=='1') { //当前位置可以通过, FootPrint(maze,curpos); area++;//留下足迹 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); if(area>min&&area<max){ curpos=start; do{ if(maze.adr[curpos.r][curpos.c]=='%') { //当前位置可以通过, maze.adr[curpos.r][curpos.c]='*'; addup.adr[curpos.r][curpos.c]='1'; e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } else { curpos=start; do{ if(maze.adr[curpos.r][curpos.c]=='%') { //当前位置可以通过, maze.adr[curpos.r][curpos.c]='0'; e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } return area; } // 根据形状进行二次判断 void sFootPrint(MazeType &maze,PostType curpos) //标记 { maze.adr[curpos.r][curpos.c]='#'; } int scount(MazeType &maze,PostType curpos){ int count = 0; if(maze.adr[curpos.r+1][curpos.c]=='*') count++; if(maze.adr[curpos.r-1][curpos.c]=='*') count++; if(maze.adr[curpos.r][curpos.c+1]=='*') count++; if(maze.adr[curpos.r][curpos.c-1]=='*') count++; return count; } int side,point,sleft,plane; int tplane; float con; //side为斑块的边数,point为斑块中点的数量, //sbase为点数为point时内部面最多的形状的最大正方形一边的点数 //sleft为减去最大正方形剩下的点 //plane是该斑块点数能构成构成最大内部面数,tplane是该斑块的内部面数 //con是斑块所含有的内部面数除以最大内部面数的紧密度 int planes(int a){ //求最大内部面数量的方法,输入的数据为斑块的点数 int splane=0; int sbase; int scan; sbase = (int)sqrt(a)+1; scan = (int)point/sbase; if(point%sbase != 0) { splane = (sbase-1)*(scan-1)+point%sbase-1; } if(point%sbase == 0) { splane = (sbase-1)*(scan-1); } return splane; } float shape(MazeType &maze,PostType start,MazeType &addup){ Stack S; PostType curpos; int curstep = 1; side = 0; point = 0; con = 0.000; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]=='*') { //当前位置可以通过 sFootPrint(maze,curpos); e.seat=curpos; e.di=1; Push(S,e); //加入路径 point++; side+=scount(maze,curpos); curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); tplane = side-point+1; plane = planes(point); con = (float)tplane/plane; if(con>tcon){ curpos=start; do{ if(maze.adr[curpos.r][curpos.c]=='#') { //当前位置可以通过 maze.adr[curpos.r][curpos.c]='y'; e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } else { curpos=start; double summ=0; for(int a=curpos.r;a<curpos.r+80;a++){ //行/2的十四分之一左右 for(int b=curpos.c;b<curpos.c+100;b++){ //列/2的二十分之一左右 if(addup.adr[a][b]=='1'){ summ++; } } } if((summ/(8000))>0.5){ //占比达到50% 以上,说明该处为斑块群。 do{ if(maze.adr[curpos.r][curpos.c]=='#') { //当前位置可以通过, maze.adr[curpos.r][curpos.c]='y'; e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } //if(summ) do{ if(maze.adr[curpos.r][curpos.c]=='#') { //当前位置可以通过, maze.adr[curpos.r][curpos.c]='0'; e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di < 4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } return con; } //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm2 *Form2; //--------------------------------------------------------------------------- __fastcall TForm2::TForm2(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm2::Edit1Change(TObject *Sender) { //int a = StrToInt(Edit1->Text); if(Edit1->Text=="") min=0; else{ min=StrToInt(Edit1->Text); } } //--------------------------------------------------------------------------- void __fastcall TForm2::Edit2Change(TObject *Sender) { // int a = StrToInt(Edit2->Text); if(Edit2->Text=="") max=0; else max=StrToInt(Edit2->Text); } //--------------------------------------------------------------------------- void __fastcall TForm2::Edit3Change(TObject *Sender) { //float a = StrToFloat(Edit3->Text); if(Edit3->Text=="") tcon=0; else tcon=StrToFloat(Edit3->Text); } //--------------------------------------------------------------------------- void __fastcall TForm2::Button1Click(TObject *Sender) { if(min < 0) { MessageBox(NULL,"面积下界必须是正整数!请重新输入。", "Error",MB_ICONERROR); } if(max < 0) { MessageBox(NULL,"面积上界必须是正整数!请重新输入。", "Error",MB_ICONERROR); } if(tcon < 0||tcon > 1){ MessageBox(NULL,"0<=紧密度<=1!请重新输入。", "Error",MB_ICONERROR); } LINE=Form1->LINE; SAMPLE=Form1->SAMPLE; int r1,b1,g1; r1=Form1->r1; g1=Form1->g1; b1=Form1->b1; bonum=Form1->bonum; Form3->Image1->Canvas->FloodFill(0,0,clYellow,fsBorder); int count=0,count1=0; int offset=SAMPLE*bonum*2-bonum*2;//1996列*8字节-读取的16字节 int r,g,b,a; FILE *fp; unsigned short int idata[20];//用来读取本行数据 unsigned short int idatanext[20];//用来读取下行数据 AnsiString name; name=Form1->name; maze.r=SAMPLE;maze.c=LINE; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(idata,2,bonum,fp);//读取数据储存在idata[]中 //fseek(fp,offset,1); //调整指针到下一行 //fread(idatanext,2,bonum*2,fp);// 读取调整指针后的这一行数据 //if(count%SAMPLE!=0) //如果这一行数据读到头,要调到隔一行的那一行 //fseek(fp,-(offset+bonum*4),1);//将指针调回上一行并退回到上一次读取的位置 count++; r=idata[r1]/3.2; g=idata[g1]/3.2; b=idata[b1]/3.2; if(r<27&&r>10&&b>40&&b<82&&g>30&&g<85) maze.adr[(count-1)%SAMPLE][count/SAMPLE]='1'; else maze.adr[(count-1)%SAMPLE][count/SAMPLE]='0'; } fclose(fp); } PostType start; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]=='1'){ start.r=j;start.c=i; MazePath(maze,start,addup); } } } //输出矢量二进制文件 /*if(Edit4->Text == "") { MessageBox(NULL,"请选择矢量文件路径!", "Error",MB_ICONERROR); } FILE *fptwo; char ac=1,bc=0; fptwo=fopen(Edit4->Text.c_str(),"wb");//打开文件 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]=='*') fwrite(&ac,1,1,fptwo); else fwrite(&bc,1,1,fptwo); } } fclose(fptwo); MessageBox(NULL,"成功生成二进制矢量文件!请在对应文件查看。", "Message",MB_ICONASTERISK); */ for(int k=0;k<LINE;k++){ for(int l=0;l<SAMPLE;l++){ if(maze.adr[l][k]=='*'){ start.r=l; start.c=k; shape(maze,start,addup); } } } //输出矢量二进制文件 /*if(Edit4->Text == "") { MessageBox(NULL,"请选择矢量文件路径!", "Error",MB_ICONERROR); } FILE *fptwo; char ac=1,bc=0; fptwo=fopen(Edit4->Text.c_str(),"wb");//打开文件 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]=='y') fwrite(&ac,1,1,fptwo); else fwrite(&bc,1,1,fptwo); } } fclose(fptwo); MessageBox(NULL,"成功生成二进制矢量文件!请在对应文件查看。", "Message",MB_ICONASTERISK); */ fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(idata,2,bonum,fp);//读取本行数据储存在idata[]中 /*fseek(fp,offset,1); //调整指针到下一行 fread(idatanext,2,bonum,fp);// 读取调整指针后的这一行数据 if(count1%SAMPLE!=0) //如果这一行数据读到头,要调到隔一行的那一行 fseek(fp,-(offset+bonum*4),1);//将指针调回上一行并退回到上一次读取的位置 */ count1++; r=idata[r1]/3.2; g=idata[g1]/3.2; b=idata[b1]/3.2; if(maze.adr[(count1-1)%SAMPLE][count1/SAMPLE]=='y') Form3->Image1->Canvas->Pixels[(count1-1)%SAMPLE][count1/SAMPLE] =Graphics::TColor(RGB(r,g,b)); } fclose(fp); } Form3->Label13->Caption=name; Form3->Label14->Caption=r1; Form3->Label15->Caption=g1; Form3->Label16->Caption=b1; Form3->Label17->Caption=Form1->LINE; Form3->Label19->Caption=Form1->SAMPLE; Form3->Label21->Caption=bonum; Form3->Label4->Caption=Edit1->Text; Form3->Label5->Caption=Edit2->Text; Form3->Label6->Caption=Edit3->Text; Form3->Show(); } //--------------------------------------------------------------------------- void __fastcall TForm2::Button2Click(TObject *Sender) { /*if(OpenDialog1->Execute()){ Edit4->Text = OpenDialog1->FileName; } */ } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef Unit3H #define Unit3H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ExtCtrls.hpp> #include <stdlib.h> #include <stdio.h> #include <Menus.hpp> #include<vector> #include<stack> using namespace std; //--------------------------------------------------------------------------- class TForm3 : public TForm { __published: // IDE-managed Components TScrollBox *ScrollBox1; TImage *Image1; TMemo *Memo1; void __fastcall Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); int __fastcall pnpoly(float test_x,float test_y,int nvert); void __fastcall back_to_photo() ; void __fastcall select_to_red(); void __fastcall go_back(); void __fastcall write_point_to_file(String file_address); private: // User declarations public: // User declarations __fastcall TForm3(TComponent* Owner); int HANG,LIE; int X_BODUAN; int D_YANGBEN; String MODEL; int amount_of_yb; unsigned short int t_min; String ADDRESS; POINT mouse_start,mouse_end,mouse_select,mouse_eye; int mouse_is_down; int select_time; vector<POINT>select_point; vector<POINT>lucky_point; typedef struct { unsigned short int data[5]; int type; }point; point** picture; typedef struct { int x_max; int y_max; int x_min; int y_min; }Range; stack<Range>rg; void show_the_picture() { picture = (point **)malloc(sizeof(point*)*HANG); for(int i=0 ; i<HANG ; i++) picture[i] = (point *)malloc((sizeof(unsigned short int)*13 + sizeof(int)*2)*LIE); Image1->Height = HANG; Image1->Width = LIE; FILE *fp; fp = fopen(ADDRESS.c_str(),"rb"); unsigned short int maxx = 0; unsigned short int minn = 0x3f3f3f3f; unsigned short int dat; int p_x = 0; int p_y = 0; int pp = 0; fseek (fp, 0, SEEK_END); ///将文件指针移动文件结尾 long long size=ftell (fp); ///求出当前文件指针距离文件开始的字节数 fseek(fp, 0, SEEK_SET); long long byte_size = size/(HANG*LIE*X_BODUAN); // return ; while(!feof(fp)) { fread(&dat,byte_size,1,fp); if(dat>maxx) maxx = dat; if(dat<minn) minn = dat; picture[p_x][p_y].data[pp] = dat; //三种不同图片格式 if(MODEL.c_str()[0]=='1') { pp++; if(pp == X_BODUAN) { p_y++; pp = 0; } if(p_y == LIE) { p_x++; p_y = 0; } } else if(MODEL.c_str()[0]=='2') { p_y++; if(p_y==LIE) { p_x++; p_y=0; } if(p_x==HANG) { p_x=0; p_y=0; pp++; } } else { p_y++; if(p_y==LIE) { pp++; p_y=0; } if(pp==X_BODUAN) { p_x++; pp=0; } } } if(maxx<255) t_min = 1; else t_min = (unsigned short int)(maxx/255); for(int i=0 ; i<HANG ; i++) { for(int j=0 ; j<LIE ; j++) { Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(picture[i][j].data[0]/t_min,picture[i][j].data[1]/t_min,picture[i][j].data[2]/t_min)); } } Memo1->Lines->Append(maxx); Memo1->Lines->Append(t_min); //这两句不要删! fclose(fp); } }; //--------------------------------------------------------------------------- extern PACKAGE TForm3 *Form3; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #include <algorithm> #include <malloc.h> #include <string.h> #include <math.h> #include<vector> using namespace std; #pragma hdrstop #include "Unit4.h" #include "Unit3.h" #include "Unit2.h" #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm4 *Form4; //--------------------------------------------------------------------------- __fastcall TForm4::TForm4(TComponent* Owner) : TForm(Owner) { max_length=0; address_of_x=0; address_of_y=0; TXT2 = ""; } int next[8][2]={{-1,1}, //右上 {0,1},//右 {1,1}, //右下 {1,0},//下 {1,-1},//左下 {0,-1},//左 {-1,-1},//左上 {-1,0}};//上 int count1=0,maxx=0,final=0; /*vector<int> sum; vector<int> regist_x; vector<int> regist_y;*/ int *regist_x = (int *)malloc(sizeof(int)*200000); int *regist_y = (int *)malloc(sizeof(int)*200000); int *sum = (int *)malloc(sizeof(int)*200000); void __fastcall TForm4::Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { GetCursorPos(&mouse_start); mouse_is_down = 1; } //--------------------------------------------------------------------------- void __fastcall TForm4::Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { GetCursorPos(&mouse_end); int x_move = mouse_end.x-mouse_start.x; int y_move = mouse_end.y-mouse_start.y; //*******************对自己图片位置的更改************************ Image1->Left += x_move; Image1->Top += y_move; if(Image1->Left>0) Image1->Left = 0; if(Image1->Top>0) Image1->Top = 0; if(Image1->Left<(ScrollBox1->Width-Image1->Width)) Image1->Left = (ScrollBox1->Width-Image1->Width); if(Image1->Top<(ScrollBox1->Height-Image1->Height)) Image1->Top = (ScrollBox1->Height-Image1->Height); //*******************对另一个图片位置的更改********************** Form3->Image1->Left += x_move; Form3->Image1->Top += y_move; if(Form3->Image1->Left>0) Form3->Image1->Left = 0; if(Form3->Image1->Top>0) Form3->Image1->Top = 0; if(Form3->Image1->Left<(Form3->ScrollBox1->Width - Form3->Image1->Width)) Form3->Image1->Left = (Form3->ScrollBox1->Width - Form3->Image1->Width); if(Form3->Image1->Top<(Form3->ScrollBox1->Height - Form3->Image1->Height)) Form3->Image1->Top = (Form3->ScrollBox1->Height - Form3->Image1->Height); mouse_is_down = 0; //*******************对另一个图片位置的更改********************** Form2->Image1->Left += x_move; Form2->Image1->Top += y_move; if(Form2->Image1->Left>0) Form2->Image1->Left = 0; if(Form2->Image1->Top>0) Form2->Image1->Top = 0; if(Form2->Image1->Left<(Form2->ScrollBox1->Width - Form2->Image1->Width)) Form2->Image1->Left = (Form2->ScrollBox1->Width - Form2->Image1->Width); if(Form2->Image1->Top<(Form2->ScrollBox1->Height - Form2->Image1->Height)) Form2->Image1->Top = (Form2->ScrollBox1->Height - Form2->Image1->Height); mouse_is_down = 0; } //--------------------------------------------------------------------------- void __fastcall TForm4::Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if(mouse_is_down) { GetCursorPos(&mouse_end); int x_move = mouse_end.x-mouse_start.x; int y_move = mouse_end.y-mouse_start.y; //*************************************对自己图片位置的更改*************************************** Image1->Left += x_move; Image1->Top += y_move; if(Image1->Left>0) Image1->Left = 0; if(Image1->Top>0) Image1->Top = 0; if(Image1->Left<(ScrollBox1->Width-Image1->Width)) Image1->Left = (ScrollBox1->Width-Image1->Width); if(Image1->Top<(ScrollBox1->Height-Image1->Height)) Image1->Top = (ScrollBox1->Height-Image1->Height); mouse_start = mouse_end; //************************************对另一个图片位置的更改************************************** Form3->Image1->Left += x_move; Form3->Image1->Top += y_move; if(Form3->Image1->Left>0) Form3->Image1->Left = 0; if(Form3->Image1->Top>0) Form3->Image1->Top = 0; if(Form3->Image1->Left<(Form3->ScrollBox1->Width - Form3->Image1->Width)) Form3->Image1->Left = (Form3->ScrollBox1->Width - Form3->Image1->Width); if(Form3->Image1->Top<(Form3->ScrollBox1->Height - Form3->Image1->Height)) Form3->Image1->Top = (Form3->ScrollBox1->Height - Form3->Image1->Height); Form3->mouse_start = Form3->mouse_end; //************************************对另一个图片位置的更改************************************** Form2->Image1->Left += x_move; Form2->Image1->Top += y_move; if(Form2->Image1->Left>0) Form2->Image1->Left = 0; if(Form2->Image1->Top>0) Form2->Image1->Top = 0; if(Form2->Image1->Left<(Form2->ScrollBox1->Width - Form2->Image1->Width)) Form2->Image1->Left = (Form2->ScrollBox1->Width - Form2->Image1->Width); if(Form2->Image1->Top<(Form2->ScrollBox1->Height - Form2->Image1->Height)) Form2->Image1->Top = (Form2->ScrollBox1->Height - Form2->Image1->Height); Form2->mouse_start = Form2->mouse_end; } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void __fastcall TForm4:: find_the_line() { //显示降噪后的图片 int i,j; for(i=0 ; i<HANG ; i++) { for(j=0 ; j<LIE ; j++) { int r = Form2->ys[Form3->picture[i][j].type+1].r; int g = Form2->ys[Form3->picture[i][j].type+1].g; int b = Form2->ys[Form3->picture[i][j].type+1].b; Form2->Image1->Canvas->Pixels[j][i]=Graphics::TColor(RGB(r,g,b)); } } change = (int **)malloc(sizeof(int *)*5172); change1 = (int **)malloc(sizeof(int *)*5172); for(i=0 ; i<5172 ; i++) { change[i] = (int *)malloc(sizeof(int )*6573); change1[i] = (int *)malloc(sizeof(int )*6573); } for(i=0 ; i<Form3->HANG; i++) { for(j=0 ; j<Form3->LIE ; j++) { change1[i][j]= Form1->check(i,j); change[i][j] = 0; } } /* for(int i=0 ; i<HANG*LIE ; i++) { sum.push_back(0); regist_x.push_back(0); regist_y.push_back(0); } */ for(i=0 ; i<200000 ; i++) { regist_x[i] = 0; regist_y[i] = 0; sum[i] = 0; } for(i=1;i<=HANG-2;i++) for(j=1;j<=LIE-2;j++) { if(change1[i][j]==0) continue; if(change[i][j])continue; count1++;//用作计数的 regist_x[count1]=i; regist_y[count1]=j; change[i][j]=1; //此时的change是book dfs(i,j);} for(i=1;i<=count1;i++) if(maxx<sum[i]){ maxx=sum[i]; final=i; } for(i=1;i<=HANG-2;i++) for(j=1;j<=LIE-2;j++) change[i][j]=0; //change重置为0,在画最长的过程中依旧为book change[regist_x[final]][regist_y[final]]=1; change1[regist_x[final]][regist_y[final]]=2; //change1=2记录的是最长的线 redfs(regist_x[final],regist_y[final]); for(i=1;i<=HANG-2;i++) for(j=1;j<=LIE-2;j++) if(change1[i][j]!=2) change1[i][j]=0; //将最终海岸线文件显示到二进制文件里 for(i=0;i<HANG;i++) { for(j=0;j<LIE;j++) { if(change1[i][j]==2 ) { Image1->Canvas->Pixels[j][i]=Graphics::TColor(RGB(0,0,0)); TXT2 += 1; } else TXT2 += 0; } } } int tx,ty,top=1; //--------------------------------------------------------------------------- void __fastcall TForm4::dfs(int x,int y) { //定义一个方向数组 for(int k=0;k<=7;k++) { tx=x+next[k][0]; ty=y+next[k][1]; //判断是否越界 if(tx<1||tx>HANG-1||ty<1||ty>LIE-2) continue; if(change1[tx][ty]==1&&change[tx][ty]==0) //此时的change是book { sum[count1]++; //将每根线的线长存到sum数组中 change[tx][ty]=1; dfs(tx,ty); } } return; } //------------------------------------------------------------------------------- void __fastcall TForm4:: redfs(int x,int y) { //printf("i'm here"); //定义一个方向数组 for(int k=0;k<=7;k++) { tx=x+next[k][0]; ty=y+next[k][1]; //判断是否越界 if(tx<1||tx>HANG-1||ty<1||ty>LIE-1) continue; if(change1[tx][ty]>0&&change[tx][ty]==0) //此时的change是book { change[tx][ty]=1; change1[tx][ty]=2; redfs(tx,ty); } } return; } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #ifndef Unit6H #define Unit6H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Menus.hpp> #include <ComCtrls.hpp> #include <Grids.hpp> #include <ValEdit.hpp> #include <ADODB.hpp> #include <DB.hpp> #include <DBGrids.hpp> //--------------------------------------------------------------------------- class TForm6 : public TForm { __published: // IDE-managed Components TDataSource *DataSource1; TADOConnection *ADOConnection1; TADOQuery *ADOQuery1; TDBGrid *DBGrid1; TButton *Button2; void __fastcall Button2Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm6(TComponent* Owner); void __fastcall find(); }; //--------------------------------------------------------------------------- extern PACKAGE TForm6 *Form6; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit5.h" #include "Unit1.h" #include "Unit2.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm5 *Form5; //--------------------------------------------------------------------------- __fastcall TForm5::TForm5(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm5::Button1Click(TObject *Sender) { ADOTable1->Open(); ADOTable1->Append(); SYSTEMTIME t; GetLocalTime(&t); String mth = t.wMonth; String d = t.wDay; String h = t.wHour; String m = t.wMinute; String s = t.wSecond; String time_str = (String)t.wYear +"/"+ ((mth.Length()==1)?("0"+mth):mth) + "/" + ((d.Length()==1)?("0"+d):d) + " " + ((h.Length()==1)?("0"+h):h) + " : "+ ((m.Length()==1)?("0"+m):m) + " : "+ ((s.Length()==1)?("0"+s):s); ADOTable1->FieldValues["实验时间"] = time_str; ADOTable1->FieldValues["实验名称"] = Edit1->Text; ADOTable1->FieldValues["实验评价"] = ComboBox1->Text; ADOTable1->Post(); ADOTable1->Close(); Form1->In_SQL(); Form5->Visible = false; ADOTable2->Open(); ADOTable2->Append(); int x = Form1->ComboBox1->Text.ToInt(); ADOTable2->FieldValues["地物个数"] = x; String ssr[7] = {"1","2","3","4","5","6","7"}; for(int i=0 ; i<x ; i++) { ADOTable2->FieldValues["Ground_" + ssr[i]] = Form2->address[i]; ADOTable2->FieldValues["rule_" + ssr[i]] = Form2->stringg[i]; } ADOTable2->Post(); ADOTable2->Close(); Form5->Visible = false; } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit1.h" #include "Unit3.h" #include "Unit2.h" #include <fstream> #include <string.h> #include<time.h> #include "Unit4.h" #include "Unit5.h" #include "Unit6.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { Memo2->Lines->Append("asdfasdfasdf\n232323"); Edit1->SetTextBuf(""); Edit2->SetTextBuf("1125"); Edit3->SetTextBuf("1996"); ComboBox1->SetTextBuf(""); ComboBox2->SetTextBuf("4"); // Form1->Height = 160; Form1->Left = 900; Memo1->SetTextBuf(""); Panel4->Visible=false; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { if(OpenDialog1->Execute()) { String str; str=OpenDialog1->FileName; Edit1->SetTextBuf(str.c_str()); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { //按钮按下,主页面信息传入从页面。 if(Edit1->Text=="" || ComboBox2->Text=="" || Edit2->Text=="" || Edit3->Text=="" || ComboBox5->Text=="") { Application->MessageBoxA("信息填写不完整,请核对后重试","系统提示",MB_ICONWARNING); return; } Form3->ADDRESS = Edit1->Text; Form3->HANG = Edit2->Text.ToInt(); Form3->LIE = Edit3->Text.ToInt(); Form3->X_BODUAN = ComboBox2->Text.ToInt(); Form3->MODEL = ComboBox5->Text; Memo2->Lines->Append(Form3->ADDRESS); Memo2->Lines->Append(Form3->HANG); Memo2->Lines->Append(Form3->LIE); Memo2->Lines->Append(Form3->X_BODUAN); Memo2->Lines->Append(Form3->MODEL); // Label11->Visible = true; Form3->show_the_picture(); Form3->Show(); // Label11->Visible = false; /* Form1->Left = 1069; Form3->Left = 215 ; Form1->Height=900; Form1->Top=142; */ BitBtn1->Enabled = true; Form3->Repaint(); //------------------------------------------------------------------------------ //开始绘图 } //--------------------------------------------------------------------------- void __fastcall TForm1::BitBtn1Click(TObject *Sender) { Form2->ADDRESS = Edit1->Text; Form2->D = ComboBox1->Text.ToInt(); Form2->X = ComboBox2->Text.ToInt(); Form2->AMOUNT = ComboBox3->Text.ToInt(); Form2->HANG = Edit2->Text.ToInt(); Form2->LIE = Edit3->Text.ToInt(); Form2->Image1->Height = Form2->HANG; Form2->Image1->Width = Form2->LIE; char * TXT = Form2->TXT1.c_str(); if(Form2->TXT1 != "") { for(int i=0 ; i<Form2->HANG ; i++) { for(int j=0 ; j<Edit3->Text.ToInt() ; j++) { int r= Form2->ys[TXT[i*(Form2->LIE) + j]-'0'+3].r; int g= Form2->ys[TXT[i*(Form2->LIE) + j]-'0'+3].g; int b= Form2->ys[TXT[i*(Form2->LIE) + j]-'0'+3].b; Form2->Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(r,g,b)); } } Memo2->SetTextBuf("OK"); Form2->Show(); return ; } if(Form1->ComboBox1->Text == "" || Form1->ComboBox3->Text == "") { Application->MessageBoxA("信息填写不完整,请核对后重试","系统提示",MB_ICONWARNING); return; } String str[I_D] = {"一","二","三","四","五","六"}; for(int i=0 ; i<ComboBox1->Text.ToInt() ; i++) { if(Form2->address[i] == "") { String t_sr = "第"+str[i]+"类地物样本未录入,请核对后重试"; Application->MessageBoxA(t_sr.c_str(),"系统提示",MB_ICONWARNING); return; } } Label9->Visible = false; // Form2->Show(); Form2->hanshu(); Form2->Image1->Left = Form3->Image1->Left; Form2->Image1->Top = Form3->Image1->Top; Form2->Show(); //*******************************安排所有窗口位置*********************** Form3->Top = 33; Form3->Left = 69; Form2->Top = 33; Form2->Left = 789; Form2->Repaint(); } //--------------------------------------------------------------------------- void __fastcall TForm1::BitBtn3Click(TObject *Sender) { if(ComboBox4->Text == "") { Application->MessageBoxA("“样本选择”不能为空!","系统提示",MB_ICONWARNING); return ; } if(OpenDialog1->Execute()) { int x = ComboBox4->Text.ToInt(); Edit4->SetTextBuf(OpenDialog1->FileName.c_str()); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button3Click(TObject *Sender) { if(Edit4->Text=="") { Application->MessageBoxA("请选择保存路径!","系统提示",MB_ICONWARNING); return ; } int number = ComboBox4->Text.ToInt(); if(Form2->address[number-1]!="") { int xxx = Application->MessageBoxA("该类样本已存在,确认将其覆盖?","系统提示",MB_YESNO); if(xxx==7)return ; } Form2->address[number-1] = Edit4->Text; String str[I_D] = {"一","二","三","四","五","六"}; String ts = "第"+str[number-1]+"类地物样本已录入!"; Label9->SetTextBuf(ts.c_str()); Label9->Visible = true; ComboBox4->SetTextBuf(""); Edit4->SetTextBuf(""); } //--------------------------------------------------------------------------- void __fastcall TForm1::RadioButton2Click(TObject *Sender) { Panel1->Visible = false; Panel4->Visible = true; Panel4->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::RadioButton1Click(TObject *Sender) { Panel1->Visible = true; Panel1->Enabled = true; Panel4->Visible = false; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button4Click(TObject *Sender) { if(Form3->select_time==0) { Form3->select_time = 1; Button4->SetTextBuf("确认选择"); Button5->Enabled = false; Button6->Enabled = false; Label11->Enabled = false; Edit5->Enabled = false; } else { Form3->select_time = 0; Button4->SetTextBuf("选择地物"); Form3->select_to_red(); Form3->select_point.clear(); Memo1->SetTextBuf(str_int(Form3->amount_of_yb).c_str()); Button5->Enabled = true; Button6->Enabled = true; Label11->Enabled = true; Edit5->Enabled = true; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender) { if(ComboBox4->Text == "") { Application->MessageBoxA("“样本选择”不能为空!","系统提示",MB_ICONWARNING); return ; } if(SaveDialog1->Execute()) { String file_str = SaveDialog1->FileName; if(FileExists(file_str.c_str())) { Application->MessageBoxA("文件已存在!","系统提示",MB_ICONWARNING); return ; } Edit5->SetTextBuf(file_str.c_str()); int number = ComboBox4->Text.ToInt(); ofstream fout(file_str.c_str()); fout.close(); // FileCreate(file_str.c_str()); } } //--------------------------------------------------------------------------- void __fastcall TForm1::BitBtn2Click(TObject *Sender) { if(ComboBox4->Text == "") { Application->MessageBoxA("“样本选择”不能为空!","系统提示",MB_ICONWARNING); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button6Click(TObject *Sender) { if(Edit5->Text=="") { Application->MessageBoxA("请选择保存路径!","系统提示",MB_ICONWARNING); return ; } String str[I_D] = {"一","二","三","四","五","六"}; int number = ComboBox4->Text.ToInt(); if(Form2->address[number-1]!="") { int xxx = Application->MessageBoxA("该类样本已存在,确认将其覆盖?","系统提示",MB_YESNO); if(xxx==7)return ; } Form2->address[number-1] = Edit5->Text; String ts = "第"+str[number-1]+"类地物样本已录入!"; Label9->SetTextBuf(ts.c_str()); Label9->Visible = true; //准备下一次样本选取 Edit5->SetTextBuf(""); Form3->back_to_photo(); Form3->amount_of_yb = 0; Button5->Enabled = false; Label11->Enabled = false; Edit5->Enabled = false; Button6->Enabled = false; ComboBox4->SetTextBuf(""); Memo1->SetTextBuf(""); //将所选样本写入文件 Form3->write_point_to_file(Form2->address[number-1]); } //--------------------------------------------------------------------------- void __fastcall TForm1::ComboBox3Change(TObject *Sender) { Form3->D_YANGBEN = ComboBox3->Text.ToInt(); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button7Click(TObject *Sender) { Form3->go_back(); Form3->select_time = 0; Button4->SetTextBuf("选择地物"); Form3->select_point.clear(); Button5->Enabled = true; Button6->Enabled = true; Label11->Enabled = true; Edit5->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::ComboBox4Change(TObject *Sender) { Label9->Visible = false; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button8Click(TObject *Sender) { sea_v.clear(); String ss="请确认信息: 您选择了 "; for(int i=0 ; i<CheckListBox1->Count ; i++) { if(CheckListBox1->Checked[i]) { sea_v.push_back(i+1); ss+=1+i; ss+="、"; } } ss.Delete(ss.Length()-1,ss.Length()-1); ss+=" 地物为海洋地物"; int Mxx = Application->MessageBox(ss.c_str(),"系统提示",MB_YESNO); if(Mxx==7) { sea_v.clear(); return; } Button9->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button9Click(TObject *Sender) { //设置Form4位置等 int h = Edit2->Text.ToInt(); int w = Edit3->Text.ToInt(); Form4->HANG = h; Form4->LIE = w; Form4->Image1->Height = h; Form4->Image1->Width = w; Form4->Image1->Left = Form3->Image1->Left; Form4->Image1->Top = Form3->Image1->Top; Memo2->Lines->Append(h); Memo2->Lines->Append(w); //判断是否为数据库模式 if(Form4->TXT2 != "") { char * st = Form4->TXT2.c_str(); for(int i=0 ; i<h ; i++) { for(int j=0 ; j<w ; j++) { if(st[i*w + j] == '1') Form4->Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(0,0,0)); else Form4->Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(255,255,255)); } } Form4->Show(); return ; } //整体分成两类 ······ for(int i=1 ; i<h-1 ; i++) { for(int j=1 ; j<w-1 ; j++) { Form3->picture[i][j].type = is_sea(i,j); } } //降噪 int x_go[8] = {1,-1,0,0,1,1,-1,-1}; int y_go[8] = {0,0,1,-1,1,-1,1,-1}; int x1_go[24] = {-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,0,0,0,0,1,1,1,1,1,2,2,2,2,2}; int y1_go[24] = {-2,-1,0,1,2,-2,-1,0,1,2,-2,-1,1,2,-2,-1,0,1,2,-2,-1,0,1,2}; int x2_go[48] = {-3,-3,-3,-3,-3,-3,-3,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3}; int y2_go[48] = {-3,-2,-1,0,1,2,3,-3,-2,-1,0,1,2,3,-3,-2,-1,0,1,2,3,-3,-2,-1,1,2,3,-3,-2,-1,0,1,2,3,-3,-2,-1,0,1,2,3,-3,-2,-1,0,1,2,3}; int x3_go[80] = {-4,-4,-4,-4,-4,-4,-4,-4,-4,-3,-3,-3,-3,-3,-3,-3,-3,-3,-2,-2,-2,-2,-2,-2,-2,-2,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4}; int y3_go[80] = {-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,1,2,3,4,-4,-3,-2,-1,0,1, 2,3,4,-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,0,1,2,3,4,-4,-3,-2,-1,0,1,2,3,4}; for(int time=1;time<=10;time++) { int flag=14; for(int i=2 ;i<Form3->HANG-2;i++) for(int j=2 ;j<Form3->LIE-2;j++) { int x_,y_,f; int diw[2] = {0,0}; for(int f=0 ; f<24 ; f++) { int x_ = i+x1_go[f]; int y_ = j+y1_go[f]; int number = Form3->picture[x_][y_].type; diw[number]++; if(diw[number]==flag) { Form3->picture[i][j].type = number; } } } for(int i=Form3->HANG-3 ;i>=2;i--) for(int j=Form3->LIE-3;j>=2 ;j--) { int x_,y_,f; int diw[2]={0,0}; memset(diw,0,sizeof(diw)); for(int f=0 ; f<24 ; f++) { int x_ = i+x1_go[f]; int y_ = j+y1_go[f]; int number = Form3->picture[x_][y_].type; diw[number]++; if(diw[number]==flag) { Form3->picture[i][j].type = number; } } } } //划线 Form4->find_the_line(); Form4->Show(); } int __fastcall TForm1::check(int x,int y) { int number_1 = 0; int number_2 = 0; int x_go[8] = {0,0,1,-1,1,1,-1,-1}; int y_go[8] = {1,-1,0,0,1,-1,-1,1}; number_1 = Form3->picture[x][y].type; if(number_1) { for(int i=0 ; i<8 ; i++) { int xx = x+x_go[i]; int yy = y+y_go[i]; if(xx<0 || xx>=Form3->HANG) continue; if(yy<0 || yy>=Form3->LIE) continue; number_2 = Form3->picture[xx][yy].type; if(number_2 ==0) return 1; } } return 0; } int __fastcall TForm1::is_sea(int x,int y) { int amount = sea_v.size(); for(int i=0 ; i<amount ; i++) { if(Form3->picture[x][y].type == sea_v[i]) return 1; } return 0; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button10Click(TObject *Sender) { for(int i=0 ; i<Form3->HANG ; i++) { for(int j=0 ; j<Form3->LIE ; j++) { int r = Form2->ys[Form3->picture[i][j].type+4].r; int g = Form2->ys[Form3->picture[i][j].type+4].g; int b = Form2->ys[Form3->picture[i][j].type+4].b; Form2->Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(r,g,b)); } } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button11Click(TObject *Sender) { Form5->Show(); Form5->Visible = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::ComboBox1Change(TObject *Sender) { //*******************************checklistbox元素添加******************* ComboBox4->Clear(); CheckListBox1->Clear(); int yybb = 1; for(int i=0 ; i<ComboBox1->Text.ToInt() ; i++) { ComboBox4->Items->Add(str_int(yybb)); CheckListBox1->Items->Add(str_int(yybb)); yybb++; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button12Click(TObject *Sender) { Form6->find(); Form6->Show(); Form6->Visible = true; Button9->Enabled = true; } //--------------------------------------------------------------------------- void __fastcall TForm1::In_SQL() { ADOTable1->Open(); ADOTable1->Append(); ADOTable1->FieldValues["文件路径"] = Edit1->Text; ADOTable1->FieldValues["行数"] = Edit2->Text.ToInt(); ADOTable1->FieldValues["列数"] = Edit3->Text.ToInt(); ADOTable1->FieldValues["波段个数"] = ComboBox2->Text.ToInt(); ADOTable1->FieldValues["图片格式"] = ComboBox5->Text; ADOTable1->FieldValues["样本个数"] = ComboBox3->Text.ToInt(); ADOTable1->FieldValues["地物个数"] = ComboBox1->Text.ToInt(); ADOTable1->FieldValues["区分地物"] = Form2->TXT1; ADOTable1->FieldValues["海岸线"] = Form4->TXT2; ADOTable1->Post(); ADOTable1->Close(); } void __fastcall TForm1::select_from_SQL(String str) { String select_str = "select * from dbo.history where 实验编号 = " + str; ADOQuery1->Close(); ADOQuery1->SQL->Clear(); ADOQuery1->SQL->Add(select_str); ADOQuery1->Open(); Edit1->Text = ADOQuery1->FieldByName("文件路径")->Value; Edit2->Text = ADOQuery1->FieldByName("行数")->Value; Edit3->Text = ADOQuery1->FieldByName("列数")->Value; ComboBox2->Text = ADOQuery1->FieldByName("波段个数")->Value; ComboBox5->Text = ADOQuery1->FieldByName("图片格式")->Value; ComboBox3->Text = ADOQuery1->FieldByName("样本个数")->Value; ComboBox1->Text = ADOQuery1->FieldByName("地物个数")->Value; Form2->TXT1 = ADOQuery1->FieldByName("区分地物")->Value; Form4->TXT2 = ADOQuery1->FieldByName("海岸线")->Value; //将Form3的对应数据传入 Form3->ADDRESS = Edit1->Text; Form3->HANG = Edit2->Text.ToInt(); Form3->LIE = Edit3->Text.ToInt(); Form3->X_BODUAN = ComboBox2->Text.ToInt(); Form3->MODEL = ComboBox5->Text; //将Form2的对应数据传入 Form2->ADDRESS = Edit1->Text; Form2->D = ComboBox1->Text.ToInt(); Form2->X = ComboBox2->Text.ToInt(); Form2->AMOUNT = ComboBox3->Text.ToInt(); Form2->HANG = Edit2->Text.ToInt(); Form2->LIE = Edit3->Text.ToInt(); Form2->Image1->Height = Form2->HANG; Form2->Image1->Width = Form2->LIE; Form2->Image1->Left = Form3->Image1->Left; Form2->Image1->Top = Form3->Image1->Top; } void __fastcall TForm1::RadioButton3Click(TObject *Sender) { Panel1->Enabled = false; Panel4->Enabled = false; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button13Click(TObject *Sender) { Form2->Close(); Form3->Close(); Form4->Close(); Form5->Close(); Form6->Close(); } //--------------------------------------------------------------------------- <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include<math.h> #include<stdio.h> #include<stdlib.h> #include<cstring> #define INIT_SIZE 10000 //存储空间初始分配量 #define INCREMENT 10 //存储空间分配增量 static int LINE; static int SAMPLE; static int nodeID; static int toClass; static int nowClass; static int spoint; static int file_type; static AnsiString name; static AnsiString netname; static AnsiString outname; static int node[2600][2600]; static int af[2600][2600]; //生成节点网络文件所需参数 static int flag_max=0; static AnsiString netoutname; static int adjacent[1000][1000]={0}; //数组的范围应该大于等于最大值+5 ??(是因为类别为1-4?) static int adjacent_right[1000][1000]={0}; static int sideNum=0; FILE *fp5; #include "Unit1.h" //边缘点判断所需形参 typedef struct{ int r; //迷宫中r行c列的位置 //!!!!!!敲黑板!!因为读取输出像素点是xy格式的,所以maze.adr[列值][行值] int c; }PostType; typedef struct{ PostType seat;//当前坐标 int di; //往下一坐标的方向 }SElemType; //栈内元素类型 typedef struct{ SElemType* base; SElemType* top; int stackSize; }Stack; //栈类型 void InitStack(Stack &S){ //构造空栈S S.base=(SElemType*)malloc(INIT_SIZE *sizeof(SElemType)); if(!S.base) exit(OVERFLOW);//存储分配失败 S.top=S.base; S.stackSize=INIT_SIZE; } int StackEmpty(Stack S){ //判断空栈 if(S.top==S.base) return 1; return 0; } void Push(Stack &S,SElemType e){//入栈 if(S.top-S.base >=S.stackSize){//栈满,加空间 S.base=(SElemType *)realloc(S.base,(S.stackSize+INCREMENT)*sizeof(SElemType)); if(!S.base) exit(OVERFLOW); //存储分配失败 S.top=S.base+S.stackSize; S.stackSize+=INCREMENT; } *S.top++=e; } int Pop(Stack &S,SElemType &e){//出栈 if(S.top==S.base) return 0; e=*--S.top; return 1; } typedef struct{ int r; int c; int adr[2600][2600]; }MazeType; //迷宫类型 MazeType maze; //定义全局自定义变量迷宫maze MazeType maze1; PostType NextPos(PostType &curpos,int i){ //探索下一位置并返回下一位置(cpos)的坐标 PostType cpos; cpos=curpos; switch(i){ //1.2.3分别表示右、下、左、上方向 case 1 : cpos.r+=1; break; case 2 : cpos.c+=1; break; case 4 : cpos.c-=1; break; case 3 : cpos.r-=1; break; default: exit(0); } return cpos; } //遍历斑块并修改 void MazePath(MazeType &maze,PostType start,int flag,int toflag){ Stack S; PostType curpos; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]==flag){//当前位置可以通过, maze.adr[curpos.r][curpos.c]=-1;//留下足迹 af[curpos.r][curpos.c]=toflag;//标记所有需要修改的节点中的点 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } //生成图像节点网络文件所需方法(重复方法名前加入net前缀) //获取斑块信息并序列化斑块 void netMazePath(MazeType &maze,PostType start,int number,int flag){ int count_all=0; //记录当前斑块的所有点个数 Stack S; PostType curpos; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]==flag){//当前位置可以通过, count_all++; maze.adr[curpos.r][curpos.c]=number+flag_max;//留下足迹 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); fprintf(fp5, "%d\n",count_all);//整合信息里的点个数 } //计算总斑块数用 void MazePath1(MazeType &maze,PostType start,int number,int flag){ int count_all=0; //记录当前斑块的所有点个数 Stack S; PostType curpos; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]==flag){//当前位置可以通过, count_all++; maze.adr[curpos.r][curpos.c]=number+flag_max;//留下足迹 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); } int if_adjacent(MazeType &maze,int x,int y,int number,int flag){ int ecount=0; if(x+1<LINE){ if(maze.adr[x+1][y] != flag&&maze.adr[x+1][y] !=(number+flag)){ if(maze.adr[x+1][y]>flag_max+number){ //这表示的是下邻接,x表示的行值,adjacent_right应该与adjacent_below互换(这里互换了写入的1和2,而没互换数组名) adjacent[flag-flag_max][maze.adr[x+1][y]-number-flag_max]++; adjacent_right[flag-flag_max][maze.adr[x+1][y]-number-flag_max]++; } else{ adjacent[flag-flag_max][maze.adr[x+1][y]-flag_max]++; adjacent_right[flag-flag_max][maze.adr[x+1][y]-flag_max]++; } ecount++; } } if(y+1<SAMPLE){ if(maze.adr[x][y+1] != flag&&maze.adr[x][y+1] !=(number+flag)){ if(maze.adr[x][y+1]>flag_max+number){ adjacent[flag-flag_max][maze.adr[x][y+1]-number-flag_max]++; } else{ adjacent[flag-flag_max][maze.adr[x][y+1]-flag_max]++; } ecount++; } } return ecount; } void AdjacentPath(MazeType &maze,PostType start,int number,int flag){ int count_edge = 0; Stack S; PostType curpos; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]==flag){//当前位置可以通过, count_edge+=if_adjacent(maze,curpos.r,curpos.c,number,flag); maze.adr[curpos.r][curpos.c]=flag+number;//留下足迹 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); fprintf(fp5, "%d\n",count_edge); // sideNum+=count_edge; for(int i=1;i<=number;i++){ if(adjacent[flag-flag_max][i]!=0){ if(adjacent_right[flag-flag_max][i]!=0){ fprintf(fp5, "%d,",flag-flag_max); fprintf(fp5, "%d,",i); fprintf(fp5, "%d,",2); fprintf(fp5, "%d\n",adjacent_right[flag-flag_max][i]/2); } if(adjacent[flag-flag_max][i]-adjacent_right[flag-flag_max][i]>0) { fprintf(fp5, "%d,",flag-flag_max); fprintf(fp5, "%d,",i); fprintf(fp5, "%d,",1); fprintf(fp5, "%d\n",adjacent[flag-flag_max][i]/2-adjacent_right[flag-flag_max][i]/2); } } } } //计算总点数用 void AdjacentPath1(MazeType &maze,PostType start,int number,int flag){ int count_edge = 0; Stack S; PostType curpos; SElemType e; InitStack(S); curpos=start; //设置"当前位置"为"入口位置" //探索第一步 do{ if(maze.adr[curpos.r][curpos.c]==flag){//当前位置可以通过, count_edge+=if_adjacent(maze,curpos.r,curpos.c,number,flag); maze.adr[curpos.r][curpos.c]=flag+number;//留下足迹 e.seat=curpos; e.di=1; Push(S,e); //加入路径 curpos=NextPos(curpos,1); //下一位置是当前位置的东邻 } else{ //当前位置不通 if(!StackEmpty(S)){ Pop(S,e); if(e.di <4){ e.di++;//换下一个方向探索 Push(S,e); curpos=NextPos(e.seat,e.di);//设定当前位置是该新方向上的相 } } } }while(!StackEmpty(S)); sideNum+=count_edge; } //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { if(OpenDialog1->Execute()) name=OpenDialog1->FileName; } //--------------------------------------------------------------------------- void __fastcall TForm1::Button2Click(TObject *Sender) { if(OpenDialog2->Execute()){ netname=OpenDialog2->FileName; } } //--------------------------------------------------------------------------- //---------------------Button3实现输出修改后的图像文件 void __fastcall TForm1::Button3Click(TObject *Sender) { if(file_type==1){ //初始化二维数组函数 memset(node,-1,sizeof(node)); memset(af,-1,sizeof(af)); //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } FILE *fp; unsigned char idata;//用来读取本行数据 maze.r=SAMPLE;maze.c=LINE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)%SAMPLE][(count-1)/SAMPLE]=idata; } fclose(fp); } //检验原图数据是否正确读取 /*FILE *ff; ff = fopen("d://ff.txt","w+"); for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ fprintf(ff,"%d ",maze.adr[j][i]); } fprintf(ff,"\n"); } */ //读取节点网络文件中的数据 FILE *fpc; //FILE *fpt; //fpt = fopen("d://tt.txt","w+"); fpc = fopen(netname.c_str(),"r+"); int IDnums,relnums,bnums;//节点总数,关系数,总边数 int pro,ID,tolnums;//属性个数(2个),节点ID,当前节点总点数。(其中nowclass和起始点位置spoint在代码头已定义) fscanf(fpc,"%d%d%d",&IDnums,&relnums,&bnums); //fprintf(fpt,"%d %d %d\n",IDnums,relnums,bnums); for(int i=0;i<IDnums;i++){ fscanf(fpc,"%d%d%d%d%d",&pro,&toClass,&spoint,&ID,&tolnums); node[(spoint-1)%SAMPLE][(spoint-1)/SAMPLE]=toClass; //fprintf(fpt,"%d %d %d %d %d\n",pro,toClass,spoint,ID,tolnums); } //fprintf(fpt,"%d %d\n",maze.adr[65][0],node[65][0]); fclose(fpc); //找出节点类型改变的斑块 PostType start; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ /*if(i*SAMPLE+j==66) { fprintf(fpt," %d",af[65][0]); int a; a=65; } */ if(node[j][i] != -1){ //只寻找并比较一个节点的第一个点 if(maze.adr[j][i]!=node[j][i]){ start.r=j; start.c=i; toClass=node[j][i]; nowClass=maze.adr[j][i]; MazePath(maze,start,nowClass,toClass);//修改当前节点 //Memo1->Lines->Append(i*SAMPLE+j); } } } } for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(af[j][i]!=-1 && maze.adr[j][i]==-1) maze.adr[j][i]=af[j][i]; } } //fprintf(fpt,"%d %d %d%d%d\n",maze.adr[43][0],node[43][0],maze.adr[44][0],maze.adr[45][0],maze.adr[46][0]); //fclose(fpt); //输出矢量二进制文件 if(Edit3->Text == "") { MessageBox(NULL,"请选择输出文件路径!", "Error",MB_ICONERROR); } FILE *fptwo; char a=1,b=2,c=3,d=4,e=0; fptwo=fopen(Edit3->Text.c_str(),"wb");//打开文件 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]==1) fwrite(&a,1,1,fptwo); if(maze.adr[j][i]==2) fwrite(&b,1,1,fptwo); if(maze.adr[j][i]==3) fwrite(&c,1,1,fptwo); if(maze.adr[j][i]==4) fwrite(&d,1,1,fptwo); if(maze.adr[j][i]==0) fwrite(&e,1,1,fptwo); } } fclose(fptwo); MessageBox(NULL,"成功生成图像文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } if(file_type==2){ //初始化二维数组函数 memset(node,-1,sizeof(node)); memset(af,-1,sizeof(af)); //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } FILE *fp; unsigned short idata;//用来读取本行数据 maze.r=SAMPLE;maze.c=LINE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)%SAMPLE][(count-1)/SAMPLE]=idata; } fclose(fp); } //检验原图数据是否正确读取 /*FILE *ff; ff = fopen("d://ff.txt","w+"); for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ fprintf(ff,"%d ",maze.adr[j][i]); } fprintf(ff,"\n"); } */ //读取节点网络文件中的数据 FILE *fpc; //FILE *fpt; //fpt = fopen("d://tt.txt","w+"); fpc = fopen(netname.c_str(),"r+"); int IDnums,relnums,bnums;//节点总数,关系数,总边数 int pro,ID,tolnums;//属性个数(2个),节点ID,当前节点总点数。(其中nowclass和起始点位置spoint在代码头已定义) fscanf(fpc,"%d%d%d",&IDnums,&relnums,&bnums); //fprintf(fpt,"%d %d %d\n",IDnums,relnums,bnums); for(int i=0;i<IDnums;i++){ fscanf(fpc,"%d%d%d%d%d",&pro,&toClass,&spoint,&ID,&tolnums); node[(spoint-1)%SAMPLE][(spoint-1)/SAMPLE]=toClass; //fprintf(fpt,"%d %d %d %d %d\n",pro,toClass,spoint,ID,tolnums); } //fprintf(fpt,"%d %d\n",maze.adr[65][0],node[65][0]); fclose(fpc); //找出节点类型改变的斑块 PostType start; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ /*if(i*SAMPLE+j==66) { fprintf(fpt," %d",af[65][0]); int a; a=65; } */ if(node[j][i] != -1){ //只寻找并比较一个节点的第一个点 if(maze.adr[j][i]!=node[j][i]){ start.r=j; start.c=i; toClass=node[j][i]; nowClass=maze.adr[j][i]; MazePath(maze,start,nowClass,toClass);//修改当前节点 //Memo1->Lines->Append(i*SAMPLE+j); } } } } for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(af[j][i]!=-1 && maze.adr[j][i]==-1) maze.adr[j][i]=af[j][i]; } } //fprintf(fpt,"%d %d %d%d%d\n",maze.adr[43][0],node[43][0],maze.adr[44][0],maze.adr[45][0],maze.adr[46][0]); //fclose(fpt); //输出矢量二进制文件 if(Edit3->Text == "") { MessageBox(NULL,"请选择输出文件路径!", "Error",MB_ICONERROR); } FILE *fptwo; char a=1,b=2,c=3,d=4,e=0; fptwo=fopen(Edit3->Text.c_str(),"wb");//打开文件 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]==1) fwrite(&a,1,1,fptwo); if(maze.adr[j][i]==2) fwrite(&b,1,1,fptwo); if(maze.adr[j][i]==3) fwrite(&c,1,1,fptwo); if(maze.adr[j][i]==4) fwrite(&d,1,1,fptwo); if(maze.adr[j][i]==0) fwrite(&e,1,1,fptwo); } } fclose(fptwo); MessageBox(NULL,"成功生成图像文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } if(file_type==4){ //初始化二维数组函数 memset(node,-1,sizeof(node)); memset(af,-1,sizeof(af)); //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } FILE *fp; unsigned int idata;//用来读取本行数据 maze.r=SAMPLE;maze.c=LINE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)%SAMPLE][(count-1)/SAMPLE]=idata; } fclose(fp); } //检验原图数据是否正确读取 /*FILE *ff; ff = fopen("d://ff.txt","w+"); for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ fprintf(ff,"%d ",maze.adr[j][i]); } fprintf(ff,"\n"); } */ //读取节点网络文件中的数据 FILE *fpc; //FILE *fpt; //fpt = fopen("d://tt.txt","w+"); fpc = fopen(netname.c_str(),"r+"); int IDnums,relnums,bnums;//节点总数,关系数,总边数 int pro,ID,tolnums;//属性个数(2个),节点ID,当前节点总点数。(其中nowclass和起始点位置spoint在代码头已定义) fscanf(fpc,"%d%d%d",&IDnums,&relnums,&bnums); //fprintf(fpt,"%d %d %d\n",IDnums,relnums,bnums); for(int i=0;i<IDnums;i++){ fscanf(fpc,"%d%d%d%d%d",&pro,&toClass,&spoint,&ID,&tolnums); node[(spoint-1)%SAMPLE][(spoint-1)/SAMPLE]=toClass; //fprintf(fpt,"%d %d %d %d %d\n",pro,toClass,spoint,ID,tolnums); } //fprintf(fpt,"%d %d\n",maze.adr[65][0],node[65][0]); fclose(fpc); //找出节点类型改变的斑块 PostType start; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ /*if(i*SAMPLE+j==66) { fprintf(fpt," %d",af[65][0]); int a; a=65; } */ if(node[j][i] != -1){ //只寻找并比较一个节点的第一个点 if(maze.adr[j][i]!=node[j][i]){ start.r=j; start.c=i; toClass=node[j][i]; nowClass=maze.adr[j][i]; MazePath(maze,start,nowClass,toClass);//修改当前节点 //Memo1->Lines->Append(i*SAMPLE+j); } } } } for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(af[j][i]!=-1 && maze.adr[j][i]==-1) maze.adr[j][i]=af[j][i]; } } //fprintf(fpt,"%d %d %d%d%d\n",maze.adr[43][0],node[43][0],maze.adr[44][0],maze.adr[45][0],maze.adr[46][0]); //fclose(fpt); //输出矢量二进制文件 if(Edit3->Text == "") { MessageBox(NULL,"请选择输出文件路径!", "Error",MB_ICONERROR); } FILE *fptwo; char a=1,b=2,c=3,d=4,e=0; fptwo=fopen(Edit3->Text.c_str(),"wb");//打开文件 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[j][i]==1) fwrite(&a,1,1,fptwo); if(maze.adr[j][i]==2) fwrite(&b,1,1,fptwo); if(maze.adr[j][i]==3) fwrite(&c,1,1,fptwo); if(maze.adr[j][i]==4) fwrite(&d,1,1,fptwo); if(maze.adr[j][i]==0) fwrite(&e,1,1,fptwo); } } fclose(fptwo); MessageBox(NULL,"成功生成图像文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit1Change(TObject *Sender) { if(Edit1->Text == ""){ LINE = 0; } else{ LINE = StrToInt(Edit1->Text); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit2Change(TObject *Sender) { if(Edit2->Text == ""){ SAMPLE = 0; } else{ SAMPLE = StrToInt(Edit2->Text); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button4Click(TObject *Sender) { if(OpenDialog3->Execute()){ outname=OpenDialog3->FileName; Edit3->Text = outname; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button5Click(TObject *Sender) { if(OpenDialog4->Execute()){ netoutname=OpenDialog4->FileName; Edit4->Text = netoutname; } } //--------------------------------------------------------------------------- void __fastcall TForm1::Button6Click(TObject *Sender) { //一字节读取 unsigned char idata; if(file_type==1){ //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } PostType start; int flag; //记录当前斑块的类型 FILE *fp; unsigned char idata;//用来读取本行数据 maze.r=LINE;maze.c=SAMPLE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata; maze1.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata;//计算总斑块数和总点数用 if(flag_max<idata) flag_max=idata; } fclose(fp); } //生成总斑块数 int number1=0;//记录当前斑块的序号 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]<=flag_max && maze1.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; MazePath1(maze1,start,number1,flag);//此方法后maze1被序列化 (5-107) } } } //生成总点数 int seq1=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]==seq1+flag_max&& maze1.adr[i][j]!=flag_max){ if(seq1<=number1){ seq1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; AdjacentPath1(maze1,start,number1,flag); } } } } //遍历斑块,输出斑块信息并序列化斑块 fp5=fopen(Edit4->Text.c_str(),"w"); fprintf(fp5, "%d\t",number1); //节点数 fprintf(fp5, "%d\t",2); //关系数 fprintf(fp5, "%d\n",sideNum);//边数 int number = 0; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]<=flag_max && maze.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number++; fprintf(fp5, "%d ",2); fprintf(fp5, "%d ",maze.adr[i][j]);//class值 fprintf(fp5, "%d ",i* SAMPLE+j+1);//起始点号 fprintf(fp5, "%d ",number);//斑块id ,点个数信息的记录在MazePath方法里 flag=maze.adr[i][j]; start.r=i;start.c=j; netMazePath(maze,start,number,flag);//此方法后maze被序列化 (5-107) } } } // 关系信息 fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\t",1);fprintf(fp5, "%d\t",0); fprintf(fp5, "%d\n",0); fprintf(fp5, "%d\t",2); fprintf(fp5, "%d\t",0);fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\n",0); //提取斑块间的邻接路径 int seq=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]==seq+flag_max&& maze.adr[i][j]!=flag_max){ if(seq<=number){ fprintf(fp5, "%d,",-1); fprintf(fp5, "%d,",seq); seq++; flag=maze.adr[i][j]; start.r=i;start.c=j; AdjacentPath(maze,start,number,flag); } } } } fclose(fp5); MessageBox(NULL,"成功生成节点网络文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } //二字节读取 unsigned short idata; if(file_type==2){ //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } PostType start; int flag; //记录当前斑块的类型 FILE *fp; unsigned short idata;//用来读取本行数据 maze.r=LINE;maze.c=SAMPLE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata; maze1.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata;//计算总斑块数和总点数用 if(flag_max<idata) flag_max=idata; } fclose(fp); } //生成总斑块数 int number1=0;//记录当前斑块的序号 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]<=flag_max && maze1.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; MazePath1(maze1,start,number1,flag);//此方法后maze1被序列化 (5-107) } } } //生成总点数 int seq1=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]==seq1+flag_max&& maze1.adr[i][j]!=flag_max){ if(seq1<=number1){ seq1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; AdjacentPath1(maze1,start,number1,flag); } } } } //遍历斑块,输出斑块信息并序列化斑块 fp5=fopen(Edit4->Text.c_str(),"w"); fprintf(fp5, "%d\t",number1); //节点数 fprintf(fp5, "%d\t",2); //关系数 fprintf(fp5, "%d\n",sideNum);//边数 int number = 0; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]<=flag_max && maze.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number++; fprintf(fp5, "%d ",2); fprintf(fp5, "%d ",maze.adr[i][j]);//class值 fprintf(fp5, "%d ",i* SAMPLE+j+1);//起始点号 fprintf(fp5, "%d ",number);//斑块id ,点个数信息的记录在MazePath方法里 flag=maze.adr[i][j]; start.r=i;start.c=j; netMazePath(maze,start,number,flag);//此方法后maze被序列化 (5-107) } } } // 关系信息 fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\t",1);fprintf(fp5, "%d\t",0); fprintf(fp5, "%d\n",0); fprintf(fp5, "%d\t",2); fprintf(fp5, "%d\t",0);fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\n",0); //提取斑块间的邻接路径 int seq=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]==seq+flag_max&& maze.adr[i][j]!=flag_max){ if(seq<=number){ fprintf(fp5, "%d,",-1); fprintf(fp5, "%d,",seq); seq++; flag=maze.adr[i][j]; start.r=i;start.c=j; AdjacentPath(maze,start,number,flag); } } } } fclose(fp5); MessageBox(NULL,"成功生成节点网络文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } //四字节读取 unsigned int idata; if(file_type==4){ //读取所有点至maze数组 if(LINE <= 0){ MessageBox(NULL,"行值必须是正整数!请重新输入行值。", "Error",MB_ICONERROR); } if(SAMPLE <= 0){ MessageBox(NULL,"列值必须是正整数!请重新输入列值。", "Error",MB_ICONERROR); } PostType start; int flag; //记录当前斑块的类型 FILE *fp; unsigned int idata;//用来读取本行数据 maze.r=LINE;maze.c=SAMPLE; int count=0; fp=fopen(name.c_str(),"rb");//打开文件 if(fp!=NULL) { while(!feof(fp)) { fread(&idata,file_type,1,fp);//读取数据储存在idata[]中 count++; maze.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata; maze1.adr[(count-1)/SAMPLE][(count-1)%SAMPLE]=idata;//计算总斑块数和总点数用 if(flag_max<idata) flag_max=idata; } fclose(fp); } //生成总斑块数 int number1=0;//记录当前斑块的序号 for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]<=flag_max && maze1.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; MazePath1(maze1,start,number1,flag);//此方法后maze1被序列化 (5-107) } } } //生成总点数 int seq1=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze1.adr[i][j]==seq1+flag_max&& maze1.adr[i][j]!=flag_max){ if(seq1<=number1){ seq1++; flag=maze1.adr[i][j]; start.r=i;start.c=j; AdjacentPath1(maze1,start,number1,flag); } } } } //遍历斑块,输出斑块信息并序列化斑块 fp5=fopen(Edit4->Text.c_str(),"w"); fprintf(fp5, "%d\t",number1); //节点数 fprintf(fp5, "%d\t",2); //关系数 fprintf(fp5, "%d\n",sideNum);//边数 int number = 0; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]<=flag_max && maze.adr[i][j]!=0){ //得到的数据有问题 1.数据中有0 ;2. 总共103个斑块? number++; fprintf(fp5, "%d ",2); fprintf(fp5, "%d ",maze.adr[i][j]);//class值 fprintf(fp5, "%d ",i* SAMPLE+j+1);//起始点号 fprintf(fp5, "%d ",number);//斑块id ,点个数信息的记录在MazePath方法里 flag=maze.adr[i][j]; start.r=i;start.c=j; netMazePath(maze,start,number,flag);//此方法后maze被序列化 (5-107) } } } // 关系信息 fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\t",1);fprintf(fp5, "%d\t",0); fprintf(fp5, "%d\n",0); fprintf(fp5, "%d\t",2); fprintf(fp5, "%d\t",0);fprintf(fp5, "%d\t",1); fprintf(fp5, "%d\n",0); //提取斑块间的邻接路径 int seq=1; for(int i=0;i<LINE;i++){ for(int j=0;j<SAMPLE;j++){ if(maze.adr[i][j]==seq+flag_max&& maze.adr[i][j]!=flag_max){ if(seq<=number){ fprintf(fp5, "%d,",-1); fprintf(fp5, "%d,",seq); seq++; flag=maze.adr[i][j]; start.r=i;start.c=j; AdjacentPath(maze,start,number,flag); } } } } fclose(fp5); MessageBox(NULL,"成功生成节点网络文件!请在对应文件查看。", "Message",MB_ICONASTERISK); } } //--------------------------------------------------------------------------- void __fastcall TForm1::Edit5Change(TObject *Sender) { if(Edit5->Text == ""){ file_type = 1; } else{ file_type = StrToInt(Edit5->Text); } } //--------------------------------------------------------------------------- <file_sep># DataMining 高分卫星海水养殖区提取系统 <file_sep>//--------------------------------------------------------------------------- #ifndef Unit2H #define Unit2H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Menus.hpp> #include<stdio.h> #include<stdlib.h> #include <Buttons.hpp> #include <ExtCtrls.hpp> #include<time.h> #include<malloc.h> #include<string.h> #include<math.h> #include <ExtCtrls.hpp> #include <Buttons.hpp> #include <ADODB.hpp> #include <DB.hpp> #include<algorithm> #include<queue> #include<string> #include<strstream> #include<iostream> #define I_X 5 //每个地物所含波段个数 #define I_D 6 //地物总数 #define I_AMOUNT 10000 using namespace std; //--------------------------------------------------------------------------- class TForm2 : public TForm { __published: // IDE-managed Components TMemo *Memo1; TScrollBox *ScrollBox1; TImage *Image1; TBitBtn *BitBtn1; TADOQuery *ADOQuery1; void __fastcall Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall BitBtn1Click(TObject *Sender); void __fastcall change_color(); void __fastcall select_from_SQL(String str); private: // User declarations public: // User declarations __fastcall TForm2(TComponent* Owner); String stringg[I_D]; //用来记录规则; String address[I_D]; //用来记录样本地址; String ADDRESS; int HANG; int LIE; int X; int D; int AMOUNT; POINT mouse_start,mouse_end; int mouse_is_down; String TXT1; int summmm; int ed_feature_1[I_X+1][I_X+1]; //记录一次扩展的规则在v_0数组中的address,便于及时到达该位置,初始化为-1。 int ed_feature_2[I_X+1][I_X+1][I_X+1][I_X+1]; //记录一次扩展的规则在v_1数组中的address,便于及时到达该位置,初始化为-1。 int ed_feature_3[I_X+1][I_X+1][I_X+1][I_X+1][3]; //记录一次扩展的规则在v_2数组中的address,便于及时到达该位置,初始化为-1。 int max_suggest; //记录所有波段值当中的最大值 //int all_number=0; //记录所有样本的数量 int amount_of_feature; //记录所有特征的数量 int amount_of_feature_2; int amount_of_feature_3; typedef struct //波段 { int ID; //波段编号 int number; //波段值 }boduan, *pboduan; typedef struct //样本 { int yangben_id; //样本编号 boduan bo_duan[I_X]; //此样本内的波段具体情况 }yangben, *pyangben; typedef struct //地物组 { int number; //地物组的编号 pyangben yang_ben; //地物组内的样本集合 char str[I_X+1]; //这些所有集合所共有的排序序列 }group, *pgroup; typedef struct //地物 { int ID; //地物编号即第几类地物 pgroup pgp; //此类地物所包含的若干个地物组 int group_amount; //地物组数量 int yangben_amount; //本地物所有样本数量 }diwu, *pdiwu; typedef struct Node { //*********************统配特征********************************* int diw_fat,diw_thin; //优势地物劣势地物 long long pass; //通过次数 int flag; //扩展类型 double percent; //区分度 int yu; //阈值 double IGR; //信息增益比 //**********************0次扩展********************************* int fat,thin; //强势波段劣势波段 //**********************1次扩展********************************* int fat_plus,thin_plus; //强势波段劣势色波段及他们的替身 (二次扩展也使用此属性,不再重复) //**********************2次扩展********************************* int number_of_bk; //记录二次扩展出的bk值 int type_2; }feature; struct cmp { bool operator()(Node a,Node b){return a.percent<b.percent;} }; typedef struct { int * tree; }forest; typedef struct { vector<feature>f; vector<int>ff; }v_v_v; v_v_v vvv[I_D]; typedef struct { int r,g,b; }yanse; yanse ys[13]; vector<feature>v_0; vector<feature>v_1; vector<feature>v_2; priority_queue<Node,vector<Node>,cmp>q; //用来记录所有规则的堆 vector<feature>feature_v; //用来记录前十名规则的数组 diwu grand[I_D+1]; FILE *fp[I_D+1]; //*************************************************主函数***************************** int hanshu() { // 记录地物的准备工作 /* fp[0] = fopen("G:\\创新项目\\2017_03_14\\原始\\数据\\资源三号数据\\海水.txt", "r"); fp[1] = fopen("G:\\创新项目\\2017_03_14\\原始\\数据\\资源三号数据\\建筑.txt", "r"); fp[2] = fopen("G:\\创新项目\\2017_03_14\\原始\\数据\\资源三号数据\\淤泥.txt", "r"); fp[3] = fopen("G:\\创新项目\\2017_03_14\\原始\\数据\\资源三号数据\\植被.txt", "r");*/ for(int i=0 ; i<D ; i++) { fp[i] = fopen(address[i].c_str(),"r"); } for(int i=0 ; i<D ; i++) { stringg[i] = ""; } for(int i=0 ; i<D ; i++) { if(fp[i]==NULL) { printf("error——%d!\n",i); exit(-1); } } // 地物初始化 diwuchushihua(); // 地物遍历 // diwubianli(); // printf("max_suggest:%lld\n",max_suggest); // 比较 /* for(int i=0 ; i<D ; i++) { for(int j=i+1 ; j<D ; j++) { compare(grand[i],grand[j]); } } // 特征入堆 for(int i=0 ; i<amount_of_feature ; i++) { v_0[i].percent = 1.0*v_0[i].pass/(grand[v_0[i].diw_fat].yangben_amount*grand[v_0[i].diw_thin].yangben_amount); q.push(v_0[i]); printf("diw_fat:%d\tdiw_thin:%d\tpass:%7lld\tflag:%d\tfat:%2d\tthin:%2d\tpercnet:%f\t%d\n",v_0[i].diw_fat,v_0[i].diw_thin,v_0[i].pass,v_0[i].flag,v_0[i].fat,v_0[i].thin,v_0[i].percent,(grand[v_0[i].diw_fat].yangben_amount*grand[v_0[i].diw_thin].yangben_amount)); } for(int i=0 ; i<amount_of_feature_2 ; i++) { v_1[i].percent = 1.0*v_1[i].pass/(grand[v_1[i].diw_fat].yangben_amount*grand[v_1[i].diw_thin].yangben_amount); q.push(v_1[i]); printf("diw_fat:%d\tdiw_thin:%d\tpass:%7lld\tflag:%2lld\tfat:%2d\tfat_plus:%2d\tthin:%2d\tthin_plus:%2d\tpercnet:%f\t%d\n",v_1[i].diw_fat,v_1[i].diw_thin,v_1[i].pass,v_1[i].flag,v_1[i].fat,v_1[i].fat_plus,v_1[i].thin,v_1[i].thin_plus,v_1[i].percent,(grand[v_1[i].diw_fat].yangben_amount*grand[v_1[i].diw_thin].yangben_amount)); } for(int i=0 ; i<amount_of_feature_3 ; i++) { v_2[i].percent = 1.0*v_2[i].pass/(grand[v_2[i].diw_fat].yangben_amount*grand[v_2[i].diw_thin].yangben_amount); q.push(v_2[i]); printf("diw_fat:%d\tdiw_thin:%d\tpass:%7lld\tflag:%2lld\tfat:%2d\tfat_plus:%2d\tthin:%2d\tthin_plus:%2d\tpercnet:%f\t%d\n",v_2[i].diw_fat,v_2[i].diw_thin,v_2[i].pass,v_2[i].flag,v_2[i].fat,v_2[i].fat_plus,v_2[i].thin,v_2[i].thin_plus,v_2[i].percent,(grand[v_2[i].diw_fat].yangben_amount*grand[v_2[i].diw_thin].yangben_amount)); } int power = 10; while(power--) { feature f = q.top(); q.pop(); printf("该区分规则遵循%d次扩展,区分度为:%.3f %%\t用来区分%d,%d地物\n",f.flag,f.percent*100,f.diw_fat,f.diw_thin); printf("强势:%2d\t强势_plus:%2d\t劣势:%2d\t劣势_plus:%2d \n",f.fat,f.fat_plus,f.thin,f.thin_plus); int flag = 0; for(int i=0 ; i<feature_v.size() ; i++) { if(f.fat==feature_v[i].fat && f.thin==feature_v[i].thin && f.fat_plus==feature_v[i].fat_plus && f.thin_plus==feature_v[i].thin_plus) flag = 1; else if(f.fat==feature_v[i].thin && f.thin==feature_v[i].fat && f.fat_plus==feature_v[i].thin_plus && f.thin_plus==feature_v[i].fat_plus) flag = 1; } if(flag) continue; feature_v.push_back(f); printf("——————————————————————————————\n"); } */ //特殊情况的添加 feature f; for(int i=0 ; i<X ; i++) { f.fat = i; f.thin = 4; f.fat_plus = 4; f.thin_plus = 4; f.flag = -1; feature_v.push_back(f); } //建立样本世界 // int all_yangben = 0; // for(int i=0 ; i<D ; i++) // all_yangben += grand[i].yangben_amount; // printf("%d\n",all_yangben); // pyangben word = (pyangben)malloc(sizeof(yangben)*all_yangben); vector<yangben>word; for(int i=0 ; i<D ; i++) { for(int j=0 ; j<grand[i].group_amount ; j++) { for(int k=0 ; k<grand[i].pgp[j].number ; k++) { word.push_back(grand[i].pgp[j].yang_ben[k]); } } } int shuzu[I_D]; for(int i=0 ; i<D ; i++) { shuzu[i] = grand[i].yangben_amount; } double et = entropy(shuzu); printf("-----------------------------C4.5算法开始!----------------------------\n"); C4_5(word,et); /* for(int i=0 ; i<D ; i++) { stringg[i] = "第"+str_int(i+1)+"类地物:"+stringg[i]+"。"; cout<<stringg[i]<<endl; } */ for(int i=0 ; i<D ; i++) { printf("*********************************************\n"); for(int j=0 ; j<vvv[i].f.size() ; j++) { printf("***********%d\n",vvv[i].ff[j]); printf("fat:%d\tthin:%d\tfat_plus:%d\tthin_plus:%d\tyu:%d\n",vvv[i].f[j].fat,vvv[i].f[j].thin,vvv[i].f[j].fat_plus,vvv[i].f[j].thin_plus,vvv[i].f[j].yu); } } Memo1->Lines->SetText(""); String ott1[11] = {"零","一","二","三","四","五","六","七","八","九","十"} ; String ott2[11] = {"零","①","②","③","④","⑤","⑥","⑦","⑧","⑨","⑩"} ; String ssttrr; for(int i=0 ; i<D ; i++) { ssttrr = "第"+ott1[i+1]+"类地物:"; // Memo1->Lines->Append(ssttrr.c_str()); // ssttrr = ""; for(int j=0 ; j<vvv[i].f.size() ; j++) { if(j) ssttrr+=" 且 "; if(vvv[i].f[j].flag == -1) { ssttrr += "波段" + str_int(vvv[i].f[j].fat+1) + ((vvv[i].ff[j]<0)?"≤":"≥") + str_int(vvv[i].f[j].yu); } else if(vvv[i].f[j].flag == 0) { ssttrr += "波段" + str_int(vvv[i].f[j].fat+1) + " - 波段" + str_int(vvv[i].f[j].thin+1) + ((vvv[i].ff[j]<0)?"≤":"≥") + str_int(vvv[i].f[j].yu); } } ssttrr+="。"; stringg[i] = ssttrr; Memo1->Lines->Append(ssttrr.c_str()); ssttrr = ""; } change_color(); clean_all(); return 0; } void diwuchushihua() { yangben yb; int i, j, k; char ch[I_X]; for (j = 0; j<D; j++) { grand[j].ID=j; grand[j].pgp = (pgroup)malloc(sizeof(group) * AMOUNT); grand[j].group_amount = 0; i = 0; k = 0; int w = 0; int m=0; if (fp[j] == 0) { printf("fp[%d]未找到文件!\n", j); exit(-1); } else { while (!feof(fp[j])) { yb.bo_duan[i].ID = i; fscanf(fp[j], "%d", &(yb.bo_duan[i].number)); if(yb.bo_duan[i].number > max_suggest) max_suggest = yb.bo_duan[i].number ; if (i == X-1) { paixu_1(yb, ch); yb.yangben_id = j; k++; for (m = 0; m < grand[j].group_amount; m++) { if (strcmp(ch, grand[j].pgp[m].str) == 0) { grand[j].pgp[m].yang_ben[grand[j].pgp[m].number] = yb; grand[j].pgp[m].number++; break; } } if (m == grand[j].group_amount) { grand[j].pgp[m].yang_ben = (pyangben)malloc(sizeof(yangben) * AMOUNT); grand[j].pgp[m].number=0; strcpy(grand[j].pgp[m].str, ch); grand[j].pgp[m].yang_ben[0] = yb; grand[j].pgp[m].number++; grand[j].group_amount++; } } i++; i %= X; } } grand[j].yangben_amount = k; fclose(fp[j]); } return; } void paixu_1(yangben yang_ben, char ch[]) { int j, k; boduan t; char c; for (j = 0; j<X; j++) { for (k = j; k<X; k++) { if (yang_ben.bo_duan[j].number>yang_ben.bo_duan[k].number) { t = yang_ben.bo_duan[j]; yang_ben.bo_duan[j] = yang_ben.bo_duan[k]; yang_ben.bo_duan[k] = t; } } } for (j = 0; j<X; j++) { c = (char)(yang_ben.bo_duan[j].ID + 48); ch[j] = c; } ch[j] = '\0'; return; } void diwubianli() { int i, k,p,j; for (k = 0; k<D; k++) { printf("****\t*****\t****\t*****\n地物%d\n组数:%d\n样本个数:%d\n******\t******\t****\t*****\n", k + 1,grand[k].group_amount,grand[k].yangben_amount); for (i = 0; i<grand[k].group_amount; i++) { printf("第%d组\n成员个数:%d\n波段排序:%s\n",i+1,grand[k].pgp[i].number,grand[k].pgp[i].str); for (j = 0; j < grand[k].pgp[i].number;j++) { printf("样本:%d{",grand[k].pgp[i].yang_ben[j].yangben_id); for (p = 0; p < X; p++) { printf("%d",grand[k].pgp[i].yang_ben[j].bo_duan[p].number); if (p < X - 1) { printf("\t"); } } printf("}\n"); } } } return; } void compare(diwu d1,diwu d2) { printf("正在分辨地物%d和地物%d,请稍后........\n",d1.ID,d2.ID); memset(ed_feature_1,-1,sizeof(ed_feature_1)); memset(ed_feature_2,-1,sizeof(ed_feature_2)); memset(ed_feature_3,-1,sizeof(ed_feature_3)); for(int i=0 ; i<d1.group_amount ; i++) { for(int j=0 ; j<d2.group_amount ; j++) { if(strcmp(d1.pgp[i].str,d2.pgp[j].str)==0) compare__1(d1.pgp[i],d2.pgp[j],d1.ID,d2.ID); // continue; else compare_0(d1.pgp[i].str,d2.pgp[j].str,d1.ID,d2.ID,d1.pgp[i].number,d2.pgp[j].number); // continue; } } } void compare__1(group a,group b,int a_d,int b_d) { // printf("hrere:地物%d(group%d)%s\t和地物%d(group%d)%s\n",a_d,a.number,a.str,b_d,b.number,b.str); int k1,k2; for(k1=0;k1<a.number;k1++) { for(k2=0;k2<b.number;k2++) { compare_1(a.yang_ben[k1],b.yang_ben[k2],a.str,a_d,b_d); } } return ; } void compare_1(yangben a,yangben b,char ch[],int a_d,int b_d) { int p,q,r,n=1,m1,m2,bingo=0; for(q=1;q<X-1;q++) { p=q-1; r=q+1; while(p>=0&&r<X) { m1=a.bo_duan[ch[p]-48].number + a.bo_duan[ch[r]-48].number-2*(a.bo_duan[ch[q]-48].number); //强势 m2=b.bo_duan[ch[p]-48].number + b.bo_duan[ch[r]-48].number-2*(b.bo_duan[ch[q]-48].number); //弱势 if(m1<=0&&m2<=0) r++; else if(m1>0&&m2>0) p--; else { int big,big_plus,small,small_plus; int diw_fat = a_d; int diw_thin = b_d; if(m1>0) { big = ch[p]-'0'; big_plus = ch[r]-'0'; small = ch[q]-'0'; small_plus = X+1; } else { small = ch[p]-'0'; small_plus = ch[r]-'0'; big = ch[q]-'0'; big_plus = X+1; } //X+1代表另一个不用的波段,用不可能存在的第X+1个波段表示。切记 if(ed_feature_2[big][big_plus][small][small_plus]!=-1) v_1[ed_feature_2[big][big_plus][small][small_plus]].pass++; else { feature f; f.diw_fat = diw_fat; f.diw_thin =diw_thin; f.flag = 1; f.fat = big; f.fat_plus = big_plus; f.thin = small; f.thin_plus = small_plus; f.pass = 1; ed_feature_2[big][big_plus][small][small_plus]= amount_of_feature_2++; v_1.push_back(f); } if(p>0) p--; else r++; bingo = 1; } } } // if(bingo) // compare_2(a,b,ch,a_d,b_d); return ; } void compare_0(char str_1[],char str_2[],int fat,int thin,int amount_1,int amount_2) { int number_1[I_X+1],number_2[I_X+1]; for(int i=0 ; i<X ; i++) { number_1[str_1[i]-'0'] = i; number_2[str_2[i]-'0'] = i; } for(int i=0 ; i<X ; i++) { for(int j=i+1 ; j<X ; j++) { if((number_1[i]<number_1[j]) == (number_2[i]>number_2[j])) { int k; int temporary_fat = (number_1[i]>number_1[j])?i:j; int temporary_thin = (number_1[i]>number_1[j])?j:i; // int address = temporary_fat*100+temporary_thin; if(ed_feature_1[temporary_fat][temporary_thin]!=-1) v_0[ed_feature_1[temporary_fat][temporary_thin]].pass+=amount_1*amount_2; else { feature f; f.flag = 0; f.diw_fat =fat; f.diw_thin =thin; f.pass =amount_1*amount_2; f.fat = temporary_fat; f.thin = temporary_thin; f.fat_plus = X+1; f.thin_plus = X+1; ed_feature_1[temporary_fat][temporary_thin] = amount_of_feature++; v_0.push_back(f); } } } } } void compare_2(yangben a,yangben b,char ch[10],int a_d,int b_d) { for(int i=0; i<X-1 ; i++) { for(int j=i+1 ; j<X ; j++) { int a_i = a.bo_duan[ch[i]-48].number; int a_j = a.bo_duan[ch[j]-48].number; int b_i = b.bo_duan[ch[i]-48].number; int b_j = b.bo_duan[ch[j]-48].number; /***************************************小扩展*************************************/ int buttom_a = max(2*a_i-a_j,1); int buttom_b = max(2*b_i-b_j,1); erci(buttom_a,buttom_b,a_d,b_d,i,j,0); /***************************************中扩展*************************************/ buttom_a = (a_i+a_j)/2; buttom_b = (b_i+b_j)/2; erci(buttom_a,buttom_b,a_d,b_d,i,j,1); /***************************************大扩展*************************************/ buttom_a = 2*a_j-a_i; buttom_b = 2*a_j-a_i; erci(buttom_a,buttom_b,a_d,b_d,i,j,2); } } } int equl_f(feature a,feature b) { if(a.flag != b.flag) return 0; if(a.diw_fat != b.diw_fat) return 0; if(a.diw_thin != b.diw_thin) return 0; if(a.fat==b.fat&&a.fat_plus==b.fat_plus&&a.thin==b.thin&&a.thin_plus==b.thin_plus) { if(a.flag==2 && a.number_of_bk!=b.number_of_bk) return 0; } return 1; } int lowbit(int x) { return x&(-x); } void update(int tree[],int x,int pos) { while(x<max_suggest*2+3) { tree[x] += pos; x += lowbit(x); } return ; } int ffind(int tree[],int x) { int sum = 0; while(x>0) { // printf("%d,tree[x]:%d\n",x,tree[x]); sum += tree[x]; x -= lowbit(x); } return sum; } void erci(int buttom_a,int buttom_b,int a_d,int b_d,int i,int j,int type) { // printf("a:%d\tb:%d\n",buttom_a,buttom_b); if(buttom_a == buttom_b) return; feature f; f.flag = 2; f.type_2 = type; f.diw_fat = a_d; f.diw_thin = b_d; f.pass = 1; if(buttom_a>buttom_b) { switch(type) { case 0:{ f.fat = j; f.fat_plus = 32; f.thin = i; f.thin_plus = X+1; break; } case 1:{ f.fat = j; f.fat_plus = i; f.thin = 32; f.thin_plus = X+1; break; } case 3:{ f.fat = 32; f.fat_plus = i; f.thin = j; f.thin_plus = X+1; break; } } f.number_of_bk = (buttom_a+buttom_b)/2; } else { switch(type) { case 0:{ f.thin = j; f.thin_plus = 32; f.fat = i; f.fat_plus = X+1; break; } case 1:{ f.thin = j; f.thin_plus = i; f.fat = 32; f.fat_plus = X+1; break; } case 3:{ f.thin = 32; f.thin_plus = i; f.fat = j; f.fat_plus = X+1; break; } } f.number_of_bk = buttom_a-buttom_b; } if(ed_feature_3[f.fat][f.fat_plus][f.thin][f.thin_plus][f.type_2]!=-1) v_2[ed_feature_3[f.fat][f.fat_plus][f.thin][f.thin_plus][f.type_2]].pass++; else { v_2.push_back(f); ed_feature_3[f.fat][f.fat_plus][f.thin][f.thin_plus][f.type_2]=amount_of_feature_3++; } } double entropy(int shuzu[]) { double sum = 0; for(int i=0 ; i<D ; i++) { sum+=shuzu[i]; } double T=0; for(int i=0;i<D;i++) { if(shuzu[i]==0) { // printf("%d\n",shuzu[i]); //防止算出非法值,当零时跳过 continue; } T+=shuzu[i]*1.0/sum*log(shuzu[i]*1.0/sum)/log(2); // printf("T:%f\n",T); } return -T; } void C4_5(vector<yangben>word,double et) { // if(feature_v.size()==0) // return ; printf("%f\n",et); forest trees[I_D]; for(int i=0 ; i<D ; i++) { trees[i].tree = (int *)malloc(sizeof(int)*(max_suggest*2+3)); } // printf("4棵树已种植完成\n"); int sum_of_word = word.size(); //记录世界的总人口 vector<int>yu; //用来记录所有阈值 double max_GRT = 0; //记录最大的信息增益比 int max_yu = 0; //记录最大信息增益比所对应的阈值 int address=0; for(int i=0 ; i<feature_v.size() ; i++) { if(feature_v[i].flag==-32) continue; printf("正在分析第%d条规则\n",i); int fat = feature_v[i].fat; int thin = feature_v[i].thin; int fat_plus = feature_v[i].fat_plus; int thin_plus = feature_v[i].thin_plus; // printf("fat:%d\tthin:%d\tfat_plus:%d\tthin_plus:%d\n",fat,thin,fat_plus,thin_plus); int temporary_yu; //用来临时记录阈值 for(int j=0 ; j<D ; j++) { memset(trees[j].tree,0,sizeof(int)*(max_suggest*2+3)); } // printf("树初始化完成\n"); // printf("%d\n",sum_of_word); for(int j=0 ; j<sum_of_word ; j++) { // printf("当前特征:%d\n",feature_v[i].flag); switch(feature_v[i].flag) { case 0:{ temporary_yu = word[j].bo_duan[fat].number - word[j].bo_duan[thin].number; break; } case 1:{ if(fat_plus==D) temporary_yu = word[j].bo_duan[fat].number - (word[j].bo_duan[thin].number+word[j].bo_duan[thin_plus].number)/2; else temporary_yu = (word[j].bo_duan[fat].number+word[j].bo_duan[fat_plus].number)/2 - word[j].bo_duan[thin].number; break; } case -1:{ temporary_yu = word[j].bo_duan[fat].number; break; } } // printf("temporary:%d\n",temporary_yu); yu.push_back(temporary_yu); update(trees[word[j].yangben_id].tree,temporary_yu+max_suggest+1,1); // if(j%10)printf("%d\n",j); } // printf("树的建立完成\n"); int sum_of_yu = yu.size(); //记录所有阈值的个数; int left[I_D],right[I_D]; for(int j=0 ; j<sum_of_yu ; j++) { for(int k=0 ; k<D ; k++) { left[k] = ffind(trees[k].tree,yu[j]+max_suggest); right[k] = ffind(trees[k].tree,max_suggest*2+2)-left[k]; } double GRT = GainRatio(left,right,et); // printf("%f\n",GRT); if(GRT>max_GRT) { max_GRT = GRT; max_yu = yu[j]; address = i; } } } printf("最大信息增益比:%f\t阈值:%d\t地址:%d\n",max_GRT,max_yu,address); vector<yangben>left_word; vector<yangben>right_word; int amount_of_left[I_D]; int amount_of_right[I_D]; memset(amount_of_left,0,sizeof(amount_of_left)); memset(amount_of_right,0,sizeof(amount_of_right)); int fat = feature_v[address].fat; int thin = feature_v[address].thin; int fat_plus = feature_v[address].fat_plus; int thin_plus = feature_v[address].thin_plus; for(int j=0 ; j<sum_of_word ; j++) { int temporary_yu; switch(feature_v[address].flag) { case 0:{ temporary_yu = word[j].bo_duan[fat].number - word[j].bo_duan[thin].number; break; } case 1:{ if(fat_plus==D) temporary_yu = word[j].bo_duan[fat].number - (word[j].bo_duan[thin].number+word[j].bo_duan[thin_plus].number)/2; else temporary_yu = (word[j].bo_duan[fat].number+word[j].bo_duan[fat_plus].number)/2 - word[j].bo_duan[thin].number; break; } case -1:{ temporary_yu = word[j].bo_duan[fat].number; break; } } if(temporary_yu <= max_yu) { left_word.push_back(word[j]); amount_of_left[word[j].yangben_id] ++; } else { right_word.push_back(word[j]); amount_of_right[word[j].yangben_id] ++; } } if(left_word.size()>100 && right_word.size()>100||1) { printf("fat:%d\tthin:%d\tfat_plus:%d\tthin_plus:%d\n",feature_v[address].fat,feature_v[address].thin,feature_v[address].fat_plus,feature_v[address].thin_plus); printf("左世界人数:%d\t右世界人数:%d\n",left_word.size(),right_word.size()); // if(max_GRT<0.5) getchar(); if(left_word.size()==0 || right_word.size()==0)return; feature_v[address].yu = max_yu; for(int i=0 ; i<D ; i++) { if(amount_of_left[i]<AMOUNT && amount_of_left[i]>AMOUNT/2) { vvv[i].f.push_back(feature_v[address]); vvv[i].ff.push_back(-1); /* if(stringg[i]=="") stringg[i] += str_1; else stringg[i] += " 且 " +str_1; */ } printf("%5d",amount_of_left[i]); } printf("\n"); for(int i=0 ; i<D ; i++) { if(amount_of_right[i]<AMOUNT && amount_of_right[i]>AMOUNT/2) { vvv[i].f.push_back(feature_v[address]); vvv[i].ff.push_back(1); /* if(stringg[i]=="") stringg[i] += str_2; else stringg[i] += " 且 " +str_2; */ } printf("%5d",amount_of_right[i]); } printf("\n"); printf("-----------------------------------------------------------------------------\n"); } feature_v[address].flag = -32; //标记已用过的特征为-32 // printf("请选择需要递归的方向:\n【1】左递归\n【2】右递归\n【0】不递归\n"); // int select; // scanf("%d",&select); // getchar(); double et_1 = entropy(amount_of_left); double et_2 = entropy(amount_of_right); if(left_word.size()>AMOUNT*3/2) C4_5(left_word,et_1); if(right_word.size()>AMOUNT*3/2) C4_5(right_word,et_2); // switch(select) // { // case 1:{ // C4_5(left_word,et_1); // break; // } // case 2:{ // C4_5(right_word,et_2); // break; // } // case 0:{ // return ; // break; // } // } } double GainRatio(int left[],int right[],double et) { double left_amount = 0; double right_amount = 0; for(int i=0 ; i<D ; i++) { left_amount += left[i]; right_amount += right[i]; } if(!(left_amount+right_amount)) return 0; double lb = left_amount/(left_amount+right_amount); double rb = right_amount/(left_amount+right_amount); double Gain = et - (lb*entropy(left) + rb*entropy(right)); if(!lb || !rb) return 0; double SplitInfo = -(lb*log(lb)/log(2)+rb*log(rb)/log(2)); return Gain/SplitInfo; } String str_int(int n) { if(n==0)return 0; String s=""; String number[10]={"0","1","2","3","4","5","6","7","8","9"}; int flag_n=0; if(n<0) { flag_n = 1; n=-n; } while(n) { int i = n%10; s=number[i]+s; n/=10; } if(flag_n) s="-"+s; return s; } void clean_all() { for(int i=0 ; i<D ; i++) { free((void *)(grand[i].pgp)); printf("??\n"); vvv[i].f.clear(); vvv[i].ff.clear(); fclose(fp[i]); } v_0.clear(); v_1.clear(); v_2.clear(); amount_of_feature = 0; amount_of_feature_2 = 0; amount_of_feature_3 = 0; while(!q.empty()) { q.pop(); } feature_v.clear(); } }; //--------------------------------------------------------------------------- extern PACKAGE TForm2 *Form2; //--------------------------------------------------------------------------- #endif <file_sep>//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "Unit3.h" #include "Unit2.h" #include "Unit4.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm3 *Form3; //--------------------------------------------------------------------------- __fastcall TForm3::TForm3(TComponent* Owner) : TForm(Owner) { mouse_is_down = 0; select_time = 0; amount_of_yb = 0; t_min = 0; } //--------------------------------------------------------------------------- void __fastcall TForm3::Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { if(select_time) { if(Button == mbRight) { POINT tp = select_point.back(); POINT tb = select_point.front(); Image1->Canvas->Pen->Color = RGB(255,0,0); Image1->Canvas->MoveTo(tp.x,tp.y); Image1->Canvas->LineTo(tb.x,tb.y); return ; } mouse_is_down = 1; GetCursorPos(&mouse_select); // mouse_select.x = mouse_select.x-Form3->Left-3-Image1->Left; mouse_select.y = mouse_select.y-Form3->Top-28-Image1->Top; if(!select_point.empty()) { POINT tp = select_point.back(); Image1->Canvas->Pen->Color = RGB(255,0,0); Image1->Canvas->MoveTo(tp.x,tp.y); Image1->Canvas->LineTo(mouse_select.x,mouse_select.y); // Memo1->Lines->Append(mouse_start.x-Form3->Left-3); // Memo2->Lines->Append(mouse_start.y-Form3->Top-28); } select_point.push_back(mouse_select); return ; } GetCursorPos(&mouse_start); mouse_is_down = 1; // Memo1->Lines->Append(mouse_start.x); // Memo2->Lines->Append(mouse_start.y); } //--------------------------------------------------------------------------- void __fastcall TForm3::Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { if(select_time) { mouse_is_down = 0; return ; } GetCursorPos(&mouse_end); int x_move = mouse_end.x-mouse_start.x; int y_move = mouse_end.y-mouse_start.y; //*******************对自己图片位置的更改************************ Image1->Left += x_move; Image1->Top += y_move; if(Image1->Left>0) Image1->Left = 0; if(Image1->Top>0) Image1->Top = 0; if(Image1->Left<(ScrollBox1->Width-Image1->Width)) Image1->Left = (ScrollBox1->Width-Image1->Width); if(Image1->Top<(ScrollBox1->Height-Image1->Height)) Image1->Top = (ScrollBox1->Height-Image1->Height); //*******************对另一个图片位置的更改********************** Form2->Image1->Left += x_move; Form2->Image1->Top += y_move; if(Form2->Image1->Left>0) Form2->Image1->Left = 0; if(Form2->Image1->Top>0) Form2->Image1->Top = 0; if(Form2->Image1->Left<(Form2->ScrollBox1->Width - Form2->Image1->Width)) Form2->Image1->Left = (Form2->ScrollBox1->Width - Form2->Image1->Width); if(Form2->Image1->Top<(Form2->ScrollBox1->Height - Form2->Image1->Height)) Form2->Image1->Top = (Form2->ScrollBox1->Height - Form2->Image1->Height); //*******************对另一个图片位置的更改********************** Form4->Image1->Left += x_move; Form4->Image1->Top += y_move; if(Form4->Image1->Left>0) Form4->Image1->Left = 0; if(Form4->Image1->Top>0) Form4->Image1->Top = 0; if(Form4->Image1->Left<(Form4->ScrollBox1->Width - Form4->Image1->Width)) Form4->Image1->Left = (Form4->ScrollBox1->Width - Form4->Image1->Width); if(Form4->Image1->Top<(Form4->ScrollBox1->Height - Form4->Image1->Height)) Form4->Image1->Top = (Form4->ScrollBox1->Height - Form4->Image1->Height); mouse_is_down = 0; } //--------------------------------------------------------------------------- void __fastcall TForm3::Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if(!mouse_is_down) { /* GetCursorPos(&mouse_eye); mouse_eye.x = mouse_eye.x-Form3->Left-3-Image1->Left; mouse_eye.y = mouse_eye.y-Form3->Top-28-Image1->Top; //获取本图片位置 mouse_eye.x += Form3->Left - Image1->Left; //移动到另一个图片 Form2->Image1->Canvas->Pixels[mouse_eye.x][mouse_eye.y] =Graphics::TColor(RGB(0,255,255)); */ return ; } if(select_time) { GetCursorPos(&mouse_select); mouse_select.x = mouse_select.x-Form3->Left-3-Image1->Left; mouse_select.y = mouse_select.y-Form3->Top-28-Image1->Top; if(!select_point.empty()) { POINT tp = select_point.back(); Image1->Canvas->Pen->Color = RGB(255,0,0); Image1->Canvas->MoveTo(tp.x,tp.y); Image1->Canvas->LineTo(mouse_select.x,mouse_select.y); // Memo1->Lines->Append(mouse_start.x-Form3->Left-3); // Memo2->Lines->Append(mouse_start.y-Form3->Top-28); } select_point.push_back(mouse_select); return ; } if(mouse_is_down) { GetCursorPos(&mouse_end); int x_move = mouse_end.x-mouse_start.x; int y_move = mouse_end.y-mouse_start.y; //*************************************对自己图片位置的更改*************************************** Image1->Left += x_move; Image1->Top += y_move; if(Image1->Left>0) Image1->Left = 0; if(Image1->Top>0) Image1->Top = 0; if(Image1->Left<(ScrollBox1->Width-Image1->Width)) Image1->Left = (ScrollBox1->Width-Image1->Width); if(Image1->Top<(ScrollBox1->Height-Image1->Height)) Image1->Top = (ScrollBox1->Height-Image1->Height); mouse_start = mouse_end; //************************************对另一个图片位置的更改************************************** Form2->Image1->Left += x_move; Form2->Image1->Top += y_move; if(Form2->Image1->Left>0) Form2->Image1->Left = 0; if(Form2->Image1->Top>0) Form2->Image1->Top = 0; if(Form2->Image1->Left<(Form2->ScrollBox1->Width - Form2->Image1->Width)) Form2->Image1->Left = (Form2->ScrollBox1->Width - Form2->Image1->Width); if(Form2->Image1->Top<(Form2->ScrollBox1->Height - Form2->Image1->Height)) Form2->Image1->Top = (Form2->ScrollBox1->Height - Form2->Image1->Height); Form2->mouse_start = Form2->mouse_end; //************************************对另一个图片位置的更改************************************** Form4->Image1->Left += x_move; Form4->Image1->Top += y_move; if(Form4->Image1->Left>0) Form4->Image1->Left = 0; if(Form4->Image1->Top>0) Form4->Image1->Top = 0; if(Form4->Image1->Left<(Form4->ScrollBox1->Width - Form4->Image1->Width)) Form4->Image1->Left = (Form4->ScrollBox1->Width - Form4->Image1->Width); if(Form4->Image1->Top<(Form4->ScrollBox1->Height - Form4->Image1->Height)) Form4->Image1->Top = (Form4->ScrollBox1->Height - Form4->Image1->Height); Form4->mouse_start = Form4->mouse_end; } } //--------------------------------------------------------------------------- int __fastcall TForm3::pnpoly(float test_x,float test_y,int nvert) { int i,j,c = 0; for(i=0,j=nvert-1 ; i<nvert ; j=i++) { if((select_point[i].y*1.0>test_y)!=(select_point[j].y*1.0>test_y)) { if(test_x<(select_point[j].x*1.0 - select_point[i].x*1.0)*(test_y-select_point[i].y*1.0)/(select_point[j].y*1.0-select_point[i].y*1.0)+select_point[i].x*1.0) { c = !c; } } } // Memo1->Lines->Append(nvert); return c; } void __fastcall TForm3::select_to_red() { int x = select_point.size(); int x_min=9999999; int y_min=9999999; int x_max=0; int y_max=0; for(int i=0 ; i<x ; i++) { if(select_point[i].x>x_max) x_max = select_point[i].x; if(select_point[i].y>y_max) y_max = select_point[i].y; if(select_point[i].x<x_min) x_min = select_point[i].x; if(select_point[i].y<y_min) y_min = select_point[i].y; } Range r; r.x_max = x_max; r.y_max = y_max; r.x_min = x_min; r.y_min = y_min; rg.push(r); int tem_xx = 0; for(int i=y_min ; i<=y_max ; i++) { for(int j=x_min ; j<=x_max ; j++) { if(pnpoly(j,i,x)) { tem_xx++; } } } if(tem_xx + amount_of_yb >= D_YANGBEN) { Application->MessageBoxA("所选择样本数量已超过最大限制!","系统提示",MB_ICONWARNING); for(int i=rg.top().x_min ; i<=rg.top().x_max ; i++) { for(int j=rg.top().y_min ; j<=rg.top().y_max ; j++) { Image1->Canvas->Pixels[i][j] =Graphics::TColor(RGB(picture[j][i].data[0]/t_min,picture[j][i].data[1]/t_min,picture[j][i].data[2]/t_min)); } } return; } for(int i=y_min ; i<=y_max ; i++) { for(int j=x_min ; j<=x_max ; j++) { if(pnpoly(j,i,x)) { Image1->Canvas->Pixels[j][i] =Graphics::TColor(RGB(255,0,0)); amount_of_yb++; POINT pot; pot.x = j; pot.y = i; lucky_point.push_back(pot); } } } } void __fastcall TForm3::back_to_photo() { while(!rg.empty()) { for(int i=rg.top().x_min ; i<=rg.top().x_max ; i++) { for(int j=rg.top().y_min ; j<=rg.top().y_max ; j++) { Image1->Canvas->Pixels[i][j] =Graphics::TColor(RGB(picture[j][i].data[0]/t_min,picture[j][i].data[1]/t_min,picture[j][i].data[2]/t_min)); } } rg.pop(); } } void __fastcall TForm3::go_back() { int x = select_point.size(); int x_min=9999999; int y_min=9999999; int x_max=0; int y_max=0; for(int i=0 ; i<x ; i++) { if(select_point[i].x>x_max) x_max = select_point[i].x; if(select_point[i].y>y_max) y_max = select_point[i].y; if(select_point[i].x<x_min) x_min = select_point[i].x; if(select_point[i].y<y_min) y_min = select_point[i].y; } for(int i=x_min ; i<=x_max ; i++) { for(int j=y_min ; j<=y_max ; j++) { Image1->Canvas->Pixels[i][j] =Graphics::TColor(RGB(picture[j][i].data[0]/t_min,picture[j][i].data[1]/t_min,picture[j][i].data[2]/t_min)); } } } void __fastcall TForm3::write_point_to_file(String file_address) { ///...//// FILE *fp; fp = fopen(file_address.c_str(),"a"); // Memo1->SetTextBuf(file_address.c_str()); if(fp==NULL) { Application->MessageBoxA("文件不存在","系统提示",MB_ICONWARNING); return ; } while(!lucky_point.empty()) { int tx = lucky_point.back().x; int ty = lucky_point.back().y; for(int i=0 ; i<X_BODUAN ; i++) { /*Memo1->Lines->Append("ok!"); Memo2->Lines->Append("ok!"); */ fprintf(fp,"%d" ,picture[ty][tx].data[i]); if(i<X_BODUAN-1) fprintf(fp," "); } lucky_point.pop_back(); if(!lucky_point.empty()) fprintf(fp,"\n"); } } <file_sep>//--------------------------------------------------------------------------- #ifndef Unit4H #define Unit4H //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TForm4 : public TForm { __published: // IDE-managed Components TScrollBox *ScrollBox1; TImage *Image1; void __fastcall Image1MouseMove(TObject *Sender, TShiftState Shift, int X, int Y); void __fastcall Image1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall Image1MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y); void __fastcall find_the_line(); void __fastcall dfs(int x,int y); void __fastcall redfs(int x,int y); private: // User declarations public: // User declarations __fastcall TForm4(TComponent* Owner); int HANG; int LIE; POINT mouse_start,mouse_end; int mouse_is_down; int **change; int **change1; int max_length; int address_of_x; int address_of_y; String TXT2; }; //--------------------------------------------------------------------------- extern PACKAGE TForm4 *Form4; //--------------------------------------------------------------------------- #endif
1bc2fc2e9bb164371d868bd29b0ce99fb5ae6908
[ "Markdown", "C++" ]
11
C++
w351565056/DataMining
10421eff9ffaff247fc078d22e308b8cc6d9b623
a76857675c1280d7f6eb37d2f03afdf0fc564d28
refs/heads/master
<file_sep>import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; /** * FrontGridPane.java * Used for display recognised results. * The front grid panel has 1 Label, 1 CopiedButton and 4 PressCopyTextFields. */ class FrontGridPane extends GridPane { private static Label resultText = new Label("LaTeX"); private static CopiedButton copiedButton = new CopiedButton("COPIED"); private static PressCopyTextField latexStyledResult = new PressCopyTextField(); private static PressCopyTextField textResult = new PressCopyTextField(); private static PressCopyTextField notNumberedBlockModeResult = new PressCopyTextField(); private static PressCopyTextField numberedBlockModeResult = new PressCopyTextField(); private static final Color frontBackgroundColor = new Color(0.9725, 0.9765, 0.9804, 1); private static final BackgroundFill frontFill = new BackgroundFill(frontBackgroundColor, CornerRadii.EMPTY, Insets.EMPTY); private static final Background frontPaneBackground = new Background(frontFill); /** * @param itemMargin margin between items. * @param textMargin margin between text and item. * @param borderStroke customised border stroke, same as in BackGridPane. */ FrontGridPane(int itemMargin, int textMargin, BorderStroke borderStroke) { this.setBorder(new Border(borderStroke)); this.setBackground(frontPaneBackground); this.setPadding(new Insets(itemMargin)); // 5 * 2 grid layout this.setVgap(5); this.setHgap(2); // "LaTeX" label text resultText.setFont(Font.font(12)); resultText.setTextFill(new Color(0.149, 0.149, 0.149, 1)); GridPane.setMargin(resultText, new Insets(0, 0, textMargin, 0)); this.add(resultText, 0, 0); // CopiedButton to indicate which result on the left side has been copied GridPane.setMargin(copiedButton, new Insets(0, 0, 0, itemMargin)); // default invisible copiedButton.setVisible(false); this.add(copiedButton, 1, 1); // mouse clicked event latexStyledResult.setOnMouseClicked(event -> { if (latexStyledResult.getLength() > 0) { // CopiedButton shows at (1, 1) copiedButton.setVisible(true); GridPane.setRowIndex(copiedButton, 1); } }); this.add(latexStyledResult, 0, 1); // mouse clicked event textResult.setOnMouseClicked(event -> { if (textResult.getLength() > 0) { // CopiedButton shows at (1, 2) copiedButton.setVisible(true); GridPane.setRowIndex(copiedButton, 2); } }); this.add(textResult, 0, 2); // mouse clicked event notNumberedBlockModeResult.setOnMouseClicked(event -> { if (notNumberedBlockModeResult.getLength() > 0) { // CopiedButton shows at (1, 3) copiedButton.setVisible(true); GridPane.setRowIndex(copiedButton, 3); } }); this.add(notNumberedBlockModeResult, 0, 3); // mouse clicked event numberedBlockModeResult.setOnMouseClicked(event -> { if (numberedBlockModeResult.getLength() > 0) { // CopiedButton shows at (1, 4) copiedButton.setVisible(true); GridPane.setRowIndex(copiedButton, 4); } }); this.add(numberedBlockModeResult, 0, 4); } /** * @return CopiedButton object used to be controlled by BackGridPane event. */ CopiedButton getCopiedButton() { return copiedButton; } /** * @return LaTeX styled result TextField. */ PressCopyTextField getLatexStyledResult() { return latexStyledResult; } /** * @return text result TextField. */ PressCopyTextField getTextResult() { return textResult; } /** * @return not numbered block mode result TextField. */ PressCopyTextField getNotNumberedBlockModeResult() { return notNumberedBlockModeResult; } /** * @return numbered block mode result TextField. */ PressCopyTextField getNumberedBlockModeResult() { return numberedBlockModeResult; } /** * Method to set the row index of CopiedButton in BackGridPane */ void setCopiedButtonRowIndex() { copiedButton.setVisible(true); GridPane.setRowIndex(copiedButton, 1); } }
935ae5d04448d189b5e021c00cd321466ce972df
[ "Java" ]
1
Java
Leokuf/img2latex-mathpix
1a425eb8bbbd2514a11e0f5571b113412412a567
f03b8b3650d7a9e65043d3eb4286e06d02bde0ad
refs/heads/master
<repo_name>nishantsahoo/Scraper-Fun<file_sep>/flipkart-scraper.py from urllib.request import urlopen from bs4 import BeautifulSoup def main(): queryTerm = "" queryTerm = input("Enter the query term: ") html = urlopen("https://www.flipkart.com/search?q=" + queryTerm) soup = BeautifulSoup(html.read(), features="html.parser"); list_product = soup.findAll('div', attrs={'class': '_3wU53n'}) if list_product: for product in list_product: print(product.text) else: print("No results found!") main() # call of the main function<file_sep>/amazon-scraper.py from urllib.request import urlopen from bs4 import BeautifulSoup import pprint pp = pprint.PrettyPrinter(indent=4) def main(): queryTerm = "" queryTerm = input("Enter the query term: ") html = urlopen("https://www.amazon.in/s/field-keywords=" + queryTerm) soup = BeautifulSoup(html.read(), features="html.parser") list_product = soup.findAll('div', attrs={'class': 'a-fixed-left-grid-col a-col-right'}) products = [] if list_product: for product in list_product: if product.find('a', attrs={'class': 'a-link-normal a-text-normal'}): name = product.find('a', attrs={'class': 'a-link-normal s-access-detail-page s-color-twister-title-link a-text-normal'}).text.strip() price = product.find('a', attrs={'class': 'a-link-normal a-text-normal'}).text.strip() product = { 'name': name, 'price': price } products += [product] pp.pprint(products) else: print("No results found!") main() # call of the main function<file_sep>/README.md # Scraper-Fun This repository will contain all my scraper files. I'll keep experimenting web scraping with Python and BeautifulSoup and have some fun in the process. :P
e5e217787856c1b0ad21678413f4c4eb671e89d9
[ "Markdown", "Python" ]
3
Python
nishantsahoo/Scraper-Fun
dc44ed989af1ab669abfcaa456da6830132db85e
eec4db1103d03e9ede29c6295ac69258b39dbc00
refs/heads/master
<repo_name>juniormag/d3-digest<file_sep>/script/watch #!/usr/bin/env bash node --use_strict src/watcher/main.js <file_sep>/www/application.js var Controller = function() { this.firstCall = true; // Whether we are requesting data for the first time. this.finished = false; // Whether we already hit the bottom. this.from = null; // Last "from" parameter we received from the remote. this.waiting = false; // Whether we are already waiting for the remote. this.templates = {}; this.$ = $(this); this.window = $(window); this.document = $(document); var that = this; $('[data-template-partial]:not([data-registered])').each(function() { var item = $(this); Handlebars.registerPartial(item.attr('data-template-partial'), item.html()); item.attr('data-registered', 'true'); }); $('[data-template]').each(function() { var item = $(this); item.attr('data-template').split(',').forEach(function(k) { that.templates[k] = Handlebars.compile(item.html()); }); }); }; Controller.prototype.render = function(item) { var result = ''; if(!this.templates[item.type]) { console.warn(['Unregistered template for item with type ', item.type].join('')); } else { try { result = this.templates[item.type](item); } catch(ex) { console.error('Error rendering item with template ' + item.type, ex); } } return result; } Controller.prototype.fixEmbeds = function(items) { $.when( items.find('iframe').ready, items.find('img').load ).done(function() { $('.grid').isotope('layout'); }); $('[data-item-type="vimeo"],[data-item-type="youtube"]').find('iframe').attr({ width: 285, height: 168 }); this.embedInterval = this.embedInterval || setInterval(function() { $('[data-item-type="tweet"]').each(function() { var $this = $(this); $this.find('iframe').css({ marginTop: 0, marginBottom: 0 }); }).promise().done(function() { $('.grid').isotope('layout'); }); }, 1000); } Controller.prototype.load = function() { if(this.finished || this.waiting) { return; } this.$.trigger('loading'); this.waiting = true; $.ajax({ url: this.firstCall ? '/api/latest' : ['/api/from/', this.from].join(''), method: 'GET', type: 'json' }) .done(function(data) { this.from = data.from; this.$.trigger('loaded'); this.waiting = false; if(!data.items) { this.finished = true; this.$.trigger('finished'); return; } var $grid = $('.grid'), result = $(); data.items.items.forEach(function(item) { result = result.add($(this.render(item))); }.bind(this)); if(this.firstCall) { this.firstCall = false; $grid .append(result) .isotope({ itemSelector: '.grid-item', masonry: { columnWidth: '.grid-item' } }); } else { $grid.isotope('insert', result); } this.fixEmbeds(result); }.bind(this)) .fail(function() { this.waiting = false; this.$.trigger('failed'); }.bind(this)); }; Controller.prototype.handleScroll = function() { if(this.window.scrollTop() + this.window.height() > this.document.height() - 100) { this.load(); } } $(function() { Handlebars.registerHelper('truncate', function(options) { var value = options.fn(this); if(value.length > 255) { var parts = value.split(' '), part; value = ''; while(parts) { part = parts.shift(); if(value.length + part.length > 255) { value += '...'; break; } else { value += ' ' + part; } } } return value; }); Handlebars.registerHelper('domain', function(options) { var value = options.fn(this), regex = /(?:https?:\/\/)?([^\/]+).*/; if(regex.test(value)) { var match = regex.exec(value); value = regex[1]; } return value; }); $.debounce = function(func, wait) { var timeout; return function() { var context = this, args = arguments, then = function() { timeout = null; func.apply(context, args); }; if(timeout) { clearTimeout(timeout); } timeout = setTimeout(then, wait); } }; var fadeStart = 0, fadeUntil = Math.max(1, screen.height / 2), fadeTarget = $('#page_cover header, .cover_pattern'), $document = $(document), controller = new Controller(), scrollHandler = $.debounce(controller.handleScroll.bind(controller), 300); controller.load(); $(window).scroll(function() { scrollHandler(); var offset = $document.scrollTop(), opacity = 0; if(offset <= fadeStart) { opacity = 1; } else if(offset <= fadeUntil) { opacity = 1 - offset / fadeUntil; } fadeTarget.css('opacity', opacity); }); }); // CANVAS var globalID_01; var canvas_square01 = document.getElementById("canvas_square01"); var ctx_square01 = canvas_square01.getContext("2d"); canvas_square01.width = $(window).width(); canvas_square01.height = $(window).height(); $( window ).on("resize", function(){ canvas_square01.width = $(window).width(); }); var W_square01 = $(window).width(); var H_square01 = $(window).height(); var particles_square01 = []; for(var i = 0; i < 200; i++) { //This will add 50 particles_square01 to the array with random positions particles_square01.push(new create_particle_square01()); } if (!window.requestAnimationFrame) { window.requestAnimationFrame = ( function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); } //Lets create a function which will help us to create multiple particles_square01 function create_particle_square01() { //Random position on the canvas_square01 this.x = Math.random()*W_square01; this.y = Math.random()*H_square01; this.vx = Math.random()*1-0.5; this.vy = Math.random()*1-0.5; var colors_square01 = ['rgba(212,9,76,0.8)', 'rgba(174,210,163,0.7)', 'rgba(252,245,198,0.7)']; //var colors_square01 = ['rgba(69,90,184,0.7)', 'rgba(8,223,180,0.7)', 'rgba(244,72,112,0.7)', 'rgba(227,45,99,0.7)']; this.color =colors_square01[Math.round(Math.random()*3)]; // Verificar velocidade com scroll // Distort this.ru = Math.random()*1000+40; this.rd = Math.random()*60+30; this.ld = Math.random()*60+30; this.lu = Math.random()*60+30; } function draw_square01(){ ctx_square01.fillStyle = 'rgba(166,59,85,1)'; ctx_square01.fillRect(0, 0, W_square01, H_square01); ctx_square01.globalCompositeOperatin for(var t = 0; t < particles_square01.length; t++) { var p_square01 = particles_square01[t]; ctx_square01.beginPath(); ctx_square01.moveTo(p_square01.x - p_square01.lu, p_square01.y - p_square01.lu); ctx_square01.lineTo(p_square01.x + 10 + p_square01.ru, p_square01.y - p_square01.ru); ctx_square01.lineTo(p_square01.x + 10 + p_square01.rd, p_square01.y + 10 + p_square01.rd); ctx_square01.lineTo(p_square01.x - p_square01.rd, p_square01.y + 10 + p_square01.rd); ctx_square01.fillStyle = p_square01.color; ctx_square01.fill(); p_square01.x += p_square01.vx; p_square01.y += p_square01.vy; var height = $(window).scrollTop(); if(height > 500) { p_square01.x -= p_square01.vx; p_square01.y -= p_square01.vy; } if(p_square01.x < -150) p_square01.x = W_square01+150; if(p_square01.y < -150) p_square01.y = H_square01+150; if(p_square01.x > W_square01+150) p_square01.x = -150; if(p_square01.y > H_square01+150) p_square01.y = -150; } window.requestAnimationFrame(draw_square01); } function animate_square01(){ globalID_01 = window.requestAnimationFrame(draw_square01); } animate_square01() <file_sep>/src/collector/main.js console.log([' ', //eslint-disable-line no-console ' ', ' ╒▄ ╔▄⌐ ╓▄ ▓─ ▐▓ ', ' ▓▌ ╒▓▓▓ ▓▌ ▓µ ▐▓ ', ' ▐▓ ▓▓\'▓▌ ▐▓ⁿ ▄▓███▓▄ ▄▓███▓▄ ▓µ ▄▓▀ ▐▓ █▓ ▓▀ ', ' ▓▌ ▐▓¬ ╚▓⌐ ▓▌ ▓▓ █▓ ▓▓. ▐▓ ▓µ ╓▓▀¬ ▐▓ ▓▌ ▓▌ ', ' ▐▓ ▓▀ █▓ ▐▓~ ▓▀▀▀▀▀▀▀▀ ▓▓▀▀▀▀▀▀▀ ▓█▓▓, ▐▓ "▓▄ ▓▓ ', ' ▓▌▓▌ ▓▌▓▌ ▓▌ ▓▓ ▓µ └█▓, ▐▓ ╙▓ ▐▓ ', ' ▐▓▓ ╙▓▓ ▀▓▄▄▄▄▄▌ ▀▓▄▄▄▄▄▌ ▓µ ╙█▓µ▐▓ ▐▓▓Γ ', ' . .┌ .╘┘─ .└┘, . .. . ╒▓▀ ', ' ╟▓████▓▓▄ ▀▀ ╓▄ ╒▄▄▓▀ ', ' ╟▓ ╙█▓ ,;; ,;, ,;;, ╟▓ . ', ' ╟▓ ▓▌ ▐▓ ╓▓█▀▀▀▀▓▓▀²,▓▀▀▀▀▀▓╕ ▓▓▀▀▀▀▀▀▀▓▓▀▀▀ ', ' ╟▓ ╟▓ ▐▓ ▓▌ ▓▌ ▓▌▄▄▄▄▄▓▓ █▓, ╟▓ ', ' ╟▓ ▓▌ ▐▓ ╙▓▄▄▄▄▄▓█ ▓ΓΓΓΓΓΓΓΓ ¬Γ▀▀▓▄ ╟▓ ', ' ╟▓ ▄▓▀ ▐▓ ▓▀Γ▀ΓΓ █▓ ▓▌ ╟▓ ', ' ╚█████▀▀Γ ▐█ ;▓█████▓▓▄ ╙▀█████▀ ▀█████▀ ▀████ ', ' ▐▓, ▐▓ ', ' `█▓▓▄▄▄▄▓█Γ ', ' ¬╘─ ', ''].join('\n')); var logger = require('npmlog'); var Settings = require('../shared/settings'), settings = new Settings(); if(settings.loggerLevel) { logger.level = settings.loggerLevel; } if(!settings.token) { logger.error('entrypoint', 'You must set your token before getting started. For further information, refer to the Slack documentation: https://api.slack.com/bot-users and this project\'s README file'); return; } // Keep Slack shut. process.env.SLACK_LOG_LEVEL = 'alert'; var Slack = require('slack-client'), Redis = require('ioredis'), Bot = require('./bot'); logger.verbose('entrypoint', `Connecting to Redis @ ${settings.redisUrl}`); var slack = new Slack(settings.token, true, true), redis = new Redis(settings.redisUrl); logger.info('entrypoint', 'Connecting to Slack...'); slack.on('open', () => { var bot = new Bot(slack, logger, settings, redis); //eslint-disable-line no-unused-vars }) .on('error', err => logger.error('entrypoint', 'Error: ', err)) .login(); <file_sep>/src/processor/proc.js var Mongo = require('../shared/mongo'), URI = require('urijs'); class Proc { constructor(logger, settings, redis) { this.logger = logger; this.redis = redis; this.settings = settings; this.db = new Mongo(settings.mongoUrl, logger); this.channels = [].concat(this.settings.channels); this.procId = 0; this.checkedCalls = ['reaction_added', 'reaction_removed', 'message_deleted', 'message_changed', 'message']; // Ensure index on TS this.db.perform((db, callback) => { this.collection = db.collection('items'); db.collection('items').createIndex( { 'ts': 1 }, { 'unique': true }, function(err, results) { callback(); } ); this.loop(); }); } waitForProcess(func, timeout) { var released = false, releaseTime = null, valid = true, id = this.procId++, tout; var invalidate = () => { this.logger.warn(`Proc#${id}`, `Last procedure #${id} took longer than ${timeout}ms. Releasing loop...`); valid = false; callback(); } var callback = () => { clearTimeout(tout); if(!released) { if(valid) { this.logger.verbose(`Proc#${id}`, 'Completed.'); } released = true; releaseTime = Date.now(); this.loop(); } else { var now = Date.now(); this.logger.warn(`Proc#${id}`, `Reentry attempt after ${now - releaseTime}ms.`); } }; tout = setTimeout(invalidate, timeout); this.logger.verbose(`Proc#${id}`, 'Starting'); func(callback); } loop() { this.redis.blpop('digest_process_queue', 0, (err, data) => { try { this.logger.verbose('Proc', `Dequed: ${data}`); data = JSON.parse(data[1]); this.waitForProcess((callback) => this.process(data, callback), 30000); } catch(ex) { this.logger.error('Proc', 'Error processing data: '); this.logger.error('Proc', ex); try { this.redis.rpush('digest_error_queue', JSON.stringify(data)) this.logger.info('Proc', 'Old received data has been pushed back to digest_error_queue.'); } catch(ex) { this.logger.error('Proc', 'Error pushing data to error queue. Data was lost.'); } } }) .catch((ex) => { this.logger.error('Proc', 'Error caught: '); this.logger.error('Proc', ex); }); } channelCheck(chn) { if(!chn) { this.logger.warn('channelCheck', 'Received empty or false-y chn: ', chn); return false; } return this.channels.indexOf(chn) > -1; } process(msg, callback) { if(!msg) { callback(); return; } if(msg.subtype) { msg.type = msg.subtype; } if(this.checkedCalls.indexOf(msg.type) > -1 && !this.channelCheck(msg.channel)) { callback(); return; } var matches; switch(msg.type) { case 'group_joined': if(this.settings.autoWatch) { if(this.channels.indexOf(msg.channel.name) === -1) { this.channels.push(msg.channel.name); } } callback(); break; case 'reaction_added': case 'reaction_removed': var delta = msg.type === 'reaction_added' ? 1 : -1, reaction = msg.reaction; if(reaction.indexOf('::') > -1) { reaction = reaction.split('::')[0]; } this.logger.verbose('Proc', `Message TS ${msg.item.ts} updating reactions index with delta ${delta}`); this.collection.findOne({ ts: msg.item.ts }).then((doc) => { if(doc) { if(!doc.reactions.hasOwnProperty(reaction)) { doc.reactions[reaction] = 0; } doc.reactions[reaction] = Math.max(0, doc.reactions[reaction] + delta); if(doc.reactions[reaction] === 0) { delete doc.reactions[reaction]; } this.collection.replaceOne({ _id: doc._id }, doc, () => { this.redis.publish('digest_notifications', JSON.stringify({ type: 'precache_item', ts: doc.ts })); callback(); }); } else { callback(); } }) .catch((ex) => { logger.error('Proc', `Error processing findOne for ts ${msg.item.ts}`, ex); callback(); }); break; case 'message_deleted': this.collection.deleteMany({ ts: msg.deleted_ts }, (err, num) => { if(num === 1) { this.logger.verbose('Proc', `Message TS ${msg.deleted_ts} removed`); } callback(); }); break; case 'message_changed': this.logger.verbose('Proc', `Message TS ${msg.message.ts} was edited.`); matches = [] URI.withinString(msg.message.text, (u) => { matches.push(u); return u; }); if(matches && matches.length > 0) { this.logger.verbose('Proc', `Message TS ${msg.message.ts} still is eligible.`); // Insert or update. this.collection.findOne({ ts: msg.message.ts }) .then((doc) => { if(doc) { this.logger.verbose('Proc', `Message TS ${msg.message.ts} found on storage. Updating text...`); // update. doc.text = msg.message.text this.collection.replaceOne({ ts: msg.message.ts }, doc, () => callback()); } else { // insert. this.logger.verbose('Proc', `Message TS ${msg.message.ts} not found on storage. Inserting a new one...`); this.collection.insertOne(this.objectForMessage(msg), () => callback()); } }); } else { // delete. this.logger.verbose('Proc', `Message TS ${msg.message.ts} is not eligible anymore and will be removed.`); this.collection.deleteMany({ ts: msg.message.ts }, {}, () => callback()); } break; case 'message': if(msg.text) { matches = []; URI.withinString(msg.text, (u) => { matches.push(u); return u; }); if(matches && matches.length > 0) { this.collection.findOne({ ts: msg.ts }) .then((doc) => { if(!doc) { this.logger.verbose('Loopr', `Message TS ${msg.ts} is eligible and does not exist on storage. Inserting now...`); this.collection.insertOne(this.objectForMessage(msg), () => callback()); } else { this.logger.verbose('Loopr', `Message TS ${msg.ts} is eligible and already exists on storage. Skipping...`); callback(); } }); } else { callback(); } } else { callback(); } break; } } objectForMessage(msg) { return { ts: msg.ts, text: msg.text, channel: msg.channel, reactions: {}, date: Date.now(), user: msg.user, }; } } module.exports = Proc; <file_sep>/src/collector/bot.js var Datastore = require('nedb'), inflection = require('inflection'), URI = require('urijs'), Settings = require('../shared/settings'), Mongo = require('../shared/mongo'); class Bot { constructor(slack, logger, settings, redis) { this.slack = slack; this.logger = logger; this.redis = redis; this.settings = settings; this.looping = false; this.quietLoop = true; this.queue = []; this.channels = settings.channels.map(c => c.toLowerCase()); this.collection = null; logger.info('Bot', `Connected to Slack as @${slack.self.name} on ${slack.team.name}`); var slackChannels = Object.keys(slack.channels) .map(c => slack.channels[c]); slackChannels = slackChannels.concat(Object.keys(slack.groups) .map(g => slack.groups[g]) .map(g => { g.is_member = true; return g; }) ); var unwatchableChannels = slackChannels .filter(c => settings.channels.indexOf(c.name) > -1) .filter(c => !c.is_member) .map(c => c.name); var forgottenChannels = slackChannels .filter(c => c.is_member) .filter(c => settings.channels.indexOf(c.name) == -1) .map(c => c.name); var validChannels = settings.channels .filter(c => unwatchableChannels.indexOf(c) == -1 && forgottenChannels.indexOf(c) == -1); this.channels = validChannels; if(unwatchableChannels.length > 0) { logger.warn('Bot', `Whoa! I'm trying to watch ${inflection.inflect('', unwatchableChannels.length, 'a channel', 'channels')}${inflection.inflect('', unwatchableChannels.length, '', ' in')} which I'm not a member of: ${unwatchableChannels.join(', ')}`); } if(forgottenChannels.length > 0) { logger.warn('Bot', `Hey! I belong to ${inflection.inflect('an', forgottenChannels.length, null, 'some')} unwatched ${inflection.inflect('channel', forgottenChannels.length)}: ${forgottenChannels.join(', ')}`); } if(validChannels.length === 0) { logger.error('Bot', 'Hmm. Looks like I have nothing to watch! Nothing to do! Yay! See u later, alligator.'); process.exit(1); return; } else { logger.info('Bot', `Okay, I will watch ${inflection.inflect('', validChannels.length, 'this', 'these')} ${inflection.inflect('channel', validChannels.length)}: ${validChannels.join(', ')}`); } slack .on('raw_message', msg => this.guard(() => this.onRawMessage(msg))) .on('message', msg => this.guard(() => this.enqueue(msg))) .on('emoji_changed', msg => this.guard(() => this.notifyEmojiChange())); } guard(func) { try { func(); } catch(ex) { this.logger.error('guard', 'Caught excaption:'); this.logger.error('guard', ex); } } notifyEmojiChange() { this.redis.publish('digest_notifications', JSON.stringify({ type: 'emoji_changed' })); } onRawMessage(msg) { if(msg.type.startsWith('reaction_') || msg.type === 'group_joined') { this.enqueue(msg); } } enqueue(msg) { var serializable = {}; var fields = ['channel', 'team', 'text', 'ts', 'type', 'user', 'event_ts', 'item', 'reaction', 'subtype', 'message', 'deleted_ts']; fields.forEach((k) => { if(msg.hasOwnProperty(k)) { serializable[k] = msg[k]; } }); if(serializable.user) { var user = this.slack.getUserByID(serializable.user); serializable.user = { 'real_name': user.real_name, 'username': user.name, 'image': user.profile.image_192, 'title': user.profile.title }; } if(!serializable.channel && serializable.item) { serializable.channel = serializable.item.channel; } if(serializable.channel && typeof(serializable.channel) === 'string') { this.logger.verbose('collector', `Trying to normalise channel: ${serializable.channel}`); serializable.channel = this.slack.getChannelGroupOrDMByID(serializable.channel).name; } if(Object.keys(msg).length > 0) { var serialized = JSON.stringify(serializable); this.logger.verbose('collector', `rpushing to digest_process_queue: ${serialized}`); this.redis.rpush('digest_process_queue', serialized); } if(serializable.type === 'group_joined' && this.settings.autoWatch) { this.logger.info('Collector', `Yay! I've been invited to ${msg.channel.name}! Updating settings...`); var channels = this.settings.channels; channels.push(msg.channel.name); this.settings.channels = channels; if(this.channels.indexOf(msg.channel.name) === -1) { this.channels.push(msg.channel.name); } } } } module.exports = Bot; <file_sep>/src/web/processor.js var async = require('async'), Path = require('path'), fs = require('fs'), request = require('request'), logger = require('npmlog'); class Processor { constructor(settings, logger, plugins, memcached, items) { this.settings = settings; this.logger = logger; this.plugins = plugins; this.items = items; this.memcached = memcached; if(!Processor.emojis) { try { Processor.emojis = JSON.parse(fs.readFileSync(Path.join(__dirname, 'emoji', 'db.json'))); } catch(ex) { this.logger.error('parser', 'Error preloading emoji database. Mayhem is on its way!'); Processor.emojis = null; } } } getEmojiUnicode(name, reentry) { var result = null; if(Processor.emojis) { var item = Processor.emojis.find((e) => e.aliases.indexOf(name) > -1); if(item) { result = item.emoji; } } if(!reentry && !result && Processor.extraEmoji) { var emo = Processor.extraEmoji[name]; if(!emo && (!Processor.lastEmojiUpdate || (Date.now() - Processor.lastEmojiUpdate) > 360000)) { Processor.updateCustomEmojis(this.settings); } else { if(emo.indexOf('http') === -1) { emo = getEmojiUnicode(emo, true); } else { emo = `<img src="${emo}" />`; } result = emo; } } if(reentry && !result) { this.logger.warn('getEmojiUnicode', `Unknown emoji ${name}. Sources exhausted.`); } return result; } addMeta(result, doc) { var copiable = ['user', 'date', 'channel', 'reactions']; var obj = doc[1]; copiable.forEach((k) => result[k] = obj[k]); result.url = doc[0]; result.id = obj._id; this.memcached.set(['d-', doc[1].ts].join(''), JSON.stringify(result), 2592000, (err) => { if(err) { this.logger.error('memcached', 'Error storing cache data: ', err); } }); return result; } runPlugins(doc, callback, index) { index = index || 0; var plug = this.plugins[index]; if(!plug) { // Plugin list is over, and yet document could not be processed. callback(null, null); return; } else { if(plug.canHandle(doc[0])) { plug.process(doc[0], (result) => { if(!result) { this.runPlugins(doc, callback, ++index); } else { if(plug.constructor.isUrlTransformer) { doc[0] = result; this.runPlugins(doc, callback, ++index); } else { callback(null, this.addMeta(result, doc)); } } }); } else { this.runPlugins(doc, callback, ++index); } } } getCached(processable, cached, callback) { var item = this.items.shift(); if(!item) { callback(); } else { this.memcached.get(['d-', item[1].ts].join(''), (err, r) => { if(err || !r) { if(err) { this.logger.error('memcached', 'Error getting item from cache: ', err); } processable.push(item); } else { var c = JSON.parse(r); c.reactions = item[1].reactions; cached.push(c); } this.getCached(processable, cached, callback); }); } } static ensureEmojiCollection(then) { if(!Processor.extraEmoji) { Processor.emojiCollection.find().toArray((err, docs) => { var emojis = {}; docs.forEach(function(i) { emojis[i.name] = i.value; }); Processor.extraEmoji = emojis; Processor.normaliseEmojiAliases(); then(); }); } else { then(); } } static normaliseEmojiAliases() { logger.verbose('normaliseEmojiAliases', 'Starting...'); var emojis = Processor.extraEmoji; Object.keys(emojis) .forEach(function(k) { var value = emojis[k]; if(value.indexOf('alias') === 0) { value = emojis[value.split(':')[1]] emojis[k] = value; } }); logger.verbose('normaliseEmojiAliases', 'Completed.'); } static updateCustomEmojis(settings) { logger.verbose('updateCustomEmojis', 'Updating custom emojis...'); request.get(`https://slack.com/api/emoji.list?token=${settings.token}`, (e, r, body) => { if(!e) { try { var data = JSON.parse(body); if(data.ok) { var emoji = data.emoji; Object.keys(emoji).forEach((k) => { Processor.emojiCollection.findAndModify( { name: k }, /* Query */ [], /* Sort */ { value: emoji[k], name: k }, /* Values */ { new: true, upsert: true }, /* Options */ function() { } /* Noop */ ); if(!Processor.extraEmoji) { Processor.extraEmoji = {}; } Processor.extraEmoji[k] = emoji[k]; }); logger.verbose('updateCustomEmojis', `${Object.keys(emoji).length} emoji(s) processed.`); Processor.normaliseEmojiAliases(); Processor.lastEmojiUpdate = Date.now(); } else { logger.error('updateCustomEmojis', 'Request failed: Invalid payload.'); } } catch(ex) { logger.error('updateCustomEmojis', 'Error requesting:'); logger.error('updateCustomEmojis', ex); } } else { logger.error('updateCustomEmojis', 'Request failed:'); logger.error('updateCustomEmojis', e); } }); } process(callback) { Processor.ensureEmojiCollection(() => { var processable = [], cached = []; this.getCached(processable, cached, () => { this.logger.verbose('processor', `Process result: ${cached.length} cached item(s), ${processable.length} processable items.`); async.map(processable, this.runPlugins.bind(this), (err, result) => { if(err) { this.logger.error('processor', 'Error running async plugns:', err); } result = (result || []).filter((r) => r); this.digest([].concat(cached, result), callback); }); }); }); } digest(result, callback) { var context = { users: [], items: [], itemsForUser: { } }; result.forEach((i) => { i.reactions = Object.keys(i.reactions) .map(r => ({ name: r, count: i.reactions[r], repr: this.getEmojiUnicode(r) })) .sort((a, b) => b.count - a.count); if(!context.users.some(u => u.username === i.user.username)) { context.users.push(i.user); } if(!context.itemsForUser[i.user.username]) { context.itemsForUser[i.user.username] = []; } var totalReactions = i.reactions .map(r => r.count); if(totalReactions.length) { totalReactions = totalReactions.reduce((a, b) => a + b); } else { totalReactions = 0; } i.totalReactions = totalReactions; context.itemsForUser[i.user.username].push(i); context.items.push(i); var u = context.users.find(u => u.username === i.user.username); if(!u.emojis) { u.emojis = {}; } i.reactions.forEach(r => { if(!u.emojis[r.name]) { u.emojis[r.name] = { name: r.name, repr: this.getEmojiUnicode(r.name), count: 0 }; } u.emojis[r.name].count += r.count; }); }); context.users = context.users.map(u => { u.emojis = Object.keys(u.emojis) .map((k) => u.emojis[k]) .sort((a, b) => b.count - a.count) .map((o) => o.repr); return u; }); context.items = context.items.sort((a, b) => b.totalReactions - a.totalReactions); callback(null, context); } } module.exports = Processor; <file_sep>/README.md # D3 Digest <p align="center"> <a href="https://travis-ci.org/d3estudio/d3-digest"><img src="https://img.shields.io/travis/d3estudio/d3-digest.svg" alt="Build Status"></a> <img src="https://img.shields.io/david/d3estudio/d3-digest.svg" alt="Dependency status" /> <img alt="Language" src="https://img.shields.io/badge/language-JS6-yellow.svg" /> <img alt="Platform" src="https://img.shields.io/badge/platform-NodeJS-brightgreen.svg" /> <img alt="License" src="https://img.shields.io/badge/license-MIT-blue.svg" /> </p> Here at [D3 Estúdio](http://d3.do), Slack is our primary communication channel. Found a nice article? Slack. Found a cool gif? Slack. Want to spread the word about an event? Well, guess what? Slack. We have been overusing the (relatively) new [Reactions](http://slackhq.com/post/123561085920/reactions) feature lately, and we stumbled on a nice idea: _Why not create a digest based on these reactions_? Well, this is what **D3 Digest** does: it watches channels through a bot and stores messages and their respective reactions. ## Installing The development environment is managed by [Azk](http://azk.io), which handles Docker and VirtualBox in order to keep everything running smoothly. To get up and running on your machine, follow these steps: 1. Download and install [Docker Toolbox](https://www.docker.com/docker-toolbox). 2. Install [Azk](http://docs.azk.io/en/installation/) 3. Clone this repo and `cd` into it. 4. Run `script/bootstrap`, which will create your `settings.json` file. 1. Head to [Slack Team Customization Page](http://my.slack.com/services/new/bot) and create a new bot and get its token. 2. Fill the `token` property on the recently-generated `settings` file. 5. Start applications you want: 1. To start the `watcher` process, that connects to Slack and watches predefined channels (please refer to the list below), run `azk start watcher`. 2. To start the `web` process, that allows you to see collected links and reactions, run `azk start web`. 6. To check system status, use `azk status`. This command will also shows hostnames and ports. > **Note**: You can also open the web application by running `azk open web`. ## Configuration options You can customize how your instance works and picks data by changing other configuration options on `settings.json`. See the list below: - `token`: `String` - Your Slack Bot token key. - Defaults to `''`. - `channels`: `[String]` - List of channels to be watched. - Defaults to `['random']`. - `loggerLevel`: `String` - Logging output level. Valid values are `silly`, `verbose`, `info`, `warn` and `error`. - Defaults to `info`. - `autoWatch`: `Boolean` - Defines whether new channels should be automatically watched. When set to `true`, any channel that the bot is invited to will automatically be inserted to the `channels` list, and your `settings.json` file will be overwritten with the new contents. - Defaults to `false` - `silencerEmojis`: `[String]` - Do not parse links containing the specified emoji. Please notice that this removes the link from the parsing process, which means that the link will be stored, even if a valid "silencer emoji" is used as a reaction. - Defaults to `['no_entry_sign']` - `twitterConsumerKey`: `String` - Used by the Twitter parsing plugin to expand twitter urls into embeded tweets. To use this, register a new Twitter application and provide your API key in this field. When unset, the Twitter parsing plugin will refuse to expand twitter urls. - Defaults to `undefined` - `twitterConsumerSecret`: `String` - Required along with `twitterConsumerKey` by the Twitter parsing plugin, if you intend to use it. Please provide your API secret in this field. - Defaults to `undefined` - `mongoUrl`: `String` - URL to your local Mongo instance, used to store links and reactions. - Defaults to `mongodb://localhost:27017/digest` - `memcachedHost`: `String` - IP to local Memcached server. This is used to store processed links, like its metadata or HTML content. Notice that, although this is not required, it will improve drastically the time required by the web interface to load and show the items. - Defaults to `127.0.0.1` - `memcachedPort`: `String` or `Number` - Port where your Memcached server is running. - Defaults to `11211` - `outputDayRange`: `Number` - Range of days to gather links from. This is used by the web interface to paginate requests for links. - Defaults to `1`. - `timezone`: `String` - Timezone of your Slack team. - Defaults to `America/Sao_Paulo` - `showLinksWithoutReaction`: `Boolean` - Defines the behaviour of the web interface regarding collected links without reactions. When set to `true`, links without reactions will also be shown on the web interface. - Defaults to `false` # API The web server exposes an API that allows the frontend to get links and reactions. The server actually exposes two endpoints: - `/api/latest` - `/api/from/<int>` Calling any of the listed endpoints will result in the same kind of response, which will have the following structure: - `from` and `until`: Used when querying the database, defines the range of time that composes the resulting `items` object. `from` must be used to future calls to `/api/from`, being passed to the `<int>` parameter. - `items`: See next topic. ## `items` The `items` property exposes informations about users who sent links, and their respective links. Available properties are: - `users`: `Array` of `Object`s. Contains all users who contributed to the generated digest. - `items`: `Array` of `Object`s. The parsed links. - `itemsForUser`: `Object`. Maps every item in `items` to its respective `user`. ## `users` An `User` object contains information a given user that combributed to the generated digest. Useful if you intend to make an index. Each object contains the following fields: - `real_name`: Full user's name. - `username`: Slack username of the user. - `image`: Slack avatar of the user. - `title`: Slack title. Usually people fill this field with what they do in your company/group. - `emojis`: List of emoji used in reactions to posts made by this user. ## `items` An `Item` represents a link posted to a watched channel. Its contents depends on which plugin parsed the link, but common keys are: - `type`: String representing the resulting item type. You can find a list of builtin types below. - `user`: `User` that posted this item - `reactions`: Array containing a list of reactions received by this post. Each item have the following structure: - `name`: Emoji name used on the reaction. - `count`: Number of times the item received this reaction. - `totalReactions`: Sum of the reactions amount received by this item. - `date`: Date this item was posted relative to Unix Epoch. - `channel`: Name of the channel that this item was found. - `id`: Unique identifier of this item. ### Item type: `youtube` The item was detected as an YouTube video. In this case, the following keys might be found: - `title`: Video title - `html`: HTML used to display the embeded video. - `thumbnail_height`: Height, in pixels, of the video's thumbnail. - `thumbnail_width`: Width, in pixels, of the video's thumbnail. - `thumbnail_url`: Url pointing to the video's thumbnail. ### Item type: `vimeo` Same as `youtube`, with one more property: - `description`: Video description ### Item type: `xkcd` Represents an XKCD comic. Keys are: - `img`: URL of the comic image. - `title`: Comic title - `link`: Link to the original comic post. ### Item type: `tweet` Represents a tweet. Keys are: - `html`: HTML used to display the embeded tweet. This also includes javascript, directly from Twitter. > **Note**: The Twitter plugin requires certain configuration properties to be set. Please refer to the [Configuration Options](#configuration-options) section for more information. ### Item type: `spotify` Represents a Spotify album, song, artist or playlist. Keys are: - `html`: HTML used to display the embeded spotify player. ### Item type: `rich-link` Represents a link that has does not match any other plugin and had its OpenGraph details extracted. Keys are: - `title`: Page title or OpenGraph item name - `summary`: Page description or OpenGraph item description - `image`: Image representing the item, or, the first image found in the page - `imageOrientation`: Is this image vertical or horizontal? It matters, you see. > **Note**: To learn more about OpenGraph, refer to the [OpenGraph Protocol Official Website](http://ogp.me). ### Item type: `poor-link` This is a special item kind, that represents an object that could not be parsed by any of the available plugins. Its keys are: - `url`: Item URL. - `title`: Item title. ---- # License ``` The MIT License (MIT) Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` <file_sep>/src/shared/mongo.js // Marked to removal var MongoClient = require('mongodb').MongoClient; class Mongo { constructor(url, logger) { this.driver = null; this.logger = logger; this.queue = []; this.performing = false; MongoClient.connect(url, (err, db) => { if(err) { this.logger.error('Mongo', 'Error connecting to MongoDB instance: ', err); return; } this.driver = db; this.logger.verbose('Mongo', `Connected: ${url}`); this._processQueue(); }); } isConnected() { return this.driver !== null; } perform(func) { if(!this.driver) { this.queue.push(func); } else { func(this.driver, function() {}); } } _processQueue() { this.queue.forEach((func) => { try { func(this.driver, function() {}); } catch(ex) { this.logger.error('Mongo', 'Error performing operation: ', ex); } }); } } module.exports = Mongo; <file_sep>/src/processor/main.js var logger = require('npmlog'), Redis = require('ioredis'); var Settings = require('../shared/settings'), Proc = require('./proc'), settings = new Settings(); if(settings.loggerLevel) { logger.level = settings.loggerLevel; } logger.verbose('entrypoint', `Connecting to Redis @ ${settings.redisUrl}`); var redis = new Redis(settings.redisUrl), proc = new Proc(logger, settings, redis); <file_sep>/Azkfile.js systems({ 'web': { depends: ['db', 'memcached', 'redis'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/web/main.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, ports: { http: '2708/tcp' }, envs: { NODE_ENV: 'dev', PORT: '2708', }, }, 'collector': { depends: ['redis'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/collector/main.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, envs: { NODE_ENV: 'dev', }, }, 'processor': { depends: ['redis', 'db'], image: {'docker': 'azukiapp/node:5'}, provision: [ 'npm install' ], workdir: '/azk/#{manifest.dir}', shell: '/bin/bash', command: "node --use_strict src/processor/main.js", wait: 20, mounts: { '/azk/#{manifest.dir}': sync('.'), '/azk/#{manifest.dir}/node_modules': persistent('./node_modules'), }, scalable: {'default': 1}, envs: { NODE_ENV: 'dev', }, }, 'db': { image: {'docker': 'azukiapp/mongodb'}, scalable: false, wait: {'retry': 20, 'timeout': 1000}, mounts: { '/data/db': persistent('mongodb-#{manifest.dir}'), }, ports: { http: '28017:28017/tcp', }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'], }, export_envs: { MONGODB_URI: 'mongodb://#{net.host}:#{net.port[27017]}/#{manifest.dir}_development' }, }, 'memcached': { image: {'docker': 'memcached'}, scalable: false, wait: {'retry': 20, 'timeout': 1000}, ports: { http: '11211:11211/tcp' }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, export_envs: { MEMCACHED_HOST: '#{net.host}', MEMCACHED_PORT: '#{net.port[11211]}' } }, 'redis': { image: { docker: 'redis' }, ports: { http: '6379:6379/tcp' }, http: { domains: ['#{manifest.dir}-#{system.name}.#{azk.default_domain}'] }, export_envs: { REDIS_URL: 'redis://#{manifest.dir}-#{system.name}.#{azk.default_domain}:#{net.port[6379]}', REDIS_HOST: '#{net.host}', REDIS_PORT: '#{net.port[6379]}' } } }); <file_sep>/script/bootstrap #!/bin/bash echo '' if [ ! -f settings.json ]; then echo -e "\033[92mCreated:\033[0m settings.json" echo -e "{\n \"token\": \"\"\n}" > settings.json else echo -e "\033[96mSkipped:\033[0m settings.json (already present)" fi echo '' <file_sep>/src/web/plugins/vimeo.js var Plugin = require('./baseplugin'), request = require('request'); class Vimeo extends Plugin { init() { this.regex = /^https?:\/\/vimeo\.com\/.*$/; } canHandle(url) { return url.match(this.regex); } process(url, callback) { this.logger.verbose('vimeo', `processing ${url}`); request.get({ url: `https://vimeo.com/api/oembed.json?url=${url}` }, (e, r, body) => { if(e) { this.logger.error('vimeo', 'Error processing request: ', e); callback(null); } else { try { var json = JSON.parse(body), fields = ['description', 'title', 'html', 'thumbnail_height', 'thumbnail_width', 'thumbnail_url'], res = { type: 'vimeo' }; fields.forEach((f) => res[f] = json[f]); callback(res); } catch(ex) { this.logger.error('vimeo', 'Error processing response: ', ex); callback(null); } } }); } } module.exports = Vimeo; <file_sep>/src/web/plugins/spotify.js var Plugin = require('./baseplugin'), request = require('request'); class Spotify extends Plugin { init() { this.httpRegex = /(?:https?:\/\/)?open\.spotify\.com\/(album|track|user\/[^\/]+\/playlist)\/([a-zA-Z0-9]+)/; this.uriRegex = /^spotify:(album|track|user:[^:]+:playlist):([a-zA-Z0-9]+)$/; } canHandle(url) { return this.httpRegex.test(url) || this.uriRegex.test(url); } process(url, callback) { this.logger.verbose('spotify', `processing ${url}`); request.get({ url: `https://embed.spotify.com/oembed/?url=${url}`, headers: {'User-Agent': 'request'} }, (e, r, body) => { if(e) { this.logger.error('spotify', 'Error processing request: ', e); callback(null); } else { try { callback({ type: 'spotify', html: JSON.parse(body).html }); } catch(ex) { this.logger.error('spotify', 'Error parsing response: ', ex); this.logger.error('spotify', `Body was: ${body}`); callback(null); } } }); } } module.exports = Spotify; <file_sep>/src/web/emoji/gen.rb require 'net/http' require 'uri' require 'json' data = Net::HTTP.get(URI.parse('https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji.json')) data = JSON.parse(data) def map_unified(item) item.split('-').map { |i| [i.hex].pack('U') }.join('') end items = {} data.each do |raw_emoji| unless items.include? raw_emoji['unified'] repr = raw_emoji['unified'] repr = raw_emoji['variations'][0] if raw_emoji['variations'].length == 1 items[raw_emoji['unified']] = { emoji: "#{map_unified(repr)}", aliases: [] } end raw_emoji['short_names'].each { |a| items[raw_emoji['unified']][:aliases].push(a) } end result = items.values() extra_result = [] begin extra_data = JSON.parse(File.read(File.expand_path('../extra.json', __FILE__))) extra_result = extra_data.map { |e| { aliases: e.split(',') } } rescue Exception => ex end File.write(File.expand_path('../db.json', __FILE__), JSON.dump(result + extra_result)) <file_sep>/src/shared/settings.js var fs = require('fs'), Path = require('path'), logger = require('npmlog'); var defaultSettings = { token: '', channels: ['random'], loggerLevel: 'info', autoWatch: false, silencerEmojis: ['no_entry_sign'], mongoUrl: process.env.MONGODB_URI || 'mongodb://localhost:27017/digest', memcachedHost: process.env.MEMCACHED_HOST || '127.0.0.1', memcachedPort: process.env.MEMCACHED_PORT || '11211', redisUrl: process.env.REDIS_URL || 'redis://127.0.0.1:6379', outputLimit: 20, timezone: 'America/Sao_Paulo', showLinksWithoutReaction: false }; class Settings { static rootPath() { return Path.join(__dirname, '..', '..'); } static getSettingsPath() { return process.env.WD_SETTINGS || Path.join(Settings.rootPath(), './settings.json'); } static loadSettings() { return JSON.parse(fs.readFileSync(Settings.getSettingsPath())); } constructor() { this.settingsLoaded = false; this.messageMatcherRegex = /\b(http|https)?(:\/\/)?(\S*)\.(\w{2,4})(\/([^\s]+))?\b/ig; var readSettings = defaultSettings; try { readSettings = Settings.loadSettings(); this.settingsLoaded = true; } catch(ex) { if(ex.code === 'ENOENT') { logger.error('settings', 'Settings file could not be found. Assuming default settings...'); } else if(ex instanceof SyntaxError) { logger.error('settings', 'Error parsing Settings file: ', ex); } else { logger.error('settings', 'Unexpected error: ', ex); } } var settingsKeys = Object.keys(readSettings), defaultKeys = Object.keys(defaultSettings), channels = defaultSettings.channels; defaultKeys.forEach(key => { if(key !== 'channels') { if(settingsKeys.indexOf(key) === -1) { readSettings[key] = defaultSettings[key]; } } else { if(settingsKeys.indexOf('channels') > -1) { channels = readSettings.channels; } } }); delete readSettings['channels']; this._channels = channels; Object.assign(this, readSettings); Object.defineProperty(this, 'channels', { get: () => { return this._channels; }, set: value => { var settings = readSettings; try { settings = Settings.readSettings(); } catch(ex) { /* Too bad. */ } settings.channels = [ ...new Set(this._channels.concat(settings.channels).concat(value)) ].filter(v => v); try { fs.writeFileSync(Settings.getSettingsPath(), JSON.stringify(settings, null, 4)); } catch(ex) { logger.error('settings', 'Cannot rewrite settings: ', ex); } this._channels = settings.channels; } }); } } module.exports = Settings; <file_sep>/src/web/plugins/baseplugin.js class Plugin { constructor(settings, logger) { this.settings = settings; this.logger = logger; this.init(); } init() { } canHandle() { return false; } process(url, callback) { return callback({}); } } Plugin.isUrlTransformer = false; // When true, automatically sets priority as 2: Super high Plugin.priority = 0; // Values: -1: Low, 0: Normal, 1: High module.exports = Plugin; <file_sep>/src/web/parser.js var Processor = require('./processor'), URI = require('urijs'); class Parser { constructor(logger, settings, plugins, mongo, memcached) { this.logger = logger; this.settings = settings; this.mongo = mongo; this.memcached = memcached; this.plugins = plugins; } static prepareDocuments(settings, docs) { docs = docs .filter((d) => !Object.keys(d.reactions).some((r) => settings.silencerEmojis.indexOf(r) > -1)) .filter((d) => { var matches = []; URI.withinString(d.text, function(u) { matches.push(u); return u; }); return matches.length > 0; }); if(docs.length < 1) { return []; } return docs.map((d) => { var url = null; URI.withinString(d.text, (u) => { url = url || u; return u; }); if(!url) { return null; } return [url, d]; }) .filter((d) => d); } itemsInRange(skipping, callback) { var slackUrlSeparator = /<(.*)>/; this.logger.verbose('parser', `Selecting ${this.settings.outputLimit} after ${skipping} items...`); this.mongo.perform((db, dbCallback) => { var query = {}, opts = { limit: this.settings.outputLimit, sort: '_id' }; if(!this.settings.showLinksWithoutReaction) { query.$where = 'Object.keys(this.reactions).length > 0'; } if(skipping > 0) { opts.skip = skipping; } db.collection('items').find(query, opts).toArray((err, docs) => { if(err) { callback(err, null); } else { this.logger.verbose('parser', `Acquired ${docs.length} documents`); docs = Parser.prepareDocuments(this.settings, docs); if(docs.length < 1) { this.logger.verbose('parser', 'No valid documents in range.'); callback(null, null); return; } this.logger.verbose('parser', `Handling ${docs.length} document(s) to processor...`); var processor = new Processor(this.settings, this.logger, this.plugins, this.memcached, docs); processor.process((err, result) => { callback(err, result) }); } }); dbCallback(); }); } } module.exports = Parser; <file_sep>/script/parse #!/usr/bin/env bash node --use_strict src/parser/main.js $@ <file_sep>/src/web/plugins/xkcd.js var Plugin = require('./baseplugin'), request = require('request'), cheerio = require('cheerio'); class XKCD extends Plugin { init() { this.regex = /^(https?:\/\/)?(www\.)?xkcd\.com\/(\d+)\/?$/i; } canHandle(url) { return url.match(this.regex); } process(url, callback) { this.logger.verbose('xkcd', `processing ${url}`); request.get({ url: url }, (e, r, body) => { if(e) { callback(null); this.logger.error('xkcd', 'Error processing request: ', e); return; } var $ = cheerio.load(body), img = $('#comic > img').first(); if(img.length === 1) { callback({ 'type': 'xkcd', 'img': img.attr('src'), 'title': img.attr('alt'), 'explain': img.attr('title'), 'link': url }); } else { this.logger.error('Empty XKCD #comic > img'); callback(null); } }); } } module.exports = XKCD;
33d399b2e131a4247749ebe07823ccb4ef895857
[ "JavaScript", "Ruby", "Markdown", "Shell" ]
19
Shell
juniormag/d3-digest
70f1cdaa65ca5c674dccceae556d6f5692e77e97
828f54dea28bb379921cb890f83c2c1aa532657d
refs/heads/master
<repo_name>vergeeva/Practical_4<file_sep>/MyForm.h #pragma once #include "Header.h" namespace Практика4 { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { List = gcnew List_D; List_Two = gcnew List_D; InitializeComponent(); // //TODO: добавьте код конструктора // } protected: List_D^ List; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::Button^ button8; protected: List_D^ List_Two; /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::ListBox^ listBox1; protected: private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::GroupBox^ groupBox2; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::TextBox^ textBox3; private: System::Windows::Forms::TextBox^ textBox4; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::GroupBox^ groupBox3; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::TextBox^ textBox5; private: System::Windows::Forms::TextBox^ textBox6; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button6; private: /// <summary> /// Обязательная переменная конструктора. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> void InitializeComponent(void) { this->listBox1 = (gcnew System::Windows::Forms::ListBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->button2 = (gcnew System::Windows::Forms::Button()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->label2 = (gcnew System::Windows::Forms::Label()); this->label3 = (gcnew System::Windows::Forms::Label()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->groupBox2 = (gcnew System::Windows::Forms::GroupBox()); this->button8 = (gcnew System::Windows::Forms::Button()); this->label6 = (gcnew System::Windows::Forms::Label()); this->button5 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->label4 = (gcnew System::Windows::Forms::Label()); this->textBox6 = (gcnew System::Windows::Forms::TextBox()); this->label5 = (gcnew System::Windows::Forms::Label()); this->textBox4 = (gcnew System::Windows::Forms::TextBox()); this->button3 = (gcnew System::Windows::Forms::Button()); this->textBox3 = (gcnew System::Windows::Forms::TextBox()); this->groupBox3 = (gcnew System::Windows::Forms::GroupBox()); this->button7 = (gcnew System::Windows::Forms::Button()); this->button6 = (gcnew System::Windows::Forms::Button()); this->label7 = (gcnew System::Windows::Forms::Label()); this->textBox5 = (gcnew System::Windows::Forms::TextBox()); this->button1 = (gcnew System::Windows::Forms::Button()); this->groupBox1->SuspendLayout(); this->groupBox2->SuspendLayout(); this->groupBox3->SuspendLayout(); this->SuspendLayout(); // // listBox1 // this->listBox1->FormattingEnabled = true; this->listBox1->ItemHeight = 16; this->listBox1->Location = System::Drawing::Point(12, 47); this->listBox1->Name = L"listBox1"; this->listBox1->Size = System::Drawing::Size(262, 324); this->listBox1->TabIndex = 0; // // label1 // this->label1->AutoSize = true; this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10.2F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); this->label1->Location = System::Drawing::Point(12, 24); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(185, 20); this->label1->TabIndex = 1; this->label1->Text = L"Имена и их вариации"; // // button2 // this->button2->Location = System::Drawing::Point(19, 117); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(142, 33); this->button2->TabIndex = 3; this->button2->Text = L"Добавить"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click); // // textBox1 // this->textBox1->Location = System::Drawing::Point(19, 44); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(142, 22); this->textBox1->TabIndex = 4; // // textBox2 // this->textBox2->Location = System::Drawing::Point(19, 89); this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(142, 22); this->textBox2->TabIndex = 5; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(16, 24); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(35, 17); this->label2->TabIndex = 6; this->label2->Text = L"Имя"; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(16, 69); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(118, 17); this->label3->TabIndex = 7; this->label3->Text = L"Вариации имени"; // // groupBox1 // this->groupBox1->Controls->Add(this->label3); this->groupBox1->Controls->Add(this->label2); this->groupBox1->Controls->Add(this->textBox2); this->groupBox1->Controls->Add(this->textBox1); this->groupBox1->Controls->Add(this->button2); this->groupBox1->Location = System::Drawing::Point(299, 47); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(200, 167); this->groupBox1->TabIndex = 8; this->groupBox1->TabStop = false; this->groupBox1->Text = L"Добавление"; // // groupBox2 // this->groupBox2->Controls->Add(this->button8); this->groupBox2->Controls->Add(this->label6); this->groupBox2->Controls->Add(this->button5); this->groupBox2->Controls->Add(this->button4); this->groupBox2->Controls->Add(this->label4); this->groupBox2->Controls->Add(this->textBox6); this->groupBox2->Controls->Add(this->label5); this->groupBox2->Controls->Add(this->textBox4); this->groupBox2->Controls->Add(this->button3); this->groupBox2->Controls->Add(this->textBox3); this->groupBox2->Location = System::Drawing::Point(290, 220); this->groupBox2->Name = L"groupBox2"; this->groupBox2->Size = System::Drawing::Size(424, 197); this->groupBox2->TabIndex = 9; this->groupBox2->TabStop = false; this->groupBox2->Text = L"Поиск и редактирование"; // // button8 // this->button8->Location = System::Drawing::Point(228, 157); this->button8->Name = L"button8"; this->button8->Size = System::Drawing::Size(142, 27); this->button8->TabIndex = 9; this->button8->Text = L"Сохранить"; this->button8->UseVisualStyleBackColor = true; this->button8->Click += gcnew System::EventHandler(this, &MyForm::button8_Click); // // label6 // this->label6->AutoSize = true; this->label6->Location = System::Drawing::Point(221, 24); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(118, 17); this->label6->TabIndex = 7; this->label6->Text = L"Вариации имени"; // // button5 // this->button5->Location = System::Drawing::Point(207, 72); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(163, 33); this->button5->TabIndex = 3; this->button5->Text = L"Поиск по вариациям"; this->button5->UseVisualStyleBackColor = true; this->button5->Click += gcnew System::EventHandler(this, &MyForm::button5_Click); // // button4 // this->button4->Location = System::Drawing::Point(19, 157); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(142, 27); this->button4->TabIndex = 8; this->button4->Text = L"Редактировать"; this->button4->UseVisualStyleBackColor = true; this->button4->Click += gcnew System::EventHandler(this, &MyForm::button4_Click); // // label4 // this->label4->AutoSize = true; this->label4->Location = System::Drawing::Point(125, 110); this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(118, 17); this->label4->TabIndex = 7; this->label4->Text = L"Вариации имени"; // // textBox6 // this->textBox6->Location = System::Drawing::Point(207, 44); this->textBox6->Name = L"textBox6"; this->textBox6->Size = System::Drawing::Size(163, 22); this->textBox6->TabIndex = 4; // // label5 // this->label5->AutoSize = true; this->label5->Location = System::Drawing::Point(16, 24); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(35, 17); this->label5->TabIndex = 6; this->label5->Text = L"Имя"; // // textBox4 // this->textBox4->Location = System::Drawing::Point(19, 44); this->textBox4->Name = L"textBox4"; this->textBox4->Size = System::Drawing::Size(142, 22); this->textBox4->TabIndex = 4; // // button3 // this->button3->Location = System::Drawing::Point(19, 72); this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(142, 33); this->button3->TabIndex = 3; this->button3->Text = L"Поиск по имени"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &MyForm::button3_Click); // // textBox3 // this->textBox3->Location = System::Drawing::Point(74, 129); this->textBox3->Name = L"textBox3"; this->textBox3->Size = System::Drawing::Size(247, 22); this->textBox3->TabIndex = 5; // // groupBox3 // this->groupBox3->Controls->Add(this->button7); this->groupBox3->Controls->Add(this->button6); this->groupBox3->Controls->Add(this->label7); this->groupBox3->Controls->Add(this->textBox5); this->groupBox3->Location = System::Drawing::Point(514, 47); this->groupBox3->Name = L"groupBox3"; this->groupBox3->Size = System::Drawing::Size(200, 167); this->groupBox3->TabIndex = 9; this->groupBox3->TabStop = false; this->groupBox3->Text = L"Формирование нового списка"; // // button7 // this->button7->Location = System::Drawing::Point(19, 125); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(142, 27); this->button7->TabIndex = 10; this->button7->Text = L"Сбросить фильтр"; this->button7->UseVisualStyleBackColor = true; this->button7->Click += gcnew System::EventHandler(this, &MyForm::button7_Click); // // button6 // this->button6->Location = System::Drawing::Point(19, 92); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(142, 27); this->button6->TabIndex = 9; this->button6->Text = L"Сформировать"; this->button6->UseVisualStyleBackColor = true; this->button6->Click += gcnew System::EventHandler(this, &MyForm::button6_Click); // // label7 // this->label7->AutoSize = true; this->label7->Location = System::Drawing::Point(16, 44); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(155, 17); this->label7->TabIndex = 8; this->label7->Text = L"Введите первую букву"; // // textBox5 // this->textBox5->Location = System::Drawing::Point(19, 64); this->textBox5->Name = L"textBox5"; this->textBox5->Size = System::Drawing::Size(142, 22); this->textBox5->TabIndex = 5; // // button1 // this->button1->Location = System::Drawing::Point(31, 384); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(197, 33); this->button1->TabIndex = 8; this->button1->Text = L"Удалить выбранное"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click); // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(8, 16); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(743, 443); this->Controls->Add(this->button1); this->Controls->Add(this->groupBox3); this->Controls->Add(this->groupBox2); this->Controls->Add(this->groupBox1); this->Controls->Add(this->label1); this->Controls->Add(this->listBox1); this->Name = L"MyForm"; this->Text = L"Имена и их вариации"; this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->groupBox2->ResumeLayout(false); this->groupBox2->PerformLayout(); this->groupBox3->ResumeLayout(false); this->groupBox3->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) { textBox3->Enabled = false; } private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) { if (textBox1->Text != "" && textBox2->Text != "") { //Добавление элемента New_Node^ AddedNode = gcnew New_Node(textBox1->Text, textBox2->Text); List->Add(AddedNode); List->ViewAll(listBox1); } } private: System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { textBox4->Enabled = false; textBox3->Enabled = true; } private: System::Void button8_Click(System::Object^ sender, System::EventArgs^ e) { textBox4->Enabled = true; textBox3->Enabled = false; // Сохранить if (textBox3->Text != "") { List->Change_New(textBox4->Text, textBox3->Text); List->ViewAll(listBox1); } } private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) { if (textBox4->Text != "") { //Поиск по имени New_Node^ Tmp = gcnew New_Node(List->Find(textBox4->Text)); textBox4->Text = Tmp->name; textBox3->Text = Tmp->var_name; } } private: System::Void button5_Click(System::Object^ sender, System::EventArgs^ e) { if (textBox6->Text != "") { //Поиск по вариациям имен if (List->Find_VN(textBox6->Text) != nullptr) { New_Node^ Tmp = gcnew New_Node(List->Find_VN(textBox6->Text)); textBox4->Text = Tmp->name; } } } private: System::Void button6_Click(System::Object^ sender, System::EventArgs^ e) { if (textBox5->Text != "") { //Создаем новый список по условию List_Two = List->New_List(textBox5->Text); List_Two->ViewAll(listBox1); } } private: System::Void button7_Click(System::Object^ sender, System::EventArgs^ e) { //Показать список без фильтра List->ViewAll(listBox1); } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { //Удаление по индексу ЛистБокса int i = listBox1->SelectedIndex; New_Node^ tmp = gcnew New_Node(List->Find(i)); List->Find_and_Del(tmp); List->ViewAll(listBox1); } }; } <file_sep>/Header.h #pragma once #pragma once using namespace System; //Вариант 2 //Разработать минимальную функциональность класса «Линейный однонаправленный список //с заглавным звеном».Обязательный метод – очистка списка. //Данными списка являются пары «Строка, строка», например, «Александр» – «Саша, Сашенька, Шура, Шурик». //Прикладные задачи //Разработать процедуры решения задач : // найти пару по значению первого поля; // по значению первого поля найти пару, и изменить значение второго поля; // найти пару по значению любого имени из второго поля; // сформировать список из всех имен, начинающихся на указанную букву, например, все //имена на букву «А» ref class New_Node { public: String^ name; //Имя String^ var_name; //Вариации имени New_Node^ next; public: New_Node(void) { name = ""; var_name = ""; next = nullptr; } New_Node(String^ N, String^ D) { name = N; var_name = D; next = nullptr; } New_Node(New_Node^ T) { this->name = T->name; this->var_name = T->var_name; next = nullptr;} virtual String^ ToString() override { return String::Format("{0} - {1};", name, var_name); } New_Node^ operator =(New_Node^ Right) { this->name = Right->name; this->var_name = Right->var_name; return this; } bool operator ==(New_Node^ Right); }; ref class List_D { New_Node^ head; public: List_D(void) { head = gcnew New_Node; head->next = nullptr; } List_D^ List_D::New_List(String^ Nickname) { List_D^ New_List = gcnew List_D(); New_Node^ S; for (S = head; S != nullptr; S = S->next) { if (S->name != "" && S->name[0] == Nickname[0]) { New_Node^ New = gcnew New_Node(S->name, S->var_name); New_List->Add(New); this->head; } } if (New_List->head != nullptr) return New_List; else return nullptr; } New_Node^ List_D::Find(New_Node^ T) { New_Node^ el = gcnew New_Node(); for (el = head; el != nullptr; el = el->next) if (el == T) return el; return nullptr; } New_Node^ List_D::Find(String^ T) { New_Node^ el = gcnew New_Node(); for (el = head; el != nullptr; el = el->next) if (el->name == T) return el; return nullptr; } New_Node^ List_D::Find(int T) { int counter = 0; New_Node^ el = gcnew New_Node(); for (el = head; el != nullptr; el = el->next) { if (counter == T) return el; else counter++; } return nullptr; } New_Node^ List_D::Find_VN(String^ T) { New_Node^ el = gcnew New_Node(); for (el = head; el != nullptr; el = el->next) if (el->var_name == T) return el; return nullptr; } void List_D::Add(New_Node^ AddedNode) { New_Node^ old_el; old_el = head; // Запоминает голову. head = AddedNode; // Делает новый головным. AddedNode->next = old_el; // Перебрасывает указатель на предыдущий. } void Change_New(String^ W, String^ New_VarName) { New_Node^ What = gcnew New_Node(Find(W)); New_Node^ el = gcnew New_Node(); for (el = head; el != nullptr; el = el->next) { if (el == What) { el->var_name = New_VarName; } } } bool List_D::Find_and_Del(New_Node^ what) { New_Node^ S = Find(what); New_Node^ el; if (S != nullptr) { if (what == head) { head = head->next; return true; } else { for (el = head; el != nullptr; el = el->next) { if (el->next == what) { el->next = el->next->next; return true; } } } } else return false; } //Отобразить void ViewAll(System::Windows::Forms::ListBox^ A) { New_Node^ q; A->Items->Clear(); q = head; while (q->next != nullptr) { A->Items->Add(q->ToString()); q = q->next; } } void Clear_All() { head = gcnew New_Node; head->next = nullptr; } }; bool New_Node::operator ==(New_Node^ Right) { return this->name == Right->name && this->var_name == Right->var_name; }
0446dd84aec662ced8274e3a52305fcc9b96cf57
[ "C++" ]
2
C++
vergeeva/Practical_4
8e284f93f43287af415d513e21ccbb977704f985
c5d58f0aaa73ac0ee5bee499aa1b2f16662c3ed7
refs/heads/master
<file_sep># perso.github.io <file_sep><!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title><NAME></title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <header> <ul id="projet" class="dropdown-content"> <li><a class="js-scrollTo" href="#section5">Projet</a></li> <li class="divider"></li> <li><a href="projet.html">Tout mes projets</a></li> <li class="divider"></li> </ul> <nav> <div class="nav-wrapper blue-grey darken-2"> <a data-activates="mobile" class="button-collapse"><i class="material-icons">menu</i></a> <a href="#section1" class="brand-logo center js-scrollTo"><NAME></a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a class="js-scrollTo" href="#section2">Cv</a></li> <li><a class="js-scrollTo" href="#section3">A propos</a></li> <li><a class="js-scrollTo" href="#section4">Experience</a></li> <li><a class="dropdown-button" href="#" data-activates="projet">Projet<i class="material-icons right">arrow_drop_down</i></a></li> <li><a class="js-scrollTo" href="#section6">Me Contacter</a></li> </ul> <ul class="side-nav blue-grey darken-2" id="mobile"> <li class="menu"><h3>Menu</h3></li> <li><a class="js-scrollTo" href="#section2">Cv</a></li> <li><a class="js-scrollTo" href="#section3">A propos</a></li> <li><a class="js-scrollTo" href="#section4">Experience</a></li> <li><a class="js-scrollTo" href="#section5">Projet</a></li> <li><a href="projet.html">Tout mes projets</a></li> <li class="menu"><h3>Me Contacter</h3></li> <li><a class="js-scrollTo" href="#section6" target= _blank>Contact</a></li> <li class="menu"><h3>Me suivre</h3></li> <li><a href="https://github.com/AlexisAubineau" target= _blank>Github</a></li> <li><a target= _blank>Linkedin</a></li> <li><a href="https://twitter.com/Skewrad_Alexis" target= _blank>Twitter</a></li> </ul> </div> </nav> </header> <body> <section id="section1" class="home-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <div class="col s12 l4 Portrait"> </div> <div class="col s12 l7 offset-l1 Bloc"> <h1></h1> <p></p> <a></a> </div> </div> </div> </div> </section> <section id="section2" class="cv-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <div class="col s12 l4 cv_portrait"></div> <div class="col s12 l7 offset-l1 cv_bloc"> <h1>Cv</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sagittis, tortor nec consequat pharetra, neque urna dignissim ipsum, in interdum urna urna sed ex. Donec sed justo nibh. Ut malesuada nibh sed lorem tristique euismod. Nullam quis rhoncus odio. Phasellus convallis nulla id nulla ultricies, vel gravida dui rutrum. Mauris blandit tempor condimentum. Nunc justo felis, fermentum eget ex non, consequat fringilla dui. Integer purus arcu, vulputate sit amet tincidunt in, tempus vel est. Praesent quis porta dolor, sed aliquam metus. Donec id finibus orci, id auctor sem. Mauris turpis ipsum, ornare nec lobortis ut, ullamcorper a mauris. Nam nisi mi, semper id nunc et, aliquet aliquet quam. Phasellus blandit pellentesque turpis, nec lacinia purus hendrerit vel. Duis interdum, tellus et mattis ullamcorper, lectus lectus congue erat, id malesuada ligula nisi id orci. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur sagittis tortor ut nunc gravida suscipit. Donec ut efficitur lacus. Curabitur maximus lectus tortor, a mattis tellus euismod sed. Ut pellentesque justo eu pretium imperdiet. Phasellus porta eros tortor, at dictum risus ultrices vitae. Pellentesque porttitor faucibus condimentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque vitae consequat libero, pulvinar cursus felis. Etiam pellentesque cursus lacus, placerat elementum justo dapibus ac. Phasellus fermentum quam eget orci congue vulputate. Curabitur efficitur nibh eu eleifend fringilla. Praesent accumsan laoreet dapibus. Quisque ipsum massa, interdum mattis nisi nec, venenatis maximus dui. Vestibulum dignissim, metus eget commodo mollis, mauris mauris imperdiet urna, in posuere nunc orci eu risus.</p> <a href="image/CV.zip"><button class="btn waves-effect waves-light" >Télécharger le cv<i class="material-icons right">present_to_all</i></button></a> </div> </div> </div> </div> </section> <section id="section3" class="about-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <div class="col s12 l4 Portrait"> </div> <div class="col s12 l7 offset-l1 Bloc"> <p></p> <a></a> </div> </div> </div> </div> </section> <section id="section4" class="experience-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <h1>Experience:</h1> </div> </div> </div> </section> <section id="section5" class="projet-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <h1>Projet:</h1> <p>Ici vous pourrez trouver tous les projets réalisés lors de mes etudes ainsi que mes projets personnels.</p> </div> <div class="col s12 l4"> <br> <h2>Ol-voyage</h2> <img src="image/ol-voyage.png" class="resume"> <p> Projet effectué en groupe lors de ma première annèe.<br> Mise en pratique de nos connaissance web et sql pour la creation d'un portail de gestion d'une gare. </p> <a href="https://alexisaubineau.github.io/olvoyage.github.io/" target= _blank>Visualiser</a> </div> <div class="col s12 l4"> <br> <h2>O-Library</h2> <p> Projet effectué en groupe lors de ma première annèe.<br> Ce projet est le fil rouge de ma première année, dont nous devions on groupe et moi mettre en a profits ce que nous avions apris lors de cette année pour créer un portail web d'une librarie </p> <a href="#" target= _blank>Visualiser</a> </div> <div class="col s12 l4"> <br> <h2>Abiflizera</h2> <img src="image/abiflizera.png" class="resume"> <p> Projet effectué en groupe lors de ma première annèe.<br> Mise en relation de nos cours et de connaissance pour classer notre site le plus haut en référencement. </p> <a href="https://www.nzt-abiflizera.fr" target= _blank>Visualiser</a> </div> <div class="col s12 l4"> <br> <h2>Shooting Asteroid</h2> <p> Projet effectué en groupe lors de ma première annèe.<br> pour la création d'un jeux video en javascript. </p> <a href="#" target= _blank>Visualiser</a> </div> <div class="col s12 l4"> <br> <h2>Gestion de note</h2> <p> Projet effectué en groupe lors de ma première annèe.<br> Création d'un pannel de gestion de note, comporte une vue admin et une vue utilisateur. </p> <a href="#" target= _blank>Visualiser</a> </div> </div> </div> </section> <section id="section6" class="contact-section"> <div class="container"> <div class="row"> <div class="col s12 l12"> <form name="sentMessage" id="contactForm" novalidate> <div class="input-field col s12"> <label for="name">Nom:</label> <input type="text" class="form-control" id="name" placeholder="Entre un nom."> <p class="help-block"></p> </div> <div class="input-field col s12"> <div class="controls"> <label for="phone">Numéro de téléphone:</label> <input type="tel" class="form-control" id="phone" placeholder="Entrer votre numéro de téléphone"> </div> </div> <div class="input-field col s12"> <div class="controls"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" placeholder="Entrer votre email"> </div> </div> <div class="input-field col s12"> <div class="controls"> <label for="message">Message:</label> <textarea id="message" placeholder="Entrer votre message" maxlength="999"></textarea> </div> </div> <button type="submit" class="btn btn-primary">Envoyer</button> </form> </div> </div> </div> </section> <footer class="page-footer blue-grey darken-2"> <div class="container"> <div class="row"> <div class="col l6 s12"> <h5 class="white-text">Plus d'information:</h5> <p class="grey-text text-lighten-4">&ensp;Vous pouvez me retrouvez sur les liens ci dessous</p> </div> <div class="col l4 offset-l2 s12"> <h5 class="white-text">Liens</h5> <ul> <li><img src="image/contacts.png" alt="" class="circle responsive-img"><div class="links"><span class="grey-text text-lighten-3"><EMAIL></span></div></li> <li><img src="image/github-circle.png" alt="" class="circle responsive-img"><div class="links"><a class="grey-text text-lighten-3" href="https://github.com/AlexisAubineau" target="_blank">Github</a></div></li> <li><img src="image/twitter-circle.png" alt="" class="circle responsive-img"><div class="links"><a class="grey-text text-lighten-3" href="https://twitter.com/Skewrad_Alexis" target="_blank">Twitter</a></div></li> </ul> </div> </div> </div> <div class="footer-copyright"> <div class="container"> © 2017 Copyright Tout droit réservé. </div> </div> </footer> <script src="js/jquery-3.2.0.min.js"></script> <script src="js/materialize.min.js"></script> <script> $(document).ready(function() { $('.js-scrollTo').on('click', function() { var page = $(this).attr('href'); var speed = 2000; $('html, body').animate( { scrollTop: $(page).offset().top }, speed ); return false; }); $(".button-collapse").sideNav(); $(".dropdown-button").dropdown(); $('.parallax').parallax(); }); function ejs_nodroit() { return(false); } document.oncontextmenu = ejs_nodroit; </script> </body> </html><file_sep><?php if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) { echo "Pas d'arguments"; return false; } $name = strip_tags(htmlspecialchars($_POST['name'])); $email_address = strip_tags(htmlspecialchars($_POST['email'])); $phone = strip_tags(htmlspecialchars($_POST['phone'])); $message = strip_tags(htmlspecialchars($_POST['message'])); // Create the email and send the message $to = '<EMAIL>'; $email_subject = "Contact effectué depuis le site par: $name"; $email_body = "Vous avez reçu une demande depuis votre site.\n\n"."Les détails:\n\nNom: $name\n\nEmail: $email_address\n\nTéléphone: $phone\n\nMessage:\n$message"; $headers = "De: [email protected]\n"; $headers .= "Reponse de: $email_address"; mail($to,$email_subject,$email_body,$headers); return true; ?>
ff811c3a5419e6068c0afc3af51d1d014e9ad726
[ "Markdown", "HTML", "PHP" ]
3
Markdown
AlexisAubineau/perso.github.io
183282e2e4d7eabce6e2d9eebd2850146993e8c9
36f9984098a362bc79de1d9db851e62b71158d54
refs/heads/main
<file_sep>Bank_Balane=10000 OLDE_PIN=1234 count=0 while (count<3): while(count<3): PIN = int(input("Enter the PIN:-")) if (PIN == OLDE_PIN): print("Enter 1 for withdraw") print("Enter 2 for Deposite") print("Enter 3 for Reset PIN ") print("Enter 4 for Balance enquiry") Open = int(input("What to open ")) if (Open == 1): print("You can only withdraw the money in between 100 to 4000 ") print("How much do u want to Withdraw:- ") Withdraw = int(input()) if (100 < Withdraw and Withdraw < 4001): print("TAKE your amount", Withdraw) Bank_Balane = Bank_Balane - Withdraw elif (100 >= Withdraw): print("Small amount cant be withdraw") else: print("That much money can not be withdraw") elif (Open == 2): print("YOU CAN ONLY Deposite MORE THAN 100") print("How munch do u want to Deposite") Deposite = int(input()) if (100 < Deposite): print("insers RS:", Deposite, "in the box") Bank_Balane = Bank_Balane + Deposite else: print("That much small amount of money can not be Deposite ") elif (Open == 3): print("Please enter the PIN") User_PIN = int(input()) if (User_PIN == OLDE_PIN): print("Enter the new PIN") User_PIN_1 = int(input()) print("Enter the new PIN again") User_PIN_2 = int(input()) if (User_PIN_1 == User_PIN_2): print("Your new pass word is", User_PIN_1) NEW_USER_PIN = User_PIN_1 else: print("PINs are Not matching") else: print("Wrong PIN") elif (Open == 4): print("Your balance is", Bank_Balane) else: print("no opt found F***") elif(PIN!=1234): count=count+1 if(count==1): print("u have last 2 chances") continue elif(count==2): print("u have last 1chances") continue elif(count==3): print("Account blocked") break print("Good bye") <file_sep># ATM Real ATM machine.
fbd8115464996fe044240757b9ee8956cf49c90d
[ "Markdown", "Python" ]
2
Python
Ayon-SSP/ATM
fbb5b1376e585f4427adc4ce54a1dc901b6169fe
44051c9689093bb4b6180ca9fb9055578cbec1f2