file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
ray.rs | //! This module defines a Ray structure and intersection algorithms
//! for axis aligned bounding boxes and triangles.
use crate::aabb::AABB;
use crate::EPSILON;
use nalgebra::{Point3, Vector3};
use std::f32::INFINITY;
/// A struct which defines a ray and some of its cached values.
#[derive(Debug)]
pub struct Ray {
/// The ray origin.
pub origin: Point3<f32>,
/// The ray direction.
pub direction: Vector3<f32>,
/// Inverse (1/x) ray direction. Cached for use in [`AABB`] intersections.
///
/// [`AABB`]: struct.AABB.html
///
inv_direction: Vector3<f32>,
/// Sign of the direction. 0 means positive, 1 means negative.
/// Cached for use in [`AABB`] intersections.
///
/// [`AABB`]: struct.AABB.html
///
sign: Vector3<usize>,
}
/// A struct which is returned by the `intersects_triangle` method.
pub struct Intersection {
/// Distance from the ray origin to the intersection point.
pub distance: f32,
/// U coordinate of the intersection.
pub u: f32,
/// V coordinate of the intersection.
pub v: f32,
}
impl Intersection {
/// Constructs an `Intersection`. `distance` should be set to positive infinity,
/// if the intersection does not occur.
pub fn new(distance: f32, u: f32, v: f32) -> Intersection {
Intersection { distance, u, v }
}
}
impl Ray {
/// Creates a new [`Ray`] from an `origin` and a `direction`.
/// `direction` will be normalized.
///
/// # Examples
/// ```
/// use bvh::ray::Ray;
/// use bvh::nalgebra::{Point3,Vector3};
///
/// let origin = Point3::new(0.0,0.0,0.0);
/// let direction = Vector3::new(1.0,0.0,0.0);
/// let ray = Ray::new(origin, direction);
///
/// assert_eq!(ray.origin, origin);
/// assert_eq!(ray.direction, direction);
/// ```
///
/// [`Ray`]: struct.Ray.html
///
pub fn new(origin: Point3<f32>, direction: Vector3<f32>) -> Ray {
let direction = direction.normalize();
Ray {
origin,
direction,
inv_direction: Vector3::new(1.0 / direction.x, 1.0 / direction.y, 1.0 / direction.z),
sign: Vector3::new(
(direction.x < 0.0) as usize,
(direction.y < 0.0) as usize,
(direction.z < 0.0) as usize,
),
}
}
/// Tests the intersection of a [`Ray`] with an [`AABB`] using the optimized algorithm
/// from [this paper](http://www.cs.utah.edu/~awilliam/box/box.pdf).
///
/// # Examples
/// ```
/// use bvh::aabb::AABB;
/// use bvh::ray::Ray;
/// use bvh::nalgebra::{Point3,Vector3};
///
/// let origin = Point3::new(0.0,0.0,0.0);
/// let direction = Vector3::new(1.0,0.0,0.0);
/// let ray = Ray::new(origin, direction);
///
/// let point1 = Point3::new(99.9,-1.0,-1.0);
/// let point2 = Point3::new(100.1,1.0,1.0);
/// let aabb = AABB::with_bounds(point1, point2);
///
/// assert!(ray.intersects_aabb(&aabb));
/// ```
///
/// [`Ray`]: struct.Ray.html
/// [`AABB`]: struct.AABB.html
///
pub fn | (&self, aabb: &AABB) -> bool {
let mut ray_min = (aabb[self.sign.x].x - self.origin.x) * self.inv_direction.x;
let mut ray_max = (aabb[1 - self.sign.x].x - self.origin.x) * self.inv_direction.x;
let y_min = (aabb[self.sign.y].y - self.origin.y) * self.inv_direction.y;
let y_max = (aabb[1 - self.sign.y].y - self.origin.y) * self.inv_direction.y;
if (ray_min > y_max) || (y_min > ray_max) {
return false;
}
if y_min > ray_min {
ray_min = y_min;
}
// Using the following solution significantly decreases the performance
// ray_min = ray_min.max(y_min);
if y_max < ray_max {
ray_max = y_max;
}
// Using the following solution significantly decreases the performance
// ray_max = ray_max.min(y_max);
let z_min = (aabb[self.sign.z].z - self.origin.z) * self.inv_direction.z;
let z_max = (aabb[1 - self.sign.z].z - self.origin.z) * self.inv_direction.z;
if (ray_min > z_max) || (z_min > ray_max) {
return false;
}
// Only required for bounded intersection intervals.
// if z_min > ray_min {
// ray_min = z_min;
// }
if z_max < ray_max {
ray_max = z_max;
}
// Using the following solution significantly decreases the performance
// ray_max = ray_max.min(y_max);
ray_max > 0.0
}
/// Naive implementation of a [`Ray`]/[`AABB`] intersection algorithm.
///
/// # Examples
/// ```
/// use bvh::aabb::AABB;
/// use bvh::ray::Ray;
/// use bvh::nalgebra::{Point3,Vector3};
///
/// let origin = Point3::new(0.0,0.0,0.0);
/// let direction = Vector3::new(1.0,0.0,0.0);
/// let ray = Ray::new(origin, direction);
///
/// let point1 = Point3::new(99.9,-1.0,-1.0);
/// let point2 = Point3::new(100.1,1.0,1.0);
/// let aabb = AABB::with_bounds(point1, point2);
///
/// assert!(ray.intersects_aabb_naive(&aabb));
/// ```
///
/// [`Ray`]: struct.Ray.html
/// [`AABB`]: struct.AABB.html
///
pub fn intersects_aabb_naive(&self, aabb: &AABB) -> bool {
let hit_min_x = (aabb.min.x - self.origin.x) * self.inv_direction.x;
let hit_max_x = (aabb.max.x - self.origin.x) * self.inv_direction.x;
let hit_min_y = (aabb.min.y - self.origin.y) * self.inv_direction.y;
let hit_max_y = (aabb.max.y - self.origin.y) * self.inv_direction.y;
let hit_min_z = (aabb.min.z - self.origin.z) * self.inv_direction.z;
let hit_max_z = (aabb.max.z - self.origin.z) * self.inv_direction.z;
let x_entry = hit_min_x.min(hit_max_x);
let y_entry = hit_min_y.min(hit_max_y);
let z_entry = hit_min_z.min(hit_max_z);
let x_exit = hit_min_x.max(hit_max_x);
let y_exit = hit_min_y.max(hit_max_y);
let z_exit = hit_min_z.max(hit_max_z);
let latest_entry = x_entry.max(y_entry).max(z_entry);
let earliest_exit = x_exit.min(y_exit).min(z_exit);
latest_entry < earliest_exit && earliest_exit > 0.0
}
/// Implementation of the algorithm described [here]
/// (https://tavianator.com/fast-branchless-raybounding-box-intersections/).
///
/// # Examples
/// ```
/// use bvh::aabb::AABB;
/// use bvh::ray::Ray;
/// use bvh::nalgebra::{Point3,Vector3};
///
/// let origin = Point3::new(0.0,0.0,0.0);
/// let direction = Vector3::new(1.0,0.0,0.0);
/// let ray = Ray::new(origin, direction);
///
/// let point1 = Point3::new(99.9,-1.0,-1.0);
/// let point2 = Point3::new(100.1,1.0,1.0);
/// let aabb = AABB::with_bounds(point1, point2);
///
/// assert!(ray.intersects_aabb_branchless(&aabb));
/// ```
///
/// [`Ray`]: struct.Ray.html
/// [`AABB`]: struct.AABB.html
///
pub fn intersects_aabb_branchless(&self, aabb: &AABB) -> bool {
let tx1 = (aabb.min.x - self.origin.x) * self.inv_direction.x;
let tx2 = (aabb.max.x - self.origin.x) * self.inv_direction.x;
let mut tmin = tx1.min(tx2);
let mut tmax = tx1.max(tx2);
let ty1 = (aabb.min.y - self.origin.y) * self.inv_direction.y;
let ty2 = (aabb.max.y - self.origin.y) * self.inv_direction.y;
tmin = tmin.max(ty1.min(ty2));
tmax = tmax.min(ty1.max(ty2));
let tz1 = (aabb.min.z - self.origin.z) * self.inv_direction.z;
let tz2 = (aabb.max.z - self.origin.z) * self.inv_direction.z;
tmin = tmin.max(tz1.min(tz2));
tmax = tmax.min(tz1.max(tz2));
tmax >= tmin && tmax >= 0.0
}
/// Implementation of the [Möller-Trumbore triangle/ray intersection algorithm]
/// (https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm).
/// Returns the distance to the intersection, as well as
/// the u and v coordinates of the intersection.
/// The distance is set to +INFINITY if the ray does not intersect the triangle, or hits
/// it from behind.
pub fn intersects_triangle(
&self,
a: &Point3<f32>,
b: &Point3<f32>,
c: &Point3<f32>,
) -> Intersection {
let a_to_b = *b - *a;
let a_to_c = *c - *a;
// Begin calculating determinant - also used to calculate u parameter
// u_vec lies in view plane
// length of a_to_c in view_plane = |u_vec| = |a_to_c|*sin(a_to_c, dir)
let u_vec = self.direction.cross(&a_to_c);
// If determinant is near zero, ray lies in plane of triangle
// The determinant corresponds to the parallelepiped volume:
// det = 0 => [dir, a_to_b, a_to_c] not linearly independant
let det = a_to_b.dot(&u_vec);
// Only testing positive bound, thus enabling backface culling
// If backface culling is not desired write:
// det < EPSILON && det > -EPSILON
if det < EPSILON {
return Intersection::new(INFINITY, 0.0, 0.0);
}
let inv_det = 1.0 / det;
// Vector from point a to ray origin
let a_to_origin = self.origin - *a;
// Calculate u parameter
let u = a_to_origin.dot(&u_vec) * inv_det;
// Test bounds: u < 0 || u > 1 => outside of triangle
if u < 0.0 || u > 1.0 {
return Intersection::new(INFINITY, u, 0.0);
}
// Prepare to test v parameter
let v_vec = a_to_origin.cross(&a_to_b);
// Calculate v parameter and test bound
let v = self.direction.dot(&v_vec) * inv_det;
// The intersection lies outside of the triangle
if v < 0.0 || u + v > 1.0 {
return Intersection::new(INFINITY, u, v);
}
let dist = a_to_c.dot(&v_vec) * inv_det;
if dist > EPSILON {
Intersection::new(dist, u, v)
} else {
Intersection::new(INFINITY, u, v)
}
}
}
#[cfg(test)]
mod tests {
use std::cmp;
use std::f32::INFINITY;
use crate::aabb::AABB;
use crate::ray::Ray;
use crate::testbase::{tuple_to_point, TupleVec};
use crate::EPSILON;
use quickcheck::quickcheck;
/// Generates a random `Ray` which points at at a random `AABB`.
fn gen_ray_to_aabb(data: (TupleVec, TupleVec, TupleVec)) -> (Ray, AABB) {
// Generate a random AABB
let aabb = AABB::empty()
.grow(&tuple_to_point(&data.0))
.grow(&tuple_to_point(&data.1));
// Get its center
let center = aabb.center();
// Generate random ray pointing at the center
let pos = tuple_to_point(&data.2);
let ray = Ray::new(pos, center - pos);
(ray, aabb)
}
// Test whether a `Ray` which points at the center of an `AABB` intersects it.
// Uses the optimized algorithm.
quickcheck! {
fn test_ray_points_at_aabb_center(data: (TupleVec, TupleVec, TupleVec)) -> bool {
let (ray, aabb) = gen_ray_to_aabb(data);
ray.intersects_aabb(&aabb)
}
}
// Test whether a `Ray` which points at the center of an `AABB` intersects it.
// Uses the naive algorithm.
quickcheck! {
fn test_ray_points_at_aabb_center_naive(data: (TupleVec, TupleVec, TupleVec)) -> bool {
let (ray, aabb) = gen_ray_to_aabb(data);
ray.intersects_aabb_naive(&aabb)
}
}
// Test whether a `Ray` which points at the center of an `AABB` intersects it.
// Uses the branchless algorithm.
quickcheck! {
fn test_ray_points_at_aabb_center_branchless(data: (TupleVec, TupleVec, TupleVec)) -> bool {
let (ray, aabb) = gen_ray_to_aabb(data);
ray.intersects_aabb_branchless(&aabb)
}
}
// Test whether a `Ray` which points away from the center of an `AABB`
// does not intersect it, unless its origin is inside the `AABB`.
// Uses the optimized algorithm.
quickcheck! {
fn test_ray_points_from_aabb_center(data: (TupleVec, TupleVec, TupleVec)) -> bool {
let (mut ray, aabb) = gen_ray_to_aabb(data);
// Invert the direction of the ray
ray.direction = -ray.direction;
ray.inv_direction = -ray.inv_direction;
!ray.intersects_aabb(&aabb) || aabb.contains(&ray.origin)
}
}
// Test whether a `Ray` which points away from the center of an `AABB`
// does not intersect it, unless its origin is inside the `AABB`.
// Uses the naive algorithm.
quickcheck! {
fn test_ray_points_from_aabb_center_naive(data: (TupleVec, TupleVec, TupleVec)) -> bool {
let (mut ray, aabb) = gen_ray_to_aabb(data);
// Invert the ray direction
ray.direction = -ray.direction;
ray.inv_direction = -ray.inv_direction;
!ray.intersects_aabb_naive(&aabb) || aabb.contains(&ray.origin)
}
}
// Test whether a `Ray` which points away from the center of an `AABB`
// does not intersect it, unless its origin is inside the `AABB`.
// Uses the branchless algorithm.
quickcheck! {
fn test_ray_points_from_aabb_center_branchless(data: (TupleVec, TupleVec, TupleVec))
-> bool {
let (mut ray, aabb) = gen_ray_to_aabb(data);
// Invert the ray direction
ray.direction = -ray.direction;
ray.inv_direction = -ray.inv_direction;
!ray.intersects_aabb_branchless(&aabb) || aabb.contains(&ray.origin)
}
}
// Test whether a `Ray` which points at the center of a triangle
// intersects it, unless it sees the back face, which is culled.
quickcheck! {
fn test_ray_hits_triangle(a: TupleVec,
b: TupleVec,
c: TupleVec,
origin: TupleVec,
u: u16,
v: u16)
-> bool {
// Define a triangle, u/v vectors and its normal
let triangle = (tuple_to_point(&a), tuple_to_point(&b), tuple_to_point(&c));
let u_vec = triangle.1 - triangle.0;
let v_vec = triangle.2 - triangle.0;
let normal = u_vec.cross(&v_vec);
// Get some u and v coordinates such that u+v <= 1
let u = u % 101;
let v = cmp::min(100 - u, v % 101);
let u = u as f32 / 100.0;
let v = v as f32 / 100.0;
// Define some point on the triangle
let point_on_triangle = triangle.0 + u * u_vec + v * v_vec;
// Define a ray which points at the triangle
let origin = tuple_to_point(&origin);
let ray = Ray::new(origin, point_on_triangle - origin);
let on_back_side = normal.dot(&(ray.origin - triangle.0)) <= 0.0;
// Perform the intersection test
let intersects = ray.intersects_triangle(&triangle.0, &triangle.1, &triangle.2);
let uv_sum = intersects.u + intersects.v;
// Either the intersection is in the back side (including the triangle-plane)
if on_back_side {
// Intersection must be INFINITY, u and v are undefined
intersects.distance == INFINITY
} else {
// Or it is on the front side
// Either the intersection is inside the triangle, which it should be
// for all u, v such that u+v <= 1.0
let intersection_inside = uv_sum >= 0.0 && uv_sum <= 1.0 &&
intersects.distance < INFINITY;
// Or the input data was close to the border
let close_to_border =
u.abs() < EPSILON || (u - 1.0).abs() < EPSILON || v.abs() < EPSILON ||
(v - 1.0).abs() < EPSILON || (u + v - 1.0).abs() < EPSILON;
if !(intersection_inside || close_to_border) {
println!("uvsum {}", uv_sum);
println!("intersects.0 {}", intersects.distance);
println!("intersects.1 (u) {}", intersects.u);
println!("intersects.2 (v) {}", intersects.v);
println!("u {}", u);
println!("v {}", v);
}
intersection_inside || close_to_border
}
}
}
}
#[cfg(all(feature = "bench", test))]
mod bench {
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use crate::aabb::AABB;
use crate::ray::Ray;
use crate::testbase::{tuple_to_point, tuple_to_vector, TupleVec};
/// Generates some random deterministic `Ray`/`AABB` pairs.
fn gen_random_ray_aabb(rng: &mut StdRng) -> (Ray, AABB) {
let a = tuple_to_point(&rng.gen::<TupleVec>());
let b = tuple_to_point(&rng.gen::<TupleVec>());
let c = tuple_to_point(&rng.gen::<TupleVec>());
let d = tuple_to_vector(&rng.gen::<TupleVec>());
let aabb = AABB::empty().grow(&a).grow(&b);
let ray = Ray::new(c, d);
(ray, aabb)
}
/// Benchmark for the optimized intersection algorithm.
#[bench]
fn bench_intersects_aabb(b: &mut ::test::Bencher) {
let seed = [0; 32];
let mut rng = StdRng::from_seed(seed);
b.iter(|| {
let one_thousand = ::test::black_box(1000);
for _ in 0..one_thousand {
let (ray, aabb) = gen_random_ray_aabb(&mut rng);
ray.intersects_aabb(&aabb);
}
});
}
/// Benchmark for the naive intersection algorithm.
#[bench]
fn bench_intersects_aabb_naive(b: &mut ::test::Bencher) {
let seed = [0; 32];
let mut rng = StdRng::from_seed(seed);
b.iter(|| {
let one_thousand = ::test::black_box(1000);
for _ in 0..one_thousand {
let (ray, aabb) = gen_random_ray_aabb(&mut rng);
ray.intersects_aabb_naive(&aabb);
}
});
}
/// Benchmark for the branchless intersection algorithm.
#[bench]
fn bench_intersects_aabb_branchless(b: &mut ::test::Bencher) {
let seed = [0; 32];
let mut rng = StdRng::from_seed(seed);
b.iter(|| {
let one_thousand = ::test::black_box(1000);
for _ in 0..one_thousand {
let (ray, aabb) = gen_random_ray_aabb(&mut rng);
ray.intersects_aabb_branchless(&aabb);
}
});
}
}
| intersects_aabb |
utils.ts | import {
RouterHistory,
RouteRecordRaw,
RouteComponent,
createWebHistory,
createWebHashHistory,
RouteRecordNormalized
} from "vue-router";
import { router } from "./index";
import { loadEnv } from "../../build";
import Layout from "/@/layout/index.vue";
import { useTimeoutFn } from "@vueuse/core";
import { usePermissionStoreHook } from "/@/store/modules/permission";
// https://cn.vitejs.dev/guide/features.html#glob-import
const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
// 动态路由
import { getAsyncRoutes } from "/@/api/routes";
// 按照路由中meta下的rank等级升序来排序路由
function ascending(arr: any[]) {
return arr.sort(
(a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
return a?.meta?.rank - b?.meta?.rank;
}
);
}
// 过滤meta中showLink为false的路由
function filterTree(data: RouteComponent[]) {
const newTree = data.filter(
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
}
// 通过path获取父级路径
function getParentPaths(path: string, routes: RouteRecordRaw[]) {
// 深度遍历查找
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
for (let i = 0; i < routes.length; i++) {
const item = routes[i];
// 找到path则返回父级path
if (item.path === path) return parents;
// children不存在或为空则不递归
if (!item.children || !item.children.length) continue;
// 往下查找时将当前path入栈
parents.push(item.path);
if (dfs(item.children, path, parents).length) return parents;
// 深度遍历查找未找到时当前path 出栈
parents.pop();
}
// 未找到时返回空数组
return [];
}
return dfs(routes, path, []);
}
// 查找对应path的路由信息
function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
let res = routes.find((item: { path: string }) => item.path == path);
if (res) {
return res;
} else {
for (let i = 0; i < routes.length; i++) {
if (
routes[i].children instanceof Array &&
routes[i].children.length > 0
) {
res = findRouteByPath(path, routes[i].children);
if (res) {
return res;
}
}
}
return null;
}
}
// 重置路由
function resetRouter(): void {
router.getRoutes().forEach(route => {
const { name } = route;
if (name) {
router.hasRoute(name) && router.removeRoute(name);
}
});
}
// 初始化路由
function initRouter(name: string) {
return new Promise(resolve => {
getAsyncRoutes({ name }).then(({ info }) => {
if (info.length === 0) {
usePermissionStoreHook().changeSetting(info);
} else {
formatFlatteningRoutes(addAsyncRoutes(info)).map(
(v: RouteRecordRaw) => {
// 防止重复添加路由
if (
router.options.routes[0].children.findIndex(
value => value.path === v.path
) !== -1
) {
return;
} else {
// 切记将路由push到routes后还需要使用addRoute,这样路由才能正常跳转
router.options.routes[0].children.push(v);
// 最终路由进行升序
ascending(router.options.routes[0].children);
if (!router.hasRoute(v?.name)) router.addRoute(v);
}
resolve(router);
}
);
usePermissionStoreHook().changeSetting(info);
}
router.addRoute({
path: "/:pathMatch(.*)",
redirect: "/error/404"
});
});
});
}
/**
* 将多级嵌套路由处理成一维数组
* @param routesList 传入路由
* @returns 返回处理后的一维路由
*/
function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
for (let i = 0; i < routesList.length; i++) {
if (routesList[i].children) {
routesList = routesList
.slice(0, i + 1)
.concat(routesList[i].children, routesList.slice(i + 1));
}
}
return routesList;
}
/**
* 一维数 | 成二级,keep-alive 只支持到二级缓存)
* https://github.com/xiaoxian521/vue-pure-admin/issues/67
* @param routesList 处理后的一维路由菜单数组
* @returns 返回将一维数组重新处理成规定路由的格式
*/
function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
const newRoutesList: RouteRecordRaw[] = [];
routesList.forEach((v: RouteRecordRaw) => {
if (v.path === "/") {
newRoutesList.push({
component: v.component,
name: v.name,
path: v.path,
redirect: v.redirect,
meta: v.meta,
children: []
});
} else {
newRoutesList[0].children.push({ ...v });
}
});
return newRoutesList;
}
// 处理缓存路由(添加、删除、刷新)
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
switch (mode) {
case "add":
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
break;
case "delete":
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
break;
default:
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
useTimeoutFn(() => {
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
}, 100);
}
}
// 过滤后端传来的动态路由 重新生成规范路由
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
if (!arrRoutes || !arrRoutes.length) return;
const modulesRoutesKeys = Object.keys(modulesRoutes);
arrRoutes.forEach((v: RouteRecordRaw) => {
if (v.redirect) {
v.component = Layout;
} else {
const index = modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
v.component = modulesRoutes[modulesRoutesKeys[index]];
}
if (v.children) {
addAsyncRoutes(v.children);
}
});
return arrRoutes;
}
// 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html
function getHistoryMode(): RouterHistory {
const routerHistory = loadEnv().VITE_ROUTER_HISTORY;
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
const historyMode = routerHistory.split(",");
const leftMode = historyMode[0];
const rightMode = historyMode[1];
// no param
if (historyMode.length === 1) {
if (leftMode === "hash") {
return createWebHashHistory("");
} else if (leftMode === "h5") {
return createWebHistory("");
}
} //has param
else if (historyMode.length === 2) {
if (leftMode === "hash") {
return createWebHashHistory(rightMode);
} else if (leftMode === "h5") {
return createWebHistory(rightMode);
}
}
}
export {
ascending,
filterTree,
initRouter,
resetRouter,
getHistoryMode,
addAsyncRoutes,
getParentPaths,
findRouteByPath,
handleAliveRoute,
formatTwoStageRoutes,
formatFlatteningRoutes
};
| 组处理成多级嵌套数组(三级及以上的路由全部拍 |
numstates.go | package gotetra
// Return n(E), the total number of states with energy <= E summed over
// all tetrahedra and band indices.
// The calculation of n(E) is implemented as described in BJA94 Appendix A.
//
// TODO doc
// Uses Kahan summation for improved accuracy on dense mesh.
func NumStates(E float64, n int, Ecache EnergyCache, all_bands_at_once bool) float64 {
num_bands := Ecache.NumBands()
num_tetra := float64(NumTetra(n))
result := 0.0
c := 0.0
if !all_bands_at_once {
for band_index := 0; band_index < num_bands; band_index++ {
for Ets := range IterTetras(n, band_index, Ecache) {
E1, E2, E3, E4 := Ets[0], Ets[1], Ets[2], Ets[3]
contrib := NumStatesContrib(E, E1, E2, E3, E4, num_tetra)
y := contrib - c
t := result + y
c = (t - result) - y
result = t
}
}
} else {
for Ets := range BandIterTetras(n, Ecache) {
for band_index := 0; band_index < num_bands; band_index++ {
E1, E2, E3, E4 := Ets[band_index][0], Ets[band_index][1], Ets[band_index][2], Ets[band_index][3]
contrib := NumStatesContrib(E, E1, E2, E3, E4, num_tetra)
y := contrib - c
t := result + y
c = (t - result) - y
result = t
}
}
}
return result
}
// Return the contribution to the number of states with energy less than
// or equal to E (i.e. the integrated density of states n(E)) from the
// (tetrahedron, band index) pair with the given energies at the vertices.
// The calculation of n(E) is implemented as described in BJA94 Appendix A.
//
// E1, E2, E3, E4 = energies at the vertices of the tetrahedron, in ascending
// order.
//
// num_tetra = total number of tetrahedra in the full Brillouin zone.
// Equal to (volume of tetrahedron) / (volume of full BZ).
func NumStatesContrib(E, E1, E2, E3, E4, num_tetra float64) float64 {
if E <= E1 {
return 0.0
} else if E1 < E && E < E2 | else if E2 < E && E < E3 {
fac := (1.0 / num_tetra) / ((E3 - E1) * (E4 - E1))
esq := (E2-E1)*(E2-E1) + 3*(E2-E1)*(E-E2) + 3*(E-E2)*(E-E2)
ecub := -(((E3 - E1) + (E4 - E2)) / ((E3 - E2) * (E4 - E2))) * (E - E2) * (E - E2) * (E - E2)
return fac * (esq + ecub)
} else if E3 < E && E < E4 {
return (1.0 / num_tetra) * (1.0 - (E4-E)*(E4-E)*(E4-E)/((E4-E1)*(E4-E2)*(E4-E3)))
} else {
// E >= E4
return (1.0 / num_tetra)
}
}
| {
return (1.0 / num_tetra) * (E - E1) * (E - E1) * (E - E1) / ((E2 - E1) * (E3 - E1) * (E4 - E1))
} |
tests.rs | use ndarray::{Array, Array2, ArrayView1, Axis};
#[cfg(feature = "quickcheck")]
use ndarray_rand::rand::{distributions::Distribution, thread_rng};
use ndarray::ShapeBuilder;
use ndarray_rand::rand_distr::Uniform;
use ndarray_rand::{RandomExt, SamplingStrategy};
use quickcheck::quickcheck;
#[test]
fn test_dim() {
let (mm, nn) = (5, 5);
for m in 0..mm {
for n in 0..nn {
let a = Array::random((m, n), Uniform::new(0., 2.));
assert_eq!(a.shape(), &[m, n]);
assert!(a.iter().all(|x| *x < 2.));
assert!(a.iter().all(|x| *x >= 0.));
assert!(a.is_standard_layout());
}
}
}
#[test]
fn test_dim_f() {
let (mm, nn) = (5, 5);
for m in 0..mm {
for n in 0..nn {
let a = Array::random((m, n).f(), Uniform::new(0., 2.));
assert_eq!(a.shape(), &[m, n]);
assert!(a.iter().all(|x| *x < 2.));
assert!(a.iter().all(|x| *x >= 0.));
assert!(a.t().is_standard_layout());
}
}
}
#[test]
#[should_panic]
fn oversampling_without_replacement_should_panic() {
let m = 5;
let a = Array::random((m, 4), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), m + 1, SamplingStrategy::WithoutReplacement);
}
quickcheck! {
fn oversampling_with_replacement_is_fine(m: usize, n: usize) -> bool {
let a = Array::random((m, n), Uniform::new(0., 2.));
// Higher than the length of both axes
let n_samples = m + n + 1;
// We don't want to deal with sampling from 0-length axes in this test
if m != 0 {
if !sampling_works(&a, SamplingStrategy::WithReplacement, Axis(0), n_samples) {
return false;
}
}
// We don't want to deal with sampling from 0-length axes in this test
if n != 0 {
if !sampling_works(&a, SamplingStrategy::WithReplacement, Axis(1), n_samples) {
return false;
}
}
true
}
}
#[cfg(feature = "quickcheck")]
quickcheck! {
fn sampling_behaves_as_expected(m: usize, n: usize, strategy: SamplingStrategy) -> bool {
let a = Array::random((m, n), Uniform::new(0., 2.));
let mut rng = &mut thread_rng();
// We don't want to deal with sampling from 0-length axes in this test
if m != 0 {
let n_row_samples = Uniform::from(1..m+1).sample(&mut rng);
if !sampling_works(&a, strategy.clone(), Axis(0), n_row_samples) {
return false;
}
}
// We don't want to deal with sampling from 0-length axes in this test
if n != 0 {
let n_col_samples = Uniform::from(1..n+1).sample(&mut rng);
if !sampling_works(&a, strategy, Axis(1), n_col_samples) {
return false;
}
}
true
}
}
fn sampling_works(
a: &Array2<f64>,
strategy: SamplingStrategy,
axis: Axis,
n_samples: usize,
) -> bool {
let samples = a.sample_axis(axis, n_samples, strategy);
samples
.axis_iter(axis)
.all(|lane| is_subset(&a, &lane, axis))
}
// Check if, when sliced along `axis`, there is at least one lane in `a` equal to `b`
fn is_subset(a: &Array2<f64>, b: &ArrayView1<f64>, axis: Axis) -> bool {
a.axis_iter(axis).any(|lane| &lane == b)
}
#[test]
#[should_panic]
fn sampling_without_replacement_from_a_zero_length_axis_should_panic() {
let n = 5;
let a = Array::random((0, n), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), 1, SamplingStrategy::WithoutReplacement);
}
#[test]
#[should_panic]
fn | () {
let n = 5;
let a = Array::random((0, n), Uniform::new(0., 2.));
let _samples = a.sample_axis(Axis(0), 1, SamplingStrategy::WithReplacement);
}
| sampling_with_replacement_from_a_zero_length_axis_should_panic |
test_helpers.rs | use crate::client::Client;
use crate::default_client::DefaultClient;
use crate::helper::tick_socket;
use crate::socket::Socket;
use crate::web_socket::WebSocket;
use crate::api::{ApiAccount, ApiGroup};
use crate::http_adapter::RestHttpAdapter;
use crate::session::Session;
use crate::web_socket_adapter::WebSocketAdapter;
use std::collections::HashMap;
pub async fn remove_group_if_exists<C: Client>(
client: &C,
mut session: &mut Session,
group_name: &str,
) |
pub async fn re_create_group<C: Client>(
client: &C,
mut session: &mut Session,
group_name: &str,
) -> ApiGroup {
remove_group_if_exists(client, &mut session, group_name).await;
client
.create_group(&mut session, group_name, None, None, None, Some(true), None)
.await
.unwrap()
}
pub async fn authenticated_client(id_one: &str) -> (DefaultClient<RestHttpAdapter>, Session) {
let client = DefaultClient::new_with_adapter();
let session = client
.authenticate_device(id_one, Some(id_one.clone()), true, HashMap::new())
.await
.unwrap();
return (client, session);
}
pub async fn clients_with_users(
id_one: &str,
id_two: &str,
id_three: &str,
) -> (DefaultClient<RestHttpAdapter>, Session, Session, Session) {
let client = DefaultClient::new_with_adapter();
let session = client
.authenticate_device(id_one, Some(id_one.clone()), true, HashMap::new())
.await
.unwrap();
let session2 = client
.authenticate_device(id_two, Some(id_two.clone()), true, HashMap::new())
.await
.unwrap();
let session3 = client
.authenticate_device(id_three, Some(id_three.clone()), true, HashMap::new())
.await
.unwrap();
return (client, session, session2, session3);
}
pub async fn sockets_with_users(
id_one: &str,
id_two: &str,
) -> (
WebSocket<WebSocketAdapter>,
WebSocket<WebSocketAdapter>,
ApiAccount,
ApiAccount,
) {
let client = DefaultClient::new_with_adapter();
let socket = WebSocket::new_with_adapter();
let socket2 = WebSocket::new_with_adapter();
tick_socket(&socket);
tick_socket(&socket2);
let mut session = client
.authenticate_device(id_one, Some(id_one.clone()), true, HashMap::new())
.await
.unwrap();
let mut session2 = client
.authenticate_device(id_two, Some(id_two.clone()), true, HashMap::new())
.await
.unwrap();
let account1 = client.get_account(&mut session).await.unwrap();
let account2 = client.get_account(&mut session2).await.unwrap();
socket.connect(&mut session, true, -1).await;
socket2.connect(&mut session2, true, -1).await;
(socket, socket2, account1, account2)
}
| {
let groups = client
.list_groups(&mut session, Some(group_name), None, None)
.await;
if let Ok(groups) = groups {
if groups.groups.len() > 0 {
client
.delete_group(&mut session, &groups.groups[0].id)
.await
.unwrap();
}
}
} |
sensor.py | """Support for Ebusd sensors."""
import logging
import datetime
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
TIME_FRAME1_BEGIN = 'time_frame1_begin'
TIME_FRAME1_END = 'time_frame1_end'
TIME_FRAME2_BEGIN = 'time_frame2_begin'
TIME_FRAME2_END = 'time_frame2_end'
TIME_FRAME3_BEGIN = 'time_frame3_begin'
TIME_FRAME3_END = 'time_frame3_end'
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
|
class EbusdSensor(Entity):
"""Ebusd component sensor methods definition."""
def __init__(self, data, sensor, name):
"""Initialize the sensor."""
self._state = None
self._client_name = name
self._name, self._unit_of_measurement, self._icon, self._type = sensor
self.data = data
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self._client_name, self._name)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def device_state_attributes(self):
"""Return the device state attributes."""
if self._type == 1 and self._state is not None:
schedule = {
TIME_FRAME1_BEGIN: None,
TIME_FRAME1_END: None,
TIME_FRAME2_BEGIN: None,
TIME_FRAME2_END: None,
TIME_FRAME3_BEGIN: None,
TIME_FRAME3_END: None
}
time_frame = self._state.split(';')
for index, item in enumerate(sorted(schedule.items())):
if index < len(time_frame):
parsed = datetime.datetime.strptime(
time_frame[index], '%H:%M')
parsed = parsed.replace(
datetime.datetime.now().year,
datetime.datetime.now().month,
datetime.datetime.now().day)
schedule[item[0]] = parsed.isoformat()
return schedule
return None
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
def update(self):
"""Fetch new state data for the sensor."""
try:
self.data.update(self._name, self._type)
if self._name not in self.data.value:
return
self._state = self.data.value[self._name]
except RuntimeError:
_LOGGER.debug("EbusdData.update exception")
| """Set up the Ebus sensor."""
ebusd_api = hass.data[DOMAIN]
monitored_conditions = discovery_info['monitored_conditions']
name = discovery_info['client_name']
dev = []
for condition in monitored_conditions:
dev.append(EbusdSensor(
ebusd_api, discovery_info['sensor_types'][condition], name))
add_entities(dev, True) |
logb.go | // Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package math32
import "math"
// Logb returns the binary exponent of x.
//
// Special cases are:
// Logb(±Inf) = +Inf
// Logb(0) = -Inf
// Logb(NaN) = NaN
func L | x float32) float32 {
return float32(math.Logb(float64(x)))
}
// Ilogb returns the binary exponent of x as an integer.
//
// Special cases are:
// Ilogb(±Inf) = MaxInt32
// Ilogb(0) = MinInt32
// Ilogb(NaN) = MaxInt32
func Ilogb(x float32) int {
return math.Ilogb(float64(x))
}
| ogb( |
config.go | // Copyright 2016 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package embed
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/coreos/etcd/compactor"
"github.com/coreos/etcd/etcdserver"
"github.com/coreos/etcd/pkg/cors"
"github.com/coreos/etcd/pkg/netutil"
"github.com/coreos/etcd/pkg/srv"
"github.com/coreos/etcd/pkg/tlsutil"
"github.com/coreos/etcd/pkg/transport"
"github.com/coreos/etcd/pkg/types"
"github.com/coreos/pkg/capnslog"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"sigs.k8s.io/yaml"
)
const (
ClusterStateFlagNew = "new"
ClusterStateFlagExisting = "existing"
DefaultName = "default"
DefaultMaxSnapshots = 5
DefaultMaxWALs = 5
DefaultMaxTxnOps = uint(128)
DefaultMaxRequestBytes = 1.5 * 1024 * 1024
DefaultGRPCKeepAliveMinTime = 5 * time.Second
DefaultGRPCKeepAliveInterval = 2 * time.Hour
DefaultGRPCKeepAliveTimeout = 20 * time.Second
DefaultListenPeerURLs = "http://localhost:2380"
DefaultListenClientURLs = "http://localhost:2379"
DefaultLogOutput = "default"
// DefaultStrictReconfigCheck is the default value for "--strict-reconfig-check" flag.
// It's enabled by default.
DefaultStrictReconfigCheck = true
// DefaultEnableV2 is the default value for "--enable-v2" flag.
// v2 is enabled by default.
// TODO: disable v2 when deprecated.
DefaultEnableV2 = true
// maxElectionMs specifies the maximum value of election timeout.
// More details are listed in ../Documentation/tuning.md#time-parameters.
maxElectionMs = 50000
)
var (
ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
"Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
DefaultAdvertiseClientURLs = "http://localhost:2379"
defaultHostname string
defaultHostStatus error
)
func init() {
defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
}
// Config holds the arguments for configuring an etcd server.
type Config struct {
// member
CorsInfo *cors.CORSInfo
LPUrls, LCUrls []url.URL
Dir string `json:"data-dir"`
WalDir string `json:"wal-dir"`
MaxSnapFiles uint `json:"max-snapshots"`
MaxWalFiles uint `json:"max-wals"`
Name string `json:"name"`
SnapCount uint64 `json:"snapshot-count"`
// AutoCompactionMode is either 'periodic' or 'revision'.
AutoCompactionMode string `json:"auto-compaction-mode"`
// AutoCompactionRetention is either duration string with time unit
// (e.g. '5m' for 5-minute), or revision unit (e.g. '5000').
// If no time unit is provided and compaction mode is 'periodic',
// the unit defaults to hour. For example, '5' translates into 5-hour.
AutoCompactionRetention string `json:"auto-compaction-retention"`
// TickMs is the number of milliseconds between heartbeat ticks.
// TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
// make ticks a cluster wide configuration.
TickMs uint `json:"heartbeat-interval"`
ElectionMs uint `json:"election-timeout"`
// InitialElectionTickAdvance is true, then local member fast-forwards
// election ticks to speed up "initial" leader election trigger. This
// benefits the case of larger election ticks. For instance, cross
// datacenter deployment may require longer election timeout of 10-second.
// If true, local node does not need wait up to 10-second. Instead,
// forwards its election ticks to 8-second, and have only 2-second left
// before leader election.
//
// Major assumptions are that:
// - cluster has no active leader thus advancing ticks enables faster
// leader election, or
// - cluster already has an established leader, and rejoining follower
// is likely to receive heartbeats from the leader after tick advance
// and before election timeout.
//
// However, when network from leader to rejoining follower is congested,
// and the follower does not receive leader heartbeat within left election
// ticks, disruptive election has to happen thus affecting cluster
// availabilities.
//
// Disabling this would slow down initial bootstrap process for cross
// datacenter deployments. Make your own tradeoffs by configuring
// --initial-election-tick-advance at the cost of slow initial bootstrap.
//
// If single-node, it advances ticks regardless.
//
// See https://github.com/coreos/etcd/issues/9333 for more detail.
InitialElectionTickAdvance bool `json:"initial-election-tick-advance"`
QuotaBackendBytes int64 `json:"quota-backend-bytes"`
MaxTxnOps uint `json:"max-txn-ops"`
MaxRequestBytes uint `json:"max-request-bytes"`
// gRPC server options
// GRPCKeepAliveMinTime is the minimum interval that a client should
// wait before pinging server. When client pings "too fast", server
// sends goaway and closes the connection (errors: too_many_pings,
// http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
// Server expects client pings only when there is any active streams
// (PermitWithoutStream is set false).
GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
// GRPCKeepAliveInterval is the frequency of server-to-client ping
// to check if a connection is alive. Close a non-responsive connection
// after an additional duration of Timeout. 0 to disable.
GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
// GRPCKeepAliveTimeout is the additional duration of wait
// before closing a non-responsive connection. 0 to disable.
GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
// clustering
APUrls, ACUrls []url.URL
ClusterState string `json:"initial-cluster-state"`
DNSCluster string `json:"discovery-srv"`
Dproxy string `json:"discovery-proxy"`
Durl string `json:"discovery"`
InitialCluster string `json:"initial-cluster"`
InitialClusterToken string `json:"initial-cluster-token"`
StrictReconfigCheck bool `json:"strict-reconfig-check"`
EnableV2 bool `json:"enable-v2"`
// security
ClientTLSInfo transport.TLSInfo
ClientAutoTLS bool
PeerTLSInfo transport.TLSInfo
PeerAutoTLS bool
// CipherSuites is a list of supported TLS cipher suites between
// client/server and peers. If empty, Go auto-populates the list.
// Note that cipher suites are prioritized in the given order.
CipherSuites []string `json:"cipher-suites"`
// debug
Debug bool `json:"debug"`
LogPkgLevels string `json:"log-package-levels"`
LogOutput string `json:"log-output"`
EnablePprof bool `json:"enable-pprof"`
Metrics string `json:"metrics"`
ListenMetricsUrls []url.URL
ListenMetricsUrlsJSON string `json:"listen-metrics-urls"`
// ForceNewCluster starts a new cluster even if previously started; unsafe.
ForceNewCluster bool `json:"force-new-cluster"`
// UserHandlers is for registering users handlers and only used for
// embedding etcd into other applications.
// The map key is the route path for the handler, and
// you must ensure it can't be conflicted with etcd's.
UserHandlers map[string]http.Handler `json:"-"`
// ServiceRegister is for registering users' gRPC services. A simple usage example:
// cfg := embed.NewConfig()
// cfg.ServerRegister = func(s *grpc.Server) {
// pb.RegisterFooServer(s, &fooServer{})
// pb.RegisterBarServer(s, &barServer{})
// }
// embed.StartEtcd(cfg)
ServiceRegister func(*grpc.Server) `json:"-"`
// auth
AuthToken string `json:"auth-token"`
// Experimental flags
ExperimentalInitialCorruptCheck bool `json:"experimental-initial-corrupt-check"`
ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"`
ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"`
}
// configYAML holds the config suitable for yaml parsing
type configYAML struct {
Config
configJSON
}
// configJSON has file options that are translated into Config options
type configJSON struct {
LPUrlsJSON string `json:"listen-peer-urls"`
LCUrlsJSON string `json:"listen-client-urls"`
CorsJSON string `json:"cors"`
APUrlsJSON string `json:"initial-advertise-peer-urls"`
ACUrlsJSON string `json:"advertise-client-urls"`
ClientSecurityJSON securityConfig `json:"client-transport-security"`
PeerSecurityJSON securityConfig `json:"peer-transport-security"`
}
type securityConfig struct {
CAFile string `json:"ca-file"`
CertFile string `json:"cert-file"`
KeyFile string `json:"key-file"`
CertAuth bool `json:"client-cert-auth"`
TrustedCAFile string `json:"trusted-ca-file"`
AutoTLS bool `json:"auto-tls"`
}
// NewConfig creates a new Config populated with default values.
func NewConfig() *Config {
lpurl, _ := url.Parse(DefaultListenPeerURLs)
apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
lcurl, _ := url.Parse(DefaultListenClientURLs)
acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
cfg := &Config{
CorsInfo: &cors.CORSInfo{},
MaxSnapFiles: DefaultMaxSnapshots,
MaxWalFiles: DefaultMaxWALs,
Name: DefaultName,
SnapCount: etcdserver.DefaultSnapCount,
MaxTxnOps: DefaultMaxTxnOps,
MaxRequestBytes: DefaultMaxRequestBytes,
GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
TickMs: 100,
ElectionMs: 1000,
InitialElectionTickAdvance: true,
LPUrls: []url.URL{*lpurl},
LCUrls: []url.URL{*lcurl},
APUrls: []url.URL{*apurl},
ACUrls: []url.URL{*acurl},
ClusterState: ClusterStateFlagNew,
InitialClusterToken: "etcd-cluster",
StrictReconfigCheck: DefaultStrictReconfigCheck,
LogOutput: DefaultLogOutput,
Metrics: "basic",
EnableV2: DefaultEnableV2,
AuthToken: "simple",
}
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
return cfg
}
func logTLSHandshakeFailure(conn *tls.Conn, err error) {
state := conn.ConnectionState()
remoteAddr := conn.RemoteAddr().String()
serverName := state.ServerName
if len(state.PeerCertificates) > 0 {
cert := state.PeerCertificates[0]
ips, dns := cert.IPAddresses, cert.DNSNames
plog.Infof("rejected connection from %q (error %q, ServerName %q, IPAddresses %q, DNSNames %q)", remoteAddr, err.Error(), serverName, ips, dns)
} else {
plog.Infof("rejected connection from %q (error %q, ServerName %q)", remoteAddr, err.Error(), serverName)
}
}
// SetupLogging initializes etcd logging.
// Must be called after flag parsing.
func (cfg *Config) SetupLogging() {
cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
capnslog.SetGlobalLogLevel(capnslog.INFO)
if cfg.Debug {
capnslog.SetGlobalLogLevel(capnslog.DEBUG)
grpc.EnableTracing = true
// enable info, warning, error
grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr))
} else {
// only discard info
grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, os.Stderr, os.Stderr))
}
if cfg.LogPkgLevels != "" {
repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
if err != nil {
plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
return
}
repoLog.SetLogLevel(settings)
}
// capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
// where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
// specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
switch cfg.LogOutput {
case "stdout":
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
case "stderr":
capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
case DefaultLogOutput:
default:
plog.Panicf(`unknown log-output %q (only supports %q, "stdout", "stderr")`, cfg.LogOutput, DefaultLogOutput)
}
}
func ConfigFromFile(path string) (*Config, error) {
cfg := &configYAML{Config: *NewConfig()}
if err := cfg.configFromFile(path); err != nil {
return nil, err
}
return &cfg.Config, nil
}
func (cfg *configYAML) configFromFile(path string) error {
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
defaultInitialCluster := cfg.InitialCluster
err = yaml.Unmarshal(b, cfg)
if err != nil {
return err
}
if cfg.LPUrlsJSON != "" {
u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
if err != nil {
plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
}
cfg.LPUrls = []url.URL(u)
}
if cfg.LCUrlsJSON != "" {
u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
if err != nil {
plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
}
cfg.LCUrls = []url.URL(u)
}
if cfg.CorsJSON != "" {
if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
plog.Panicf("unexpected error setting up cors: %v", err)
}
}
if cfg.APUrlsJSON != "" {
u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
if err != nil {
plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
}
cfg.APUrls = []url.URL(u)
}
if cfg.ACUrlsJSON != "" {
u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
if err != nil {
plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
}
cfg.ACUrls = []url.URL(u)
}
if cfg.ListenMetricsUrlsJSON != "" {
u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
if err != nil {
plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
}
cfg.ListenMetricsUrls = []url.URL(u)
}
// If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
cfg.InitialCluster = ""
}
if cfg.ClusterState == "" |
copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
tls.CAFile = ysc.CAFile
tls.CertFile = ysc.CertFile
tls.KeyFile = ysc.KeyFile
tls.ClientCertAuth = ysc.CertAuth
tls.TrustedCAFile = ysc.TrustedCAFile
}
copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
return cfg.Validate()
}
func updateCipherSuites(tls *transport.TLSInfo, ss []string) error {
if len(tls.CipherSuites) > 0 && len(ss) > 0 {
return fmt.Errorf("TLSInfo.CipherSuites is already specified (given %v)", ss)
}
if len(ss) > 0 {
cs := make([]uint16, len(ss))
for i, s := range ss {
var ok bool
cs[i], ok = tlsutil.GetCipherSuite(s)
if !ok {
return fmt.Errorf("unexpected TLS cipher suite %q", s)
}
}
tls.CipherSuites = cs
}
return nil
}
// Validate ensures that '*embed.Config' fields are properly configured.
func (cfg *Config) Validate() error {
if err := checkBindURLs(cfg.LPUrls); err != nil {
return err
}
if err := checkBindURLs(cfg.LCUrls); err != nil {
return err
}
if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
return err
}
if err := checkHostURLs(cfg.APUrls); err != nil {
// TODO: return err in v3.4
addrs := make([]string, len(cfg.APUrls))
for i := range cfg.APUrls {
addrs[i] = cfg.APUrls[i].String()
}
plog.Warningf("advertise-peer-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
}
if err := checkHostURLs(cfg.ACUrls); err != nil {
// TODO: return err in v3.4
addrs := make([]string, len(cfg.ACUrls))
for i := range cfg.ACUrls {
addrs[i] = cfg.ACUrls[i].String()
}
plog.Warningf("advertise-client-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
}
// Check if conflicting flags are passed.
nSet := 0
for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
if v {
nSet++
}
}
if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
}
if nSet > 1 {
return ErrConflictBootstrapFlags
}
if cfg.TickMs <= 0 {
return fmt.Errorf("--heartbeat-interval must be >0 (set to %dms)", cfg.TickMs)
}
if cfg.ElectionMs <= 0 {
return fmt.Errorf("--election-timeout must be >0 (set to %dms)", cfg.ElectionMs)
}
if 5*cfg.TickMs > cfg.ElectionMs {
return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
}
if cfg.ElectionMs > maxElectionMs {
return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
}
// check this last since proxying in etcdmain may make this OK
if cfg.LCUrls != nil && cfg.ACUrls == nil {
return ErrUnsetAdvertiseClientURLsFlag
}
switch cfg.AutoCompactionMode {
case "":
case compactor.ModeRevision, compactor.ModePeriodic:
default:
return fmt.Errorf("unknown auto-compaction-mode %q", cfg.AutoCompactionMode)
}
return nil
}
// PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
token = cfg.InitialClusterToken
switch {
case cfg.Durl != "":
urlsmap = types.URLsMap{}
// If using discovery, generate a temporary cluster based on
// self's advertised peer URLs
urlsmap[cfg.Name] = cfg.APUrls
token = cfg.Durl
case cfg.DNSCluster != "":
clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
if cerr != nil {
plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
return nil, "", cerr
}
for _, s := range clusterStrs {
plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
}
clusterStr := strings.Join(clusterStrs, ",")
if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
}
urlsmap, err = types.NewURLsMap(clusterStr)
// only etcd member must belong to the discovered cluster.
// proxy does not need to belong to the discovered cluster.
if which == "etcd" {
if _, ok := urlsmap[cfg.Name]; !ok {
return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
}
}
default:
// We're statically configured, and cluster has appropriately been set.
urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
}
return urlsmap, token, err
}
func (cfg Config) InitialClusterFromName(name string) (ret string) {
if len(cfg.APUrls) == 0 {
return ""
}
n := name
if name == "" {
n = DefaultName
}
for i := range cfg.APUrls {
ret = ret + "," + n + "=" + cfg.APUrls[i].String()
}
return ret[1:]
}
func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
func (cfg Config) defaultPeerHost() bool {
return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
}
func (cfg Config) defaultClientHost() bool {
return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
}
func (cfg *Config) ClientSelfCert() (err error) {
if !cfg.ClientAutoTLS {
return nil
}
if !cfg.ClientTLSInfo.Empty() {
plog.Warningf("ignoring client auto TLS since certs given")
return nil
}
chosts := make([]string, len(cfg.LCUrls))
for i, u := range cfg.LCUrls {
chosts[i] = u.Host
}
cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
if err != nil {
return err
}
return updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites)
}
func (cfg *Config) PeerSelfCert() (err error) {
if !cfg.PeerAutoTLS {
return nil
}
if !cfg.PeerTLSInfo.Empty() {
plog.Warningf("ignoring peer auto TLS since certs given")
return nil
}
phosts := make([]string, len(cfg.LPUrls))
for i, u := range cfg.LPUrls {
phosts[i] = u.Host
}
cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
if err != nil {
return err
}
return updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites)
}
// UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
// if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
// e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
// then the advertise peer host would be updated with machine's default host,
// while keeping the listen URL's port.
// User can work around this by explicitly setting URL with 127.0.0.1.
// It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
// TODO: check whether fields are set instead of whether fields have default value
func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
if defaultHostname == "" || defaultHostStatus != nil {
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
}
return "", defaultHostStatus
}
used := false
pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
if cfg.defaultPeerHost() && pip == "0.0.0.0" {
cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
used = true
}
// update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
}
cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
if cfg.defaultClientHost() && cip == "0.0.0.0" {
cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
used = true
}
dhost := defaultHostname
if !used {
dhost = ""
}
return dhost, defaultHostStatus
}
// checkBindURLs returns an error if any URL uses a domain name.
func checkBindURLs(urls []url.URL) error {
for _, url := range urls {
if url.Scheme == "unix" || url.Scheme == "unixs" {
continue
}
host, _, err := net.SplitHostPort(url.Host)
if err != nil {
return err
}
if host == "localhost" {
// special case for local address
// TODO: support /etc/hosts ?
continue
}
if net.ParseIP(host) == nil {
return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
}
}
return nil
}
func checkHostURLs(urls []url.URL) error {
for _, url := range urls {
host, _, err := net.SplitHostPort(url.Host)
if err != nil {
return err
}
if host == "" {
return fmt.Errorf("unexpected empty host (%s)", url.String())
}
}
return nil
}
| {
cfg.ClusterState = ClusterStateFlagNew
} |
void.expanded.rs | use serde::{Deserialize, Serialize};
enum Void {}
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _IMPL_SERIALIZE_FOR_Void: () = {
#[allow(unknown_lints)]
#[allow(rust_2018_idioms)] | #[automatically_derived]
impl _serde::Serialize for Void {
fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error>
where
__S: _serde::Serializer,
{
match *self {}
}
}
};
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _IMPL_DESERIALIZE_FOR_Void: () = {
#[allow(unknown_lints)]
#[allow(rust_2018_idioms)]
extern crate serde as _serde;
#[automatically_derived]
impl<'de> _serde::Deserialize<'de> for Void {
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
where
__D: _serde::Deserializer<'de>,
{
#[allow(non_camel_case_types)]
enum __Field {}
struct __FieldVisitor;
impl<'de> _serde::de::Visitor<'de> for __FieldVisitor {
type Value = __Field;
fn expecting(
&self,
__formatter: &mut _serde::export::Formatter,
) -> _serde::export::fmt::Result {
_serde::export::Formatter::write_str(__formatter, "variant identifier")
}
fn visit_u64<__E>(self, __value: u64) -> _serde::export::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
_ => _serde::export::Err(_serde::de::Error::invalid_value(
_serde::de::Unexpected::Unsigned(__value),
&"variant index 0 <= i < 0",
)),
}
}
fn visit_str<__E>(self, __value: &str) -> _serde::export::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
_ => _serde::export::Err(_serde::de::Error::unknown_variant(
__value, VARIANTS,
)),
}
}
fn visit_bytes<__E>(
self,
__value: &[u8],
) -> _serde::export::Result<Self::Value, __E>
where
__E: _serde::de::Error,
{
match __value {
_ => {
let __value = &_serde::export::from_utf8_lossy(__value);
_serde::export::Err(_serde::de::Error::unknown_variant(
__value, VARIANTS,
))
}
}
}
}
impl<'de> _serde::Deserialize<'de> for __Field {
#[inline]
fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error>
where
__D: _serde::Deserializer<'de>,
{
_serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor)
}
}
struct __Visitor<'de> {
marker: _serde::export::PhantomData<Void>,
lifetime: _serde::export::PhantomData<&'de ()>,
}
impl<'de> _serde::de::Visitor<'de> for __Visitor<'de> {
type Value = Void;
fn expecting(
&self,
__formatter: &mut _serde::export::Formatter,
) -> _serde::export::fmt::Result {
_serde::export::Formatter::write_str(__formatter, "enum Void")
}
fn visit_enum<__A>(
self,
__data: __A,
) -> _serde::export::Result<Self::Value, __A::Error>
where
__A: _serde::de::EnumAccess<'de>,
{
_serde::export::Result::map(
_serde::de::EnumAccess::variant::<__Field>(__data),
|(__impossible, _)| match __impossible {},
)
}
}
const VARIANTS: &'static [&'static str] = &[];
_serde::Deserializer::deserialize_enum(
__deserializer,
"Void",
VARIANTS,
__Visitor {
marker: _serde::export::PhantomData::<Void>,
lifetime: _serde::export::PhantomData,
},
)
}
}
}; | extern crate serde as _serde; |
package.py | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class Smartmontools(AutotoolsPackage):
"""S.M.A.R.T. utility toolset."""
homepage = "https://smartmontools.sourceforge.net"
url = "https://nchc.dl.sourceforge.net/project/smartmontools/smartmontools/6.6/smartmontools-6.6.tar.gz"
version('6.6', sha256='51f43d0fb064fccaf823bbe68cf0d317d0895ff895aa353b3339a3b316a53054')
def | (self, env):
env.prepend_path('PATH', self.prefix.sbin)
env.prepend_path('LD_LIBRARY_PATH', self.prefix.usr.lib)
| setup_run_environment |
test_txn07.py | #!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# 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 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.
#
# test_txn07.py
# Transactions: commits and rollbacks
#
import fnmatch, os, shutil, run, time
from suite_subprocess import suite_subprocess
from wiredtiger import stat
from wtscenario import multiply_scenarios, number_scenarios
import wttest
class test_txn07(wttest.WiredTigerTestCase, suite_subprocess):
logmax = "100K"
tablename = 'test_txn07'
uri = 'table:' + tablename
archive_list = ['true', 'false']
sync_list = [
'(method=dsync,enabled)',
'(method=fsync,enabled)',
'(method=none,enabled)',
'(enabled=false)'
]
types = [
('row', dict(tabletype='row',
create_params = 'key_format=i,value_format=S')),
('var', dict(tabletype='var',
create_params = 'key_format=r,value_format=S')),
('fix', dict(tabletype='fix',
create_params = 'key_format=r,value_format=8t')),
]
op1s = [
('trunc-all', dict(op1=('all', 0))),
('trunc-both', dict(op1=('both', 2))),
('trunc-start', dict(op1=('start', 2))),
('trunc-stop', dict(op1=('stop', 2))),
]
txn1s = [('t1c', dict(txn1='commit')), ('t1r', dict(txn1='rollback'))]
compress = [
('nop', dict(compress='nop')),
('snappy', dict(compress='snappy')),
('zlib', dict(compress='zlib')),
('none', dict(compress='')),
]
scenarios = number_scenarios(multiply_scenarios('.', types, op1s, txn1s,
compress))
# Overrides WiredTigerTestCase
def setUpConnectionOpen(self, dir):
self.home = dir
# Cycle through the different transaction_sync values in a
# deterministic manner.
self.txn_sync = self.sync_list[
self.scenario_number % len(self.sync_list)]
self.backup_dir = os.path.join(self.home, "WT_BACKUP")
conn_params = \
'log=(archive=false,enabled,file_max=%s,' % self.logmax + \
'compressor=%s)' % self.compress + \
self.extensionArg(self.compress) + \
',create,error_prefix="%s: ",' % self.shortid() + \
"statistics=(fast)," + \
'transaction_sync="%s",' % self.txn_sync
# print "Creating conn at '%s' with config '%s'" % (dir, conn_params)
try:
conn = self.wiredtiger_open(dir, conn_params)
except wiredtiger.WiredTigerError as e:
print "Failed conn at '%s' with config '%s'" % (dir, conn_params)
self.pr(`conn`)
self.session2 = conn.open_session()
return conn
# Return the wiredtiger_open extension argument for a shared library.
def extensionArg(self, name):
|
# Check that a cursor (optionally started in a new transaction), sees the
# expected values.
def check(self, session, txn_config, expected):
if txn_config:
session.begin_transaction(txn_config)
c = session.open_cursor(self.uri, None)
actual = dict((k, v) for k, v in c if v != 0)
# Search for the expected items as well as iterating
for k, v in expected.iteritems():
self.assertEqual(c[k], v)
c.close()
if txn_config:
session.commit_transaction()
self.assertEqual(actual, expected)
# Check the state of the system with respect to the current cursor and
# different isolation levels.
def check_all(self, current, committed):
# Transactions see their own changes.
# Read-uncommitted transactions see all changes.
# Snapshot and read-committed transactions should not see changes.
self.check(self.session, None, current)
self.check(self.session2, "isolation=snapshot", committed)
self.check(self.session2, "isolation=read-committed", committed)
self.check(self.session2, "isolation=read-uncommitted", current)
# Opening a clone of the database home directory should run
# recovery and see the committed results.
self.backup(self.backup_dir)
backup_conn_params = 'log=(enabled,file_max=%s,' % self.logmax + \
'compressor=%s)' % self.compress + \
self.extensionArg(self.compress)
backup_conn = self.wiredtiger_open(self.backup_dir, backup_conn_params)
try:
self.check(backup_conn.open_session(), None, committed)
finally:
backup_conn.close()
def test_ops(self):
# print "Creating %s with config '%s'" % (self.uri, self.create_params)
self.session.create(self.uri, self.create_params)
# Set up the table with entries for 1-5.
# We then truncate starting or ending in various places.
c = self.session.open_cursor(self.uri, None)
if self.tabletype == 'fix':
value = 1
else:
# Choose large compressible values for the string cases.
value = 'abc' * 1000000
current = {1:value, 2:value, 3:value, 4:value, 5:value}
for k in current:
c[k] = value
committed = current.copy()
ops = (self.op1, )
txns = (self.txn1, )
for i, ot in enumerate(zip(ops, txns)):
self.session.begin_transaction()
ok, txn = ot
# print '%d: %s(%d)[%s]' % (i, ok[0], ok[1], txn)
op, k = ok
# print '%d: %s(%d)[%s]' % (i, ok[0], ok[1], txn)
if op == 'stop':
c.set_key(k)
self.session.truncate(None, None, c, None)
kstart = 1
kstop = k
elif op == 'start':
c.set_key(k)
self.session.truncate(None, c, None, None)
kstart = k
kstop = len(current)
elif op == 'both':
c2 = self.session.open_cursor(self.uri, None)
# For both, the key given is the start key. Add 2
# for the stop key.
kstart = k
kstop = k + 2
c.set_key(kstart)
c2.set_key(kstop)
self.session.truncate(None, c, c2, None)
c2.close()
elif op == 'all':
c2 = self.session.open_cursor(self.uri, None)
kstart = 1
kstop = len(current)
c.set_key(kstart)
c2.set_key(kstop)
self.session.truncate(None, c, c2, None)
c2.close()
while (kstart <= kstop):
del current[kstart]
kstart += 1
# print current
# Check the state after each operation.
self.check_all(current, committed)
if txn == 'commit':
committed = current.copy()
self.session.commit_transaction()
elif txn == 'rollback':
current = committed.copy()
self.session.rollback_transaction()
# Check the state after each commit/rollback.
self.check_all(current, committed)
stat_cursor = self.session.open_cursor('statistics:', None, None)
clen = stat_cursor[stat.conn.log_compress_len][2]
cmem = stat_cursor[stat.conn.log_compress_mem][2]
cwrites = stat_cursor[stat.conn.log_compress_writes][2]
cfails = stat_cursor[stat.conn.log_compress_write_fails][2]
csmall = stat_cursor[stat.conn.log_compress_small][2]
stat_cursor.close()
if self.compress == '':
self.assertEqual(clen, cmem)
self.assertEqual(cwrites, 0)
self.assertEqual(cfails, 0)
elif self.compress == 'nop':
self.assertEqual(clen, cmem)
self.assertEqual(cwrites, 0)
self.assertEqual((cfails > 0 or csmall > 0), True)
else:
self.assertEqual(clen < cmem, True)
self.assertEqual(cwrites > 0, True)
self.assertEqual((cfails > 0 or csmall > 0), True)
#
# Run printlog and make sure it exits with zero status.
#
self.runWt(['-h', self.backup_dir, 'printlog'], outfilename='printlog.out')
if __name__ == '__main__':
wttest.run()
| if name == None or name == '':
return ''
testdir = os.path.dirname(__file__)
extdir = os.path.join(run.wt_builddir, 'ext/compressors')
extfile = os.path.join(
extdir, name, '.libs', 'libwiredtiger_' + name + '.so')
if not os.path.exists(extfile):
self.skipTest('compression extension "' + extfile + '" not built')
return ',extensions=["' + extfile + '"]' |
views.py | """Node views
Copyright 2015 Archive Analytics Solutions
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import uuid
import datetime
from django.core.exceptions import PermissionDenied
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import NodeForm
from .client import NodeClient
from indigo.models import Node
from indigo.models.errors import NodeConflictError
import logging
logger = logging.getLogger("indigo")
@login_required
def home(request):
nodes = [n.to_dict() for n in Node.list()]
return render(request, 'nodes/index.html', {"nodes": nodes})
@login_required
def new(request):
form = NodeForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
try:
Node.create(name=form.cleaned_data["name"],
address=form.cleaned_data["address"])
messages.add_message(request, messages.INFO, 'New node was added')
except NodeConflictError:
messages.add_message(request, messages.ERROR, 'That name is already in use')
return HttpResponseRedirect(reverse('nodes:home'))
return render(request, 'nodes/new.html', {'form': form})
@login_required
def edit(request, id):
# TODO: Create the initial_data from the node itself, if we can
# find it.
node = Node.find_by_id(id)
initial_data = node.to_dict()
if request.method == 'POST':
form = NodeForm(request.POST)
if form.is_valid():
node.update(name=form.cleaned_data['name'], address=form.cleaned_data['address'])
messages.add_message(request, messages.INFO,
"Node information for '{}' has been changed".format(form.cleaned_data['name']))
return HttpResponseRedirect(reverse('nodes:home'))
else:
form = NodeForm(initial=initial_data)
return render(request, 'nodes/edit.html', {'form': form})
@login_required
def check(request, id):
node = Node.find_by_id(id)
client = NodeClient(node.address + ":9000")
ok, metrics = client.get_state()
if ok:
node.update(status="UP", last_update=datetime.datetime.now())
messages.add_message(request, messages.INFO, 'The node was reachable')
else:
messages.add_message(request, messages.WARNING, 'The node at {} was unreachable'.format(node.address))
node.update(status="DOWN", last_update=datetime.datetime.now())
return HttpResponseRedirect(reverse("nodes:home"))
@login_required
def metrics(request, id):
node = Node.find_by_id(id)
if not node or not request.user.administrator:
raise PermissionDenied()
client = NodeClient(node.address + ":9000")
ok, metrics = client.get_state()
if not ok:
messages.add_message(request, messages.WARNING, 'The node at {} was unreachable'.format(node.address))
return render(request, 'nodes/metrics.html', { "node": node, "metrics": metrics})
@login_required
def | (request, id):
node = Node.find_by_id(id)
return render(request, 'nodes/logs.html', { "node": node})
| logview |
test_model_images.py | import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
# script repurposed from sentdex's edits and TensorFlow's example script. Pretty messy as not all unnecessary
# parts of the original have been removed
# # Model preparation
# ## Variables
#
# Any model exported using the `export_inference_graph.py` tool can be loaded here simply by changing `PATH_TO_CKPT` to point to a new .pb file.
#
# By default we use an "SSD with Mobilenet" model here. See the [detection model zoo](https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md) for a list of other models that can be run out-of-the-box with varying speeds and accuracies.
# What model to download.
MODEL_NAME = 'trained_model' # change to whatever folder has the new graph
# MODEL_FILE = MODEL_NAME + '.tar.gz' # these lines not needed as we are using our own model
# DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'label.pbtxt') # our labels are in training/object-detection.pbkt
NUM_CLASSES = 3 # we only are using one class at the moment (mask at the time of edit)
# ## Download Model
# opener = urllib.request.URLopener() # we don't need to download model since we have our own
# opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# tar_file = tarfile.open(MODEL_FILE)
# for file in tar_file.getmembers():
# file_name = os.path.basename(file.name)
# if 'frozen_inference_graph.pb' in file_name:
# tar_file.extract(file, os.getcwd())
# ## Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
# ## Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`. Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine
|
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = 'test'
TEST_IMAGE_PATHS = [os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(0, 60)] # adjust range for # of images in folder
# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)
with detection_graph.as_default():
with tf.Session(graph=detection_graph) as sess:
i = 0
for image_path in TEST_IMAGE_PATHS:
image = Image.open(image_path)
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = load_image_into_numpy_array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
plt.figure(figsize=IMAGE_SIZE)
plt.imshow(image_np) # matplotlib is configured for command line only so we save the outputs instead
plt.savefig("outputs/detection_output{}.png".format(i)) # create an outputs folder for the images to be saved
i = i+1 # this was a quick fix for iteration, create a pull request if you'd like | # In[7]:
|
__init__.py | """Command line interface for chalice.
Contains commands for deploying chalice.
"""
import logging
import os
import platform
import sys
import tempfile
import shutil
import traceback
import functools
import json
import botocore.exceptions
import click
from typing import Dict, Any, Optional, cast # noqa
from chalice import __version__ as chalice_version
from chalice.app import Chalice # noqa
from chalice.awsclient import TypedAWSClient
from chalice.awsclient import ReadTimeout
from chalice.cli.factory import CLIFactory
from chalice.cli.factory import NoSuchFunctionError
from chalice.config import Config # noqa
from chalice.logs import display_logs, LogRetrieveOptions
from chalice.utils import create_zip_file
from chalice.deploy.validate import validate_routes, validate_python_version
from chalice.deploy.validate import ExperimentalFeatureError
from chalice.utils import getting_started_prompt, UI, serialize_to_json
from chalice.constants import CONFIG_VERSION, TEMPLATE_APP, GITIGNORE
from chalice.constants import DEFAULT_STAGE_NAME
from chalice.constants import DEFAULT_APIGATEWAY_STAGE_NAME
from chalice.local import LocalDevServer # noqa
from chalice.constants import DEFAULT_HANDLER_NAME
from chalice.invoke import UnhandledLambdaError
from chalice.deploy.swagger import TemplatedSwaggerGenerator
from chalice.deploy.planner import PlanEncoder
from chalice.deploy.appgraph import ApplicationGraphBuilder, GraphPrettyPrint
def _configure_logging(level, format_string=None):
# type: (int, Optional[str]) -> None
if format_string is None:
format_string = "%(asctime)s %(name)s [%(levelname)s] %(message)s"
logger = logging.getLogger('')
logger.setLevel(level)
handler = logging.StreamHandler()
handler.setLevel(level)
formatter = logging.Formatter(format_string)
handler.setFormatter(formatter)
logger.addHandler(handler)
def create_new_project_skeleton(project_name, profile=None):
# type: (str, Optional[str]) -> None
chalice_dir = os.path.join(project_name, '.chalice')
os.makedirs(chalice_dir)
config = os.path.join(project_name, '.chalice', 'config.json')
cfg = {
'version': CONFIG_VERSION,
'app_name': project_name,
'stages': {
DEFAULT_STAGE_NAME: {
'api_gateway_stage': DEFAULT_APIGATEWAY_STAGE_NAME,
}
}
}
if profile is not None:
cfg['profile'] = profile
with open(config, 'w') as f:
f.write(serialize_to_json(cfg))
with open(os.path.join(project_name, 'requirements.txt'), 'w'):
pass
with open(os.path.join(project_name, 'app.py'), 'w') as f:
f.write(TEMPLATE_APP % project_name)
with open(os.path.join(project_name, '.gitignore'), 'w') as f:
f.write(GITIGNORE)
def get_system_info():
# type: () -> str
python_info = "python {}.{}.{}".format(sys.version_info[0],
sys.version_info[1],
sys.version_info[2])
platform_system = platform.system().lower()
platform_release = platform.release()
platform_info = "{} {}".format(platform_system, platform_release)
return "{}, {}".format(python_info, platform_info)
@click.group()
@click.version_option(version=chalice_version,
message='%(prog)s %(version)s, {}'
.format(get_system_info()))
@click.option('--project-dir',
help='The project directory path (absolute or relative).'
'Defaults to CWD')
@click.option('--debug/--no-debug',
default=False,
help='Print debug logs to stderr.')
@click.pass_context
def cli(ctx, project_dir, debug=False):
# type: (click.Context, str, bool) -> None
if project_dir is None:
project_dir = os.getcwd()
elif not os.path.isabs(project_dir):
project_dir = os.path.abspath(project_dir)
if debug is True:
_configure_logging(logging.DEBUG)
_configure_cli_env_vars()
ctx.obj['project_dir'] = project_dir
ctx.obj['debug'] = debug
ctx.obj['factory'] = CLIFactory(project_dir, debug, environ=os.environ)
os.chdir(project_dir)
def _configure_cli_env_vars():
# type: () -> None
# This will set chalice specific env vars so users can detect if
# we're running a Chalice CLI command. This is useful if you want
# conditional behavior only when we're actually running in Lambda
# in your app.py file.
os.environ['AWS_CHALICE_CLI_MODE'] = 'true'
@cli.command()
@click.option('--host', default='127.0.0.1')
@click.option('--port', default=8000, type=click.INT)
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help='Name of the Chalice stage for the local server to use.')
@click.option('--autoreload/--no-autoreload',
default=True,
help='Automatically restart server when code changes.')
@click.pass_context
def local(ctx, host='127.0.0.1', port=8000, stage=DEFAULT_STAGE_NAME,
autoreload=True):
# type: (click.Context, str, int, str, bool) -> None
factory = ctx.obj['factory'] # type: CLIFactory
from chalice.cli import reloader
# We don't create the server here because that will bind the
# socket and we only want to do this in the worker process.
server_factory = functools.partial(
create_local_server, factory, host, port, stage)
# When running `chalice local`, a stdout logger is configured
# so you'll see the same stdout logging as you would when
# running in lambda. This is configuring the root logger.
# The app-specific logger (app.log) will still continue
# to work.
logging.basicConfig(
stream=sys.stdout, level=logging.INFO, format='%(message)s')
if autoreload:
project_dir = factory.create_config_obj(
chalice_stage_name=stage).project_dir
rc = reloader.run_with_reloader(
server_factory, os.environ, project_dir)
# Click doesn't sys.exit() with the RC this function. The
# recommended way to do this is to use sys.exit() directly,
# see: https://github.com/pallets/click/issues/747
sys.exit(rc)
run_local_server(factory, host, port, stage)
def create_local_server(factory, host, port, stage):
# type: (CLIFactory, str, int, str) -> LocalDevServer
config = factory.create_config_obj(
chalice_stage_name=stage
)
app_obj = config.chalice_app
# Check that `chalice deploy` would let us deploy these routes, otherwise
# there is no point in testing locally.
routes = config.chalice_app.routes
validate_routes(routes)
server = factory.create_local_server(app_obj, config, host, port)
return server
def run_local_server(factory, host, port, stage):
# type: (CLIFactory, str, int, str) -> None
server = create_local_server(factory, host, port, stage)
server.serve_forever()
@cli.command()
@click.option('--autogen-policy/--no-autogen-policy',
default=None,
help='Automatically generate IAM policy for app code.')
@click.option('--profile', help='Override profile at deploy time.')
@click.option('--api-gateway-stage',
help='Name of the API gateway stage to deploy to.')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help=('Name of the Chalice stage to deploy to. '
'Specifying a new chalice stage will create '
'an entirely new set of AWS resources.'))
@click.option('--connection-timeout',
type=int,
help=('Overrides the default botocore connection '
'timeout.'))
@click.pass_context
def deploy(ctx, autogen_policy, profile, api_gateway_stage, stage,
connection_timeout):
# type: (click.Context, Optional[bool], str, str, str, int) -> None
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(
chalice_stage_name=stage, autogen_policy=autogen_policy,
api_gateway_stage=api_gateway_stage,
)
session = factory.create_botocore_session(
connection_timeout=connection_timeout)
ui = UI()
d = factory.create_default_deployer(session=session,
config=config,
ui=ui)
deployed_values = d.deploy(config, chalice_stage_name=stage)
reporter = factory.create_deployment_reporter(ui=ui)
reporter.display_report(deployed_values)
@cli.group()
def dev():
# type: () -> None
"""Development and debugging commands for chalice.
All the commands under the "chalice dev" namespace are provided
to help chalice developers introspect the internals of chalice.
They are also useful for users to better understand the chalice
deployment process.
These commands are provided for informational purposes only.
There is NO guarantee of backwards compatibility for any
"chalice dev" commands. Do not rely on the output of these commands.
These commands allow introspection of chalice internals, and the
internals of chalice are subject to change as needed.
"""
@dev.command()
@click.option('--autogen-policy/--no-autogen-policy',
default=None,
help='Automatically generate IAM policy for app code.')
@click.option('--profile', help='Override profile at deploy time.')
@click.option('--api-gateway-stage',
help='Name of the API gateway stage to deploy to.')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help=('Name of the Chalice stage to deploy to. '
'Specifying a new chalice stage will create '
'an entirely new set of AWS resources.'))
@click.pass_context
def plan(ctx, autogen_policy, profile, api_gateway_stage, stage):
# type: (click.Context, Optional[bool], str, str, str) -> None
|
@dev.command()
@click.option('--autogen-policy/--no-autogen-policy',
default=None,
help='Automatically generate IAM policy for app code.')
@click.option('--profile', help='Override profile at deploy time.')
@click.option('--api-gateway-stage',
help='Name of the API gateway stage to deploy to.')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help=('Name of the Chalice stage to deploy to. '
'Specifying a new chalice stage will create '
'an entirely new set of AWS resources.'))
@click.pass_context
def appgraph(ctx, autogen_policy, profile, api_gateway_stage, stage):
# type: (click.Context, Optional[bool], str, str, str) -> None
"""Generate and display the application graph."""
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(
chalice_stage_name=stage, autogen_policy=autogen_policy,
api_gateway_stage=api_gateway_stage,
)
graph_build = ApplicationGraphBuilder()
graph = graph_build.build(config, stage)
ui = UI()
GraphPrettyPrint(ui).display_graph(graph)
@cli.command('invoke')
@click.option('-n', '--name', metavar='NAME', required=True,
help=('The name of the function to invoke. '
'This is the logical name of the function. If the '
'function is decorated by app.route use the name '
'api_handler instead.'))
@click.option('--profile', metavar='PROFILE',
help='Override profile at deploy time.')
@click.option('--stage', metavar='STAGE', default=DEFAULT_STAGE_NAME,
help=('Name of the Chalice stage to deploy to. '
'Specifying a new chalice stage will create '
'an entirely new set of AWS resources.'))
@click.pass_context
def invoke(ctx, name, profile, stage):
# type: (click.Context, str, str, str) -> None
"""Invoke the deployed lambda function NAME.
Reads payload from STDIN.
"""
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
try:
invoke_handler = factory.create_lambda_invoke_handler(name, stage)
payload = factory.create_stdin_reader().read()
invoke_handler.invoke(payload)
except NoSuchFunctionError as e:
err = click.ClickException(
"could not find a lambda function named %s." % e.name)
err.exit_code = 2
raise err
except botocore.exceptions.ClientError as e:
error = e.response['Error']
err = click.ClickException(
"got '%s' exception back from Lambda\n%s"
% (error['Code'], error['Message']))
err.exit_code = 1
raise err
except UnhandledLambdaError:
err = click.ClickException(
"Unhandled exception in Lambda function, details above.")
err.exit_code = 1
raise err
except ReadTimeout as e:
err = click.ClickException(e.message)
err.exit_code = 1
raise err
@cli.command('delete')
@click.option('--profile', help='Override profile at deploy time.')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help='Name of the Chalice stage to delete.')
@click.pass_context
def delete(ctx, profile, stage):
# type: (click.Context, str, str) -> None
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(chalice_stage_name=stage)
session = factory.create_botocore_session()
d = factory.create_deletion_deployer(session=session, ui=UI())
d.deploy(config, chalice_stage_name=stage)
@cli.command()
@click.option('--num-entries', default=None, type=int,
help='Max number of log entries to show.')
@click.option('--include-lambda-messages/--no-include-lambda-messages',
default=False,
help='Controls whether or not lambda log messages are included.')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help='Name of the Chalice stage to get logs for.')
@click.option('-n', '--name',
help='The name of the lambda function to retrieve logs from.',
default=DEFAULT_HANDLER_NAME)
@click.option('-s', '--since',
help=('Only display logs since the provided time. If the '
'-f/--follow option is specified, then this value will '
'default to 10 minutes from the current time. Otherwise '
'by default all log messages are displayed. This value '
'can either be an ISO8601 formatted timestamp or a '
'relative time. For relative times provide a number '
'and a single unit. Units can be "s" for seconds, '
'"m" for minutes, "h" for hours, "d" for days, and "w" '
'for weeks. For example "5m" would indicate to display '
'logs starting five minutes in the past.'),
default=None)
@click.option('-f', '--follow/--no-follow',
default=False,
help=('Continuously poll for new log messages. Note that this '
'is a best effort attempt, and in certain cases can '
'miss log messages. This option is intended for '
'interactive usage only.'))
@click.option('--profile', help='The profile to use for fetching logs.')
@click.pass_context
def logs(ctx, num_entries, include_lambda_messages, stage,
name, since, follow, profile):
# type: (click.Context, int, bool, str, str, str, bool, str) -> None
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(stage, False)
deployed = config.deployed_resources(stage)
if name in deployed.resource_names():
lambda_arn = deployed.resource_values(name)['lambda_arn']
session = factory.create_botocore_session()
retriever = factory.create_log_retriever(
session, lambda_arn, follow)
options = LogRetrieveOptions.create(
max_entries=num_entries,
since=since,
include_lambda_messages=include_lambda_messages,
)
display_logs(retriever, sys.stdout, options)
@cli.command('gen-policy')
@click.option('--filename',
help='The filename to analyze. Otherwise app.py is assumed.')
@click.pass_context
def gen_policy(ctx, filename):
# type: (click.Context, str) -> None
from chalice import policy
if filename is None:
filename = os.path.join(ctx.obj['project_dir'], 'app.py')
if not os.path.isfile(filename):
click.echo("App file does not exist: %s" % filename, err=True)
raise click.Abort()
with open(filename) as f:
contents = f.read()
generated = policy.policy_from_source_code(contents)
click.echo(serialize_to_json(generated))
@cli.command('new-project')
@click.argument('project_name', required=False)
@click.option('--profile', required=False)
def new_project(project_name, profile):
# type: (str, str) -> None
if project_name is None:
project_name = getting_started_prompt(click)
if os.path.isdir(project_name):
click.echo("Directory already exists: %s" % project_name, err=True)
raise click.Abort()
create_new_project_skeleton(project_name, profile)
validate_python_version(Config.create())
@cli.command('url')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help='Name of the Chalice stage to get the deployed URL for.')
@click.pass_context
def url(ctx, stage):
# type: (click.Context, str) -> None
factory = ctx.obj['factory'] # type: CLIFactory
config = factory.create_config_obj(stage)
deployed = config.deployed_resources(stage)
if deployed is not None and 'rest_api' in deployed.resource_names():
click.echo(deployed.resource_values('rest_api')['rest_api_url'])
else:
e = click.ClickException(
"Could not find a record of a Rest API in chalice stage: '%s'"
% stage)
e.exit_code = 2
raise e
@cli.command('generate-sdk')
@click.option('--sdk-type', default='javascript',
type=click.Choice(['javascript']))
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help='Name of the Chalice stage to generate an SDK for.')
@click.argument('outdir')
@click.pass_context
def generate_sdk(ctx, sdk_type, stage, outdir):
# type: (click.Context, str, str, str) -> None
factory = ctx.obj['factory'] # type: CLIFactory
config = factory.create_config_obj(stage)
session = factory.create_botocore_session()
client = TypedAWSClient(session)
deployed = config.deployed_resources(stage)
if deployed is not None and 'rest_api' in deployed.resource_names():
rest_api_id = deployed.resource_values('rest_api')['rest_api_id']
api_gateway_stage = config.api_gateway_stage
client.download_sdk(rest_api_id, outdir,
api_gateway_stage=api_gateway_stage,
sdk_type=sdk_type)
else:
click.echo("Could not find API ID, has this application "
"been deployed?", err=True)
raise click.Abort()
@cli.command('generate-models')
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help="Chalice Stage for which to generate models.")
@click.pass_context
def generate_models(ctx, stage):
# type: (click.Context, str) -> None
"""Generate a model from Chalice routes.
Currently only supports generating Swagger 2.0 models.
"""
factory = ctx.obj['factory'] # type: CLIFactory
config = factory.create_config_obj(stage)
if not config.chalice_app.routes:
click.echo('No REST API found to generate model from.')
raise click.Abort()
swagger_generator = TemplatedSwaggerGenerator()
model = swagger_generator.generate_swagger(
config.chalice_app,
)
ui = UI()
ui.write(json.dumps(model, indent=4, cls=PlanEncoder))
ui.write('\n')
@cli.command('package')
@click.option('--pkg-format', default='cloudformation',
help=('Specify the provisioning engine to use for '
'template output. Chalice supports both '
'CloudFormation and Terraform. Default '
'is CloudFormation.'),
type=click.Choice(['cloudformation', 'terraform']))
@click.option('--stage', default=DEFAULT_STAGE_NAME,
help="Chalice Stage to package.")
@click.option('--single-file', is_flag=True,
default=False,
help=("Create a single packaged file. "
"By default, the 'out' argument "
"specifies a directory in which the "
"package assets will be placed. If "
"this argument is specified, a single "
"zip file will be created instead. CloudFormation Only."))
@click.option('--merge-template',
help=('Specify a JSON or YAML template to be merged '
'into the generated template. This is useful '
'for adding resources to a Chalice template or '
'modify values in the template. CloudFormation Only.'))
@click.option('--template-format', default='json',
type=click.Choice(['json', 'yaml'], case_sensitive=False),
help=('Specify if the generated template should be serialized '
'as either JSON or YAML. CloudFormation only.'))
@click.option('--profile', help='Override profile at packaging time.')
@click.argument('out')
@click.pass_context
def package(ctx, single_file, stage, merge_template,
out, pkg_format, template_format, profile):
# type: (click.Context, bool, str, str, str, str, str, str) -> None
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(stage)
options = factory.create_package_options()
packager = factory.create_app_packager(config, options,
pkg_format,
template_format,
merge_template)
if pkg_format == 'terraform' and (merge_template or
single_file or
template_format != 'json'):
# I don't see any reason we couldn't support --single-file for
# terraform if we wanted to.
click.echo((
"Terraform format does not support "
"--merge-template, --single-file, or --template-format"))
raise click.Abort()
if single_file:
dirname = tempfile.mkdtemp()
try:
packager.package_app(config, dirname, stage)
create_zip_file(source_dir=dirname, outfile=out)
finally:
shutil.rmtree(dirname)
else:
packager.package_app(config, out, stage)
@cli.command('generate-pipeline')
@click.option('--pipeline-version',
default='v1',
type=click.Choice(['v1', 'v2']),
help='Which version of the pipeline template to generate.')
@click.option('-i', '--codebuild-image',
help=("Specify default codebuild image to use. "
"This option must be provided when using a python "
"version besides 2.7."))
@click.option('-s', '--source', default='codecommit',
type=click.Choice(['codecommit', 'github']),
help=("Specify the input source. The default value of "
"'codecommit' will create a CodeCommit repository "
"for you. The 'github' value allows you to "
"reference an existing GitHub repository."))
@click.option('-b', '--buildspec-file',
help=("Specify path for buildspec.yml file. "
"By default, the build steps are included in the "
"generated cloudformation template. If this option "
"is provided, a buildspec.yml will be generated "
"as a separate file and not included in the cfn "
"template. This allows you to make changes to how "
"the project is built without having to redeploy "
"a CloudFormation template. This file should be "
"named 'buildspec.yml' and placed in the root "
"directory of your app."))
@click.argument('filename')
@click.pass_context
def generate_pipeline(ctx, pipeline_version, codebuild_image, source,
buildspec_file, filename):
# type: (click.Context, str, str, str, str, str) -> None
"""Generate a cloudformation template for a starter CD pipeline.
This command will write a starter cloudformation template to
the filename you provide. It contains a CodeCommit repo,
a CodeBuild stage for packaging your chalice app, and a
CodePipeline stage to deploy your application using cloudformation.
You can use any AWS SDK or the AWS CLI to deploy this stack.
Here's an example using the AWS CLI:
\b
$ chalice generate-pipeline pipeline.json
$ aws cloudformation deploy --stack-name mystack \b
--template-file pipeline.json --capabilities CAPABILITY_IAM
"""
from chalice import pipeline
factory = ctx.obj['factory'] # type: CLIFactory
config = factory.create_config_obj()
p = cast(pipeline.BasePipelineTemplate, None)
if pipeline_version == 'v1':
p = pipeline.CreatePipelineTemplateLegacy()
else:
p = pipeline.CreatePipelineTemplateV2()
params = pipeline.PipelineParameters(
app_name=config.app_name,
lambda_python_version=config.lambda_python_version,
codebuild_image=codebuild_image,
code_source=source,
pipeline_version=pipeline_version,
)
output = p.create_template(params)
if buildspec_file:
extractor = pipeline.BuildSpecExtractor()
buildspec_contents = extractor.extract_buildspec(output)
with open(buildspec_file, 'w') as f:
f.write(buildspec_contents)
with open(filename, 'w') as f:
f.write(serialize_to_json(output))
def main():
# type: () -> int
# click's dynamic attrs will allow us to pass through
# 'obj' via the context object, so we're ignoring
# these error messages from pylint because we know it's ok.
# pylint: disable=unexpected-keyword-arg,no-value-for-parameter
try:
return cli(obj={})
except botocore.exceptions.NoRegionError:
click.echo("No region configured. "
"Either export the AWS_DEFAULT_REGION "
"environment variable or set the "
"region value in our ~/.aws/config file.", err=True)
return 2
except ExperimentalFeatureError as e:
click.echo(str(e))
return 2
except Exception:
click.echo(traceback.format_exc(), err=True)
return 2
| """Generate and display deployment plan.
This command will calculate and pretty print the deployment plan
without actually executing the plan. It's primarily used to better
understand the chalice deployment process.
"""
factory = ctx.obj['factory'] # type: CLIFactory
factory.profile = profile
config = factory.create_config_obj(
chalice_stage_name=stage, autogen_policy=autogen_policy,
api_gateway_stage=api_gateway_stage,
)
session = factory.create_botocore_session()
ui = UI()
d = factory.create_plan_only_deployer(
session=session, config=config, ui=ui)
d.deploy(config, chalice_stage_name=stage) |
dounots.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DounotsComponent } from './dounots.component';
describe('DounotsComponent', () => {
let component: DounotsComponent;
let fixture: ComponentFixture<DounotsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DounotsComponent ] |
beforeEach(() => {
fixture = TestBed.createComponent(DounotsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); | })
.compileComponents();
})); |
multiprocess_simply.py | """
simply hired using multi process design
scrape through 11 pages of simply using a multi processing for each I/O (4x faster)
"""
from requests import get
from bs4 import BeautifulSoup
from threading import Thread
import multiprocessing
from os import getpid
import psutil
def get_simply(url, role ):
|
def getrole_simply(role, location):
test_data ={}
if "," in location:
location=location.split(',')
location= location[0].strip()+ "," + location[1].strip()
url_first= 'https://www.simplyhired.com/search?q='+role+'&l='+location
url= 'https://www.simplyhired.com/search?q='+role+'&l='+location + '&pn='
processor_count= multiprocessing.cpu_count() #get cpu count
pool=multiprocessing.Pool(11)
iterable = zip( [ url +str(i) if i != 0 else url_first for i in range(1,30) ], [role for i in range(1,30) ] )
result_pool=pool.starmap( get_simply, iterable)
pool.close()
pool.join()
for i, p in enumerate(result_pool):
for key, value in p.items():
if value not in test_data.values():
test_data[key]= value
return test_data
'''
process = psutil.Process(getpid())
print('total memory usage: ' , process.memory_info().rss , psutil.cpu_percent()) # in bytes
'''
if __name__ == "__main__":
getrole_simply('python', 'new jersey') | alldata={}
response = get(url, headers={'User-Agent': 'Mozilla/5.0'})
try:
soup = BeautifulSoup(response.text, 'html.parser')
content_container= soup.find_all('div', {'class': ['SerpJob-jobCard']})
link= 'https://www.simplyhired.com'
except AttributeError:
pass
for content in content_container:
title, href=None , None
try:
title=content.a.text
href=content.a['href']
company=content.span.text
summary=content.p.text
except TypeError:
pass
except AttributeError:
pass
if title is not None and role.upper() in title.upper():
if href is not None:
href=link+href
alldata[href]=[title, company, summary, href]
return alldata |
main.rs | extern crate clap;
extern crate dokan;
extern crate widestring;
extern crate winapi;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::os::windows::io::AsRawHandle;
use std::sync::{Arc, Mutex, RwLock, Weak};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::SystemTime;
use clap::{App, Arg};
use dokan::*;
use widestring::{U16CStr, U16Str, U16CString, U16String};
use winapi::shared::{ntdef, ntstatus::*};
use winapi::um::winnt;
mod security;
mod err_utils;
mod path;
use security::SecurityDescriptor;
use err_utils::*;
use path::FullName;
#[derive(Debug)]
struct AltStream {
handle_count: u32,
delete_pending: bool,
data: Vec<u8>,
}
impl AltStream {
fn new() -> Self {
Self {
handle_count: 0,
delete_pending: false,
data: Vec::new(),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct Attributes {
value: u32,
}
impl Attributes {
fn new(attrs: u32) -> Self {
const SUPPORTED_ATTRS: u32 = winnt::FILE_ATTRIBUTE_ARCHIVE | winnt::FILE_ATTRIBUTE_HIDDEN
| winnt::FILE_ATTRIBUTE_NOT_CONTENT_INDEXED | winnt::FILE_ATTRIBUTE_OFFLINE | winnt::FILE_ATTRIBUTE_READONLY
| winnt::FILE_ATTRIBUTE_SYSTEM | winnt::FILE_ATTRIBUTE_TEMPORARY;
Self { value: attrs & SUPPORTED_ATTRS }
}
fn get_output_attrs(&self, is_dir: bool) -> u32 {
let mut attrs = self.value;
if is_dir {
attrs |= winnt::FILE_ATTRIBUTE_DIRECTORY;
}
if attrs == 0 {
attrs = winnt::FILE_ATTRIBUTE_NORMAL
}
attrs
}
}
#[derive(Debug)]
struct Stat {
id: u64,
attrs: Attributes,
ctime: SystemTime,
mtime: SystemTime,
atime: SystemTime,
sec_desc: SecurityDescriptor,
handle_count: u32,
delete_pending: bool,
parent: Weak<DirEntry>,
alt_streams: HashMap<EntryName, Arc<RwLock<AltStream>>>,
}
impl Stat {
fn new(id: u64, attrs: u32, sec_desc: SecurityDescriptor, parent: Weak<DirEntry>) -> Self {
let now = SystemTime::now();
Self {
id,
attrs: Attributes::new(attrs),
ctime: now,
mtime: now,
atime: now,
sec_desc,
handle_count: 0,
delete_pending: false,
parent,
alt_streams: HashMap::new(),
}
}
fn update_atime(&mut self, atime: SystemTime) {
self.atime = atime;
}
fn update_mtime(&mut self, mtime: SystemTime) {
self.update_atime(mtime);
self.mtime = mtime;
}
}
#[derive(Debug, Eq)]
struct EntryNameRef(U16Str);
fn u16_tolower(c: u16) -> u16 {
if c >= 'A' as u16 && c <= 'Z' as u16 {
c + 'a' as u16 - 'A' as u16
} else { c }
}
impl Hash for EntryNameRef {
fn hash<H: Hasher>(&self, state: &mut H) {
for c in self.0.as_slice() {
state.write_u16(u16_tolower(*c));
}
}
}
impl PartialEq for EntryNameRef {
fn eq(&self, other: &Self) -> bool {
if self.0.len() != other.0.len() { false } else {
self.0.as_slice().iter().zip(other.0.as_slice())
.all(|(c1, c2)| u16_tolower(*c1) == u16_tolower(*c2))
}
}
}
impl EntryNameRef {
fn new(s: &U16Str) -> &Self {
unsafe { &*(s as *const _ as *const Self) }
}
}
#[derive(Debug, Clone)]
struct EntryName(U16String);
impl Borrow<EntryNameRef> for EntryName {
fn borrow(&self) -> &EntryNameRef {
EntryNameRef::new(&self.0)
}
}
impl Hash for EntryName {
fn hash<H: Hasher>(&self, state: &mut H) {
Borrow::<EntryNameRef>::borrow(self).hash(state)
}
}
impl PartialEq for EntryName {
fn eq(&self, other: &Self) -> bool {
Borrow::<EntryNameRef>::borrow(self).eq(other.borrow())
}
}
impl Eq for EntryName {}
#[derive(Debug)]
struct FileEntry {
stat: RwLock<Stat>,
data: RwLock<Vec<u8>>,
}
impl FileEntry {
fn new(stat: Stat) -> Self {
Self {
stat: RwLock::new(stat),
data: RwLock::new(Vec::new()),
}
}
}
// The compiler incorrectly believes that its usage in a public function of the private path module is public.
#[derive(Debug)]
pub struct DirEntry {
stat: RwLock<Stat>,
children: RwLock<HashMap<EntryName, Entry>>,
}
impl DirEntry {
fn new(stat: Stat) -> Self {
Self {
stat: RwLock::new(stat),
children: RwLock::new(HashMap::new()),
}
}
}
#[derive(Debug)]
enum Entry {
File(Arc<FileEntry>),
Directory(Arc<DirEntry>),
}
impl Entry {
fn stat(&self) -> &RwLock<Stat> {
match self {
Entry::File(file) => &file.stat,
Entry::Directory(dir) => &dir.stat,
}
}
fn is_dir(&self) -> bool {
match self {
Entry::File(_) => false,
Entry::Directory(_) => true,
}
}
}
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
match self {
Entry::File(file) => {
if let Entry::File(other_file) = other {
Arc::ptr_eq(file, other_file)
} else {
false
}
}
Entry::Directory(dir) => {
if let Entry::Directory(other_dir) = other {
Arc::ptr_eq(dir, other_dir)
} else {
false
}
}
}
}
}
impl Eq for Entry {}
impl Clone for Entry {
fn clone(&self) -> Self {
match self {
Entry::File(file) => Entry::File(Arc::clone(file)),
Entry::Directory(dir) => Entry::Directory(Arc::clone(dir)),
}
}
}
#[derive(Debug)]
struct EntryHandle {
entry: Entry,
alt_stream: RwLock<Option<Arc<RwLock<AltStream>>>>,
delete_on_close: bool,
mtime_delayed: Mutex<Option<SystemTime>>,
atime_delayed: Mutex<Option<SystemTime>>,
ctime_enabled: AtomicBool,
mtime_enabled: AtomicBool,
atime_enabled: AtomicBool,
}
impl EntryHandle {
fn new(entry: Entry, alt_stream: Option<Arc<RwLock<AltStream>>>, delete_on_close: bool) -> Self {
entry.stat().write().unwrap().handle_count += 1;
if let Some(s) = &alt_stream {
s.write().unwrap().handle_count += 1;
}
Self {
entry,
alt_stream: RwLock::new(alt_stream),
delete_on_close,
mtime_delayed: Mutex::new(None),
atime_delayed: Mutex::new(None),
ctime_enabled: AtomicBool::new(true),
mtime_enabled: AtomicBool::new(true),
atime_enabled: AtomicBool::new(true),
}
}
fn is_dir(&self) -> bool {
if self.alt_stream.read().unwrap().is_some() { false } else { self.entry.is_dir() }
}
fn update_atime(&self, stat: &mut Stat, atime: SystemTime) {
if self.atime_enabled.load(Ordering::Relaxed) {
stat.atime = atime;
}
}
fn update_mtime(&self, stat: &mut Stat, mtime: SystemTime) {
self.update_atime(stat, mtime);
if self.mtime_enabled.load(Ordering::Relaxed) {
stat.mtime = mtime;
}
}
}
impl Drop for EntryHandle {
fn drop(&mut self) {
// The read lock on stat will be released before locking parent. This avoids possible deadlocks with
// create_file.
let parent = self.entry.stat().read().unwrap().parent.upgrade();
// Lock parent before checking. This avoids racing with create_file.
let parent_children = parent.as_ref()
.map(|p| p.children.write().unwrap());
let mut stat = self.entry.stat().write().unwrap();
if self.delete_on_close && self.alt_stream.read().unwrap().is_none() {
stat.delete_pending = true;
}
stat.handle_count -= 1;
if stat.delete_pending && stat.handle_count == 0 {
// The result of upgrade() can be safely unwrapped here because the root directory is the only case when the
// reference can be null, which has been handled in delete_directory.
parent.as_ref().unwrap().stat.write().unwrap().update_mtime(SystemTime::now());
let mut parent_children = parent_children.unwrap();
let key = parent_children.iter().find_map(|(k, v)| {
if &self.entry == v { Some(k) } else { None }
}).unwrap().clone();
parent_children.remove(Borrow::<EntryNameRef>::borrow(&key)).unwrap();
} else {
// Ignore root directory.
stat.delete_pending = false
}
let alt_stream = self.alt_stream.read().unwrap();
if let Some(stream) = alt_stream.as_ref() {
stat.mtime = SystemTime::now();
let mut stream_locked = stream.write().unwrap();
if self.delete_on_close {
stream_locked.delete_pending = true;
}
stream_locked.handle_count -= 1;
if stream_locked.delete_pending && stream_locked.handle_count == 0 {
let key = stat.alt_streams.iter().find_map(|(k, v)| {
if Arc::ptr_eq(stream, v) { Some(k) } else { None }
}).unwrap().clone();
stat.alt_streams.remove(Borrow::<EntryNameRef>::borrow(&key)).unwrap();
self.update_atime(&mut stat, SystemTime::now());
}
}
}
}
#[derive(Debug)]
struct MemFsHandler {
id_counter: AtomicU64,
root: Arc<DirEntry>,
}
impl MemFsHandler {
fn new() -> Self {
Self {
id_counter: AtomicU64::new(1),
root: Arc::new(DirEntry::new(Stat::new(
0, 0,
SecurityDescriptor::new_default().unwrap(),
Weak::new(),
))),
}
}
fn next_id(&self) -> u64 {
self.id_counter.fetch_add(1, Ordering::Relaxed)
}
fn create_new(
&self,
name: &FullName,
attrs: u32,
delete_on_close: bool,
creator_desc: winnt::PSECURITY_DESCRIPTOR,
token: ntdef::HANDLE,
parent: &Arc<DirEntry>,
children: &mut HashMap<EntryName, Entry>,
is_dir: bool,
) -> Result<CreateFileInfo<EntryHandle>, OperationError> {
if attrs & winnt::FILE_ATTRIBUTE_READONLY > 0 && delete_on_close {
return nt_res(STATUS_CANNOT_DELETE);
}
let mut stat = Stat::new(
self.next_id(),
attrs,
SecurityDescriptor::new_inherited(
&parent.stat.read().unwrap().sec_desc,
creator_desc, token, is_dir,
)?,
Arc::downgrade(&parent),
);
let stream = if let Some(stream_info) = &name.stream_info {
if stream_info.check_default(is_dir)? { None } else {
let stream = Arc::new(RwLock::new(AltStream::new()));
assert!(stat.alt_streams
.insert(EntryName(stream_info.name.to_owned()), Arc::clone(&stream))
.is_none());
Some(stream)
}
} else { None };
let entry = if is_dir {
Entry::Directory(Arc::new(DirEntry::new(stat)))
} else {
Entry::File(Arc::new(FileEntry::new(stat)))
};
assert!(children
.insert(EntryName(name.file_name.to_owned()), entry.clone())
.is_none());
parent.stat.write().unwrap().update_mtime(SystemTime::now());
let is_dir = is_dir && stream.is_some();
Ok(CreateFileInfo {
context: EntryHandle::new(entry, stream, delete_on_close),
is_dir,
new_file_created: true,
})
}
}
fn check_fill_data_error(res: Result<(), FillDataError>) -> Result<(), OperationError> {
match res {
Ok(()) => Ok(()),
Err(FillDataError::BufferFull) => nt_res(STATUS_INTERNAL_ERROR),
// Silently ignore this error because 1) file names passed to create_file should have been checked
// by Windows. 2) We don't want an error on a single file to make the whole directory unreadable.
Err(FillDataError::NameTooLong) => Ok(()),
}
}
const FILE_SUPERSEDE: u32 = 0;
const FILE_OPEN: u32 = 1;
const FILE_CREATE: u32 = 2;
const FILE_OPEN_IF: u32 = 3;
const FILE_OVERWRITE: u32 = 4;
const FILE_OVERWRITE_IF: u32 = 5;
const FILE_MAXIMUM_DISPOSITION: u32 = 5;
const FILE_DIRECTORY_FILE: u32 = 0x00000001;
const FILE_NON_DIRECTORY_FILE: u32 = 0x00000040;
const FILE_DELETE_ON_CLOSE: u32 = 0x00001000;
impl<'a, 'b: 'a> FileSystemHandler<'a, 'b> for MemFsHandler {
type Context = EntryHandle;
fn create_file(
&'b self,
file_name: &U16CStr,
security_context: &DOKAN_IO_SECURITY_CONTEXT,
desired_access: winnt::ACCESS_MASK,
file_attributes: u32,
_share_access: u32,
create_disposition: u32,
create_options: u32,
info: &mut OperationInfo<'a, 'b, Self>,
) -> Result<CreateFileInfo<Self::Context>, OperationError> {
if create_disposition > FILE_MAXIMUM_DISPOSITION {
return nt_res(STATUS_INVALID_PARAMETER);
}
let delete_on_close = create_options & FILE_DELETE_ON_CLOSE > 0;
let path_info = path::split_path(&self.root, file_name)?;
if let Some((name, parent)) = path_info {
let mut children = parent.children.write().unwrap();
if let Some(entry) = children.get(EntryNameRef::new(name.file_name)) {
let stat = entry.stat().read().unwrap();
let is_readonly = stat.attrs.value & winnt::FILE_ATTRIBUTE_READONLY > 0;
let is_hidden_system = stat.attrs.value & winnt::FILE_ATTRIBUTE_HIDDEN > 0 &&
stat.attrs.value & winnt::FILE_ATTRIBUTE_SYSTEM > 0 &&
!(file_attributes & winnt::FILE_ATTRIBUTE_HIDDEN > 0 &&
file_attributes & winnt::FILE_ATTRIBUTE_SYSTEM > 0);
if is_readonly &&
(desired_access & winnt::FILE_WRITE_DATA > 0 ||
desired_access & winnt::FILE_APPEND_DATA > 0) {
return nt_res(STATUS_ACCESS_DENIED);
}
if stat.delete_pending {
return nt_res(STATUS_DELETE_PENDING);
}
if is_readonly && delete_on_close {
return nt_res(STATUS_CANNOT_DELETE);
}
std::mem::drop(stat);
let ret = if let Some(stream_info) = &name.stream_info {
if stream_info.check_default(entry.is_dir())? { None } else {
let mut stat = entry.stat().write().unwrap();
let stream_name = EntryNameRef::new(stream_info.name);
if let Some(stream) = stat.alt_streams
.get(stream_name)
.map(|s| Arc::clone(s))
{
if stream.read().unwrap().delete_pending {
return nt_res(STATUS_DELETE_PENDING);
}
match create_disposition {
FILE_SUPERSEDE | FILE_OVERWRITE | FILE_OVERWRITE_IF => {
if create_disposition != FILE_SUPERSEDE && is_readonly {
return nt_res(STATUS_ACCESS_DENIED);
}
stat.attrs.value |= winnt::FILE_ATTRIBUTE_ARCHIVE;
stat.update_mtime(SystemTime::now());
stream.write().unwrap().data.clear();
}
FILE_CREATE => return nt_res(STATUS_OBJECT_NAME_COLLISION),
_ => (),
}
Some((stream, false))
} else {
if create_disposition == FILE_OPEN || create_disposition == FILE_OVERWRITE {
return nt_res(STATUS_OBJECT_NAME_NOT_FOUND);
}
if is_readonly {
return nt_res(STATUS_ACCESS_DENIED);
}
let stream = Arc::new(RwLock::new(AltStream::new()));
stat.update_atime(SystemTime::now());
assert!(stat.alt_streams
.insert(EntryName(stream_info.name.to_owned()), Arc::clone(&stream))
.is_none());
Some((stream, true))
}
}
} else { None };
if let Some((stream, new_file_created)) = ret {
return Ok(CreateFileInfo {
context: EntryHandle::new(entry.clone(), Some(stream), delete_on_close),
is_dir: false,
new_file_created,
});
}
match entry {
Entry::File(file) => {
if create_options & FILE_DIRECTORY_FILE > 0 {
return nt_res(STATUS_NOT_A_DIRECTORY);
}
match create_disposition {
FILE_SUPERSEDE | FILE_OVERWRITE | FILE_OVERWRITE_IF => {
if create_disposition != FILE_SUPERSEDE && is_readonly || is_hidden_system {
return nt_res(STATUS_ACCESS_DENIED);
}
file.data.write().unwrap().clear();
let mut stat = file.stat.write().unwrap();
stat.attrs = Attributes::new(file_attributes | winnt::FILE_ATTRIBUTE_ARCHIVE);
stat.update_mtime(SystemTime::now());
}
FILE_CREATE => return nt_res(STATUS_OBJECT_NAME_COLLISION),
_ => (),
}
Ok(CreateFileInfo {
context: EntryHandle::new(Entry::File(Arc::clone(file)), None, delete_on_close),
is_dir: false,
new_file_created: false,
})
}
Entry::Directory(dir) => {
if create_options & FILE_NON_DIRECTORY_FILE > 0 {
return nt_res(STATUS_FILE_IS_A_DIRECTORY);
}
match create_disposition {
FILE_OPEN | FILE_OPEN_IF => {
Ok(CreateFileInfo {
context: EntryHandle::new(Entry::Directory(Arc::clone(dir)), None, delete_on_close),
is_dir: true,
new_file_created: false,
})
}
FILE_CREATE => nt_res(STATUS_OBJECT_NAME_COLLISION),
_ => nt_res(STATUS_INVALID_PARAMETER),
}
}
}
} else {
if parent.stat.read().unwrap().delete_pending {
return nt_res(STATUS_DELETE_PENDING);
}
let token = info.requester_token().unwrap();
if create_options & FILE_DIRECTORY_FILE > 0 {
match create_disposition {
FILE_CREATE | FILE_OPEN_IF => {
self.create_new(
&name,
file_attributes,
delete_on_close,
security_context.AccessState.SecurityDescriptor,
token.as_raw_handle(),
&parent,
&mut children,
true,
)
}
FILE_OPEN => nt_res(STATUS_OBJECT_NAME_NOT_FOUND),
_ => nt_res(STATUS_INVALID_PARAMETER),
}
} else {
if create_disposition == FILE_OPEN || create_disposition == FILE_OVERWRITE {
nt_res(STATUS_OBJECT_NAME_NOT_FOUND)
} else {
self.create_new(
&name,
file_attributes | winnt::FILE_ATTRIBUTE_ARCHIVE,
delete_on_close,
security_context.AccessState.SecurityDescriptor,
token.as_raw_handle(),
&parent,
&mut children,
false,
)
}
}
}
} else {
if create_disposition == FILE_OPEN || create_disposition == FILE_OPEN_IF {
if create_options & FILE_NON_DIRECTORY_FILE > 0 {
nt_res(STATUS_FILE_IS_A_DIRECTORY)
} else {
Ok(CreateFileInfo {
context: EntryHandle::new(
Entry::Directory(Arc::clone(&self.root)),
None, info.delete_on_close(),
),
is_dir: true,
new_file_created: false,
})
}
} else {
nt_res(STATUS_INVALID_PARAMETER)
}
}
}
fn close_file(
&'b self,
_file_name: &U16CStr,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) {
let mut stat = context.entry.stat().write().unwrap();
if let Some(mtime) = context.mtime_delayed.lock().unwrap().clone() {
if mtime > stat.mtime {
stat.mtime = mtime;
}
}
if let Some(atime) = context.atime_delayed.lock().unwrap().clone() {
if atime > stat.atime {
stat.atime = atime;
}
}
}
fn read_file(
&'b self,
_file_name: &U16CStr,
offset: i64,
buffer: &mut [u8],
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<u32, OperationError> {
let mut do_read = |data: &Vec<_>| {
let offset = offset as usize;
let len = std::cmp::min(buffer.len(), data.len() - offset);
buffer[0..len].copy_from_slice(&data[offset..offset + len]);
len as u32
};
let alt_stream = context.alt_stream.read().unwrap();
if let Some(stream) = alt_stream.as_ref() {
Ok(do_read(&stream.read().unwrap().data))
} else if let Entry::File(file) = &context.entry {
Ok(do_read(&file.data.read().unwrap()))
} else {
nt_res(STATUS_INVALID_DEVICE_REQUEST)
}
}
fn write_file(
&'b self,
_file_name: &U16CStr,
offset: i64,
buffer: &[u8],
info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<u32, OperationError> {
let do_write = |data: &mut Vec<_>| {
let offset = if info.write_to_eof() { data.len() } else { offset as usize };
let len = buffer.len();
if offset + len > data.len() {
data.resize(offset + len, 0);
}
data[offset..offset + len].copy_from_slice(buffer);
len as u32
};
let alt_stream = context.alt_stream.read().unwrap();
let ret = if let Some(stream) = alt_stream.as_ref() {
Ok(do_write(&mut stream.write().unwrap().data))
} else if let Entry::File(file) = &context.entry {
Ok(do_write(&mut file.data.write().unwrap()))
} else {
nt_res(STATUS_ACCESS_DENIED)
};
if ret.is_ok() {
context.entry.stat().write().unwrap().attrs.value |= winnt::FILE_ATTRIBUTE_ARCHIVE;
let now = SystemTime::now();
if context.mtime_enabled.load(Ordering::Relaxed) {
*context.mtime_delayed.lock().unwrap() = Some(now);
}
if context.atime_enabled.load(Ordering::Relaxed) {
*context.atime_delayed.lock().unwrap() = Some(now);
}
}
ret
}
fn flush_file_buffers(
&'b self,
_file_name: &U16CStr,
_info: &OperationInfo<'a, 'b, Self>,
_context: &'a Self::Context,
) -> Result<(), OperationError> {
Ok(())
}
fn get_file_information(
&'b self,
_file_name: &U16CStr,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<FileInfo, OperationError> {
let stat = context.entry.stat().read().unwrap();
let alt_stream = context.alt_stream.read().unwrap();
Ok(FileInfo {
attributes: stat.attrs.get_output_attrs(context.is_dir()),
creation_time: stat.ctime,
last_access_time: stat.atime,
last_write_time: stat.mtime,
file_size: if let Some(stream) = alt_stream.as_ref() {
stream.read().unwrap().data.len() as u64
} else {
match &context.entry {
Entry::File(file) => file.data.read().unwrap().len() as u64,
Entry::Directory(_) => 0,
}
},
number_of_links: 1,
file_index: stat.id,
})
}
fn find_files(
&'b self,
_file_name: &U16CStr,
mut fill_find_data: impl FnMut(&FindData) -> Result<(), FillDataError>,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
if context.alt_stream.read().unwrap().is_some() {
return nt_res(STATUS_INVALID_DEVICE_REQUEST);
}
if let Entry::Directory(dir) = &context.entry {
let children = dir.children.read().unwrap();
for (k, v) in children.iter() {
let stat = v.stat().read().unwrap();
let res = fill_find_data(&FindData {
attributes: stat.attrs.get_output_attrs(v.is_dir()),
creation_time: stat.ctime,
last_access_time: stat.atime,
last_write_time: stat.mtime,
file_size: match v {
Entry::File(file) => file.data.read().unwrap().len() as u64,
Entry::Directory(_) => 0,
},
file_name: U16CString::from_ustr(&k.0).unwrap(),
});
check_fill_data_error(res)?;
}
Ok(())
} else {
nt_res(STATUS_INVALID_DEVICE_REQUEST)
}
}
fn set_file_attributes(
&'b self,
_file_name: &U16CStr,
file_attributes: u32,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let mut stat = context.entry.stat().write().unwrap();
stat.attrs = Attributes::new(file_attributes);
context.update_atime(&mut stat, SystemTime::now());
Ok(())
}
fn set_file_time(
&'b self,
_file_name: &U16CStr,
creation_time: FileTimeInfo,
last_access_time: FileTimeInfo,
last_write_time: FileTimeInfo,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let mut stat = context.entry.stat().write().unwrap();
let process_time_info = |time_info: &FileTimeInfo, time: &mut SystemTime, flag: &AtomicBool| {
match time_info {
FileTimeInfo::SetTime(new_time) =>
if flag.load(Ordering::Relaxed) {
*time = *new_time
},
FileTimeInfo::DisableUpdate => flag.store(false, Ordering::Relaxed),
FileTimeInfo::ResumeUpdate => flag.store(true, Ordering::Relaxed),
FileTimeInfo::DontChange => (),
}
};
process_time_info(&creation_time, &mut stat.ctime, &context.ctime_enabled);
process_time_info(&last_write_time, &mut stat.mtime, &context.mtime_enabled);
process_time_info(&last_access_time, &mut stat.atime, &context.atime_enabled);
Ok(())
}
fn delete_file(
&'b self,
_file_name: &U16CStr,
info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
if context.entry.stat().read().unwrap().attrs.value & winnt::FILE_ATTRIBUTE_READONLY > 0 {
return nt_res(STATUS_CANNOT_DELETE);
}
let alt_stream = context.alt_stream.read().unwrap();
if let Some(stream) = alt_stream.as_ref() {
stream.write().unwrap().delete_pending = info.delete_on_close();
} else {
context.entry.stat().write().unwrap().delete_pending = info.delete_on_close();
}
Ok(())
}
fn delete_directory(
&'b self,
_file_name: &U16CStr,
info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
if context.alt_stream.read().unwrap().is_some() {
return nt_res(STATUS_INVALID_DEVICE_REQUEST);
}
if let Entry::Directory(dir) = &context.entry {
// Lock children first to avoid race conditions.
let children = dir.children.read().unwrap();
let mut stat = dir.stat.write().unwrap();
if stat.parent.upgrade().is_none() {
// Root directory can't be deleted.
return nt_res(STATUS_ACCESS_DENIED);
}
if info.delete_on_close() && !children.is_empty() {
nt_res(STATUS_DIRECTORY_NOT_EMPTY)
} else {
stat.delete_pending = info.delete_on_close();
Ok(())
}
} else {
nt_res(STATUS_INVALID_DEVICE_REQUEST)
}
}
fn move_file(
&'b self,
file_name: &U16CStr,
new_file_name: &U16CStr,
replace_if_existing: bool,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let src_path = file_name.as_slice();
let offset = src_path.iter().rposition(|x| *x == '\\' as u16)
.ok_or(nt_err(STATUS_INVALID_PARAMETER))?;
let src_name = U16Str::from_slice(&src_path[offset + 1..]);
let src_parent = context.entry.stat().read().unwrap().parent.upgrade()
.ok_or(nt_err(STATUS_INVALID_DEVICE_REQUEST))?;
if new_file_name.as_slice().first() == Some(&(':' as u16)) {
let src_stream_info = FullName::new(src_name)?.stream_info;
let dst_stream_info = FullName::new(U16Str::from_slice(new_file_name.as_slice()))?.stream_info;
let src_is_default = context.alt_stream.read().unwrap().is_none();
let dst_is_default = if let Some(stream_info) = &dst_stream_info {
stream_info.check_default(context.entry.is_dir())?
} else { true };
let check_can_move = |streams: &mut HashMap<EntryName, Arc<RwLock<AltStream>>>, name: &U16Str| {
let name_ref = EntryNameRef::new(name);
if let Some(stream) = streams.get(name_ref) {
if context.alt_stream.read().unwrap().as_ref()
.map(|s| Arc::ptr_eq(s, stream))
.unwrap_or(false) {
Ok(())
} else if !replace_if_existing {
nt_res(STATUS_OBJECT_NAME_COLLISION)
} else if stream.read().unwrap().handle_count > 0 {
nt_res(STATUS_ACCESS_DENIED)
} else {
streams.remove(name_ref).unwrap();
Ok(())
}
} else { Ok(()) }
};
let mut stat = context.entry.stat().write().unwrap();
match (src_is_default, dst_is_default) {
(true, true) => if context.entry.is_dir() {
return nt_res(STATUS_OBJECT_NAME_INVALID);
},
(true, false) => if let Entry::File(file) = &context.entry {
let dst_name = dst_stream_info.unwrap().name;
check_can_move(&mut stat.alt_streams, dst_name)?;
let mut stream = AltStream::new();
let mut data = file.data.write().unwrap();
stream.handle_count = 1;
stream.delete_pending = stat.delete_pending;
stat.delete_pending = false;
stream.data = data.clone();
data.clear();
let stream = Arc::new(RwLock::new(stream));
assert!(stat.alt_streams
.insert(EntryName(dst_name.to_owned()), Arc::clone(&stream))
.is_none());
*context.alt_stream.write().unwrap() = Some(stream);
} else {
return nt_res(STATUS_OBJECT_NAME_INVALID);
}
(false, true) => if let Entry::File(file) = &context.entry {
let mut context_stream = context.alt_stream.write().unwrap();
let src_stream = context_stream.as_ref().unwrap();
let mut src_stream_locked = src_stream.write().unwrap();
if src_stream_locked.handle_count > 1 {
return nt_res(STATUS_SHARING_VIOLATION);
}
if !replace_if_existing {
return nt_res(STATUS_OBJECT_NAME_COLLISION);
}
src_stream_locked.handle_count -= 1;
stat.delete_pending = src_stream_locked.delete_pending;
src_stream_locked.delete_pending = false;
*file.data.write().unwrap() = src_stream_locked.data.clone();
stat.alt_streams.remove(EntryNameRef::new(src_stream_info.unwrap().name)).unwrap();
std::mem::drop(src_stream_locked);
*context_stream = None;
} else {
return nt_res(STATUS_OBJECT_NAME_INVALID);
}
(false, false) => {
let dst_name = dst_stream_info.unwrap().name;
check_can_move(&mut stat.alt_streams, dst_name)?;
let stream = stat.alt_streams.remove(EntryNameRef::new(src_stream_info.unwrap().name)).unwrap();
stat.alt_streams.insert(EntryName(dst_name.to_owned()), Arc::clone(&stream));
*context.alt_stream.write().unwrap() = Some(stream);
}
}
stat.update_atime(SystemTime::now());
} else {
if context.alt_stream.read().unwrap().is_some() {
return nt_res(STATUS_OBJECT_NAME_INVALID);
}
let (dst_name, dst_parent) = path::split_path(&self.root, new_file_name)?
.ok_or(nt_err(STATUS_OBJECT_NAME_INVALID))?; | if dst_name.stream_info.is_some() {
return nt_res(STATUS_OBJECT_NAME_INVALID);
}
let now = SystemTime::now();
let src_name_ref = EntryNameRef::new(src_name);
let dst_name_ref = EntryNameRef::new(dst_name.file_name);
let check_can_move = |children: &mut HashMap<EntryName, Entry>| {
if let Some(entry) = children.get(dst_name_ref) {
if &context.entry == entry {
Ok(())
} else if !replace_if_existing {
nt_res(STATUS_OBJECT_NAME_COLLISION)
} else if context.entry.is_dir() || entry.is_dir() {
nt_res(STATUS_ACCESS_DENIED)
} else {
let stat = entry.stat().read().unwrap();
let can_replace = stat.handle_count > 0 ||
stat.attrs.value & winnt::FILE_ATTRIBUTE_READONLY > 0;
std::mem::drop(stat);
if can_replace {
nt_res(STATUS_ACCESS_DENIED)
} else {
children.remove(dst_name_ref).unwrap();
Ok(())
}
}
} else { Ok(()) }
};
if Arc::ptr_eq(&src_parent, &dst_parent) {
let mut children = src_parent.children.write().unwrap();
check_can_move(&mut children)?;
// Remove first in case moving to the same name.
let entry = children.remove(src_name_ref).unwrap();
assert!(children.insert(EntryName(dst_name.file_name.to_owned()), entry).is_none());
src_parent.stat.write().unwrap().update_mtime(now);
context.update_atime(&mut context.entry.stat().write().unwrap(), now);
} else {
let mut src_children = src_parent.children.write().unwrap();
let mut dst_children = dst_parent.children.write().unwrap();
check_can_move(&mut dst_children)?;
let entry = src_children.remove(src_name_ref).unwrap();
assert!(dst_children.insert(EntryName(dst_name.file_name.to_owned()), entry).is_none());
src_parent.stat.write().unwrap().update_mtime(now);
dst_parent.stat.write().unwrap().update_mtime(now);
let mut stat = context.entry.stat().write().unwrap();
stat.parent = Arc::downgrade(&dst_parent);
context.update_atime(&mut stat, now);
}
}
Ok(())
}
fn set_end_of_file(
&'b self,
_file_name: &U16CStr,
offset: i64,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let alt_stream = context.alt_stream.read().unwrap();
let ret = if let Some(stream) = alt_stream.as_ref() {
stream.write().unwrap().data.resize(offset as usize, 0);
Ok(())
} else if let Entry::File(file) = &context.entry {
file.data.write().unwrap().resize(offset as usize, 0);
Ok(())
} else {
nt_res(STATUS_INVALID_DEVICE_REQUEST)
};
if ret.is_ok() {
context.update_mtime(&mut context.entry.stat().write().unwrap(), SystemTime::now());
}
ret
}
fn set_allocation_size(
&'b self,
_file_name: &U16CStr,
alloc_size: i64,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let set_alloc = |data: &mut Vec<_>| {
let alloc_size = alloc_size as usize;
let cap = data.capacity();
if alloc_size < data.len() {
data.resize(alloc_size, 0);
} else if alloc_size < cap {
let mut new_data = Vec::with_capacity(alloc_size);
new_data.append(data);
*data = new_data;
} else if alloc_size > cap {
data.reserve(alloc_size - cap);
}
};
let alt_stream = context.alt_stream.read().unwrap();
let ret = if let Some(stream) = alt_stream.as_ref() {
set_alloc(&mut stream.write().unwrap().data);
Ok(())
} else if let Entry::File(file) = &context.entry {
set_alloc(&mut file.data.write().unwrap());
Ok(())
} else {
nt_res(STATUS_INVALID_DEVICE_REQUEST)
};
if ret.is_ok() {
context.update_mtime(&mut context.entry.stat().write().unwrap(), SystemTime::now());
}
ret
}
fn get_disk_free_space(
&'b self,
_info: &OperationInfo<'a, 'b, Self>,
) -> Result<DiskSpaceInfo, OperationError> {
Ok(DiskSpaceInfo {
byte_count: 1024 * 1024 * 1024,
free_byte_count: 512 * 1024 * 1024,
available_byte_count: 512 * 1024 * 1024,
})
}
fn get_volume_information(
&'b self,
_info: &OperationInfo<'a, 'b, Self>,
) -> Result<VolumeInfo, OperationError> {
Ok(VolumeInfo {
name: U16CString::from_str("dokan-rust memfs").unwrap(),
serial_number: 0,
max_component_length: path::MAX_COMPONENT_LENGTH,
fs_flags: winnt::FILE_CASE_PRESERVED_NAMES | winnt::FILE_CASE_SENSITIVE_SEARCH | winnt::FILE_UNICODE_ON_DISK
| winnt::FILE_PERSISTENT_ACLS | winnt::FILE_NAMED_STREAMS,
// Custom names don't play well with UAC.
fs_name: U16CString::from_str("NTFS").unwrap(),
})
}
fn get_file_security(
&'b self,
_file_name: &U16CStr,
security_information: u32,
security_descriptor: winnt::PSECURITY_DESCRIPTOR,
buffer_length: u32,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<u32, OperationError> {
context.entry.stat().read().unwrap().sec_desc.get_security_info(
security_information,
security_descriptor,
buffer_length,
)
}
fn set_file_security(
&'b self,
_file_name: &U16CStr,
security_information: u32,
security_descriptor: winnt::PSECURITY_DESCRIPTOR,
_buffer_length: u32,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
let mut stat = context.entry.stat().write().unwrap();
let ret = stat.sec_desc.set_security_info(
security_information,
security_descriptor,
);
if ret.is_ok() {
context.update_atime(&mut stat, SystemTime::now());
}
ret
}
fn find_streams(
&'b self,
_file_name: &U16CStr,
mut fill_find_stream_data: impl FnMut(&FindStreamData) -> Result<(), FillDataError>,
_info: &OperationInfo<'a, 'b, Self>,
context: &'a Self::Context,
) -> Result<(), OperationError> {
if let Entry::File(file) = &context.entry {
let res = fill_find_stream_data(&FindStreamData {
size: file.data.read().unwrap().len() as i64,
name: U16CString::from_str("::$DATA").unwrap(),
});
check_fill_data_error(res)?;
}
for (k, v) in context.entry.stat().read().unwrap().alt_streams.iter() {
let mut name_buf = vec![':' as u16];
name_buf.extend_from_slice(k.0.as_slice());
name_buf.extend_from_slice(U16String::from_str(":$DATA").as_slice());
let res = fill_find_stream_data(&FindStreamData {
size: v.read().unwrap().data.len() as i64,
name: U16CString::from_ustr(U16Str::from_slice(&name_buf)).unwrap(),
});
check_fill_data_error(res)?;
}
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = App::new("dokan-rust memfs example")
.author(env!("CARGO_PKG_AUTHORS"))
.arg(Arg::with_name("mount_point").short("m").long("mount-point")
.takes_value(true).value_name("MOUNT_POINT").required(true)
.help("Mount point path."))
.arg(Arg::with_name("thread_count").short("t").long("threads")
.takes_value(true).value_name("THREAD_COUNT").default_value("0")
.help("Thread count. Use \"0\" to let Dokan choose it automatically."))
.arg(Arg::with_name("dokan_debug").short("d").long("dokan-debug")
.help("Enable Dokan's debug output."))
.arg(Arg::with_name("removable").short("r").long("removable")
.help("Mount as a removable drive."))
.get_matches();
let mount_point = U16CString::from_str(matches.value_of("mount_point").unwrap())?;
let mut flags = MountFlags::ALT_STREAM;
if matches.is_present("dokan_debug") {
flags |= MountFlags::DEBUG | MountFlags::STDERR;
}
if matches.is_present("removable") {
flags |= MountFlags::REMOVABLE;
}
Drive::new()
.mount_point(&mount_point)
.thread_count(matches.value_of("thread_count").unwrap().parse()?)
.flags(flags)
.mount(&MemFsHandler::new())?;
Ok(())
} | |
RespondToTradeRequest.py | from kol.request.GenericRequest import GenericRequest
from kol.manager import PatternManager
import kol.Error as Error
from kol.util import Report
class RespondToTradeRequest(GenericRequest):
def __init__(self, session, tradeid, items=None, meat=0, message=""):
|
def parseResponse(self):
noMeatPattern = PatternManager.getOrCompilePattern('traderHasNotEnoughMeat')
if noMeatPattern.search(self.responseText):
raise Error.Error("You don't have as much meat as you're promising.", Error.NOT_ENOUGH_MEAT)
noItemsPattern = PatternManager.getOrCompilePattern('traderHasNotEnoughItems')
if noItemsPattern.search(self.responseText):
raise Error.Error("You don't have as many items as you're promising.", Error.NOT_ENOUGH_ITEMS)
#Not testing for an offer being cancelled due to a bug in KoL - space reserved
successPattern = PatternManager.getOrCompilePattern('tradeResponseSentSuccessfully')
if successPattern.search(self.responseText):
Report.trace("request", "Response to trade " + str(self.requestData['whichoffer']) + ' sent successfully.')
else:
raise Error.Error("Unknown error sending response to trade " + str(self.requestData['whichoffer']), Error.REQUEST_GENERIC) | super(RespondToTradeRequest, self).__super__(session)
self.url = session.serverURL + "makeoffer.php"
self.requestData['action'] = 'counter'
self.requestData['pwd'] = session.pwd
self.requestData['whichoffer'] = tradeid
self.requestData['offermeat'] = meat
self.requestData['memo2'] = message
ctr = 1
for item in items:
self.requestData['whichitem' + str(ctr)] = item['itemID']
self.requestData['howmany' + str(ctr)] = item['quantity']
ctr += 1 |
0002_projects.py | # Generated by Django 3.1.3 on 2020-11-28 15:05
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('awwards', '0001_initial'),
]
operations = [
migrations.CreateModel( | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', cloudinary.models.CloudinaryField(max_length=255, verbose_name='image')),
('description', models.TextField()),
('created_date', models.DateTimeField(default=django.utils.timezone.now)),
('title', models.CharField(max_length=255)),
('link', models.URLField()),
('author', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('author_profile', models.ForeignKey(blank=True, default='1', on_delete=django.db.models.deletion.CASCADE, to='awwards.profile')),
],
options={
'db_table': 'project',
'ordering': ['-created_date'],
},
),
] | name='Projects', |
issue-4736.rs | struct NonCopyable(());
| fn main() {
let z = NonCopyable{ p: () }; //~ ERROR struct `NonCopyable` has no field named `p`
} |
|
cancellationToken.ts | namespace ts.projectSystem {
describe("unittests:: tsserver:: cancellationToken", () => {
// Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test
let oldPrepare: AnyFunction;
before(() => {
oldPrepare = (Error as any).prepareStackTrace;
delete (Error as any).prepareStackTrace;
});
after(() => {
(Error as any).prepareStackTrace = oldPrepare;
});
it("is attached to request", () => {
const f1 = {
path: "/a/b/app.ts",
content: "let xyz = 1;"
};
const host = createServerHost([f1]);
let expectedRequestId: number;
const cancellationToken: server.ServerCancellationToken = {
isCancellationRequested: () => false,
setRequest: requestId => {
if (expectedRequestId === undefined) {
assert.isTrue(false, "unexpected call");
}
assert.equal(requestId, expectedRequestId);
},
resetRequest: noop
};
const session = createSession(host, { cancellationToken });
expectedRequestId = session.getNextSeq();
session.executeCommandSeq({
command: "open",
arguments: { file: f1.path }
} as server.protocol.OpenRequest);
expectedRequestId = session.getNextSeq();
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as server.protocol.GeterrRequest);
expectedRequestId = session.getNextSeq();
session.executeCommandSeq({
command: "occurrences",
arguments: { file: f1.path, line: 1, offset: 6 }
} as server.protocol.OccurrencesRequest);
expectedRequestId = 2;
host.runQueuedImmediateCallbacks();
expectedRequestId = 2;
host.runQueuedImmediateCallbacks();
});
it("Geterr is cancellable", () => {
const f1 = {
path: "/a/app.ts",
content: "let x = 1"
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: {}
})
};
const cancellationToken = new TestServerCancellationToken();
const host = createServerHost([f1, config]);
const session = createSession(host, {
canUseEvents: true,
eventHandler: noop,
cancellationToken
});
{
session.executeCommandSeq({
command: "open",
arguments: { file: f1.path }
} as protocol.OpenRequest);
// send geterr for missing file
session.executeCommandSeq({
command: "geterr",
arguments: { files: ["/a/missing"] }
} as protocol.GeterrRequest);
// Queued files
assert.equal(host.getOutput().length, 0, "expected 0 message");
host.checkTimeoutQueueLengthAndRun(1);
// Completed event since file is missing
assert.equal(host.getOutput().length, 1, "expect 1 message");
verifyRequestCompleted(session.getSeq(), 0);
}
{
const getErrId = session.getNextSeq();
// send geterr for a valid file
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as protocol.GeterrRequest);
assert.equal(host.getOutput().length, 0, "expect 0 messages");
// run new request
session.executeCommandSeq({
command: "projectInfo",
arguments: { file: f1.path }
} as protocol.ProjectInfoRequest);
session.clearMessages();
// cancel previously issued Geterr
cancellationToken.setRequestToCancel(getErrId);
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
verifyRequestCompleted(getErrId, 0);
cancellationToken.resetToken();
}
{
const getErrId = session.getNextSeq();
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as protocol.GeterrRequest);
assert.equal(host.getOutput().length, 0, "expect 0 messages");
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = getMessage(0) as protocol.Event;
assert.equal(e1.event, "syntaxDiag");
session.clearMessages();
cancellationToken.setRequestToCancel(getErrId);
host.runQueuedImmediateCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
verifyRequestCompleted(getErrId, 0);
cancellationToken.resetToken();
}
{
const getErrId = session.getNextSeq();
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as protocol.GeterrRequest);
assert.equal(host.getOutput().length, 0, "expect 0 messages");
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = getMessage(0) as protocol.Event;
assert.equal(e1.event, "syntaxDiag");
session.clearMessages();
// the semanticDiag message
host.runQueuedImmediateCallbacks();
assert.equal(host.getOutput().length, 1);
const e2 = getMessage(0) as protocol.Event;
assert.equal(e2.event, "semanticDiag");
session.clearMessages();
host.runQueuedImmediateCallbacks(1);
assert.equal(host.getOutput().length, 2);
const e3 = getMessage(0) as protocol.Event;
assert.equal(e3.event, "suggestionDiag");
verifyRequestCompleted(getErrId, 1);
cancellationToken.resetToken();
}
{
const getErr1 = session.getNextSeq();
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as protocol.GeterrRequest);
assert.equal(host.getOutput().length, 0, "expect 0 messages");
// run first step
host.runQueuedTimeoutCallbacks();
assert.equal(host.getOutput().length, 1, "expect 1 message");
const e1 = getMessage(0) as protocol.Event;
assert.equal(e1.event, "syntaxDiag");
session.clearMessages();
session.executeCommandSeq({
command: "geterr",
arguments: { files: [f1.path] }
} as protocol.GeterrRequest);
// make sure that getErr1 is completed
verifyRequestCompleted(getErr1, 0);
}
function verifyRequestCompleted(expectedSeq: number, n: number) {
const event = getMessage(n) as protocol.RequestCompletedEvent;
assert.equal(event.event, "requestCompleted");
assert.equal(event.body.request_seq, expectedSeq, "expectedSeq");
session.clearMessages();
}
function | (n: number) {
return JSON.parse(server.extractMessage(host.getOutput()[n]));
}
});
it("Lower priority tasks are cancellable", () => {
const f1 = {
path: "/a/app.ts",
content: `{ let x = 1; } var foo = "foo"; var bar = "bar"; var fooBar = "fooBar";`
};
const config = {
path: "/a/tsconfig.json",
content: JSON.stringify({
compilerOptions: {}
})
};
const cancellationToken = new TestServerCancellationToken(/*cancelAfterRequest*/ 3);
const host = createServerHost([f1, config]);
const session = createSession(host, {
canUseEvents: true,
eventHandler: noop,
cancellationToken,
throttleWaitMilliseconds: 0
});
{
session.executeCommandSeq({
command: "open",
arguments: { file: f1.path }
} as protocol.OpenRequest);
// send navbar request (normal priority)
session.executeCommandSeq({
command: "navbar",
arguments: { file: f1.path }
} as protocol.NavBarRequest);
// ensure the nav bar request can be canceled
verifyExecuteCommandSeqIsCancellable({
command: "navbar",
arguments: { file: f1.path }
} as protocol.NavBarRequest);
// send outlining spans request (normal priority)
session.executeCommandSeq({
command: "outliningSpans",
arguments: { file: f1.path }
} as protocol.OutliningSpansRequestFull);
// ensure the outlining spans request can be canceled
verifyExecuteCommandSeqIsCancellable({
command: "outliningSpans",
arguments: { file: f1.path }
} as protocol.OutliningSpansRequestFull);
}
function verifyExecuteCommandSeqIsCancellable<T extends server.protocol.Request>(request: Partial<T>) {
// Set the next request to be cancellable
// The cancellation token will cancel the request the third time
// isCancellationRequested() is called.
cancellationToken.setRequestToCancel(session.getNextSeq());
let operationCanceledExceptionThrown = false;
try {
session.executeCommandSeq(request);
}
catch (e) {
assert(e instanceof OperationCanceledException);
operationCanceledExceptionThrown = true;
}
assert(operationCanceledExceptionThrown, "Operation Canceled Exception not thrown for request: " + JSON.stringify(request));
}
});
});
}
| getMessage |
test_complete_graph.rs | extern crate graph;
use graph::*;
#[test]
fn test_complete_graph() -> Result<()> {
let mut complete_graph =
Graph::generate_complete_graph(None, Some(10), None, None, None, None, None, None).unwrap();
assert!(complete_graph.is_connected(Some(true))); | let _ = graph::test_utilities::default_test_suite(&mut complete_graph, None);
Ok(())
} |
|
Photo.ts | import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "../../../../src";
import {User} from "./User";
@Entity()
export class | {
@PrimaryGeneratedColumn()
id: number;
@Column()
url: string;
@ManyToOne("User", "photos")
user: User;
} | Photo |
meta_store_test.rs | // Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
use async_raft::storage::HardState;
use async_raft::RaftStorage;
use common_runtime::tokio;
use common_tracing::tracing;
use crate::meta_service::MetaStore;
use crate::tests::service::new_test_context;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_meta_store_restart() -> anyhow::Result<()> | {
// - Create a MetaStore
// - Update MetaStore
// - Close and reopen it
// - Test state is restored
// TODO check log
// TODO check state machine
let id = 3;
let tc = new_test_context();
tracing::info!("--- new MetaStore");
{
let ms = MetaStore::new(id, &tc.config).await?;
assert_eq!(id, ms.id);
assert_eq!(None, ms.read_hard_state().await?);
tracing::info!("--- update MetaStore");
ms.save_hard_state(&HardState {
current_term: 10,
voted_for: Some(5),
})
.await?;
}
tracing::info!("--- reopen MetaStore");
{
let ms = MetaStore::open(&tc.config).await?;
assert_eq!(id, ms.id);
assert_eq!(
Some(HardState {
current_term: 10,
voted_for: Some(5),
}),
ms.read_hard_state().await?
);
}
Ok(())
} |
|
random.test.ts | import { RGBColor } from '@antv/color-schema';
import { randomColor } from '@src/generators/random';
describe('Random Generator', () => {
test('should generate random colors', () => {
const { model, value } = randomColor() as RGBColor; | expect(model).toBe('rgb');
expect(Math.min(r, g, b) >= 0 && Math.max(r, g, b) < 256).toBe(true);
});
}); | const { r, g, b } = value; |
virtual_machines.go | // +build vms
package proxmox
| import "fmt"
func (v *VirtualMachine) Start() (status string, err error) {
return status, v.client.Post(fmt.Sprintf("/nodes/%s/qemu/%s/status/start", v.Node, v.VMID), nil, &status)
}
func (v *VirtualMachine) Stop() (status *VirtualMachineStatus, err error) {
return status, v.client.Post(fmt.Sprintf("/nodes/%s/qemu/%s/status/stop", v.Node, v.VMID), nil, &status)
}
func (v *VirtualMachine) Suspend() (status *VirtualMachineStatus, err error) {
return status, v.client.Post(fmt.Sprintf("/nodes/%s/qemu/%s/status/suspend", v.Node, v.VMID), nil, &status)
}
func (v *VirtualMachine) Reboot() (status *VirtualMachineStatus, err error) {
return status, v.client.Post(fmt.Sprintf("/nodes/%s/qemu/%s/status/reboot", v.Node, v.VMID), nil, &status)
}
func (v *VirtualMachine) Resume() (status *VirtualMachineStatus, err error) {
return status, v.client.Post(fmt.Sprintf("/nodes/%s/qemu/%s/status/resume", v.Node, v.VMID), nil, &status)
} | |
icon_wb_auto.rs |
pub struct IconWbAuto {
props: crate::Props,
}
impl yew::Component for IconWbAuto {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
|
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M6.85 12.65h2.3L8 9l-1.15 3.65zM22 7l-1.2 6.29L19.3 7h-1.6l-1.49 6.29L15 7h-.76C12.77 5.17 10.53 4 8 4c-4.42 0-8 3.58-8 8s3.58 8 8 8c3.13 0 5.84-1.81 7.15-4.43l.1.43H17l1.5-6.1L20 16h1.75l2.05-9H22zm-11.7 9l-.7-2H6.4l-.7 2H3.8L7 7h2l3.2 9h-1.9z"/></svg>
</svg>
}
}
}
| {
false
} |
get_groups_group_id_accounts_saving_currency.go | package models | type GetGroupsGroupIdAccountsSavingCurrency struct {
Code string `json:"code,omitempty"`
Name string `json:"name,omitempty"`
DecimalPlaces int32 `json:"decimalPlaces,omitempty"`
DisplaySymbol string `json:"displaySymbol,omitempty"`
NameCode string `json:"nameCode,omitempty"`
DisplayLabel string `json:"displayLabel,omitempty"`
} |
// GetGroupsGroupIdAccountsSavingCurrency struct for GetGroupsGroupIdAccountsSavingCurrency |
teams.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.19.0
// source: external/iam/v2/common/teams.proto
package common
import (
_ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Team struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Projects []string `protobuf:"bytes,3,rep,name=projects,proto3" json:"projects,omitempty"`
}
func (x *Team) Reset() {
*x = Team{}
if protoimpl.UnsafeEnabled {
mi := &file_external_iam_v2_common_teams_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Team) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Team) ProtoMessage() {}
func (x *Team) ProtoReflect() protoreflect.Message {
mi := &file_external_iam_v2_common_teams_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Team.ProtoReflect.Descriptor instead.
func (*Team) Descriptor() ([]byte, []int) {
return file_external_iam_v2_common_teams_proto_rawDescGZIP(), []int{0}
}
func (x *Team) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *Team) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Team) GetProjects() []string {
if x != nil {
return x.Projects
}
return nil
}
var File_external_iam_v2_common_teams_proto protoreflect.FileDescriptor
var file_external_iam_v2_common_teams_proto_rawDesc = []byte{
0x0a, 0x22, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x69, 0x61, 0x6d, 0x2f, 0x76,
0x32, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2f, 0x74, 0x65, 0x61, 0x6d, 0x73, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x18, 0x63, 0x68, 0x65, 0x66, 0x2e, 0x61, 0x75, 0x74, 0x6f, 0x6d,
0x61, 0x74, 0x65, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x69, 0x61, 0x6d, 0x2e, 0x76, 0x32, 0x1a, 0x2c,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x73, 0x77, 0x61, 0x67, 0x67,
0x65, 0x72, 0x2f, 0x6f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x46, 0x0a, 0x04,
0x54, 0x65, 0x61, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01,
0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x72, 0x6f, 0x6a,
0x65, 0x63, 0x74, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x08, 0x70, 0x72, 0x6f, 0x6a,
0x65, 0x63, 0x74, 0x73, 0x42, 0x35, 0x5a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63,
0x6f, 0x6d, 0x2f, 0x63, 0x68, 0x65, 0x66, 0x2f, 0x61, 0x75, 0x74, 0x6f, 0x6d, 0x61, 0x74, 0x65,
0x2f, 0x61, 0x70, 0x69, 0x2f, 0x65, 0x78, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x69, 0x61,
0x6d, 0x2f, 0x76, 0x32, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x62, 0x06, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x33,
}
var (
file_external_iam_v2_common_teams_proto_rawDescOnce sync.Once
file_external_iam_v2_common_teams_proto_rawDescData = file_external_iam_v2_common_teams_proto_rawDesc
)
func file_external_iam_v2_common_teams_proto_rawDescGZIP() []byte |
var file_external_iam_v2_common_teams_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
var file_external_iam_v2_common_teams_proto_goTypes = []interface{}{
(*Team)(nil), // 0: chef.automate.api.iam.v2.Team
}
var file_external_iam_v2_common_teams_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_external_iam_v2_common_teams_proto_init() }
func file_external_iam_v2_common_teams_proto_init() {
if File_external_iam_v2_common_teams_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_external_iam_v2_common_teams_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Team); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_external_iam_v2_common_teams_proto_rawDesc,
NumEnums: 0,
NumMessages: 1,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_external_iam_v2_common_teams_proto_goTypes,
DependencyIndexes: file_external_iam_v2_common_teams_proto_depIdxs,
MessageInfos: file_external_iam_v2_common_teams_proto_msgTypes,
}.Build()
File_external_iam_v2_common_teams_proto = out.File
file_external_iam_v2_common_teams_proto_rawDesc = nil
file_external_iam_v2_common_teams_proto_goTypes = nil
file_external_iam_v2_common_teams_proto_depIdxs = nil
}
| {
file_external_iam_v2_common_teams_proto_rawDescOnce.Do(func() {
file_external_iam_v2_common_teams_proto_rawDescData = protoimpl.X.CompressGZIP(file_external_iam_v2_common_teams_proto_rawDescData)
})
return file_external_iam_v2_common_teams_proto_rawDescData
} |
address_book.rs | //! The `AddressBook` manages information about what peers exist, when they were
//! seen, and what services they provide.
use std::{cmp::Reverse, iter::Extend, net::SocketAddr, time::Instant};
use chrono::Utc;
use ordered_map::OrderedMap;
use tokio::sync::watch;
use tracing::Span;
use crate::{
constants, meta_addr::MetaAddrChange, protocol::external::canonical_socket_addr,
types::MetaAddr, PeerAddrState,
};
#[cfg(test)]
mod tests;
/// A database of peer listener addresses, their advertised services, and
/// information on when they were last seen.
///
/// # Security
///
/// Address book state must be based on outbound connections to peers.
///
/// If the address book is updated incorrectly:
/// - malicious peers can interfere with other peers' `AddressBook` state,
/// or
/// - Zebra can advertise unreachable addresses to its own peers.
///
/// ## Adding Addresses
///
/// The address book should only contain Zcash listener port addresses from peers
/// on the configured network. These addresses can come from:
/// - DNS seeders
/// - addresses gossiped by other peers
/// - the canonical address (`Version.address_from`) provided by each peer,
/// particularly peers on inbound connections.
///
/// The remote addresses of inbound connections must not be added to the address
/// book, because they contain ephemeral outbound ports, not listener ports.
///
/// Isolated connections must not add addresses or update the address book.
///
/// ## Updating Address State
///
/// Updates to address state must be based on outbound connections to peers.
///
/// Updates must not be based on:
/// - the remote addresses of inbound connections, or
/// - the canonical address of any connection.
#[derive(Debug)]
pub struct AddressBook {
/// Peer listener addresses, suitable for outbound connections,
/// in connection attempt order.
///
/// Some peers in this list might have open outbound or inbound connections.
///
/// We reverse the comparison order, because the standard library ([`BTreeMap`])
/// sorts in ascending order, but [`OrderedMap`] sorts in descending order.
by_addr: OrderedMap<SocketAddr, MetaAddr, Reverse<MetaAddr>>,
/// The maximum number of addresses in the address book.
///
/// Always set to [`MAX_ADDRS_IN_ADDRESS_BOOK`](constants::MAX_ADDRS_IN_ADDRESS_BOOK),
/// in release builds. Lower values are used during testing.
addr_limit: usize,
/// The local listener address.
local_listener: SocketAddr,
/// The span for operations on this address book.
span: Span,
/// A channel used to send the latest address book metrics.
address_metrics_tx: watch::Sender<AddressMetrics>,
/// The last time we logged a message about the address metrics.
last_address_log: Option<Instant>,
}
/// Metrics about the states of the addresses in an [`AddressBook`].
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct AddressMetrics {
/// The number of addresses in the `Responded` state.
responded: usize,
/// The number of addresses in the `NeverAttemptedGossiped` state.
never_attempted_gossiped: usize,
/// The number of addresses in the `NeverAttemptedAlternate` state.
never_attempted_alternate: usize,
/// The number of addresses in the `Failed` state.
failed: usize,
/// The number of addresses in the `AttemptPending` state.
attempt_pending: usize,
/// The number of `Responded` addresses within the liveness limit.
recently_live: usize,
/// The number of `Responded` addresses outside the liveness limit.
recently_stopped_responding: usize,
}
#[allow(clippy::len_without_is_empty)]
impl AddressBook {
/// Construct an [`AddressBook`] with the given `local_listener` and
/// [`tracing::Span`].
pub fn new(local_listener: SocketAddr, span: Span) -> AddressBook {
let constructor_span = span.clone();
let _guard = constructor_span.enter();
let instant_now = Instant::now();
let chrono_now = Utc::now();
// The default value is correct for an empty address book,
// and it gets replaced by `update_metrics` anyway.
let (address_metrics_tx, _address_metrics_rx) = watch::channel(AddressMetrics::default());
let mut new_book = AddressBook {
by_addr: OrderedMap::new(|meta_addr| Reverse(*meta_addr)),
addr_limit: constants::MAX_ADDRS_IN_ADDRESS_BOOK,
local_listener: canonical_socket_addr(local_listener),
span,
address_metrics_tx,
last_address_log: None,
};
new_book.update_metrics(instant_now, chrono_now);
new_book
}
/// Construct an [`AddressBook`] with the given `local_listener`,
/// `addr_limit`, [`tracing::Span`], and addresses.
///
/// `addr_limit` is enforced by this method, and by [`AddressBook::update`].
///
/// If there are multiple [`MetaAddr`]s with the same address,
/// an arbitrary address is inserted into the address book,
/// and the rest are dropped.
///
/// This constructor can be used to break address book invariants,
/// so it should only be used in tests.
#[cfg(any(test, feature = "proptest-impl"))]
pub fn new_with_addrs(
local_listener: SocketAddr,
addr_limit: usize,
span: Span,
addrs: impl IntoIterator<Item = MetaAddr>,
) -> AddressBook {
let constructor_span = span.clone();
let _guard = constructor_span.enter();
let instant_now = Instant::now();
let chrono_now = Utc::now();
let mut new_book = AddressBook::new(local_listener, span);
new_book.addr_limit = addr_limit;
let addrs = addrs
.into_iter()
.map(|mut meta_addr| {
meta_addr.addr = canonical_socket_addr(meta_addr.addr);
meta_addr
})
.filter(MetaAddr::address_is_valid_for_outbound)
.take(addr_limit)
.map(|meta_addr| (meta_addr.addr, meta_addr));
for (socket_addr, meta_addr) in addrs {
// overwrite any duplicate addresses
new_book.by_addr.insert(socket_addr, meta_addr);
}
new_book.update_metrics(instant_now, chrono_now);
new_book
}
/// Return a watch channel for the address book metrics.
///
/// The metrics in the watch channel are only updated when the address book updates,
/// so they can be significantly outdated if Zebra is disconnected or hung.
///
/// The current metrics value is marked as seen.
/// So `Receiver::changed` will only return after the next address book update.
pub fn address_metrics_watcher(&self) -> watch::Receiver<AddressMetrics> {
self.address_metrics_tx.subscribe()
}
/// Get the local listener address.
///
/// This address contains minimal state, but it is not sanitized.
pub fn local_listener_meta_addr(&self) -> MetaAddr {
MetaAddr::new_local_listener_change(&self.local_listener)
.into_new_meta_addr()
.expect("unexpected invalid new local listener addr")
}
/// Get the contents of `self` in random order with sanitized timestamps.
pub fn sanitized(&self, now: chrono::DateTime<Utc>) -> Vec<MetaAddr> {
use rand::seq::SliceRandom;
let _guard = self.span.enter();
let mut peers = self.by_addr.clone();
// Unconditionally add our local listener address to the advertised peers,
// to replace any self-connection failures. The address book and change
// constructors make sure that the SocketAddr is canonical.
let local_listener = self.local_listener_meta_addr();
peers.insert(local_listener.addr, local_listener);
// Then sanitize and shuffle
let mut peers = peers
.descending_values()
.filter_map(MetaAddr::sanitize)
// Security: remove peers that:
// - last responded more than three hours ago, or
// - haven't responded yet but were reported last seen more than three hours ago
//
// This prevents Zebra from gossiping nodes that are likely unreachable. Gossiping such
// nodes impacts the network health, because connection attempts end up being wasted on
// peers that are less likely to respond.
.filter(|addr| addr.is_active_for_gossip(now))
.collect::<Vec<_>>();
peers.shuffle(&mut rand::thread_rng());
peers
}
/// Look up `addr` in the address book, and return its [`MetaAddr`].
///
/// Converts `addr` to a canonical address before looking it up.
pub fn get(&mut self, addr: &SocketAddr) -> Option<MetaAddr> {
let addr = canonical_socket_addr(*addr);
// Unfortunately, `OrderedMap` doesn't implement `get`.
let meta_addr = self.by_addr.remove(&addr);
if let Some(meta_addr) = meta_addr {
self.by_addr.insert(addr, meta_addr);
}
meta_addr
}
/// Apply `change` to the address book, returning the updated `MetaAddr`,
/// if the change was valid.
///
/// # Correctness
///
/// All changes should go through `update`, so that the address book
/// only contains valid outbound addresses.
///
/// Change addresses must be canonical `SocketAddr`s. This makes sure that
/// each address book entry has a unique IP address.
///
/// # Security
///
/// This function must apply every attempted, responded, and failed change
/// to the address book. This prevents rapid reconnections to the same peer.
///
/// As an exception, this function can ignore all changes for specific
/// [`SocketAddr`]s. Ignored addresses will never be used to connect to
/// peers.
pub fn update(&mut self, change: MetaAddrChange) -> Option<MetaAddr> {
let previous = self.get(&change.addr());
let _guard = self.span.enter();
let instant_now = Instant::now();
let chrono_now = Utc::now();
let updated = change.apply_to_meta_addr(previous);
trace!(
?change,
?updated,
?previous,
total_peers = self.by_addr.len(),
recent_peers = self.recently_live_peers(chrono_now).count(),
);
if let Some(updated) = updated {
// Ignore invalid outbound addresses.
// (Inbound connections can be monitored via Zebra's metrics.)
if !updated.address_is_valid_for_outbound() {
return None;
}
// Ignore invalid outbound services and other info,
// but only if the peer has never been attempted.
//
// Otherwise, if we got the info directly from the peer,
// store it in the address book, so we know not to reconnect.
//
// TODO: delete peers with invalid info when they get too old (#1873)
if !updated.last_known_info_is_valid_for_outbound()
&& updated.last_connection_state.is_never_attempted()
{
return None;
}
self.by_addr.insert(updated.addr, updated);
// Security: Limit the number of peers in the address book.
//
// We only delete outdated peers when we have too many peers.
// If we deleted them as soon as they became too old,
// then other peers could re-insert them into the address book.
// And we would start connecting to those outdated peers again,
// ignoring the age limit in [`MetaAddr::is_probably_reachable`].
while self.by_addr.len() > self.addr_limit {
let surplus_peer = self
.peers()
.next_back()
.expect("just checked there is at least one peer");
self.by_addr.remove(&surplus_peer.addr);
}
assert!(self.len() <= self.addr_limit);
std::mem::drop(_guard);
self.update_metrics(instant_now, chrono_now);
}
updated
}
/// Removes the entry with `addr`, returning it if it exists
///
/// # Note
///
/// All address removals should go through `take`, so that the address
/// book metrics are accurate.
#[allow(dead_code)]
fn | (&mut self, removed_addr: SocketAddr) -> Option<MetaAddr> {
let _guard = self.span.enter();
let instant_now = Instant::now();
let chrono_now = Utc::now();
trace!(
?removed_addr,
total_peers = self.by_addr.len(),
recent_peers = self.recently_live_peers(chrono_now).count(),
);
if let Some(entry) = self.by_addr.remove(&removed_addr) {
std::mem::drop(_guard);
self.update_metrics(instant_now, chrono_now);
Some(entry)
} else {
None
}
}
/// Returns true if the given [`SocketAddr`] is pending a reconnection
/// attempt.
pub fn pending_reconnection_addr(&mut self, addr: &SocketAddr) -> bool {
let meta_addr = self.get(addr);
let _guard = self.span.enter();
match meta_addr {
None => false,
Some(peer) => peer.last_connection_state == PeerAddrState::AttemptPending,
}
}
/// Return an iterator over all peers.
///
/// Returns peers in reconnection attempt order, including recently connected peers.
pub fn peers(&'_ self) -> impl Iterator<Item = MetaAddr> + DoubleEndedIterator + '_ {
let _guard = self.span.enter();
self.by_addr.descending_values().cloned()
}
/// Return an iterator over peers that are due for a reconnection attempt,
/// in reconnection attempt order.
pub fn reconnection_peers(
&'_ self,
instant_now: Instant,
chrono_now: chrono::DateTime<Utc>,
) -> impl Iterator<Item = MetaAddr> + DoubleEndedIterator + '_ {
let _guard = self.span.enter();
// Skip live peers, and peers pending a reconnect attempt.
// The peers are already stored in sorted order.
self.by_addr
.descending_values()
.filter(move |peer| peer.is_ready_for_connection_attempt(instant_now, chrono_now))
.cloned()
}
/// Return an iterator over all the peers in `state`,
/// in reconnection attempt order, including recently connected peers.
pub fn state_peers(
&'_ self,
state: PeerAddrState,
) -> impl Iterator<Item = MetaAddr> + DoubleEndedIterator + '_ {
let _guard = self.span.enter();
self.by_addr
.descending_values()
.filter(move |peer| peer.last_connection_state == state)
.cloned()
}
/// Return an iterator over peers that might be connected,
/// in reconnection attempt order.
pub fn maybe_connected_peers(
&'_ self,
instant_now: Instant,
chrono_now: chrono::DateTime<Utc>,
) -> impl Iterator<Item = MetaAddr> + DoubleEndedIterator + '_ {
let _guard = self.span.enter();
self.by_addr
.descending_values()
.filter(move |peer| !peer.is_ready_for_connection_attempt(instant_now, chrono_now))
.cloned()
}
/// Return an iterator over peers we've seen recently,
/// in reconnection attempt order.
pub fn recently_live_peers(
&'_ self,
now: chrono::DateTime<Utc>,
) -> impl Iterator<Item = MetaAddr> + DoubleEndedIterator + '_ {
let _guard = self.span.enter();
self.by_addr
.descending_values()
.filter(move |peer| peer.was_recently_live(now))
.cloned()
}
/// Returns the number of entries in this address book.
pub fn len(&self) -> usize {
self.by_addr.len()
}
/// Returns metrics for the addresses in this address book.
/// Only for use in tests.
///
/// # Correctness
///
/// Use [`AddressBook::address_metrics_watcher().borrow()`] in production code,
/// to avoid deadlocks.
#[cfg(test)]
pub fn address_metrics(&self, now: chrono::DateTime<Utc>) -> AddressMetrics {
self.address_metrics_internal(now)
}
/// Returns metrics for the addresses in this address book.
///
/// # Correctness
///
/// External callers should use [`AddressBook::address_metrics_watcher().borrow()`]
/// in production code, to avoid deadlocks.
/// (Using the watch channel receiver does not lock the address book mutex.)
fn address_metrics_internal(&self, now: chrono::DateTime<Utc>) -> AddressMetrics {
let responded = self.state_peers(PeerAddrState::Responded).count();
let never_attempted_gossiped = self
.state_peers(PeerAddrState::NeverAttemptedGossiped)
.count();
let never_attempted_alternate = self
.state_peers(PeerAddrState::NeverAttemptedAlternate)
.count();
let failed = self.state_peers(PeerAddrState::Failed).count();
let attempt_pending = self.state_peers(PeerAddrState::AttemptPending).count();
let recently_live = self.recently_live_peers(now).count();
let recently_stopped_responding = responded
.checked_sub(recently_live)
.expect("all recently live peers must have responded");
AddressMetrics {
responded,
never_attempted_gossiped,
never_attempted_alternate,
failed,
attempt_pending,
recently_live,
recently_stopped_responding,
}
}
/// Update the metrics for this address book.
fn update_metrics(&mut self, instant_now: Instant, chrono_now: chrono::DateTime<Utc>) {
let _guard = self.span.enter();
let m = self.address_metrics_internal(chrono_now);
// Ignore errors: we don't care if any receivers are listening.
let _ = self.address_metrics_tx.send(m);
// TODO: rename to address_book.[state_name]
metrics::gauge!("candidate_set.responded", m.responded as f64);
metrics::gauge!("candidate_set.gossiped", m.never_attempted_gossiped as f64);
metrics::gauge!(
"candidate_set.alternate",
m.never_attempted_alternate as f64
);
metrics::gauge!("candidate_set.failed", m.failed as f64);
metrics::gauge!("candidate_set.pending", m.attempt_pending as f64);
// TODO: rename to address_book.responded.recently_live
metrics::gauge!("candidate_set.recently_live", m.recently_live as f64);
// TODO: rename to address_book.responded.stopped_responding
metrics::gauge!(
"candidate_set.disconnected",
m.recently_stopped_responding as f64
);
std::mem::drop(_guard);
self.log_metrics(&m, instant_now);
}
/// Log metrics for this address book
fn log_metrics(&mut self, m: &AddressMetrics, now: Instant) {
let _guard = self.span.enter();
trace!(
address_metrics = ?m,
);
if m.responded > 0 {
return;
}
// These logs are designed to be human-readable in a terminal, at the
// default Zebra log level. If you need to know address states for
// every request, use the trace-level logs, or the metrics exporter.
if let Some(last_address_log) = self.last_address_log {
// Avoid duplicate address logs
if now.saturating_duration_since(last_address_log).as_secs() < 60 {
return;
}
} else {
// Suppress initial logs until the peer set has started up.
// There can be multiple address changes before the first peer has
// responded.
self.last_address_log = Some(now);
return;
}
self.last_address_log = Some(now);
// if all peers have failed
if m.responded
+ m.attempt_pending
+ m.never_attempted_gossiped
+ m.never_attempted_alternate
== 0
{
warn!(
address_metrics = ?m,
"all peer addresses have failed. Hint: check your network connection"
);
} else {
info!(
address_metrics = ?m,
"no active peer connections: trying gossiped addresses"
);
}
}
}
impl Extend<MetaAddrChange> for AddressBook {
fn extend<T>(&mut self, iter: T)
where
T: IntoIterator<Item = MetaAddrChange>,
{
for change in iter.into_iter() {
self.update(change);
}
}
}
impl Clone for AddressBook {
/// Clone the addresses, address limit, local listener address, and span.
///
/// Cloned address books have a separate metrics struct watch channel, and an empty last address log.
///
/// All address books update the same prometheus metrics.
fn clone(&self) -> AddressBook {
// The existing metrics might be outdated, but we avoid calling `update_metrics`,
// so we don't overwrite the prometheus metrics from the main address book.
let (address_metrics_tx, _address_metrics_rx) =
watch::channel(*self.address_metrics_tx.borrow());
AddressBook {
by_addr: self.by_addr.clone(),
addr_limit: self.addr_limit,
local_listener: self.local_listener,
span: self.span.clone(),
address_metrics_tx,
last_address_log: None,
}
}
}
| take |
DevPostHttpInterceptor.ts | import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
HttpResponse
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { tap, catchError } from "rxjs/operators";
import { Post } from "./posts.service";
| { postname: "mock1", date: new Date(Date.now()), userId: 1234, interest: 'testing' },
{ postname: "mock2", date: new Date(new Date(Date.now()).setMonth(7)), userId: 5678, interest: 'testing' }
];
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.method != "GET" && req.url.indexOf("Posts") === -1) {
return next.handle(req); // do nothing, not a Get Posts call
} else {
return next.handle(req).pipe(
tap(response => {
if (response instanceof HttpResponse) {
const mockResponse = response.clone({
body: JSON.stringify(this.postList),
status: 200,
statusText: "mocked"
});
return mockResponse;
}
else{
return next.handle(req);
}
})
);
}
}
} | @Injectable()
export class DevPostsHttpInterceptor implements HttpInterceptor {
postList: Post[] = [ |
clksel.rs | #[doc = "Register `CLKSEL` reader"]
pub struct R(crate::R<CLKSEL_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CLKSEL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CLKSEL_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CLKSEL_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `CLKSEL` writer"]
pub struct W(crate::W<CLKSEL_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<CLKSEL_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<CLKSEL_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<CLKSEL_SPEC>) -> Self {
W(writer)
}
}
#[doc = "select clock source register of RNG shift register\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CLKSEL_A {
#[doc = "0: refer to clock generator block"]
RNG = 0,
#[doc = "1: `1`"]
PCLK = 1,
}
impl From<CLKSEL_A> for bool {
#[inline(always)]
fn from(variant: CLKSEL_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `CLKSEL` reader - select clock source register of RNG shift register"]
pub struct CLKSEL_R(crate::FieldReader<bool, CLKSEL_A>);
impl CLKSEL_R {
pub(crate) fn new(bits: bool) -> Self {
CLKSEL_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CLKSEL_A {
match self.bits {
false => CLKSEL_A::RNG,
true => CLKSEL_A::PCLK,
}
}
#[doc = "Checks if the value of the field is `RNG`"]
#[inline(always)]
pub fn is_rng(&self) -> bool {
**self == CLKSEL_A::RNG
}
#[doc = "Checks if the value of the field is `PCLK`"]
#[inline(always)]
pub fn is_pclk(&self) -> bool {
**self == CLKSEL_A::PCLK
}
}
impl core::ops::Deref for CLKSEL_R {
type Target = crate::FieldReader<bool, CLKSEL_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CLKSEL` writer - select clock source register of RNG shift register"]
pub struct CLKSEL_W<'a> {
w: &'a mut W,
}
impl<'a> CLKSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CLKSEL_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "refer to clock generator block"]
#[inline(always)]
pub fn rng(self) -> &'a mut W {
self.variant(CLKSEL_A::RNG)
}
#[doc = "`1`"]
#[inline(always)]
pub fn pclk(self) -> &'a mut W {
self.variant(CLKSEL_A::PCLK)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - select clock source register of RNG shift register"]
#[inline(always)]
pub fn | (&self) -> CLKSEL_R {
CLKSEL_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - select clock source register of RNG shift register"]
#[inline(always)]
pub fn clksel(&mut self) -> CLKSEL_W {
CLKSEL_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "RNG Clock source select register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [clksel](index.html) module"]
pub struct CLKSEL_SPEC;
impl crate::RegisterSpec for CLKSEL_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [clksel::R](R) reader structure"]
impl crate::Readable for CLKSEL_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [clksel::W](W) writer structure"]
impl crate::Writable for CLKSEL_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets CLKSEL to value 0"]
impl crate::Resettable for CLKSEL_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| clksel |
config.go | // Copyright (c) 2013-2017 The btcsuite developers
// Copyright (c) 2017 BitGo
// Copyright (c) 2019 Tranquility Node Ltd
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/pyx-partners/dmgd/chaincfg"
"github.com/pyx-partners/dmgd/chaincfg/chainhash"
"github.com/pyx-partners/dmgd/connmgr"
"github.com/pyx-partners/dmgd/database"
_ "github.com/pyx-partners/dmgd/database/ffldb"
"github.com/pyx-partners/dmgd/mempool"
"github.com/pyx-partners/dmgd/provautil"
"github.com/pyx-partners/dmgd/wire"
flags "github.com/btcsuite/go-flags"
"github.com/btcsuite/go-socks/socks"
)
const (
defaultConfigFilename = "dmgd.conf"
defaultDataDirname = "data"
defaultLogLevel = "info"
defaultLogDirname = "logs"
defaultLogFilename = "dmgd.log"
defaultMaxPeers = 125
defaultBanDuration = time.Hour * 24
defaultBanThreshold = 100
defaultConnectTimeout = time.Second * 30
defaultMaxRPCClients = 10
defaultMaxRPCWebsockets = 25
defaultMaxRPCConcurrentReqs = 20
defaultDbType = "ffldb"
defaultFreeTxRelayLimit = 2500.0
defaultBlockMinSize = 500000
defaultBlockMaxSize = 750000
blockMaxSizeMin = 1000
blockMaxSizeMax = wire.MaxBlockPayload - 1000
defaultGenerate = false
defaultMaxOrphanTransactions = 100
defaultMaxOrphanTxSize = mempool.MaxStandardTxSize
defaultSigCacheMaxSize = 100000
sampleConfigFilename = "sample-dmgd.conf"
defaultTxIndex = false
defaultAddrIndex = false
defaultUseOnlySyncPeerInv = false
)
var (
defaultHomeDir = provautil.AppDataDir("dmgd", false)
defaultConfigFile = filepath.Join(defaultHomeDir, defaultConfigFilename)
defaultDataDir = filepath.Join(defaultHomeDir, defaultDataDirname)
knownDbTypes = database.SupportedDrivers()
defaultRPCKeyFile = filepath.Join(defaultHomeDir, "rpc.key")
defaultRPCCertFile = filepath.Join(defaultHomeDir, "rpc.cert")
defaultLogDir = filepath.Join(defaultHomeDir, defaultLogDirname)
)
// runServiceCommand is only set to a real function on Windows. It is used
// to parse and execute service commands specified via the -s flag.
var runServiceCommand func(string) error
// minUint32 is a helper function to return the minimum of two uint32s.
// This avoids a math import and the need to cast to floats.
func minUint32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
// config defines the configuration options for btcd.
//
// See loadConfig for details on the configuration load process.
type config struct {
ShowVersion bool `short:"V" long:"version" description:"Display version information and exit"`
ConfigFile string `short:"C" long:"configfile" description:"Path to configuration file"`
DataDir string `short:"b" long:"datadir" description:"Directory to store data"`
LogDir string `long:"logdir" description:"Directory to log output."`
AddPeers []string `short:"a" long:"addpeer" description:"Add a peer to connect with at startup"`
ConnectPeers []string `long:"connect" description:"Connect only to the specified peers at startup"`
DisableListen bool `long:"nolisten" description:"Disable listening for incoming connections -- NOTE: Listening is automatically disabled if the --connect or --proxy options are used without also specifying listen interfaces via --listen"`
Listeners []string `long:"listen" description:"Add an interface/port to listen for connections (default all interfaces port: 6464, testnet: 16464)"`
MaxPeers int `long:"maxpeers" description:"Max number of inbound and outbound peers"`
DisableBanning bool `long:"nobanning" description:"Disable banning of misbehaving peers"`
BanDuration time.Duration `long:"banduration" description:"How long to ban misbehaving peers. Valid time units are {s, m, h}. Minimum 1 second"`
BanThreshold uint32 `long:"banthreshold" description:"Maximum allowed ban score before disconnecting and banning misbehaving peers."`
RPCUser string `short:"u" long:"rpcuser" description:"Username for RPC connections"`
RPCPass string `short:"P" long:"rpcpass" default-mask:"-" description:"Password for RPC connections"`
RPCHash string `long:"rpchash" description:"SHA2 of auth credentials (may be specified instead of user/pass)"`
RPCLimitUser string `long:"rpclimituser" description:"Username for limited RPC connections"`
RPCLimitPass string `long:"rpclimitpass" default-mask:"-" description:"Password for limited RPC connections"`
RPCLimitHash string `long:"rpclimithash" description:"SHA2 of auth credentials for limited RPC user (may be specified instead of user/pass)"`
RPCListeners []string `long:"rpclisten" description:"Add an interface/port to listen for RPC connections (default port: 8334, testnet: 18334)"`
RPCCert string `long:"rpccert" description:"File containing the certificate file"`
RPCKey string `long:"rpckey" description:"File containing the certificate key"`
RPCMaxClients int `long:"rpcmaxclients" description:"Max number of RPC clients for standard connections"`
RPCMaxWebsockets int `long:"rpcmaxwebsockets" description:"Max number of RPC websocket connections"`
RPCMaxConcurrentReqs int `long:"rpcmaxconcurrentreqs" description:"Max number of concurrent RPC requests that may be processed concurrently"`
RPCQuirks bool `long:"rpcquirks" description:"Mirror some JSON-RPC quirks of Bitcoin Core -- NOTE: Discouraged unless interoperability issues need to be worked around"`
DisableRPC bool `long:"norpc" description:"Disable built-in RPC server -- NOTE: The RPC server is disabled by default if no rpcuser/rpcpass or rpclimituser/rpclimitpass is specified"`
DisableTLS bool `long:"notls" description:"Disable TLS for the RPC server -- NOTE: This is only allowed if the RPC server is bound to localhost"`
DisableDNSSeed bool `long:"nodnsseed" description:"Disable DNS seeding for peers"`
ExternalIPs []string `long:"externalip" description:"Add an ip to the list of local addresses we claim to listen on to peers"`
Proxy string `long:"proxy" description:"Connect via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
ProxyUser string `long:"proxyuser" description:"Username for proxy server"`
ProxyPass string `long:"proxypass" default-mask:"-" description:"Password for proxy server"`
OnionProxy string `long:"onion" description:"Connect to tor hidden services via SOCKS5 proxy (eg. 127.0.0.1:9050)"`
OnionProxyUser string `long:"onionuser" description:"Username for onion proxy server"`
OnionProxyPass string `long:"onionpass" default-mask:"-" description:"Password for onion proxy server"`
NoOnion bool `long:"noonion" description:"Disable connecting to tor hidden services"`
TorIsolation bool `long:"torisolation" description:"Enable Tor stream isolation by randomizing user credentials for each connection."`
TestNet bool `long:"testnet" description:"Use the test network"`
RegressionTest bool `long:"regtest" description:"Use the regression test network"`
SimNet bool `long:"simnet" description:"Use the simulation test network"`
AddCheckpoints []string `long:"addcheckpoint" description:"Add a custom checkpoint. Format: '<height>:<hash>'"`
DbType string `long:"dbtype" description:"Database backend to use for the Block Chain"`
Profile string `long:"profile" description:"Enable HTTP profiling on given port -- NOTE port must be between 1024 and 65536"`
CPUProfile string `long:"cpuprofile" description:"Write CPU profile to the specified file"`
DebugLevel string `short:"d" long:"debuglevel" description:"Logging level for all subsystems {trace, debug, info, warn, error, critical} -- You may also specify <subsystem>=<level>,<subsystem2>=<level>,... to set the log level for individual subsystems -- Use show to list available subsystems"`
Upnp bool `long:"upnp" description:"Use UPnP to map our listening port outside of NAT"`
UseOnlySyncPeerInv bool `long:"useonlysyncpeerinv" description:"Use only sync peer inv messages to reduce orphan fetching"`
MinRelayTxFee float64 `long:"minrelaytxfee" description:"The minimum transaction fee in DMG/kB to be considered a non-zero fee."`
FreeTxRelayLimit float64 `long:"limitfreerelay" description:"Limit relay of transactions with no transaction fee to the given amount in thousands of bytes per minute"`
RelayPriority bool `long:"relaypriority" description:"Require free or low-fee transactions to have high priority for relaying"`
MaxOrphanTxs int `long:"maxorphantx" description:"Max number of orphan transactions to keep in memory"`
Generate bool `long:"generate" description:"Generate (mine) blocks using the CPU"`
MiningAddrs []string `long:"miningaddr" description:"Add the specified payment address to the list of addresses to use for generated blocks -- At least one address is required if the generate option is set"`
BlockMinSize uint32 `long:"blockminsize" description:"Mininum block size in bytes to be used when creating a block"`
BlockMaxSize uint32 `long:"blockmaxsize" description:"Maximum block size in bytes to be used when creating a block"`
BlockPrioritySize uint32 `long:"blockprioritysize" description:"Size in bytes for high-priority/low-fee transactions when creating a block"`
NoPeerBloomFilters bool `long:"nopeerbloomfilters" description:"Disable bloom filtering support"`
SigCacheMaxSize uint `long:"sigcachemaxsize" description:"The maximum number of entries in the signature verification cache"`
BlocksOnly bool `long:"blocksonly" description:"Do not accept transactions from remote peers."`
TxIndex bool `long:"txindex" description:"Maintain a full hash-based transaction index which makes all transactions available via the getrawtransaction RPC"`
DropTxIndex bool `long:"droptxindex" description:"Deletes the hash-based transaction index from the database on start up and then exits."`
AddrIndex bool `long:"addrindex" description:"Maintain a full address-based transaction index which makes the searchrawtransactions RPC available"`
DropAddrIndex bool `long:"dropaddrindex" description:"Deletes the address-based transaction index from the database on start up and then exits."`
RelayNonStd bool `long:"relaynonstd" description:"Relay non-standard transactions regardless of the default settings for the active network."`
RejectNonStd bool `long:"rejectnonstd" description:"Reject non-standard transactions regardless of the default settings for the active network."`
EnableExternalRPC bool `long:"enableexternalrpc" description:"Allow external listening of the RPC API. This also requires that TLS is not disabled."`
lookup func(string) ([]net.IP, error)
oniondial func(string, string, time.Duration) (net.Conn, error)
dial func(string, string, time.Duration) (net.Conn, error)
addCheckpoints []chaincfg.Checkpoint
miningAddrs []provautil.Address
minRelayTxFee provautil.Amount
}
// serviceOptions defines the configuration options for the daemon as a service on
// Windows.
type serviceOptions struct {
ServiceCommand string `short:"s" long:"service" description:"Service command {install, remove, start, stop}"`
}
// cleanAndExpandPath expands environment variables and leading ~ in the
// passed path, cleans the result, and returns it.
func cleanAndExpandPath(path string) string {
// Expand initial ~ to OS specific home directory.
if strings.HasPrefix(path, "~") {
homeDir := filepath.Dir(defaultHomeDir)
path = strings.Replace(path, "~", homeDir, 1)
}
// NOTE: The os.ExpandEnv doesn't work with Windows-style %VARIABLE%,
// but they variables can still be expanded via POSIX-style $VARIABLE.
return filepath.Clean(os.ExpandEnv(path))
}
// validLogLevel returns whether or not logLevel is a valid debug log level.
func validLogLevel(logLevel string) bool {
switch logLevel {
case "trace":
fallthrough
case "debug":
fallthrough
case "info":
fallthrough
case "warn":
fallthrough
case "error":
fallthrough
case "critical":
return true
}
return false
}
// supportedSubsystems returns a sorted slice of the supported subsystems for
// logging purposes.
func supportedSubsystems() []string {
// Convert the subsystemLoggers map keys to a slice.
subsystems := make([]string, 0, len(subsystemLoggers))
for subsysID := range subsystemLoggers {
subsystems = append(subsystems, subsysID)
}
// Sort the subsystems for stable display.
sort.Strings(subsystems)
return subsystems
}
// parseAndSetDebugLevels attempts to parse the specified debug level and set
// the levels accordingly. An appropriate error is returned if anything is
// invalid.
func parseAndSetDebugLevels(debugLevel string) error {
// When the specified string doesn't have any delimters, treat it as
// the log level for all subsystems.
if !strings.Contains(debugLevel, ",") && !strings.Contains(debugLevel, "=") {
// Validate debug log level.
if !validLogLevel(debugLevel) {
str := "The specified debug level [%v] is invalid"
return fmt.Errorf(str, debugLevel)
}
// Change the logging level for all subsystems.
setLogLevels(debugLevel)
return nil
}
// Split the specified string into subsystem/level pairs while detecting
// issues and update the log levels accordingly.
for _, logLevelPair := range strings.Split(debugLevel, ",") {
if !strings.Contains(logLevelPair, "=") {
str := "The specified debug level contains an invalid " +
"subsystem/level pair [%v]"
return fmt.Errorf(str, logLevelPair)
}
// Extract the specified subsystem and log level.
fields := strings.Split(logLevelPair, "=")
subsysID, logLevel := fields[0], fields[1]
// Validate subsystem.
if _, exists := subsystemLoggers[subsysID]; !exists {
str := "The specified subsystem [%v] is invalid -- " +
"supported subsytems %v"
return fmt.Errorf(str, subsysID, supportedSubsystems())
}
// Validate log level.
if !validLogLevel(logLevel) {
str := "The specified debug level [%v] is invalid"
return fmt.Errorf(str, logLevel)
}
setLogLevel(subsysID, logLevel)
}
return nil
}
// validDbType returns whether or not dbType is a supported database type.
func validDbType(dbType string) bool {
for _, knownType := range knownDbTypes {
if dbType == knownType {
return true
}
}
return false
}
// removeDuplicateAddresses returns a new slice with all duplicate entries in
// addrs removed.
func removeDuplicateAddresses(addrs []string) []string {
result := make([]string, 0, len(addrs))
seen := map[string]struct{}{}
for _, val := range addrs {
if _, ok := seen[val]; !ok {
result = append(result, val)
seen[val] = struct{}{}
}
}
return result
}
// normalizeAddress returns addr with the passed default port appended if
// there is not already a port specified.
func normalizeAddress(addr, defaultPort string) string {
_, _, err := net.SplitHostPort(addr)
if err != nil {
return net.JoinHostPort(addr, defaultPort)
}
return addr
}
// normalizeAddresses returns a new slice with all the passed peer addresses
// normalized with the given default port, and all duplicates removed.
func normalizeAddresses(addrs []string, defaultPort string) []string {
for i, addr := range addrs {
addrs[i] = normalizeAddress(addr, defaultPort)
}
return removeDuplicateAddresses(addrs)
}
// newCheckpointFromStr parses checkpoints in the '<height>:<hash>' format.
func newCheckpointFromStr(checkpoint string) (chaincfg.Checkpoint, error) {
parts := strings.Split(checkpoint, ":")
if len(parts) != 2 {
return chaincfg.Checkpoint{}, fmt.Errorf("unable to parse "+
"checkpoint %q -- use the syntax <height>:<hash>",
checkpoint)
}
height, err := strconv.ParseInt(parts[0], 10, 32)
if err != nil {
return chaincfg.Checkpoint{}, fmt.Errorf("unable to parse "+
"checkpoint %q due to malformed height", checkpoint)
}
if len(parts[1]) == 0 {
return chaincfg.Checkpoint{}, fmt.Errorf("unable to parse "+
"checkpoint %q due to missing hash", checkpoint)
}
hash, err := chainhash.NewHashFromStr(parts[1])
if err != nil {
return chaincfg.Checkpoint{}, fmt.Errorf("unable to parse "+
"checkpoint %q due to malformed hash", checkpoint)
}
return chaincfg.Checkpoint{
Height: uint32(height),
Hash: hash,
}, nil
}
// parseCheckpoints checks the checkpoint strings for valid syntax
// ('<height>:<hash>') and parses them to chaincfg.Checkpoint instances.
func | (checkpointStrings []string) ([]chaincfg.Checkpoint, error) {
if len(checkpointStrings) == 0 {
return nil, nil
}
checkpoints := make([]chaincfg.Checkpoint, len(checkpointStrings))
for i, cpString := range checkpointStrings {
checkpoint, err := newCheckpointFromStr(cpString)
if err != nil {
return nil, err
}
checkpoints[i] = checkpoint
}
return checkpoints, nil
}
// filesExists reports whether the named file or directory exists.
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// newConfigParser returns a new command line flags parser.
func newConfigParser(cfg *config, so *serviceOptions, options flags.Options) *flags.Parser {
parser := flags.NewParser(cfg, options)
if runtime.GOOS == "windows" {
parser.AddGroup("Service Options", "Service Options", so)
}
return parser
}
// loadConfig initializes and parses the config using a config file and command
// line options.
//
// The configuration proceeds as follows:
// 1) Start with a default config with sane settings
// 2) Pre-parse the command line to check for an alternative config file
// 3) Load configuration file overwriting defaults with any specified options
// 4) Parse CLI options and overwrite/add any specified options
//
// The above results in btcd functioning properly without any config settings
// while still allowing the user to override settings with config files and
// command line options. Command line options always take precedence.
func loadConfig() (*config, []string, error) {
// Default config.
cfg := config{
ConfigFile: defaultConfigFile,
DebugLevel: defaultLogLevel,
MaxPeers: defaultMaxPeers,
BanDuration: defaultBanDuration,
BanThreshold: defaultBanThreshold,
RPCMaxClients: defaultMaxRPCClients,
RPCMaxWebsockets: defaultMaxRPCWebsockets,
RPCMaxConcurrentReqs: defaultMaxRPCConcurrentReqs,
DataDir: defaultDataDir,
LogDir: defaultLogDir,
DbType: defaultDbType,
RPCKey: defaultRPCKeyFile,
RPCCert: defaultRPCCertFile,
MinRelayTxFee: mempool.DefaultMinRelayTxFee.ToDMG(),
FreeTxRelayLimit: defaultFreeTxRelayLimit,
BlockMinSize: defaultBlockMinSize,
BlockMaxSize: defaultBlockMaxSize,
BlockPrioritySize: mempool.DefaultBlockPrioritySize,
MaxOrphanTxs: defaultMaxOrphanTransactions,
SigCacheMaxSize: defaultSigCacheMaxSize,
Generate: defaultGenerate,
TxIndex: defaultTxIndex,
AddrIndex: defaultAddrIndex,
UseOnlySyncPeerInv: defaultUseOnlySyncPeerInv,
}
// Service options which are only added on Windows.
serviceOpts := serviceOptions{}
// Pre-parse the command line options to see if an alternative config
// file or the version flag was specified. Any errors aside from the
// help message error can be ignored here since they will be caught by
// the final parse below.
preCfg := cfg
preParser := newConfigParser(&preCfg, &serviceOpts, flags.HelpFlag)
_, err := preParser.Parse()
if err != nil {
if e, ok := err.(*flags.Error); ok && e.Type == flags.ErrHelp {
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
}
// Show the version and exit if the version flag was specified.
appName := filepath.Base(os.Args[0])
appName = strings.TrimSuffix(appName, filepath.Ext(appName))
usageMessage := fmt.Sprintf("Use %s -h to show usage", appName)
if preCfg.ShowVersion {
fmt.Println(appName, "version", version())
os.Exit(0)
}
// Perform service command and exit if specified. Invalid service
// commands show an appropriate error. Only runs on Windows since
// the runServiceCommand function will be nil when not on Windows.
if serviceOpts.ServiceCommand != "" && runServiceCommand != nil {
err := runServiceCommand(serviceOpts.ServiceCommand)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
os.Exit(0)
}
// Load additional config from file.
var configFileError error
parser := newConfigParser(&cfg, &serviceOpts, flags.Default)
if !(preCfg.RegressionTest || preCfg.SimNet) || preCfg.ConfigFile !=
defaultConfigFile {
if _, err := os.Stat(preCfg.ConfigFile); os.IsNotExist(err) {
err := createDefaultConfigFile(preCfg.ConfigFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating a "+
"default config file: %v\n", err)
}
}
err := flags.NewIniParser(parser).ParseFile(preCfg.ConfigFile)
if err != nil {
if _, ok := err.(*os.PathError); !ok {
fmt.Fprintf(os.Stderr, "Error parsing config "+
"file: %v\n", err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
configFileError = err
}
}
// Don't add peers from the config file when in regression test mode.
if preCfg.RegressionTest && len(cfg.AddPeers) > 0 {
cfg.AddPeers = nil
}
// Parse command line options again to ensure they take precedence.
remainingArgs, err := parser.Parse()
if err != nil {
if e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {
fmt.Fprintln(os.Stderr, usageMessage)
}
return nil, nil, err
}
// Create the home directory if it doesn't already exist.
funcName := "loadConfig"
err = os.MkdirAll(defaultHomeDir, 0700)
if err != nil {
// Show a nicer error message if it's because a symlink is
// linked to a directory that does not exist (probably because
// it's not mounted).
if e, ok := err.(*os.PathError); ok && os.IsExist(err) {
if link, lerr := os.Readlink(e.Path); lerr == nil {
str := "is symlink %s -> %s mounted?"
err = fmt.Errorf(str, e.Path, link)
}
}
str := "%s: Failed to create home directory: %v"
err := fmt.Errorf(str, funcName, err)
fmt.Fprintln(os.Stderr, err)
return nil, nil, err
}
// Multiple networks can't be selected simultaneously.
numNets := 0
// Count number of network flags passed; assign active network params
// while we're at it
if cfg.TestNet {
numNets++
activeNetParams = &testNetParams
}
if cfg.RegressionTest {
numNets++
activeNetParams = ®ressionNetParams
}
if cfg.SimNet {
numNets++
// Also disable dns seeding on the simulation test network.
activeNetParams = &simNetParams
cfg.DisableDNSSeed = true
}
if numNets > 1 {
str := "%s: The testnet, regtest, and simnet params can't be " +
"used together -- choose one of the three"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Set the default policy for relaying non-standard transactions
// according to the default of the active network. The set
// configuration value takes precedence over the default value for the
// selected network.
relayNonStd := activeNetParams.RelayNonStdTxs
switch {
case cfg.RelayNonStd && cfg.RejectNonStd:
str := "%s: rejectnonstd and relaynonstd cannot be used " +
"together -- choose only one"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
case cfg.RejectNonStd:
relayNonStd = false
case cfg.RelayNonStd:
relayNonStd = true
}
cfg.RelayNonStd = relayNonStd
// Append the network type to the data directory so it is "namespaced"
// per network. In addition to the block database, there are other
// pieces of data that are saved to disk such as address manager state.
// All data is specific to a network, so namespacing the data directory
// means each individual piece of serialized data does not have to
// worry about changing names per network and such.
cfg.DataDir = cleanAndExpandPath(cfg.DataDir)
cfg.DataDir = filepath.Join(cfg.DataDir, activeNetParams.Name)
// Append the network type to the log directory so it is "namespaced"
// per network in the same fashion as the data directory.
cfg.LogDir = cleanAndExpandPath(cfg.LogDir)
cfg.LogDir = filepath.Join(cfg.LogDir, activeNetParams.Name)
// Special show command to list supported subsystems and exit.
if cfg.DebugLevel == "show" {
fmt.Println("Supported subsystems", supportedSubsystems())
os.Exit(0)
}
// Initialize logging at the default logging level.
initSeelogLogger(filepath.Join(cfg.LogDir, defaultLogFilename))
setLogLevels(defaultLogLevel)
// Parse, validate, and set debug log level(s).
if err := parseAndSetDebugLevels(cfg.DebugLevel); err != nil {
err := fmt.Errorf("%s: %v", funcName, err.Error())
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Validate database type.
if !validDbType(cfg.DbType) {
str := "%s: The specified database type [%v] is invalid -- " +
"supported types %v"
err := fmt.Errorf(str, funcName, cfg.DbType, knownDbTypes)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Validate profile port number
if cfg.Profile != "" {
profilePort, err := strconv.Atoi(cfg.Profile)
if err != nil || profilePort < 1024 || profilePort > 65535 {
str := "%s: The profile port must be between 1024 and 65535"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
}
// Don't allow ban durations that are too short.
if cfg.BanDuration < time.Second {
str := "%s: The banduration option may not be less than 1s -- parsed [%v]"
err := fmt.Errorf(str, funcName, cfg.BanDuration)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --addPeer and --connect do not mix.
if len(cfg.AddPeers) > 0 && len(cfg.ConnectPeers) > 0 {
str := "%s: the --addpeer and --connect options can not be " +
"mixed"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --proxy or --connect without --listen disables listening.
if (cfg.Proxy != "" || len(cfg.ConnectPeers) > 0) &&
len(cfg.Listeners) == 0 {
cfg.DisableListen = true
}
// Connect means no DNS seeding.
if len(cfg.ConnectPeers) > 0 {
cfg.DisableDNSSeed = true
}
// Add the default listener if none were specified. The default
// listener is all addresses on the listen port for the network
// we are to connect to.
if len(cfg.Listeners) == 0 {
cfg.Listeners = []string{
net.JoinHostPort("", activeNetParams.DefaultPort),
}
}
// Check to make sure password is not used if hash is specified
if cfg.RPCHash != "" && cfg.RPCPass != "" {
str := "%s: --rpcpass may not be used if --rpchash is specified"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if cfg.RPCLimitHash != "" && cfg.RPCLimitPass != "" {
str := "%s: --rpclimitpass may not be used if --rpclimithash is specified"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Check to make sure limited and admin users don't have the same username
if cfg.RPCUser == cfg.RPCLimitUser && cfg.RPCUser != "" {
str := "%s: --rpcuser and --rpclimituser must not specify the " +
"same username"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Check to make sure limited and admin users don't have the same password
if cfg.RPCPass == cfg.RPCLimitPass && cfg.RPCPass != "" {
str := "%s: --rpcpass and --rpclimitpass must not specify the " +
"same password"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// The RPC server is disabled if no hash or (username+password) is provided.
if (cfg.RPCHash == "" && (cfg.RPCUser == "" || cfg.RPCPass == "")) &&
(cfg.RPCLimitHash == "" && (cfg.RPCLimitUser == "" || cfg.RPCLimitPass == "")) {
cfg.DisableRPC = true
}
// Default RPC to listen on localhost only.
if !cfg.DisableRPC && len(cfg.RPCListeners) == 0 {
addrs, err := net.LookupHost("localhost")
if err != nil {
return nil, nil, err
}
cfg.RPCListeners = make([]string, 0, len(addrs))
for _, addr := range addrs {
addr = net.JoinHostPort(addr, activeNetParams.rpcPort)
cfg.RPCListeners = append(cfg.RPCListeners, addr)
}
}
// Validate the the minrelaytxfee.
cfg.minRelayTxFee, err = provautil.NewAmount(cfg.MinRelayTxFee)
if err != nil {
str := "%s: invalid minrelaytxfee: %v"
err := fmt.Errorf(str, funcName, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Limit the max block size to a sane value.
if cfg.BlockMaxSize < blockMaxSizeMin || cfg.BlockMaxSize >
blockMaxSizeMax {
str := "%s: The blockmaxsize option must be in between %d " +
"and %d -- parsed [%d]"
err := fmt.Errorf(str, funcName, blockMaxSizeMin,
blockMaxSizeMax, cfg.BlockMaxSize)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Limit the max orphan count to a sane vlue.
if cfg.MaxOrphanTxs < 0 {
str := "%s: The maxorphantx option may not be less than 0 " +
"-- parsed [%d]"
err := fmt.Errorf(str, funcName, cfg.MaxOrphanTxs)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Limit the block priority and minimum block sizes to max block size.
cfg.BlockPrioritySize = minUint32(cfg.BlockPrioritySize, cfg.BlockMaxSize)
cfg.BlockMinSize = minUint32(cfg.BlockMinSize, cfg.BlockMaxSize)
// --txindex and --droptxindex do not mix.
if cfg.TxIndex && cfg.DropTxIndex {
err := fmt.Errorf("%s: the --txindex and --droptxindex "+
"options may not be activated at the same time",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --addrindex and --dropaddrindex do not mix.
if cfg.AddrIndex && cfg.DropAddrIndex {
err := fmt.Errorf("%s: the --addrindex and --dropaddrindex "+
"options may not be activated at the same time",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// --addrindex and --droptxindex do not mix.
if cfg.AddrIndex && cfg.DropTxIndex {
err := fmt.Errorf("%s: the --addrindex and --droptxindex "+
"options may not be activated at the same time "+
"because the address index relies on the transaction "+
"index",
funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Check mining addresses are valid and saved parsed versions.
cfg.miningAddrs = make([]provautil.Address, 0, len(cfg.MiningAddrs))
for _, strAddr := range cfg.MiningAddrs {
addr, err := provautil.DecodeAddress(strAddr, activeNetParams.Params)
if err != nil {
str := "%s: mining address '%s' failed to decode: %v"
err := fmt.Errorf(str, funcName, strAddr, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if !addr.IsForNet(activeNetParams.Params) {
str := "%s: mining address '%s' is on the wrong network"
err := fmt.Errorf(str, funcName, strAddr)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
cfg.miningAddrs = append(cfg.miningAddrs, addr)
}
// Ensure there is at least one mining address when the generate flag is
// set.
if cfg.Generate && len(cfg.MiningAddrs) == 0 {
str := "%s: the generate flag is set, but there are no mining " +
"addresses specified "
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Add default port to all listener addresses if needed and remove
// duplicate addresses.
cfg.Listeners = normalizeAddresses(cfg.Listeners,
activeNetParams.DefaultPort)
// Add default port to all rpc listener addresses if needed and remove
// duplicate addresses.
cfg.RPCListeners = normalizeAddresses(cfg.RPCListeners,
activeNetParams.rpcPort)
// RPC listening on external interfaces is only allowed when explicitly
// enabled and TLS is required.
if !cfg.EnableExternalRPC || (!cfg.DisableRPC && cfg.DisableTLS) {
allowedTLSListeners := map[string]struct{}{
"localhost": {},
"127.0.0.1": {},
"::1": {},
"fe80::1%lo0": {},
}
for _, addr := range cfg.RPCListeners {
host, _, err := net.SplitHostPort(addr)
if err != nil {
str := "%s: RPC listen interface '%s' is " +
"invalid: %v"
err := fmt.Errorf(str, funcName, addr, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
if _, ok := allowedTLSListeners[host]; !ok {
var str string
if cfg.DisableTLS {
str = "%s: the --notls option may not be used " +
"when binding RPC to non localhost " +
"addresses: %s"
} else {
str = "%s: the --enableexternalrpc option" +
"must be used when binding RPC to non " +
"localhost addresses: %s"
}
err := fmt.Errorf(str, funcName, addr)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
}
}
// Add default port to all added peer addresses if needed and remove
// duplicate addresses.
cfg.AddPeers = normalizeAddresses(cfg.AddPeers,
activeNetParams.DefaultPort)
cfg.ConnectPeers = normalizeAddresses(cfg.ConnectPeers,
activeNetParams.DefaultPort)
// --noonion and --onion do not mix.
if cfg.NoOnion && cfg.OnionProxy != "" {
err := fmt.Errorf("%s: the --noonion and --onion options may "+
"not be activated at the same time", funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Check the checkpoints for syntax errors.
cfg.addCheckpoints, err = parseCheckpoints(cfg.AddCheckpoints)
if err != nil {
str := "%s: Error parsing checkpoints: %v"
err := fmt.Errorf(str, funcName, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Tor stream isolation requires either proxy or onion proxy to be set.
if cfg.TorIsolation && cfg.Proxy == "" && cfg.OnionProxy == "" {
str := "%s: Tor stream isolation requires either proxy or " +
"onionproxy to be set"
err := fmt.Errorf(str, funcName)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Setup dial and DNS resolution (lookup) functions depending on the
// specified options. The default is to use the standard
// net.DialTimeout function as well as the system DNS resolver. When a
// proxy is specified, the dial function is set to the proxy specific
// dial function and the lookup is set to use tor (unless --noonion is
// specified in which case the system DNS resolver is used).
cfg.dial = net.DialTimeout
cfg.lookup = net.LookupIP
if cfg.Proxy != "" {
_, _, err := net.SplitHostPort(cfg.Proxy)
if err != nil {
str := "%s: Proxy address '%s' is invalid: %v"
err := fmt.Errorf(str, funcName, cfg.Proxy, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Tor isolation flag means proxy credentials will be overridden
// unless there is also an onion proxy configured in which case
// that one will be overridden.
torIsolation := false
if cfg.TorIsolation && cfg.OnionProxy == "" &&
(cfg.ProxyUser != "" || cfg.ProxyPass != "") {
torIsolation = true
fmt.Fprintln(os.Stderr, "Tor isolation set -- "+
"overriding specified proxy user credentials")
}
proxy := &socks.Proxy{
Addr: cfg.Proxy,
Username: cfg.ProxyUser,
Password: cfg.ProxyPass,
TorIsolation: torIsolation,
}
cfg.dial = proxy.DialTimeout
// Treat the proxy as tor and perform DNS resolution through it
// unless the --noonion flag is set or there is an
// onion-specific proxy configured.
if !cfg.NoOnion && cfg.OnionProxy == "" {
cfg.lookup = func(host string) ([]net.IP, error) {
return connmgr.TorLookupIP(host, cfg.Proxy)
}
}
}
// Setup onion address dial function depending on the specified options.
// The default is to use the same dial function selected above. However,
// when an onion-specific proxy is specified, the onion address dial
// function is set to use the onion-specific proxy while leaving the
// normal dial function as selected above. This allows .onion address
// traffic to be routed through a different proxy than normal traffic.
if cfg.OnionProxy != "" {
_, _, err := net.SplitHostPort(cfg.OnionProxy)
if err != nil {
str := "%s: Onion proxy address '%s' is invalid: %v"
err := fmt.Errorf(str, funcName, cfg.OnionProxy, err)
fmt.Fprintln(os.Stderr, err)
fmt.Fprintln(os.Stderr, usageMessage)
return nil, nil, err
}
// Tor isolation flag means onion proxy credentials will be
// overridden.
if cfg.TorIsolation &&
(cfg.OnionProxyUser != "" || cfg.OnionProxyPass != "") {
fmt.Fprintln(os.Stderr, "Tor isolation set -- "+
"overriding specified onionproxy user "+
"credentials ")
}
cfg.oniondial = func(network, addr string, timeout time.Duration) (net.Conn, error) {
proxy := &socks.Proxy{
Addr: cfg.OnionProxy,
Username: cfg.OnionProxyUser,
Password: cfg.OnionProxyPass,
TorIsolation: cfg.TorIsolation,
}
return proxy.DialTimeout(network, addr, timeout)
}
// When configured in bridge mode (both --onion and --proxy are
// configured), it means that the proxy configured by --proxy is
// not a tor proxy, so override the DNS resolution to use the
// onion-specific proxy.
if cfg.Proxy != "" {
cfg.lookup = func(host string) ([]net.IP, error) {
return connmgr.TorLookupIP(host, cfg.OnionProxy)
}
}
} else {
cfg.oniondial = cfg.dial
}
// Specifying --noonion means the onion address dial function results in
// an error.
if cfg.NoOnion {
cfg.oniondial = func(a, b string, t time.Duration) (net.Conn, error) {
return nil, errors.New("tor has been disabled")
}
}
// Warn about missing config file only after all other configuration is
// done. This prevents the warning on help messages and invalid
// options. Note this should go directly before the return.
if configFileError != nil {
btcdLog.Warnf("%v", configFileError)
}
return &cfg, remainingArgs, nil
}
// createDefaultConfig copies the file sample-dmgd.conf to the given destination path,
// and populates it with some randomly generated RPC username and password.
func createDefaultConfigFile(destinationPath string) error {
// Create the destination directory if it does not exists
err := os.MkdirAll(filepath.Dir(destinationPath), 0700)
if err != nil {
return err
}
// We assume sample config file path is same as binary
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err
}
sampleConfigPath := filepath.Join(path, sampleConfigFilename)
// We generate a random user and password
randomBytes := make([]byte, 20)
_, err = rand.Read(randomBytes)
if err != nil {
return err
}
generatedRPCUser := base64.StdEncoding.EncodeToString(randomBytes)
_, err = rand.Read(randomBytes)
if err != nil {
return err
}
generatedRPCPass := base64.StdEncoding.EncodeToString(randomBytes)
login := generatedRPCUser + ":" + generatedRPCPass
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte(login))
authsha := sha256.Sum256([]byte(auth))
generatedRPCHash := hex.EncodeToString(authsha[:])
src, err := os.Open(sampleConfigPath)
if err != nil {
return err
}
defer src.Close()
dest, err := os.OpenFile(destinationPath,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer dest.Close()
// We copy every line from the sample config file to the destination,
// only replacing the two lines for rpcuser and rpcpass
reader := bufio.NewReader(src)
for err != io.EOF {
var line string
line, err = reader.ReadString('\n')
if err != nil && err != io.EOF {
return err
}
if strings.Contains(line, "rpcuser=") {
line = "\n; REMOVE PASSWORD FROM THIS FILE AFTER SECURING IT ELSEWHERE\nrpcuser=" + generatedRPCUser + "\n"
} else if strings.Contains(line, "rpcpass=") {
line = "; rpcpass=" + generatedRPCPass + "\n\n"
} else if strings.Contains(line, "rpchash=") {
line = "rpchash=" + generatedRPCHash + "\n"
}
if _, err := dest.WriteString(line); err != nil {
return err
}
}
return nil
}
// btcdDial connects to the address on the named network using the appropriate
// dial function depending on the address and configuration options. For
// example, .onion addresses will be dialed using the onion specific proxy if
// one was specified, but will otherwise use the normal dial function (which
// could itself use a proxy or not).
func btcdDial(addr net.Addr) (net.Conn, error) {
if strings.Contains(addr.String(), ".onion:") {
return cfg.oniondial(addr.Network(), addr.String(),
defaultConnectTimeout)
}
return cfg.dial(addr.Network(), addr.String(), defaultConnectTimeout)
}
// btcdLookup resolves the IP of the given host using the correct DNS lookup
// function depending on the configuration options. For example, addresses will
// be resolved using tor when the --proxy flag was specified unless --noonion
// was also specified in which case the normal system DNS resolver will be used.
//
// Any attempt to resolve a tor address (.onion) will return an error since they
// are not intended to be resolved outside of the tor proxy.
func btcdLookup(host string) ([]net.IP, error) {
if strings.HasSuffix(host, ".onion") {
return nil, fmt.Errorf("attempt to resolve tor address %s", host)
}
return cfg.lookup(host)
}
| parseCheckpoints |
midi-notes.ts | import { MidiNote } from "@brandongregoryscott/reactronica";
const MidiNotes: MidiNote[] = [
"C-2",
"C#-2",
"D-2",
"D#-2",
"E-2",
"F-2",
"F#-2",
"G-2",
"G#-2",
"A-2",
"A#-2",
"B-2",
"C-1",
"C#-1",
"D-1",
"D#-1",
"E-1",
"F-1",
"F#-1",
"G-1",
"G#-1",
"A-1",
"A#-1",
"B-1",
"C0",
"C#0",
"D0",
"D#0",
"E0",
"F0",
"F#0",
"G0",
"G#0",
"A0",
"A#0",
"B0",
"C1",
"C#1",
"D1",
"D#1",
"E1",
"F1",
"F#1",
"G1",
"G#1",
"A1",
"A#1",
"B1",
"C2",
"C#2",
"D2",
"D#2",
"E2",
"F2",
"F#2",
"G2",
"G#2",
"A2",
"A#2",
"B2",
"C3",
"C#3",
"D3",
"D#3",
"E3",
"F3",
"F#3",
"G3",
"G#3",
"A3",
"A#3",
"B3",
"C4",
"C#4",
"D4",
"D#4",
"E4",
"F4",
"F#4",
"G4",
"G#4",
"A4",
"A#4",
"B4",
"C5",
"C#5",
"D5",
"D#5",
"E5",
"F5",
"F#5",
"G5",
"G#5",
"A5",
"A#5",
"B5",
"C6",
"C#6",
"D6",
"D#6",
"E6",
"F6",
"F#6",
"G6",
"G#6",
"A6",
"A#6",
"B6",
"C7",
"C#7",
"D7",
"D#7",
"E7", | "F7",
"F#7",
"G7",
"G#7",
"A7",
"A#7",
"B7",
"C8",
"C#8",
"D8",
"D#8",
"E8",
"F8",
"F#8",
"G8",
];
export { MidiNotes }; | |
test_create_amendment.py | from tests.system.action.base import BaseActionTestCase
class MotionCreateAmendmentActionTest(BaseActionTestCase):
def setUp(self) -> None:
super().setUp()
# create parent motion and workflow
self.set_models(
{
"motion_workflow/12": {
"name": "name_workflow1",
"first_state_id": 34,
"state_ids": [34],
},
"motion_state/34": {"name": "name_state34", "meeting_id": 222},
"motion/1": {
"title": "title_eJveLQIh",
"sort_child_ids": [],
"meeting_id": 222,
},
}
)
def test_create_amendment(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"text": "text_test1",
},
)
self.assert_status_code(response, 200)
model = self.get_model("motion/2")
assert model.get("title") == "test_Xcdfgee"
assert model.get("meeting_id") == 222
assert model.get("lead_motion_id") == 1
assert model.get("text") == "text_test1"
def test_create_amendment_default_workflow(self) -> None:
self.set_models(
{
"meeting/222": {
"motions_default_amendment_workflow_id": 12,
"is_active_in_organization_id": 1,
},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"lead_motion_id": 1,
"text": "text_test1",
},
)
self.assert_status_code(response, 200)
model = self.get_model("motion/2")
assert model.get("title") == "test_Xcdfgee"
assert model.get("meeting_id") == 222
assert model.get("lead_motion_id") == 1
assert model.get("text") == "text_test1"
assert model.get("state_id") == 34
def test_create_with_amendment_paragraphs_valid(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"amendment_paragraph_$": {4: "text"},
},
)
self.assert_status_code(response, 200)
model = self.get_model("motion/2")
assert model.get("title") == "test_Xcdfgee"
assert model.get("meeting_id") == 222
assert model.get("lead_motion_id") == 1
assert model.get("state_id") == 34
assert model.get("amendment_paragraph_$4") == "text"
assert model.get("amendment_paragraph_$") == ["4"]
def test_create_with_amendment_paragraphs_0(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"amendment_paragraph_$": {0: "text"},
},
)
self.assert_status_code(response, 200)
model = self.get_model("motion/2")
assert model.get("amendment_paragraph_$0") == "text"
assert model.get("amendment_paragraph_$") == ["0"]
def test_create_with_amendment_paragraphs_string(self) -> None:
|
def test_create_with_amendment_paragraphs_invalid(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"amendment_paragraph_$": {"a4": "text"},
},
)
self.assert_status_code(response, 400)
assert "data.amendment_paragraph_$ must not contain {'a4'} properties" in str(
response.json["message"]
)
def test_create_missing_text(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
},
)
self.assert_status_code(response, 400)
assert "Text or amendment_paragraph_$ is required in this context." in str(
response.json["message"]
)
def test_create_text_and_amendment_paragraphs(self) -> None:
self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"text": "text",
"amendment_paragraph_$": {4: "text"},
},
)
self.assert_status_code(response, 400)
assert "give both of text and amendment_paragraph_$" in response.json["message"]
def test_create_missing_reason(self) -> None:
self.set_models(
{
"meeting/222": {
"motions_reason_required": True,
"is_active_in_organization_id": 1,
},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"text": "text",
},
)
self.assert_status_code(response, 400)
assert "Reason is required" in response.json["message"]
| self.set_models(
{
"meeting/222": {"is_active_in_organization_id": 1},
"user/1": {"meeting_ids": [222]},
}
)
response = self.request(
"motion.create",
{
"title": "test_Xcdfgee",
"meeting_id": 222,
"workflow_id": 12,
"lead_motion_id": 1,
"amendment_paragraph_$": {"0": "text"},
},
)
self.assert_status_code(response, 200)
model = self.get_model("motion/2")
assert model.get("amendment_paragraph_$0") == "text"
assert model.get("amendment_paragraph_$") == ["0"] |
server.go | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2018 Datadog, Inc.
/*
Package api implements the agent IPC api. Using HTTP
calls, it's possible to communicate with the agent,
sending commands and receiving infos.
*/
package api
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
stdLog "log"
"net"
"net/http"
"strings"
"github.com/DataDog/datadog-agent/cmd/cluster-agent/api/agent"
"github.com/DataDog/datadog-agent/pkg/api/security"
"github.com/DataDog/datadog-agent/pkg/api/util"
"github.com/DataDog/datadog-agent/pkg/config" | )
var (
listener net.Listener
)
// StartServer creates the router and starts the HTTP server
func StartServer() error {
// create the root HTTP router
r := mux.NewRouter()
// IPC REST API server
agent.SetupHandlers(r)
// Validate token for every request
r.Use(validateToken)
// get the transport we're going to use under HTTP
var err error
listener, err = getListener()
if err != nil {
// we use the listener to handle commands for the agent, there's
// no way we can recover from this error
return fmt.Errorf("Unable to create the api server: %v", err)
}
// Internal token
util.SetAuthToken()
// DCA client token
util.SetDCAAuthToken()
// create cert
hosts := []string{"127.0.0.1", "localhost"}
_, rootCertPEM, rootKey, err := security.GenerateRootCert(hosts, 2048)
if err != nil {
return fmt.Errorf("unable to start TLS server")
}
// PEM encode the private key
rootKeyPEM := pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rootKey),
})
// Create a TLS cert using the private key and certificate
rootTLSCert, err := tls.X509KeyPair(rootCertPEM, rootKeyPEM)
if err != nil {
return fmt.Errorf("invalid key pair: %v", err)
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{rootTLSCert},
}
srv := &http.Server{
Handler: r,
ErrorLog: stdLog.New(&config.ErrorLogWriter{}, "", 0), // log errors to seelog
TLSConfig: &tlsConfig,
}
tlsListener := tls.NewListener(listener, &tlsConfig)
go srv.Serve(tlsListener)
return nil
}
// StopServer closes the connection and the server
// stops listening to new commands.
func StopServer() {
if listener != nil {
listener.Close()
}
}
// We only want to maintain 1 API and expose an external route to serve the cluster level metadata.
// As we have 2 different tokens for the validation, we need to validate accordingly.
func validateToken(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.String()
if strings.HasPrefix(path, "/api/v1/metadata/") && len(strings.Split(path, "/")) == 7 {
if err := util.ValidateDCARequest(w, r); err != nil {
return
}
} else {
if err := util.Validate(w, r); err != nil {
return
}
}
next.ServeHTTP(w, r)
})
} | "github.com/gorilla/mux" |
test_index_of_dispersion.py | from __future__ import annotations
import random
import pytest
def | ():
from scitbx.array_family import flex
from dials.algorithms.image.filter import index_of_dispersion_filter
# Create an image
image = flex.random_double(2000 * 2000)
image.reshape(flex.grid(2000, 2000))
mask = flex.random_bool(2000 * 2000, 0.99).as_int()
mask.reshape(flex.grid(2000, 2000))
# Calculate the summed area table
mask2 = mask.deep_copy()
index_of_dispersion_filter = index_of_dispersion_filter(image, mask2, (3, 3), 2)
mean = index_of_dispersion_filter.mean()
var = index_of_dispersion_filter.sample_variance()
index_of_dispersion = index_of_dispersion_filter.index_of_dispersion()
# For a selection of random points, ensure that the value is the
# sum of the area under the kernel
eps = 1e-7
for i in range(10000):
i = random.randint(10, 1990)
j = random.randint(10, 1990)
m1 = mean[j, i]
v1 = var[j, i]
f1 = index_of_dispersion[j, i]
p = image[j - 3 : j + 4, i - 3 : i + 4]
m = mask[j - 3 : j + 4, i - 3 : i + 4]
if mask[j, i] == 0:
m2 = 0.0
v2 = 0.0
f2 = 1.0
else:
p = flex.select(p, flags=m)
mv = flex.mean_and_variance(flex.double(p))
m2 = mv.mean()
v2 = mv.unweighted_sample_variance()
f2 = v2 / m2
assert m1 == pytest.approx(m2, abs=eps)
assert v1 == pytest.approx(v2, abs=eps)
assert f1 == pytest.approx(f2, abs=eps)
| test |
inject-field.decorator.ts | import 'reflect-metadata';
import { InjectFlags, Injector } from '@angular/core';
import { debugLog } from 'core-app/shared/helpers/debug_output';
export interface InjectableClass {
injector:Injector;
}
export function | (token?:any, defaultValue:any = null, flags?:InjectFlags) {
return (target:InjectableClass, property:string) => {
if (delete (target as any)[property]) {
Object.defineProperty(target, property, {
get(this:InjectableClass) {
if (token) {
return this.injector.get<any>(token, defaultValue, flags);
}
const type = Reflect.getMetadata('design:type', target, property);
return this.injector.get<any>(type, defaultValue, flags);
},
set(this:InjectableClass, _val:any) {
debugLog(`Trying to set InjectField property ${property}`);
},
});
}
};
}
| InjectField |
pathconstants.ts |
export const ANDROID_APP_PATH = join(process.cwd(), 'src', 'mobile', 'src', 'app', 'android', 'ApiDemos-debug.apk')
export const MOCHA_OUTPUT_DIR = join(process.cwd(), 'reports', 'appium'); | import { join } from 'path'; |
|
committee.rs | pub use chain_impl_mockchain::vote::CommitteeId;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// remove serde encoding for the CommitteeId
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(remote = "CommitteeId")]
pub struct CommitteeIdDef(#[serde(getter = "get_bytes")] [u8; CommitteeId::COMMITTEE_ID_SIZE]);
impl From<CommitteeIdDef> for CommitteeId {
fn from(committee_id_def: CommitteeIdDef) -> Self {
Self::from(committee_id_def.0)
}
}
impl From<CommitteeId> for CommitteeIdDef {
fn from(committee_id: CommitteeId) -> Self {
Self(get_bytes(&committee_id))
}
}
impl From<[u8; CommitteeId::COMMITTEE_ID_SIZE]> for CommitteeIdDef {
fn from(committee_id: [u8; CommitteeId::COMMITTEE_ID_SIZE]) -> Self {
Self(committee_id)
}
}
impl CommitteeIdDef {
/// returns the identifier encoded in hexadecimal string
pub fn to_hex(&self) -> String {
hex::encode(self.0)
}
/// read the identifier from the hexadecimal string
pub fn | (s: &str) -> Result<Self, hex::FromHexError> {
CommitteeId::from_hex(s).map(Into::into)
}
}
fn get_bytes(committee_id: &CommitteeId) -> [u8; CommitteeId::COMMITTEE_ID_SIZE] {
let mut bytes = [0; CommitteeId::COMMITTEE_ID_SIZE];
bytes.copy_from_slice(committee_id.as_ref());
bytes
}
/* ------------------- Serde ----------------------------------------------- */
impl Serialize for CommitteeIdDef {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
let hex = hex::encode(&self.0);
serializer.serialize_str(&hex)
} else {
serializer.serialize_bytes(&self.0)
}
}
}
impl<'de> Deserialize<'de> for CommitteeIdDef {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let bytes = if deserializer.is_human_readable() {
let s: String = String::deserialize(deserializer)?;
let mut bytes = [0; CommitteeId::COMMITTEE_ID_SIZE];
hex::decode_to_slice(&s, &mut bytes).map_err(serde::de::Error::custom)?;
bytes
} else {
let b: Vec<u8> = Vec::deserialize(deserializer)?;
if b.len() != CommitteeId::COMMITTEE_ID_SIZE {
return Err(serde::de::Error::custom("not enough bytes"));
}
let mut bytes = [0; CommitteeId::COMMITTEE_ID_SIZE];
bytes.copy_from_slice(&b);
bytes
};
Ok(Self(bytes))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::{Arbitrary, Gen};
impl Arbitrary for CommitteeIdDef {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let mut cid = CommitteeIdDef([0; CommitteeId::COMMITTEE_ID_SIZE]);
g.fill_bytes(&mut cid.0);
cid
}
}
}
| from_hex |
p1.rs | use std::io;
use file_reader;
const INPUT_FILENAME: &str = "input.txt";
#[derive(Debug)]
struct PwData {
min: usize,
max: usize,
letter: char,
pw: String,
}
fn main() {
let input_str = match file_reader::file_to_vec(INPUT_FILENAME) {
Err(_) => {
println!("Couldn't turn file into vec!");
return;
},
Ok(v) => v,
};
let input: Vec<PwData> =
input_str.into_iter().map(process_input).collect();
let result = input.into_iter().map(validate_pw).filter_map(io::Result::ok).collect::<Vec<()>>().len();
println!("{:?}", result);
}
fn process_input(input: String) -> PwData {
// input string looks like: <u32>-<u32> <char>: <String>
let min: usize = input[0..input.find('-').unwrap()].parse::<usize>().unwrap();
let max: usize = input[input.find('-').unwrap() + 1..input.find(' ').unwrap()].parse::<usize>().unwrap();
let letter: char = input.chars().nth(input.find(' ').unwrap() + 1).unwrap();
let pw: String = String::from(&input[input.find(": ").unwrap() + 2..input.len()]); |
fn validate_pw(pw_data: PwData) -> io::Result<()> {
let num_letter = pw_data.pw.matches(pw_data.letter).collect::<Vec<&str>>().len();
if pw_data.min <= num_letter && num_letter <= pw_data.max {
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, "invalid pw"))
}
} |
PwData { min, max, letter, pw }
} |
ACO.py | import numpy as np
import matplotlib.pyplot as plt
import urllib.request
import os
import time
def download(root_path,filename):
if not os.path.exists(root_path):
os.mkdir(root_path)
if not os.path.exists(os.path.join(root_path,filename)):
url = "http://elib.zib.de/pub/mp-testdata/tsp/tsplib/tsp/"+filename
urllib.request.urlretrieve(url,os.path.join(root_path,filename))
print("The data set: %s downloaded!"%os.path.join(root_path,filename))
else:
print("The data set: %s already has downloaded!"%os.path.join(root_path,filename))
def get_data(filename):
data_list = []
with open(filename,mode="r") as f:
flag = False
while True:
line = f.readline()
if "EOF" in line:
break
elif "NODE_COORD_SECTION" in line:
flag = True
elif flag:
tmp = line.strip().split(" ")
data_list.append([float(item) for item in tmp])
return np.array(data_list)
class ACO:
def __init__(self,ant_num,alpha,beta,rho,Q,epoches):
self.ant_num = ant_num
self.alpha = alpha
self.beta = beta
self.rho = rho
self.Q = Q
self.epoches = epoches
self.citys_mat = None
self.E_best = None
self.sol_best = None
self.length_list = None
self.name = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
def solve(self,citys_mat):
self.citys_mat = citys_mat
citys_num = citys_mat.shape[0]
# 获取邻接矩阵
citys_x = citys_mat[:, 0].reshape(citys_num, 1).dot(np.ones((1, citys_num)))
citys_y = citys_mat[:, 1].reshape(citys_num, 1).dot(np.ones((1, citys_num)))
citys_distance = np.sqrt(np.square(citys_x - citys_x.T) + np.square(citys_y - citys_y.T))
# 初始化启发函数
Heu_f = 1.0/(citys_distance + np.diag([np.inf] * citys_num))
# 信息素矩阵
Tau_table = np.ones((citys_num,citys_num))
# 每一次迭代过程中每个蚂蚁的路径记录表
Route_table = np.zeros((self.ant_num,citys_num),dtype=np.int)
# 每一次迭代过程中的最佳路径
Route_best = np.zeros((self.epoches,citys_num),dtype=np.int)
# 每一次迭代过程中最佳路径记录表
Length_best = np.zeros(self.epoches)
# 每次迭代过程中蚂蚁的平均路径长度
Length_average = np.zeros(self.epoches)
# 每次迭代过程中当前路径长度
Length_current = np.zeros(self.ant_num)
iter = 0
while iter <self.epoches:
# 产生城市集合表
# 随机产生各个蚂蚁的起点城市
Route_table[:,0]= self.randseed(citys_num)
# 更新信息素
Delta_tau = np.zeros((citys_num, citys_num))
for k in range(self.ant_num):
# 用于记录蚂蚁下一个访问的城市集合
# 蚂蚁已经访问过的城市
tabu = [Route_table[k,0]]
allow_set = list(set(range(citys_num))-set(tabu))
city_index = Route_table[k,0]
for i in range(1,citys_num):
# 初始化城市之间的转移概率
P_table = np.zeros(len(allow_set))
# 计算城市之间的转移概率
for j in range(len(allow_set)):
P_table[j] = np.power(Tau_table[city_index,allow_set[j]],self.alpha)*\ |
# 轮盘赌算法来选择下一个访问的城市
#out_prob = np.cumsum(P_table)
while True:
r = np.random.rand()
index_need = np.where(P_table > r)[0]
if len(index_need) >0:
city_index2 = allow_set[index_need[0]]
break
Route_table[k,i] = city_index2
tabu.append(city_index2)
allow_set = list(set(range(0,citys_num))-set(tabu))
city_index = city_index2
tabu.append(tabu[0])
# 计算蚂蚁路径的距离信息
for j in range(citys_num):
Length_current[k] = Length_current[k] + citys_distance[tabu[j],tabu[j+1]]
for j in range(citys_num):
Delta_tau[tabu[j],tabu[j+1]] = Delta_tau[tabu[j],tabu[j+1]] + self.Q / Length_current[k]
# 计算最短路径、最短路径长度以及平均路径长度
Length_best[iter] = np.min(Length_current)
index = np.where(Length_current == np.min(Length_current))[0][0]
Route_best[iter] = Route_table[index]
Length_average[iter] = np.mean(Length_current)
#更新信息素
Tau_table = (1-self.rho)*Tau_table + Delta_tau
#Route_table = np.zeros((self.ant_num,citys_num),dtype=np.int)
Length_current = np.zeros(self.ant_num)
print("epoches:%d,best value every epoches%.4f"%(iter, Length_best[iter]))
iter = iter + 1
self.E_best = np.min(Length_best)
index = np.where(Length_best == np.min(Length_best))[0][0]
self.sol_best = Route_table[index]
self.length_list = Length_average
def randseed(self,citys_num):
if self.ant_num <citys_num:
initial_route = np.random.permutation(range(citys_num))[:self.ant_num]
else:
initial_route = np.zeros((self.ant_num,))
initial_route[:citys_num] = np.random.permutation(range(citys_num))
tmp_index = citys_num
while tmp_index + citys_num <= self.ant_num:
initial_route[tmp_index:citys_num + tmp_index] = np.random.permutation(range(citys_num))
tmp_index += citys_num
tmp_left = self.ant_num % citys_num
if tmp_left != 0:
initial_route[tmp_index:] = np.random.permutation(range(citys_num))[:tmp_left]
return initial_route
def draw(self):
print(self.sol_best)
print(self.E_best)
if not os.path.exists("log"):
os.mkdir("log")
# draw loss
x = np.linspace(0, len(self.length_list) - 1, len(self.length_list))
y = np.array(self.length_list)
plt.plot(x, y)
plt.title(label="loss")
plt.savefig(os.path.join("log", "%s_loss.png" % self.name))
plt.close()
# draw dots
for k in range(0, len(self.sol_best) - 1):
start = self.citys_mat[self.sol_best[k]]
end = self.citys_mat[self.sol_best[k + 1]]
plt.plot(start[0], start[1], "bo")
plt.plot(end[0], end[1], "bo")
plt.arrow(start[0], start[1], end[0] - start[0], end[1] - start[1],
length_includes_head=True, head_width=0.2, head_length=0.3, lw=1,
color="r")
start = self.citys_mat[self.sol_best[-1]]
end = self.citys_mat[self.sol_best[0]]
plt.plot(start[0], start[1], "bo")
plt.plot(end[0], end[1], "bo")
plt.arrow(start[0], start[1], end[0] - start[0], end[1] - start[1],
length_includes_head=True, head_width=0.2, head_length=0.3, lw=1,
color="r")
plt.title(label="length:%.2f" % (self.E_best))
plt.savefig(os.path.join("log", "%s_route.png" % self.name))
plt.show()
def main():
filename = "eil51.tsp"
root_path = "data"
download(root_path,filename)
data_list = get_data(os.path.join(root_path,filename))
ant_num = 500
alpha = 1
beta = 5
rho = 0.2
Q = 10
epoches = 20
model = ACO(ant_num, alpha, beta, rho, Q, epoches)
model.solve(data_list[:,1:])
model.draw()
if __name__ == '__main__':
main() | np.power(Heu_f[city_index,allow_set[j]],self.beta)
P_table = P_table/np.sum(P_table) |
_Search.js | import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import get from 'lodash/get'
import omit from 'lodash/omit'
import { fbt } from 'fbt-runtime'
import Categories from '@origin/graphql/src/constants/Categories'
// import PriceFilter from './filters/Price'
const CategoriesEnum = require('Categories$FbtEnum')
import withConfig from 'hoc/withConfig'
import Dropdown from 'components/Dropdown'
const categories = Categories.root.map(c => ({
id: c[0],
type: c[0].split('.').slice(-1)[0]
}))
categories.unshift({ id: '', type: '' })
class Search extends Component {
constructor(props) {
super(props)
this.state = props.value || {}
}
render() {
const enabled = get(this.props, 'config.discovery', false)
const category = this.state.category || {}
return (
<div className="search-bar">
<div className="container d-flex align-items-center">
<div className="input-group search-query">
<Dropdown
className="input-group-prepend"
content={
<SearchDropdown
active={category}
onChange={category =>
this.setState({ category, open: false }, () => {
this.doSearch()
})
}
/>
}
open={this.state.open}
onClose={() => this.setState({ open: false })}
>
<button
className="btn btn-outline-secondary dropdown-toggle"
onClick={() =>
this.setState({ open: this.state.open ? false : true })
}
>
{CategoriesEnum[category.id] ? (
<fbt desc="category">
<fbt:enum enum-range={CategoriesEnum} value={category.id} />
</fbt>
) : (
fbt('All', 'listingType.all')
)}
</button>
</Dropdown>
<input
type="text"
className="form-control"
placeholder={enabled ? 'Search' : 'Note: Search unavailable'}
value={this.state.searchInput}
onChange={e => this.setState({ searchInput: e.target.value })}
onKeyUp={e => {
if (e.keyCode === 13) this.doSearch()
}}
/>
<div className="input-group-append">
<button
className="btn btn-primary"
onClick={() => this.doSearch()}
/>
</div> | </div>
{/* <PriceFilter
low={this.state.priceLow}
high={this.state.priceHigh}
onChange={({ low, high }) => {
this.setState(
{ priceMin: low / 1000, priceMax: high / 1000 },
() => this.doSearch()
)
}}
/> */}
</div>
</div>
)
}
doSearch() {
if (this.props.onSearch) {
this.props.onSearch(omit(this.state, 'open'))
}
}
}
const SearchDropdown = ({ onChange, active }) => (
<div className="dropdown-menu show">
{categories.map((category, idx) => (
<a
key={idx}
className={`dropdown-item${
active && active.id === category.id ? ' active' : ''
}`}
href="#"
onClick={e => {
e.preventDefault()
onChange(category)
}}
>
{CategoriesEnum[category.id] ? (
<fbt desc="category">
<fbt:enum enum-range={CategoriesEnum} value={category.id} />
</fbt>
) : (
fbt('All', 'listingType.all')
)}
</a>
))}
</div>
)
export default withConfig(withRouter(Search))
require('react-styl')(`
.search-bar
padding: 0.7rem 0
box-shadow: 0 1px 0 0 var(--light)
background-color: var(--pale-grey)
.input-group.search-query
max-width: 520px
.btn-outline-secondary
border: 1px solid var(--light)
font-size: 14px
font-weight: normal
color: var(--dusk)
&:hover,&:active,&:focus
color: var(--white)
.dropdown-toggle::after
margin-left: 0.5rem
.form-control
border-color: var(--light)
&::placeholder
opacity: 0.5
.btn-primary
background: var(--dusk) url(images/magnifying-glass.svg) no-repeat center
border-color: var(--dusk)
padding-left: 1.25rem
padding-right: 1.25rem
`) | |
to_domain_test.go | // Copyright (c) 2018 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dbmodel
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"testing"
gogojsonpb "github.com/gogo/protobuf/jsonpb"
"github.com/kr/pretty"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/jaegertracing/jaeger/model"
)
func TestToDomain(t *testing.T) {
testToDomain(t, false)
testToDomain(t, true)
// this is just to confirm the uint64 representation of float64(72.5) used as a "temperature" tag
assert.Equal(t, int64(4634802150889750528), int64(math.Float64bits(72.5)))
}
func testToDomain(t *testing.T, testParentSpanID bool) {
for i := 1; i <= NumberOfFixtures; i++ {
span, err := loadESSpanFixture(i)
require.NoError(t, err)
if testParentSpanID {
span.ParentSpanID = "3"
}
actualSpan, err := NewToDomain(":").SpanToDomain(&span)
require.NoError(t, err)
out := fmt.Sprintf("fixtures/domain_%02d.json", i)
outStr, err := ioutil.ReadFile(out)
require.NoError(t, err)
var expectedSpan model.Span
require.NoError(t, gogojsonpb.Unmarshal(bytes.NewReader(outStr), &expectedSpan))
CompareModelSpans(t, &expectedSpan, actualSpan)
}
}
func loadESSpanFixture(i int) (Span, error) {
in := fmt.Sprintf("fixtures/es_%02d.json", i)
inStr, err := ioutil.ReadFile(in)
if err != nil {
return Span{}, err
}
var span Span
err = json.Unmarshal(inStr, &span)
return span, err
}
func failingSpanTransform(t *testing.T, embeddedSpan *Span, errMsg string) {
domainSpan, err := NewToDomain(":").SpanToDomain(embeddedSpan)
assert.Nil(t, domainSpan)
assert.EqualError(t, err, errMsg)
}
func failingSpanTransformAnyMsg(t *testing.T, embeddedSpan *Span) {
domainSpan, err := NewToDomain(":").SpanToDomain(embeddedSpan)
assert.Nil(t, domainSpan)
assert.Error(t, err)
}
func TestFailureBadTypeTags(t *testing.T) {
badTagESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTagESSpan.Tags = []KeyValue{
{
Key: "meh",
Type: "badType",
Value: "",
},
}
failingSpanTransformAnyMsg(t, &badTagESSpan)
}
func TestFailureBadBoolTags(t *testing.T) {
badTagESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTagESSpan.Tags = []KeyValue{
{
Key: "meh",
Value: "meh",
Type: "bool",
},
}
failingSpanTransformAnyMsg(t, &badTagESSpan)
}
func | (t *testing.T) {
badTagESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTagESSpan.Tags = []KeyValue{
{
Key: "meh",
Value: "meh",
Type: "int64",
},
}
failingSpanTransformAnyMsg(t, &badTagESSpan)
}
func TestFailureBadFloatTags(t *testing.T) {
badTagESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTagESSpan.Tags = []KeyValue{
{
Key: "meh",
Value: "meh",
Type: "float64",
},
}
failingSpanTransformAnyMsg(t, &badTagESSpan)
}
func TestFailureBadBinaryTags(t *testing.T) {
badTagESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTagESSpan.Tags = []KeyValue{
{
Key: "zzzz",
Value: "zzzz",
Type: "binary",
},
}
failingSpanTransformAnyMsg(t, &badTagESSpan)
}
func TestFailureBadLogs(t *testing.T) {
badLogsESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badLogsESSpan.Logs = []Log{
{
Timestamp: 0,
Fields: []KeyValue{
{
Key: "sneh",
Value: "",
Type: "badType",
},
},
},
}
failingSpanTransform(t, &badLogsESSpan, "not a valid ValueType string badType")
}
func TestRevertKeyValueOfType(t *testing.T) {
tests := []struct {
kv *KeyValue
err string
}{
{
kv: &KeyValue{
Key: "sneh",
Type: "badType",
Value: "someString",
},
err: "not a valid ValueType string",
},
{
kv: &KeyValue{},
err: "invalid nil Value",
},
{
kv: &KeyValue{
Value: 123,
},
err: "non-string Value of type",
},
}
td := ToDomain{}
for _, test := range tests {
t.Run(test.err, func(t *testing.T) {
tag := test.kv
_, err := td.convertKeyValue(tag)
require.Error(t, err)
assert.Contains(t, err.Error(), test.err)
})
}
}
func TestFailureBadRefs(t *testing.T) {
badRefsESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badRefsESSpan.References = []Reference{
{
RefType: "makeOurOwnCasino",
TraceID: "1",
},
}
failingSpanTransform(t, &badRefsESSpan, "not a valid SpanRefType string makeOurOwnCasino")
}
func TestFailureBadTraceIDRefs(t *testing.T) {
badRefsESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badRefsESSpan.References = []Reference{
{
RefType: "CHILD_OF",
TraceID: "ZZBADZZ",
SpanID: "1",
},
}
failingSpanTransformAnyMsg(t, &badRefsESSpan)
}
func TestFailureBadSpanIDRefs(t *testing.T) {
badRefsESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badRefsESSpan.References = []Reference{
{
RefType: "CHILD_OF",
TraceID: "1",
SpanID: "ZZBADZZ",
},
}
failingSpanTransformAnyMsg(t, &badRefsESSpan)
}
func TestFailureBadProcess(t *testing.T) {
badProcessESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTags := []KeyValue{
{
Key: "meh",
Value: "",
Type: "badType",
},
}
badProcessESSpan.Process = Process{
ServiceName: "hello",
Tags: badTags,
}
failingSpanTransform(t, &badProcessESSpan, "not a valid ValueType string badType")
}
func TestFailureBadTraceID(t *testing.T) {
badTraceIDESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badTraceIDESSpan.TraceID = "zz"
failingSpanTransformAnyMsg(t, &badTraceIDESSpan)
}
func TestFailureBadSpanID(t *testing.T) {
badSpanIDESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badSpanIDESSpan.SpanID = "zz"
failingSpanTransformAnyMsg(t, &badSpanIDESSpan)
}
func TestFailureBadParentSpanID(t *testing.T) {
badParentSpanIDESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badParentSpanIDESSpan.ParentSpanID = "zz"
failingSpanTransformAnyMsg(t, &badParentSpanIDESSpan)
}
func TestFailureBadSpanFieldTag(t *testing.T) {
badParentSpanIDESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badParentSpanIDESSpan.Tag = map[string]interface{}{"foo": struct{}{}}
failingSpanTransformAnyMsg(t, &badParentSpanIDESSpan)
}
func TestFailureBadProcessFieldTag(t *testing.T) {
badParentSpanIDESSpan, err := loadESSpanFixture(1)
require.NoError(t, err)
badParentSpanIDESSpan.Process.Tag = map[string]interface{}{"foo": struct{}{}}
failingSpanTransformAnyMsg(t, &badParentSpanIDESSpan)
}
func CompareModelSpans(t *testing.T, expected *model.Span, actual *model.Span) {
model.SortSpan(expected)
model.SortSpan(actual)
if !assert.EqualValues(t, expected, actual) {
for _, err := range pretty.Diff(expected, actual) {
t.Log(err)
}
out, err := json.Marshal(actual)
assert.NoError(t, err)
t.Logf("Actual trace: %s", string(out))
}
}
func TestTagsMap(t *testing.T) {
tests := []struct {
fieldTags map[string]interface{}
expected []model.KeyValue
err error
}{
{fieldTags: map[string]interface{}{"bool:bool": true}, expected: []model.KeyValue{model.Bool("bool.bool", true)}},
{fieldTags: map[string]interface{}{"int.int": int64(1)}, expected: []model.KeyValue{model.Int64("int.int", 1)}},
{fieldTags: map[string]interface{}{"int:int": int64(2)}, expected: []model.KeyValue{model.Int64("int.int", 2)}},
{fieldTags: map[string]interface{}{"float": float64(1.1)}, expected: []model.KeyValue{model.Float64("float", 1.1)}},
{fieldTags: map[string]interface{}{"float": float64(123)}, expected: []model.KeyValue{model.Float64("float", float64(123))}},
{fieldTags: map[string]interface{}{"float": float64(123.0)}, expected: []model.KeyValue{model.Float64("float", float64(123.0))}},
{fieldTags: map[string]interface{}{"float:float": float64(123)}, expected: []model.KeyValue{model.Float64("float.float", float64(123))}},
{fieldTags: map[string]interface{}{"json_number:int": json.Number("123")}, expected: []model.KeyValue{model.Int64("json_number.int", 123)}},
{fieldTags: map[string]interface{}{"json_number:float": json.Number("123.0")}, expected: []model.KeyValue{model.Float64("json_number.float", float64(123.0))}},
{fieldTags: map[string]interface{}{"json_number:err": json.Number("foo")}, err: fmt.Errorf("invalid tag type in foo: strconv.ParseFloat: parsing \"foo\": invalid syntax")},
{fieldTags: map[string]interface{}{"str": "foo"}, expected: []model.KeyValue{model.String("str", "foo")}},
{fieldTags: map[string]interface{}{"str:str": "foo"}, expected: []model.KeyValue{model.String("str.str", "foo")}},
{fieldTags: map[string]interface{}{"binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary", []byte("foo"))}},
{fieldTags: map[string]interface{}{"binary:binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary.binary", []byte("foo"))}},
{fieldTags: map[string]interface{}{"unsupported": struct{}{}}, err: fmt.Errorf("invalid tag type in %+v", struct{}{})},
}
converter := NewToDomain(":")
for i, test := range tests {
t.Run(fmt.Sprintf("%d, %s", i, test.fieldTags), func(t *testing.T) {
tags, err := converter.convertTagFields(test.fieldTags)
if err != nil {
fmt.Println(err.Error())
}
if test.err != nil {
assert.Equal(t, test.err.Error(), err.Error())
require.Nil(t, tags)
} else {
require.NoError(t, err)
assert.Equal(t, test.expected, tags)
}
})
}
}
func TestDotReplacement(t *testing.T) {
converter := NewToDomain("#")
k := "foo.foo"
assert.Equal(t, k, converter.ReplaceDotReplacement(converter.ReplaceDot(k)))
}
| TestFailureBadIntTags |
globalDemographics.test.ts | import { Sequelize } from 'sequelize';
import { stub, assert, match, SinonStub, restore } from 'sinon';
import GlobalDemographicsService from '../../../src/services/global/globalDemographics';
import CommunityDemographicsService from '../../../src/services/ubi/communityDemographics';
import { ManagerAttributes } from '../../../src/database/models/ubi/manager';
import { AppUser } from '../../../src/interfaces/app/appUser';
import { BeneficiaryAttributes } from '../../../src/interfaces/ubi/beneficiary';
import { CommunityAttributes } from '../../../src/interfaces/ubi/community';
import { sequelizeSetup, truncate } from '../../config/sequelizeSetup';
import CommunityFactory from '../../factories/community';
import UserFactory from '../../factories/user';
import ManagerFactory from '../../factories/manager';
import BeneficiaryFactory from '../../factories/beneficiary';
import { models } from '../../../src/database';
const globalDemographicsService = new GlobalDemographicsService();
const communityDemographicsService = new CommunityDemographicsService();
async function waitForStubCall(stub: SinonStub<any, any>, callNumber: number) {
return new Promise((resolve) => {
const validationInterval = setInterval(() => {
if (stub.callCount >= callNumber) {
resolve('');
clearInterval(validationInterval);
}
}, 1000);
});
}
describe('calculate global demographics', () => {
let sequelize: Sequelize;
let users: AppUser[];
let communities: CommunityAttributes[];
let managers: ManagerAttributes[];
let beneficiaries: BeneficiaryAttributes[];
const maxClaim = '450000000000000000000';
let dbGlobalDemographicsInsertStub: SinonStub;
before(async () => {
sequelize = sequelizeSetup();
await sequelize.sync();
const year = new Date().getUTCFullYear();
const ageRange1 = year - 18;
const ageRange2 = year - 25;
const ageRange3 = year - 35;
const ageRange4 = year - 45;
const ageRange5 = year - 55;
const ageRange6 = year - 65;
users = await UserFactory({
n: 7,
props: [
{
gender: 'm',
year: ageRange1
},
{
gender: 'm',
year: ageRange1
},
{
gender: 'f',
year: ageRange2,
},
{
gender: 'f',
year: ageRange3,
},
{
gender: 'f',
year: ageRange4
},
{
gender: 'u',
year: ageRange5
},
{
gender: 'u',
year: ageRange6
}
]
});
communities = await CommunityFactory([
{
requestByAddress: users[0].address,
started: new Date(),
status: 'valid',
visibility: 'public',
contract: {
baseInterval: 60 * 60 * 24,
claimAmount: '1000000000000000000',
communityId: 0,
incrementInterval: 5 * 60,
maxClaim,
},
hasAddress: true,
}
]);
managers = await ManagerFactory([users[0]], communities[0].id);
beneficiaries = await BeneficiaryFactory(
users.slice(0, 7),
communities[0].id
);
dbGlobalDemographicsInsertStub = stub(
globalDemographicsService.globalDemographics,
'bulkCreate'
);
});
after(async () => {
await truncate(sequelize, 'Beneficiary');
await truncate(sequelize);
});
it('calculateDemographics with undisclosed', async () => {
await models.appUser.destroy({
where: { |
await communityDemographicsService.calculate();
await globalDemographicsService.calculate();
await waitForStubCall(dbGlobalDemographicsInsertStub, 1);
assert.callCount(dbGlobalDemographicsInsertStub, 1);
assert.calledWith(dbGlobalDemographicsInsertStub.getCall(0), [{
ageRange1:'1',
ageRange2:'1',
ageRange3:'1',
ageRange4:'1',
ageRange5:'1',
ageRange6:'1',
country: match.any,
date: match.any,
female:'3',
male:'1',
totalGender:'7',
undisclosed:'3',
}]);
});
}); | address: users[0].address
}
}); |
mud.py | import gevent.server
from mud_telnet_handler import MudTelnetHandler
from game_server import GameServer
import argparse
import logging
# Set up logging
log = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("--playerdir", type=str, default="./players", help="Directory where all player data is kept.")
parser.add_argument("--map", type=str, default="mud.map", help="Map file")
parser.add_argument("--port", type=int, default=3000, help="Listening port.")
args = parser.parse_args()
log.info("Mud starting. Params: %s" % args)
# Set up some class vars of MudTelnetHandler
MudTelnetHandler.player_dir = args.playerdir + "/"
MudTelnetHandler.game_server = GameServer(args.map) |
server = gevent.server.StreamServer(("", args.port), MudTelnetHandler.streamserver_handle)
server.serve_forever() |
|
model_radio_fields.rs | use mango_orm::*;
use mango_orm::{migration::Monitor, test_tool::del_test_db};
use metamorphose::Model;
use mongodb::{
bson::{doc, oid::ObjectId},
sync::Client,
};
use serde::{Deserialize, Serialize};
// APP NAME
// #################################################################################################
mod app_name {
use super::*;
// Test application settings
// *********************************************************************************************
pub const PROJECT_NAME: &str = "project_name";
pub const UNIQUE_PROJECT_KEY: &str = "h4xFDD1fTZxvQY3";
pub const SERVICE_NAME: &str = "service_name";
pub const DATABASE_NAME: &str = "database_name";
pub const DB_CLIENT_NAME: &str = "default";
const DB_QUERY_DOCS_LIMIT: u32 = 1000;
// Create models
// *********************************************************************************************
#[Model]
#[derive(Serialize, Deserialize, Default)]
pub struct TestModel {
// text
#[serde(default)]
#[field_attrs(
widget = "radioText",
value = "volvo",
options = r#"[
["volvo","Volvo"],
["saab","Saab"],
["mercedes","Mercedes"],
["audi","Audi"]
]"#
)]
pub radio_text: Option<String>,
// i32
#[serde(default)]
#[field_attrs(
widget = "radioI32",
value = 1,
options = r#"[
[1,"Volvo"],
[2,"Saab"],
[3,"Mercedes"],
[4,"Audi"]
]"#
)]
pub radio_i32: Option<i32>,
// u32
#[serde(default)]
#[field_attrs(
widget = "radioU32",
value = 1,
options = r#"[
[1,"Volvo"],
[2,"Saab"],
[3,"Mercedes"],
[4,"Audi"]
]"#
)]
pub radio_u32: Option<u32>,
// i64
#[serde(default)]
#[field_attrs(
widget = "radioI64",
value = 1,
options = r#"[
[1,"Volvo"],
[2,"Saab"],
[3,"Mercedes"],
[4,"Audi"]
]"#
)]
pub radio_i64: Option<i64>,
// f64
#[serde(default)]
#[field_attrs(
widget = "radioF64",
value = 1.1,
options = r#"[
[1.1,"Volvo"],
[2.2,"Saab"],
[3.3,"Mercedes"],
[4.4,"Audi"]
]"#
)]
pub radio_f64: Option<f64>,
}
// Test migration
// *********************************************************************************************
// Model list
pub fn model_list() -> Result<Vec<Meta>, Box<dyn std::error::Error>> {
Ok(vec![TestModel::meta()?])
}
// Test, migration service `Mango`
pub fn mango_migration() -> Result<(), Box<dyn std::error::Error>> {
// Caching MongoDB clients
MONGODB_CLIENT_STORE.write()?.insert(
"default".to_string(),
mongodb::sync::Client::with_uri_str("mongodb://localhost:27017")?,
);
// Remove test databases
// ( Test databases may remain in case of errors )
del_test_db(PROJECT_NAME, UNIQUE_PROJECT_KEY, &model_list()?)?;
// Migration
let monitor = Monitor {
project_name: PROJECT_NAME,
unique_project_key: UNIQUE_PROJECT_KEY,
// Register models
models: model_list()?,
};
monitor.migrat()?;
// Add metadata and widgects map to cache.
TestModel::to_cache()?;
//
Ok(())
}
}
// TEST
// #################################################################################################
#[test]
fn test_model_radio_fields() -> Result<(), Box<dyn std::error::Error>> {
// ---------------------------------------------------------------------------------------------
app_name::mango_migration()?;
// ^ ^ ^ ---------------------------------------------------------------------------------------
let mut test_model = app_name::TestModel {
// text
radio_text: Some("audi".to_string()),
// i32
radio_i32: Some(4),
// u32
radio_u32: Some(4),
// i64
radio_i64: Some(4),
// f64
radio_f64: Some(4.4),
..Default::default()
};
// Create
// ---------------------------------------------------------------------------------------------
let result = test_model.save(None, None)?;
// Validating create
assert!(result.is_valid(), "{}", result.hash()?);
// Validation of `hash`
assert!(test_model.hash.is_some());
// radio_text
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("audi", map_wigets.get("radio_text").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("volvo", map_wigets.get("radio_text").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["volvo","Volvo"],["saab","Saab"],["mercedes","Mercedes"],["audi","Audi"]]"#
)?,
map_wigets.get("radio_text").unwrap().options
);
// radio_i32
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_i32").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_i32").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_i32").unwrap().options
);
// radio_u32
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_u32").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_u32").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_u32").unwrap().options
);
// radio_i64
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_i64").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_i64").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_i64").unwrap().options
);
// radio_f64
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4.4", map_wigets.get("radio_f64").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1.1", map_wigets.get("radio_f64").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1.1","Volvo"],["2.2","Saab"],["3.3","Mercedes"],["4.4","Audi"]]"#
)?,
map_wigets.get("radio_f64").unwrap().options
);
// Validating values in database
{
let form_store = FORM_STORE.read()?;
let client_store = MONGODB_CLIENT_STORE.read()?;
let form_cache: &FormCache = form_store.get(&app_name::TestModel::key()[..]).unwrap();
let meta: &Meta = &form_cache.meta;
let client: &Client = client_store.get(meta.db_client_name.as_str()).unwrap(); | let filter = doc! {"_id": object_id};
assert_eq!(1_i64, coll.count_documents(None, None)?);
let doc = coll.find_one(filter, None)?.unwrap();
// text
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_text"));
assert_eq!("audi", doc.get_str("radio_text")?);
// i32
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_i32"));
assert_eq!(4, doc.get_i32("radio_i32")?);
// u32
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_u32"));
assert_eq!(4, doc.get_i64("radio_u32")?);
// i64
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_i64"));
assert_eq!(4, doc.get_i64("radio_i64")?);
// f64
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_f64"));
assert_eq!(4.4, doc.get_f64("radio_f64")?);
}
// Update
// ---------------------------------------------------------------------------------------------
let tmp_hash = test_model.hash.clone().unwrap();
let result = test_model.save(None, None)?;
// Validating create
assert!(result.is_valid(), "{}", result.hash()?);
// Validation of `hash`
assert!(test_model.hash.is_some());
assert_eq!(tmp_hash, test_model.hash.clone().unwrap());
// radio_text
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("audi", map_wigets.get("radio_text").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("volvo", map_wigets.get("radio_text").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["volvo","Volvo"],["saab","Saab"],["mercedes","Mercedes"],["audi","Audi"]]"#
)?,
map_wigets.get("radio_text").unwrap().options
);
// radio_i32
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_i32").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_i32").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_i32").unwrap().options
);
// radio_u32
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_u32").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_u32").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_u32").unwrap().options
);
// radio_i64
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4", map_wigets.get("radio_i64").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1", map_wigets.get("radio_i64").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1","Volvo"],["2","Saab"],["3","Mercedes"],["4","Audi"]]"#
)?,
map_wigets.get("radio_i64").unwrap().options
);
// radio_f64
// ---------------------------------------------------------------------------------------------
let map_wigets = result.wig();
assert_eq!("4.4", map_wigets.get("radio_f64").unwrap().value);
let map_wigets = app_name::TestModel::form_wig()?;
assert_eq!("1.1", map_wigets.get("radio_f64").unwrap().value);
assert_eq!(
serde_json::from_str::<Vec<(String, String)>>(
r#"[["1.1","Volvo"],["2.2","Saab"],["3.3","Mercedes"],["4.4","Audi"]]"#
)?,
map_wigets.get("radio_f64").unwrap().options
);
// Validating values in database
{
let form_store = FORM_STORE.read()?;
let client_store = MONGODB_CLIENT_STORE.read()?;
let form_cache: &FormCache = form_store.get(&app_name::TestModel::key()[..]).unwrap();
let meta: &Meta = &form_cache.meta;
let client: &Client = client_store.get(meta.db_client_name.as_str()).unwrap();
let object_id = ObjectId::with_string(test_model.hash.clone().unwrap().as_str())?;
let coll = client
.database(meta.database_name.as_str())
.collection(meta.collection_name.as_str());
let filter = doc! {"_id": object_id};
assert_eq!(1_i64, coll.count_documents(None, None)?);
let doc = coll.find_one(filter, None)?.unwrap();
// text
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_text"));
assert_eq!("audi", doc.get_str("radio_text")?);
// i32
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_i32"));
assert_eq!(4, doc.get_i32("radio_i32")?);
// u32
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_u32"));
assert_eq!(4, doc.get_i64("radio_u32")?);
// i64
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_i64"));
assert_eq!(4, doc.get_i64("radio_i64")?);
// f64
// -----------------------------------------------------------------------------------------
assert!(!doc.is_null("radio_f64"));
assert_eq!(4.4, doc.get_f64("radio_f64")?);
}
// ---------------------------------------------------------------------------------------------
del_test_db(
app_name::PROJECT_NAME,
app_name::UNIQUE_PROJECT_KEY,
&app_name::model_list()?,
)?;
// ^ ^ ^ ---------------------------------------------------------------------------------------
Ok(())
} | let object_id = ObjectId::with_string(test_model.hash.clone().unwrap().as_str())?;
let coll = client
.database(meta.database_name.as_str())
.collection(meta.collection_name.as_str()); |
stdio.rs | // Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use pyo3::buffer::PyBuffer;
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
/// A Python file-like that proxies to the `stdio` module, which implements thread-local input.
#[pyclass]
pub struct PyStdioRead;
#[pymethods]
impl PyStdioRead {
fn isatty(&self) -> bool {
if let Ok(fd) = self.fileno() {
unsafe { libc::isatty(fd) != 0 }
} else {
false
}
}
fn fileno(&self) -> PyResult<i32> {
stdio::get_destination()
.stdin_as_raw_fd()
.map_err(PyException::new_err)
}
fn readinto(&self, obj: &PyAny, py: Python) -> PyResult<usize> {
let py_buffer = PyBuffer::get(obj)?;
let mut buffer = vec![0; py_buffer.len_bytes() as usize];
let read = py
.allow_threads(|| stdio::get_destination().read_stdin(&mut buffer))
.map_err(|e| PyException::new_err(e.to_string()))?;
// NB: `as_mut_slice` exposes a `&[Cell<u8>]`, which we can't use directly in `read`. We use
// `copy_from_slice` instead, which unfortunately involves some extra copying.
py_buffer.copy_from_slice(py, &buffer)?;
Ok(read)
}
#[getter]
fn closed(&self) -> bool {
false
}
fn readable(&self) -> bool |
fn seekable(&self) -> bool {
false
}
}
/// A Python file-like that proxies to the `stdio` module, which implements thread-local output.
#[pyclass]
pub struct PyStdioWrite {
pub(crate) is_stdout: bool,
}
#[pymethods]
impl PyStdioWrite {
fn write(&self, payload: &str, py: Python) {
py.allow_threads(|| {
let destination = stdio::get_destination();
if self.is_stdout {
destination.write_stdout(payload.as_bytes());
} else {
destination.write_stderr(payload.as_bytes());
}
});
}
fn isatty(&self) -> bool {
if let Ok(fd) = self.fileno() {
unsafe { libc::isatty(fd) != 0 }
} else {
false
}
}
fn fileno(&self) -> PyResult<i32> {
let destination = stdio::get_destination();
let fd = if self.is_stdout {
destination.stdout_as_raw_fd()
} else {
destination.stderr_as_raw_fd()
};
fd.map_err(PyException::new_err)
}
fn flush(&self) {
// All of our destinations are line-buffered.
}
}
| {
true
} |
projects.py | #!/usr/bin/env python3
#
# Copyright (c) 2019 Roberto Riggio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Projects CLI tools."""
import uuid
import argparse
import empower.cli.command as command
from empower.core.plmnid import PLMNID
from empower.core.ssid import SSID
def pa_delete_project(args, cmd):
"""Delete project parser method. """
usage = "%s <options>" % command.USAGE.format(cmd)
desc = command.DESCS[cmd]
parser = argparse.ArgumentParser(usage=usage, description=desc)
required = parser.add_argument_group('required named arguments')
required.add_argument('-p', '--project_id', help='The project id',
required=True, type=uuid.UUID)
(args, leftovers) = parser.parse_known_args(args)
return args, leftovers
def do_delete_project(gargs, args, _):
"""Delete a project. """
url = '/api/v1/projects/%s' % args.project_id
command.connect(gargs, ('DELETE', url), 204)
print(args.project_id)
def pa_create_project(args, cmd):
"""Create project parser method. """
usage = "%s <options>" % command.USAGE.format(cmd)
desc = command.DESCS[cmd]
parser = argparse.ArgumentParser(usage=usage, description=desc)
required = parser.add_argument_group('required named arguments')
required.add_argument('-d', '--desc', help='The project description',
required=True, type=str, dest="desc")
required.add_argument('-o', '--owner', help='The project owner',
required=True, type=str, dest="owner")
parser.add_argument("-c", "--mcc", dest="mcc", default=None,
help="The network MCC; default=None",
type=str)
parser.add_argument("-n", "--mnc", dest="mcc", default=None,
help="The network MNC; default=None",
type=str)
parser.add_argument("-s", "--ssid", dest="ssid", default=None,
help="The network SSID; default=None",
type=SSID)
parser.add_argument("-t", "--ssid_type", dest="ssid_type",
default="unique", choices=["unique", "shared"],
help="The network SSID type; default=unique")
(args, leftovers) = parser.parse_known_args(args)
return args, leftovers
def do_create_project(gargs, args, _):
""" Add a new Project """
request = {
"version": "1.0",
"desc": args.desc,
"owner": args.owner
}
if args.ssid:
request["wifi_props"] = {
"bssid_type": args.ssid_type,
"ssid": args.ssid
}
if args.mcc and args.mnc:
plmnid = PLMNID(args.mcc, args.mnc)
request["lte_props"] = {
"plmnid": plmnid.to_dict()
}
headers = command.get_headers(gargs)
url = '/api/v1/projects'
response, _ = command.connect(gargs, ('POST', url), 201, request,
headers=headers)
location = response.headers['Location']
tokens = location.split("/")
project_id = tokens[-1]
print(project_id)
def do_list_projects(gargs, *_):
| """List currently running workers. """
_, data = command.connect(gargs, ('GET', '/api/v1/projects'), 200)
for entry in data.values():
accum = []
accum.append("project_id ")
accum.append(entry['project_id'])
accum.append(" desc \"%s\"" % entry['desc'])
if 'wifi_props' in entry and entry['wifi_props']:
accum.append(" ssid \"%s\"" % entry['wifi_props']['ssid'])
if 'lte_props' in entry and entry['lte_props']:
accum.append(" plmnid \"%s\"" % entry['lte_props']['plmnid'])
print(''.join(accum)) |
|
utils.py | """
.. module:: utils
:synopsis: Miscellaneous helper constructs
.. moduleauthor:: Steven Silvester <[email protected]>
"""
import os
import inspect
import dis
import tempfile
import sys
from .compat import PY2
def _remove_temp_files(dirname):
"""
Remove the created mat files in the user's temp folder
"""
import os
import glob
for fname in glob.glob(os.path.join(dirname, 'tmp*.mat')):
try:
os.remove(fname)
except OSError: # pragma: no cover
pass
def get_nout():
"""
Return the number of return values the caller is expecting.
Adapted from the ompc project.
Returns
=======
out : int
Number of arguments expected by caller.
"""
frame = inspect.currentframe()
# step into the function that called us
# nout is two frames back
frame = frame.f_back.f_back
bytecode = frame.f_code.co_code
if sys.version_info >= (3, 6):
instruction = bytecode[frame.f_lasti + 2]
else:
instruction = bytecode[frame.f_lasti + 3]
instruction = ord(instruction) if PY2 else instruction
if instruction == dis.opmap['UNPACK_SEQUENCE']:
if sys.version_info >= (3, 6):
howmany = bytecode[frame.f_lasti + 3]
else:
howmany = bytecode[frame.f_lasti + 4]
howmany = ord(howmany) if PY2 else howmany
return howmany
elif instruction in [dis.opmap['POP_TOP'], dis.opmap['PRINT_EXPR']]:
return 0
return 1
def create_file(temp_dir):
"""
Create a MAT file with a random name in the temp directory
Parameters
==========
temp_dir : str, optional
If specified, the file will be created in that directory,
otherwise a default directory is used.
Returns
=======
out : str
Random file name with the desired extension
"""
temp_file = tempfile.NamedTemporaryFile(suffix='.mat', delete=False,
dir=temp_dir)
temp_file.close()
return os.path.abspath(temp_file.name)
class Scilab2PyError(Exception):
|
class Struct(dict):
"""
Scilab style struct, enhanced.
Supports dictionary and attribute style access. Can be pickled,
and supports code completion in a REPL.
Examples
========
>>> from pprint import pprint
>>> from scilab2py import Struct
>>> a = Struct()
>>> a.b = 'spam' # a["b"] == 'spam'
>>> a.c["d"] = 'eggs' # a.c.d == 'eggs'
>>> pprint(a)
{'b': 'spam', 'c': {'d': 'eggs'}}
"""
def __getattr__(self, attr):
"""Access the dictionary keys for unknown attributes."""
try:
return self[attr]
except KeyError:
msg = "'Struct' object has no attribute %s" % attr
raise AttributeError(msg)
def __getitem__(self, attr):
"""
Get a dict value; create a Struct if requesting a Struct member.
Do not create a key if the attribute starts with an underscore.
"""
if attr in self.keys() or attr.startswith('_'):
return dict.__getitem__(self, attr)
frame = inspect.currentframe()
# step into the function that called us
if frame.f_back.f_back and self._is_allowed(frame.f_back.f_back):
dict.__setitem__(self, attr, Struct())
elif self._is_allowed(frame.f_back):
dict.__setitem__(self, attr, Struct())
return dict.__getitem__(self, attr)
def _is_allowed(self, frame):
"""Check for allowed op code in the calling frame"""
allowed = [dis.opmap['STORE_ATTR'], dis.opmap['LOAD_CONST'],
dis.opmap.get('STOP_CODE', 0)]
bytecode = frame.f_code.co_code
instruction = bytecode[frame.f_lasti + 3]
instruction = ord(instruction) if PY2 else instruction
return instruction in allowed
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
@property
def __dict__(self):
"""Allow for code completion in a REPL"""
return self.copy()
def get_log(name=None):
"""Return a console logger.
Output may be sent to the logger using the `debug`, `info`, `warning`,
`error` and `critical` methods.
Parameters
----------
name : str
Name of the log.
References
----------
.. [1] Logging facility for Python,
http://docs.python.org/library/logging.html
"""
import logging
if name is None:
name = 'scilab2py'
else:
name = 'scilab2py.' + name
log = logging.getLogger(name)
log.setLevel(logging.WARN)
return log
def _setup_log():
"""Configure root logger.
"""
import logging
import sys
try:
handler = logging.StreamHandler(stream=sys.stdout)
except TypeError: # pragma: no cover
handler = logging.StreamHandler(strm=sys.stdout)
log = get_log()
log.addHandler(handler)
log.setLevel(logging.WARN)
log.propagate = False
_setup_log()
| """ Called when we can't open Scilab or Scilab throws an error
"""
pass |
Menu.tsx | import React, { FC } from 'react';
import './menu.scss';
interface IMenuProps {
menuItems: Array<{ name: string; active: boolean }>;
menuSelected: number;
menuClick: (menuNumber: number) => void;
}
const Menu: FC<IMenuProps> = (props) => {
const renderMenuItems = () => {
return props.menuItems.map((item, index) => {
const handleMenuClick = () => {
props.menuClick(index);
};
return (
<MenuItem
key={item.name + item.active}
isActive={props.menuSelected === index}
menuClick={handleMenuClick}
| />
);
});
};
return <div className='mainMenuWrapper'>{renderMenuItems()}</div>;
};
interface IMenuItemProps {
label: string;
isActive: boolean;
menuClick: () => void;
}
const MenuItem: FC<IMenuItemProps> = (props) => {
const classes = props.isActive ? 'mainMenuItem mainMenuItemActive' : 'mainMenuItem';
return (
<div onClick={props.menuClick} className={classes}>
{props.label}
</div>
);
};
export default Menu; | label={item.name}
|
sampling_events.py | from rest_framework.permissions import BasePermission
class IsCreator(BasePermission):
def has_object_permission(self, request, view, obj):
user = request.user
creator = obj.created_by
return user == creator
class HasChangePermissions(BasePermission):
def has_object_permission(self, request, view, obj):
user = request.user
collection = obj.collection
return collection.has_permission(
user, 'change_collection_sampling_events')
class HasViewPermissions(BasePermission):
def has_object_permission(self, request, view, obj):
user = request.user
collection = obj.collection
return collection.has_permission(
user, 'view_collection_sampling_events')
class IsCollectionAdmin(BasePermission):
def has_object_permission(self, request, view, obj):
user = request.user
collection = obj.collection
return collection.is_admin(user)
class IsCollectionTypeAdmin(BasePermission):
def has_object_permission(self, request, view, obj):
|
class HasViewItemsPermissions(BasePermission):
def has_object_permission(self, request, view, obj):
user = request.user
collection = obj.collection
return collection.has_permission(
user, 'view_collection_item')
| user = request.user
collection = obj.collection
collection_type = collection.collection_type
return collection_type.is_admin(user) |
button.go | package main
import (
"github.com/reiver/cyber80/os/log"
"github.com/reiver/cyber80/os/webbed"
"syscall/js"
)
const (
// This should be the ‘id’ on the <button> element in the HTML code.
buttonMagicID = "magic256-run"
)
var (
button js.Value
)
func init() {
b | utton = webbed.Document.Call("getElementById", buttonMagicID)
if button.IsNull() {
log.Panic("ERROR: ‘button’ is null")
return
}
if button.IsUndefined() {
log.Panic("ERROR: ‘button’ is undefined")
return
}
button.Call("addEventListener", "click", js.FuncOf(run))
}
|
|
history.constant.ts | export const HISTORY_ITEMS_PER_PAGE = 20; |
||
trivial.rs | use crate::prelude::*;
use std::marker::PhantomData;
/// Creates an observable that emits no items, just terminates with an error.
///
/// # Arguments
///
/// * `e` - An error to emit and terminate with
pub fn | <Err>(e: Err) -> ObservableBase<ThrowEmitter<Err>> {
ObservableBase::new(ThrowEmitter(e))
}
#[derive(Clone)]
pub struct ThrowEmitter<Err>(Err);
#[doc(hidden)]
macro throw_emitter($subscription:ty, $($marker:ident +)* $lf: lifetime) {
#[inline]
fn emit<O>(self, mut subscriber: Subscriber<O, $subscription>)
where
O: Observer<Self::Item, Self::Err> + $($marker +)* $lf
{
subscriber.error(self.0);
}
}
impl<Err> Emitter for ThrowEmitter<Err> {
type Item = ();
type Err = Err;
}
impl<'a, Err> LocalEmitter<'a> for ThrowEmitter<Err> {
throw_emitter!(LocalSubscription, 'a);
}
impl<Err> SharedEmitter for ThrowEmitter<Err> {
throw_emitter!(SharedSubscription, Send + Sync + 'static);
}
/// Creates an observable that produces no values.
///
/// Completes immediately. Never emits an error.
///
/// # Examples
/// ```
/// use rxrust::prelude::*;
///
/// observable::empty()
/// .subscribe(|v: &i32| {println!("{},", v)});
///
/// // Result: no thing printed
/// ```
pub fn empty<Item>() -> ObservableBase<EmptyEmitter<Item>> {
ObservableBase::new(EmptyEmitter(PhantomData))
}
#[derive(Clone)]
pub struct EmptyEmitter<Item>(PhantomData<Item>);
#[doc(hidden)]
macro empty_emitter($subscription:ty, $($marker:ident +)* $lf: lifetime) {
#[inline]
fn emit<O>(self, mut subscriber: Subscriber<O, $subscription>)
where
O: Observer<Self::Item, Self::Err> + $($marker +)* $lf
{
subscriber.complete();
}
}
impl<Item> Emitter for EmptyEmitter<Item> {
type Item = Item;
type Err = ();
}
impl<'a, Item> LocalEmitter<'a> for EmptyEmitter<Item> {
empty_emitter!(LocalSubscription, 'a);
}
impl<Item> SharedEmitter for EmptyEmitter<Item> {
empty_emitter!(SharedSubscription, Send + Sync + 'static);
}
/// Creates an observable that never emits anything.
///
/// Neither emits a value, nor completes, nor emits an error.
pub fn never() -> ObservableBase<NeverEmitter> {
ObservableBase::new(NeverEmitter())
}
#[derive(Clone)]
pub struct NeverEmitter();
#[doc(hidden)]
macro never_emitter($subscription:ty, $($marker:ident +)* $lf: lifetime) {
#[inline]
fn emit<O>(self, subscriber: Subscriber<O, $subscription>)
where
O: Observer<Self::Item, Self::Err> + $($marker +)* $lf
{
}
}
impl Emitter for NeverEmitter {
type Item = ();
type Err = ();
}
impl<'a> LocalEmitter<'a> for NeverEmitter {
#[inline]
never_emitter!(LocalSubscription, 'a);
}
impl SharedEmitter for NeverEmitter {
#[inline]
never_emitter!(SharedSubscription, Send + Sync + 'static);
}
#[cfg(test)]
mod test {
use crate::prelude::*;
#[test]
fn throw() {
let mut value_emitted = false;
let mut completed = false;
let mut error_emitted = String::new();
observable::throw(String::from("error")).subscribe_all(
// helping with type inference
|_| value_emitted = true,
|e| error_emitted = e,
|| completed = true,
);
assert!(!value_emitted);
assert!(!completed);
assert_eq!(error_emitted, "error");
}
#[test]
fn empty() {
let mut hits = 0;
let mut completed = false;
observable::empty().subscribe_complete(|()| hits += 1, || completed = true);
assert_eq!(hits, 0);
assert_eq!(completed, true);
}
}
| throw |
data_augmentor.py | from functools import partial
import torch
import random
import numpy as np
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...utils import common_utils, box_utils
from . import augmentor_utils, database_sampler
class DataAugmentor(object):
def __init__(self, root_path, augmentor_configs, class_names, logger=None):
self.root_path = root_path
self.class_names = class_names
self.logger = logger
self.data_augmentor_queue = []
aug_config_list = augmentor_configs if isinstance(augmentor_configs, list) \
else augmentor_configs.AUG_CONFIG_LIST
for cur_cfg in aug_config_list:
if not isinstance(augmentor_configs, list):
if cur_cfg.NAME in augmentor_configs.DISABLE_AUG_LIST:
continue
cur_augmentor = getattr(self, cur_cfg.NAME)(config=cur_cfg)
self.data_augmentor_queue.append(cur_augmentor)
def gt_sampling(self, config=None):
db_sampler = database_sampler.DataBaseSampler(
root_path=self.root_path,
sampler_cfg=config,
class_names=self.class_names,
logger=self.logger
)
return db_sampler
def __getstate__(self):
d = dict(self.__dict__)
del d['logger']
return d
def __setstate__(self, d):
self.__dict__.update(d)
def object_size_normalization(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.object_size_normalization, config=config)
gt_boxes, points = data_dict['gt_boxes'], data_dict['points']
if gt_boxes.shape[1] > 7:
gt_boxes = gt_boxes[:,:7]
offset = np.array(config['OFFSET'])
# get masks of points inside boxes
point_masks = roiaware_pool3d_utils.points_in_boxes_cpu(
torch.from_numpy(points[:, 0:3]), torch.from_numpy(gt_boxes)).numpy()
num_obj = gt_boxes.shape[0]
obj_points_list = []
gt_boxes_size = gt_boxes[:, 3:6]
new_gt_boxes_size = gt_boxes_size + offset
scale_factor = new_gt_boxes_size / gt_boxes_size
# scale the objects
for i in range(num_obj):
point_mask = point_masks[i]
obj_points = points[point_mask > 0] # get object points within the gt box
obj_points[:, :3] -= gt_boxes[i, :3] # relative to box center
obj_points[:, :3] *= scale_factor[i] # scale
obj_points[:, :3] += gt_boxes[i, :3] # back to global coordinate
obj_points_list.append(obj_points)
# remove points inside boxes
points = box_utils.remove_points_in_boxes3d(points, gt_boxes)
# scale the boxes
gt_boxes[:, 3:6] *= scale_factor
# remove points inside boxes
points = box_utils.remove_points_in_boxes3d(points, gt_boxes)
# merge points
# points = box_utils.remove_points_in_boxes3d(points, gt_boxes)
obj_points = np.concatenate(obj_points_list, axis=0)
points = np.concatenate([points, obj_points], axis=0)
data_dict['points'] = points
data_dict['gt_boxes'][:,:7] = gt_boxes
return data_dict
def random_world_flip(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.random_world_flip, config=config)
gt_boxes = data_dict['gt_boxes'] if 'gt_boxes' in data_dict else None
points = data_dict['points']
for cur_axis in config['ALONG_AXIS_LIST']:
assert cur_axis in ['x', 'y']
if 'gt_boxes' in data_dict:
gt_boxes, points, world_flip_enabled = getattr(augmentor_utils, 'random_flip_along_%s' % cur_axis)(
gt_boxes, points, return_enable=True
)
else:
points, world_flip_enabled = getattr(augmentor_utils, 'random_flip_along_%s_points' % cur_axis)(
points, return_enable=True
)
if 'gt_boxes' in data_dict:
data_dict['gt_boxes'] = gt_boxes
data_dict['points'] = points
data_dict['world_flip_enabled'] = world_flip_enabled
return data_dict
def random_world_rotation(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.random_world_rotation, config=config)
rot_range = config['WORLD_ROT_ANGLE']
if not isinstance(rot_range, list):
rot_range = [-rot_range, rot_range]
if 'gt_boxes' in data_dict:
gt_boxes, points, world_rotation = augmentor_utils.global_rotation(
data_dict['gt_boxes'], data_dict['points'], rot_range=rot_range, return_rotation=True
)
else:
points, world_rotation = augmentor_utils.global_rotation_points(
data_dict['points'], rot_range=rot_range, return_rotation=True
)
if 'gt_boxes' in data_dict:
data_dict['gt_boxes'] = gt_boxes
data_dict['points'] = points
data_dict['world_rotation'] = world_rotation
return data_dict
def random_world_scaling(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.random_world_scaling, config=config)
if 'gt_boxes' in data_dict:
gt_boxes, points, scale_ratio = augmentor_utils.global_scaling(
data_dict['gt_boxes'], data_dict['points'], config['WORLD_SCALE_RANGE']
)
else:
points, scale_ratio = augmentor_utils.global_scaling_points(data_dict['points'], config['WORLD_SCALE_RANGE'])
data_dict['world_scaling'] = scale_ratio
if 'gt_boxes' in data_dict:
data_dict['gt_boxes'] = gt_boxes
data_dict['points'] = points
return data_dict
def random_world_scaling_xyz(self, data_dict=None, config=None):
|
def jitter_point_cloud(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.jitter_point_cloud, config=config)
sigma = config['SIGMA']
clip = config['CLIP']
assert(clip > 0)
points = data_dict['points']
jittered_data = np.clip(sigma * np.random.randn(points.shape[0], points.shape[1]), -1*clip, clip)
points += jittered_data
data_dict['points'] = points
data_dict['jittered'] = True
data_dict['jitter_values'] = jittered_data
return data_dict
def random_world_shift(self, data_dict=None, config=None):
if data_dict is None:
return partial(self.random_world_shift, config=config)
shift_range = config['RANGE']
shifts = np.random.uniform(-shift_range, shift_range, 3)
data_dict['points'] += shifts
data_dict['world_shifts'] = shifts
return data_dict
def forward(self, data_dict, augment=True):
"""
Args:
data_dict:
points: (N, 3 + C_in)
gt_boxes: optional, (N, 7) [x, y, z, dx, dy, dz, heading]
gt_names: optional, (N), string
...
Returns:
"""
if augment:
for cur_augmentor in self.data_augmentor_queue:
data_dict = cur_augmentor(data_dict=data_dict)
if 'gt_boxes' in data_dict:
data_dict['gt_boxes'][:, 6] = common_utils.limit_period(
data_dict['gt_boxes'][:, 6], offset=0.5, period=2 * np.pi
)
if 'road_plane' in data_dict:
data_dict.pop('road_plane')
if 'gt_boxes' in data_dict and 'gt_boxes_mask' in data_dict:
gt_boxes_mask = data_dict['gt_boxes_mask']
data_dict['gt_boxes'] = data_dict['gt_boxes'][gt_boxes_mask]
data_dict['gt_names'] = data_dict['gt_names'][gt_boxes_mask]
data_dict.pop('gt_boxes_mask')
return data_dict
| if data_dict is None:
return partial(self.random_world_scaling_xyz, config=config)
gt_boxes = data_dict['gt_boxes']
points = data_dict['points']
scale_range = config['SCALE_RANGE']
noise_scale = np.random.uniform(scale_range[0], scale_range[1], 3)
points[:, :3] *= noise_scale
gt_boxes[:, :3] *= noise_scale
gt_boxes[:, 3:6] *= noise_scale
data_dict['points'] = points
data_dict['gt_boxes'] = gt_boxes
data_dict['world_scaling_xyz'] = noise_scale
return data_dict |
aggregate.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Physical exec for aggregate window function expressions.
use crate::error::{DataFusionError, Result};
use crate::logical_plan::window_frames::{WindowFrame, WindowFrameUnits};
use crate::physical_plan::windows::find_ranges_in_range;
use crate::physical_plan::{
expressions::PhysicalSortExpr, Accumulator, AggregateExpr, PhysicalExpr, WindowExpr,
};
use arrow::compute::concat;
use arrow::record_batch::RecordBatch;
use arrow::{array::ArrayRef, datatypes::Field};
use std::any::Any;
use std::iter::IntoIterator;
use std::ops::Range;
use std::sync::Arc;
/// A window expr that takes the form of an aggregate function
#[derive(Debug)]
pub struct AggregateWindowExpr {
aggregate: Arc<dyn AggregateExpr>,
partition_by: Vec<Arc<dyn PhysicalExpr>>,
order_by: Vec<PhysicalSortExpr>,
window_frame: Option<WindowFrame>,
}
impl AggregateWindowExpr {
/// create a new aggregate window function expression
pub(super) fn new(
aggregate: Arc<dyn AggregateExpr>,
partition_by: &[Arc<dyn PhysicalExpr>],
order_by: &[PhysicalSortExpr],
window_frame: Option<WindowFrame>,
) -> Self {
Self {
aggregate,
partition_by: partition_by.to_vec(),
order_by: order_by.to_vec(),
window_frame,
}
}
/// the aggregate window function operates based on window frame, and by default the mode is
/// "range".
fn evaluation_mode(&self) -> WindowFrameUnits {
self.window_frame.unwrap_or_default().units
}
/// create a new accumulator based on the underlying aggregation function
fn create_accumulator(&self) -> Result<AggregateWindowAccumulator> {
let accumulator = self.aggregate.create_accumulator()?;
Ok(AggregateWindowAccumulator { accumulator })
}
/// peer based evaluation based on the fact that batch is pre-sorted given the sort columns
/// and then per partition point we'll evaluate the peer group (e.g. SUM or MAX gives the same
/// results for peers) and concatenate the results.
fn peer_based_evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
let num_rows = batch.num_rows();
let partition_points =
self.evaluate_partition_points(num_rows, &self.partition_columns(batch)?)?; | self.evaluate_partition_points(num_rows, &self.sort_columns(batch)?)?;
let values = self.evaluate_args(batch)?;
let results = partition_points
.iter()
.map(|partition_range| {
let sort_partition_points =
find_ranges_in_range(partition_range, &sort_partition_points);
let mut window_accumulators = self.create_accumulator()?;
sort_partition_points
.iter()
.map(|range| window_accumulators.scan_peers(&values, range))
.collect::<Result<Vec<_>>>()
})
.collect::<Result<Vec<Vec<ArrayRef>>>>()?
.into_iter()
.flatten()
.collect::<Vec<ArrayRef>>();
let results = results.iter().map(|i| i.as_ref()).collect::<Vec<_>>();
concat(&results).map_err(DataFusionError::ArrowError)
}
fn group_based_evaluate(&self, _batch: &RecordBatch) -> Result<ArrayRef> {
Err(DataFusionError::NotImplemented(format!(
"Group based evaluation for {} is not yet implemented",
self.name()
)))
}
fn row_based_evaluate(&self, _batch: &RecordBatch) -> Result<ArrayRef> {
Err(DataFusionError::NotImplemented(format!(
"Row based evaluation for {} is not yet implemented",
self.name()
)))
}
}
impl WindowExpr for AggregateWindowExpr {
/// Return a reference to Any that can be used for downcasting
fn as_any(&self) -> &dyn Any {
self
}
fn name(&self) -> &str {
self.aggregate.name()
}
fn field(&self) -> Result<Field> {
self.aggregate.field()
}
fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.aggregate.expressions()
}
fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>] {
&self.partition_by
}
fn order_by(&self) -> &[PhysicalSortExpr] {
&self.order_by
}
/// evaluate the window function values against the batch
fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
match self.evaluation_mode() {
WindowFrameUnits::Range => self.peer_based_evaluate(batch),
WindowFrameUnits::Rows => self.row_based_evaluate(batch),
WindowFrameUnits::Groups => self.group_based_evaluate(batch),
}
}
}
/// Aggregate window accumulator utilizes the accumulator from aggregation and do a accumulative sum
/// across evaluation arguments based on peer equivalences.
#[derive(Debug)]
struct AggregateWindowAccumulator {
accumulator: Box<dyn Accumulator>,
}
impl AggregateWindowAccumulator {
/// scan one peer group of values (as arguments to window function) given by the value_range
/// and return evaluation result that are of the same number of rows.
fn scan_peers(
&mut self,
values: &[ArrayRef],
value_range: &Range<usize>,
) -> Result<ArrayRef> {
if value_range.is_empty() {
return Err(DataFusionError::Internal(
"Value range cannot be empty".to_owned(),
));
}
let len = value_range.end - value_range.start;
let values = values
.iter()
.map(|v| v.slice(value_range.start, len))
.collect::<Vec<_>>();
self.accumulator.update_batch(&values)?;
let value = self.accumulator.evaluate()?;
Ok(value.to_array_of_size(len))
}
} | let sort_partition_points = |
u_char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Unicode-intensive `char` methods.
*
* These methods implement functionality for `char` that requires knowledge of
* Unicode definitions, including normalization, categorization, and display information.
*/
use core::option::Option;
use tables::{derived_property, property, general_category, conversions, charwidth};
/// Returns whether the specified `char` is considered a Unicode alphabetic
/// code point
pub fn is_alphabetic(c: char) -> bool {
match c {
'a' ... 'z' | 'A' ... 'Z' => true,
c if c > '\x7f' => derived_property::Alphabetic(c),
_ => false
}
}
/// Returns whether the specified `char` satisfies the 'XID_Start' Unicode property
///
/// 'XID_Start' is a Unicode Derived Property specified in
/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
/// mostly similar to ID_Start but modified for closure under NFKx.
#[allow(non_snake_case)]
pub fn is_XID_start(c: char) -> bool { derived_property::XID_Start(c) }
/// Returns whether the specified `char` satisfies the 'XID_Continue' Unicode property
///
/// 'XID_Continue' is a Unicode Derived Property specified in
/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
/// mostly similar to 'ID_Continue' but modified for closure under NFKx.
#[allow(non_snake_case)]
pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) }
///
/// Indicates whether a `char` is in lower case
///
/// This is defined according to the terms of the Unicode Derived Core Property 'Lowercase'.
///
#[inline]
pub fn is_lowercase(c: char) -> bool {
match c {
'a' ... 'z' => true,
c if c > '\x7f' => derived_property::Lowercase(c),
_ => false
}
}
///
/// Indicates whether a `char` is in upper case
///
/// This is defined according to the terms of the Unicode Derived Core Property 'Uppercase'.
///
#[inline]
pub fn is_uppercase(c: char) -> bool {
match c {
'A' ... 'Z' => true,
c if c > '\x7f' => derived_property::Uppercase(c),
_ => false
}
}
///
/// Indicates whether a `char` is whitespace
///
/// Whitespace is defined in terms of the Unicode Property 'White_Space'.
///
#[inline]
pub fn is_whitespace(c: char) -> bool {
match c {
' ' | '\x09' ... '\x0d' => true,
c if c > '\x7f' => property::White_Space(c),
_ => false
}
}
///
/// Indicates whether a `char` is alphanumeric
///
/// Alphanumericness is defined in terms of the Unicode General Categories
/// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
///
#[inline]
pub fn is_alphanumeric(c: char) -> bool {
is_alphabetic(c)
|| is_digit(c)
}
///
/// Indicates whether a `char` is a control code point
///
/// Control code points are defined in terms of the Unicode General Category
/// 'Cc'.
///
#[inline]
pub fn is_control(c: char) -> bool { general_category::Cc(c) }
/// Indicates whether the `char` is numeric (Nd, Nl, or No)
#[inline]
pub fn is_digit(c: char) -> bool {
match c {
'0' ... '9' => true,
c if c > '\x7f' => general_category::N(c),
_ => false
}
}
/// Convert a char to its uppercase equivalent
///
/// The case-folding performed is the common or simple mapping:
/// it maps one Unicode codepoint (one char in Rust) to its uppercase equivalent according
/// to the Unicode database at ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
/// The additional SpecialCasing.txt is not considered here, as it expands to multiple
/// codepoints in some cases.
///
/// A full reference can be found here
/// http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
///
/// # Return value
///
/// Returns the char itself if no conversion was made
#[inline]
pub fn to_uppercase(c: char) -> char {
conversions::to_upper(c)
}
/// Convert a char to its lowercase equivalent
///
/// The case-folding performed is the common or simple mapping
/// see `to_uppercase` for references and more information
///
/// # Return value
///
/// Returns the char itself if no conversion if possible
#[inline]
pub fn to_lowercase(c: char) -> char {
conversions::to_lower(c)
}
/// Returns this character's displayed width in columns, or `None` if it is a
/// control character other than `'\x00'`.
///
/// `is_cjk` determines behavior for characters in the Ambiguous category:
/// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
/// In CJK contexts, `is_cjk` should be `true`, else it should be `false`.
/// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
/// recommends that these characters be treated as 1 column (i.e.,
/// `is_cjk` = `false`) if the context cannot be reliably determined.
pub fn width(c: char, is_cjk: bool) -> Option<uint> {
charwidth::width(c, is_cjk)
}
/// Useful functions for Unicode characters.
pub trait UnicodeChar {
/// Returns whether the specified character is considered a Unicode
/// alphabetic code point.
fn is_alphabetic(&self) -> bool;
/// Returns whether the specified character satisfies the 'XID_Start'
/// Unicode property.
///
/// 'XID_Start' is a Unicode Derived Property specified in
/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
/// mostly similar to ID_Start but modified for closure under NFKx.
#[allow(non_snake_case)]
fn is_XID_start(&self) -> bool;
/// Returns whether the specified `char` satisfies the 'XID_Continue'
/// Unicode property.
///
/// 'XID_Continue' is a Unicode Derived Property specified in
/// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications),
/// mostly similar to 'ID_Continue' but modified for closure under NFKx.
#[allow(non_snake_case)]
fn is_XID_continue(&self) -> bool;
/// Indicates whether a character is in lowercase.
///
/// This is defined according to the terms of the Unicode Derived Core
/// Property `Lowercase`.
fn is_lowercase(&self) -> bool;
/// Indicates whether a character is in uppercase.
///
/// This is defined according to the terms of the Unicode Derived Core
/// Property `Uppercase`.
fn is_uppercase(&self) -> bool;
/// Indicates whether a character is whitespace.
///
/// Whitespace is defined in terms of the Unicode Property `White_Space`.
fn is_whitespace(&self) -> bool;
/// Indicates whether a character is alphanumeric.
///
/// Alphanumericness is defined in terms of the Unicode General Categories
/// 'Nd', 'Nl', 'No' and the Derived Core Property 'Alphabetic'.
fn is_alphanumeric(&self) -> bool;
/// Indicates whether a character is a control code point.
///
/// Control code points are defined in terms of the Unicode General
/// Category `Cc`.
fn is_control(&self) -> bool;
/// Indicates whether the character is numeric (Nd, Nl, or No).
fn is_digit(&self) -> bool;
/// Converts a character to its lowercase equivalent.
///
/// The case-folding performed is the common or simple mapping. See
/// `to_uppercase()` for references and more information.
///
/// # Return value
///
/// Returns the lowercase equivalent of the character, or the character
/// itself if no conversion is possible.
fn to_lowercase(&self) -> char;
/// Converts a character to its uppercase equivalent.
///
/// The case-folding performed is the common or simple mapping: it maps
/// one Unicode codepoint (one character in Rust) to its uppercase
/// equivalent according to the Unicode database [1]. The additional
/// `SpecialCasing.txt` is not considered here, as it expands to multiple
/// codepoints in some cases.
///
/// A full reference can be found here [2].
///
/// # Return value
///
/// Returns the uppercase equivalent of the character, or the character
/// itself if no conversion was made.
///
/// [1]: ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt
///
/// [2]: http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G33992
fn to_uppercase(&self) -> char;
/// Returns this character's displayed width in columns, or `None` if it is a
/// control character other than `'\x00'`.
///
/// `is_cjk` determines behavior for characters in the Ambiguous category:
/// if `is_cjk` is `true`, these are 2 columns wide; otherwise, they are 1.
/// In CJK contexts, `is_cjk` should be `true`, else it should be `false`.
/// [Unicode Standard Annex #11](http://www.unicode.org/reports/tr11/)
/// recommends that these characters be treated as 1 column (i.e.,
/// `is_cjk` = `false`) if the context cannot be reliably determined.
fn width(&self, is_cjk: bool) -> Option<uint>;
}
impl UnicodeChar for char {
fn is_alphabetic(&self) -> bool { is_alphabetic(*self) }
fn is_XID_start(&self) -> bool |
fn is_XID_continue(&self) -> bool { is_XID_continue(*self) }
fn is_lowercase(&self) -> bool { is_lowercase(*self) }
fn is_uppercase(&self) -> bool { is_uppercase(*self) }
fn is_whitespace(&self) -> bool { is_whitespace(*self) }
fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) }
fn is_control(&self) -> bool { is_control(*self) }
fn is_digit(&self) -> bool { is_digit(*self) }
fn to_lowercase(&self) -> char { to_lowercase(*self) }
fn to_uppercase(&self) -> char { to_uppercase(*self) }
fn width(&self, is_cjk: bool) -> Option<uint> { width(*self, is_cjk) }
}
| { is_XID_start(*self) } |
measure_baseclass.py | #!/usr/bin/python
import json
import sys
import traceback
import os
import requests
import argparse
SLEEP_TIME = 60*5
debug = False
key_loc = '~/.atlas/auth'
class MeasurementBase(object):
def __init__(self, target, key, probe_list=None, sess=None):
self.target = target
self.description = ''
self.start_time = None
self.stop_time = None
self.af = 4
self.is_oneoff = True
self.is_public = True
self.resolve_on_probe = True
self.interval = 86400 #1 day
self.key = key
self.sess = sess if sess else requests
if probe_list:
self.num_probes = len(probe_list)
self.probe_type = 'probes'
self.probe_value = setup_probe_value('probes', probe_list)
def setup_definitions(self):
definitions = {}
definitions['target'] = self.target
definitions['description'] = self.description
definitions['af'] = self.af #set ip version
definitions['type'] = self.measurement_type
definitions['is_oneoff'] = str(self.is_oneoff).lower()
definitions['interval'] = self.interval
definitions['resolve_on_probe'] = str(self.resolve_on_probe).lower()
definitions['is_public'] = str(self.is_public).lower()
return definitions
def setup_probes(self):
probes = {}
probes['requested'] = self.num_probes
probes['type'] = self.probe_type
probes['value'] = self.probe_value
return probes
def run(self):
key = self.key
definitions = self.setup_definitions()
probes = self.setup_probes()
data = {'definitions': [definitions], 'probes': [probes]}
if self.start_time is not None:
data['start_time'] = self.start_time
if self.stop_time is not None:
data['stop_time'] = self.stop_time
data_str = json.dumps(data)
headers = {'content-type': 'application/json', 'accept': 'application/json'}
response = self.sess.post('https://atlas.ripe.net/api/v1/measurement/?key='+key, data_str, headers=headers)
response_str = response.text
return json.loads(response_str)
def readkey(keyfile=key_loc):
auth_file = os.path.expanduser(keyfile)
f = open(auth_file)
key = f.read().strip()
f.close()
if len(key) <= 0:
sys.stderr.write('Meaurement key is too short!\n')
return key
def setup_probe_value(type, arg_values):
"""
type is the probe type.
arg_values is a list of args passed in by user
"""
if type == 'asn' or type == 'msm':
return int(arg_values[0]) #return an integer value
elif type == 'probes':
arg_values = map(str, arg_values)
return ','.join(arg_values) #return command separated list of probe ids
else:
return arg_values[0] #for everything else just return single item from list
def load_input(inputfile):
target_dict = {}
f = open(inputfile)
for line in f:
line = line.strip()
if not line: #empty
continue
chunks = line.split(' ')
nodeid = chunks[0]
targetip = chunks[1]
try:
target_dict[targetip].append(nodeid)
except KeyError:
target_dict[targetip] = [nodeid]
f.close()
return target_dict
def process_response(response):
if 'error' in response:
error_details = response['error']
code = error_details['code']
message = error_details['message']
#return a tuple with error message and code
return 'error', '%s code: %d' % (message, code)
elif 'measurements' in response:
measurement_list = response['measurements']
return 'ok', measurement_list
else:
return 'error', 'Unknown response: %s' % str(response)
def format_response(response):
if 'error' in response:
error_details = response['error']
code = error_details['code']
message = error_details['message']
return message+' code: '+str(code)
elif 'measurements' in response:
measurement_list = response['measurements'] | return '\n'.join(measurement_list_str)
else:
return 'Error processing response: '+str(response)
def config_argparser():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--description', default=[''], nargs=1, help='measurement description (default: empty)')
parser.add_argument('-k', '--key-file', default=[key_loc], nargs=1, help='Path to RIPE Atlas API key (default: '+key_loc+')')
parser.add_argument('-r', '--dont-resolve-on-probe', action='store_true',
help='Do DNS resolution on probe? (default: on)')
parser.add_argument('--ipv6', action='store_true', help='Use IPv6 instead of IPv4 (default: IPv4)')
parser.add_argument('--repeats', nargs=1, default=[0],
help='Is a one-off measurement. Non-zero is the repeating interval in seconds (default: 0)')
parser.add_argument('--private', action='store_true',
help='Sets this measurement to be private. Other people will not see the results. (default: public)')
parser.add_argument('--start-time', default=[None], nargs=1, help='Specify a Unix timestamp for this measurement to begin (default: immediately)')
parser.add_argument('--stop-time', default=[None], nargs=1, help='Specify a Unix timestamp for this measurement to stop')
parser.add_argument('target_list', nargs=1, help='Path to target-list')
parser.add_argument('meas_id_output', nargs=1, help='Path to file where measurement ids will be written')
return parser | measurement_list_str = map(str, measurement_list) |
command-parameter.ts | import { commandDefaults } from '../constants';
import { Devices } from './command-constructor-form';
interface ICommandParameter {
name: string;
value?: string;
}
export class | implements ICommandParameter {
name: string;
value?: string;
constructor(name: string, value?: string) {
this.name = name;
this.value = value;
}
toString(): string {
if (!this.value) {
return this.name;
}
return `${this.name} ${this.value}`;
}
}
export class EnvVarCommandParameter extends CommandParameter {
envVarName: string;
constructor(name: string, envVarName: string, value: string) {
super(name, value);
this.envVarName = envVarName;
}
toString(): string {
return `${this.name} ${this.envVarName}=${this.value}`;
}
}
interface ICommandParametersBuilder {
parameters: CommandParameter[];
addDevicesParameters(devices: Devices[]): void;
addProxyParameters(httpProxy: string, httpsProxy: string, noProxy: string): void;
}
export class PythonCommandParametersBuilder implements ICommandParametersBuilder {
private readonly _parameters: CommandParameter[];
get parameters(): CommandParameter[] {
return this._parameters;
}
constructor() {
this._parameters = [
new CommandParameter('--image', commandDefaults.dockerImageWithTag),
];
}
addDevicesParameters(devices: Devices[]): void {
if (devices.includes(Devices.GPU)) {
this._parameters.push(new CommandParameter('--enable-gpu'));
}
if (devices.includes(Devices.NCS2)) {
this._parameters.push(new CommandParameter('--enable-myriad'));
}
if (devices.includes(Devices.HDDL)) {
this._parameters.push(new CommandParameter('--enable-hddl'));
}
}
addProxyParameters(httpProxy: string, httpsProxy: string, noProxy: string): void {
if (httpProxy) {
this._parameters.push(new CommandParameter('--http-proxy', httpProxy));
}
if (httpsProxy) {
this._parameters.push(new CommandParameter('--https-proxy', httpsProxy));
}
if (noProxy) {
this._parameters.push(new CommandParameter('--no-proxy', noProxy));
}
}
}
export class DockerCommandParametersBuilder implements ICommandParametersBuilder {
private readonly _parameters: CommandParameter[];
private readonly _itParameter: CommandParameter;
get parameters(): CommandParameter[] {
return [...this._parameters, this._itParameter];
}
constructor() {
const { dockerImageWithTag, bindIP, hostPort, containerPort, containerName } = commandDefaults;
this._parameters = [
new CommandParameter('-p', `${bindIP}:${hostPort}:${containerPort}`),
new CommandParameter('--name', containerName),
];
this._itParameter = new CommandParameter('-it', dockerImageWithTag);
}
addDevicesParameters(devices: Devices[]): void {
if (devices.includes(Devices.GPU)) {
// Example:
// --device /dev/dri
// --group-add=$(stat -c '%g' /dev/dri/render* | head -1)
this._parameters.push(new CommandParameter('--device', '/dev/dri'));
this._parameters.push(new CommandParameter('--group-add', '$(stat -c \'%g\' /dev/dri/render* | head -1)'));
}
if (devices.includes(Devices.NCS2)) {
// Example:
// --device-cgroup-rule='c 189:* rmw'
// -v /dev/bus/usb:/dev/bus/usb
this._parameters.push(new CommandParameter('--device-cgroup-rule', '\'c 189:* rmw\''));
this._parameters.push(new CommandParameter('-v', '/dev/bus/usb:/dev/bus/usb'));
}
if (devices.includes(Devices.HDDL)) {
// Example:
// --device=/dev/ion:/dev/ion
// -v /var/tmp:/var/tmp
this._parameters.push(new CommandParameter('--device', '/dev/ion:/dev/ion'));
this._parameters.push(new CommandParameter('-v', '/var/tmp:/var/tmp'));
}
}
addProxyParameters(httpProxy: string, httpsProxy: string, noProxy: string): void {
if (httpProxy) {
this._parameters.push(new EnvVarCommandParameter('-e', 'HTTP_PROXY', httpProxy));
}
if (httpsProxy) {
this._parameters.push(new EnvVarCommandParameter('-e', 'HTTPS_PROXY', httpsProxy));
}
if (noProxy) {
this._parameters.push(new EnvVarCommandParameter('-e', 'NO_PROXY', noProxy));
}
}
}
| CommandParameter |
android.js | import React, { Component } from 'react';
class | extends Component {
render() {
return (
<div>
<div className="section">
<h1>Android Savegames</h1>
<p>
GTA:SA for Android has a savegame folder at{' '}
<code><internal-storage>/Android/data/com.rockstargames.gtasa*/files</code> where <code>*</code> seems
to be a i18n handle.
<br />
This folder usually contains:
</p>
<ul>
<li>
<dl>
<dt>CINFO.BIN</dt>
<dd>Contains a lot of binary stuff as the name suggests.</dd>
</dl>
</li>
<li>
<dl>
<dt>gta_sa.set</dt>
<dd>Contains binary data, probably game settings.</dd>
</dl>
</li>
<li>
<dl>
<dt>GTASAsf*.b</dt>
<dd>
Savegame files (1-10), 9 & 10 seem to be cloud synced because they are present with a valid size even
when they were never used.
</dd>
</dl>
</li>
<li>
<dl>
<dt>gtasatelem.set</dt>
<dd>
Starts with{' '}
<code>
telemv001, contains binary data along the String <code>Usage</code>. Seems like analytics.
</code>
</dd>
</dl>
</li>
</ul>
<h2>Savegame Layout (and differences to the PC Version)</h2>
<p>
The savegame layout seems to differ to the PC version in some ways.
<ul>
<li>
Only 31 occurrences of <code>BLOCK</code> instead of 34
</li>
<li>Size of 195000 bytes</li>
<li>
Id: <code>0x53AD8157</code>
</li>
</ul>
<h3>Block 00</h3>
<p>
Block 00 contains something that fits the version (from position 0/0 to 0/4) but the title seems to
contain level ids instead of the savegame title (The ingame title being "Ryder" while the value saved in
the file is <code>INTRO_2</code>).
<br />
Additionally, there is also the filename of the savefile in block 00 (at position 168/10). The Android
block 00 is ~116 bytes bigger than the PC version.
</p>
<h3>Block 01</h3>
<p>
Block 01 also seems to be different to the PC version. It contains some keywords like <code>BEARD</code>,{' '}
<code>CORNROW</code>, etc. that are not present in the PC savegame. Additionally, the mission names and
the positions are different (for example <code>INTRO2</code> in the Android save opposed to{' '}
<code>INT2</code> in the PC save. The mission names also seem to not match the savegame title in Block 00.
There are also multiple occurrences of passages that look like charsets:
</p>
{/* prettier-ignore */}
<div style={{maxWidth: '100%', overflowX: 'scroll'}}>
<pre><code style={{color:"#000000"}}>017068 31 00 02 00 32 00 02 00 33 00 02 00 34 00 02 00 35 00 02 00 36 00 02 00 37 00 02 00 38 00 02 00 39 00 02 00 3A 00 02 00 3B 00 1...2...3...4...5...6...7...8...9...:...;.<br/>
017110 02 00 3C 00 02 00 3D 00 02 00 3E 00 02 00 3F 00 02 00 40 00 02 00 41 00 02 00 42 00 02 00 43 00 02 00 44 00 02 00 45 00 02 00 ..<...=...>[email protected]...<br/>
017152 46 00 02 00 47 00 02 00 48 00 02 00 49 00 02 00 4A 00 02 00 4B 00 02 00 4C 00 02 00 4D 00 02 00 4E 00 02 00 4F 00 02 00 50 00 F...G...H...I...J...K...L...M...N...O...P.<br/>
017194 02 00 51 00 02 00 52 00 02 00 53 00 02 00 54 00 02 00 55 00 02 00 56 00 02 00 57 00 02 00 58 00 02 00 59 00 02 00 5A 00 02 00 ..Q...R...S...T...U...V...W...X...Y...Z...<br/>
017236 5B 00 02 00 5C 00 02 00 5D 00 02 00 5E 00 02 00 5F 00 02 00 60 00 02 00 61 00 02 00 62 00 02 00 63 00 02 00 64 00 02 00 65 00 [...\...]...^..._...`...a...b...c...d...e.<br/>
017278 02 00 66 00 02 00 67 00 02 00 68 00 02 00 69 00 02 00 6A 00 02 00 6B 00 02 00 6C 00 02 00 6D 00 02 00 6E 00 02 00 6F 00 02 00 ..f...g...h...i...j...k...l...m...n...o...<br/>
017320 70 00 02 00 71 00 02 00 72 00 02 00 73 00 02 00 74 00 02 00 75 00 02 00 76 00 02 00 77 00 02 00 78 00 02 00 79 00 02 00 7A 00 p...q...r...s...t...u...v...w...x...y...z.<br/>
017362 02 00 7B 00 02 00 7C 00 02 00 7D 00 02 00 7E 00 02 ..{'{...|...}'}...~..<br/>
</code></pre>
</div>
<span style={{ fontSize: '10px' }}>
Generated by <a href="http://www.wxHexEditor.org/">wxHexEditor</a>
</span>
</p>
<h3>Block 02</h3>
<p>Block 02 seems similar to the PC version, both contain no human readable text.</p>
</div>
</div>
);
}
}
export default Android;
| Android |
test_wuvt.py | """
test_wuvt.py - tests for the wuvt module
author: mutantmonkey <[email protected]>
"""
import re
import unittest
from mock import MagicMock
from modules import wuvt
from web import catch_timeout
@catch_timeout
class TestWuvt(unittest.TestCase):
| def setUp(self):
self.phenny = MagicMock()
@catch_timeout
def test_wuvt(self):
wuvt.wuvt(self.phenny, None)
out = self.phenny.say.call_args[0][0]
m = re.match('^.* is currently playing .* by .*$', out,
flags=re.UNICODE)
self.assertTrue(m) |
|
MsgVpnBridgeTlsTrustedCommonNameResponse.ts | /* eslint-disable */
import type { MsgVpnBridgeTlsTrustedCommonName } from './MsgVpnBridgeTlsTrustedCommonName';
import type { MsgVpnBridgeTlsTrustedCommonNameCollections } from './MsgVpnBridgeTlsTrustedCommonNameCollections';
import type { MsgVpnBridgeTlsTrustedCommonNameLinks } from './MsgVpnBridgeTlsTrustedCommonNameLinks';
import type { SempMeta } from './SempMeta';
export type MsgVpnBridgeTlsTrustedCommonNameResponse = {
collections?: MsgVpnBridgeTlsTrustedCommonNameCollections;
data?: MsgVpnBridgeTlsTrustedCommonName; | export namespace MsgVpnBridgeTlsTrustedCommonNameResponse {
/**
* the discriminator for the model if required for more complex api's
*/
export const discriminator = 'MsgVpnBridgeTlsTrustedCommonNameResponse';
} | links?: MsgVpnBridgeTlsTrustedCommonNameLinks;
meta: SempMeta;
}
|
codemap.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The CodeMap tracks all the source code used within a single crate, mapping
//! from integer byte positions to the original source code location. Each bit
//! of source parsed during crate parsing (typically files, in-memory strings,
//! or various bits of macro expansion) cover a continuous range of bytes in the
//! CodeMap and are represented by FileMaps. Byte positions are stored in
//! `spans` and used pervasively in the compiler. They are absolute positions
//! within the CodeMap, which upon request can be converted to line and column
//! information, source code snippets, etc.
pub use self::ExpnFormat::*;
use std::cell::{Cell, RefCell};
use std::ops::{Add, Sub};
use std::path::Path;
use std::rc::Rc;
use std::cmp;
use std::{fmt, fs};
use std::io::{self, Read};
use serialize::{Encodable, Decodable, Encoder, Decoder};
use ast::Name;
use errors::emitter::MAX_HIGHLIGHT_LINES;
// _____________________________________________________________________________
// Pos, BytePos, CharPos
//
pub trait Pos {
fn from_usize(n: usize) -> Self;
fn to_usize(&self) -> usize;
}
/// A byte offset. Keep this small (currently 32-bits), as AST contains
/// a lot of them.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub struct BytePos(pub u32);
/// A character offset. Because of multibyte utf8 characters, a byte offset
/// is not equivalent to a character offset. The CodeMap will convert BytePos
/// values to CharPos values as necessary.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Debug)]
pub struct CharPos(pub usize);
// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix
// have been unsuccessful
impl Pos for BytePos {
fn from_usize(n: usize) -> BytePos { BytePos(n as u32) }
fn to_usize(&self) -> usize { let BytePos(n) = *self; n as usize }
}
impl Add for BytePos {
type Output = BytePos;
fn add(self, rhs: BytePos) -> BytePos {
BytePos((self.to_usize() + rhs.to_usize()) as u32)
}
}
impl Sub for BytePos {
type Output = BytePos;
fn sub(self, rhs: BytePos) -> BytePos {
BytePos((self.to_usize() - rhs.to_usize()) as u32)
}
}
impl Encodable for BytePos {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u32(self.0)
}
}
impl Decodable for BytePos {
fn decode<D: Decoder>(d: &mut D) -> Result<BytePos, D::Error> {
Ok(BytePos(d.read_u32()?))
}
}
impl Pos for CharPos {
fn from_usize(n: usize) -> CharPos { CharPos(n) }
fn to_usize(&self) -> usize { let CharPos(n) = *self; n }
}
impl Add for CharPos {
type Output = CharPos;
fn add(self, rhs: CharPos) -> CharPos {
CharPos(self.to_usize() + rhs.to_usize())
}
}
impl Sub for CharPos {
type Output = CharPos;
fn sub(self, rhs: CharPos) -> CharPos {
CharPos(self.to_usize() - rhs.to_usize())
}
}
// _____________________________________________________________________________
// Span, MultiSpan, Spanned
//
/// Spans represent a region of code, used for error reporting. Positions in spans
/// are *absolute* positions from the beginning of the codemap, not positions
/// relative to FileMaps. Methods on the CodeMap can be used to relate spans back
/// to the original source.
/// You must be careful if the span crosses more than one file - you will not be
/// able to use many of the functions on spans in codemap and you cannot assume
/// that the length of the span = hi - lo; there may be space in the BytePos
/// range between files.
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct Span {
pub lo: BytePos,
pub hi: BytePos,
/// Information about where the macro came from, if this piece of
/// code was created by a macro expansion.
pub expn_id: ExpnId
}
/// Spans are converted to MultiSpans just before error reporting, either automatically,
/// generated by line grouping, or manually constructed.
/// In the latter case care should be taken to ensure that spans are ordered, disjoint,
/// and point into the same FileMap.
#[derive(Clone)]
pub struct MultiSpan {
pub spans: Vec<Span>
}
pub const DUMMY_SP: Span = Span { lo: BytePos(0), hi: BytePos(0), expn_id: NO_EXPANSION };
// Generic span to be used for code originating from the command line
pub const COMMAND_LINE_SP: Span = Span { lo: BytePos(0),
hi: BytePos(0),
expn_id: COMMAND_LINE_EXPN };
impl Span {
/// Returns `self` if `self` is not the dummy span, and `other` otherwise.
pub fn substitute_dummy(self, other: Span) -> Span {
if self.source_equal(&DUMMY_SP) { other } else { self }
}
pub fn contains(self, other: Span) -> bool {
self.lo <= other.lo && other.hi <= self.hi
}
/// Return true if the spans are equal with regards to the source text.
///
/// Use this instead of `==` when either span could be generated code,
/// and you only care that they point to the same bytes of source text.
pub fn source_equal(&self, other: &Span) -> bool {
self.lo == other.lo && self.hi == other.hi
}
/// Returns `Some(span)`, a union of `self` and `other`, on overlap.
pub fn merge(self, other: Span) -> Option<Span> {
if self.expn_id != other.expn_id {
return None;
}
if (self.lo <= other.lo && self.hi > other.lo) ||
(self.lo >= other.lo && self.lo < other.hi) {
Some(Span {
lo: cmp::min(self.lo, other.lo),
hi: cmp::max(self.hi, other.hi),
expn_id: self.expn_id,
})
} else {
None
}
}
/// Returns `Some(span)`, where the start is trimmed by the end of `other`
pub fn trim_start(self, other: Span) -> Option<Span> {
if self.hi > other.hi {
Some(Span { lo: cmp::max(self.lo, other.hi), .. self })
} else {
None
}
}
}
#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
pub struct Spanned<T> {
pub node: T,
pub span: Span,
}
impl Encodable for Span {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("Span", 2, |s| {
s.emit_struct_field("lo", 0, |s| {
self.lo.encode(s)
})?;
s.emit_struct_field("hi", 1, |s| {
self.hi.encode(s)
})
})
}
}
impl Decodable for Span {
fn decode<D: Decoder>(d: &mut D) -> Result<Span, D::Error> {
d.read_struct("Span", 2, |d| {
let lo = d.read_struct_field("lo", 0, |d| {
BytePos::decode(d)
})?;
let hi = d.read_struct_field("hi", 1, |d| {
BytePos::decode(d)
})?;
Ok(mk_sp(lo, hi))
})
}
}
fn default_span_debug(span: Span, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Span {{ lo: {:?}, hi: {:?}, expn_id: {:?} }}",
span.lo, span.hi, span.expn_id)
}
thread_local!(pub static SPAN_DEBUG: Cell<fn(Span, &mut fmt::Formatter) -> fmt::Result> =
Cell::new(default_span_debug));
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
SPAN_DEBUG.with(|span_debug| span_debug.get()(*self, f))
}
}
pub fn spanned<T>(lo: BytePos, hi: BytePos, t: T) -> Spanned<T> {
respan(mk_sp(lo, hi), t)
}
pub fn respan<T>(sp: Span, t: T) -> Spanned<T> {
Spanned {node: t, span: sp}
}
pub fn dummy_spanned<T>(t: T) -> Spanned<T> {
respan(DUMMY_SP, t)
}
/* assuming that we're not in macro expansion */
pub fn mk_sp(lo: BytePos, hi: BytePos) -> Span {
Span {lo: lo, hi: hi, expn_id: NO_EXPANSION}
}
/// Return the span itself if it doesn't come from a macro expansion,
/// otherwise return the call site span up to the `enclosing_sp` by
/// following the `expn_info` chain.
pub fn original_sp(cm: &CodeMap, sp: Span, enclosing_sp: Span) -> Span {
let call_site1 = cm.with_expn_info(sp.expn_id, |ei| ei.map(|ei| ei.call_site));
let call_site2 = cm.with_expn_info(enclosing_sp.expn_id, |ei| ei.map(|ei| ei.call_site));
match (call_site1, call_site2) {
(None, _) => sp,
(Some(call_site1), Some(call_site2)) if call_site1 == call_site2 => sp,
(Some(call_site1), _) => original_sp(cm, call_site1, enclosing_sp),
}
}
impl MultiSpan {
pub fn new() -> MultiSpan {
MultiSpan { spans: Vec::new() }
}
pub fn to_span_bounds(&self) -> Span {
assert!(!self.spans.is_empty());
let Span { lo, expn_id, .. } = *self.spans.first().unwrap();
let Span { hi, .. } = *self.spans.last().unwrap();
Span { lo: lo, hi: hi, expn_id: expn_id }
}
/// Merges or inserts the given span into itself.
pub fn push_merge(&mut self, mut sp: Span) |
/// Inserts the given span into itself, for use with `end_highlight_lines`.
pub fn push_trim(&mut self, mut sp: Span) {
let mut prev = mk_sp(BytePos(0), BytePos(0));
if let Some(first) = self.spans.get_mut(0) {
if first.lo > sp.lo {
// Prevent us here from spanning fewer lines
// because of trimming the start of the span
// (this should not be visible, because this method ought
// to not be used in conjunction with `highlight_lines`)
first.lo = sp.lo;
}
}
for idx in 0.. {
if let Some(sp_trim) = sp.trim_start(prev) {
// Implies `sp.hi > prev.hi`
let cur = match self.spans.get(idx) {
Some(s) => *s,
None => {
sp = sp_trim;
break;
}
};
// `cur` may overlap with `sp_trim`
if let Some(cur_trim) = cur.trim_start(sp_trim) {
// Implies `sp.hi < cur.hi`
self.spans.insert(idx, sp_trim);
self.spans[idx + 1] = cur_trim;
return;
} else if sp.hi == cur.hi {
return;
}
prev = cur;
}
}
self.spans.push(sp);
}
}
impl From<Span> for MultiSpan {
fn from(span: Span) -> MultiSpan {
MultiSpan { spans: vec![span] }
}
}
// _____________________________________________________________________________
// Loc, LocWithOpt, FileMapAndLine, FileMapAndBytePos
//
/// A source code location used for error reporting
#[derive(Debug)]
pub struct Loc {
/// Information about the original source
pub file: Rc<FileMap>,
/// The (1-based) line number
pub line: usize,
/// The (0-based) column offset
pub col: CharPos
}
/// A source code location used as the result of lookup_char_pos_adj
// Actually, *none* of the clients use the filename *or* file field;
// perhaps they should just be removed.
#[derive(Debug)]
pub struct LocWithOpt {
pub filename: FileName,
pub line: usize,
pub col: CharPos,
pub file: Option<Rc<FileMap>>,
}
// used to be structural records. Better names, anyone?
#[derive(Debug)]
pub struct FileMapAndLine { pub fm: Rc<FileMap>, pub line: usize }
#[derive(Debug)]
pub struct FileMapAndBytePos { pub fm: Rc<FileMap>, pub pos: BytePos }
// _____________________________________________________________________________
// ExpnFormat, NameAndSpan, ExpnInfo, ExpnId
//
/// The source of expansion.
#[derive(Clone, Hash, Debug, PartialEq, Eq)]
pub enum ExpnFormat {
/// e.g. #[derive(...)] <item>
MacroAttribute(Name),
/// e.g. `format!()`
MacroBang(Name),
}
#[derive(Clone, Hash, Debug)]
pub struct NameAndSpan {
/// The format with which the macro was invoked.
pub format: ExpnFormat,
/// Whether the macro is allowed to use #[unstable]/feature-gated
/// features internally without forcing the whole crate to opt-in
/// to them.
pub allow_internal_unstable: bool,
/// The span of the macro definition itself. The macro may not
/// have a sensible definition span (e.g. something defined
/// completely inside libsyntax) in which case this is None.
pub span: Option<Span>
}
impl NameAndSpan {
pub fn name(&self) -> Name {
match self.format {
ExpnFormat::MacroAttribute(s) => s,
ExpnFormat::MacroBang(s) => s,
}
}
}
/// Extra information for tracking spans of macro and syntax sugar expansion
#[derive(Hash, Debug)]
pub struct ExpnInfo {
/// The location of the actual macro invocation or syntax sugar , e.g.
/// `let x = foo!();` or `if let Some(y) = x {}`
///
/// This may recursively refer to other macro invocations, e.g. if
/// `foo!()` invoked `bar!()` internally, and there was an
/// expression inside `bar!`; the call_site of the expression in
/// the expansion would point to the `bar!` invocation; that
/// call_site span would have its own ExpnInfo, with the call_site
/// pointing to the `foo!` invocation.
pub call_site: Span,
/// Information about the expansion.
pub callee: NameAndSpan
}
#[derive(PartialEq, Eq, Clone, Debug, Hash, RustcEncodable, RustcDecodable, Copy)]
pub struct ExpnId(u32);
pub const NO_EXPANSION: ExpnId = ExpnId(!0);
// For code appearing from the command line
pub const COMMAND_LINE_EXPN: ExpnId = ExpnId(!1);
impl ExpnId {
pub fn from_u32(id: u32) -> ExpnId {
ExpnId(id)
}
pub fn into_u32(self) -> u32 {
self.0
}
}
// _____________________________________________________________________________
// FileMap, MultiByteChar, FileName, FileLines
//
pub type FileName = String;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct LineInfo {
/// Index of line, starting from 0.
pub line_index: usize,
/// Column in line where span begins, starting from 0.
pub start_col: CharPos,
/// Column in line where span ends, starting from 0, exclusive.
pub end_col: CharPos,
}
pub struct FileLines {
pub file: Rc<FileMap>,
pub lines: Vec<LineInfo>
}
/// Identifies an offset of a multi-byte character in a FileMap
#[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq)]
pub struct MultiByteChar {
/// The absolute offset of the character in the CodeMap
pub pos: BytePos,
/// The number of bytes, >=2
pub bytes: usize,
}
/// A single source in the CodeMap.
pub struct FileMap {
/// The name of the file that the source came from, source that doesn't
/// originate from files has names between angle brackets by convention,
/// e.g. `<anon>`
pub name: FileName,
/// The complete source code
pub src: Option<Rc<String>>,
/// The start position of this source in the CodeMap
pub start_pos: BytePos,
/// The end position of this source in the CodeMap
pub end_pos: BytePos,
/// Locations of lines beginnings in the source code
pub lines: RefCell<Vec<BytePos>>,
/// Locations of multi-byte characters in the source code
pub multibyte_chars: RefCell<Vec<MultiByteChar>>,
}
impl Encodable for FileMap {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_struct("FileMap", 5, |s| {
s.emit_struct_field("name", 0, |s| self.name.encode(s))?;
s.emit_struct_field("start_pos", 1, |s| self.start_pos.encode(s))?;
s.emit_struct_field("end_pos", 2, |s| self.end_pos.encode(s))?;
s.emit_struct_field("lines", 3, |s| {
let lines = self.lines.borrow();
// store the length
s.emit_u32(lines.len() as u32)?;
if !lines.is_empty() {
// In order to preserve some space, we exploit the fact that
// the lines list is sorted and individual lines are
// probably not that long. Because of that we can store lines
// as a difference list, using as little space as possible
// for the differences.
let max_line_length = if lines.len() == 1 {
0
} else {
lines.windows(2)
.map(|w| w[1] - w[0])
.map(|bp| bp.to_usize())
.max()
.unwrap()
};
let bytes_per_diff: u8 = match max_line_length {
0 ... 0xFF => 1,
0x100 ... 0xFFFF => 2,
_ => 4
};
// Encode the number of bytes used per diff.
bytes_per_diff.encode(s)?;
// Encode the first element.
lines[0].encode(s)?;
let diff_iter = (&lines[..]).windows(2)
.map(|w| (w[1] - w[0]));
match bytes_per_diff {
1 => for diff in diff_iter { (diff.0 as u8).encode(s)? },
2 => for diff in diff_iter { (diff.0 as u16).encode(s)? },
4 => for diff in diff_iter { diff.0.encode(s)? },
_ => unreachable!()
}
}
Ok(())
})?;
s.emit_struct_field("multibyte_chars", 4, |s| {
(*self.multibyte_chars.borrow()).encode(s)
})
})
}
}
impl Decodable for FileMap {
fn decode<D: Decoder>(d: &mut D) -> Result<FileMap, D::Error> {
d.read_struct("FileMap", 5, |d| {
let name: String = d.read_struct_field("name", 0, |d| Decodable::decode(d))?;
let start_pos: BytePos = d.read_struct_field("start_pos", 1, |d| Decodable::decode(d))?;
let end_pos: BytePos = d.read_struct_field("end_pos", 2, |d| Decodable::decode(d))?;
let lines: Vec<BytePos> = d.read_struct_field("lines", 3, |d| {
let num_lines: u32 = Decodable::decode(d)?;
let mut lines = Vec::with_capacity(num_lines as usize);
if num_lines > 0 {
// Read the number of bytes used per diff.
let bytes_per_diff: u8 = Decodable::decode(d)?;
// Read the first element.
let mut line_start: BytePos = Decodable::decode(d)?;
lines.push(line_start);
for _ in 1..num_lines {
let diff = match bytes_per_diff {
1 => d.read_u8()? as u32,
2 => d.read_u16()? as u32,
4 => d.read_u32()?,
_ => unreachable!()
};
line_start = line_start + BytePos(diff);
lines.push(line_start);
}
}
Ok(lines)
})?;
let multibyte_chars: Vec<MultiByteChar> =
d.read_struct_field("multibyte_chars", 4, |d| Decodable::decode(d))?;
Ok(FileMap {
name: name,
start_pos: start_pos,
end_pos: end_pos,
src: None,
lines: RefCell::new(lines),
multibyte_chars: RefCell::new(multibyte_chars)
})
})
}
}
impl fmt::Debug for FileMap {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "FileMap({})", self.name)
}
}
impl FileMap {
/// EFFECT: register a start-of-line offset in the
/// table of line-beginnings.
/// UNCHECKED INVARIANT: these offsets must be added in the right
/// order and must be in the right places; there is shared knowledge
/// about what ends a line between this file and parse.rs
/// WARNING: pos param here is the offset relative to start of CodeMap,
/// and CodeMap will append a newline when adding a filemap without a newline at the end,
/// so the safe way to call this is with value calculated as
/// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap.
pub fn next_line(&self, pos: BytePos) {
// the new charpos must be > the last one (or it's the first one).
let mut lines = self.lines.borrow_mut();
let line_len = lines.len();
assert!(line_len == 0 || ((*lines)[line_len - 1] < pos));
lines.push(pos);
}
/// get a line from the list of pre-computed line-beginnings.
/// line-number here is 0-based.
pub fn get_line(&self, line_number: usize) -> Option<&str> {
match self.src {
Some(ref src) => {
let lines = self.lines.borrow();
lines.get(line_number).map(|&line| {
let begin: BytePos = line - self.start_pos;
let begin = begin.to_usize();
// We can't use `lines.get(line_number+1)` because we might
// be parsing when we call this function and thus the current
// line is the last one we have line info for.
let slice = &src[begin..];
match slice.find('\n') {
Some(e) => &slice[..e],
None => slice
}
})
}
None => None
}
}
pub fn record_multibyte_char(&self, pos: BytePos, bytes: usize) {
assert!(bytes >=2 && bytes <= 4);
let mbc = MultiByteChar {
pos: pos,
bytes: bytes,
};
self.multibyte_chars.borrow_mut().push(mbc);
}
pub fn is_real_file(&self) -> bool {
!(self.name.starts_with("<") &&
self.name.ends_with(">"))
}
pub fn is_imported(&self) -> bool {
self.src.is_none()
}
fn count_lines(&self) -> usize {
self.lines.borrow().len()
}
}
/// An abstraction over the fs operations used by the Parser.
pub trait FileLoader {
/// Query the existence of a file.
fn file_exists(&self, path: &Path) -> bool;
/// Read the contents of an UTF-8 file into memory.
fn read_file(&self, path: &Path) -> io::Result<String>;
}
/// A FileLoader that uses std::fs to load real files.
pub struct RealFileLoader;
impl FileLoader for RealFileLoader {
fn file_exists(&self, path: &Path) -> bool {
fs::metadata(path).is_ok()
}
fn read_file(&self, path: &Path) -> io::Result<String> {
let mut src = String::new();
fs::File::open(path)?.read_to_string(&mut src)?;
Ok(src)
}
}
// _____________________________________________________________________________
// CodeMap
//
pub struct CodeMap {
pub files: RefCell<Vec<Rc<FileMap>>>,
expansions: RefCell<Vec<ExpnInfo>>,
file_loader: Box<FileLoader>
}
impl CodeMap {
pub fn new() -> CodeMap {
CodeMap {
files: RefCell::new(Vec::new()),
expansions: RefCell::new(Vec::new()),
file_loader: Box::new(RealFileLoader)
}
}
pub fn with_file_loader(file_loader: Box<FileLoader>) -> CodeMap {
CodeMap {
files: RefCell::new(Vec::new()),
expansions: RefCell::new(Vec::new()),
file_loader: file_loader
}
}
pub fn file_exists(&self, path: &Path) -> bool {
self.file_loader.file_exists(path)
}
pub fn load_file(&self, path: &Path) -> io::Result<Rc<FileMap>> {
let src = self.file_loader.read_file(path)?;
Ok(self.new_filemap(path.to_str().unwrap().to_string(), src))
}
fn next_start_pos(&self) -> usize {
let files = self.files.borrow();
match files.last() {
None => 0,
// Add one so there is some space between files. This lets us distinguish
// positions in the codemap, even in the presence of zero-length files.
Some(last) => last.end_pos.to_usize() + 1,
}
}
/// Creates a new filemap without setting its line information. If you don't
/// intend to set the line information yourself, you should use new_filemap_and_lines.
pub fn new_filemap(&self, filename: FileName, mut src: String) -> Rc<FileMap> {
let start_pos = self.next_start_pos();
let mut files = self.files.borrow_mut();
// Remove utf-8 BOM if any.
if src.starts_with("\u{feff}") {
src.drain(..3);
}
let end_pos = start_pos + src.len();
let filemap = Rc::new(FileMap {
name: filename,
src: Some(Rc::new(src)),
start_pos: Pos::from_usize(start_pos),
end_pos: Pos::from_usize(end_pos),
lines: RefCell::new(Vec::new()),
multibyte_chars: RefCell::new(Vec::new()),
});
files.push(filemap.clone());
filemap
}
/// Creates a new filemap and sets its line information.
pub fn new_filemap_and_lines(&self, filename: &str, src: &str) -> Rc<FileMap> {
let fm = self.new_filemap(filename.to_string(), src.to_owned());
let mut byte_pos: u32 = 0;
for line in src.lines() {
// register the start of this line
fm.next_line(BytePos(byte_pos));
// update byte_pos to include this line and the \n at the end
byte_pos += line.len() as u32 + 1;
}
fm
}
/// Allocates a new FileMap representing a source file from an external
/// crate. The source code of such an "imported filemap" is not available,
/// but we still know enough to generate accurate debuginfo location
/// information for things inlined from other crates.
pub fn new_imported_filemap(&self,
filename: FileName,
source_len: usize,
mut file_local_lines: Vec<BytePos>,
mut file_local_multibyte_chars: Vec<MultiByteChar>)
-> Rc<FileMap> {
let start_pos = self.next_start_pos();
let mut files = self.files.borrow_mut();
let end_pos = Pos::from_usize(start_pos + source_len);
let start_pos = Pos::from_usize(start_pos);
for pos in &mut file_local_lines {
*pos = *pos + start_pos;
}
for mbc in &mut file_local_multibyte_chars {
mbc.pos = mbc.pos + start_pos;
}
let filemap = Rc::new(FileMap {
name: filename,
src: None,
start_pos: start_pos,
end_pos: end_pos,
lines: RefCell::new(file_local_lines),
multibyte_chars: RefCell::new(file_local_multibyte_chars),
});
files.push(filemap.clone());
filemap
}
pub fn mk_substr_filename(&self, sp: Span) -> String {
let pos = self.lookup_char_pos(sp.lo);
(format!("<{}:{}:{}>",
pos.file.name,
pos.line,
pos.col.to_usize() + 1)).to_string()
}
/// Lookup source information about a BytePos
pub fn lookup_char_pos(&self, pos: BytePos) -> Loc {
let chpos = self.bytepos_to_file_charpos(pos);
match self.lookup_line(pos) {
Ok(FileMapAndLine { fm: f, line: a }) => {
let line = a + 1; // Line numbers start at 1
let linebpos = (*f.lines.borrow())[a];
let linechpos = self.bytepos_to_file_charpos(linebpos);
debug!("byte pos {:?} is on the line at byte pos {:?}",
pos, linebpos);
debug!("char pos {:?} is on the line at char pos {:?}",
chpos, linechpos);
debug!("byte is on line: {}", line);
assert!(chpos >= linechpos);
Loc {
file: f,
line: line,
col: chpos - linechpos,
}
}
Err(f) => {
Loc {
file: f,
line: 0,
col: chpos,
}
}
}
}
// If the relevant filemap is empty, we don't return a line number.
fn lookup_line(&self, pos: BytePos) -> Result<FileMapAndLine, Rc<FileMap>> {
let idx = self.lookup_filemap_idx(pos);
let files = self.files.borrow();
let f = (*files)[idx].clone();
let len = f.lines.borrow().len();
if len == 0 {
return Err(f);
}
let mut a = 0;
{
let lines = f.lines.borrow();
let mut b = lines.len();
while b - a > 1 {
let m = (a + b) / 2;
if (*lines)[m] > pos {
b = m;
} else {
a = m;
}
}
assert!(a <= lines.len());
}
Ok(FileMapAndLine { fm: f, line: a })
}
pub fn lookup_char_pos_adj(&self, pos: BytePos) -> LocWithOpt {
let loc = self.lookup_char_pos(pos);
LocWithOpt {
filename: loc.file.name.to_string(),
line: loc.line,
col: loc.col,
file: Some(loc.file)
}
}
pub fn span_to_string(&self, sp: Span) -> String {
if self.files.borrow().is_empty() && sp.source_equal(&DUMMY_SP) {
return "no-location".to_string();
}
let lo = self.lookup_char_pos_adj(sp.lo);
let hi = self.lookup_char_pos_adj(sp.hi);
return (format!("{}:{}:{}: {}:{}",
lo.filename,
lo.line,
lo.col.to_usize() + 1,
hi.line,
hi.col.to_usize() + 1)).to_string()
}
// Returns true if two spans have the same callee
// (Assumes the same ExpnFormat implies same callee)
fn match_callees(&self, sp_a: &Span, sp_b: &Span) -> bool {
let fmt_a = self
.with_expn_info(sp_a.expn_id,
|ei| ei.map(|ei| ei.callee.format.clone()));
let fmt_b = self
.with_expn_info(sp_b.expn_id,
|ei| ei.map(|ei| ei.callee.format.clone()));
fmt_a == fmt_b
}
/// Returns a formatted string showing the expansion chain of a span
///
/// Spans are printed in the following format:
///
/// filename:start_line:col: end_line:col
/// snippet
/// Callee:
/// Callee span
/// Callsite:
/// Callsite span
///
/// Callees and callsites are printed recursively (if available, otherwise header
/// and span is omitted), expanding into their own callee/callsite spans.
/// Each layer of recursion has an increased indent, and snippets are truncated
/// to at most 50 characters. Finally, recursive calls to the same macro are squashed,
/// with '...' used to represent any number of recursive calls.
pub fn span_to_expanded_string(&self, sp: Span) -> String {
self.span_to_expanded_string_internal(sp, "")
}
fn span_to_expanded_string_internal(&self, sp:Span, indent: &str) -> String {
let mut indent = indent.to_owned();
let mut output = "".to_owned();
let span_str = self.span_to_string(sp);
let mut span_snip = self.span_to_snippet(sp)
.unwrap_or("Snippet unavailable".to_owned());
// Truncate by code points - in worst case this will be more than 50 characters,
// but ensures at least 50 characters and respects byte boundaries.
let char_vec: Vec<(usize, char)> = span_snip.char_indices().collect();
if char_vec.len() > 50 {
span_snip.truncate(char_vec[49].0);
span_snip.push_str("...");
}
output.push_str(&format!("{}{}\n{}`{}`\n", indent, span_str, indent, span_snip));
if sp.expn_id == NO_EXPANSION || sp.expn_id == COMMAND_LINE_EXPN {
return output;
}
let mut callee = self.with_expn_info(sp.expn_id,
|ei| ei.and_then(|ei| ei.callee.span.clone()));
let mut callsite = self.with_expn_info(sp.expn_id,
|ei| ei.map(|ei| ei.call_site.clone()));
indent.push_str(" ");
let mut is_recursive = false;
while callee.is_some() && self.match_callees(&sp, &callee.unwrap()) {
callee = self.with_expn_info(callee.unwrap().expn_id,
|ei| ei.and_then(|ei| ei.callee.span.clone()));
is_recursive = true;
}
if let Some(span) = callee {
output.push_str(&indent);
output.push_str("Callee:\n");
if is_recursive {
output.push_str(&indent);
output.push_str("...\n");
}
output.push_str(&(self.span_to_expanded_string_internal(span, &indent)));
}
is_recursive = false;
while callsite.is_some() && self.match_callees(&sp, &callsite.unwrap()) {
callsite = self.with_expn_info(callsite.unwrap().expn_id,
|ei| ei.map(|ei| ei.call_site.clone()));
is_recursive = true;
}
if let Some(span) = callsite {
output.push_str(&indent);
output.push_str("Callsite:\n");
if is_recursive {
output.push_str(&indent);
output.push_str("...\n");
}
output.push_str(&(self.span_to_expanded_string_internal(span, &indent)));
}
output
}
/// Return the source span - this is either the supplied span, or the span for
/// the macro callsite that expanded to it.
pub fn source_callsite(&self, sp: Span) -> Span {
let mut span = sp;
// Special case - if a macro is parsed as an argument to another macro, the source
// callsite is the first callsite, which is also source-equivalent to the span.
let mut first = true;
while span.expn_id != NO_EXPANSION && span.expn_id != COMMAND_LINE_EXPN {
if let Some(callsite) = self.with_expn_info(span.expn_id,
|ei| ei.map(|ei| ei.call_site.clone())) {
if first && span.source_equal(&callsite) {
if self.lookup_char_pos(span.lo).file.is_real_file() {
return Span { expn_id: NO_EXPANSION, .. span };
}
}
first = false;
span = callsite;
}
else {
break;
}
}
span
}
/// Return the source callee.
///
/// Returns None if the supplied span has no expansion trace,
/// else returns the NameAndSpan for the macro definition
/// corresponding to the source callsite.
pub fn source_callee(&self, sp: Span) -> Option<NameAndSpan> {
let mut span = sp;
// Special case - if a macro is parsed as an argument to another macro, the source
// callsite is source-equivalent to the span, and the source callee is the first callee.
let mut first = true;
while let Some(callsite) = self.with_expn_info(span.expn_id,
|ei| ei.map(|ei| ei.call_site.clone())) {
if first && span.source_equal(&callsite) {
if self.lookup_char_pos(span.lo).file.is_real_file() {
return self.with_expn_info(span.expn_id,
|ei| ei.map(|ei| ei.callee.clone()));
}
}
first = false;
if let Some(_) = self.with_expn_info(callsite.expn_id,
|ei| ei.map(|ei| ei.call_site.clone())) {
span = callsite;
}
else {
return self.with_expn_info(span.expn_id,
|ei| ei.map(|ei| ei.callee.clone()));
}
}
None
}
pub fn span_to_filename(&self, sp: Span) -> FileName {
self.lookup_char_pos(sp.lo).file.name.to_string()
}
pub fn span_to_lines(&self, sp: Span) -> FileLinesResult {
if sp.lo > sp.hi {
return Err(SpanLinesError::IllFormedSpan(sp));
}
let lo = self.lookup_char_pos(sp.lo);
let hi = self.lookup_char_pos(sp.hi);
if lo.file.start_pos != hi.file.start_pos {
return Err(SpanLinesError::DistinctSources(DistinctSources {
begin: (lo.file.name.clone(), lo.file.start_pos),
end: (hi.file.name.clone(), hi.file.start_pos),
}));
}
assert!(hi.line >= lo.line);
let mut lines = Vec::with_capacity(hi.line - lo.line + 1);
// The span starts partway through the first line,
// but after that it starts from offset 0.
let mut start_col = lo.col;
// For every line but the last, it extends from `start_col`
// and to the end of the line. Be careful because the line
// numbers in Loc are 1-based, so we subtract 1 to get 0-based
// lines.
for line_index in lo.line-1 .. hi.line-1 {
let line_len = lo.file.get_line(line_index).map(|s| s.len()).unwrap_or(0);
lines.push(LineInfo { line_index: line_index,
start_col: start_col,
end_col: CharPos::from_usize(line_len) });
start_col = CharPos::from_usize(0);
}
// For the last line, it extends from `start_col` to `hi.col`:
lines.push(LineInfo { line_index: hi.line - 1,
start_col: start_col,
end_col: hi.col });
Ok(FileLines {file: lo.file, lines: lines})
}
pub fn span_to_snippet(&self, sp: Span) -> Result<String, SpanSnippetError> {
if sp.lo > sp.hi {
return Err(SpanSnippetError::IllFormedSpan(sp));
}
let local_begin = self.lookup_byte_offset(sp.lo);
let local_end = self.lookup_byte_offset(sp.hi);
if local_begin.fm.start_pos != local_end.fm.start_pos {
return Err(SpanSnippetError::DistinctSources(DistinctSources {
begin: (local_begin.fm.name.clone(),
local_begin.fm.start_pos),
end: (local_end.fm.name.clone(),
local_end.fm.start_pos)
}));
} else {
match local_begin.fm.src {
Some(ref src) => {
let start_index = local_begin.pos.to_usize();
let end_index = local_end.pos.to_usize();
let source_len = (local_begin.fm.end_pos -
local_begin.fm.start_pos).to_usize();
if start_index > end_index || end_index > source_len {
return Err(SpanSnippetError::MalformedForCodemap(
MalformedCodemapPositions {
name: local_begin.fm.name.clone(),
source_len: source_len,
begin_pos: local_begin.pos,
end_pos: local_end.pos,
}));
}
return Ok((&src[start_index..end_index]).to_string())
}
None => {
return Err(SpanSnippetError::SourceNotAvailable {
filename: local_begin.fm.name.clone()
});
}
}
}
}
/// Groups and sorts spans by lines into `MultiSpan`s, where `push` adds them to their group,
/// specifying the unification behaviour for overlapping spans.
/// Spans overflowing a line are put into their own one-element-group.
pub fn custom_group_spans<F>(&self, mut spans: Vec<Span>, push: F) -> Vec<MultiSpan>
where F: Fn(&mut MultiSpan, Span)
{
spans.sort_by(|a, b| a.lo.cmp(&b.lo));
let mut groups = Vec::<MultiSpan>::new();
let mut overflowing = vec![];
let mut prev_expn = ExpnId(!2u32);
let mut prev_file = !0usize;
let mut prev_line = !0usize;
let mut err_size = 0;
for sp in spans {
let line = self.lookup_char_pos(sp.lo).line;
let line_hi = self.lookup_char_pos(sp.hi).line;
if line != line_hi {
overflowing.push(sp.into());
continue
}
let file = self.lookup_filemap_idx(sp.lo);
if err_size < MAX_HIGHLIGHT_LINES && sp.expn_id == prev_expn && file == prev_file {
// `push` takes care of sorting, trimming, and merging
push(&mut groups.last_mut().unwrap(), sp);
if line != prev_line {
err_size += 1;
}
} else {
groups.push(sp.into());
err_size = 1;
}
prev_expn = sp.expn_id;
prev_file = file;
prev_line = line;
}
groups.extend(overflowing);
groups
}
/// Groups and sorts spans by lines into `MultiSpan`s, merging overlapping spans.
/// Spans overflowing a line are put into their own one-element-group.
pub fn group_spans(&self, spans: Vec<Span>) -> Vec<MultiSpan> {
self.custom_group_spans(spans, |msp, sp| msp.push_merge(sp))
}
/// Like `group_spans`, but trims overlapping spans instead of
/// merging them (for use with `end_highlight_lines`)
pub fn end_group_spans(&self, spans: Vec<Span>) -> Vec<MultiSpan> {
self.custom_group_spans(spans, |msp, sp| msp.push_trim(sp))
}
pub fn get_filemap(&self, filename: &str) -> Rc<FileMap> {
for fm in self.files.borrow().iter() {
if filename == fm.name {
return fm.clone();
}
}
panic!("asking for {} which we don't know about", filename);
}
/// For a global BytePos compute the local offset within the containing FileMap
pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos {
let idx = self.lookup_filemap_idx(bpos);
let fm = (*self.files.borrow())[idx].clone();
let offset = bpos - fm.start_pos;
FileMapAndBytePos {fm: fm, pos: offset}
}
/// Converts an absolute BytePos to a CharPos relative to the filemap.
pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos {
let idx = self.lookup_filemap_idx(bpos);
let files = self.files.borrow();
let map = &(*files)[idx];
// The number of extra bytes due to multibyte chars in the FileMap
let mut total_extra_bytes = 0;
for mbc in map.multibyte_chars.borrow().iter() {
debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos);
if mbc.pos < bpos {
// every character is at least one byte, so we only
// count the actual extra bytes.
total_extra_bytes += mbc.bytes - 1;
// We should never see a byte position in the middle of a
// character
assert!(bpos.to_usize() >= mbc.pos.to_usize() + mbc.bytes);
} else {
break;
}
}
assert!(map.start_pos.to_usize() + total_extra_bytes <= bpos.to_usize());
CharPos(bpos.to_usize() - map.start_pos.to_usize() - total_extra_bytes)
}
// Return the index of the filemap (in self.files) which contains pos.
fn lookup_filemap_idx(&self, pos: BytePos) -> usize {
let files = self.files.borrow();
let files = &*files;
let count = files.len();
// Binary search for the filemap.
let mut a = 0;
let mut b = count;
while b - a > 1 {
let m = (a + b) / 2;
if files[m].start_pos > pos {
b = m;
} else {
a = m;
}
}
assert!(a < count, "position {} does not resolve to a source location", pos.to_usize());
return a;
}
/// Check if the backtrace `subtrace` contains `suptrace` as a prefix.
pub fn more_specific_trace(&self,
mut subtrace: ExpnId,
suptrace: ExpnId)
-> bool {
loop {
if subtrace == suptrace {
return true;
}
let stop = self.with_expn_info(subtrace, |opt_expn_info| {
if let Some(expn_info) = opt_expn_info {
subtrace = expn_info.call_site.expn_id;
false
} else {
true
}
});
if stop {
return false;
}
}
}
pub fn record_expansion(&self, expn_info: ExpnInfo) -> ExpnId {
let mut expansions = self.expansions.borrow_mut();
expansions.push(expn_info);
let len = expansions.len();
if len > u32::max_value() as usize {
panic!("too many ExpnInfo's!");
}
ExpnId(len as u32 - 1)
}
pub fn with_expn_info<T, F>(&self, id: ExpnId, f: F) -> T where
F: FnOnce(Option<&ExpnInfo>) -> T,
{
match id {
NO_EXPANSION | COMMAND_LINE_EXPN => f(None),
ExpnId(i) => f(Some(&(*self.expansions.borrow())[i as usize]))
}
}
/// Check if a span is "internal" to a macro in which #[unstable]
/// items can be used (that is, a macro marked with
/// `#[allow_internal_unstable]`).
pub fn span_allows_unstable(&self, span: Span) -> bool {
debug!("span_allows_unstable(span = {:?})", span);
let mut allows_unstable = false;
let mut expn_id = span.expn_id;
loop {
let quit = self.with_expn_info(expn_id, |expninfo| {
debug!("span_allows_unstable: expninfo = {:?}", expninfo);
expninfo.map_or(/* hit the top level */ true, |info| {
let span_comes_from_this_expansion =
info.callee.span.map_or(span.source_equal(&info.call_site), |mac_span| {
mac_span.contains(span)
});
debug!("span_allows_unstable: span: {:?} call_site: {:?} callee: {:?}",
(span.lo, span.hi),
(info.call_site.lo, info.call_site.hi),
info.callee.span.map(|x| (x.lo, x.hi)));
debug!("span_allows_unstable: from this expansion? {}, allows unstable? {}",
span_comes_from_this_expansion,
info.callee.allow_internal_unstable);
if span_comes_from_this_expansion {
allows_unstable = info.callee.allow_internal_unstable;
// we've found the right place, stop looking
true
} else {
// not the right place, keep looking
expn_id = info.call_site.expn_id;
false
}
})
});
if quit {
break
}
}
debug!("span_allows_unstable? {}", allows_unstable);
allows_unstable
}
pub fn count_lines(&self) -> usize {
self.files.borrow().iter().fold(0, |a, f| a + f.count_lines())
}
}
// _____________________________________________________________________________
// SpanLinesError, SpanSnippetError, DistinctSources, MalformedCodemapPositions
//
pub type FileLinesResult = Result<FileLines, SpanLinesError>;
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanLinesError {
IllFormedSpan(Span),
DistinctSources(DistinctSources),
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SpanSnippetError {
IllFormedSpan(Span),
DistinctSources(DistinctSources),
MalformedForCodemap(MalformedCodemapPositions),
SourceNotAvailable { filename: String }
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct DistinctSources {
begin: (String, BytePos),
end: (String, BytePos)
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct MalformedCodemapPositions {
name: String,
source_len: usize,
begin_pos: BytePos,
end_pos: BytePos
}
// _____________________________________________________________________________
// Tests
//
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t1 () {
let cm = CodeMap::new();
let fm = cm.new_filemap("blork.rs".to_string(),
"first line.\nsecond line".to_string());
fm.next_line(BytePos(0));
// Test we can get lines with partial line info.
assert_eq!(fm.get_line(0), Some("first line."));
// TESTING BROKEN BEHAVIOR: line break declared before actual line break.
fm.next_line(BytePos(10));
assert_eq!(fm.get_line(1), Some("."));
fm.next_line(BytePos(12));
assert_eq!(fm.get_line(2), Some("second line"));
}
#[test]
#[should_panic]
fn t2 () {
let cm = CodeMap::new();
let fm = cm.new_filemap("blork.rs".to_string(),
"first line.\nsecond line".to_string());
// TESTING *REALLY* BROKEN BEHAVIOR:
fm.next_line(BytePos(0));
fm.next_line(BytePos(10));
fm.next_line(BytePos(2));
}
fn init_code_map() -> CodeMap {
let cm = CodeMap::new();
let fm1 = cm.new_filemap("blork.rs".to_string(),
"first line.\nsecond line".to_string());
let fm2 = cm.new_filemap("empty.rs".to_string(),
"".to_string());
let fm3 = cm.new_filemap("blork2.rs".to_string(),
"first line.\nsecond line".to_string());
fm1.next_line(BytePos(0));
fm1.next_line(BytePos(12));
fm2.next_line(fm2.start_pos);
fm3.next_line(fm3.start_pos);
fm3.next_line(fm3.start_pos + BytePos(12));
cm
}
#[test]
fn t3() {
// Test lookup_byte_offset
let cm = init_code_map();
let fmabp1 = cm.lookup_byte_offset(BytePos(23));
assert_eq!(fmabp1.fm.name, "blork.rs");
assert_eq!(fmabp1.pos, BytePos(23));
let fmabp1 = cm.lookup_byte_offset(BytePos(24));
assert_eq!(fmabp1.fm.name, "empty.rs");
assert_eq!(fmabp1.pos, BytePos(0));
let fmabp2 = cm.lookup_byte_offset(BytePos(25));
assert_eq!(fmabp2.fm.name, "blork2.rs");
assert_eq!(fmabp2.pos, BytePos(0));
}
#[test]
fn t4() {
// Test bytepos_to_file_charpos
let cm = init_code_map();
let cp1 = cm.bytepos_to_file_charpos(BytePos(22));
assert_eq!(cp1, CharPos(22));
let cp2 = cm.bytepos_to_file_charpos(BytePos(25));
assert_eq!(cp2, CharPos(0));
}
#[test]
fn t5() {
// Test zero-length filemaps.
let cm = init_code_map();
let loc1 = cm.lookup_char_pos(BytePos(22));
assert_eq!(loc1.file.name, "blork.rs");
assert_eq!(loc1.line, 2);
assert_eq!(loc1.col, CharPos(10));
let loc2 = cm.lookup_char_pos(BytePos(25));
assert_eq!(loc2.file.name, "blork2.rs");
assert_eq!(loc2.line, 1);
assert_eq!(loc2.col, CharPos(0));
}
fn init_code_map_mbc() -> CodeMap {
let cm = CodeMap::new();
// € is a three byte utf8 char.
let fm1 =
cm.new_filemap("blork.rs".to_string(),
"fir€st €€€€ line.\nsecond line".to_string());
let fm2 = cm.new_filemap("blork2.rs".to_string(),
"first line€€.\n€ second line".to_string());
fm1.next_line(BytePos(0));
fm1.next_line(BytePos(28));
fm2.next_line(fm2.start_pos);
fm2.next_line(fm2.start_pos + BytePos(20));
fm1.record_multibyte_char(BytePos(3), 3);
fm1.record_multibyte_char(BytePos(9), 3);
fm1.record_multibyte_char(BytePos(12), 3);
fm1.record_multibyte_char(BytePos(15), 3);
fm1.record_multibyte_char(BytePos(18), 3);
fm2.record_multibyte_char(fm2.start_pos + BytePos(10), 3);
fm2.record_multibyte_char(fm2.start_pos + BytePos(13), 3);
fm2.record_multibyte_char(fm2.start_pos + BytePos(18), 3);
cm
}
#[test]
fn t6() {
// Test bytepos_to_file_charpos in the presence of multi-byte chars
let cm = init_code_map_mbc();
let cp1 = cm.bytepos_to_file_charpos(BytePos(3));
assert_eq!(cp1, CharPos(3));
let cp2 = cm.bytepos_to_file_charpos(BytePos(6));
assert_eq!(cp2, CharPos(4));
let cp3 = cm.bytepos_to_file_charpos(BytePos(56));
assert_eq!(cp3, CharPos(12));
let cp4 = cm.bytepos_to_file_charpos(BytePos(61));
assert_eq!(cp4, CharPos(15));
}
#[test]
fn t7() {
// Test span_to_lines for a span ending at the end of filemap
let cm = init_code_map();
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
let file_lines = cm.span_to_lines(span).unwrap();
assert_eq!(file_lines.file.name, "blork.rs");
assert_eq!(file_lines.lines.len(), 1);
assert_eq!(file_lines.lines[0].line_index, 1);
}
/// Given a string like " ^~~~~~~~~~~~ ", produces a span
/// coverting that range. The idea is that the string has the same
/// length as the input, and we uncover the byte positions. Note
/// that this can span lines and so on.
fn span_from_selection(input: &str, selection: &str) -> Span {
assert_eq!(input.len(), selection.len());
let left_index = selection.find('^').unwrap() as u32;
let right_index = selection.rfind('~').map(|x|x as u32).unwrap_or(left_index);
Span { lo: BytePos(left_index), hi: BytePos(right_index + 1), expn_id: NO_EXPANSION }
}
/// Test span_to_snippet and span_to_lines for a span coverting 3
/// lines in the middle of a file.
#[test]
fn span_to_snippet_and_lines_spanning_multiple_lines() {
let cm = CodeMap::new();
let inputtext = "aaaaa\nbbbbBB\nCCC\nDDDDDddddd\neee\n";
let selection = " \n ^~\n~~~\n~~~~~ \n \n";
cm.new_filemap_and_lines("blork.rs", inputtext);
let span = span_from_selection(inputtext, selection);
// check that we are extracting the text we thought we were extracting
assert_eq!(&cm.span_to_snippet(span).unwrap(), "BB\nCCC\nDDDDD");
// check that span_to_lines gives us the complete result with the lines/cols we expected
let lines = cm.span_to_lines(span).unwrap();
let expected = vec![
LineInfo { line_index: 1, start_col: CharPos(4), end_col: CharPos(6) },
LineInfo { line_index: 2, start_col: CharPos(0), end_col: CharPos(3) },
LineInfo { line_index: 3, start_col: CharPos(0), end_col: CharPos(5) }
];
assert_eq!(lines.lines, expected);
}
#[test]
fn t8() {
// Test span_to_snippet for a span ending at the end of filemap
let cm = init_code_map();
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
let snippet = cm.span_to_snippet(span);
assert_eq!(snippet, Ok("second line".to_string()));
}
#[test]
fn t9() {
// Test span_to_str for a span ending at the end of filemap
let cm = init_code_map();
let span = Span {lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION};
let sstr = cm.span_to_string(span);
assert_eq!(sstr, "blork.rs:2:1: 2:12");
}
#[test]
fn t10() {
// Test span_to_expanded_string works in base case (no expansion)
let cm = init_code_map();
let span = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
let sstr = cm.span_to_expanded_string(span);
assert_eq!(sstr, "blork.rs:1:1: 1:12\n`first line.`\n");
let span = Span { lo: BytePos(12), hi: BytePos(23), expn_id: NO_EXPANSION };
let sstr = cm.span_to_expanded_string(span);
assert_eq!(sstr, "blork.rs:2:1: 2:12\n`second line`\n");
}
#[test]
fn t11() {
// Test span_to_expanded_string works with expansion
use ast::Name;
let cm = init_code_map();
let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
let format = ExpnFormat::MacroBang(Name(0u32));
let callee = NameAndSpan { format: format,
allow_internal_unstable: false,
span: None };
let info = ExpnInfo { call_site: root, callee: callee };
let id = cm.record_expansion(info);
let sp = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id };
let sstr = cm.span_to_expanded_string(sp);
assert_eq!(sstr,
"blork.rs:2:1: 2:12\n`second line`\n Callsite:\n \
blork.rs:1:1: 1:12\n `first line.`\n");
}
fn init_expansion_chain(cm: &CodeMap) -> Span {
// Creates an expansion chain containing two recursive calls
// root -> expA -> expA -> expB -> expB -> end
use ast::Name;
let root = Span { lo: BytePos(0), hi: BytePos(11), expn_id: NO_EXPANSION };
let format_root = ExpnFormat::MacroBang(Name(0u32));
let callee_root = NameAndSpan { format: format_root,
allow_internal_unstable: false,
span: Some(root) };
let info_a1 = ExpnInfo { call_site: root, callee: callee_root };
let id_a1 = cm.record_expansion(info_a1);
let span_a1 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a1 };
let format_a = ExpnFormat::MacroBang(Name(1u32));
let callee_a = NameAndSpan { format: format_a,
allow_internal_unstable: false,
span: Some(span_a1) };
let info_a2 = ExpnInfo { call_site: span_a1, callee: callee_a.clone() };
let id_a2 = cm.record_expansion(info_a2);
let span_a2 = Span { lo: BytePos(12), hi: BytePos(23), expn_id: id_a2 };
let info_b1 = ExpnInfo { call_site: span_a2, callee: callee_a };
let id_b1 = cm.record_expansion(info_b1);
let span_b1 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b1 };
let format_b = ExpnFormat::MacroBang(Name(2u32));
let callee_b = NameAndSpan { format: format_b,
allow_internal_unstable: false,
span: None };
let info_b2 = ExpnInfo { call_site: span_b1, callee: callee_b.clone() };
let id_b2 = cm.record_expansion(info_b2);
let span_b2 = Span { lo: BytePos(25), hi: BytePos(36), expn_id: id_b2 };
let info_end = ExpnInfo { call_site: span_b2, callee: callee_b };
let id_end = cm.record_expansion(info_end);
Span { lo: BytePos(37), hi: BytePos(48), expn_id: id_end }
}
#[test]
fn t12() {
// Test span_to_expanded_string collapses recursive macros and handles
// recursive callsite and callee expansions
let cm = init_code_map();
let end = init_expansion_chain(&cm);
let sstr = cm.span_to_expanded_string(end);
let res_str =
r"blork2.rs:2:1: 2:12
`second line`
Callsite:
...
blork2.rs:1:1: 1:12
`first line.`
Callee:
blork.rs:2:1: 2:12
`second line`
Callee:
blork.rs:1:1: 1:12
`first line.`
Callsite:
blork.rs:1:1: 1:12
`first line.`
Callsite:
...
blork.rs:2:1: 2:12
`second line`
Callee:
blork.rs:1:1: 1:12
`first line.`
Callsite:
blork.rs:1:1: 1:12
`first line.`
";
assert_eq!(sstr, res_str);
}
#[test]
fn t13() {
// Test that collecting multiple spans into line-groups works correctly
let cm = CodeMap::new();
let inp = "_aaaaa__bbb\nvv\nw\nx\ny\nz\ncccccc__ddddee__";
let sp1 = " ^~~~~ \n \n \n \n \n \n ";
let sp2 = " \n \n \n \n \n^\n ";
let sp3 = " ^~~\n~~\n \n \n \n \n ";
let sp4 = " \n \n \n \n \n \n^~~~~~ ";
let sp5 = " \n \n \n \n \n \n ^~~~ ";
let sp6 = " \n \n \n \n \n \n ^~~~ ";
let sp_trim = " \n \n \n \n \n \n ^~ ";
let sp_merge = " \n \n \n \n \n \n ^~~~~~ ";
let sp7 = " \n ^\n \n \n \n \n ";
let sp8 = " \n \n^\n \n \n \n ";
let sp9 = " \n \n \n^\n \n \n ";
let sp10 = " \n \n \n \n^\n \n ";
let span = |sp, expected| {
let sp = span_from_selection(inp, sp);
assert_eq!(&cm.span_to_snippet(sp).unwrap(), expected);
sp
};
cm.new_filemap_and_lines("blork.rs", inp);
let sp1 = span(sp1, "aaaaa");
let sp2 = span(sp2, "z");
let sp3 = span(sp3, "bbb\nvv");
let sp4 = span(sp4, "cccccc");
let sp5 = span(sp5, "dddd");
let sp6 = span(sp6, "ddee");
let sp7 = span(sp7, "v");
let sp8 = span(sp8, "w");
let sp9 = span(sp9, "x");
let sp10 = span(sp10, "y");
let sp_trim = span(sp_trim, "ee");
let sp_merge = span(sp_merge, "ddddee");
let spans = vec![sp5, sp2, sp4, sp9, sp10, sp7, sp3, sp8, sp1, sp6];
macro_rules! check_next {
($groups: expr, $expected: expr) => ({
let actual = $groups.next().map(|g|&g.spans[..]);
let expected = $expected;
println!("actual:\n{:?}\n", actual);
println!("expected:\n{:?}\n", expected);
assert_eq!(actual, expected.as_ref().map(|x|&x[..]));
});
}
let _groups = cm.group_spans(spans.clone());
let it = &mut _groups.iter();
check_next!(it, Some([sp1, sp7, sp8, sp9, sp10, sp2]));
// New group because we're exceeding MAX_HIGHLIGHT_LINES
check_next!(it, Some([sp4, sp_merge]));
check_next!(it, Some([sp3]));
check_next!(it, None::<[Span; 0]>);
let _groups = cm.end_group_spans(spans);
let it = &mut _groups.iter();
check_next!(it, Some([sp1, sp7, sp8, sp9, sp10, sp2]));
// New group because we're exceeding MAX_HIGHLIGHT_LINES
check_next!(it, Some([sp4, sp5, sp_trim]));
check_next!(it, Some([sp3]));
check_next!(it, None::<[Span; 0]>);
}
}
| {
let mut idx_merged = None;
for idx in 0.. {
let cur = match self.spans.get(idx) {
Some(s) => *s,
None => break,
};
// Try to merge with a contained Span
if let Some(union) = cur.merge(sp) {
self.spans[idx] = union;
sp = union;
idx_merged = Some(idx);
break;
}
// Or insert into the first sorted position
if sp.hi <= cur.lo {
self.spans.insert(idx, sp);
idx_merged = Some(idx);
break;
}
}
if let Some(idx) = idx_merged {
// Merge with spans trailing the insertion/merging position
while (idx + 1) < self.spans.len() {
if let Some(union) = self.spans[idx + 1].merge(sp) {
self.spans[idx] = union;
self.spans.remove(idx + 1);
} else {
break;
}
}
} else {
self.spans.push(sp);
}
} |
MediaBlock.tsx | import styles from './MediaBlock.module.scss';
import { Component } from 'react';
import { MediaLinkItem } from '../../typings';
import MediaLink from '../media-link/MediaLink';
| private readonly items: MediaLinkItem[] = [
{
url: "https://dev.to/koddr/build-a-restful-api-on-go-fiber-postgresql-jwt-and-swagger-docs-in-isolated-docker-containers-475j",
website: "dev.to",
title: "📖 Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers",
author: "Vic Shóstak",
date: "march 22, 2021"
},
{
url: "https://dev.to/fenny/getting-started-with-fiber-36b6",
website: "dev.to",
title: "Getting started with Fiber ⚡",
author: "Fenny 🔥",
date: "june 10, 2020"
},
{
url: "https://blog.logrocket.com/express-style-api-go-fiber/",
website: "logrocket.com",
title: "Building an Express-style API in Go with Fiber",
author: "Alexander Nnakwue",
date: "june 10, 2020"
},
{
url: "https://vugt.me/the-road-to-web-based-authentication-with-fiber/",
website: "vugt.me",
title: "The road to web-based authentication with Fiber ⚡",
author: "Thomas van Vugt",
date: "May 20, 2020"
},
{
url: "https://dev.to/koddr/fiber-v1-9-5-how-to-improve-performance-by-817-and-stay-fast-flexible-and-friendly-2dp6",
website: "dev.to",
title: "Fiber v1.9.6 🔥 How to improve performance by 817% and stay fast, flexible and friendly?",
author: "Vic Shóstak",
date: "May 12, 2020"
},
{
url: "https://blog.yongweilun.me/create-a-travel-list-app-with-go-fiber-angular-mongodb-and-google-cloud-secret-manager-ck9fgxy0p061pcss1xt1ubu8t",
website: "yongweilun.me",
title: "🌎 Create a travel list app with Go, Fiber, Angular, MongoDB and Google Cloud Secret Manager",
author: "Wei Lun",
date: "April 25, 2020"
},
{
url: "https://tutorialedge.net/golang/basic-rest-api-go-fiber/",
website: "tutorialedge.net",
title: "Building a Basic REST API in Go using Fiber",
author: "Elliot Forbes",
date: "April 23, 2020"
},
{
url:
"https://dev.to/jozsefsallai/creating-fast-apis-in-go-using-fiber-59m9",
website: "dev.to",
title: "Creating Fast APIs In Go Using Fiber",
author: "József Sallai",
date: "April 7, 2020"
},
{
url:
"https://dev.to/koddr/are-sure-what-your-lovely-web-framework-running-so-fast-2jl1",
website: "dev.to",
title: "Is switching from Express to Fiber worth it? 🤔",
author: "Vic Shóstak",
date: "April 1, 2020"
},
{
url:
"https://dev.to/koddr/fiber-v1-8-what-s-new-updated-and-re-thinked-339h",
website: "dev.to",
title: "🚀 Fiber v1.8. What's new, updated and re-thinked?",
author: "Vic Shóstak",
date: "March 3, 2020"
},
{
url:
"https://dev.to/koddr/fiber-v2-is-out-now-what-s-new-and-is-he-still-fast-flexible-and-friendly-3ipf",
website: "dev.to",
title:
"Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?",
author: "Vic Shóstak",
date: "February 21, 2020"
},
{
url:
"https://dev.to/koddr/welcome-to-fiber-an-express-js-styled-fastest-web-framework-written-with-on-golang-497",
website: "dev.to",
title:
"Welcome to Fiber — an Express.js styled web framework written in Go with ❤️",
author: "Vic Shóstak",
date: "February 3, 2020"
}
];
render() {
return (
<section className={`generic-block faint reverse ${styles.mediaBlock}`}>
<div className={`mid ${styles.mid}`}>
<div className="media-container">
<h3>Media</h3>
<div className={styles.mediaLinks}>
{this.items.map((data, idx) => <MediaLink data={data} key={idx} />)}
</div>
</div>
</div>
</section>
);
}
}
export default MediaBlock; | class MediaBlock extends Component { |
ObserverData.py | # -----------------------------------------------------------------------------
# Name: ObserverData.py
# Purpose: Observer Database routines
#
# Author: Will Smith <[email protected]>
#
# Created: Jan - July, 2016
# License: MIT
# ------------------------------------------------------------------------------
# Python implementation of Observer data class
from operator import itemgetter
from PyQt5.QtCore import pyqtProperty, QObject, QVariant
from py.observer.ObserverDBUtil import ObserverDBUtil
from py.observer.ObserverDBModels import Lookups, Users, Vessels, \
Programs, Contacts, VesselContacts, Ports, CatchCategories, IfqDealers, Species
from py.observer.ObserverUsers import ObserverUsers
import logging
import unittest
class ObserverData(QObject):
"""
Handles details of various Observer data
(from database, etc)
"""
# A special MIX species for use within OPTECS.
# Used to divert MIX baskets, which are unspeciated, to CATCH_ADDITIONAL_BASKETS rather than
# SPECIES_COMPOSITION_BASKETS.
MIX_PACFIN_CODE = 'MIX'
MIX_SPECIES_CODE = 99999
def __init__(self):
super(ObserverData, self).__init__()
self._logger = logging.getLogger(__name__)
self._observers = None
self._observers_keys = None
self._vessels = None
self._lookup_fisheries = None # Fisheries in LOOKUPS table - purpose unclear
self._captains = None # Skippers
self._captain_vessel_id = None
self._ports = None
self._catch_categories = None
self._trawl_gear_types = None
self._fg_gear_types = None
self._first_receivers = None
self._species = None
self._lookups = None
# Get data tables
self._get_observers_orm()
self._get_vessels_orm()
self._get_captains_orm()
self._get_ports_orm()
self._get_catch_categories_orm()
self._get_first_receivers_orm()
self._get_species_orm()
# Data from LOOKUPS table
self._get_lookups_orm()
self._weightmethods = self._build_lookup_data('WEIGHT_METHOD')
self._sc_samplemethods = self._build_lookup_data('SC_SAMPLE_METHOD')
self._discardreasons = self._build_lookup_data('DISCARD_REASON', values_in_text=False)
self._vesseltypes = self._build_lookup_data('VESSEL_TYPE')
self._beaufort = self._get_beaufort_dict()
self._gearperf = self._get_gearperf_trawl_dict()
self._gearperf_fg = self._get_gearperf_fg_dict()
self._trawl_gear_types = self._get_trawl_gear_list() # Single field, key + desc concatenated
self._fg_gear_types = self._get_fg_gear_list() # Single field, key + desc concatenated
self._soaktimes = self._get_avg_soaktimes_list()
self._bs_samplemethods = sorted(self._list_lookup_desc('BS_SAMPLE_METHOD', values_in_text=True))
self._vessellogbooknames = self._list_lookup_desc('VESSEL_LOGBOOK_NAME')
self._create_mix_species_if_not_present()
def _create_mix_species_if_not_present(self):
"""
Check SPECIES table for 'MIX' pacfin code, if not there, create it.
Scientific name, commmon name, and PacFIN code are all 'MIX'.
Species ID and species code are both 99999.
"""
current_user_id = ObserverDBUtil.get_current_user_id()
created_date = ObserverDBUtil.get_arrow_datestr(date_format=ObserverDBUtil.oracle_date_format)
mix_species_info = {
'species': ObserverData.MIX_SPECIES_CODE,
'scientific_name': ObserverData.MIX_PACFIN_CODE,
'common_name': ObserverData.MIX_PACFIN_CODE,
'species_code': ObserverData.MIX_SPECIES_CODE,
'pacfin_code': ObserverData.MIX_PACFIN_CODE,
'created_by': current_user_id if current_user_id else 1,
'created_date': created_date,
}
try:
Species.get(Species.pacfin_code == 'MIX')
self._logger.info('MIX exists in SPECIES table.')
except Species.DoesNotExist:
self._logger.info('Adding MIX to SPECIES table (one-time operation)')
Species.create(**mix_species_info)
@staticmethod
def make_username(user_model):
return user_model.first_name + ' ' + user_model.last_name
def _get_observers_orm(self, rebuild=False):
"""
Get observers from database via ORM, store DB keys
"""
if self._observers is not None and not rebuild: # only build this once
return
self._observers = list()
self._observers_keys = dict()
obs_q = Users.select()
for obs in obs_q:
username = self.make_username(obs)
self._observers.append(username)
self._observers_keys[username] = obs
self._observers = sorted(self._observers) # Sort Alphabetically - should we do this by last name instead?
def _get_vessels_orm(self, rebuild=False):
"""
Get vessels from database via ORM, store DB keys
"""
if self._vessels is not None and not rebuild: # only build this once
return
self._vessels = list()
vess_q = Vessels.select().where(Vessels.vessel_status.not_in(['S', 'I', 'R'])) # Not sunk, inactive, retired
for vessel in vess_q:
vessel_number = vessel.coast_guard_number
if not vessel_number or len(vessel_number) < 1:
vessel_number = vessel.state_reg_number
vessel_entry = '{} - {}'.format(vessel.vessel_name.upper(), vessel_number)
self._vessels.append(vessel_entry)
self._vessels = sorted(self._vessels) # Don't Remove Duplicates + Sort Alphabetically
def _get_programs_orm(self, rebuild=False):
"""
Get programs from database via ORM, store DB keys
"""
if self._programs is not None and not rebuild: # only build this once
return
self._programs = list()
fish_q = Programs.select()
for fishery in fish_q:
self._programs.append(fishery.program_name)
self._programs = sorted(set(self._programs)) # Remove Duplicates + Sort Alphabetically
def _get_captains_orm(self, rebuild=False):
"""
Get skippers from database via ORM, store DB keys
"""
if self._captains is not None and not rebuild: # only build this once
return
self._captains = list()
if self._captain_vessel_id:
captains_q = Contacts.select(). \
join(VesselContacts, on=(Contacts.contact == VesselContacts.contact)). \
where(
(Contacts.contact_category == 3) & # Vessel category
(VesselContacts.contact_status != 'NA') &
(VesselContacts.vessel == self._captain_vessel_id) & # Vessel ID
((VesselContacts.contact_type == 1) | # Skipper
(VesselContacts.contact_type == 3))) # Skipper/ Owner
else:
captains_q = Contacts.select(). \
join(VesselContacts, on=(Contacts.contact == VesselContacts.contact)). \
where(
(VesselContacts.contact_status != 'NA') &
(Contacts.contact_category == 3) & # Vessel
((VesselContacts.contact_type == 1) | # Skipper
(VesselContacts.contact_type == 3))) # Skipper/ Owner
for captain in captains_q:
if len(captain.first_name) > 0:
self._captains.append(captain.first_name + ' ' + captain.last_name)
self._captains = sorted(set(self._captains)) # Remove Duplicates + Sort Alphabetically
def _get_first_receivers_orm(self, rebuild=False):
"""
Get first receivers from database via ORM, store DB keys
@return: dict of values and PK
"""
if self._first_receivers is not None and not rebuild: # only build this once
return
self._first_receivers = list()
fr_q = IfqDealers. \
select(IfqDealers, Ports). \
join(Ports, on=(IfqDealers.port_code == Ports.ifq_port_code).alias('port')). \
where(IfqDealers.active == 1)
for fr in fr_q:
fr_line = '{} {}'.format(fr.dealer_name, fr.port.port_name)
# self._logger.info(fr_line)
self._first_receivers.append(fr_line)
self._first_receivers = sorted(self._first_receivers)
def _get_catch_categories_orm(self, rebuild=False):
"""
To support autocomplete, get catch categories from database via ORM, store DB keys
"""
if self._catch_categories is not None and not rebuild: # only build this once
return
self._catch_categories = list()
catch_q = CatchCategories.select().where(CatchCategories.active.is_null(True))
for cc in catch_q:
self._catch_categories.append('{} {}'.format(cc.catch_category_code, cc.catch_category_name))
self._catch_categories = sorted(self._catch_categories) # Sort Alphabetically
def _get_ports_orm(self, rebuild=False):
"""
Get ports from database via ORM, store DB keys
"""
if self._ports is not None and not rebuild: # only build this once
return
self._ports = list()
port_q = Ports.select()
for port in port_q:
self._ports.append(port.port_name.title()) # Title case
self._ports = sorted(set(self._ports)) # Remove Duplicates + Sort Alphabetically
def _get_species_orm(self, rebuild=False):
"""
To support autocomplete, get catch categories from database via ORM, store DB keys
"""
if self._species is not None and not rebuild: # only build this once
return
self._species = list()
species_q = Species.select().where(Species.active.is_null(True))
for s in species_q:
self._species.append('{}'.format(s.common_name))
self._species = sorted(self._species) # Sort Alphabetically
def get_observer_id(self, observer_name):
if observer_name in self._observers_keys:
return self._observers_keys[observer_name].user # USER_ID
else:
return None
def get_observer_name(self, observer_id):
obs = Users.get(Users.user == observer_id)
return self.make_username(obs)
@pyqtProperty(QVariant)
def catch_categories(self): # for autocomplete
return self._catchcategories
@pyqtProperty(QVariant)
def observers(self):
return self._observers
@pyqtProperty(QVariant)
def vessels(self):
return self._vessels
@pyqtProperty(QVariant)
def vessel_logbook_names(self):
return self._vessellogbooknames
@property
def weight_methods(self):
return self._weightmethods
@property
def sc_sample_methods(self):
return self._sc_samplemethods
@property
def species(self):
return self._species
@property
def bs_sample_methods(self):
return self._bs_samplemethods
@property
def vessel_types(self):
return self._vesseltypes
@property
def discard_reasons(self):
return self._discardreasons
@property
def catch_categories(self): # For AutoComplete
return self._catch_categories
@property
def trawl_gear_types(self): # For AutoComplete
return self._trawl_gear_types
@property
def fg_gear_types(self): # For AutoComplete
return self._fg_gear_types
@property
def beaufort(self):
return self._beaufort
@property
def soaktimes(self):
return self._soaktimes
@property
def gearperf(self):
return self._gearperf
@property
def gearperf_fg(self):
return self._gearperf_fg
@property
def first_receivers(self):
return self._first_receivers
@staticmethod
def get_fisheries_by_program_id(program_id, is_fg):
return ObserverUsers.get_fisheries_by_program_id(program_id, is_fg)
def _get_lookups_orm(self, rebuild=False):
"""
Get lookups via peewee ORM
:return:
"""
if self._lookups is not None and not rebuild: # only build this once unless rebuilt
return
self._lookups = dict() # of lists
# http://peewee.readthedocs.org/en/latest/peewee/querying.html#query-operators
lookups_q = Lookups.select().where((Lookups.active >> None) | (Lookups.active == 1))
for lu in lookups_q:
key = lu.lookup_type
if key in self._lookups:
self._lookups[key].append({'desc': lu.description, 'value': lu.lookup_value})
else:
self._lookups[key] = [{'desc': lu.description, 'value': lu.lookup_value}]
if len(self._lookups) == 0:
raise ConnectionError('Unable to get LOOKUPS from database, check observer DB')
# Build fisheries list
self._lookup_fisheries = list()
for fishery in self._lookups['FISHERY']:
self._lookup_fisheries.append(fishery['desc'])
self._lookup_fisheries = sorted(self._lookup_fisheries)
@pyqtProperty(QVariant)
def lookup_fisheries(self):
return self._lookup_fisheries
@pyqtProperty(QVariant)
def fisheries(self): # TODO do we want these or the lookup table entries?
return self._programs
@pyqtProperty(QVariant)
def captains(self):
return self._captains
@pyqtProperty(QVariant)
def captain_vessel_id(self):
return self._captain_vessel_id
@captain_vessel_id.setter
def captain_vessel_id(self, vessel_id):
self._logger.debug(f'Set Captain Vessel ID to {vessel_id}')
if vessel_id != self._captain_vessel_id:
self._captain_vessel_id = vessel_id
self._get_captains_orm(rebuild=True)
@pyqtProperty(QVariant)
def ports(self):
return self._ports
def _build_lookup_data(self, lookup_type, include_empty=True, values_in_text=True):
"""
Get values and descriptions from LOOKUPS
:param lookup_type: primary name of lookup
:param include_empty: include an extra empty item, useful for combo box with no default
:param values_in_text: include the value in the text descriptions returned
:return: list of dicts of the format [{'text': 'asf', 'value' 'somedata'}]
"""
if self._lookups is None:
self._get_lookups_orm()
lookupdata = list()
if include_empty:
lookupdata.append({'text': '-', 'value': '-1'}) # Create empty selection option
for data in self._lookups[lookup_type]:
if values_in_text:
lookupdata.append({'text': data['value'].zfill(2) + ' ' + data['desc'], # zfill for 0-padding
'value': data['value']})
else:
lookupdata.append({'text': data['desc'],
'value': data['value']})
lookupdata = sorted(lookupdata, key=itemgetter('text')) # Sort Alphabetically
return lookupdata
def _get_beaufort_dict(self):
"""
Build beaufort description dict
@return: dict of format {'0':'Description', ...}
"""
bvals = self._build_lookup_data('BEAUFORT_VALUE', include_empty=False, values_in_text=False)
return {b['value']: b['text'] for b in bvals}
def _get_soaktime_dict(self):
"""
Build avg soak time range description dict
@return: dict of format {'0':'Description', ...}
"""
bvals = self._build_lookup_data('AVG_SOAK_TIME_RANGE', include_empty=False, values_in_text=False)
return {b['value']: b['text'] for b in bvals}
def _get_gearperf_trawl_dict(self):
"""
Build gear performance description dict
@return: dict of format {'1':'Description', ...}
"""
gvals = self._build_lookup_data('GEAR_PERFORMANCE', include_empty=False, values_in_text=False)
return {b['value']: b['text'] for b in gvals}
def _get_gearperf_fg_dict(self):
"""
Build gear performance description dict for FG
NOTE The description for #5 is trawl based, so hardcoded the alternate text here
@return: dict of format {'1':'Description', ...}
"""
gvals = self._build_lookup_data('GEAR_PERFORMANCE', include_empty=False, values_in_text=False)
# FG - manually change this one value
for g in gvals:
if g['value'] == '5':
g['text'] = 'Problem - Pot(s) or other gear lost'
break
return {b['value']: b['text'] for b in gvals}
def _list_lookup_desc(self, lookup_type, values_in_text=False):
"""
Get simple list of values from LOOKUPS given a list created by _build_lookup_data
"""
lookup_data = self._build_lookup_data(lookup_type, include_empty=False, values_in_text=values_in_text)
lookuplistdata = list()
for datum in lookup_data:
lookuplistdata.append(datum['text'])
return sorted(lookuplistdata)
def _get_trawl_gear_list(self):
"""
Get the list of trawl gear types and descriptions, concatenated.
Sort by trawl type treated as integer.
:return: a list of strings of gear type value, space, and gear type description.
"""
gvals = self._build_lookup_data('TRAWL_GEAR_TYPE', include_empty=False, values_in_text=False)
# Sort by gear type - numerically, not alphabetically.
lookupdata = []
for entry in gvals:
entry['value_as_int'] = int(entry['value'])
lookupdata.append(entry)
lookupdata = sorted(lookupdata, key=itemgetter('value_as_int')) # Sort numerically by gear number.
return [str(entry['value_as_int']) + ' ' + entry['text'] for entry in lookupdata]
def _get_fg_gear_list(self):
"""
Get the list of fg gear types and descriptions, concatenated.
Sort by trawl type treated as integer.
:return: a list of strings of gear type value, space, and gear type description.
"""
gvals = self._build_lookup_data('FG_GEAR_TYPE', include_empty=False, values_in_text=False)
# Sort by gear type - numerically, not alphabetically.
lookupdata = []
for entry in gvals:
entry['value_as_int'] = int(entry['value'])
lookupdata.append(entry)
lookupdata = sorted(lookupdata, key=itemgetter('value_as_int')) # Sort numerically by gear number.
return [str(entry['value_as_int']) + ' ' + entry['text'] for entry in lookupdata]
def | (self):
"""
Get the list of avg soak times descriptions, concatenated.
Sort by # type treated as integer.
:return: a list of strings of soak time value, space, and soak time description.
"""
gvals = self._build_lookup_data('AVG_SOAK_TIME_RANGE', include_empty=False, values_in_text=False)
# Sort by gear type - numerically, not alphabetically.
lookupdata = []
for entry in gvals:
entry['value_as_int'] = int(entry['value'])
lookupdata.append(entry)
lookupdata = sorted(lookupdata, key=itemgetter('value_as_int')) # Sort numerically by gear number.
return [str(entry['value_as_int']) + ' ' + entry['text'] for entry in lookupdata]
class TestObserverData(unittest.TestCase):
"""
Test basic SQLite connectivity
"""
def setUp(self):
logging.basicConfig(level=logging.DEBUG)
self.testdata = ObserverData()
def test_connection(self):
self.assertIsNotNone(self.testdata.db_connection)
cursor = self.testdata.db_connection.cursor()
self.assertIsNotNone(cursor)
def test_beaufort(self):
beef = self.testdata._get_beaufort_dict()
self.assertGreater(len(beef['0']), 5)
self.assertGreater(len(beef['9']), 5)
def test_gearperf(self):
beef = self.testdata._get_gearperf_trawl_dict()
self.assertGreater(len(beef['1']), 5)
self.assertGreater(len(beef['7']), 5)
def test_observers(self):
logging.debug(self.testdata.observers)
self.assertGreater(len(self.testdata.observers), 10)
def test_vessels(self):
logging.debug(self.testdata.vessels)
self.assertGreater(len(self.testdata.vessels), 10)
def test_weightmethods(self):
logging.debug(self.testdata.weight_methods)
self.assertGreater(len(self.testdata.weight_methods), 10)
def test_vesseltypes(self):
logging.debug(self.testdata.vessel_types)
self.assertGreater(len(self.testdata.vessel_types), 5)
def test_vessellogbooknames(self):
logging.debug(self.testdata.vessel_logbook_names)
self.assertGreater(len(self.testdata.vessel_logbook_names), 5)
def test_discardreasons(self):
logging.debug(self.testdata.discard_reasons)
self.assertGreater(len(self.testdata.discard_reasons), 5)
def test_catchcategories(self):
logging.debug(self.testdata.catch_categories)
self.assertGreater(len(self.testdata.catch_categories), 200)
def test_trawlgeartypes(self):
logging.debug(self.testdata.trawl_gear_types)
self.assertEqual(len(self.testdata.trawl_gear_types), 12)
def test_lookups_orm(self):
"""
Compares old and new LOOKUPS select
:return:
"""
self.testdata._get_lookups()
copylookups = dict(self.testdata._lookups)
self.testdata._get_lookups_orm(rebuild=True)
self.assertGreater(len(copylookups), 0)
self.assertEqual(len(copylookups), len(self.testdata._lookups))
@unittest.skip("ObserverData no longer has a 'programs' attribute.")
def test_fisheries(self):
self.assertGreater(len(self.testdata.programs), 10)
logging.debug(self.testdata.programs)
def test_observers_orm(self):
"""
Compares old and new LOOKUPS select
:return:
"""
self.testdata._get_observers()
copyobs = list(self.testdata._observers)
self.testdata._get_observers_orm(rebuild=True)
self.assertGreater(len(copyobs), 0)
self.assertEqual(len(copyobs), len(self.testdata._observers))
def test_get_observer(self):
self.assertEqual(self.testdata.get_observer_id('Eric Brasseur'), 1484)
self.assertEqual(self.testdata.get_observer_name(1471), 'Amos Cernohouz')
if __name__ == '__main__':
unittest.main()
| _get_avg_soaktimes_list |
asgi.py | """
ASGI config for clubChinois project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
""" | import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'clubChinois.settings')
application = get_asgi_application() | |
runner.ts | // Setup env which is development, I have plan for dynamic by params on script
process.env.NODE_ENV = 'development'
import chalk from 'chalk'
import { say } from 'cfonts'
import electron from 'electron'
import path from 'path'
import PortFinder from 'portfinder'
import { spawn } from 'child_process'
import { watch } from 'rollup'
import { createServer } from 'vite'
import config from '../config'
// Setup options
import rendererOptions from './vite.config'
import rollupConfigOptions from './rollup.config'
let electronProcess = null
let manualRestart = false
function | (data: any, color: string) {
if (data) {
let log = ''
data = data.toString().split(/\r?\n/)
data.forEach((line: string) => {
log += ` ${line}\n`
})
if (/[0-9A-z]+/.test(log)) {
console.log(
chalk[color].bold(`┏ Electron -------------------`) +
'\n\n' +
log +
chalk[color].bold('┗ ----------------------------') +
'\n'
)
}
}
}
function logStats(proc: string, input: any) {
let log = ''
log += chalk.yellow.bold(
`┏ Process ${new Array(19 - proc.length + 1).join('-')}`
)
log += '\n\n'
if (typeof input === 'object') {
input
.toString({
colors: true,
chunks: false,
})
.split(/\r?\n/)
.forEach((line) => {
log += ' ' + line + '\n'
})
} else {
log += ` ${input}\n`
}
log += '\n' + chalk.yellow.bold(`┗ ${new Array(28 + 1).join('-')}`) + '\n'
console.log(log)
}
function removeJunk(chunk) {
if (config.dev.removeElectronJunk) {
// Example: 2018-08-10 22:48:42.866 Electron[90311:4883863] *** WARNING: Textured window <AtomNSWindow: 0x7fb75f68a770>
if (
/\d+-\d+-\d+ \d+:\d+:\d+\.\d+ Electron(?: Helper)?\[\d+:\d+] /.test(chunk)
) {
return false
}
// Example: [90789:0810/225804.894349:ERROR:CONSOLE(105)] "Uncaught (in promise) Error: Could not instantiate: ProductRegistryImpl.Registry", source: chrome-devtools://devtools/bundled/inspector.js (105)
if (/\[\d+:\d+\/|\d+\.\d+:ERROR:CONSOLE\(\d+\)\]/.test(chunk)) {
return false
}
// Example: ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
if (/ALSA lib [a-z]+\.c:\d+:\([a-z_]+\)/.test(chunk)) {
return false
}
}
return chunk
}
function sayHi() {
const cols = process.stdout.columns
// why use string & boolean, if set boolean, not show text
let text: string | boolean = ''
if (cols > 104) text = 'Electron+Vite'
else if (cols > 76) text = 'Electron+|Vite'
else text = false
if (text) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false,
})
} else console.log(chalk.yellow.bold('\n Electron+Vite'))
console.log(chalk.blue(' Say Hi! Ready... ') + '\n')
}
async function startRenderer(): Promise<void> {
return new Promise((resolve, reject) => {
// set base port
PortFinder.basePort = config.dev.port || 9000
PortFinder.getPort(async (error, port) => {
if (error) reject('PortError' + error)
else {
// So suck with config here, InlineConfig interface but export default config "UserConfig"
// Link: https://vitejs.dev/guide/api-javascript.html#createserver
const server = await createServer(rendererOptions())
// set port if available
process.env.PORT = String(port)
server.listen(port).then(() => {
console.log(
'\n\n' +
chalk.blue(' Preparing main process, please wait...') +
'\n\n'
)
})
resolve()
}
})
})
}
function startMain(): Promise<void> {
return new Promise((resolve, reject) => {
// Use rollup to watch file changed, simple vite use it, so i will use it =)) no other reason
const watcher = watch(rollupConfigOptions(process.env?.NODE_ENV))
watcher.on('change', (filename) => {
// Main process log stats
logStats('Main File Changed', filename)
})
watcher.on('event', (event) => {
if (event.code === 'END') {
if (electronProcess && electronProcess.kill) {
manualRestart = true
process.kill(electronProcess.pid)
electronProcess = null
startElectron()
setTimeout(() => {
manualRestart = false
}, 7000)
}
resolve()
} else if (event.code === 'ERROR') {
reject(event.error)
}
})
})
}
function startElectron() {
let args = [
'--inspect=6969',
path.join(__dirname, '../dist/electron/main/main.js'),
]
// detect yarn or npm and process command-line args accordingly
if (process.env.npm_execpath.endsWith('yarn.js')) {
args = args.concat(process.argv.slice(3))
} else if (process.env.npm_execpath.endsWith('npm-cli.js')) {
args = args.concat(process.argv.slice(2))
}
// @ts-ignore: Maybe electron.toString() =))) i never try it, u can try it, i guess it's not working
electronProcess = spawn(electron, args)
electronProcess.stdout.on('data', (data: any) => {
electronLog(removeJunk(data), 'blue')
})
electronProcess.stderr.on('data', (data: any) => {
electronLog(removeJunk(data), 'red')
})
electronProcess.on('close', () => {
if (!manualRestart) process.exit()
})
}
async function init() {
sayHi()
try {
// Start renderer process
await startRenderer()
// Start main process
await startMain()
// Start electron runtime
await startElectron()
} catch (error) {
console.error(error)
process.exit(1)
}
}
// Run init function
init()
| electronLog |
__derive.rs | /*!
Functions that are exported and used by `elastic_types_derive`.
This module is 'private' and should only be consumed by `elastic_types_derive`.
Its contents aren't subject to SemVer.
*/
use chrono::{
format::{
self,
Parsed,
},
DateTime,
Utc,
};
use serde::Serialize;
use serde_json;
use crate::types::private::field::{
FieldMapping,
FieldType,
SerializeFieldMapping,
};
pub use crate::types::{
date::{
DateFormat,
DateValue,
FormattedDate,
ParseError,
},
document::{
mapping::{
ObjectFieldType,
ObjectMapping,
PropertiesMapping,
},
DocumentType,
Id,
Index,
StaticIndex,
StaticType,
Type,
DEFAULT_DOC_TYPE,
},
};
pub use chrono::format::{
Fixed,
Item,
Numeric,
Pad,
};
pub use serde::ser::SerializeStruct;
/** Serialise a field mapping as a field using the given serialiser. */
#[inline]
pub fn field_ser<TField, TMapping, TPivot, S>(
state: &mut S,
field: &'static str,
) -> Result<(), S::Error>
where
TField: FieldType<TMapping, TPivot>,
TMapping: FieldMapping<TPivot>,
S: SerializeStruct,
SerializeFieldMapping<TMapping, TPivot>: Serialize,
{
state.serialize_field(field, &SerializeFieldMapping::<TMapping, TPivot>::default())
}
/**
Serialize a field individually.
This method isn't intended to be used publicly, but is useful in the docs.
*/
#[inline]
pub fn standalone_field_ser<TMapping, TPivot>(
_: TMapping,
) -> Result<serde_json::Value, serde_json::Error>
where
TMapping: FieldMapping<TPivot>,
SerializeFieldMapping<TMapping, TPivot>: Serialize,
{
serde_json::to_value(&SerializeFieldMapping::<TMapping, TPivot>::default())
}
/** Parse a date string using an owned slice of items. */
pub fn parse_from_tokens<'a>(date: &str, fmt: Vec<Item<'a>>) -> Result<DateValue, ParseError> |
/** Format a date string using an owned slice of items. */
pub fn format_with_tokens<'a>(date: &'a DateValue, fmt: Vec<Item<'a>>) -> FormattedDate<'a> {
date.format_with_items(fmt.into_iter()).into()
}
| {
let mut parsed = Parsed::new();
match format::parse(&mut parsed, date, fmt.into_iter()) {
Ok(_) => {
// If the parsed result doesn't contain any time, set it to the default
if parsed.hour_mod_12.is_none() {
let _ = parsed.set_hour(0);
let _ = parsed.set_minute(0);
}
// Set the DateTime result
let naive_date = parsed.to_naive_datetime_with_offset(0)?;
let date = DateTime::from_utc(naive_date, Utc);
Ok(date.into())
}
Err(e) => Err(e.into()),
}
} |
errors3.rs | // errors3.rs
// This is a program that is trying to use a completed version of the
// `total_cost` function from the previous exercise. It's not working though!
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!
use std::num::ParseIntError;
fn main() {
let mut tokens = 100;
let pretend_user_input = "8";
let cost = match total_cost(pretend_user_input) {
Ok(something) => something,
Err(something) => panic!("Conversion failed"),
};
if cost > tokens {
println!("You can't afford that many!");
} else {
tokens -= cost;
println!("You now have {} tokens.", tokens);
} | let cost_per_item = 5;
let qty = item_quantity.parse::<i32>()?;
Ok(qty * cost_per_item + processing_fee)
} | }
pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1; |
register_delete_route.ts | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { schema } from '@kbn/config-schema';
import { ILegacyScopedClusterClient } from 'kibana/server';
import { isEsError } from '../../../shared_imports';
import { RouteDependencies } from '../../../types';
import { licensePreRoutingFactory } from '../../../lib/license_pre_routing_factory';
const paramsSchema = schema.object({
watchId: schema.string(),
});
function deleteWatch(dataClient: ILegacyScopedClusterClient, watchId: string) {
return dataClient.callAsCurrentUser('watcher.deleteWatch', {
id: watchId,
});
}
export function registerDeleteRoute(deps: RouteDependencies) {
deps.router.delete(
{
path: '/api/watcher/watch/{watchId}',
validate: {
params: paramsSchema,
},
},
licensePreRoutingFactory(deps, async (ctx, request, response) => {
const { watchId } = request.params;
try {
return response.ok({
body: await deleteWatch(ctx.watcher!.client, watchId),
});
} catch (e) {
// Case: Error from Elasticsearch JS client
if (isEsError(e)) { |
// Case: default
return response.internalError({ body: e });
}
})
);
} | const body = e.statusCode === 404 ? `Watch with id = ${watchId} not found` : e;
return response.customError({ statusCode: e.statusCode, body });
} |
support.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package lscc
import (
"github.com/hyperledger/fabric/common/cauthdsl"
"github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric/msp/mgmt"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
)
type supportImpl struct {
}
// PutChaincodeToLocalStorage stores the supplied chaincode
// package to local storage (i.e. the file system)
func (s *supportImpl) PutChaincodeToLocalStorage(ccpack ccprovider.CCPackage) error {
if err := ccpack.PutChaincodeToFS(); err != nil {
return errors.Errorf("error installing chaincode code %s:%s(%s)", ccpack.GetChaincodeData().CCName(), ccpack.GetChaincodeData().CCVersion(), err)
}
return nil
}
// GetChaincodeFromLocalStorage retrieves the chaincode package
// for the requested chaincode, specified by name and version
func (s *supportImpl) GetChaincodeFromLocalStorage(ccname string, ccversion string) (ccprovider.CCPackage, error) {
return ccprovider.GetChaincodeFromFS(ccname, ccversion)
}
// GetChaincodesFromLocalStorage returns an array of all chaincode
// data that have previously been persisted to local storage
func (s *supportImpl) GetChaincodesFromLocalStorage() (*pb.ChaincodeQueryResponse, error) {
return ccprovider.GetInstalledChaincodes()
}
// GetInstantiationPolicy returns the instantiation policy for the
// supplied chaincode (or the channel's default if none was specified)
func (s *supportImpl) GetInstantiationPolicy(channel string, ccpack ccprovider.CCPackage) ([]byte, error) {
var ip []byte
var err error
// if ccpack is a SignedCDSPackage, return its IP, otherwise use a default IP
sccpack, isSccpack := ccpack.(*ccprovider.SignedCDSPackage)
if isSccpack {
ip = sccpack.GetInstantiationPolicy()
if ip == nil |
} else {
// the default instantiation policy allows any of the channel MSP admins
// to be able to instantiate
mspids := channelMSPIDs(channel)
p := cauthdsl.SignedByAnyAdmin(mspids)
ip, err = protoutil.Marshal(p)
if err != nil {
return nil, errors.Errorf("error marshalling default instantiation policy")
}
}
return ip, nil
}
// CheckInstantiationPolicy checks whether the supplied signed proposal
// complies with the supplied instantiation policy
func (s *supportImpl) CheckInstantiationPolicy(signedProp *pb.SignedProposal, chainName string, instantiationPolicy []byte) error {
// create a policy object from the policy bytes
mgr := mgmt.GetManagerForChain(chainName)
if mgr == nil {
return errors.Errorf("error checking chaincode instantiation policy: MSP manager for channel %s not found", chainName)
}
npp := cauthdsl.NewPolicyProvider(mgr)
instPol, _, err := npp.NewPolicy(instantiationPolicy)
if err != nil {
return err
}
proposal, err := protoutil.GetProposal(signedProp.ProposalBytes)
if err != nil {
return err
}
// get the signature header of the proposal
header, err := protoutil.GetHeader(proposal.Header)
if err != nil {
return err
}
shdr, err := protoutil.GetSignatureHeader(header.SignatureHeader)
if err != nil {
return err
}
// construct signed data we can evaluate the instantiation policy against
sd := []*protoutil.SignedData{{
Data: signedProp.ProposalBytes,
Identity: shdr.Creator,
Signature: signedProp.Signature,
}}
err = instPol.Evaluate(sd)
if err != nil {
return errors.WithMessage(err, "instantiation policy violation")
}
return nil
}
| {
return nil, errors.Errorf("instantiation policy cannot be nil for a SignedCCDeploymentSpec")
} |
x01_make_karma_sources.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import ujson
from pathlib import Path
from typing import Dict, Tuple, List, Set, Union, Optional, Any
from semantic_modeling.config import config | from semantic_modeling.utilities.serializable import serializeJSON
from transformation.r2rml.commands.modeling import SetInternalLinkCmd, SetSemanticTypeCmd
from transformation.r2rml.r2rml import R2RML
dataset = "museum_crm"
ont = get_ontology(dataset)
source_dir = Path(config.datasets[dataset].as_path()) / "karma-version" / "sources"
source_dir.mkdir(exist_ok=True, parents=True)
for tbl in get_sampled_data_tables(dataset):
serializeJSON(tbl.rows, source_dir / f"{tbl.id}.json", indent=4) | from semantic_modeling.data_io import get_data_tables, get_raw_data_tables, get_semantic_models, get_ontology, \
get_sampled_data_tables |
build.rs | use std::{env, fs, path::PathBuf};
mod defaults {
pub const GRAPH_DIM: &str = "5";
}
fn main() | {
let out_dir = {
let out_dir = env::var_os("OUT_DIR").expect("Env-var OUT_DIR is not set.");
PathBuf::from(&out_dir)
};
// read in graph-dim from environment
let graph_dim: usize = {
let graph_dim = env::var_os("GRAPH_DIM").unwrap_or(defaults::GRAPH_DIM.into());
let graph_dim = graph_dim.to_string_lossy();
graph_dim.parse().expect(&format!(
"The provided env-var GRAPH_DIM should be usize, but isn't (GRAPH_DIM={}).",
graph_dim,
))
};
// https://stackoverflow.com/a/37528134
//
// write compiler-constants into file
fs::write(
out_dir.join("compiler.rs"),
format!(
"pub const GRAPH_DIM: usize = {};
",
graph_dim
),
)
.expect("Writing compiler.rs didn't work.");
// reruns
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GRAPH_DIM");
} |
|
setup.go | // Copyright © 2018 Joel Rebello <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
"github.com/bmc-toolbox/bmcbutler/asset"
"github.com/bmc-toolbox/bmcbutler/butler"
"github.com/bmc-toolbox/bmcbutler/inventory" | "github.com/bmc-toolbox/bmcbutler/resource"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)
// setupCmd represents the setup command
var setupCmd = &cobra.Command{
Use: "setup",
Short: "Setup onetime configuration for BMCs.",
Long: `Some BMC configuration options must be set just once,
and this config can cause the BMC and or its dependencies to power reset,
for example: disabling/enabling flex addresses on the Dell m1000e,
this requires all the blades in the chassis to be power cycled.`,
Run: func(cmd *cobra.Command, args []string) {
setup()
},
}
func init() {
rootCmd.AddCommand(setupCmd)
}
func setup() {
// A channel to recieve inventory assets
inventoryChan := make(chan []asset.Asset)
inventorySource := viper.GetString("inventory.setup.source")
butlersToSpawn := viper.GetInt("butlersToSpawn")
if butlersToSpawn == 0 {
butlersToSpawn = 5
}
switch inventorySource {
case "needSetup":
inventoryInstance := inventory.NeedSetup{Log: log, BatchSize: 10, Channel: inventoryChan}
// Spawn a goroutine that returns a slice of assets over inventoryChan
// the number of assets in the slice is determined by the batch size.
if serial == "" {
go inventoryInstance.AssetIter()
} else {
go inventoryInstance.AssetIterBySerial(serial, assetType)
}
default:
fmt.Println("Unknown inventory source declared in cfg: ", inventorySource)
os.Exit(1)
}
// Read in declared resources
resourceInstance := resource.Resource{Log: log}
config := resourceInstance.ReadResources()
// Spawn butlers to work
butlerChan := make(chan butler.ButlerMsg, 10)
butlerInstance := butler.Butler{Log: log, SpawnCount: butlersToSpawn, Channel: butlerChan}
if serial != "" {
butlerInstance.IgnoreLocation = true
}
go butlerInstance.Spawn()
//over inventory channel and pass asset lists recieved to bmcbutlers
for asset := range inventoryChan {
butlerMsg := butler.ButlerMsg{Assets: asset, Config: config}
butlerChan <- butlerMsg
}
close(butlerChan)
//wait until butlers are done.
butlerInstance.Wait()
} | |
github.rs | use cmd_lib::run_fun;
use serde::Deserialize;
#[derive(Deserialize, Debug, Clone)]
pub struct PullRequest {
number: u32,
}
#[derive(Deserialize, Debug)]
pub struct | {
labels: Vec<Label>,
}
#[derive(Deserialize, Debug)]
pub struct Label {
name: String,
}
pub struct GitHub;
impl GitHub {
/// Shells out to GitHub's CLI `gh` to try and determine if the commit belongs to any pull-request
pub fn find_pull_request_by(
sha: &str,
marker_label: &str,
) -> anyhow::Result<Option<PullRequest>> {
log::trace!("listing pull-requests that contain the commit:");
let pulls = run_fun!(gh pr list --state merged --search ${sha} --limit 1 --json number)?;
log::trace!("{pulls}");
let pulls: Vec<PullRequest> = serde_json::from_str(&pulls)?;
if pulls.is_empty() {
log::debug!("the commit sha {sha} is not part of any pull-request");
return Ok(None);
}
let pr = pulls.first().unwrap().clone();
log::trace!("extracted {pr:?}");
log::trace!("getting labels for the possibly qualified pull-request:");
let labels = {
let pr_number = pr.number;
run_fun!(gh pr view ${pr_number} --json labels)?
};
log::trace!("{labels}");
let labels: Labels = serde_json::from_str(&labels)?;
if labels.labels.is_empty() {
log::debug!(
"the commit sha {sha} is not part of any pull-request with the {marker_label} label"
);
return Ok(None);
}
for label in labels.labels {
if label.name == marker_label {
return Ok(Some(pr));
}
}
Ok(None)
}
}
pub struct Actions;
impl Actions {
// Set an "output" in GitHub Actions
pub fn set_output(key: &str, value: &str) {
log::debug!("setting output name={key} value={value}");
println!("::set-output name={key}::{value}");
}
}
| Labels |
main.py | # readfile "rf()" function
def rf(filename):
|
# import external files
exec(rf("translate.py"))
exec(rf("parse.py"))
exec(rf("fileServer.py"))
# main body
# arg1 defines live server port
# main calling point of program
startServer(8080)
| return open(filename, "r").read() |
internal.rs | use automerge_protocol as amp;
use nonzero_ext::nonzero;
use smol_str::SmolStr;
#[derive(Eq, PartialEq, Hash, Debug, Clone, Copy)]
pub(crate) struct ActorId(pub usize);
#[derive(Eq, PartialEq, Debug, Hash, Clone, Copy)]
pub(crate) struct OpId(pub u64, pub ActorId);
#[derive(Eq, PartialEq, Debug, Hash, Clone, Copy)]
pub(crate) enum ObjectId {
Id(OpId),
Root,
}
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
pub(crate) enum ElementId {
Head,
Id(OpId),
}
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub(crate) enum Key {
Map(SmolStr),
Seq(ElementId),
}
#[derive(PartialEq, Debug, Clone)]
pub(crate) struct InternalOp {
pub action: InternalOpType,
pub obj: ObjectId,
pub key: Key,
pub pred: Vec<OpId>,
pub insert: bool,
}
impl InternalOp {
pub fn obj_type(&self) -> Option<amp::ObjType> {
match self.action {
InternalOpType::Make(objtype) => Some(objtype),
_ => None,
}
}
pub fn is_inc(&self) -> bool {
matches!(self.action, InternalOpType::Inc(_))
}
}
#[derive(PartialEq, Debug, Clone)]
pub(crate) enum InternalOpType {
Make(amp::ObjType),
Del,
Inc(i64),
Set(amp::ScalarValue),
}
impl Key {
pub fn as_element_id(&self) -> Option<ElementId> {
match self {
Key::Map(_) => None,
Key::Seq(eid) => Some(*eid),
}
}
| ElementId::Id(id) => Some(id),
ElementId::Head => None,
}
}
}
impl From<OpId> for ObjectId {
fn from(id: OpId) -> ObjectId {
ObjectId::Id(id)
}
}
impl From<OpId> for ElementId {
fn from(id: OpId) -> ElementId {
ElementId::Id(id)
}
}
impl From<OpId> for Key {
fn from(id: OpId) -> Key {
Key::Seq(ElementId::Id(id))
}
}
impl From<&InternalOpType> for amp::OpType {
fn from(i: &InternalOpType) -> amp::OpType {
match i {
InternalOpType::Del => amp::OpType::Del(nonzero!(1_u32)),
InternalOpType::Make(ot) => amp::OpType::Make(*ot),
InternalOpType::Set(v) => amp::OpType::Set(v.clone()),
InternalOpType::Inc(i) => amp::OpType::Inc(*i),
}
}
} | pub fn to_opid(&self) -> Option<OpId> {
match self.as_element_id()? { |
zkp_verify.rs | use ckb_zkp::{verify, verify_from_bytes, Curve, GadgetProof, Proof, Scheme};
use std::env;
use std::path::PathBuf;
const SETUP_DIR: &'static str = "./trusted_setup";
fn print_common() {
println!("");
println!("scheme:");
println!(" groth16 -- Groth16 zero-knowledge proof system. [Default]");
println!(" bulletproofs -- Bulletproofs zero-knowledge proof system.");
println!("");
println!("curve:");
println!(" bn_256 -- BN_256 pairing curve. [Default]");
println!(" bls12_381 -- BLS12_381 pairing curve.");
println!("");
println!("OPTIONS:");
println!(" --json -- input/ouput use json type file.");
println!(" --prepare -- use prepared verification key when verifying proof.");
println!("");
}
fn print_help() |
pub fn handle_args() -> Result<(String, String, bool, bool), String> {
let args: Vec<_> = env::args().collect();
if args.len() < 3 {
print_help();
return Err("Params invalid!".to_owned());
}
let is_pp = args.contains(&"--prepare".to_owned());
let is_json = args.contains(&"--json".to_owned());
let (s, c, n) = match args[2].as_str() {
"groth16" => match args[3].as_str() {
"bls12_381" => (Scheme::Groth16, Curve::Bls12_381, 4),
"bn_256" => (Scheme::Groth16, Curve::Bn_256, 4),
_ => (Scheme::Groth16, Curve::Bn_256, 3),
},
"bulletproofs" => match args[3].as_str() {
"bls12_381" => (Scheme::Bulletproofs, Curve::Bls12_381, 4),
"bn_256" => (Scheme::Bulletproofs, Curve::Bn_256, 4),
_ => (Scheme::Bulletproofs, Curve::Bn_256, 3),
},
"bls12_381" => (Scheme::Groth16, Curve::Bls12_381, 3),
"bn_256" => (Scheme::Groth16, Curve::Bn_256, 3),
_ => (Scheme::Groth16, Curve::Bn_256, 2),
};
let vk_file = format!("{}-{}-{}.vk", args[1], s.to_str(), c.to_str());
Ok((vk_file, args[n].clone(), is_pp, is_json))
}
fn from_hex(s: &str) -> Result<Vec<u8>, ()> {
if s.len() % 2 != 0 {
return Err(());
}
let mut value = vec![0u8; s.len() / 2];
for i in 0..(s.len() / 2) {
let res = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).map_err(|_e| ())?;
value[i] = res;
}
Ok(value)
}
pub fn main() -> Result<(), String> {
let (vk_file, filename, _is_pp, is_json) = handle_args()?;
// load pk file.
let mut vk_path = PathBuf::from(SETUP_DIR);
vk_path.push(vk_file);
if !vk_path.exists() {
return Err(format!("Cannot found setup file: {:?}", vk_path));
}
let vk = std::fs::read(&vk_path).unwrap();
let path = PathBuf::from(filename);
let res = if path.exists() {
println!("Start verify {:?}...", path);
if is_json {
let content = std::fs::read_to_string(&path).expect("file not found!");
let json: serde_json::Value = serde_json::from_str(&content).unwrap();
let g_str = json["gadget"].as_str().unwrap();
let s_str = json["scheme"].as_str().unwrap();
let c_str = json["curve"].as_str().unwrap();
let params = &json["params"];
let p_str = json["proof"].as_str().unwrap();
let s = Scheme::from_str(s_str).unwrap();
let c = Curve::from_str(c_str).unwrap();
let p = match g_str {
"mimc" => GadgetProof::MiMC(
from_hex(params[0].as_str().unwrap()).unwrap(),
from_hex(p_str).unwrap(),
),
"greater" => {
let n = params[0].as_str().unwrap().parse::<u64>().unwrap();
GadgetProof::GreaterThan(n, from_hex(p_str).unwrap())
}
"less" => {
let n = params[0].as_str().unwrap().parse::<u64>().unwrap();
GadgetProof::LessThan(n, from_hex(p_str).unwrap())
}
"between" => {
let l = params[0].as_str().unwrap().parse::<u64>().unwrap();
let r = params[1].as_str().unwrap().parse::<u64>().unwrap();
GadgetProof::Between(l, r, from_hex(p_str).unwrap())
}
_ => return Err("unimplemented".to_owned()),
};
verify(Proof { s, c, p }, &vk)
} else {
let b = std::fs::read(&path).expect("file not found!");
verify_from_bytes(&b, &vk)
}
} else {
return Err(format!("Not found file: {:?}.", path));
};
println!("Verify is: {}", res);
Ok(())
}
| {
println!("zkp-verify");
println!("");
println!("Usage: zkp-verify [GADGET] <scheme> <curve> [FILE] <OPTIONS>");
println!("");
println!("GADGET: ");
println!(" mimc -- MiMC hash & proof.");
println!(" greater -- Greater than comparison proof.");
println!(" less -- Less than comparison proof.");
println!(" between -- Between comparison proof.");
print_common();
} |
widerface2kitti.py | import scipy.io
import os
from PIL import Image, ImageDraw
class widerFace2kitti():
def __init__(self, annotation_file, widerFace_base_dir, kitti_base_dir, kitti_resize_dims, category_limit, train):
self.annotation_file = annotation_file
self.data = scipy.io.loadmat(self.annotation_file)
self.file_names = self.data.get('file_list') # File Name
self.event_list = self.data.get('event_list') # Folder Name
self.bbox_list = self.data.get('face_bbx_list') # Bounding Boxes
self.label_list = self.data.get('occlusion_label_list')
self.kitti_base_dir = kitti_base_dir
self.widerFace_base_dir = widerFace_base_dir
self.count_mask = category_limit[0]
self.count_no_mask = category_limit[1]
self.kitti_resize_dims = kitti_resize_dims
self.train = train
self.len_dataset = len(self.file_names)
if self.train:
# os.makedirs(self.kitti_base_dir+'/train/images',mode=0o777)
self.kitti_images = os.path.join(self.kitti_base_dir, 'train/images')
# os.makedirs(self.kitti_base_dir+ '/train/labels',mode=0o777)
self.kitti_labels = os.path.join(self.kitti_base_dir, 'train/labels')
else:
# os.makedirs(self.kitti_base_dir+'/test/images',mode=0o777)
self.kitti_images = os.path.join(self.kitti_base_dir, 'test/images')
# os.makedirs(self.kitti_base_dir+'/test/labels',mode=0o777)
self.kitti_labels = os.path.join(self.kitti_base_dir, 'test/labels')
def make_labels(self, image_name, category_names, bboxes):
# Process image
file_image = os.path.splitext(image_name)[0].split('\\')[1]
img = Image.open(os.path.join(self.widerFace_base_dir, image_name)).convert("RGB")
resize_img = img.resize(self.kitti_resize_dims)
resize_img.save(os.path.join(self.kitti_images, file_image+'.jpg'), 'JPEG')
# Process labels
with open(os.path.join(self.kitti_labels, file_image+ '.txt'), 'w') as label_file:
for i in range (0, len(bboxes)):
resized_bbox = self.resize_bbox(img=img, bbox=bboxes[i], dims=self.kitti_resize_dims)
out_str = [category_names[i].replace(" ", "")
+ ' ' + ' '.join(['0'] * 1)
+ ' ' + ' '.join(['0'] * 2)
+ ' ' + ' '.join([b for b in resized_bbox])
+ ' ' + ' '.join(['0'] * 7)
+ '\n']
label_file.write(out_str[0])
def resize_bbox(self, img, bbox, dims):
img_w, img_h = img.size
x_min, y_min, x_max, y_max = bbox
ratio_w, ratio_h = img_w / dims[0], img_h / dims[1]
new_bbox = [str(x_min / ratio_w), str(y_min / ratio_h), str(x_max / ratio_w), str(y_max / ratio_h)]
return new_bbox
def mat2data(self):
count = 0
_count_mask, _count_no_mask = 0,0
pick_list = ['19--Couple', '13--Interview', '16--Award_Ceremony','2--Demonstration', '22--Picnic']
# Use following pick list for more image data
# pick_list = ['2--Demonstration', '4--Dancing', '5--Car_Accident', '15--Stock_Market', '23--Shoppers',
# '27--Spa', '32--Worker_Laborer', '33--Running', '37--Soccer',
# '47--Matador_Bullfighter','57--Angler', '51--Dresses', '46--Jockey',
# '9--Press_Conference','16--Award_Ceremony', '17--Ceremony',
# '20--Family_Group', '22--Picnic', '25--Soldier_Patrol', '31--Waiter_Waitress',
# '49--Greeting', '38--Tennis', '43--Row_Boat', '29--Students_Schoolkids']
for event_idx, event in enumerate(self.event_list):
directory = event[0][0]
if any(ele in directory for ele in pick_list):
for im_idx, im in enumerate(self.file_names[event_idx][0]):
im_name = im[0][0]
read_im_file = os.path.join(directory, im_name+'.jpg')
face_bbx = self.bbox_list[event_idx][0][im_idx][0]
category_id = self.label_list[event_idx][0][im_idx][0]
# print face_bbx.shape
bboxes = []
category_names = []
if _count_no_mask < self.count_no_mask:
for i in range(face_bbx.shape[0]):
xmin = int(face_bbx[i][0])
ymin = int(face_bbx[i][1])
xmax = int(face_bbx[i][2]) + xmin
ymax = int(face_bbx[i][3]) + ymin
# Consider only Occlusion Free masks
if category_id[i][0] ==0:
category_name = 'No-Mask'
bboxes.append((xmin, ymin, xmax, ymax))
category_names.append(category_name)
_count_no_mask += 1
try:
if bboxes:
self.make_labels(image_name=read_im_file, category_names= category_names, bboxes=bboxes)
except:
pass
print("WideFace: Total Mask Labelled:{} and No-Mask Labelled:{}".format(_count_mask, _count_no_mask))
return _count_mask, _count_no_mask
def test_labels(self, file_name):
img = Image.open(os.path.join(self.kitti_images, file_name + '.jpg'))
text_file = open(os .path.join(self.kitti_labels, file_name + '.txt'), 'r')
features = []
bbox = []
category = []
for line in text_file:
features = line.split()
bbox.append([float(features[4]), float(features[5]), float(features[6]), float(features[7])])
category.append(features[0])
print("Bounding Box", bbox)
print("Category:", category)
i=0
for bb in bbox:
draw_img = ImageDraw.Draw(img)
shape = ((bb[0], bb[1]), (bb[2], bb[3]))
if category[i] == 'No-Mask':
outline_clr = "red"
elif category[i] == 'Mask':
outline_clr = "green" |
def main():
widerFace_base_dir = r'C:\Users\nvidia\Downloads\WiderFace-Dataset' # Update According to dataset location
kitti_base_dir = r'C:\Users\nvidia\Downloads\KITTI' # Update According to KITTI output dataset location
train = True # For generating validation dataset; select False
if train:
annotation_file = os.path.join(widerFace_base_dir, 'wider_face_split/wider_face_train.mat')
widerFace_base_dir = os.path.join(widerFace_base_dir, 'WIDER_train/images')
else:
# Modify this
annotation_file = os.path.join(widerFace_base_dir, 'MAFA-Label-Test/LabelTestAll.mat')
widerFace_base_dir = os.path.join(widerFace_base_dir, 'test-images\images')
category_limit = [1000, 1000] # Mask / No-Mask Limits
kitti_resize_dims = (480, 272) # Look at TLT model requirements
kitti_label = widerFace2kitti(annotation_file=annotation_file, widerFace_base_dir=widerFace_base_dir,
kitti_base_dir=kitti_base_dir, kitti_resize_dims=kitti_resize_dims,
category_limit=category_limit, train=train)
count_masks, count_no_masks = kitti_label.mat2data()
# kitti_label.test_labels(file_name='0_Parade_Parade_0_371')
if __name__ == '__main__':
main() | draw_img.rectangle(shape, fill=None, outline=outline_clr, width=4)
i+=1
img.show() |
sourcegraph_test.go | package sourcegraph
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/shurcooL/graphql"
"github.com/stretchr/testify/assert"
"github.com/uber-go/tally/v4"
"go.uber.org/zap/zaptest"
"google.golang.org/protobuf/types/known/anypb"
sourcegraphv1cfg "github.com/lyft/clutch/backend/api/config/service/sourcegraph/v1"
sourcegraphv1 "github.com/lyft/clutch/backend/api/sourcegraph/v1"
)
func TestNew(t *testing.T) {
cfg, _ := anypb.New(&sourcegraphv1cfg.Config{
Host: "https://localhost",
Token: "secret",
})
log := zaptest.NewLogger(t)
scope := tally.NewTestScope("", nil)
_, err := New(cfg, log, scope)
assert.NoError(t, err)
}
func TestCompareCommits(t *testing.T) |
var compareCommitsSingleResponse string = `{"data":{"repository":{"comparison":{"commits":{"nodes":[{"message":"housekeeping: Update dependency cypress to v8.2.0 (#1672)\n","oid":"8a9857493108d0be9ebc251f30f72665c79424f6","author":{"person":{"email":"29139614+renovate[bot]@users.noreply.github.com","displayName":"renovate[bot]"}}}]}}}}}`
var compareCommitsMultiResultResponse string = `{"data":{"repository":{"comparison":{"commits":{"nodes":[{"message":"housekeeping: Update dependency cypress to v8.2.0 (#1672)\n","oid":"8a9857493108d0be9ebc251f30f72665c79424f6","author":{"person":{"email":"29139614+renovate[bot]@users.noreply.github.com","displayName":"renovate[bot]"}}},{"message":"housekeeping: Update dependency remark-toc to v8 (#1680)\n","oid":"5802372fe18c37e9ab62341b18d7f286078430b4","author":{"person":{"email":"29139614+renovate[bot]@users.noreply.github.com","displayName":"renovate[bot]"}}}]}}}}}`
var compareCommitsNoResultsResponse string = `{"data":{"repository":{"comparison":{"commits":{"nodes":[]}}}}}`
| {
t.Parallel()
log := zaptest.NewLogger(t)
scope := tally.NewTestScope("", nil)
tests := []struct {
id string
handler func(http.ResponseWriter, *http.Request)
req *sourcegraphv1.CompareCommitsRequest
res *sourcegraphv1.CompareCommitsResponse
}{
{
id: "single response",
req: &sourcegraphv1.CompareCommitsRequest{
Repository: "github.com/lyft/clutch",
Base: "8a9857493108d0be9ebc251f30f72665c79424f6",
Head: "8a9857493108d0be9ebc251f30f72665c79424f6",
},
handler: func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(compareCommitsSingleResponse))
},
res: &sourcegraphv1.CompareCommitsResponse{
Commits: []*sourcegraphv1.Commit{
{
Oid: "8a9857493108d0be9ebc251f30f72665c79424f6",
Email: "29139614+renovate[bot]@users.noreply.github.com",
Message: "housekeeping: Update dependency cypress to v8.2.0 (#1672)\n",
DisplayName: "renovate[bot]",
},
},
},
},
{
id: "multi result response",
req: &sourcegraphv1.CompareCommitsRequest{
Repository: "github.com/lyft/clutch",
Base: "8a9857493108d0be9ebc251f30f72665c79424f6~2",
Head: "8a9857493108d0be9ebc251f30f72665c79424f6",
},
handler: func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(compareCommitsMultiResultResponse))
},
res: &sourcegraphv1.CompareCommitsResponse{
Commits: []*sourcegraphv1.Commit{
{
Oid: "8a9857493108d0be9ebc251f30f72665c79424f6",
Email: "29139614+renovate[bot]@users.noreply.github.com",
Message: "housekeeping: Update dependency cypress to v8.2.0 (#1672)\n",
DisplayName: "renovate[bot]",
},
{
Oid: "5802372fe18c37e9ab62341b18d7f286078430b4",
Email: "29139614+renovate[bot]@users.noreply.github.com",
Message: "housekeeping: Update dependency remark-toc to v8 (#1680)\n",
DisplayName: "renovate[bot]",
},
},
},
},
{
id: "no results response",
req: &sourcegraphv1.CompareCommitsRequest{
Repository: "github.com/lyft/clutch",
Base: "8a9857493108d0be9ebc251f30f72665c79424f6~2",
Head: "8a9857493108d0be9ebc251f30f72665c79424f6",
},
handler: func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(compareCommitsNoResultsResponse))
},
res: &sourcegraphv1.CompareCommitsResponse{
Commits: []*sourcegraphv1.Commit{},
},
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.id, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(tt.handler))
defer srv.Close()
sgURL, err := url.Parse(srv.URL)
assert.NoError(t, err)
gqlClient := graphql.NewClient(sgURL.String(), srv.Client())
c := &client{
log: log,
scope: scope,
gqlClient: gqlClient,
}
res, err := c.CompareCommits(context.Background(), tt.req)
assert.NoError(t, err)
assert.Equal(t, tt.res.Commits, res.Commits)
})
}
} |
cross_over.py | import numpy as np
# This class generating new list item given first of list item row and second of list item row
class | :
@staticmethod
def crossover(best):
row_begin_index = 0
row_half = 2
cross_list = []
for i in range(len(best) - 1):
first_part1 = best[i][row_begin_index:row_half, :]
first_part2 = best[i + 1][row_half:, :]
cross_list.append(np.concatenate((first_part1, first_part2)))
second_part1 = best[i][row_half:, :]
second_part2 = best[i + 1][row_begin_index:row_half, :]
cross_list.append(np.concatenate((second_part2, second_part1)))
return cross_list
| Crossover |
lib.rs | use std::collections::HashMap;
use std::fs;
use std::io::{Read, Write};
use std::path::Path;
use walkdir::WalkDir;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
type VersionType = u64;
const RAFT_STORE_PROXY_VERSION_PREFIX: &str = "RAFT_STORE_PROXY_VERSION";
const DB_PREFIX: &str = " pub mod DB {\n";
const DB_SUFFIX: &str = "\n }";
const ROOT_PREFIX: &str = "pub mod root {\n";
const ROOT_SUFFIX: &str = "\n}\n";
fn read_file_to_string<P: AsRef<Path>>(path: P, expect: &str) -> String {
let mut file = fs::File::open(path).expect(expect);
let mut buff = String::new();
file.read_to_string(&mut buff).expect(expect);
buff
}
fn filter_by_namespace(buff: &str) -> String {
let mut res = String::new();
// pub mod root {?
let a1 = buff.find(ROOT_PREFIX).unwrap() + ROOT_PREFIX.len();
res.push_str(&buff[..a1]);
// ? pub mod DB {
let b1 = buff.find(DB_PREFIX).unwrap();
let b2 = (&buff[b1..]).find(DB_SUFFIX).unwrap() + DB_SUFFIX.len() + b1;
// println!("{}", &buff[b1..b2]);
res.push_str(&buff[b1..b2]);
res.push_str(ROOT_SUFFIX);
res
}
fn scan_ffi_src_head(dir: &str) -> (Vec<String>, VersionType) |
fn read_version_file(version_cpp_file: &str) -> VersionType {
let buff = read_file_to_string(version_cpp_file, "Couldn't open version file");
let begin = buff.find(RAFT_STORE_PROXY_VERSION_PREFIX).unwrap();
let buff = &buff[(begin + RAFT_STORE_PROXY_VERSION_PREFIX.len() + 3)..buff.len()];
let end = buff.find("ull").unwrap();
let buff = &buff[..end];
let version = buff.parse::<VersionType>().unwrap();
version
}
fn make_version_file(version: VersionType, tar_version_head_path: &str) {
let buff = format!(
"#pragma once\n#include <cstdint>\nnamespace DB {{ constexpr uint64_t {} = {}ull; }}",
RAFT_STORE_PROXY_VERSION_PREFIX, version
);
let tmp_path = format!("{}.tmp", tar_version_head_path);
let mut file = fs::File::create(&tmp_path).expect("Couldn't create tmp cpp version head file");
file.write(buff.as_bytes()).unwrap();
fs::rename(&tmp_path, tar_version_head_path).expect("Couldn't make cpp version head file");
}
pub fn gen_ffi_code() {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let src_dir = format!(
"{}/../raftstore-proxy/ffi/src/RaftStoreProxyFFI",
manifest_dir
);
let tar_file = format!(
"{}/../components/raftstore/src/engine_store_ffi/interfaces.rs",
manifest_dir
);
let version_cpp_file = format!("{}/@version", src_dir);
let ori_version = read_version_file(&version_cpp_file);
println!("\nFFI src dir path is {}", src_dir);
println!("Original version is {}", ori_version);
let (headers, hash_version) = scan_ffi_src_head(&src_dir);
{
println!("Scan and get src files");
for f in &headers {
println!(" {}", f);
}
if ori_version == hash_version {
println!("Check hash version equal & NOT overwrite version");
} else {
println!(
"Current hash version is {}, start to generate rust code with version {}",
ori_version, hash_version
);
make_version_file(hash_version, &version_cpp_file);
}
}
let mut builder = bindgen::Builder::default()
.clang_arg("-xc++")
.clang_arg("-std=c++11")
.clang_arg("-Wno-pragma-once-outside-header")
.layout_tests(false)
.derive_copy(false)
.enable_cxx_namespaces()
.disable_header_comment()
.default_enum_style(bindgen::EnumVariation::Rust {
non_exhaustive: false,
});
for path in headers {
builder = builder.header(path);
}
let bindings = builder.generate().unwrap();
let buff = bindings.to_string();
let buff = filter_by_namespace(&buff);
let ori_buff = read_file_to_string(&tar_file, "Couldn't open rust ffi code file");
if ori_buff == buff {
println!("There is no need to overwrite rust ffi code file");
} else {
println!("Start generate rust code into {}\n", tar_file);
let mut file = fs::File::create(tar_file).expect("Couldn't create rust ffi code file");
file.write(buff.as_bytes()).unwrap();
}
}
| {
let mut headers = Vec::new();
let mut headers_buff = HashMap::new();
for result in WalkDir::new(Path::new(dir)) {
let dent = result.expect("Error happened when search headers");
if !dent.file_type().is_file() {
continue;
}
let buff = read_file_to_string(dent.path(), "Couldn't open headers");
let head_file_path = String::from(dent.path().to_str().unwrap());
if !head_file_path.ends_with(".h") {
continue;
}
headers.push(head_file_path.clone());
headers_buff.insert(head_file_path, buff);
}
headers.sort();
let hash_version = {
let mut hasher = DefaultHasher::new();
for name in &headers {
let buff = headers_buff.get(name).unwrap();
buff.hash(&mut hasher);
}
hasher.finish()
};
(headers, hash_version)
} |
getDMMF.ts | import { getRawDMMF } from '../engineCommands'
import { DMMF } from '../runtime/dmmf-types'
import { externalToInternalDmmf } from '../runtime/externalToInternalDmmf'
import { transformDmmf } from '../runtime/transformDmmf'
const modelBlacklist = {
// helper types
Enumerable: true,
MergeTruthyValues: true,
CleanupNever: true,
AtLeastOne: true,
OnlyOne: true,
// scalar filters
StringFilter: true,
IDFilter: true,
FloatFilter: true,
IntFilter: true,
BooleanFilter: true,
DateTimeFilter: true,
// nullable scalar filters
NullableStringFilter: true,
NullableIDFilter: true,
NullableFloatFilter: true,
NullableIntFilter: true,
NullableBooleanFilter: true,
NullableDateTimeFilter: true,
// photon classes
PhotonFetcher: true,
Photon: true,
Engine: true,
PhotonOptions: true,
}
const fieldBlacklist = {
AND: true,
OR: true,
NOT: true,
}
/**
* Checks if a model or field shouldn't be there
* @param document DMMF.Document
*/
function checkBlacklist(sdl: DMMF.Datamodel) {
for (const model of sdl.models) {
if (modelBlacklist[model.name]) {
throw new Error(`Model name ${model.name} is a reserved name and not allowed in the datamodel`)
}
for (const field of model.fields) {
if (fieldBlacklist[field.name]) {
throw new Error(`Field ${model.name}.${field.name} is a reserved name and not allowed in the datamodel`)
}
}
}
}
export interface GetDmmfOptions {
datamodel: string
datamodelPath?: string
cwd?: string
prismaPath?: string
}
export async function | ({ datamodel, cwd, prismaPath, datamodelPath }: GetDmmfOptions): Promise<DMMF.Document> {
const externalDmmf = await getRawDMMF(datamodel, cwd, prismaPath, datamodelPath)
const dmmf = transformDmmf(externalToInternalDmmf(externalDmmf))
checkBlacklist(dmmf.datamodel)
return dmmf
}
| getDMMF |
chart.go | package chart
import (
"io"
"strings"
)
const chartjs string = `/*!
* Chart.js v2.9.3
* https://www.chartjs.org
* (c) 2019 Chart.js Contributors
* Released under the MIT License
*/
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(function(){try{return require("moment")}catch(t){}}()):"function"==typeof define&&define.amd?define(["require"],(function(t){return e(function(){try{return t("moment")}catch(t){}}())})):(t=t||self).Chart=e(t.moment)}(this,(function(t){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},n=function(t,e){return t(e={exports:{}},e.exports),e.exports}((function(t){var n={};for(var i in e)e.hasOwnProperty(i)&&(n[e[i]]=i);var a=t.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var r in a)if(a.hasOwnProperty(r)){if(!("channels"in a[r]))throw new Error("missing channels property: "+r);if(!("labels"in a[r]))throw new Error("missing channel labels property: "+r);if(a[r].labels.length!==a[r].channels)throw new Error("channel and label counts mismatch: "+r);var o=a[r].channels,s=a[r].labels;delete a[r].channels,delete a[r].labels,Object.defineProperty(a[r],"channels",{value:o}),Object.defineProperty(a[r],"labels",{value:s})}a.rgb.hsl=function(t){var e,n,i=t[0]/255,a=t[1]/255,r=t[2]/255,o=Math.min(i,a,r),s=Math.max(i,a,r),l=s-o;return s===o?e=0:i===s?e=(a-r)/l:a===s?e=2+(r-i)/l:r===s&&(e=4+(i-a)/l),(e=Math.min(60*e,360))<0&&(e+=360),n=(o+s)/2,[e,100*(s===o?0:n<=.5?l/(s+o):l/(2-s-o)),100*n]},a.rgb.hsv=function(t){var e,n,i,a,r,o=t[0]/255,s=t[1]/255,l=t[2]/255,u=Math.max(o,s,l),d=u-Math.min(o,s,l),h=function(t){return(u-t)/6/d+.5};return 0===d?a=r=0:(r=d/u,e=h(o),n=h(s),i=h(l),o===u?a=i-n:s===u?a=1/3+e-i:l===u&&(a=2/3+n-e),a<0?a+=1:a>1&&(a-=1)),[360*a,100*r,100*u]},a.rgb.hwb=function(t){var e=t[0],n=t[1],i=t[2];return[a.rgb.hsl(t)[0],100*(1/255*Math.min(e,Math.min(n,i))),100*(i=1-1/255*Math.max(e,Math.max(n,i)))]},a.rgb.cmyk=function(t){var e,n=t[0]/255,i=t[1]/255,a=t[2]/255;return[100*((1-n-(e=Math.min(1-n,1-i,1-a)))/(1-e)||0),100*((1-i-e)/(1-e)||0),100*((1-a-e)/(1-e)||0),100*e]},a.rgb.keyword=function(t){var i=n[t];if(i)return i;var a,r,o,s=1/0;for(var l in e)if(e.hasOwnProperty(l)){var u=e[l],d=(r=t,o=u,Math.pow(r[0]-o[0],2)+Math.pow(r[1]-o[1],2)+Math.pow(r[2]-o[2],2));d<s&&(s=d,a=l)}return a},a.keyword.rgb=function(t){return e[t]},a.rgb.xyz=function(t){var e=t[0]/255,n=t[1]/255,i=t[2]/255;return[100*(.4124*(e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92)+.3576*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.1805*(i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92)),100*(.2126*e+.7152*n+.0722*i),100*(.0193*e+.1192*n+.9505*i)]},a.rgb.lab=function(t){var e=a.rgb.xyz(t),n=e[0],i=e[1],r=e[2];return i/=100,r/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116)-16,500*(n-i),200*(i-(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116))]},a.hsl.rgb=function(t){var e,n,i,a,r,o=t[0]/360,s=t[1]/100,l=t[2]/100;if(0===s)return[r=255*l,r,r];e=2*l-(n=l<.5?l*(1+s):l+s-l*s),a=[0,0,0];for(var u=0;u<3;u++)(i=o+1/3*-(u-1))<0&&i++,i>1&&i--,r=6*i<1?e+6*(n-e)*i:2*i<1?n:3*i<2?e+(n-e)*(2/3-i)*6:e,a[u]=255*r;return a},a.hsl.hsv=function(t){var e=t[0],n=t[1]/100,i=t[2]/100,a=n,r=Math.max(i,.01);return n*=(i*=2)<=1?i:2-i,a*=r<=1?r:2-r,[e,100*(0===i?2*a/(r+a):2*n/(i+n)),100*((i+n)/2)]},a.hsv.rgb=function(t){var e=t[0]/60,n=t[1]/100,i=t[2]/100,a=Math.floor(e)%6,r=e-Math.floor(e),o=255*i*(1-n),s=255*i*(1-n*r),l=255*i*(1-n*(1-r));switch(i*=255,a){case 0:return[i,l,o];case 1:return[s,i,o];case 2:return[o,i,l];case 3:return[o,s,i];case 4:return[l,o,i];case 5:return[i,o,s]}},a.hsv.hsl=function(t){var e,n,i,a=t[0],r=t[1]/100,o=t[2]/100,s=Math.max(o,.01);return i=(2-r)*o,n=r*s,[a,100*(n=(n/=(e=(2-r)*s)<=1?e:2-e)||0),100*(i/=2)]},a.hwb.rgb=function(t){var e,n,i,a,r,o,s,l=t[0]/360,u=t[1]/100,d=t[2]/100,h=u+d;switch(h>1&&(u/=h,d/=h),i=6*l-(e=Math.floor(6*l)),0!=(1&e)&&(i=1-i),a=u+i*((n=1-d)-u),e){default:case 6:case 0:r=n,o=a,s=u;break;case 1:r=a,o=n,s=u;break;case 2:r=u,o=n,s=a;break;case 3:r=u,o=a,s=n;break;case 4:r=a,o=u,s=n;break;case 5:r=n,o=u,s=a}return[255*r,255*o,255*s]},a.cmyk.rgb=function(t){var e=t[0]/100,n=t[1]/100,i=t[2]/100,a=t[3]/100;return[255*(1-Math.min(1,e*(1-a)+a)),255*(1-Math.min(1,n*(1-a)+a)),255*(1-Math.min(1,i*(1-a)+a))]},a.xyz.rgb=function(t){var e,n,i,a=t[0]/100,r=t[1]/100,o=t[2]/100;return n=-.9689*a+1.8758*r+.0415*o,i=.0557*a+-.204*r+1.057*o,e=(e=3.2406*a+-1.5372*r+-.4986*o)>.0031308?1.055*Math.pow(e,1/2.4)-.055:12.92*e,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:12.92*i,[255*(e=Math.min(Math.max(0,e),1)),255*(n=Math.min(Math.max(0,n),1)),255*(i=Math.min(Math.max(0,i),1))]},a.xyz.lab=function(t){var e=t[0],n=t[1],i=t[2];return n/=100,i/=108.883,e=(e/=95.047)>.008856?Math.pow(e,1/3):7.787*e+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(e-n),200*(n-(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116))]},a.lab.xyz=function(t){var e,n,i,a=t[0];e=t[1]/500+(n=(a+16)/116),i=n-t[2]/200;var r=Math.pow(n,3),o=Math.pow(e,3),s=Math.pow(i,3);return n=r>.008856?r:(n-16/116)/7.787,e=o>.008856?o:(e-16/116)/7.787,i=s>.008856?s:(i-16/116)/7.787,[e*=95.047,n*=100,i*=108.883]},a.lab.lch=function(t){var e,n=t[0],i=t[1],a=t[2];return(e=360*Math.atan2(a,i)/2/Math.PI)<0&&(e+=360),[n,Math.sqrt(i*i+a*a),e]},a.lch.lab=function(t){var e,n=t[0],i=t[1];return e=t[2]/360*2*Math.PI,[n,i*Math.cos(e),i*Math.sin(e)]},a.rgb.ansi16=function(t){var e=t[0],n=t[1],i=t[2],r=1 in arguments?arguments[1]:a.rgb.hsv(t)[2];if(0===(r=Math.round(r/50)))return 30;var o=30+(Math.round(i/255)<<2|Math.round(n/255)<<1|Math.round(e/255));return 2===r&&(o+=60),o},a.hsv.ansi16=function(t){return a.rgb.ansi16(a.hsv.rgb(t),t[2])},a.rgb.ansi256=function(t){var e=t[0],n=t[1],i=t[2];return e===n&&n===i?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(n/255*5)+Math.round(i/255*5)},a.ansi16.rgb=function(t){var e=t%10;if(0===e||7===e)return t>50&&(e+=3.5),[e=e/10.5*255,e,e];var n=.5*(1+~~(t>50));return[(1&e)*n*255,(e>>1&1)*n*255,(e>>2&1)*n*255]},a.ansi256.rgb=function(t){if(t>=232){var e=10*(t-232)+8;return[e,e,e]}var n;return t-=16,[Math.floor(t/36)/5*255,Math.floor((n=t%36)/6)/5*255,n%6/5*255]},a.rgb.hex=function(t){var e=(((255&Math.round(t[0]))<<16)+((255&Math.round(t[1]))<<8)+(255&Math.round(t[2]))).toString(16).toUpperCase();return"000000".substring(e.length)+e},a.hex.rgb=function(t){var e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];var n=e[0];3===e[0].length&&(n=n.split("").map((function(t){return t+t})).join(""));var i=parseInt(n,16);return[i>>16&255,i>>8&255,255&i]},a.rgb.hcg=function(t){var e,n=t[0]/255,i=t[1]/255,a=t[2]/255,r=Math.max(Math.max(n,i),a),o=Math.min(Math.min(n,i),a),s=r-o;return e=s<=0?0:r===n?(i-a)/s%6:r===i?2+(a-n)/s:4+(n-i)/s+4,e/=6,[360*(e%=1),100*s,100*(s<1?o/(1-s):0)]},a.hsl.hcg=function(t){var e=t[1]/100,n=t[2]/100,i=1,a=0;return(i=n<.5?2*e*n:2*e*(1-n))<1&&(a=(n-.5*i)/(1-i)),[t[0],100*i,100*a]},a.hsv.hcg=function(t){var e=t[1]/100,n=t[2]/100,i=e*n,a=0;return i<1&&(a=(n-i)/(1-i)),[t[0],100*i,100*a]},a.hcg.rgb=function(t){var e=t[0]/360,n=t[1]/100,i=t[2]/100;if(0===n)return[255*i,255*i,255*i];var a,r=[0,0,0],o=e%1*6,s=o%1,l=1-s;switch(Math.floor(o)){case 0:r[0]=1,r[1]=s,r[2]=0;break;case 1:r[0]=l,r[1]=1,r[2]=0;break;case 2:r[0]=0,r[1]=1,r[2]=s;break;case 3:r[0]=0,r[1]=l,r[2]=1;break;case 4:r[0]=s,r[1]=0,r[2]=1;break;default:r[0]=1,r[1]=0,r[2]=l}return a=(1-n)*i,[255*(n*r[0]+a),255*(n*r[1]+a),255*(n*r[2]+a)]},a.hcg.hsv=function(t){var e=t[1]/100,n=e+t[2]/100*(1-e),i=0;return n>0&&(i=e/n),[t[0],100*i,100*n]},a.hcg.hsl=function(t){var e=t[1]/100,n=t[2]/100*(1-e)+.5*e,i=0;return n>0&&n<.5?i=e/(2*n):n>=.5&&n<1&&(i=e/(2*(1-n))),[t[0],100*i,100*n]},a.hcg.hwb=function(t){var e=t[1]/100,n=e+t[2]/100*(1-e);return[t[0],100*(n-e),100*(1-n)]},a.hwb.hcg=function(t){var e=t[1]/100,n=1-t[2]/100,i=n-e,a=0;return i<1&&(a=(n-i)/(1-i)),[t[0],100*i,100*a]},a.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]},a.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]},a.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]},a.gray.hsl=a.gray.hsv=function(t){return[0,0,t[0]]},a.gray.hwb=function(t){return[0,100,t[0]]},a.gray.cmyk=function(t){return[0,0,0,t[0]]},a.gray.lab=function(t){return[t[0],0,0]},a.gray.hex=function(t){var e=255&Math.round(t[0]/100*255),n=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return"000000".substring(n.length)+n},a.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}}));n.rgb,n.hsl,n.hsv,n.hwb,n.cmyk,n.xyz,n.lab,n.lch,n.hex,n.keyword,n.ansi16,n.ansi256,n.hcg,n.apple,n.gray;function i(t){var e=function(){for(var t={},e=Object.keys(n),i=e.length,a=0;a<i;a++)t[e[a]]={distance:-1,parent:null};return t}(),i=[t];for(e[t].distance=0;i.length;)for(var a=i.pop(),r=Object.keys(n[a]),o=r.length,s=0;s<o;s++){var l=r[s],u=e[l];-1===u.distance&&(u.distance=e[a].distance+1,u.parent=a,i.unshift(l))}return e}function a(t,e){return function(n){return e(t(n))}}function r(t,e){for(var i=[e[t].parent,t],r=n[e[t].parent][t],o=e[t].parent;e[o].parent;)i.unshift(e[o].parent),r=a(n[e[o].parent][o],r),o=e[o].parent;return r.conversion=i,r}var o={};Object.keys(n).forEach((function(t){o[t]={},Object.defineProperty(o[t],"channels",{value:n[t].channels}),Object.defineProperty(o[t],"labels",{value:n[t].labels});var e=function(t){for(var e=i(t),n={},a=Object.keys(e),o=a.length,s=0;s<o;s++){var l=a[s];null!==e[l].parent&&(n[l]=r(l,e))}return n}(t);Object.keys(e).forEach((function(n){var i=e[n];o[t][n]=function(t){var e=function(e){if(null==e)return e;arguments.length>1&&(e=Array.prototype.slice.call(arguments));var n=t(e);if("object"==typeof n)for(var i=n.length,a=0;a<i;a++)n[a]=Math.round(n[a]);return n};return"conversion"in t&&(e.conversion=t.conversion),e}(i),o[t][n].raw=function(t){var e=function(e){return null==e?e:(arguments.length>1&&(e=Array.prototype.slice.call(arguments)),t(e))};return"conversion"in t&&(e.conversion=t.conversion),e}(i)}))}));var s=o,l={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},u={getRgba:d,getHsla:h,getRgb:function(t){var e=d(t);return e&&e.slice(0,3)},getHsl:function(t){var e=h(t);return e&&e.slice(0,3)},getHwb:c,getAlpha:function(t){var e=d(t);if(e)return e[3];if(e=h(t))return e[3];if(e=c(t))return e[3]},hexString:function(t,e){e=void 0!==e&&3===t.length?e:t[3];return"#"+v(t[0])+v(t[1])+v(t[2])+(e>=0&&e<1?v(Math.round(255*e)):"")},rgbString:function(t,e){if(e<1||t[3]&&t[3]<1)return f(t,e);return"rgb("+t[0]+", "+t[1]+", "+t[2]+")"},rgbaString:f,percentString:function(t,e){if(e<1||t[3]&&t[3]<1)return g(t,e);var n=Math.round(t[0]/255*100),i=Math.round(t[1]/255*100),a=Math.round(t[2]/255*100);return"rgb("+n+"%, "+i+"%, "+a+"%)"},percentaString:g,hslString:function(t,e){if(e<1||t[3]&&t[3]<1)return p(t,e);return"hsl("+t[0]+", "+t[1]+"%, "+t[2]+"%)"},hslaString:p,hwbString:function(t,e){void 0===e&&(e=void 0!==t[3]?t[3]:1);return"hwb("+t[0]+", "+t[1]+"%, "+t[2]+"%"+(void 0!==e&&1!==e?", "+e:"")+")"},keyword:function(t){return b[t.slice(0,3)]}};function d(t){if(t){var e=[0,0,0],n=1,i=t.match(/^#([a-fA-F0-9]{3,4})$/i),a="";if(i){a=(i=i[1])[3];for(var r=0;r<e.length;r++)e[r]=parseInt(i[r]+i[r],16);a&&(n=Math.round(parseInt(a+a,16)/255*100)/100)}else if(i=t.match(/^#([a-fA-F0-9]{6}([a-fA-F0-9]{2})?)$/i)){a=i[2],i=i[1];for(r=0;r<e.length;r++)e[r]=parseInt(i.slice(2*r,2*r+2),16);a&&(n=Math.round(parseInt(a,16)/255*100)/100)}else if(i=t.match(/^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i)){for(r=0;r<e.length;r++)e[r]=parseInt(i[r+1]);n=parseFloat(i[4])}else if(i=t.match(/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/i)){for(r=0;r<e.length;r++)e[r]=Math.round(2.55*parseFloat(i[r+1]));n=parseFloat(i[4])}else if(i=t.match(/(\w+)/)){if("transparent"==i[1])return[0,0,0,0];if(!(e=l[i[1]]))return}for(r=0;r<e.length;r++)e[r]=m(e[r],0,255);return n=n||0==n?m(n,0,1):1,e[3]=n,e}}function h(t){if(t){var e=t.match(/^hsla?\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/);if(e){var n=parseFloat(e[4]);return[m(parseInt(e[1]),0,360),m(parseFloat(e[2]),0,100),m(parseFloat(e[3]),0,100),m(isNaN(n)?1:n,0,1)]}}}function c(t){if(t){var e=t.match(/^hwb\(\s*([+-]?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)/);if(e){var n=parseFloat(e[4]);return[m(parseInt(e[1]),0,360),m(parseFloat(e[2]),0,100),m(parseFloat(e[3]),0,100),m(isNaN(n)?1:n,0,1)]}}}function f(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"rgba("+t[0]+", "+t[1]+", "+t[2]+", "+e+")"}function g(t,e){return"rgba("+Math.round(t[0]/255*100)+"%, "+Math.round(t[1]/255*100)+"%, "+Math.round(t[2]/255*100)+"%, "+(e||t[3]||1)+")"}function p(t,e){return void 0===e&&(e=void 0!==t[3]?t[3]:1),"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+e+")"}function m(t,e,n){return Math.min(Math.max(e,t),n)}function v(t){var e=t.toString(16).toUpperCase();return e.length<2?"0"+e:e}var b={};for(var x in l)b[l[x]]=x;var y=function(t){return t instanceof y?t:this instanceof y?(this.valid=!1,this.values={rgb:[0,0,0],hsl:[0,0,0],hsv:[0,0,0],hwb:[0,0,0],cmyk:[0,0,0,0],alpha:1},void("string"==typeof t?(e=u.getRgba(t))?this.setValues("rgb",e):(e=u.getHsla(t))?this.setValues("hsl",e):(e=u.getHwb(t))&&this.setValues("hwb",e):"object"==typeof t&&(void 0!==(e=t).r||void 0!==e.red?this.setValues("rgb",e):void 0!==e.l||void 0!==e.lightness?this.setValues("hsl",e):void 0!==e.v||void 0!==e.value?this.setValues("hsv",e):void 0!==e.w||void 0!==e.whiteness?this.setValues("hwb",e):void 0===e.c&&void 0===e.cyan||this.setValues("cmyk",e)))):new y(t);var e};y.prototype={isValid:function(){return this.valid},rgb:function(){return this.setSpace("rgb",arguments)},hsl:function(){return this.setSpace("hsl",arguments)},hsv:function(){return this.setSpace("hsv",arguments)},hwb:function(){return this.setSpace("hwb",arguments)},cmyk:function(){return this.setSpace("cmyk",arguments)},rgbArray:function(){return this.values.rgb},hslArray:function(){return this.values.hsl},hsvArray:function(){return this.values.hsv},hwbArray:function(){var t=this.values;return 1!==t.alpha?t.hwb.concat([t.alpha]):t.hwb},cmykArray:function(){return this.values.cmyk},rgbaArray:function(){var t=this.values;return t.rgb.concat([t.alpha])},hslaArray:function(){var t=this.values;return t.hsl.concat([t.alpha])},alpha:function(t){return void 0===t?this.values.alpha:(this.setValues("alpha",t),this)},red:function(t){return this.setChannel("rgb",0,t)},green:function(t){return this.setChannel("rgb",1,t)},blue:function(t){return this.setChannel("rgb",2,t)},hue:function(t){return t&&(t=(t%=360)<0?360+t:t),this.setChannel("hsl",0,t)},saturation:function(t){return this.setChannel("hsl",1,t)},lightness:function(t){return this.setChannel("hsl",2,t)},saturationv:function(t){return this.setChannel("hsv",1,t)},whiteness:function(t){return this.setChannel("hwb",1,t)},blackness:function(t){return this.setChannel("hwb",2,t)},value:function(t){return this.setChannel("hsv",2,t)},cyan:function(t){return this.setChannel("cmyk",0,t)},magenta:function(t){return this.setChannel("cmyk",1,t)},yellow:function(t){return this.setChannel("cmyk",2,t)},black:function(t){return this.setChannel("cmyk",3,t)},hexString:function(){return u.hexString(this.values.rgb)},rgbString:function(){return u.rgbString(this.values.rgb,this.values.alpha)},rgbaString:function(){return u.rgbaString(this.values.rgb,this.values.alpha)},percentString:function(){return u.percentString(this.values.rgb,this.values.alpha)},hslString:function(){return u.hslString(this.values.hsl,this.values.alpha)},hslaString:function(){return u.hslaString(this.values.hsl,this.values.alpha)},hwbString:function(){return u.hwbString(this.values.hwb,this.values.alpha)},keyword:function(){return u.keyword(this.values.rgb,this.values.alpha)},rgbNumber:function(){var t=this.values.rgb;return t[0]<<16|t[1]<<8|t[2]},luminosity:function(){for(var t=this.values.rgb,e=[],n=0;n<t.length;n++){var i=t[n]/255;e[n]=i<=.03928?i/12.92:Math.pow((i+.055)/1.055,2.4)}return.2126*e[0]+.7152*e[1]+.0722*e[2]},contrast:function(t){var e=this.luminosity(),n=t.luminosity();return e>n?(e+.05)/(n+.05):(n+.05)/(e+.05)},level:function(t){var e=this.contrast(t);return e>=7.1?"AAA":e>=4.5?"AA":""},dark:function(){var t=this.values.rgb;return(299*t[0]+587*t[1]+114*t[2])/1e3<128},light:function(){return!this.dark()},negate:function(){for(var t=[],e=0;e<3;e++)t[e]=255-this.values.rgb[e];return this.setValues("rgb",t),this},lighten:function(t){var e=this.values.hsl;return e[2]+=e[2]*t,this.setValues("hsl",e),this},darken:function(t){var e=this.values.hsl;return e[2]-=e[2]*t,this.setValues("hsl",e),this},saturate:function(t){var e=this.values.hsl;return e[1]+=e[1]*t,this.setValues("hsl",e),this},desaturate:function(t){var e=this.values.hsl;return e[1]-=e[1]*t,this.setValues("hsl",e),this},whiten:function(t){var e=this.values.hwb;return e[1]+=e[1]*t,this.setValues("hwb",e),this},blacken:function(t){var e=this.values.hwb;return e[2]+=e[2]*t,this.setValues("hwb",e),this},greyscale:function(){var t=this.values.rgb,e=.3*t[0]+.59*t[1]+.11*t[2];return this.setValues("rgb",[e,e,e]),this},clearer:function(t){var e=this.values.alpha;return this.setValues("alpha",e-e*t),this},opaquer:function(t){var e=this.values.alpha;return this.setValues("alpha",e+e*t),this},rotate:function(t){var e=this.values.hsl,n=(e[0]+t)%360;return e[0]=n<0?360+n:n,this.setValues("hsl",e),this},mix:function(t,e){var n=t,i=void 0===e?.5:e,a=2*i-1,r=this.alpha()-n.alpha(),o=((a*r==-1?a:(a+r)/(1+a*r))+1)/2,s=1-o;return this.rgb(o*this.red()+s*n.red(),o*this.green()+s*n.green(),o*this.blue()+s*n.blue()).alpha(this.alpha()*i+n.alpha()*(1-i))},toJSON:function(){return this.rgb()},clone:function(){var t,e,n=new y,i=this.values,a=n.values;for(var r in i)i.hasOwnProperty(r)&&(t=i[r],"[object Array]"===(e={}.toString.call(t))?a[r]=t.slice(0):"[object Number]"===e?a[r]=t:console.error("unexpected color value:",t));return n}},y.prototype.spaces={rgb:["red","green","blue"],hsl:["hue","saturation","lightness"],hsv:["hue","saturation","value"],hwb:["hue","whiteness","blackness"],cmyk:["cyan","magenta","yellow","black"]},y.prototype.maxes={rgb:[255,255,255],hsl:[360,100,100],hsv:[360,100,100],hwb:[360,100,100],cmyk:[100,100,100,100]},y.prototype.getValues=function(t){for(var e=this.values,n={},i=0;i<t.length;i++)n[t.charAt(i)]=e[t][i];return 1!==e.alpha&&(n.a=e.alpha),n},y.prototype.setValues=function(t,e){var n,i,a=this.values,r=this.spaces,o=this.maxes,l=1;if(this.valid=!0,"alpha"===t)l=e;else if(e.length)a[t]=e.slice(0,t.length),l=e[t.length];else if(void 0!==e[t.charAt(0)]){for(n=0;n<t.length;n++)a[t][n]=e[t.charAt(n)];l=e.a}else if(void 0!==e[r[t][0]]){var u=r[t];for(n=0;n<t.length;n++)a[t][n]=e[u[n]];l=e.alpha}if(a.alpha=Math.max(0,Math.min(1,void 0===l?a.alpha:l)),"alpha"===t)return!1;for(n=0;n<t.length;n++)i=Math.max(0,Math.min(o[t][n],a[t][n])),a[t][n]=Math.round(i);for(var d in r)d!==t&&(a[d]=s[t][d](a[t]));return!0},y.prototype.setSpace=function(t,e){var n=e[0];return void 0===n?this.getValues(t):("number"==typeof n&&(n=Array.prototype.slice.call(e)),this.setValues(t,n),this)},y.prototype.setChannel=function(t,e,n){var i=this.values[t];return void 0===n?i[e]:n===i[e]?this:(i[e]=n,this.setValues(t,i),this)},"undefined"!=typeof window&&(window.Color=y);var _,k=y,w={noop:function(){},uid:(_=0,function(){return _++}),isNullOrUndef:function(t){return null==t},isArray:function(t){if(Array.isArray&&Array.isArray(t))return!0;var e=Object.prototype.toString.call(t);return"[object"===e.substr(0,7)&&"Array]"===e.substr(-6)},isObject:function(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)},isFinite:function(t){return("number"==typeof t||t instanceof Number)&&isFinite(t)},valueOrDefault:function(t,e){return void 0===t?e:t},valueAtIndexOrDefault:function(t,e,n){return w.valueOrDefault(w.isArray(t)?t[e]:t,n)},callback:function(t,e,n){if(t&&"function"==typeof t.call)return t.apply(n,e)},each:function(t,e,n,i){var a,r,o;if(w.isArray(t))if(r=t.length,i)for(a=r-1;a>=0;a--)e.call(n,t[a],a);else for(a=0;a<r;a++)e.call(n,t[a],a);else if(w.isObject(t))for(r=(o=Object.keys(t)).length,a=0;a<r;a++)e.call(n,t[o[a]],o[a])},arrayEquals:function(t,e){var n,i,a,r;if(!t||!e||t.length!==e.length)return!1;for(n=0,i=t.length;n<i;++n)if(a=t[n],r=e[n],a instanceof Array&&r instanceof Array){if(!w.arrayEquals(a,r))return!1}else if(a!==r)return!1;return!0},clone:function(t){if(w.isArray(t))return t.map(w.clone);if(w.isObject(t)){for(var e={},n=Object.keys(t),i=n.length,a=0;a<i;++a)e[n[a]]=w.clone(t[n[a]]);return e}return t},_merger:function(t,e,n,i){var a=e[t],r=n[t];w.isObject(a)&&w.isObject(r)?w.merge(a,r,i):e[t]=w.clone(r)},_mergerIf:function(t,e,n){var i=e[t],a=n[t];w.isObject(i)&&w.isObject(a)?w.mergeIf(i,a):e.hasOwnProperty(t)||(e[t]=w.clone(a))},merge:function(t,e,n){var i,a,r,o,s,l=w.isArray(e)?e:[e],u=l.length;if(!w.isObject(t))return t;for(i=(n=n||{}).merger||w._merger,a=0;a<u;++a)if(e=l[a],w.isObject(e))for(s=0,o=(r=Object.keys(e)).length;s<o;++s)i(r[s],t,e,n);return t},mergeIf:function(t,e){return w.merge(t,e,{merger:w._mergerIf})},extend:Object.assign||function(t){return w.merge(t,[].slice.call(arguments,1),{merger:function(t,e,n){e[t]=n[t]}})},inherits:function(t){var e=this,n=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return e.apply(this,arguments)},i=function(){this.constructor=n};return i.prototype=e.prototype,n.prototype=new i,n.extend=w.inherits,t&&w.extend(n.prototype,t),n.__super__=e.prototype,n},_deprecated:function(t,e,n,i){void 0!==e&&console.warn(t+': "'+n+'" is deprecated. Please use "'+i+'" instead')}},M=w;w.callCallback=w.callback,w.indexOf=function(t,e,n){return Array.prototype.indexOf.call(t,e,n)},w.getValueOrDefault=w.valueOrDefault,w.getValueAtIndexOrDefault=w.valueAtIndexOrDefault;var S={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return(t-=1)*t*t+1},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-((t-=1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return t*t*t*t*t},easeOutQuint:function(t){return(t-=1)*t*t*t*t+1},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return 1-Math.cos(t*(Math.PI/2))},easeOutSine:function(t){return Math.sin(t*(Math.PI/2))},easeInOutSine:function(t){return-.5*(Math.cos(Math.PI*t)-1)},easeInExpo:function(t){return 0===t?0:Math.pow(2,10*(t-1))},easeOutExpo:function(t){return 1===t?1:1-Math.pow(2,-10*t)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(2-Math.pow(2,-10*--t))},easeInCirc:function(t){return t>=1?t:-(Math.sqrt(1-t*t)-1)},easeOutCirc:function(t){return Math.sqrt(1-(t-=1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var e=1.70158,n=0,i=1;return 0===t?0:1===t?1:(n||(n=.3),i<1?(i=1,e=n/4):e=n/(2*Math.PI)*Math.asin(1/i),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/n))},easeOutElastic:function(t){var e=1.70158,n=0,i=1;return 0===t?0:1===t?1:(n||(n=.3),i<1?(i=1,e=n/4):e=n/(2*Math.PI)*Math.asin(1/i),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/n)+1)},easeInOutElastic:function(t){var e=1.70158,n=0,i=1;return 0===t?0:2==(t/=.5)?1:(n||(n=.45),i<1?(i=1,e=n/4):e=n/(2*Math.PI)*Math.asin(1/i),t<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/n)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/n)*.5+1)},easeInBack:function(t){var e=1.70158;return t*t*((e+1)*t-e)},easeOutBack:function(t){var e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack:function(t){var e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:function(t){return 1-S.easeOutBounce(1-t)},easeOutBounce:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:function(t){return t<.5?.5*S.easeInBounce(2*t):.5*S.easeOutBounce(2*t-1)+.5}},C={effects:S};M.easingEffects=S;var P=Math.PI,A=P/180,D=2*P,T=P/2,I=P/4,F=2*P/3,L={clear:function(t){t.ctx.clearRect(0,0,t.width,t.height)},roundedRect:function(t,e,n,i,a,r){if(r){var o=Math.min(r,a/2,i/2),s=e+o,l=n+o,u=e+i-o,d=n+a-o;t.moveTo(e,l),s<u&&l<d?(t.arc(s,l,o,-P,-T),t.arc(u,l,o,-T,0),t.arc(u,d,o,0,T),t.arc(s,d,o,T,P)):s<u?(t.moveTo(s,n),t.arc(u,l,o,-T,T),t.arc(s,l,o,T,P+T)):l<d?(t.arc(s,l,o,-P,0),t.arc(s,d,o,0,P)):t.arc(s,l,o,-P,P),t.closePath(),t.moveTo(e,n)}else t.rect(e,n,i,a)},drawPoint:function(t,e,n,i,a,r){var o,s,l,u,d,h=(r||0)*A;if(e&&"object"==typeof e&&("[object HTMLImageElement]"===(o=e.toString())||"[object HTMLCanvasElement]"===o))return t.save(),t.translate(i,a),t.rotate(h),t.drawImage(e,-e.width/2,-e.height/2,e.width,e.height),void t.restore();if(!(isNaN(n)||n<=0)){switch(t.beginPath(),e){default:t.arc(i,a,n,0,D),t.closePath();break;case"triangle":t.moveTo(i+Math.sin(h)*n,a-Math.cos(h)*n),h+=F,t.lineTo(i+Math.sin(h)*n,a-Math.cos(h)*n),h+=F,t.lineTo(i+Math.sin(h)*n,a-Math.cos(h)*n),t.closePath();break;case"rectRounded":u=n-(d=.516*n),s=Math.cos(h+I)*u,l=Math.sin(h+I)*u,t.arc(i-s,a-l,d,h-P,h-T),t.arc(i+l,a-s,d,h-T,h),t.arc(i+s,a+l,d,h,h+T),t.arc(i-l,a+s,d,h+T,h+P),t.closePath();break;case"rect":if(!r){u=Math.SQRT1_2*n,t.rect(i-u,a-u,2*u,2*u);break}h+=I;case"rectRot":s=Math.cos(h)*n,l=Math.sin(h)*n,t.moveTo(i-s,a-l),t.lineTo(i+l,a-s),t.lineTo(i+s,a+l),t.lineTo(i-l,a+s),t.closePath();break;case"crossRot":h+=I;case"cross":s=Math.cos(h)*n,l=Math.sin(h)*n,t.moveTo(i-s,a-l),t.lineTo(i+s,a+l),t.moveTo(i+l,a-s),t.lineTo(i-l,a+s);break;case"star":s=Math.cos(h)*n,l=Math.sin(h)*n,t.moveTo(i-s,a-l),t.lineTo(i+s,a+l),t.moveTo(i+l,a-s),t.lineTo(i-l,a+s),h+=I,s=Math.cos(h)*n,l=Math.sin(h)*n,t.moveTo(i-s,a-l),t.lineTo(i+s,a+l),t.moveTo(i+l,a-s),t.lineTo(i-l,a+s);break;case"line":s=Math.cos(h)*n,l=Math.sin(h)*n,t.moveTo(i-s,a-l),t.lineTo(i+s,a+l);break;case"dash":t.moveTo(i,a),t.lineTo(i+Math.cos(h)*n,a+Math.sin(h)*n)}t.fill(),t.stroke()}},_isPointInArea:function(t,e){return t.x>e.left-1e-6&&t.x<e.right+1e-6&&t.y>e.top-1e-6&&t.y<e.bottom+1e-6},clipArea:function(t,e){t.save(),t.beginPath(),t.rect(e.left,e.top,e.right-e.left,e.bottom-e.top),t.clip()},unclipArea:function(t){t.restore()},lineTo:function(t,e,n,i){var a=n.steppedLine;if(a){if("middle"===a){var r=(e.x+n.x)/2;t.lineTo(r,i?n.y:e.y),t.lineTo(r,i?e.y:n.y)}else"after"===a&&!i||"after"!==a&&i?t.lineTo(e.x,n.y):t.lineTo(n.x,e.y);t.lineTo(n.x,n.y)}else n.tension?t.bezierCurveTo(i?e.controlPointPreviousX:e.controlPointNextX,i?e.controlPointPreviousY:e.controlPointNextY,i?n.controlPointNextX:n.controlPointPreviousX,i?n.controlPointNextY:n.controlPointPreviousY,n.x,n.y):t.lineTo(n.x,n.y)}},O=L;M.clear=L.clear,M.drawRoundedRectangle=function(t){t.beginPath(),L.roundedRect.apply(L,arguments)};var R={_set:function(t,e){return M.merge(this[t]||(this[t]={}),e)}};R._set("global",{defaultColor:"rgba(0,0,0,0.1)",defaultFontColor:"#666",defaultFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",defaultFontSize:12,defaultFontStyle:"normal",defaultLineHeight:1.2,showLines:!0});var z=R,N=M.valueOrDefault;var B={toLineHeight:function(t,e){var n=(""+t).match(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/);if(!n||"normal"===n[1])return 1.2*e;switch(t=+n[2],n[3]){case"px":return t;case"%":t/=100}return e*t},toPadding:function(t){var e,n,i,a;return M.isObject(t)?(e=+t.top||0,n=+t.right||0,i=+t.bottom||0,a=+t.left||0):e=n=i=a=+t||0,{top:e,right:n,bottom:i,left:a,height:e+i,width:a+n}},_parseFont:function(t){var e=z.global,n=N(t.fontSize,e.defaultFontSize),i={family:N(t.fontFamily,e.defaultFontFamily),lineHeight:M.options.toLineHeight(N(t.lineHeight,e.defaultLineHeight),n),size:n,style:N(t.fontStyle,e.defaultFontStyle),weight:null,string:""};return i.string=function(t){return!t||M.isNullOrUndef(t.size)||M.isNullOrUndef(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}(i),i},resolve:function(t,e,n,i){var a,r,o,s=!0;for(a=0,r=t.length;a<r;++a)if(void 0!==(o=t[a])&&(void 0!==e&&"function"==typeof o&&(o=o(e),s=!1),void 0!==n&&M.isArray(o)&&(o=o[n],s=!1),void 0!==o))return i&&!s&&(i.cacheable=!1),o}},E={_factorize:function(t){var e,n=[],i=Math.sqrt(t);for(e=1;e<i;e++)t%e==0&&(n.push(e),n.push(t/e));return i===(0|i)&&n.push(i),n.sort((function(t,e){return t-e})).pop(),n},log10:Math.log10||function(t){var e=Math.log(t)*Math.LOG10E,n=Math.round(e);return t===Math.pow(10,n)?n:e}},W=E;M.log10=E.log10;var V=M,H=C,j=O,q=B,U=W,Y={getRtlAdapter:function(t,e,n){return t?function(t,e){return{x:function(n){return t+t+e-n},setWidth:function(t){e=t},textAlign:function(t){return"center"===t?t:"right"===t?"left":"right"},xPlus:function(t,e){return t-e},leftForLtr:function(t,e){return t-e}}}(e,n):{x:function(t){return t},setWidth:function(t){},textAlign:function(t){return t},xPlus:function(t,e){return t+e},leftForLtr:function(t,e){return t}}},overrideTextDirection:function(t,e){var n,i;"ltr"!==e&&"rtl"!==e||(i=[(n=t.canvas.style).getPropertyValue("direction"),n.getPropertyPriority("direction")],n.setProperty("direction",e,"important"),t.prevTextDirection=i)},restoreTextDirection:function(t){var e=t.prevTextDirection;void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}};V.easing=H,V.canvas=j,V.options=q,V.math=U,V.rtl=Y;var G=function(t){V.extend(this,t),this.initialize.apply(this,arguments)};V.extend(G.prototype,{_type:void 0,initialize:function(){this.hidden=!1},pivot:function(){var t=this;return t._view||(t._view=V.extend({},t._model)),t._start={},t},transition:function(t){var e=this,n=e._model,i=e._start,a=e._view;return n&&1!==t?(a||(a=e._view={}),i||(i=e._start={}),function(t,e,n,i){var a,r,o,s,l,u,d,h,c,f=Object.keys(n);for(a=0,r=f.length;a<r;++a)if(u=n[o=f[a]],e.hasOwnProperty(o)||(e[o]=u),(s=e[o])!==u&&"_"!==o[0]){if(t.hasOwnProperty(o)||(t[o]=s),(d=typeof u)===typeof(l=t[o]))if("string"===d){if((h=k(l)).valid&&(c=k(u)).valid){e[o]=c.mix(h,i).rgbString();continue}}else if(V.isFinite(l)&&V.isFinite(u)){e[o]=l+(u-l)*i;continue}e[o]=u}}(i,a,n,t),e):(e._view=V.extend({},n),e._start=null,e)},tooltipPosition:function(){return{x:this._model.x,y:this._model.y}},hasValue:function(){return V.isNumber(this._model.x)&&V.isNumber(this._model.y)}}),G.extend=V.inherits;var X=G,K=X.extend({chart:null,currentStep:0,numSteps:60,easing:"",render:null,onAnimationProgress:null,onAnimationComplete:null}),Z=K;Object.defineProperty(K.prototype,"animationObject",{get:function(){return this}}),Object.defineProperty(K.prototype,"chartInstance",{get:function(){return this.chart},set:function(t){this.chart=t}}),z._set("global",{animation:{duration:1e3,easing:"easeOutQuart",onProgress:V.noop,onComplete:V.noop}});var $={animations:[],request:null,addAnimation:function(t,e,n,i){var a,r,o=this.animations;for(e.chart=t,e.startTime=Date.now(),e.duration=n,i||(t.animating=!0),a=0,r=o.length;a<r;++a)if(o[a].chart===t)return void(o[a]=e);o.push(e),1===o.length&&this.requestAnimationFrame()},cancelAnimation:function(t){var e=V.findIndex(this.animations,(function(e){return e.chart===t}));-1!==e&&(this.animations.splice(e,1),t.animating=!1)},requestAnimationFrame:function(){var t=this;null===t.request&&(t.request=V.requestAnimFrame.call(window,(function(){t.request=null,t.startDigest()})))},startDigest:function(){this.advance(),this.animations.length>0&&this.requestAnimationFrame()},advance:function(){for(var t,e,n,i,a=this.animations,r=0;r<a.length;)e=(t=a[r]).chart,n=t.numSteps,i=Math.floor((Date.now()-t.startTime)/t.duration*n)+1,t.currentStep=Math.min(i,n),V.callback(t.render,[e,t],e),V.callback(t.onAnimationProgress,[t],e),t.currentStep>=n?(V.callback(t.onAnimationComplete,[t],e),e.animating=!1,a.splice(r,1)):++r}},J=V.options.resolve,Q=["push","pop","shift","splice","unshift"];function tt(t,e){var n=t._chartjs;if(n){var i=n.listeners,a=i.indexOf(e);-1!==a&&i.splice(a,1),i.length>0||(Q.forEach((function(e){delete t[e]})),delete t._chartjs)}}var et=function(t,e){this.initialize(t,e)};V.extend(et.prototype,{datasetElementType:null,dataElementType:null,_datasetElementOptions:["backgroundColor","borderCapStyle","borderColor","borderDash","borderDashOffset","borderJoinStyle","borderWidth"],_dataElementOptions:["backgroundColor","borderColor","borderWidth","pointStyle"],initialize:function(t,e){var n=this;n.chart=t,n.index=e,n.linkScales(),n.addElements(),n._type=n.getMeta().type},updateIndex:function(t){this.index=t},linkScales:function(){var t=this.getMeta(),e=this.chart,n=e.scales,i=this.getDataset(),a=e.options.scales;null!==t.xAxisID&&t.xAxisID in n&&!i.xAxisID||(t.xAxisID=i.xAxisID||a.xAxes[0].id),null!==t.yAxisID&&t.yAxisID in n&&!i.yAxisID||(t.yAxisID=i.yAxisID||a.yAxes[0].id)},getDataset:function(){return this.chart.data.datasets[this.index]},getMeta:function(){return this.chart.getDatasetMeta(this.index)},getScaleForId:function(t){return this.chart.scales[t]},_getValueScaleId:function(){return this.getMeta().yAxisID},_getIndexScaleId:function(){return this.getMeta().xAxisID},_getValueScale:function(){return this.getScaleForId(this._getValueScaleId())},_getIndexScale:function(){return this.getScaleForId(this._getIndexScaleId())},reset:function(){this._update(!0)},destroy:function(){this._data&&tt(this._data,this)},createMetaDataset:function(){var t=this.datasetElementType;return t&&new t({_chart:this.chart,_datasetIndex:this.index})},createMetaData:function(t){var e=this.dataElementType;return e&&new e({_chart:this.chart,_datasetIndex:this.index,_index:t})},addElements:function(){var t,e,n=this.getMeta(),i=this.getDataset().data||[],a=n.data;for(t=0,e=i.length;t<e;++t)a[t]=a[t]||this.createMetaData(t);n.dataset=n.dataset||this.createMetaDataset()},addElementAndReset:function(t){var e=this.createMetaData(t);this.getMeta().data.splice(t,0,e),this.updateElement(e,t,!0)},buildOrUpdateElements:function(){var t,e,n=this,i=n.getDataset(),a=i.data||(i.data=[]);n._data!==a&&(n._data&&tt(n._data,n),a&&Object.isExtensible(a)&&(e=n,(t=a)._chartjs?t._chartjs.listeners.push(e):(Object.defineProperty(t,"_chartjs",{configurable:!0,enumerable:!1,value:{listeners:[e]}}),Q.forEach((function(e){var n="onData"+e.charAt(0).toUpperCase()+e.slice(1),i=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value:function(){var e=Array.prototype.slice.call(arguments),a=i.apply(this,e);return V.each(t._chartjs.listeners,(function(t){"function"==typeof t[n]&&t[n].apply(t,e)})),a}})})))),n._data=a),n.resyncElements()},_configure:function(){this._config=V.merge({},[this.chart.options.datasets[this._type],this.getDataset()],{merger:function(t,e,n){"_meta"!==t&&"data"!==t&&V._merger(t,e,n)}})},_update:function(t){this._configure(),this._cachedDataOpts=null,this.update(t)},update:V.noop,transition:function(t){for(var e=this.getMeta(),n=e.data||[],i=n.length,a=0;a<i;++a)n[a].transition(t);e.dataset&&e.dataset.transition(t)},draw:function(){var t=this.getMeta(),e=t.data||[],n=e.length,i=0;for(t.dataset&&t.dataset.draw();i<n;++i)e[i].draw()},getStyle:function(t){var e,n=this.getMeta(),i=n.dataset;return this._configure(),i&&void 0===t?e=this._resolveDatasetElementOptions(i||{}):(t=t||0,e=this._resolveDataElementOptions(n.data[t]||{},t)),!1!==e.fill&&null!==e.fill||(e.backgroundColor=e.borderColor),e},_resolveDatasetElementOptions:function(t,e){var n,i,a,r,o=this,s=o.chart,l=o._config,u=t.custom||{},d=s.options.elements[o.datasetElementType.prototype._type]||{},h=o._datasetElementOptions,c={},f={chart:s,dataset:o.getDataset(),datasetIndex:o.index,hover:e};for(n=0,i=h.length;n<i;++n)a=h[n],r=e?"hover"+a.charAt(0).toUpperCase()+a.slice(1):a,c[a]=J([u[r],l[r],d[r]],f);return c},_resolveDataElementOptions:function(t,e){var n=this,i=t&&t.custom,a=n._cachedDataOpts;if(a&&!i)return a;var r,o,s,l,u=n.chart,d=n._config,h=u.options.elements[n.dataElementType.prototype._type]||{},c=n._dataElementOptions,f={},g={chart:u,dataIndex:e,dataset:n.getDataset(),datasetIndex:n.index},p={cacheable:!i};if(i=i||{},V.isArray(c))for(o=0,s=c.length;o<s;++o)f[l=c[o]]=J([i[l],d[l],h[l]],g,e,p);else for(o=0,s=(r=Object.keys(c)).length;o<s;++o)f[l=r[o]]=J([i[l],d[c[l]],d[l],h[l]],g,e,p);return p.cacheable&&(n._cachedDataOpts=Object.freeze(f)),f},removeHoverStyle:function(t){V.merge(t._model,t.$previousStyle||{}),delete t.$previousStyle},setHoverStyle:function(t){var e=this.chart.data.datasets[t._datasetIndex],n=t._index,i=t.custom||{},a=t._model,r=V.getHoverColor;t.$previousStyle={backgroundColor:a.backgroundColor,borderColor:a.borderColor,borderWidth:a.borderWidth},a.backgroundColor=J([i.hoverBackgroundColor,e.hoverBackgroundColor,r(a.backgroundColor)],void 0,n),a.borderColor=J([i.hoverBorderColor,e.hoverBorderColor,r(a.borderColor)],void 0,n),a.borderWidth=J([i.hoverBorderWidth,e.hoverBorderWidth,a.borderWidth],void 0,n)},_removeDatasetHoverStyle:function(){var t=this.getMeta().dataset;t&&this.removeHoverStyle(t)},_setDatasetHoverStyle:function(){var t,e,n,i,a,r,o=this.getMeta().dataset,s={};if(o){for(r=o._model,a=this._resolveDatasetElementOptions(o,!0),t=0,e=(i=Object.keys(a)).length;t<e;++t)s[n=i[t]]=r[n],r[n]=a[n];o.$previousStyle=s}},resyncElements:function(){var t=this.getMeta(),e=this.getDataset().data,n=t.data.length,i=e.length;i<n?t.data.splice(i,n-i):i>n&&this.insertElements(n,i-n)},insertElements:function(t,e){for(var n=0;n<e;++n)this.addElementAndReset(t+n)},onDataPush:function(){var t=arguments.length;this.insertElements(this.getDataset().data.length-t,t)},onDataPop:function(){this.getMeta().data.pop()},onDataShift:function(){this.getMeta().data.shift()},onDataSplice:function(t,e){this.getMeta().data.splice(t,e),this.insertElements(t,arguments.length-2)},onDataUnshift:function(){this.insertElements(0,arguments.length)}}),et.extend=V.inherits;var nt=et,it=2*Math.PI;function at(t,e){var n=e.startAngle,i=e.endAngle,a=e.pixelMargin,r=a/e.outerRadius,o=e.x,s=e.y;t.beginPath(),t.arc(o,s,e.outerRadius,n-r,i+r),e.innerRadius>a?(r=a/e.innerRadius,t.arc(o,s,e.innerRadius-a,i+r,n-r,!0)):t.arc(o,s,a,i+Math.PI/2,n-Math.PI/2),t.closePath(),t.clip()}function rt(t,e,n){var i="inner"===e.borderAlign;i?(t.lineWidth=2*e.borderWidth,t.lineJoin="round"):(t.lineWidth=e.borderWidth,t.lineJoin="bevel"),n.fullCircles&&function(t,e,n,i){var a,r=n.endAngle;for(i&&(n.endAngle=n.startAngle+it,at(t,n),n.endAngle=r,n.endAngle===n.startAngle&&n.fullCircles&&(n.endAngle+=it,n.fullCircles--)),t.beginPath(),t.arc(n.x,n.y,n.innerRadius,n.startAngle+it,n.startAngle,!0),a=0;a<n.fullCircles;++a)t.stroke();for(t.beginPath(),t.arc(n.x,n.y,e.outerRadius,n.startAngle,n.startAngle+it),a=0;a<n.fullCircles;++a)t.stroke()}(t,e,n,i),i&&at(t,n),t.beginPath(),t.arc(n.x,n.y,e.outerRadius,n.startAngle,n.endAngle),t.arc(n.x,n.y,n.innerRadius,n.endAngle,n.startAngle,!0),t.closePath(),t.stroke()}z._set("global",{elements:{arc:{backgroundColor:z.global.defaultColor,borderColor:"#fff",borderWidth:2,borderAlign:"center"}}});var ot=X.extend({_type:"arc",inLabelRange:function(t){var e=this._view;return!!e&&Math.pow(t-e.x,2)<Math.pow(e.radius+e.hoverRadius,2)},inRange:function(t,e){var n=this._view;if(n){for(var i=V.getAngleFromPoint(n,{x:t,y:e}),a=i.angle,r=i.distance,o=n.startAngle,s=n.endAngle;s<o;)s+=it;for(;a>s;)a-=it;for(;a<o;)a+=it;var l=a>=o&&a<=s,u=r>=n.innerRadius&&r<=n.outerRadius;return l&&u}return!1},getCenterPoint:function(){var t=this._view,e=(t.startAngle+t.endAngle)/2,n=(t.innerRadius+t.outerRadius)/2;return{x:t.x+Math.cos(e)*n,y:t.y+Math.sin(e)*n}},getArea:function(){var t=this._view;return Math.PI*((t.endAngle-t.startAngle)/(2*Math.PI))*(Math.pow(t.outerRadius,2)-Math.pow(t.innerRadius,2))},tooltipPosition:function(){var t=this._view,e=t.startAngle+(t.endAngle-t.startAngle)/2,n=(t.outerRadius-t.innerRadius)/2+t.innerRadius;return{x:t.x+Math.cos(e)*n,y:t.y+Math.sin(e)*n}},draw:function(){var t,e=this._chart.ctx,n=this._view,i="inner"===n.borderAlign?.33:0,a={x:n.x,y:n.y,innerRadius:n.innerRadius,outerRadius:Math.max(n.outerRadius-i,0),pixelMargin:i,startAngle:n.startAngle,endAngle:n.endAngle,fullCircles:Math.floor(n.circumference/it)};if(e.save(),e.fillStyle=n.backgroundColor,e.strokeStyle=n.borderColor,a.fullCircles){for(a.endAngle=a.startAngle+it,e.beginPath(),e.arc(a.x,a.y,a.outerRadius,a.startAngle,a.endAngle),e.arc(a.x,a.y,a.innerRadius,a.endAngle,a.startAngle,!0),e.closePath(),t=0;t<a.fullCircles;++t)e.fill();a.endAngle=a.startAngle+n.circumference%it}e.beginPath(),e.arc(a.x,a.y,a.outerRadius,a.startAngle,a.endAngle),e.arc(a.x,a.y,a.innerRadius,a.endAngle,a.startAngle,!0),e.closePath(),e.fill(),n.borderWidth&&rt(e,n,a),e.restore()}}),st=V.valueOrDefault,lt=z.global.defaultColor;z._set("global",{elements:{line:{tension:.4,backgroundColor:lt,borderWidth:3,borderColor:lt,borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",capBezierPoints:!0,fill:!0}}});var ut=X.extend({_type:"line",draw:function(){var t,e,n,i=this,a=i._view,r=i._chart.ctx,o=a.spanGaps,s=i._children.slice(),l=z.global,u=l.elements.line,d=-1,h=i._loop;if(s.length){if(i._loop){for(t=0;t<s.length;++t)if(e=V.previousItem(s,t),!s[t]._view.skip&&e._view.skip){s=s.slice(t).concat(s.slice(0,t)),h=o;break}h&&s.push(s[0])}for(r.save(),r.lineCap=a.borderCapStyle||u.borderCapStyle,r.setLineDash&&r.setLineDash(a.borderDash||u.borderDash),r.lineDashOffset=st(a.borderDashOffset,u.borderDashOffset),r.lineJoin=a.borderJoinStyle||u.borderJoinStyle,r.lineWidth=st(a.borderWidth,u.borderWidth),r.strokeStyle=a.borderColor||l.defaultColor,r.beginPath(),(n=s[0]._view).skip||(r.moveTo(n.x,n.y),d=0),t=1;t<s.length;++t)n=s[t]._view,e=-1===d?V.previousItem(s,t):s[d],n.skip||(d!==t-1&&!o||-1===d?r.moveTo(n.x,n.y):V.canvas.lineTo(r,e._view,n),d=t);h&&r.closePath(),r.stroke(),r.restore()}}}),dt=V.valueOrDefault,ht=z.global.defaultColor;function ct(t){var e=this._view;return!!e&&Math.abs(t-e.x)<e.radius+e.hitRadius}z._set("global",{elements:{point:{radius:3,pointStyle:"circle",backgroundColor:ht,borderColor:ht,borderWidth:1,hitRadius:1,hoverRadius:4,hoverBorderWidth:1}}});var ft=X.extend({_type:"point",inRange:function(t,e){var n=this._view;return!!n&&Math.pow(t-n.x,2)+Math.pow(e-n.y,2)<Math.pow(n.hitRadius+n.radius,2)},inLabelRange:ct,inXRange:ct,inYRange:function(t){var e=this._view;return!!e&&Math.abs(t-e.y)<e.radius+e.hitRadius},getCenterPoint:function(){var t=this._view;return{x:t.x,y:t.y}},getArea:function(){return Math.PI*Math.pow(this._view.radius,2)},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y,padding:t.radius+t.borderWidth}},draw:function(t){var e=this._view,n=this._chart.ctx,i=e.pointStyle,a=e.rotation,r=e.radius,o=e.x,s=e.y,l=z.global,u=l.defaultColor;e.skip||(void 0===t||V.canvas._isPointInArea(e,t))&&(n.strokeStyle=e.borderColor||u,n.lineWidth=dt(e.borderWidth,l.elements.point.borderWidth),n.fillStyle=e.backgroundColor||u,V.canvas.drawPoint(n,i,r,o,s,a))}}),gt=z.global.defaultColor;function pt(t){return t&&void 0!==t.width}function mt(t){var e,n,i,a,r;return pt(t)?(r=t.width/2,e=t.x-r,n=t.x+r,i=Math.min(t.y,t.base),a=Math.max(t.y,t.base)):(r=t.height/2,e=Math.min(t.x,t.base),n=Math.max(t.x,t.base),i=t.y-r,a=t.y+r),{left:e,top:i,right:n,bottom:a}}function vt(t,e,n){return t===e?n:t===n?e:t}function bt(t,e,n){var i,a,r,o,s=t.borderWidth,l=function(t){var e=t.borderSkipped,n={};return e?(t.horizontal?t.base>t.x&&(e=vt(e,"left","right")):t.base<t.y&&(e=vt(e,"bottom","top")),n[e]=!0,n):n}(t);return V.isObject(s)?(i=+s.top||0,a=+s.right||0,r=+s.bottom||0,o=+s.left||0):i=a=r=o=+s||0,{t:l.top||i<0?0:i>n?n:i,r:l.right||a<0?0:a>e?e:a,b:l.bottom||r<0?0:r>n?n:r,l:l.left||o<0?0:o>e?e:o}}function xt(t,e,n){var i=null===e,a=null===n,r=!(!t||i&&a)&&mt(t);return r&&(i||e>=r.left&&e<=r.right)&&(a||n>=r.top&&n<=r.bottom)}z._set("global",{elements:{rectangle:{backgroundColor:gt,borderColor:gt,borderSkipped:"bottom",borderWidth:0}}});var yt=X.extend({_type:"rectangle",draw:function(){var t=this._chart.ctx,e=this._view,n=function(t){var e=mt(t),n=e.right-e.left,i=e.bottom-e.top,a=bt(t,n/2,i/2);return{outer:{x:e.left,y:e.top,w:n,h:i},inner:{x:e.left+a.l,y:e.top+a.t,w:n-a.l-a.r,h:i-a.t-a.b}}}(e),i=n.outer,a=n.inner;t.fillStyle=e.backgroundColor,t.fillRect(i.x,i.y,i.w,i.h),i.w===a.w&&i.h===a.h||(t.save(),t.beginPath(),t.rect(i.x,i.y,i.w,i.h),t.clip(),t.fillStyle=e.borderColor,t.rect(a.x,a.y,a.w,a.h),t.fill("evenodd"),t.restore())},height:function(){var t=this._view;return t.base-t.y},inRange:function(t,e){return xt(this._view,t,e)},inLabelRange:function(t,e){var n=this._view;return pt(n)?xt(n,t,null):xt(n,null,e)},inXRange:function(t){return xt(this._view,t,null)},inYRange:function(t){return xt(this._view,null,t)},getCenterPoint:function(){var t,e,n=this._view;return pt(n)?(t=n.x,e=(n.y+n.base)/2):(t=(n.x+n.base)/2,e=n.y),{x:t,y:e}},getArea:function(){var t=this._view;return pt(t)?t.width*Math.abs(t.y-t.base):t.height*Math.abs(t.x-t.base)},tooltipPosition:function(){var t=this._view;return{x:t.x,y:t.y}}}),_t={},kt=ot,wt=ut,Mt=ft,St=yt;_t.Arc=kt,_t.Line=wt,_t.Point=Mt,_t.Rectangle=St;var Ct=V._deprecated,Pt=V.valueOrDefault;function At(t,e,n){var i,a,r=n.barThickness,o=e.stackCount,s=e.pixels[t],l=V.isNullOrUndef(r)?function(t,e){var n,i,a,r,o=t._length;for(a=1,r=e.length;a<r;++a)o=Math.min(o,Math.abs(e[a]-e[a-1]));for(a=0,r=t.getTicks().length;a<r;++a)i=t.getPixelForTick(a),o=a>0?Math.min(o,Math.abs(i-n)):o,n=i;return o}(e.scale,e.pixels):-1;return V.isNullOrUndef(r)?(i=l*n.categoryPercentage,a=n.barPercentage):(i=r*o,a=1),{chunk:i/o,ratio:a,start:s-i/2}}z._set("bar",{hover:{mode:"label"},scales:{xAxes:[{type:"category",offset:!0,gridLines:{offsetGridLines:!0}}],yAxes:[{type:"linear"}]}}),z._set("global",{datasets:{bar:{categoryPercentage:.8,barPercentage:.9}}});var Dt=nt.extend({dataElementType:_t.Rectangle,_dataElementOptions:["backgroundColor","borderColor","borderSkipped","borderWidth","barPercentage","barThickness","categoryPercentage","maxBarThickness","minBarLength"],initialize:function(){var t,e,n=this;nt.prototype.initialize.apply(n,arguments),(t=n.getMeta()).stack=n.getDataset().stack,t.bar=!0,e=n._getIndexScale().options,Ct("bar chart",e.barPercentage,"scales.[x/y]Axes.barPercentage","dataset.barPercentage"),Ct("bar chart",e.barThickness,"scales.[x/y]Axes.barThickness","dataset.barThickness"),Ct("bar chart",e.categoryPercentage,"scales.[x/y]Axes.categoryPercentage","dataset.categoryPercentage"),Ct("bar chart",n._getValueScale().options.minBarLength,"scales.[x/y]Axes.minBarLength","dataset.minBarLength"),Ct("bar chart",e.maxBarThickness,"scales.[x/y]Axes.maxBarThickness","dataset.maxBarThickness")},update:function(t){var e,n,i=this.getMeta().data;for(this._ruler=this.getRuler(),e=0,n=i.length;e<n;++e)this.updateElement(i[e],e,t)},updateElement:function(t,e,n){var i=this,a=i.getMeta(),r=i.getDataset(),o=i._resolveDataElementOptions(t,e);t._xScale=i.getScaleForId(a.xAxisID),t._yScale=i.getScaleForId(a.yAxisID),t._datasetIndex=i.index,t._index=e,t._model={backgroundColor:o.backgroundColor,borderColor:o.borderColor,borderSkipped:o.borderSkipped,borderWidth:o.borderWidth,datasetLabel:r.label,label:i.chart.data.labels[e]},V.isArray(r.data[e])&&(t._model.borderSkipped=null),i._updateElementGeometry(t,e,n,o),t.pivot()},_updateElementGeometry:function(t,e,n,i){var a=this,r=t._model,o=a._getValueScale(),s=o.getBasePixel(),l=o.isHorizontal(),u=a._ruler||a.getRuler(),d=a.calculateBarValuePixels(a.index,e,i),h=a.calculateBarIndexPixels(a.index,e,u,i);r.horizontal=l,r.base=n?s:d.base,r.x=l?n?s:d.head:h.center,r.y=l?h.center:n?s:d.head,r.height=l?h.size:void 0,r.width=l?void 0:h.size},_getStacks:function(t){var e,n,i=this._getIndexScale(),a=i._getMatchingVisibleMetas(this._type),r=i.options.stacked,o=a.length,s=[];for(e=0;e<o&&(n=a[e],(!1===r||-1===s.indexOf(n.stack)||void 0===r&&void 0===n.stack)&&s.push(n.stack),n.index!==t);++e);return s},getStackCount:function(){return this._getStacks().length},getStackIndex:function(t,e){var n=this._getStacks(t),i=void 0!==e?n.indexOf(e):-1;return-1===i?n.length-1:i},getRuler:function(){var t,e,n=this._getIndexScale(),i=[];for(t=0,e=this.getMeta().data.length;t<e;++t)i.push(n.getPixelForValue(null,t,this.index));return{pixels:i,start:n._startPixel,end:n._endPixel,stackCount:this.getStackCount(),scale:n}},calculateBarValuePixels:function(t,e,n){var i,a,r,o,s,l,u,d=this.chart,h=this._getValueScale(),c=h.isHorizontal(),f=d.data.datasets,g=h._getMatchingVisibleMetas(this._type),p=h._parseValue(f[t].data[e]),m=n.minBarLength,v=h.options.stacked,b=this.getMeta().stack,x=void 0===p.start?0:p.max>=0&&p.min>=0?p.min:p.max,y=void 0===p.start?p.end:p.max>=0&&p.min>=0?p.max-p.min:p.min-p.max,_=g.length;if(v||void 0===v&&void 0!==b)for(i=0;i<_&&(a=g[i]).index!==t;++i)a.stack===b&&(r=void 0===(u=h._parseValue(f[a.index].data[e])).start?u.end:u.min>=0&&u.max>=0?u.max:u.min,(p.min<0&&r<0||p.max>=0&&r>0)&&(x+=r));return o=h.getPixelForValue(x),l=(s=h.getPixelForValue(x+y))-o,void 0!==m&&Math.abs(l)<m&&(l=m,s=y>=0&&!c||y<0&&c?o-m:o+m),{size:l,base:o,head:s,center:s+l/2}},calculateBarIndexPixels:function(t,e,n,i){var a="flex"===i.barThickness?function(t,e,n){var i,a=e.pixels,r=a[t],o=t>0?a[t-1]:null,s=t<a.length-1?a[t+1]:null,l=n.categoryPercentage;return null===o&&(o=r-(null===s?e.end-e.start:s-r)),null===s&&(s=r+r-o),i=r-(r-Math.min(o,s))/2*l,{chunk:Math.abs(s-o)/2*l/e.stackCount,ratio:n.barPercentage,start:i}}(e,n,i):At(e,n,i),r=this.getStackIndex(t,this.getMeta().stack),o=a.start+a.chunk*r+a.chunk/2,s=Math.min(Pt(i.maxBarThickness,1/0),a.chunk*a.ratio);return{base:o-s/2,head:o+s/2,center:o,size:s}},draw:function(){var t=this.chart,e=this._getValueScale(),n=this.getMeta().data,i=this.getDataset(),a=n.length,r=0;for(V.canvas.clipArea(t.ctx,t.chartArea);r<a;++r){var o=e._parseValue(i.data[r]);isNaN(o.min)||isNaN(o.max)||n[r].draw()}V.canvas.unclipArea(t.ctx)},_resolveDataElementOptions:function(){var t=this,e=V.extend({},nt.prototype._resolveDataElementOptions.apply(t,arguments)),n=t._getIndexScale().options,i=t._getValueScale().options;return e.barPercentage=Pt(n.barPercentage,e.barPercentage),e.barThickness=Pt(n.barThickness,e.barThickness),e.categoryPercentage=Pt(n.categoryPercentage,e.categoryPercentage),e.maxBarThickness=Pt(n.maxBarThickness,e.maxBarThickness),e.minBarLength=Pt(i.minBarLength,e.minBarLength),e}}),Tt=V.valueOrDefault,It=V.options.resolve;z._set("bubble",{hover:{mode:"single"},scales:{xAxes:[{type:"linear",position:"bottom",id:"x-axis-0"}],yAxes:[{type:"linear",position:"left",id:"y-axis-0"}]},tooltips:{callbacks:{title:function(){return""},label:function(t,e){var n=e.datasets[t.datasetIndex].label||"",i=e.datasets[t.datasetIndex].data[t.index];return n+": ("+t.xLabel+", "+t.yLabel+", "+i.r+")"}}}});var Ft=nt.extend({dataElementType:_t.Point,_dataElementOptions:["backgroundColor","borderColor","borderWidth","hoverBackgroundColor","hoverBorderColor","hoverBorderWidth","hoverRadius","hitRadius","pointStyle","rotation"],update:function(t){var e=this,n=e.getMeta().data;V.each(n,(function(n,i){e.updateElement(n,i,t)}))},updateElement:function(t,e,n){var i=this,a=i.getMeta(),r=t.custom||{},o=i.getScaleForId(a.xAxisID),s=i.getScaleForId(a.yAxisID),l=i._resolveDataElementOptions(t,e),u=i.getDataset().data[e],d=i.index,h=n?o.getPixelForDecimal(.5):o.getPixelForValue("object"==typeof u?u:NaN,e,d),c=n?s.getBasePixel():s.getPixelForValue(u,e,d);t._xScale=o,t._yScale=s,t._options=l,t._datasetIndex=d,t._index=e,t._model={backgroundColor:l.backgroundColor,borderColor:l.borderColor,borderWidth:l.borderWidth,hitRadius:l.hitRadius,pointStyle:l.pointStyle,rotation:l.rotation,radius:n?0:l.radius,skip:r.skip||isNaN(h)||isNaN(c),x:h,y:c},t.pivot()},setHoverStyle:function(t){var e=t._model,n=t._options,i=V.getHoverColor;t.$previousStyle={backgroundColor:e.backgroundColor,borderColor:e.borderColor,borderWidth:e.borderWidth,radius:e.radius},e.backgroundColor=Tt(n.hoverBackgroundColor,i(n.backgroundColor)),e.borderColor=Tt(n.hoverBorderColor,i(n.borderColor)),e.borderWidth=Tt(n.hoverBorderWidth,n.borderWidth),e.radius=n.radius+n.hoverRadius},_resolveDataElementOptions:function(t,e){var n=this,i=n.chart,a=n.getDataset(),r=t.custom||{},o=a.data[e]||{},s=nt.prototype._resolveDataElementOptions.apply(n,arguments),l={chart:i,dataIndex:e,dataset:a,datasetIndex:n.index};return n._cachedDataOpts===s&&(s=V.extend({},s)),s.radius=It([r.radius,o.r,n._config.radius,i.options.elements.point.radius],l,e),s}}),Lt=V.valueOrDefault,Ot=Math.PI,Rt=2*Ot,zt=Ot/2;z._set("doughnut",{animation:{animateRotate:!0,animateScale:!1},hover:{mode:"single"},legendCallback:function(t){var e,n,i,a=document.createElement("ul"),r=t.data,o=r.datasets,s=r.labels;if(a.setAttribute("class",t.id+"-legend"),o.length)for(e=0,n=o[0].data.length;e<n;++e)(i=a.appendChild(document.createElement("li"))).appendChild(document.createElement("span")).style.backgroundColor=o[0].backgroundColor[e],s[e]&&i.appendChild(document.createTextNode(s[e]));return a.outerHTML},legend:{labels:{generateLabels:function(t){var e=t.data;return e.labels.length&&e.datasets.length?e.labels.map((function(n,i){var a=t.getDatasetMeta(0),r=a.controller.getStyle(i);return{text:n,fillStyle:r.backgroundColor,strokeStyle:r.borderColor,lineWidth:r.borderWidth,hidden:isNaN(e.datasets[0].data[i])||a.data[i].hidden,index:i}})):[]}},onClick:function(t,e){var n,i,a,r=e.index,o=this.chart;for(n=0,i=(o.data.datasets||[]).length;n<i;++n)(a=o.getDatasetMeta(n)).data[r]&&(a.data[r].hidden=!a.data[r].hidden);o.update()}},cutoutPercentage:50,rotation:-zt,circumference:Rt,tooltips:{callbacks:{title:function(){return""},label:function(t,e){var n=e.labels[t.index],i=": "+e.datasets[t.datasetIndex].data[t.index];return V.isArray(n)?(n=n.slice())[0]+=i:n+=i,n}}}});var Nt=nt.extend({dataElementType:_t.Arc,linkScales:V.noop,_dataElementOptions:["backgroundColor","borderColor","borderWidth","borderAlign","hoverBackgroundColor","hoverBorderColor","hoverBorderWidth"],getRingIndex:function(t){for(var e=0,n=0;n<t;++n)this.chart.isDatasetVisible(n)&&++e;return e},update:function(t){var e,n,i,a,r=this,o=r.chart,s=o.chartArea,l=o.options,u=1,d=1,h=0,c=0,f=r.getMeta(),g=f.data,p=l.cutoutPercentage/100||0,m=l.circumference,v=r._getRingWeight(r.index);if(m<Rt){var b=l.rotation%Rt,x=(b+=b>=Ot?-Rt:b<-Ot?Rt:0)+m,y=Math.cos(b),_=Math.sin(b),k=Math.cos(x),w=Math.sin(x),M=b<=0&&x>=0||x>=Rt,S=b<=zt&&x>=zt||x>=Rt+zt,C=b<=-zt&&x>=-zt||x>=Ot+zt,P=b===-Ot||x>=Ot?-1:Math.min(y,y*p,k,k*p),A=C?-1:Math.min(_,_*p,w,w*p),D=M?1:Math.max(y,y*p,k,k*p),T=S?1:Math.max(_,_*p,w,w*p);u=(D-P)/2,d=(T-A)/2,h=-(D+P)/2,c=-(T+A)/2}for(i=0,a=g.length;i<a;++i)g[i]._options=r._resolveDataElementOptions(g[i],i);for(o.borderWidth=r.getMaxBorderWidth(),e=(s.right-s.left-o.borderWidth)/u,n=(s.bottom-s.top-o.borderWidth)/d,o.outerRadius=Math.max(Math.min(e,n)/2,0),o.innerRadius=Math.max(o.outerRadius*p,0),o.radiusLength=(o.outerRadius-o.innerRadius)/(r._getVisibleDatasetWeightTotal()||1),o.offsetX=h*o.outerRadius,o.offsetY=c*o.outerRadius,f.total=r.calculateTotal(),r.outerRadius=o.outerRadius-o.radiusLength*r._getRingWeightOffset(r.index),r.innerRadius=Math.max(r.outerRadius-o.radiusLength*v,0),i=0,a=g.length;i<a;++i)r.updateElement(g[i],i,t)},updateElement:function(t,e,n){var i=this,a=i.chart,r=a.chartArea,o=a.options,s=o.animation,l=(r.left+r.right)/2,u=(r.top+r.bottom)/2,d=o.rotation,h=o.rotation,c=i.getDataset(),f=n&&s.animateRotate?0:t.hidden?0:i.calculateCircumference(c.data[e])*(o.circumference/Rt),g=n&&s.animateScale?0:i.innerRadius,p=n&&s.animateScale?0:i.outerRadius,m=t._options||{};V.extend(t,{_datasetIndex:i.index,_index:e,_model:{backgroundColor:m.backgroundColor,borderColor:m.borderColor,borderWidth:m.borderWidth,borderAlign:m.borderAlign,x:l+a.offsetX,y:u+a.offsetY,startAngle:d,endAngle:h,circumference:f,outerRadius:p,innerRadius:g,label:V.valueAtIndexOrDefault(c.label,e,a.data.labels[e])}});var v=t._model;n&&s.animateRotate||(v.startAngle=0===e?o.rotation:i.getMeta().data[e-1]._model.endAngle,v.endAngle=v.startAngle+v.circumference),t.pivot()},calculateTotal:function(){var t,e=this.getDataset(),n=this.getMeta(),i=0;return V.each(n.data,(function(n,a){t=e.data[a],isNaN(t)||n.hidden||(i+=Math.abs(t))})),i},calculateCircumference:function(t){var e=this.getMeta().total;return e>0&&!isNaN(t)?Rt*(Math.abs(t)/e):0},getMaxBorderWidth:function(t){var e,n,i,a,r,o,s,l,u=0,d=this.chart;if(!t)for(e=0,n=d.data.datasets.length;e<n;++e)if(d.isDatasetVisible(e)){t=(i=d.getDatasetMeta(e)).data,e!==this.index&&(r=i.controller);break}if(!t)return 0;for(e=0,n=t.length;e<n;++e)a=t[e],r?(r._configure(),o=r._resolveDataElementOptions(a,e)):o=a._options,"inner"!==o.borderAlign&&(s=o.borderWidth,u=(l=o.hoverBorderWidth)>(u=s>u?s:u)?l:u);return u},setHoverStyle:function(t){var e=t._model,n=t._options,i=V.getHoverColor;t.$previousStyle={backgroundColor:e.backgroundColor,borderColor:e.borderColor,borderWidth:e.borderWidth},e.backgroundColor=Lt(n.hoverBackgroundColor,i(n.backgroundColor)),e.borderColor=Lt(n.hoverBorderColor,i(n.borderColor)),e.borderWidth=Lt(n.hoverBorderWidth,n.borderWidth)},_getRingWeightOffset:function(t){for(var e=0,n=0;n<t;++n)this.chart.isDatasetVisible(n)&&(e+=this._getRingWeight(n));return e},_getRingWeight:function(t){return Math.max(Lt(this.chart.data.datasets[t].weight,1),0)},_getVisibleDatasetWeightTotal:function(){return this._getRingWeightOffset(this.chart.data.datasets.length)}});z._set("horizontalBar",{hover:{mode:"index",axis:"y"},scales:{xAxes:[{type:"linear",position:"bottom"}],yAxes:[{type:"category",position:"left",offset:!0,gridLines:{offsetGridLines:!0}}]},elements:{rectangle:{borderSkipped:"left"}},tooltips:{mode:"index",axis:"y"}}),z._set("global",{datasets:{horizontalBar:{categoryPercentage:.8,barPercentage:.9}}});var Bt=Dt.extend({_getValueScaleId:function(){return this.getMeta().xAxisID},_getIndexScaleId:function(){return this.getMeta().yAxisID}}),Et=V.valueOrDefault,Wt=V.options.resolve,Vt=V.canvas._isPointInArea;function Ht(t,e){var n=t&&t.options.ticks||{},i=n.reverse,a=void 0===n.min?e:0,r=void 0===n.max?e:0;return{start:i?r:a,end:i?a:r}}function jt(t,e,n){var i=n/2,a=Ht(t,i),r=Ht(e,i);return{top:r.end,right:a.end,bottom:r.start,left:a.start}}function qt(t){var e,n,i,a;return V.isObject(t)?(e=t.top,n=t.right,i=t.bottom,a=t.left):e=n=i=a=t,{top:e,right:n,bottom:i,left:a}}z._set("line",{showLines:!0,spanGaps:!1,hover:{mode:"label"},scales:{xAxes:[{type:"category",id:"x-axis-0"}],yAxes:[{type:"linear",id:"y-axis-0"}]}});var Ut=nt.extend({datasetElementType:_t.Line,dataElementType:_t.Point,_datasetElementOptions:["backgroundColor","borderCapStyle","borderColor","borderDash","borderDashOffset","borderJoinStyle","borderWidth","cubicInterpolationMode","fill"],_dataElementOptions:{backgroundColor:"pointBackgroundColor",borderColor:"pointBorderColor",borderWidth:"pointBorderWidth",hitRadius:"pointHitRadius",hoverBackgroundColor:"pointHoverBackgroundColor",hoverBorderColor:"pointHoverBorderColor",hoverBorderWidth:"pointHoverBorderWidth",hoverRadius:"pointHoverRadius",pointStyle:"pointStyle",radius:"pointRadius",rotation:"pointRotation"},update:function(t){var e,n,i=this,a=i.getMeta(),r=a.dataset,o=a.data||[],s=i.chart.options,l=i._config,u=i._showLine=Et(l.showLine,s.showLines);for(i._xScale=i.getScaleForId(a.xAxisID),i._yScale=i.getScaleForId(a.yAxisID),u&&(void 0!==l.tension&&void 0===l.lineTension&&(l.lineTension=l.tension),r._scale=i._yScale,r._datasetIndex=i.index,r._children=o,r._model=i._resolveDatasetElementOptions(r),r.pivot()),e=0,n=o.length;e<n;++e)i.updateElement(o[e],e,t);for(u&&0!==r._model.tension&&i.updateBezierControlPoints(),e=0,n=o.length;e<n;++e)o[e].pivot()},updateElement:function(t,e,n){var i,a,r=this,o=r.getMeta(),s=t.custom||{},l=r.getDataset(),u=r.index,d=l.data[e],h=r._xScale,c=r._yScale,f=o.dataset._model,g=r._resolveDataElementOptions(t,e);i=h.getPixelForValue("object"==typeof d?d:NaN,e,u),a=n?c.getBasePixel():r.calculatePointY(d,e,u),t._xScale=h,t._yScale=c,t._options=g,t._datasetIndex=u,t._index=e,t._model={x:i,y:a,skip:s.skip||isNaN(i)||isNaN(a),radius:g.radius,pointStyle:g.pointStyle,rotation:g.rotation,backgroundColor:g.backgroundColor,borderColor:g.borderColor,borderWidth:g.borderWidth,tension:Et(s.tension,f?f.tension:0),steppedLine:!!f&&f.steppedLine,hitRadius:g.hitRadius}},_resolveDatasetElementOptions:function(t){var e=this,n=e._config,i=t.custom||{},a=e.chart.options,r=a.elements.line,o=nt.prototype._resolveDatasetElementOptions.apply(e,arguments);return o.spanGaps=Et(n.spanGaps,a.spanGaps),o.tension=Et(n.lineTension,r.tension),o.steppedLine=Wt([i.steppedLine,n.steppedLine,r.stepped]),o.clip=qt(Et(n.clip,jt(e._xScale,e._yScale,o.borderWidth))),o},calculatePointY:function(t,e,n){var i,a,r,o,s,l,u,d=this.chart,h=this._yScale,c=0,f=0;if(h.options.stacked){for(s=+h.getRightValue(t),u=(l=d._getSortedVisibleDatasetMetas()).length,i=0;i<u&&(r=l[i]).index!==n;++i)a=d.data.datasets[r.index],"line"===r.type&&r.yAxisID===h.id&&((o=+h.getRightValue(a.data[e]))<0?f+=o||0:c+=o||0);return s<0?h.getPixelForValue(f+s):h.getPixelForValue(c+s)}return h.getPixelForValue(t)},updateBezierControlPoints:function(){var t,e,n,i,a=this.chart,r=this.getMeta(),o=r.dataset._model,s=a.chartArea,l=r.data||[];function u(t,e,n){return Math.max(Math.min(t,n),e)}if(o.spanGaps&&(l=l.filter((function(t){return!t._model.skip}))),"monotone"===o.cubicInterpolationMode)V.splineCurveMonotone(l);else for(t=0,e=l.length;t<e;++t)n=l[t]._model,i=V.splineCurve(V.previousItem(l,t)._model,n,V.nextItem(l,t)._model,o.tension),n.controlPointPreviousX=i.previous.x,n.controlPointPreviousY=i.previous.y,n.controlPointNextX=i.next.x,n.controlPointNextY=i.next.y;if(a.options.elements.line.capBezierPoints)for(t=0,e=l.length;t<e;++t)n=l[t]._model,Vt(n,s)&&(t>0&&Vt(l[t-1]._model,s)&&(n.controlPointPreviousX=u(n.controlPointPreviousX,s.left,s.right),n.controlPointPreviousY=u(n.controlPointPreviousY,s.top,s.bottom)),t<l.length-1&&Vt(l[t+1]._model,s)&&(n.controlPointNextX=u(n.controlPointNextX,s.left,s.right),n.controlPointNextY=u(n.controlPointNextY,s.top,s.bottom)))},draw:function(){var t,e=this.chart,n=this.getMeta(),i=n.data||[],a=e.chartArea,r=e.canvas,o=0,s=i.length;for(this._showLine&&(t=n.dataset._model.clip,V.canvas.clipArea(e.ctx,{left:!1===t.left?0:a.left-t.left,right:!1===t.right?r.width:a.right+t.right,top:!1===t.top?0:a.top-t.top,bottom:!1===t.bottom?r.height:a.bottom+t.bottom}),n.dataset.draw(),V.canvas.unclipArea(e.ctx));o<s;++o)i[o].draw(a)},setHoverStyle:function(t){var e=t._model,n=t._options,i=V.getHoverColor;t.$previousStyle={backgroundColor:e.backgroundColor,borderColor:e.borderColor,borderWidth:e.borderWidth,radius:e.radius},e.backgroundColor=Et(n.hoverBackgroundColor,i(n.backgroundColor)),e.borderColor=Et(n.hoverBorderColor,i(n.borderColor)),e.borderWidth=Et(n.hoverBorderWidth,n.borderWidth),e.radius=Et(n.hoverRadius,n.radius)}}),Yt=V.options.resolve;z._set("polarArea",{scale:{type:"radialLinear",angleLines:{display:!1},gridLines:{circular:!0},pointLabels:{display:!1},ticks:{beginAtZero:!0}},animation:{animateRotate:!0,animateScale:!0},startAngle:-.5*Math.PI,legendCallback:function(t){var e,n,i,a=document.createElement("ul"),r=t.data,o=r.datasets,s=r.labels;if(a.setAttribute("class",t.id+"-legend"),o.length)for(e=0,n=o[0].data.length;e<n;++e)(i=a.appendChild(document.createElement("li"))).appendChild(document.createElement("span")).style.backgroundColor=o[0].backgroundColor[e],s[e]&&i.appendChild(document.createTextNode(s[e]));return a.outerHTML},legend:{labels:{generateLabels:function(t){var e=t.data;return e.labels.length&&e.datasets.length?e.labels.map((function(n,i){var a=t.getDatasetMeta(0),r=a.controller.getStyle(i);return{text:n,fillStyle:r.backgroundColor,strokeStyle:r.borderColor,lineWidth:r.borderWidth,hidden:isNaN(e.datasets[0].data[i])||a.data[i].hidden,index:i}})):[]}},onClick:function(t,e){var n,i,a,r=e.index,o=this.chart;for(n=0,i=(o.data.datasets||[]).length;n<i;++n)(a=o.getDatasetMeta(n)).data[r].hidden=!a.data[r].hidden;o.update()}},tooltips:{callbacks:{title:function(){return""},label:function(t,e){return e.labels[t.index]+": "+t.yLabel}}}});var Gt=nt.extend({dataElementType:_t.Arc,linkScales:V.noop,_dataElementOptions:["backgroundColor","borderColor","borderWidth","borderAlign","hoverBackgroundColor","hoverBorderColor","hoverBorderWidth"],_getIndexScaleId:function(){return this.chart.scale.id},_getValueScaleId:function(){return this.chart.scale.id},update:function(t){var e,n,i,a=this,r=a.getDataset(),o=a.getMeta(),s=a.chart.options.startAngle||0,l=a._starts=[],u=a._angles=[],d=o.data;for(a._updateRadius(),o.count=a.countVisibleElements(),e=0,n=r.data.length;e<n;e++)l[e]=s,i=a._computeAngle(e),u[e]=i,s+=i;for(e=0,n=d.length;e<n;++e)d[e]._options=a._resolveDataElementOptions(d[e],e),a.updateElement(d[e],e,t)},_updateRadius:function(){var t=this,e=t.chart,n=e.chartArea,i=e.options,a=Math.min(n.right-n.left,n.bottom-n.top);e.outerRadius=Math.max(a/2,0),e.innerRadius=Math.max(i.cutoutPercentage?e.outerRadius/100*i.cutoutPercentage:1,0),e.radiusLength=(e.outerRadius-e.innerRadius)/e.getVisibleDatasetCount(),t.outerRadius=e.outerRadius-e.radiusLength*t.index,t.innerRadius=t.outerRadius-e.radiusLength},updateElement:function(t,e,n){var i=this,a=i.chart,r=i.getDataset(),o=a.options,s=o.animation,l=a.scale,u=a.data.labels,d=l.xCenter,h=l.yCenter,c=o.startAngle,f=t.hidden?0:l.getDistanceFromCenterForValue(r.data[e]),g=i._starts[e],p=g+(t.hidden?0:i._angles[e]),m=s.animateScale?0:l.getDistanceFromCenterForValue(r.data[e]),v=t._options||{};V.extend(t,{_datasetIndex:i.index,_index:e,_scale:l,_model:{backgroundColor:v.backgroundColor,borderColor:v.borderColor,borderWidth:v.borderWidth,borderAlign:v.borderAlign,x:d,y:h,innerRadius:0,outerRadius:n?m:f,startAngle:n&&s.animateRotate?c:g,endAngle:n&&s.animateRotate?c:p,label:V.valueAtIndexOrDefault(u,e,u[e])}}),t.pivot()},countVisibleElements:function(){var t=this.getDataset(),e=this.getMeta(),n=0;return V.each(e.data,(function(e,i){isNaN(t.data[i])||e.hidden||n++})),n},setHoverStyle:function(t){var e=t._model,n=t._options,i=V.getHoverColor,a=V.valueOrDefault;t.$previousStyle={backgroundColor:e.backgroundColor,borderColor:e.borderColor,borderWidth:e.borderWidth},e.backgroundColor=a(n.hoverBackgroundColor,i(n.backgroundColor)),e.borderColor=a(n.hoverBorderColor,i(n.borderColor)),e.borderWidth=a(n.hoverBorderWidth,n.borderWidth)},_computeAngle:function(t){var e=this,n=this.getMeta().count,i=e.getDataset(),a=e.getMeta();if(isNaN(i.data[t])||a.data[t].hidden)return 0;var r={chart:e.chart,dataIndex:t,dataset:i,datasetIndex:e.index};return Yt([e.chart.options.elements.arc.angle,2*Math.PI/n],r,t)}});z._set("pie",V.clone(z.doughnut)),z._set("pie",{cutoutPercentage:0});var Xt=Nt,Kt=V.valueOrDefault;z._set("radar",{spanGaps:!1,scale:{type:"radialLinear"},elements:{line:{fill:"start",tension:0}}});var Zt=nt.extend({datasetElementType:_t.Line,dataElementType:_t.Point,linkScales:V.noop,_datasetElementOptions:["backgroundColor","borderWidth","borderColor","borderCapStyle","borderDash","borderDashOffset","borderJoinStyle","fill"],_dataElementOptions:{backgroundColor:"pointBackgroundColor",borderColor:"pointBorderColor",borderWidth:"pointBorderWidth",hitRadius:"pointHitRadius",hoverBackgroundColor:"pointHoverBackgroundColor",hoverBorderColor:"pointHoverBorderColor",hoverBorderWidth:"pointHoverBorderWidth",hoverRadius:"pointHoverRadius",pointStyle:"pointStyle",radius:"pointRadius",rotation:"pointRotation"},_getIndexScaleId:function(){return this.chart.scale.id},_getValueScaleId:function(){return this.chart.scale.id},update:function(t){var e,n,i=this,a=i.getMeta(),r=a.dataset,o=a.data||[],s=i.chart.scale,l=i._config;for(void 0!==l.tension&&void 0===l.lineTension&&(l.lineTension=l.tension),r._scale=s,r._datasetIndex=i.index,r._children=o,r._loop=!0,r._model=i._resolveDatasetElementOptions(r),r.pivot(),e=0,n=o.length;e<n;++e)i.updateElement(o[e],e,t);for(i.updateBezierControlPoints(),e=0,n=o.length;e<n;++e)o[e].pivot()},updateElement:function(t,e,n){var i=this,a=t.custom||{},r=i.getDataset(),o=i.chart.scale,s=o.getPointPositionForValue(e,r.data[e]),l=i._resolveDataElementOptions(t,e),u=i.getMeta().dataset._model,d=n?o.xCenter:s.x,h=n?o.yCenter:s.y;t._scale=o,t._options=l,t._datasetIndex=i.index,t._index=e,t._model={x:d,y:h,skip:a.skip||isNaN(d)||isNaN(h),radius:l.radius,pointStyle:l.pointStyle,rotation:l.rotation,backgroundColor:l.backgroundColor,borderColor:l.borderColor,borderWidth:l.borderWidth,tension:Kt(a.tension,u?u.tension:0),hitRadius:l.hitRadius}},_resolveDatasetElementOptions:function(){var t=this,e=t._config,n=t.chart.options,i=nt.prototype._resolveDatasetElementOptions.apply(t,arguments);return i.spanGaps=Kt(e.spanGaps,n.spanGaps),i.tension=Kt(e.lineTension,n.elements.line.tension),i},updateBezierControlPoints:function(){var t,e,n,i,a=this.getMeta(),r=this.chart.chartArea,o=a.data||[];function s(t,e,n){return Math.max(Math.min(t,n),e)}for(a.dataset._model.spanGaps&&(o=o.filter((function(t){return!t._model.skip}))),t=0,e=o.length;t<e;++t)n=o[t]._model,i=V.splineCurve(V.previousItem(o,t,!0)._model,n,V.nextItem(o,t,!0)._model,n.tension),n.controlPointPreviousX=s(i.previous.x,r.left,r.right),n.controlPointPreviousY=s(i.previous.y,r.top,r.bottom),n.controlPointNextX=s(i.next.x,r.left,r.right),n.controlPointNextY=s(i.next.y,r.top,r.bottom)},setHoverStyle:function(t){var e=t._model,n=t._options,i=V.getHoverColor;t.$previousStyle={backgroundColor:e.backgroundColor,borderColor:e.borderColor,borderWidth:e.borderWidth,radius:e.radius},e.backgroundColor=Kt(n.hoverBackgroundColor,i(n.backgroundColor)),e.borderColor=Kt(n.hoverBorderColor,i(n.borderColor)),e.borderWidth=Kt(n.hoverBorderWidth,n.borderWidth),e.radius=Kt(n.hoverRadius,n.radius)}});z._set("scatter",{hover:{mode:"single"},scales:{xAxes:[{id:"x-axis-1",type:"linear",position:"bottom"}],yAxes:[{id:"y-axis-1",type:"linear",position:"left"}]},tooltips:{callbacks:{title:function(){return""},label:function(t){return"("+t.xLabel+", "+t.yLabel+")"}}}}),z._set("global",{datasets:{scatter:{showLine:!1}}});var $t={bar:Dt,bubble:Ft,doughnut:Nt,horizontalBar:Bt,line:Ut,polarArea:Gt,pie:Xt,radar:Zt,scatter:Ut};function Jt(t,e){return t.native?{x:t.x,y:t.y}:V.getRelativePosition(t,e)}function Qt(t,e){var n,i,a,r,o,s,l=t._getSortedVisibleDatasetMetas();for(i=0,r=l.length;i<r;++i)for(a=0,o=(n=l[i].data).length;a<o;++a)(s=n[a])._view.skip||e(s)}function te(t,e){var n=[];return Qt(t,(function(t){t.inRange(e.x,e.y)&&n.push(t)})),n}function ee(t,e,n,i){var a=Number.POSITIVE_INFINITY,r=[];return Qt(t,(function(t){if(!n||t.inRange(e.x,e.y)){var o=t.getCenterPoint(),s=i(e,o);s<a?(r=[t],a=s):s===a&&r.push(t)}})),r}function ne(t){var e=-1!==t.indexOf("x"),n=-1!==t.indexOf("y");return function(t,i){var a=e?Math.abs(t.x-i.x):0,r=n?Math.abs(t.y-i.y):0;return Math.sqrt(Math.pow(a,2)+Math.pow(r,2))}}function ie(t,e,n){var i=Jt(e,t);n.axis=n.axis||"x";var a=ne(n.axis),r=n.intersect?te(t,i):ee(t,i,!1,a),o=[];return r.length?(t._getSortedVisibleDatasetMetas().forEach((function(t){var e=t.data[r[0]._index];e&&!e._view.skip&&o.push(e)})),o):[]}var ae={modes:{single:function(t,e){var n=Jt(e,t),i=[];return Qt(t,(function(t){if(t.inRange(n.x,n.y))return i.push(t),i})),i.slice(0,1)},label:ie,index:ie,dataset:function(t,e,n){var i=Jt(e,t);n.axis=n.axis||"xy";var a=ne(n.axis),r=n.intersect?te(t,i):ee(t,i,!1,a);return r.length>0&&(r=t.getDatasetMeta(r[0]._datasetIndex).data),r},"x-axis":function(t,e){return ie(t,e,{intersect:!1})},point:function(t,e){return te(t,Jt(e,t))},nearest:function(t,e,n){var i=Jt(e,t);n.axis=n.axis||"xy";var a=ne(n.axis);return ee(t,i,n.intersect,a)},x:function(t,e,n){var i=Jt(e,t),a=[],r=!1;return Qt(t,(function(t){t.inXRange(i.x)&&a.push(t),t.inRange(i.x,i.y)&&(r=!0)})),n.intersect&&!r&&(a=[]),a},y:function(t,e,n){var i=Jt(e,t),a=[],r=!1;return Qt(t,(function(t){t.inYRange(i.y)&&a.push(t),t.inRange(i.x,i.y)&&(r=!0)})),n.intersect&&!r&&(a=[]),a}}},re=V.extend;function oe(t,e){return V.where(t,(function(t){return t.pos===e}))}function se(t,e){return t.sort((function(t,n){var i=e?n:t,a=e?t:n;return i.weight===a.weight?i.index-a.index:i.weight-a.weight}))}function le(t,e,n,i){return Math.max(t[n],e[n])+Math.max(t[i],e[i])}function ue(t,e,n){var i,a,r=n.box,o=t.maxPadding;if(n.size&&(t[n.pos]-=n.size),n.size=n.horizontal?r.height:r.width,t[n.pos]+=n.size,r.getPadding){var s=r.getPadding();o.top=Math.max(o.top,s.top),o.left=Math.max(o.left,s.left),o.bottom=Math.max(o.bottom,s.bottom),o.right=Math.max(o.right,s.right)}if(i=e.outerWidth-le(o,t,"left","right"),a=e.outerHeight-le(o,t,"top","bottom"),i!==t.w||a!==t.h)return t.w=i,t.h=a,n.horizontal?i!==t.w:a!==t.h}function de(t,e){var n=e.maxPadding;function i(t){var i={left:0,top:0,right:0,bottom:0};return t.forEach((function(t){i[t]=Math.max(e[t],n[t])})),i}return i(t?["left","right"]:["top","bottom"])}function he(t,e,n){var i,a,r,o,s,l,u=[];for(i=0,a=t.length;i<a;++i)(o=(r=t[i]).box).update(r.width||e.w,r.height||e.h,de(r.horizontal,e)),ue(e,n,r)&&(l=!0,u.length&&(s=!0)),o.fullWidth||u.push(r);return s&&he(u,e,n)||l}function ce(t,e,n){var i,a,r,o,s=n.padding,l=e.x,u=e.y;for(i=0,a=t.length;i<a;++i)o=(r=t[i]).box,r.horizontal?(o.left=o.fullWidth?s.left:e.left,o.right=o.fullWidth?n.outerWidth-s.right:e.left+e.w,o.top=u,o.bottom=u+o.height,o.width=o.right-o.left,u=o.bottom):(o.left=l,o.right=l+o.width,o.top=e.top,o.bottom=e.top+e.h,o.height=o.bottom-o.top,l=o.right);e.x=l,e.y=u}z._set("global",{layout:{padding:{top:0,right:0,bottom:0,left:0}}});var fe,ge={defaults:{},addBox:function(t,e){t.boxes||(t.boxes=[]),e.fullWidth=e.fullWidth||!1,e.position=e.position||"top",e.weight=e.weight||0,e._layers=e._layers||function(){return[{z:0,draw:function(){e.draw.apply(e,arguments)}}]},t.boxes.push(e)},removeBox:function(t,e){var n=t.boxes?t.boxes.indexOf(e):-1;-1!==n&&t.boxes.splice(n,1)},configure:function(t,e,n){for(var i,a=["fullWidth","position","weight"],r=a.length,o=0;o<r;++o)i=a[o],n.hasOwnProperty(i)&&(e[i]=n[i])},update:function(t,e,n){if(t){var i=t.options.layout||{},a=V.options.toPadding(i.padding),r=e-a.width,o=n-a.height,s=function(t){var e=function(t){var e,n,i,a=[];for(e=0,n=(t||[]).length;e<n;++e)i=t[e],a.push({index:e,box:i,pos:i.position,horizontal:i.isHorizontal(),weight:i.weight});return a}(t),n=se(oe(e,"left"),!0),i=se(oe(e,"right")),a=se(oe(e,"top"),!0),r=se(oe(e,"bottom"));return{leftAndTop:n.concat(a),rightAndBottom:i.concat(r),chartArea:oe(e,"chartArea"),vertical:n.concat(i),horizontal:a.concat(r)}}(t.boxes),l=s.vertical,u=s.horizontal,d=Object.freeze({outerWidth:e,outerHeight:n,padding:a,availableWidth:r,vBoxMaxWidth:r/2/l.length,hBoxMaxHeight:o/2}),h=re({maxPadding:re({},a),w:r,h:o,x:a.left,y:a.top},a);!function(t,e){var n,i,a;for(n=0,i=t.length;n<i;++n)(a=t[n]).width=a.horizontal?a.box.fullWidth&&e.availableWidth:e.vBoxMaxWidth,a.height=a.horizontal&&e.hBoxMaxHeight}(l.concat(u),d),he(l,h,d),he(u,h,d)&&he(l,h,d),function(t){var e=t.maxPadding;function n(n){var i=Math.max(e[n]-t[n],0);return t[n]+=i,i}t.y+=n("top"),t.x+=n("left"),n("right"),n("bottom")}(h),ce(s.leftAndTop,h,d),h.x+=h.w,h.y+=h.h,ce(s.rightAndBottom,h,d),t.chartArea={left:h.left,top:h.top,right:h.left+h.w,bottom:h.top+h.h},V.each(s.chartArea,(function(e){var n=e.box;re(n,t.chartArea),n.update(h.w,h.h)}))}}},pe=(fe=Object.freeze({__proto__:null,default:"@keyframes chartjs-render-animation{from{opacity:.99}to{opacity:1}}.chartjs-render-monitor{animation:chartjs-render-animation 1ms}.chartjs-size-monitor,.chartjs-size-monitor-expand,.chartjs-size-monitor-shrink{position:absolute;direction:ltr;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1}.chartjs-size-monitor-expand>div{position:absolute;width:1000000px;height:1000000px;left:0;top:0}.chartjs-size-monitor-shrink>div{position:absolute;width:200%;height:200%;left:0;top:0}"}))&&fe.default||fe,me="$chartjs",ve="chartjs-size-monitor",be="chartjs-render-monitor",xe="chartjs-render-animation",ye=["animationstart","webkitAnimationStart"],_e={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"};function ke(t,e){var n=V.getStyle(t,e),i=n&&n.match(/^(\d+)(\.\d+)?px$/);return i?Number(i[1]):void 0}var we=!!function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("e",null,e)}catch(t){}return t}()&&{passive:!0};function Me(t,e,n){t.addEventListener(e,n,we)}function Se(t,e,n){t.removeEventListener(e,n,we)}function Ce(t,e,n,i,a){return{type:t,chart:e,native:a||null,x:void 0!==n?n:null,y:void 0!==i?i:null}}function Pe(t){var e=document.createElement("div");return e.className=t||"",e}function Ae(t,e,n){var i,a,r,o,s=t[me]||(t[me]={}),l=s.resizer=function(t){var e=Pe(ve),n=Pe(ve+"-expand"),i=Pe(ve+"-shrink");n.appendChild(Pe()),i.appendChild(Pe()),e.appendChild(n),e.appendChild(i),e._reset=function(){n.scrollLeft=1e6,n.scrollTop=1e6,i.scrollLeft=1e6,i.scrollTop=1e6};var a=function(){e._reset(),t()};return Me(n,"scroll",a.bind(n,"expand")),Me(i,"scroll",a.bind(i,"shrink")),e}((i=function(){if(s.resizer){var i=n.options.maintainAspectRatio&&t.parentNode,a=i?i.clientWidth:0;e(Ce("resize",n)),i&&i.clientWidth<a&&n.canvas&&e(Ce("resize",n))}},r=!1,o=[],function(){o=Array.prototype.slice.call(arguments),a=a||this,r||(r=!0,V.requestAnimFrame.call(window,(function(){r=!1,i.apply(a,o)})))}));!function(t,e){var n=t[me]||(t[me]={}),i=n.renderProxy=function(t){t.animationName===xe&&e()};V.each(ye,(function(e){Me(t,e,i)})),n.reflow=!!t.offsetParent,t.classList.add(be)}(t,(function(){if(s.resizer){var e=t.parentNode;e&&e!==l.parentNode&&e.insertBefore(l,e.firstChild),l._reset()}}))}function De(t){var e=t[me]||{},n=e.resizer;delete e.resizer,function(t){var e=t[me]||{},n=e.renderProxy;n&&(V.each(ye,(function(e){Se(t,e,n)})),delete e.renderProxy),t.classList.remove(be)}(t),n&&n.parentNode&&n.parentNode.removeChild(n)}var Te={disableCSSInjection:!1,_enabled:"undefined"!=typeof window&&"undefined"!=typeof document,_ensureLoaded:function(t){if(!this.disableCSSInjection){var e=t.getRootNode?t.getRootNode():document;!function(t,e){var n=t[me]||(t[me]={});if(!n.containsStyles){n.containsStyles=!0,e="/* Chart.js */\n"+e;var i=document.createElement("style");i.setAttribute("type","text/css"),i.appendChild(document.createTextNode(e)),t.appendChild(i)}}(e.host?e:document.head,pe)}},acquireContext:function(t,e){"string"==typeof t?t=document.getElementById(t):t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas);var n=t&&t.getContext&&t.getContext("2d");return n&&n.canvas===t?(this._ensureLoaded(t),function(t,e){var n=t.style,i=t.getAttribute("height"),a=t.getAttribute("width");if(t[me]={initial:{height:i,width:a,style:{display:n.display,height:n.height,width:n.width}}},n.display=n.display||"block",null===a||""===a){var r=ke(t,"width");void 0!==r&&(t.width=r)}if(null===i||""===i)if(""===t.style.height)t.height=t.width/(e.options.aspectRatio||2);else{var o=ke(t,"height");void 0!==r&&(t.height=o)}}(t,e),n):null},releaseContext:function(t){var e=t.canvas;if(e[me]){var n=e[me].initial;["height","width"].forEach((function(t){var i=n[t];V.isNullOrUndef(i)?e.removeAttribute(t):e.setAttribute(t,i)})),V.each(n.style||{},(function(t,n){e.style[n]=t})),e.width=e.width,delete e[me]}},addEventListener:function(t,e,n){var i=t.canvas;if("resize"!==e){var a=n[me]||(n[me]={});Me(i,e,(a.proxies||(a.proxies={}))[t.id+"_"+e]=function(e){n(function(t,e){var n=_e[t.type]||t.type,i=V.getRelativePosition(t,e);return Ce(n,e,i.x,i.y,t)}(e,t))})}else Ae(i,n,t)},removeEventListener:function(t,e,n){var i=t.canvas;if("resize"!==e){var a=((n[me]||{}).proxies||{})[t.id+"_"+e];a&&Se(i,e,a)}else De(i)}};V.addEvent=Me,V.removeEvent=Se;var Ie=Te._enabled?Te:{acquireContext:function(t){return t&&t.canvas&&(t=t.canvas),t&&t.getContext("2d")||null}},Fe=V.extend({initialize:function(){},acquireContext:function(){},releaseContext:function(){},addEventListener:function(){},removeEventListener:function(){}},Ie);z._set("global",{plugins:{}});var Le={_plugins:[],_cacheId:0,register:function(t){var e=this._plugins;[].concat(t).forEach((function(t){-1===e.indexOf(t)&&e.push(t)})),this._cacheId++},unregister:function(t){var e=this._plugins;[].concat(t).forEach((function(t){var n=e.indexOf(t);-1!==n&&e.splice(n,1)})),this._cacheId++},clear:function(){this._plugins=[],this._cacheId++},count:function(){return this._plugins.length},getAll:function(){return this._plugins},notify:function(t,e,n){var i,a,r,o,s,l=this.descriptors(t),u=l.length;for(i=0;i<u;++i)if("function"==typeof(s=(r=(a=l[i]).plugin)[e])&&((o=[t].concat(n||[])).push(a.options),!1===s.apply(r,o)))return!1;return!0},descriptors:function(t){var e=t.$plugins||(t.$plugins={});if(e.id===this._cacheId)return e.descriptors;var n=[],i=[],a=t&&t.config||{},r=a.options&&a.options.plugins||{};return this._plugins.concat(a.plugins||[]).forEach((function(t){if(-1===n.indexOf(t)){var e=t.id,a=r[e];!1!==a&&(!0===a&&(a=V.clone(z.global.plugins[e])),n.push(t),i.push({plugin:t,options:a||{}}))}})),e.descriptors=i,e.id=this._cacheId,i},_invalidate:function(t){delete t.$plugins}},Oe={constructors:{},defaults:{},registerScaleType:function(t,e,n){this.constructors[t]=e,this.defaults[t]=V.clone(n)},getScaleConstructor:function(t){return this.constructors.hasOwnProperty(t)?this.constructors[t]:void 0},getScaleDefaults:function(t){return this.defaults.hasOwnProperty(t)?V.merge({},[z.scale,this.defaults[t]]):{}},updateScaleDefaults:function(t,e){this.defaults.hasOwnProperty(t)&&(this.defaults[t]=V.extend(this.defaults[t],e))},addScalesToLayout:function(t){V.each(t.scales,(function(e){e.fullWidth=e.options.fullWidth,e.position=e.options.position,e.weight=e.options.weight,ge.addBox(t,e)}))}},Re=V.valueOrDefault,ze=V.rtl.getRtlAdapter;z._set("global",{tooltips:{enabled:!0,custom:null,mode:"nearest",position:"average",intersect:!0,backgroundColor:"rgba(0,0,0,0.8)",titleFontStyle:"bold",titleSpacing:2,titleMarginBottom:6,titleFontColor:"#fff",titleAlign:"left",bodySpacing:2,bodyFontColor:"#fff",bodyAlign:"left",footerFontStyle:"bold",footerSpacing:2,footerMarginTop:6,footerFontColor:"#fff",footerAlign:"left",yPadding:6,xPadding:6,caretPadding:2,caretSize:5,cornerRadius:6,multiKeyBackground:"#fff",displayColors:!0,borderColor:"rgba(0,0,0,0)",borderWidth:0,callbacks:{beforeTitle:V.noop,title:function(t,e){var n="",i=e.labels,a=i?i.length:0;if(t.length>0){var r=t[0];r.label?n=r.label:r.xLabel?n=r.xLabel:a>0&&r.index<a&&(n=i[r.index])}return n},afterTitle:V.noop,beforeBody:V.noop,beforeLabel:V.noop,label:function(t,e){var n=e.datasets[t.datasetIndex].label||"";return n&&(n+=": "),V.isNullOrUndef(t.value)?n+=t.yLabel:n+=t.value,n},labelColor:function(t,e){var n=e.getDatasetMeta(t.datasetIndex).data[t.index]._view;return{borderColor:n.borderColor,backgroundColor:n.backgroundColor}},labelTextColor:function(){return this._options.bodyFontColor},afterLabel:V.noop,afterBody:V.noop,beforeFooter:V.noop,footer:V.noop,afterFooter:V.noop}}});var Ne={average:function(t){if(!t.length)return!1;var e,n,i=0,a=0,r=0;for(e=0,n=t.length;e<n;++e){var o=t[e];if(o&&o.hasValue()){var s=o.tooltipPosition();i+=s.x,a+=s.y,++r}}return{x:i/r,y:a/r}},nearest:function(t,e){var n,i,a,r=e.x,o=e.y,s=Number.POSITIVE_INFINITY;for(n=0,i=t.length;n<i;++n){var l=t[n];if(l&&l.hasValue()){var u=l.getCenterPoint(),d=V.distanceBetweenPoints(e,u);d<s&&(s=d,a=l)}}if(a){var h=a.tooltipPosition();r=h.x,o=h.y}return{x:r,y:o}}};function Be(t,e){return e&&(V.isArray(e)?Array.prototype.push.apply(t,e):t.push(e)),t}function Ee(t){return("string"==typeof t||t instanceof String)&&t.indexOf("\n")>-1?t.split("\n"):t}function We(t){var e=z.global;return{xPadding:t.xPadding,yPadding:t.yPadding,xAlign:t.xAlign,yAlign:t.yAlign,rtl:t.rtl,textDirection:t.textDirection,bodyFontColor:t.bodyFontColor,_bodyFontFamily:Re(t.bodyFontFamily,e.defaultFontFamily),_bodyFontStyle:Re(t.bodyFontStyle,e.defaultFontStyle),_bodyAlign:t.bodyAlign,bodyFontSize:Re(t.bodyFontSize,e.defaultFontSize),bodySpacing:t.bodySpacing,titleFontColor:t.titleFontColor,_titleFontFamily:Re(t.titleFontFamily,e.defaultFontFamily),_titleFontStyle:Re(t.titleFontStyle,e.defaultFontStyle),titleFontSize:Re(t.titleFontSize,e.defaultFontSize),_titleAlign:t.titleAlign,titleSpacing:t.titleSpacing,titleMarginBottom:t.titleMarginBottom,footerFontColor:t.footerFontColor,_footerFontFamily:Re(t.footerFontFamily,e.defaultFontFamily),_footerFontStyle:Re(t.footerFontStyle,e.defaultFontStyle),footerFontSize:Re(t.footerFontSize,e.defaultFontSize),_footerAlign:t.footerAlign,footerSpacing:t.footerSpacing,footerMarginTop:t.footerMarginTop,caretSize:t.caretSize,cornerRadius:t.cornerRadius,backgroundColor:t.backgroundColor,opacity:0,legendColorBackground:t.multiKeyBackground,displayColors:t.displayColors,borderColor:t.borderColor,borderWidth:t.borderWidth}}function Ve(t,e){return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-t.xPadding:t.x+t.xPadding}function He(t){return Be([],Ee(t))}var je=X.extend({initialize:function(){this._model=We(this._options),this._lastActive=[]},getTitle:function(){var t=this,e=t._options,n=e.callbacks,i=n.beforeTitle.apply(t,arguments),a=n.title.apply(t,arguments),r=n.afterTitle.apply(t,arguments),o=[];return o=Be(o,Ee(i)),o=Be(o,Ee(a)),o=Be(o,Ee(r))},getBeforeBody:function(){return He(this._options.callbacks.beforeBody.apply(this,arguments))},getBody:function(t,e){var n=this,i=n._options.callbacks,a=[];return V.each(t,(function(t){var r={before:[],lines:[],after:[]};Be(r.before,Ee(i.beforeLabel.call(n,t,e))),Be(r.lines,i.label.call(n,t,e)),Be(r.after,Ee(i.afterLabel.call(n,t,e))),a.push(r)})),a},getAfterBody:function(){return He(this._options.callbacks.afterBody.apply(this,arguments))},getFooter:function(){var t=this,e=t._options.callbacks,n=e.beforeFooter.apply(t,arguments),i=e.footer.apply(t,arguments),a=e.afterFooter.apply(t,arguments),r=[];return r=Be(r,Ee(n)),r=Be(r,Ee(i)),r=Be(r,Ee(a))},update:function(t){var e,n,i,a,r,o,s,l,u,d,h=this,c=h._options,f=h._model,g=h._model=We(c),p=h._active,m=h._data,v={xAlign:f.xAlign,yAlign:f.yAlign},b={x:f.x,y:f.y},x={width:f.width,height:f.height},y={x:f.caretX,y:f.caretY};if(p.length){g.opacity=1;var _=[],k=[];y=Ne[c.position].call(h,p,h._eventPosition);var w=[];for(e=0,n=p.length;e<n;++e)w.push((i=p[e],a=void 0,r=void 0,o=void 0,s=void 0,l=void 0,u=void 0,d=void 0,a=i._xScale,r=i._yScale||i._scale,o=i._index,s=i._datasetIndex,l=i._chart.getDatasetMeta(s).controller,u=l._getIndexScale(),d=l._getValueScale(),{xLabel:a?a.getLabelForIndex(o,s):"",yLabel:r?r.getLabelForIndex(o,s):"",label:u?""+u.getLabelForIndex(o,s):"",value:d?""+d.getLabelForIndex(o,s):"",index:o,datasetIndex:s,x:i._model.x,y:i._model.y}));c.filter&&(w=w.filter((function(t){return c.filter(t,m)}))),c.itemSort&&(w=w.sort((function(t,e){return c.itemSort(t,e,m)}))),V.each(w,(function(t){_.push(c.callbacks.labelColor.call(h,t,h._chart)),k.push(c.callbacks.labelTextColor.call(h,t,h._chart))})),g.title=h.getTitle(w,m),g.beforeBody=h.getBeforeBody(w,m),g.body=h.getBody(w,m),g.afterBody=h.getAfterBody(w,m),g.footer=h.getFooter(w,m),g.x=y.x,g.y=y.y,g.caretPadding=c.caretPadding,g.labelColors=_,g.labelTextColors=k,g.dataPoints=w,x=function(t,e){var n=t._chart.ctx,i=2*e.yPadding,a=0,r=e.body,o=r.reduce((function(t,e){return t+e.before.length+e.lines.length+e.after.length}),0);o+=e.beforeBody.length+e.afterBody.length;var s=e.title.length,l=e.footer.length,u=e.titleFontSize,d=e.bodyFontSize,h=e.footerFontSize;i+=s*u,i+=s?(s-1)*e.titleSpacing:0,i+=s?e.titleMarginBottom:0,i+=o*d,i+=o?(o-1)*e.bodySpacing:0,i+=l?e.footerMarginTop:0,i+=l*h,i+=l?(l-1)*e.footerSpacing:0;var c=0,f=function(t){a=Math.max(a,n.measureText(t).width+c)};return n.font=V.fontString(u,e._titleFontStyle,e._titleFontFamily),V.each(e.title,f),n.font=V.fontString(d,e._bodyFontStyle,e._bodyFontFamily),V.each(e.beforeBody.concat(e.afterBody),f),c=e.displayColors?d+2:0,V.each(r,(function(t){V.each(t.before,f),V.each(t.lines,f),V.each(t.after,f)})),c=0,n.font=V.fontString(h,e._footerFontStyle,e._footerFontFamily),V.each(e.footer,f),{width:a+=2*e.xPadding,height:i}}(this,g),b=function(t,e,n,i){var a=t.x,r=t.y,o=t.caretSize,s=t.caretPadding,l=t.cornerRadius,u=n.xAlign,d=n.yAlign,h=o+s,c=l+s;return"right"===u?a-=e.width:"center"===u&&((a-=e.width/2)+e.width>i.width&&(a=i.width-e.width),a<0&&(a=0)),"top"===d?r+=h:r-="bottom"===d?e.height+h:e.height/2,"center"===d?"left"===u?a+=h:"right"===u&&(a-=h):"left"===u?a-=c:"right"===u&&(a+=c),{x:a,y:r}}(g,x,v=function(t,e){var n,i,a,r,o,s=t._model,l=t._chart,u=t._chart.chartArea,d="center",h="center";s.y<e.height?h="top":s.y>l.height-e.height&&(h="bottom");var c=(u.left+u.right)/2,f=(u.top+u.bottom)/2;"center"===h?(n=function(t){return t<=c},i=function(t){return t>c}):(n=function(t){return t<=e.width/2},i=function(t){return t>=l.width-e.width/2}),a=function(t){return t+e.width+s.caretSize+s.caretPadding>l.width},r=function(t){return t-e.width-s.caretSize-s.caretPadding<0},o=function(t){return t<=f?"top":"bottom"},n(s.x)?(d="left",a(s.x)&&(d="center",h=o(s.y))):i(s.x)&&(d="right",r(s.x)&&(d="center",h=o(s.y)));var g=t._options;return{xAlign:g.xAlign?g.xAlign:d,yAlign:g.yAlign?g.yAlign:h}}(this,x),h._chart)}else g.opacity=0;return g.xAlign=v.xAlign,g.yAlign=v.yAlign,g.x=b.x,g.y=b.y,g.width=x.width,g.height=x.height,g.caretX=y.x,g.caretY=y.y,h._model=g,t&&c.custom&&c.custom.call(h,g),h},drawCaret:function(t,e){var n=this._chart.ctx,i=this._view,a=this.getCaretPosition(t,e,i);n.lineTo(a.x1,a.y1),n.lineTo(a.x2,a.y2),n.lineTo(a.x3,a.y3)},getCaretPosition:function(t,e,n){var i,a,r,o,s,l,u=n.caretSize,d=n.cornerRadius,h=n.xAlign,c=n.yAlign,f=t.x,g=t.y,p=e.width,m=e.height;if("center"===c)s=g+m/2,"left"===h?(a=(i=f)-u,r=i,o=s+u,l=s-u):(a=(i=f+p)+u,r=i,o=s-u,l=s+u);else if("left"===h?(i=(a=f+d+u)-u,r=a+u):"right"===h?(i=(a=f+p-d-u)-u,r=a+u):(i=(a=n.caretX)-u,r=a+u),"top"===c)s=(o=g)-u,l=o;else{s=(o=g+m)+u,l=o;var v=r;r=i,i=v}return{x1:i,x2:a,x3:r,y1:o,y2:s,y3:l}},drawTitle:function(t,e,n){var i,a,r,o=e.title,s=o.length;if(s){var l=ze(e.rtl,e.x,e.width);for(t.x=Ve(e,e._titleAlign),n.textAlign=l.textAlign(e._titleAlign),n.textBaseline="middle",i=e.titleFontSize,a=e.titleSpacing,n.fillStyle=e.titleFontColor,n.font=V.fontString(i,e._titleFontStyle,e._titleFontFamily),r=0;r<s;++r)n.fillText(o[r],l.x(t.x),t.y+i/2),t.y+=i+a,r+1===s&&(t.y+=e.titleMarginBottom-a)}},drawBody:function(t,e,n){var i,a,r,o,s,l,u,d,h=e.bodyFontSize,c=e.bodySpacing,f=e._bodyAlign,g=e.body,p=e.displayColors,m=0,v=p?Ve(e,"left"):0,b=ze(e.rtl,e.x,e.width),x=function(e){n.fillText(e,b.x(t.x+m),t.y+h/2),t.y+=h+c},y=b.textAlign(f);for(n.textAlign=f,n.textBaseline="middle",n.font=V.fontString(h,e._bodyFontStyle,e._bodyFontFamily),t.x=Ve(e,y),n.fillStyle=e.bodyFontColor,V.each(e.beforeBody,x),m=p&&"right"!==y?"center"===f?h/2+1:h+2:0,s=0,u=g.length;s<u;++s){for(i=g[s],a=e.labelTextColors[s],r=e.labelColors[s],n.fillStyle=a,V.each(i.before,x),l=0,d=(o=i.lines).length;l<d;++l){if(p){var _=b.x(v);n.fillStyle=e.legendColorBackground,n.fillRect(b.leftForLtr(_,h),t.y,h,h),n.lineWidth=1,n.strokeStyle=r.borderColor,n.strokeRect(b.leftForLtr(_,h),t.y,h,h),n.fillStyle=r.backgroundColor,n.fillRect(b.leftForLtr(b.xPlus(_,1),h-2),t.y+1,h-2,h-2),n.fillStyle=a}x(o[l])}V.each(i.after,x)}m=0,V.each(e.afterBody,x),t.y-=c},drawFooter:function(t,e,n){var i,a,r=e.footer,o=r.length;if(o){var s=ze(e.rtl,e.x,e.width);for(t.x=Ve(e,e._footerAlign),t.y+=e.footerMarginTop,n.textAlign=s.textAlign(e._footerAlign),n.textBaseline="middle",i=e.footerFontSize,n.fillStyle=e.footerFontColor,n.font=V.fontString(i,e._footerFontStyle,e._footerFontFamily),a=0;a<o;++a)n.fillText(r[a],s.x(t.x),t.y+i/2),t.y+=i+e.footerSpacing}},drawBackground:function(t,e,n,i){n.fillStyle=e.backgroundColor,n.strokeStyle=e.borderColor,n.lineWidth=e.borderWidth;var a=e.xAlign,r=e.yAlign,o=t.x,s=t.y,l=i.width,u=i.height,d=e.cornerRadius;n.beginPath(),n.moveTo(o+d,s),"top"===r&&this.drawCaret(t,i),n.lineTo(o+l-d,s),n.quadraticCurveTo(o+l,s,o+l,s+d),"center"===r&&"right"===a&&this.drawCaret(t,i),n.lineTo(o+l,s+u-d),n.quadraticCurveTo(o+l,s+u,o+l-d,s+u),"bottom"===r&&this.drawCaret(t,i),n.lineTo(o+d,s+u),n.quadraticCurveTo(o,s+u,o,s+u-d),"center"===r&&"left"===a&&this.drawCaret(t,i),n.lineTo(o,s+d),n.quadraticCurveTo(o,s,o+d,s),n.closePath(),n.fill(),e.borderWidth>0&&n.stroke()},draw:function(){var t=this._chart.ctx,e=this._view;if(0!==e.opacity){var n={width:e.width,height:e.height},i={x:e.x,y:e.y},a=Math.abs(e.opacity<.001)?0:e.opacity,r=e.title.length||e.beforeBody.length||e.body.length||e.afterBody.length||e.footer.length;this._options.enabled&&r&&(t.save(),t.globalAlpha=a,this.drawBackground(i,e,t,n),i.y+=e.yPadding,V.rtl.overrideTextDirection(t,e.textDirection),this.drawTitle(i,e,t),this.drawBody(i,e,t),this.drawFooter(i,e,t),V.rtl.restoreTextDirection(t,e.textDirection),t.restore())}},handleEvent:function(t){var e,n=this,i=n._options;return n._lastActive=n._lastActive||[],"mouseout"===t.type?n._active=[]:(n._active=n._chart.getElementsAtEventForMode(t,i.mode,i),i.reverse&&n._active.reverse()),(e=!V.arrayEquals(n._active,n._lastActive))&&(n._lastActive=n._active,(i.enabled||i.custom)&&(n._eventPosition={x:t.x,y:t.y},n.update(!0),n.pivot())),e}}),qe=Ne,Ue=je;Ue.positioners=qe;var Ye=V.valueOrDefault;function Ge(){return V.merge({},[].slice.call(arguments),{merger:function(t,e,n,i){if("xAxes"===t||"yAxes"===t){var a,r,o,s=n[t].length;for(e[t]||(e[t]=[]),a=0;a<s;++a)o=n[t][a],r=Ye(o.type,"xAxes"===t?"category":"linear"),a>=e[t].length&&e[t].push({}),!e[t][a].type||o.type&&o.type!==e[t][a].type?V.merge(e[t][a],[Oe.getScaleDefaults(r),o]):V.merge(e[t][a],o)}else V._merger(t,e,n,i)}})}function Xe(){return V.merge({},[].slice.call(arguments),{merger:function(t,e,n,i){var a=e[t]||{},r=n[t];"scales"===t?e[t]=Ge(a,r):"scale"===t?e[t]=V.merge(a,[Oe.getScaleDefaults(r.type),r]):V._merger(t,e,n,i)}})}function Ke(t){var e=t.options;V.each(t.scales,(function(e){ge.removeBox(t,e)})),e=Xe(z.global,z[t.config.type],e),t.options=t.config.options=e,t.ensureScalesHaveIDs(),t.buildOrUpdateScales(),t.tooltip._options=e.tooltips,t.tooltip.initialize()}function Ze(t,e,n){var i,a=function(t){return t.id===i};do{i=e+n++}while(V.findIndex(t,a)>=0);return i}function $e(t){return"top"===t||"bottom"===t}function Je(t,e){return function(n,i){return n[t]===i[t]?n[e]-i[e]:n[t]-i[t]}}z._set("global",{elements:{},events:["mousemove","mouseout","click","touchstart","touchmove"],hover:{onHover:null,mode:"nearest",intersect:!0,animationDuration:400},onClick:null,maintainAspectRatio:!0,responsive:!0,responsiveAnimationDuration:0});var Qe=function(t,e){return this.construct(t,e),this};V.extend(Qe.prototype,{construct:function(t,e){var n=this;e=function(t){var e=(t=t||{}).data=t.data||{};return e.datasets=e.datasets||[],e.labels=e.labels||[],t.options=Xe(z.global,z[t.type],t.options||{}),t}(e);var i=Fe.acquireContext(t,e),a=i&&i.canvas,r=a&&a.height,o=a&&a.width;n.id=V.uid(),n.ctx=i,n.canvas=a,n.config=e,n.width=o,n.height=r,n.aspectRatio=r?o/r:null,n.options=e.options,n._bufferedRender=!1,n._layers=[],n.chart=n,n.controller=n,Qe.instances[n.id]=n,Object.defineProperty(n,"data",{get:function(){return n.config.data},set:function(t){n.config.data=t}}),i&&a?(n.initialize(),n.update()):console.error("Failed to create chart: can't acquire context from the given item")},initialize:function(){var t=this;return Le.notify(t,"beforeInit"),V.retinaScale(t,t.options.devicePixelRatio),t.bindEvents(),t.options.responsive&&t.resize(!0),t.initToolTip(),Le.notify(t,"afterInit"),t},clear:function(){return V.canvas.clear(this),this},stop:function(){return $.cancelAnimation(this),this},resize:function(t){var e=this,n=e.options,i=e.canvas,a=n.maintainAspectRatio&&e.aspectRatio||null,r=Math.max(0,Math.floor(V.getMaximumWidth(i))),o=Math.max(0,Math.floor(a?r/a:V.getMaximumHeight(i)));if((e.width!==r||e.height!==o)&&(i.width=e.width=r,i.height=e.height=o,i.style.width=r+"px",i.style.height=o+"px",V.retinaScale(e,n.devicePixelRatio),!t)){var s={width:r,height:o};Le.notify(e,"resize",[s]),n.onResize&&n.onResize(e,s),e.stop(),e.update({duration:n.responsiveAnimationDuration})}},ensureScalesHaveIDs:function(){var t=this.options,e=t.scales||{},n=t.scale;V.each(e.xAxes,(function(t,n){t.id||(t.id=Ze(e.xAxes,"x-axis-",n))})),V.each(e.yAxes,(function(t,n){t.id||(t.id=Ze(e.yAxes,"y-axis-",n))})),n&&(n.id=n.id||"scale")},buildOrUpdateScales:function(){var t=this,e=t.options,n=t.scales||{},i=[],a=Object.keys(n).reduce((function(t,e){return t[e]=!1,t}),{});e.scales&&(i=i.concat((e.scales.xAxes||[]).map((function(t){return{options:t,dtype:"category",dposition:"bottom"}})),(e.scales.yAxes||[]).map((function(t){return{options:t,dtype:"linear",dposition:"left"}})))),e.scale&&i.push({options:e.scale,dtype:"radialLinear",isDefault:!0,dposition:"chartArea"}),V.each(i,(function(e){var i=e.options,r=i.id,o=Ye(i.type,e.dtype);$e(i.position)!==$e(e.dposition)&&(i.position=e.dposition),a[r]=!0;var s=null;if(r in n&&n[r].type===o)(s=n[r]).options=i,s.ctx=t.ctx,s.chart=t;else{var l=Oe.getScaleConstructor(o);if(!l)return;s=new l({id:r,type:o,options:i,ctx:t.ctx,chart:t}),n[s.id]=s}s.mergeTicksOptions(),e.isDefault&&(t.scale=s)})),V.each(a,(function(t,e){t||delete n[e]})),t.scales=n,Oe.addScalesToLayout(this)},buildOrUpdateControllers:function(){var t,e,n=this,i=[],a=n.data.datasets;for(t=0,e=a.length;t<e;t++){var r=a[t],o=n.getDatasetMeta(t),s=r.type||n.config.type;if(o.type&&o.type!==s&&(n.destroyDatasetMeta(t),o=n.getDatasetMeta(t)),o.type=s,o.order=r.order||0,o.index=t,o.controller)o.controller.updateIndex(t),o.controller.linkScales();else{var l=$t[o.type];if(void 0===l)throw new Error('"'+o.type+'" is not a chart type.');o.controller=new l(n,t),i.push(o.controller)}}return i},resetElements:function(){var t=this;V.each(t.data.datasets,(function(e,n){t.getDatasetMeta(n).controller.reset()}),t)},reset:function(){this.resetElements(),this.tooltip.initialize()},update:function(t){var e,n,i=this;if(t&&"object"==typeof t||(t={duration:t,lazy:arguments[1]}),Ke(i),Le._invalidate(i),!1!==Le.notify(i,"beforeUpdate")){i.tooltip._data=i.data;var a=i.buildOrUpdateControllers();for(e=0,n=i.data.datasets.length;e<n;e++)i.getDatasetMeta(e).controller.buildOrUpdateElements();i.updateLayout(),i.options.animation&&i.options.animation.duration&&V.each(a,(function(t){t.reset()})),i.updateDatasets(),i.tooltip.initialize(),i.lastActive=[],Le.notify(i,"afterUpdate"),i._layers.sort(Je("z","_idx")),i._bufferedRender?i._bufferedRequest={duration:t.duration,easing:t.easing,lazy:t.lazy}:i.render(t)}},updateLayout:function(){var t=this;!1!==Le.notify(t,"beforeLayout")&&(ge.update(this,this.width,this.height),t._layers=[],V.each(t.boxes,(function(e){e._configure&&e._configure(),t._layers.push.apply(t._layers,e._layers())}),t),t._layers.forEach((function(t,e){t._idx=e})),Le.notify(t,"afterScaleUpdate"),Le.notify(t,"afterLayout"))},updateDatasets:function(){if(!1!==Le.notify(this,"beforeDatasetsUpdate")){for(var t=0,e=this.data.datasets.length;t<e;++t)this.updateDataset(t);Le.notify(this,"afterDatasetsUpdate")}},updateDataset:function(t){var e=this.getDatasetMeta(t),n={meta:e,index:t};!1!==Le.notify(this,"beforeDatasetUpdate",[n])&&(e.controller._update(),Le.notify(this,"afterDatasetUpdate",[n]))},render:function(t){var e=this;t&&"object"==typeof t||(t={duration:t,lazy:arguments[1]});var n=e.options.animation,i=Ye(t.duration,n&&n.duration),a=t.lazy;if(!1!==Le.notify(e,"beforeRender")){var r=function(t){Le.notify(e,"afterRender"),V.callback(n&&n.onComplete,[t],e)};if(n&&i){var o=new Z({numSteps:i/16.66,easing:t.easing||n.easing,render:function(t,e){var n=V.easing.effects[e.easing],i=e.currentStep,a=i/e.numSteps;t.draw(n(a),a,i)},onAnimationProgress:n.onProgress,onAnimationComplete:r});$.addAnimation(e,o,i,a)}else e.draw(),r(new Z({numSteps:0,chart:e}));return e}},draw:function(t){var e,n,i=this;if(i.clear(),V.isNullOrUndef(t)&&(t=1),i.transition(t),!(i.width<=0||i.height<=0)&&!1!==Le.notify(i,"beforeDraw",[t])){for(n=i._layers,e=0;e<n.length&&n[e].z<=0;++e)n[e].draw(i.chartArea);for(i.drawDatasets(t);e<n.length;++e)n[e].draw(i.chartArea);i._drawTooltip(t),Le.notify(i,"afterDraw",[t])}},transition:function(t){for(var e=0,n=(this.data.datasets||[]).length;e<n;++e)this.isDatasetVisible(e)&&this.getDatasetMeta(e).controller.transition(t);this.tooltip.transition(t)},_getSortedDatasetMetas:function(t){var e,n,i=[];for(e=0,n=(this.data.datasets||[]).length;e<n;++e)t&&!this.isDatasetVisible(e)||i.push(this.getDatasetMeta(e));return i.sort(Je("order","index")),i},_getSortedVisibleDatasetMetas:function(){return this._getSortedDatasetMetas(!0)},drawDatasets:function(t){var e,n;if(!1!==Le.notify(this,"beforeDatasetsDraw",[t])){for(n=(e=this._getSortedVisibleDatasetMetas()).length-1;n>=0;--n)this.drawDataset(e[n],t);Le.notify(this,"afterDatasetsDraw",[t])}},drawDataset:function(t,e){var n={meta:t,index:t.index,easingValue:e};!1!==Le.notify(this,"beforeDatasetDraw",[n])&&(t.controller.draw(e),Le.notify(this,"afterDatasetDraw",[n]))},_drawTooltip:function(t){var e=this.tooltip,n={tooltip:e,easingValue:t};!1!==Le.notify(this,"beforeTooltipDraw",[n])&&(e.draw(),Le.notify(this,"afterTooltipDraw",[n]))},getElementAtEvent:function(t){return ae.modes.single(this,t)},getElementsAtEvent:function(t){return ae.modes.label(this,t,{intersect:!0})},getElementsAtXAxis:function(t){return ae.modes["x-axis"](this,t,{intersect:!0})},getElementsAtEventForMode:function(t,e,n){var i=ae.modes[e];return"function"==typeof i?i(this,t,n):[]},getDatasetAtEvent:function(t){return ae.modes.dataset(this,t,{intersect:!0})},getDatasetMeta:function(t){var e=this.data.datasets[t];e._meta||(e._meta={});var n=e._meta[this.id];return n||(n=e._meta[this.id]={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e.order||0,index:t}),n},getVisibleDatasetCount:function(){for(var t=0,e=0,n=this.data.datasets.length;e<n;++e)this.isDatasetVisible(e)&&t++;return t},isDatasetVisible:function(t){var e=this.getDatasetMeta(t);return"boolean"==typeof e.hidden?!e.hidden:!this.data.datasets[t].hidden},generateLegend:function(){return this.options.legendCallback(this)},destroyDatasetMeta:function(t){var e=this.id,n=this.data.datasets[t],i=n._meta&&n._meta[e];i&&(i.controller.destroy(),delete n._meta[e])},destroy:function(){var t,e,n=this,i=n.canvas;for(n.stop(),t=0,e=n.data.datasets.length;t<e;++t)n.destroyDatasetMeta(t);i&&(n.unbindEvents(),V.canvas.clear(n),Fe.releaseContext(n.ctx),n.canvas=null,n.ctx=null),Le.notify(n,"destroy"),delete Qe.instances[n.id]},toBase64Image:function(){return this.canvas.toDataURL.apply(this.canvas,arguments)},initToolTip:function(){var t=this;t.tooltip=new Ue({_chart:t,_chartInstance:t,_data:t.data,_options:t.options.tooltips},t)},bindEvents:function(){var t=this,e=t._listeners={},n=function(){t.eventHandler.apply(t,arguments)};V.each(t.options.events,(function(i){Fe.addEventListener(t,i,n),e[i]=n})),t.options.responsive&&(n=function(){t.resize()},Fe.addEventListener(t,"resize",n),e.resize=n)},unbindEvents:function(){var t=this,e=t._listeners;e&&(delete t._listeners,V.each(e,(function(e,n){Fe.removeEventListener(t,n,e)})))},updateHoverStyle:function(t,e,n){var i,a,r,o=n?"set":"remove";for(a=0,r=t.length;a<r;++a)(i=t[a])&&this.getDatasetMeta(i._datasetIndex).controller[o+"HoverStyle"](i);"dataset"===e&&this.getDatasetMeta(t[0]._datasetIndex).controller["_"+o+"DatasetHoverStyle"]()},eventHandler:function(t){var e=this,n=e.tooltip;if(!1!==Le.notify(e,"beforeEvent",[t])){e._bufferedRender=!0,e._bufferedRequest=null;var i=e.handleEvent(t);n&&(i=n._start?n.handleEvent(t):i|n.handleEvent(t)),Le.notify(e,"afterEvent",[t]);var a=e._bufferedRequest;return a?e.render(a):i&&!e.animating&&(e.stop(),e.render({duration:e.options.hover.animationDuration,lazy:!0})),e._bufferedRender=!1,e._bufferedRequest=null,e}},handleEvent:function(t){var e,n=this,i=n.options||{},a=i.hover;return n.lastActive=n.lastActive||[],"mouseout"===t.type?n.active=[]:n.active=n.getElementsAtEventForMode(t,a.mode,a),V.callback(i.onHover||i.hover.onHover,[t.native,n.active],n),"mouseup"!==t.type&&"click"!==t.type||i.onClick&&i.onClick.call(n,t.native,n.active),n.lastActive.length&&n.updateHoverStyle(n.lastActive,a.mode,!1),n.active.length&&a.mode&&n.updateHoverStyle(n.active,a.mode,!0),e=!V.arrayEquals(n.active,n.lastActive),n.lastActive=n.active,e}}),Qe.instances={};var tn=Qe;Qe.Controller=Qe,Qe.types={},V.configMerge=Xe,V.scaleMerge=Ge;function en(){throw new Error("This method is not implemented: either no adapter can be found or an incomplete integration was provided.")}function nn(t){this.options=t||{}}V.extend(nn.prototype,{formats:en,parse:en,format:en,add:en,diff:en,startOf:en,endOf:en,_create:function(t){return t}}),nn.override=function(t){V.extend(nn.prototype,t)};var an={_date:nn},rn={formatters:{values:function(t){return V.isArray(t)?t:""+t},linear:function(t,e,n){var i=n.length>3?n[2]-n[1]:n[1]-n[0];Math.abs(i)>1&&t!==Math.floor(t)&&(i=t-Math.floor(t));var a=V.log10(Math.abs(i)),r="";if(0!==t)if(Math.max(Math.abs(n[0]),Math.abs(n[n.length-1]))<1e-4){var o=V.log10(Math.abs(t)),s=Math.floor(o)-Math.floor(a);s=Math.max(Math.min(s,20),0),r=t.toExponential(s)}else{var l=-1*Math.floor(a);l=Math.max(Math.min(l,20),0),r=t.toFixed(l)}else r="0";return r},logarithmic:function(t,e,n){var i=t/Math.pow(10,Math.floor(V.log10(t)));return 0===t?"0":1===i||2===i||5===i||0===e||e===n.length-1?t.toExponential():""}}},on=V.isArray,sn=V.isNullOrUndef,ln=V.valueOrDefault,un=V.valueAtIndexOrDefault;function dn(t,e,n){var i,a=t.getTicks().length,r=Math.min(e,a-1),o=t.getPixelForTick(r),s=t._startPixel,l=t._endPixel;if(!(n&&(i=1===a?Math.max(o-s,l-o):0===e?(t.getPixelForTick(1)-o)/2:(o-t.getPixelForTick(r-1))/2,(o+=r<e?i:-i)<s-1e-6||o>l+1e-6)))return o}function hn(t,e,n,i){var a,r,o,s,l,u,d,h,c,f,g,p,m,v=n.length,b=[],x=[],y=[];for(a=0;a<v;++a){if(s=n[a].label,l=n[a].major?e.major:e.minor,t.font=u=l.string,d=i[u]=i[u]||{data:{},gc:[]},h=l.lineHeight,c=f=0,sn(s)||on(s)){if(on(s))for(r=0,o=s.length;r<o;++r)g=s[r],sn(g)||on(g)||(c=V.measureText(t,d.data,d.gc,c,g),f+=h)}else c=V.measureText(t,d.data,d.gc,c,s),f=h;b.push(c),x.push(f),y.push(h/2)}function _(t){return{width:b[t]||0,height:x[t]||0,offset:y[t]||0}}return function(t,e){V.each(t,(function(t){var n,i=t.gc,a=i.length/2;if(a>e){for(n=0;n<a;++n)delete t.data[i[n]];i.splice(0,a)}}))}(i,v),p=b.indexOf(Math.max.apply(null,b)),m=x.indexOf(Math.max.apply(null,x)),{first:_(0),last:_(v-1),widest:_(p),highest:_(m)}}function cn(t){return t.drawTicks?t.tickMarkLength:0}function fn(t){var e,n;return t.display?(e=V.options._parseFont(t),n=V.options.toPadding(t.padding),e.lineHeight+n.height):0}function gn(t,e){return V.extend(V.options._parseFont({fontFamily:ln(e.fontFamily,t.fontFamily),fontSize:ln(e.fontSize,t.fontSize),fontStyle:ln(e.fontStyle,t.fontStyle),lineHeight:ln(e.lineHeight,t.lineHeight)}),{color:V.options.resolve([e.fontColor,t.fontColor,z.global.defaultFontColor])})}function pn(t){var e=gn(t,t.minor);return{minor:e,major:t.major.enabled?gn(t,t.major):e}}function mn(t){var e,n,i,a=[];for(n=0,i=t.length;n<i;++n)void 0!==(e=t[n])._index&&a.push(e);return a}function vn(t,e,n,i){var a,r,o,s,l=ln(n,0),u=Math.min(ln(i,t.length),t.length),d=0;for(e=Math.ceil(e),i&&(e=(a=i-n)/Math.floor(a/e)),s=l;s<0;)d++,s=Math.round(l+d*e);for(r=Math.max(l,0);r<u;r++)o=t[r],r===s?(o._index=r,d++,s=Math.round(l+d*e)):delete o.label}z._set("scale",{display:!0,position:"left",offset:!1,gridLines:{display:!0,color:"rgba(0,0,0,0.1)",lineWidth:1,drawBorder:!0,drawOnChartArea:!0,drawTicks:!0,tickMarkLength:10,zeroLineWidth:1,zeroLineColor:"rgba(0,0,0,0.25)",zeroLineBorderDash:[],zeroLineBorderDashOffset:0,offsetGridLines:!1,borderDash:[],borderDashOffset:0},scaleLabel:{display:!1,labelString:"",padding:{top:4,bottom:4}},ticks:{beginAtZero:!1,minRotation:0,maxRotation:50,mirror:!1,padding:0,reverse:!1,display:!0,autoSkip:!0,autoSkipPadding:0,labelOffset:0,callback:rn.formatters.values,minor:{},major:{}}});var bn=X.extend({zeroLineIndex:0,getPadding:function(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}},getTicks:function(){return this._ticks},_getLabels:function(){var t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]},mergeTicksOptions:function(){},beforeUpdate:function(){V.callback(this.options.beforeUpdate,[this])},update:function(t,e,n){var i,a,r,o,s,l=this,u=l.options.ticks,d=u.sampleSize;if(l.beforeUpdate(),l.maxWidth=t,l.maxHeight=e,l.margins=V.extend({left:0,right:0,top:0,bottom:0},n),l._ticks=null,l.ticks=null,l._labelSizes=null,l._maxLabelLines=0,l.longestLabelWidth=0,l.longestTextCache=l.longestTextCache||{},l._gridLineItems=null,l._labelItems=null,l.beforeSetDimensions(),l.setDimensions(),l.afterSetDimensions(),l.beforeDataLimits(),l.determineDataLimits(),l.afterDataLimits(),l.beforeBuildTicks(),o=l.buildTicks()||[],(!(o=l.afterBuildTicks(o)||o)||!o.length)&&l.ticks)for(o=[],i=0,a=l.ticks.length;i<a;++i)o.push({value:l.ticks[i],major:!1});return l._ticks=o,s=d<o.length,r=l._convertTicksToLabels(s?function(t,e){for(var n=[],i=t.length/e,a=0,r=t.length;a<r;a+=i)n.push(t[Math.floor(a)]);return n}(o,d):o),l._configure(),l.beforeCalculateTickRotation(),l.calculateTickRotation(),l.afterCalculateTickRotation(),l.beforeFit(),l.fit(),l.afterFit(),l._ticksToDraw=u.display&&(u.autoSkip||"auto"===u.source)?l._autoSkip(o):o,s&&(r=l._convertTicksToLabels(l._ticksToDraw)),l.ticks=r,l.afterUpdate(),l.minSize},_configure:function(){var t,e,n=this,i=n.options.ticks.reverse;n.isHorizontal()?(t=n.left,e=n.right):(t=n.top,e=n.bottom,i=!i),n._startPixel=t,n._endPixel=e,n._reversePixels=i,n._length=e-t},afterUpdate:function(){V.callback(this.options.afterUpdate,[this])},beforeSetDimensions:function(){V.callback(this.options.beforeSetDimensions,[this])},setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0},afterSetDimensions:function(){V.callback(this.options.afterSetDimensions,[this])},beforeDataLimits:function(){V.callback(this.options.beforeDataLimits,[this])},determineDataLimits:V.noop,afterDataLimits:function(){V.callback(this.options.afterDataLimits,[this])},beforeBuildTicks:function(){V.callback(this.options.beforeBuildTicks,[this])},buildTicks:V.noop,afterBuildTicks:function(t){var e=this;return on(t)&&t.length?V.callback(e.options.afterBuildTicks,[e,t]):(e.ticks=V.callback(e.options.afterBuildTicks,[e,e.ticks])||e.ticks,t)},beforeTickToLabelConversion:function(){V.callback(this.options.beforeTickToLabelConversion,[this])},convertTicksToLabels:function(){var t=this.options.ticks;this.ticks=this.ticks.map(t.userCallback||t.callback,this)},afterTickToLabelConversion:function(){V.callback(this.options.afterTickToLabelConversion,[this])},beforeCalculateTickRotation:function(){V.callback(this.options.beforeCalculateTickRotation,[this])},calculateTickRotation:function(){var t,e,n,i,a,r,o,s=this,l=s.options,u=l.ticks,d=s.getTicks().length,h=u.minRotation||0,c=u.maxRotation,f=h;!s._isVisible()||!u.display||h>=c||d<=1||!s.isHorizontal()?s.labelRotation=h:(e=(t=s._getLabelSizes()).widest.width,n=t.highest.height-t.highest.offset,i=Math.min(s.maxWidth,s.chart.width-e),e+6>(a=l.offset?s.maxWidth/d:i/(d-1))&&(a=i/(d-(l.offset?.5:1)),r=s.maxHeight-cn(l.gridLines)-u.padding-fn(l.scaleLabel),o=Math.sqrt(e*e+n*n),f=V.toDegrees(Math.min(Math.asin(Math.min((t.highest.height+6)/a,1)),Math.asin(Math.min(r/o,1))-Math.asin(n/o))),f=Math.max(h,Math.min(c,f))),s.labelRotation=f)},afterCalculateTickRotation:function(){V.callback(this.options.afterCalculateTickRotation,[this])},beforeFit:function(){V.callback(this.options.beforeFit,[this])},fit:function(){var t=this,e=t.minSize={width:0,height:0},n=t.chart,i=t.options,a=i.ticks,r=i.scaleLabel,o=i.gridLines,s=t._isVisible(),l="bottom"===i.position,u=t.isHorizontal();if(u?e.width=t.maxWidth:s&&(e.width=cn(o)+fn(r)),u?s&&(e.height=cn(o)+fn(r)):e.height=t.maxHeight,a.display&&s){var d=pn(a),h=t._getLabelSizes(),c=h.first,f=h.last,g=h.widest,p=h.highest,m=.4*d.minor.lineHeight,v=a.padding;if(u){var b=0!==t.labelRotation,x=V.toRadians(t.labelRotation),y=Math.cos(x),_=Math.sin(x),k=_*g.width+y*(p.height-(b?p.offset:0))+(b?0:m);e.height=Math.min(t.maxHeight,e.height+k+v);var w,M,S=t.getPixelForTick(0)-t.left,C=t.right-t.getPixelForTick(t.getTicks().length-1);b?(w=l?y*c.width+_*c.offset:_*(c.height-c.offset),M=l?_*(f.height-f.offset):y*f.width+_*f.offset):(w=c.width/2,M=f.width/2),t.paddingLeft=Math.max((w-S)*t.width/(t.width-S),0)+3,t.paddingRight=Math.max((M-C)*t.width/(t.width-C),0)+3}else{var P=a.mirror?0:g.width+v+m;e.width=Math.min(t.maxWidth,e.width+P),t.paddingTop=c.height/2,t.paddingBottom=f.height/2}}t.handleMargins(),u?(t.width=t._length=n.width-t.margins.left-t.margins.right,t.height=e.height):(t.width=e.width,t.height=t._length=n.height-t.margins.top-t.margins.bottom)},handleMargins:function(){var t=this;t.margins&&(t.margins.left=Math.max(t.paddingLeft,t.margins.left),t.margins.top=Math.max(t.paddingTop,t.margins.top),t.margins.right=Math.max(t.paddingRight,t.margins.right),t.margins.bottom=Math.max(t.paddingBottom,t.margins.bottom))},afterFit:function(){V.callback(this.options.afterFit,[this])},isHorizontal:function(){var t=this.options.position;return"top"===t||"bottom"===t},isFullWidth:function(){return this.options.fullWidth},getRightValue:function(t){if(sn(t))return NaN;if(("number"==typeof t||t instanceof Number)&&!isFinite(t))return NaN;if(t)if(this.isHorizontal()){if(void 0!==t.x)return this.getRightValue(t.x)}else if(void 0!==t.y)return this.getRightValue(t.y);return t},_convertTicksToLabels:function(t){var e,n,i,a=this;for(a.ticks=t.map((function(t){return t.value})),a.beforeTickToLabelConversion(),e=a.convertTicksToLabels(t)||a.ticks,a.afterTickToLabelConversion(),n=0,i=t.length;n<i;++n)t[n].label=e[n];return e},_getLabelSizes:function(){var t=this,e=t._labelSizes;return e||(t._labelSizes=e=hn(t.ctx,pn(t.options.ticks),t.getTicks(),t.longestTextCache),t.longestLabelWidth=e.widest.width),e},_parseValue:function(t){var e,n,i,a;return on(t)?(e=+this.getRightValue(t[0]),n=+this.getRightValue(t[1]),i=Math.min(e,n),a=Math.max(e,n)):(e=void 0,n=t=+this.getRightValue(t),i=t,a=t),{min:i,max:a,start:e,end:n}},_getScaleLabel:function(t){var e=this._parseValue(t);return void 0!==e.start?"["+e.start+", "+e.end+"]":+this.getRightValue(t)},getLabelForIndex:V.noop,getPixelForValue:V.noop,getValueForPixel:V.noop,getPixelForTick:function(t){var e=this.options.offset,n=this._ticks.length,i=1/Math.max(n-(e?0:1),1);return t<0||t>n-1?null:this.getPixelForDecimal(t*i+(e?i/2:0))},getPixelForDecimal:function(t){return this._reversePixels&&(t=1-t),this._startPixel+t*this._length},getDecimalForPixel:function(t){var e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e},getBasePixel:function(){return this.getPixelForValue(this.getBaseValue())},getBaseValue:function(){var t=this.min,e=this.max;return this.beginAtZero?0:t<0&&e<0?e:t>0&&e>0?t:0},_autoSkip:function(t){var e,n,i,a,r=this.options.ticks,o=this._length,s=r.maxTicksLimit||o/this._tickSize()+1,l=r.major.enabled?function(t){var e,n,i=[];for(e=0,n=t.length;e<n;e++)t[e].major&&i.push(e);return i}(t):[],u=l.length,d=l[0],h=l[u-1];if(u>s)return function(t,e,n){var i,a,r=0,o=e[0];for(n=Math.ceil(n),i=0;i<t.length;i++)a=t[i],i===o?(a._index=i,o=e[++r*n]):delete a.label}(t,l,u/s),mn(t);if(i=function(t,e,n,i){var a,r,o,s,l=function(t){var e,n,i=t.length;if(i<2)return!1;for(n=t[0],e=1;e<i;++e)if(t[e]-t[e-1]!==n)return!1;return n}(t),u=(e.length-1)/i;if(!l)return Math.max(u,1);for(o=0,s=(a=V.math._factorize(l)).length-1;o<s;o++)if((r=a[o])>u)return r;return Math.max(u,1)}(l,t,0,s),u>0){for(e=0,n=u-1;e<n;e++)vn(t,i,l[e],l[e+1]);return a=u>1?(h-d)/(u-1):null,vn(t,i,V.isNullOrUndef(a)?0:d-a,d),vn(t,i,h,V.isNullOrUndef(a)?t.length:h+a),mn(t)}return vn(t,i),mn(t)},_tickSize:function(){var t=this.options.ticks,e=V.toRadians(this.labelRotation),n=Math.abs(Math.cos(e)),i=Math.abs(Math.sin(e)),a=this._getLabelSizes(),r=t.autoSkipPadding||0,o=a?a.widest.width+r:0,s=a?a.highest.height+r:0;return this.isHorizontal()?s*n>o*i?o/n:s/i:s*i<o*n?s/n:o/i},_isVisible:function(){var t,e,n,i=this.chart,a=this.options.display;if("auto"!==a)return!!a;for(t=0,e=i.data.datasets.length;t<e;++t)if(i.isDatasetVisible(t)&&((n=i.getDatasetMeta(t)).xAxisID===this.id||n.yAxisID===this.id))return!0;return!1},_computeGridLineItems:function(t){var e,n,i,a,r,o,s,l,u,d,h,c,f,g,p,m,v,b=this,x=b.chart,y=b.options,_=y.gridLines,k=y.position,w=_.offsetGridLines,M=b.isHorizontal(),S=b._ticksToDraw,C=S.length+(w?1:0),P=cn(_),A=[],D=_.drawBorder?un(_.lineWidth,0,0):0,T=D/2,I=V._alignPixel,F=function(t){return I(x,t,D)};for("top"===k?(e=F(b.bottom),s=b.bottom-P,u=e-T,h=F(t.top)+T,f=t.bottom):"bottom"===k?(e=F(b.top),h=t.top,f=F(t.bottom)-T,s=e+T,u=b.top+P):"left"===k?(e=F(b.right),o=b.right-P,l=e-T,d=F(t.left)+T,c=t.right):(e=F(b.left),d=t.left,c=F(t.right)-T,o=e+T,l=b.left+P),n=0;n<C;++n)i=S[n]||{},sn(i.label)&&n<S.length||(n===b.zeroLineIndex&&y.offset===w?(g=_.zeroLineWidth,p=_.zeroLineColor,m=_.zeroLineBorderDash||[],v=_.zeroLineBorderDashOffset||0):(g=un(_.lineWidth,n,1),p=un(_.color,n,"rgba(0,0,0,0.1)"),m=_.borderDash||[],v=_.borderDashOffset||0),void 0!==(a=dn(b,i._index||n,w))&&(r=I(x,a,g),M?o=l=d=c=r:s=u=h=f=r,A.push({tx1:o,ty1:s,tx2:l,ty2:u,x1:d,y1:h,x2:c,y2:f,width:g,color:p,borderDash:m,borderDashOffset:v})));return A.ticksLength=C,A.borderValue=e,A},_computeLabelItems:function(){var t,e,n,i,a,r,o,s,l,u,d,h,c=this,f=c.options,g=f.ticks,p=f.position,m=g.mirror,v=c.isHorizontal(),b=c._ticksToDraw,x=pn(g),y=g.padding,_=cn(f.gridLines),k=-V.toRadians(c.labelRotation),w=[];for("top"===p?(r=c.bottom-_-y,o=k?"left":"center"):"bottom"===p?(r=c.top+_+y,o=k?"right":"center"):"left"===p?(a=c.right-(m?0:_)-y,o=m?"left":"right"):(a=c.left+(m?0:_)+y,o=m?"right":"left"),t=0,e=b.length;t<e;++t)i=(n=b[t]).label,sn(i)||(s=c.getPixelForTick(n._index||t)+g.labelOffset,u=(l=n.major?x.major:x.minor).lineHeight,d=on(i)?i.length:1,v?(a=s,h="top"===p?((k?1:.5)-d)*u:(k?0:.5)*u):(r=s,h=(1-d)*u/2),w.push({x:a,y:r,rotation:k,label:i,font:l,textOffset:h,textAlign:o}));return w},_drawGrid:function(t){var e=this,n=e.options.gridLines;if(n.display){var i,a,r,o,s,l=e.ctx,u=e.chart,d=V._alignPixel,h=n.drawBorder?un(n.lineWidth,0,0):0,c=e._gridLineItems||(e._gridLineItems=e._computeGridLineItems(t));for(r=0,o=c.length;r<o;++r)i=(s=c[r]).width,a=s.color,i&&a&&(l.save(),l.lineWidth=i,l.strokeStyle=a,l.setLineDash&&(l.setLineDash(s.borderDash),l.lineDashOffset=s.borderDashOffset),l.beginPath(),n.drawTicks&&(l.moveTo(s.tx1,s.ty1),l.lineTo(s.tx2,s.ty2)),n.drawOnChartArea&&(l.moveTo(s.x1,s.y1),l.lineTo(s.x2,s.y2)),l.stroke(),l.restore());if(h){var f,g,p,m,v=h,b=un(n.lineWidth,c.ticksLength-1,1),x=c.borderValue;e.isHorizontal()?(f=d(u,e.left,v)-v/2,g=d(u,e.right,b)+b/2,p=m=x):(p=d(u,e.top,v)-v/2,m=d(u,e.bottom,b)+b/2,f=g=x),l.lineWidth=h,l.strokeStyle=un(n.color,0),l.beginPath(),l.moveTo(f,p),l.lineTo(g,m),l.stroke()}}},_drawLabels:function(){var t=this;if(t.options.ticks.display){var e,n,i,a,r,o,s,l,u=t.ctx,d=t._labelItems||(t._labelItems=t._computeLabelItems());for(e=0,i=d.length;e<i;++e){if(o=(r=d[e]).font,u.save(),u.translate(r.x,r.y),u.rotate(r.rotation),u.font=o.string,u.fillStyle=o.color,u.textBaseline="middle",u.textAlign=r.textAlign,s=r.label,l=r.textOffset,on(s))for(n=0,a=s.length;n<a;++n)u.fillText(""+s[n],0,l),l+=o.lineHeight;else u.fillText(s,0,l);u.restore()}}},_drawTitle:function(){var t=this,e=t.ctx,n=t.options,i=n.scaleLabel;if(i.display){var a,r,o=ln(i.fontColor,z.global.defaultFontColor),s=V.options._parseFont(i),l=V.options.toPadding(i.padding),u=s.lineHeight/2,d=n.position,h=0;if(t.isHorizontal())a=t.left+t.width/2,r="bottom"===d?t.bottom-u-l.bottom:t.top+u+l.top;else{var c="left"===d;a=c?t.left+u+l.top:t.right-u-l.top,r=t.top+t.height/2,h=c?-.5*Math.PI:.5*Math.PI}e.save(),e.translate(a,r),e.rotate(h),e.textAlign="center",e.textBaseline="middle",e.fillStyle=o,e.font=s.string,e.fillText(i.labelString,0,0),e.restore()}},draw:function(t){this._isVisible()&&(this._drawGrid(t),this._drawTitle(),this._drawLabels())},_layers:function(){var t=this,e=t.options,n=e.ticks&&e.ticks.z||0,i=e.gridLines&&e.gridLines.z||0;return t._isVisible()&&n!==i&&t.draw===t._draw?[{z:i,draw:function(){t._drawGrid.apply(t,arguments),t._drawTitle.apply(t,arguments)}},{z:n,draw:function(){t._drawLabels.apply(t,arguments)}}]:[{z:n,draw:function(){t.draw.apply(t,arguments)}}]},_getMatchingVisibleMetas:function(t){var e=this,n=e.isHorizontal();return e.chart._getSortedVisibleDatasetMetas().filter((function(i){return(!t||i.type===t)&&(n?i.xAxisID===e.id:i.yAxisID===e.id)}))}});bn.prototype._draw=bn.prototype.draw;var xn=bn,yn=V.isNullOrUndef,_n=xn.extend({determineDataLimits:function(){var t,e=this,n=e._getLabels(),i=e.options.ticks,a=i.min,r=i.max,o=0,s=n.length-1;void 0!==a&&(t=n.indexOf(a))>=0&&(o=t),void 0!==r&&(t=n.indexOf(r))>=0&&(s=t),e.minIndex=o,e.maxIndex=s,e.min=n[o],e.max=n[s]},buildTicks:function(){var t=this._getLabels(),e=this.minIndex,n=this.maxIndex;this.ticks=0===e&&n===t.length-1?t:t.slice(e,n+1)},getLabelForIndex:function(t,e){var n=this.chart;return n.getDatasetMeta(e).controller._getValueScaleId()===this.id?this.getRightValue(n.data.datasets[e].data[t]):this._getLabels()[t]},_configure:function(){var t=this,e=t.options.offset,n=t.ticks;xn.prototype._configure.call(t),t.isHorizontal()||(t._reversePixels=!t._reversePixels),n&&(t._startValue=t.minIndex-(e?.5:0),t._valueRange=Math.max(n.length-(e?0:1),1))},getPixelForValue:function(t,e,n){var i,a,r,o=this;return yn(e)||yn(n)||(t=o.chart.data.datasets[n].data[e]),yn(t)||(i=o.isHorizontal()?t.x:t.y),(void 0!==i||void 0!==t&&isNaN(e))&&(a=o._getLabels(),t=V.valueOrDefault(i,t),e=-1!==(r=a.indexOf(t))?r:e,isNaN(e)&&(e=t)),o.getPixelForDecimal((e-o._startValue)/o._valueRange)},getPixelForTick:function(t){var e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t],t+this.minIndex)},getValueForPixel:function(t){var e=Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange);return Math.min(Math.max(e,0),this.ticks.length-1)},getBasePixel:function(){return this.bottom}}),kn={position:"bottom"};_n._defaults=kn;var wn=V.noop,Mn=V.isNullOrUndef;var Sn=xn.extend({getRightValue:function(t){return"string"==typeof t?+t:xn.prototype.getRightValue.call(this,t)},handleTickRangeOptions:function(){var t=this,e=t.options.ticks;if(e.beginAtZero){var n=V.sign(t.min),i=V.sign(t.max);n<0&&i<0?t.max=0:n>0&&i>0&&(t.min=0)}var a=void 0!==e.min||void 0!==e.suggestedMin,r=void 0!==e.max||void 0!==e.suggestedMax;void 0!==e.min?t.min=e.min:void 0!==e.suggestedMin&&(null===t.min?t.min=e.suggestedMin:t.min=Math.min(t.min,e.suggestedMin)),void 0!==e.max?t.max=e.max:void 0!==e.suggestedMax&&(null===t.max?t.max=e.suggestedMax:t.max=Math.max(t.max,e.suggestedMax)),a!==r&&t.min>=t.max&&(a?t.max=t.min+1:t.min=t.max-1),t.min===t.max&&(t.max++,e.beginAtZero||t.min--)},getTickLimit:function(){var t,e=this.options.ticks,n=e.stepSize,i=e.maxTicksLimit;return n?t=Math.ceil(this.max/n)-Math.floor(this.min/n)+1:(t=this._computeTickLimit(),i=i||11),i&&(t=Math.min(i,t)),t},_computeTickLimit:function(){return Number.POSITIVE_INFINITY},handleDirectionalChanges:wn,buildTicks:function(){var t=this,e=t.options.ticks,n=t.getTickLimit(),i={maxTicks:n=Math.max(2,n),min:e.min,max:e.max,precision:e.precision,stepSize:V.valueOrDefault(e.fixedStepSize,e.stepSize)},a=t.ticks=function(t,e){var n,i,a,r,o=[],s=t.stepSize,l=s||1,u=t.maxTicks-1,d=t.min,h=t.max,c=t.precision,f=e.min,g=e.max,p=V.niceNum((g-f)/u/l)*l;if(p<1e-14&&Mn(d)&&Mn(h))return[f,g];(r=Math.ceil(g/p)-Math.floor(f/p))>u&&(p=V.niceNum(r*p/u/l)*l),s||Mn(c)?n=Math.pow(10,V._decimalPlaces(p)):(n=Math.pow(10,c),p=Math.ceil(p*n)/n),i=Math.floor(f/p)*p,a=Math.ceil(g/p)*p,s&&(!Mn(d)&&V.almostWhole(d/p,p/1e3)&&(i=d),!Mn(h)&&V.almostWhole(h/p,p/1e3)&&(a=h)),r=(a-i)/p,r=V.almostEquals(r,Math.round(r),p/1e3)?Math.round(r):Math.ceil(r),i=Math.round(i*n)/n,a=Math.round(a*n)/n,o.push(Mn(d)?i:d);for(var m=1;m<r;++m)o.push(Math.round((i+m*p)*n)/n);return o.push(Mn(h)?a:h),o}(i,t);t.handleDirectionalChanges(),t.max=V.max(a),t.min=V.min(a),e.reverse?(a.reverse(),t.start=t.max,t.end=t.min):(t.start=t.min,t.end=t.max)},convertTicksToLabels:function(){var t=this;t.ticksAsNumbers=t.ticks.slice(),t.zeroLineIndex=t.ticks.indexOf(0),xn.prototype.convertTicksToLabels.call(t)},_configure:function(){var t,e=this,n=e.getTicks(),i=e.min,a=e.max;xn.prototype._configure.call(e),e.options.offset&&n.length&&(i-=t=(a-i)/Math.max(n.length-1,1)/2,a+=t),e._startValue=i,e._endValue=a,e._valueRange=a-i}}),Cn={position:"left",ticks:{callback:rn.formatters.linear}};function Pn(t,e,n,i){var a,r,o=t.options,s=function(t,e,n){var i=[n.type,void 0===e&&void 0===n.stack?n.index:"",n.stack].join(".");return void 0===t[i]&&(t[i]={pos:[],neg:[]}),t[i]}(e,o.stacked,n),l=s.pos,u=s.neg,d=i.length;for(a=0;a<d;++a)r=t._parseValue(i[a]),isNaN(r.min)||isNaN(r.max)||n.data[a].hidden||(l[a]=l[a]||0,u[a]=u[a]||0,o.relativePoints?l[a]=100:r.min<0||r.max<0?u[a]+=r.min:l[a]+=r.max)}function An(t,e,n){var i,a,r=n.length;for(i=0;i<r;++i)a=t._parseValue(n[i]),isNaN(a.min)||isNaN(a.max)||e.data[i].hidden||(t.min=Math.min(t.min,a.min),t.max=Math.max(t.max,a.max))}var Dn=Sn.extend({determineDataLimits:function(){var t,e,n,i,a=this,r=a.options,o=a.chart.data.datasets,s=a._getMatchingVisibleMetas(),l=r.stacked,u={},d=s.length;if(a.min=Number.POSITIVE_INFINITY,a.max=Number.NEGATIVE_INFINITY,void 0===l)for(t=0;!l&&t<d;++t)l=void 0!==(e=s[t]).stack;for(t=0;t<d;++t)n=o[(e=s[t]).index].data,l?Pn(a,u,e,n):An(a,e,n);V.each(u,(function(t){i=t.pos.concat(t.neg),a.min=Math.min(a.min,V.min(i)),a.max=Math.max(a.max,V.max(i))})),a.min=V.isFinite(a.min)&&!isNaN(a.min)?a.min:0,a.max=V.isFinite(a.max)&&!isNaN(a.max)?a.max:1,a.handleTickRangeOptions()},_computeTickLimit:function(){var t;return this.isHorizontal()?Math.ceil(this.width/40):(t=V.options._parseFont(this.options.ticks),Math.ceil(this.height/t.lineHeight))},handleDirectionalChanges:function(){this.isHorizontal()||this.ticks.reverse()},getLabelForIndex:function(t,e){return this._getScaleLabel(this.chart.data.datasets[e].data[t])},getPixelForValue:function(t){return this.getPixelForDecimal((+this.getRightValue(t)-this._startValue)/this._valueRange)},getValueForPixel:function(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange},getPixelForTick:function(t){var e=this.ticksAsNumbers;return t<0||t>e.length-1?null:this.getPixelForValue(e[t])}}),Tn=Cn;Dn._defaults=Tn;var In=V.valueOrDefault,Fn=V.math.log10;var Ln={position:"left",ticks:{callback:rn.formatters.logarithmic}};function On(t,e){return V.isFinite(t)&&t>=0?t:e}var Rn=xn.extend({determineDataLimits:function(){var t,e,n,i,a,r,o=this,s=o.options,l=o.chart,u=l.data.datasets,d=o.isHorizontal();function h(t){return d?t.xAxisID===o.id:t.yAxisID===o.id}o.min=Number.POSITIVE_INFINITY,o.max=Number.NEGATIVE_INFINITY,o.minNotZero=Number.POSITIVE_INFINITY;var c=s.stacked;if(void 0===c)for(t=0;t<u.length;t++)if(e=l.getDatasetMeta(t),l.isDatasetVisible(t)&&h(e)&&void 0!==e.stack){c=!0;break}if(s.stacked||c){var f={};for(t=0;t<u.length;t++){var g=[(e=l.getDatasetMeta(t)).type,void 0===s.stacked&&void 0===e.stack?t:"",e.stack].join(".");if(l.isDatasetVisible(t)&&h(e))for(void 0===f[g]&&(f[g]=[]),a=0,r=(i=u[t].data).length;a<r;a++){var p=f[g];n=o._parseValue(i[a]),isNaN(n.min)||isNaN(n.max)||e.data[a].hidden||n.min<0||n.max<0||(p[a]=p[a]||0,p[a]+=n.max)}}V.each(f,(function(t){if(t.length>0){var e=V.min(t),n=V.max(t);o.min=Math.min(o.min,e),o.max=Math.max(o.max,n)}}))}else for(t=0;t<u.length;t++)if(e=l.getDatasetMeta(t),l.isDatasetVisible(t)&&h(e))for(a=0,r=(i=u[t].data).length;a<r;a++)n=o._parseValue(i[a]),isNaN(n.min)||isNaN(n.max)||e.data[a].hidden||n.min<0||n.max<0||(o.min=Math.min(n.min,o.min),o.max=Math.max(n.max,o.max),0!==n.min&&(o.minNotZero=Math.min(n.min,o.minNotZero)));o.min=V.isFinite(o.min)?o.min:null,o.max=V.isFinite(o.max)?o.max:null,o.minNotZero=V.isFinite(o.minNotZero)?o.minNotZero:null,this.handleTickRangeOptions()},handleTickRangeOptions:function(){var t=this,e=t.options.ticks;t.min=On(e.min,t.min),t.max=On(e.max,t.max),t.min===t.max&&(0!==t.min&&null!==t.min?(t.min=Math.pow(10,Math.floor(Fn(t.min))-1),t.max=Math.pow(10,Math.floor(Fn(t.max))+1)):(t.min=1,t.max=10)),null===t.min&&(t.min=Math.pow(10,Math.floor(Fn(t.max))-1)),null===t.max&&(t.max=0!==t.min?Math.pow(10,Math.floor(Fn(t.min))+1):10),null===t.minNotZero&&(t.min>0?t.minNotZero=t.min:t.max<1?t.minNotZero=Math.pow(10,Math.floor(Fn(t.max))):t.minNotZero=1)},buildTicks:function(){var t=this,e=t.options.ticks,n=!t.isHorizontal(),i={min:On(e.min),max:On(e.max)},a=t.ticks=function(t,e){var n,i,a=[],r=In(t.min,Math.pow(10,Math.floor(Fn(e.min)))),o=Math.floor(Fn(e.max)),s=Math.ceil(e.max/Math.pow(10,o));0===r?(n=Math.floor(Fn(e.minNotZero)),i=Math.floor(e.minNotZero/Math.pow(10,n)),a.push(r),r=i*Math.pow(10,n)):(n=Math.floor(Fn(r)),i=Math.floor(r/Math.pow(10,n)));var l=n<0?Math.pow(10,Math.abs(n)):1;do{a.push(r),10===++i&&(i=1,l=++n>=0?1:l),r=Math.round(i*Math.pow(10,n)*l)/l}while(n<o||n===o&&i<s);var u=In(t.max,r);return a.push(u),a}(i,t);t.max=V.max(a),t.min=V.min(a),e.reverse?(n=!n,t.start=t.max,t.end=t.min):(t.start=t.min,t.end=t.max),n&&a.reverse()},convertTicksToLabels:function(){this.tickValues=this.ticks.slice(),xn.prototype.convertTicksToLabels.call(this)},getLabelForIndex:function(t,e){return this._getScaleLabel(this.chart.data.datasets[e].data[t])},getPixelForTick:function(t){var e=this.tickValues;return t<0||t>e.length-1?null:this.getPixelForValue(e[t])},_getFirstTickValue:function(t){var e=Math.floor(Fn(t));return Math.floor(t/Math.pow(10,e))*Math.pow(10,e)},_configure:function(){var t=this,e=t.min,n=0;xn.prototype._configure.call(t),0===e&&(e=t._getFirstTickValue(t.minNotZero),n=In(t.options.ticks.fontSize,z.global.defaultFontSize)/t._length),t._startValue=Fn(e),t._valueOffset=n,t._valueRange=(Fn(t.max)-Fn(e))/(1-n)},getPixelForValue:function(t){var e=this,n=0;return(t=+e.getRightValue(t))>e.min&&t>0&&(n=(Fn(t)-e._startValue)/e._valueRange+e._valueOffset),e.getPixelForDecimal(n)},getValueForPixel:function(t){var e=this,n=e.getDecimalForPixel(t);return 0===n&&0===e.min?0:Math.pow(10,e._startValue+(n-e._valueOffset)*e._valueRange)}}),zn=Ln;Rn._defaults=zn;var Nn=V.valueOrDefault,Bn=V.valueAtIndexOrDefault,En=V.options.resolve,Wn={display:!0,animate:!0,position:"chartArea",angleLines:{display:!0,color:"rgba(0,0,0,0.1)",lineWidth:1,borderDash:[],borderDashOffset:0},gridLines:{circular:!1},ticks:{showLabelBackdrop:!0,backdropColor:"rgba(255,255,255,0.75)",backdropPaddingY:2,backdropPaddingX:2,callback:rn.formatters.linear},pointLabels:{display:!0,fontSize:10,callback:function(t){return t}}};function Vn(t){var e=t.ticks;return e.display&&t.display?Nn(e.fontSize,z.global.defaultFontSize)+2*e.backdropPaddingY:0}function Hn(t,e,n,i,a){return t===i||t===a?{start:e-n/2,end:e+n/2}:t<i||t>a?{start:e-n,end:e}:{start:e,end:e+n}}function jn(t){return 0===t||180===t?"center":t<180?"left":"right"}function qn(t,e,n,i){var a,r,o=n.y+i/2;if(V.isArray(e))for(a=0,r=e.length;a<r;++a)t.fillText(e[a],n.x,o),o+=i;else t.fillText(e,n.x,o)}function Un(t,e,n){90===t||270===t?n.y-=e.h/2:(t>270||t<90)&&(n.y-=e.h)}function Yn(t){return V.isNumber(t)?t:0}var Gn=Sn.extend({setDimensions:function(){var t=this;t.width=t.maxWidth,t.height=t.maxHeight,t.paddingTop=Vn(t.options)/2,t.xCenter=Math.floor(t.width/2),t.yCenter=Math.floor((t.height-t.paddingTop)/2),t.drawingArea=Math.min(t.height-t.paddingTop,t.width)/2},determineDataLimits:function(){var t=this,e=t.chart,n=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;V.each(e.data.datasets,(function(a,r){if(e.isDatasetVisible(r)){var o=e.getDatasetMeta(r);V.each(a.data,(function(e,a){var r=+t.getRightValue(e);isNaN(r)||o.data[a].hidden||(n=Math.min(r,n),i=Math.max(r,i))}))}})),t.min=n===Number.POSITIVE_INFINITY?0:n,t.max=i===Number.NEGATIVE_INFINITY?0:i,t.handleTickRangeOptions()},_computeTickLimit:function(){return Math.ceil(this.drawingArea/Vn(this.options))},convertTicksToLabels:function(){var t=this;Sn.prototype.convertTicksToLabels.call(t),t.pointLabels=t.chart.data.labels.map((function(){var e=V.callback(t.options.pointLabels.callback,arguments,t);return e||0===e?e:""}))},getLabelForIndex:function(t,e){return+this.getRightValue(this.chart.data.datasets[e].data[t])},fit:function(){var t=this.options;t.display&&t.pointLabels.display?function(t){var e,n,i,a=V.options._parseFont(t.options.pointLabels),r={l:0,r:t.width,t:0,b:t.height-t.paddingTop},o={};t.ctx.font=a.string,t._pointLabelSizes=[];var s,l,u,d=t.chart.data.labels.length;for(e=0;e<d;e++){i=t.getPointPosition(e,t.drawingArea+5),s=t.ctx,l=a.lineHeight,u=t.pointLabels[e],n=V.isArray(u)?{w:V.longestText(s,s.font,u),h:u.length*l}:{w:s.measureText(u).width,h:l},t._pointLabelSizes[e]=n;var h=t.getIndexAngle(e),c=V.toDegrees(h)%360,f=Hn(c,i.x,n.w,0,180),g=Hn(c,i.y,n.h,90,270);f.start<r.l&&(r.l=f.start,o.l=h),f.end>r.r&&(r.r=f.end,o.r=h),g.start<r.t&&(r.t=g.start,o.t=h),g.end>r.b&&(r.b=g.end,o.b=h)}t.setReductions(t.drawingArea,r,o)}(this):this.setCenterPoint(0,0,0,0)},setReductions:function(t,e,n){var i=this,a=e.l/Math.sin(n.l),r=Math.max(e.r-i.width,0)/Math.sin(n.r),o=-e.t/Math.cos(n.t),s=-Math.max(e.b-(i.height-i.paddingTop),0)/Math.cos(n.b);a=Yn(a),r=Yn(r),o=Yn(o),s=Yn(s),i.drawingArea=Math.min(Math.floor(t-(a+r)/2),Math.floor(t-(o+s)/2)),i.setCenterPoint(a,r,o,s)},setCenterPoint:function(t,e,n,i){var a=this,r=a.width-e-a.drawingArea,o=t+a.drawingArea,s=n+a.drawingArea,l=a.height-a.paddingTop-i-a.drawingArea;a.xCenter=Math.floor((o+r)/2+a.left),a.yCenter=Math.floor((s+l)/2+a.top+a.paddingTop)},getIndexAngle:function(t){var e=this.chart,n=(t*(360/e.data.labels.length)+((e.options||{}).startAngle||0))%360;return(n<0?n+360:n)*Math.PI*2/360},getDistanceFromCenterForValue:function(t){var e=this;if(V.isNullOrUndef(t))return NaN;var n=e.drawingArea/(e.max-e.min);return e.options.ticks.reverse?(e.max-t)*n:(t-e.min)*n},getPointPosition:function(t,e){var n=this.getIndexAngle(t)-Math.PI/2;return{x:Math.cos(n)*e+this.xCenter,y:Math.sin(n)*e+this.yCenter}},getPointPositionForValue:function(t,e){return this.getPointPosition(t,this.getDistanceFromCenterForValue(e))},getBasePosition:function(t){var e=this.min,n=this.max;return this.getPointPositionForValue(t||0,this.beginAtZero?0:e<0&&n<0?n:e>0&&n>0?e:0)},_drawGrid:function(){var t,e,n,i=this,a=i.ctx,r=i.options,o=r.gridLines,s=r.angleLines,l=Nn(s.lineWidth,o.lineWidth),u=Nn(s.color,o.color);if(r.pointLabels.display&&function(t){var e=t.ctx,n=t.options,i=n.pointLabels,a=Vn(n),r=t.getDistanceFromCenterForValue(n.ticks.reverse?t.min:t.max),o=V.options._parseFont(i);e.save(),e.font=o.string,e.textBaseline="middle";for(var s=t.chart.data.labels.length-1;s>=0;s--){var l=0===s?a/2:0,u=t.getPointPosition(s,r+l+5),d=Bn(i.fontColor,s,z.global.defaultFontColor);e.fillStyle=d;var h=t.getIndexAngle(s),c=V.toDegrees(h);e.textAlign=jn(c),Un(c,t._pointLabelSizes[s],u),qn(e,t.pointLabels[s],u,o.lineHeight)}e.restore()}(i),o.display&&V.each(i.ticks,(function(t,n){0!==n&&(e=i.getDistanceFromCenterForValue(i.ticksAsNumbers[n]),function(t,e,n,i){var a,r=t.ctx,o=e.circular,s=t.chart.data.labels.length,l=Bn(e.color,i-1),u=Bn(e.lineWidth,i-1);if((o||s)&&l&&u){if(r.save(),r.strokeStyle=l,r.lineWidth=u,r.setLineDash&&(r.setLineDash(e.borderDash||[]),r.lineDashOffset=e.borderDashOffset||0),r.beginPath(),o)r.arc(t.xCenter,t.yCenter,n,0,2*Math.PI);else{a=t.getPointPosition(0,n),r.moveTo(a.x,a.y);for(var d=1;d<s;d++)a=t.getPointPosition(d,n),r.lineTo(a.x,a.y)}r.closePath(),r.stroke(),r.restore()}}(i,o,e,n))})),s.display&&l&&u){for(a.save(),a.lineWidth=l,a.strokeStyle=u,a.setLineDash&&(a.setLineDash(En([s.borderDash,o.borderDash,[]])),a.lineDashOffset=En([s.borderDashOffset,o.borderDashOffset,0])),t=i.chart.data.labels.length-1;t>=0;t--)e=i.getDistanceFromCenterForValue(r.ticks.reverse?i.min:i.max),n=i.getPointPosition(t,e),a.beginPath(),a.moveTo(i.xCenter,i.yCenter),a.lineTo(n.x,n.y),a.stroke();a.restore()}},_drawLabels:function(){var t=this,e=t.ctx,n=t.options.ticks;if(n.display){var i,a,r=t.getIndexAngle(0),o=V.options._parseFont(n),s=Nn(n.fontColor,z.global.defaultFontColor);e.save(),e.font=o.string,e.translate(t.xCenter,t.yCenter),e.rotate(r),e.textAlign="center",e.textBaseline="middle",V.each(t.ticks,(function(r,l){(0!==l||n.reverse)&&(i=t.getDistanceFromCenterForValue(t.ticksAsNumbers[l]),n.showLabelBackdrop&&(a=e.measureText(r).width,e.fillStyle=n.backdropColor,e.fillRect(-a/2-n.backdropPaddingX,-i-o.size/2-n.backdropPaddingY,a+2*n.backdropPaddingX,o.size+2*n.backdropPaddingY)),e.fillStyle=s,e.fillText(r,0,-i))})),e.restore()}},_drawTitle:V.noop}),Xn=Wn;Gn._defaults=Xn;var Kn=V._deprecated,Zn=V.options.resolve,$n=V.valueOrDefault,Jn=Number.MIN_SAFE_INTEGER||-9007199254740991,Qn=Number.MAX_SAFE_INTEGER||9007199254740991,ti={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},ei=Object.keys(ti);function ni(t,e){return t-e}function ii(t){return V.valueOrDefault(t.time.min,t.ticks.min)}function ai(t){return V.valueOrDefault(t.time.max,t.ticks.max)}function ri(t,e,n,i){var a=function(t,e,n){for(var i,a,r,o=0,s=t.length-1;o>=0&&o<=s;){if(a=t[(i=o+s>>1)-1]||null,r=t[i],!a)return{lo:null,hi:r};if(r[e]<n)o=i+1;else{if(!(a[e]>n))return{lo:a,hi:r};s=i-1}}return{lo:r,hi:null}}(t,e,n),r=a.lo?a.hi?a.lo:t[t.length-2]:t[0],o=a.lo?a.hi?a.hi:t[t.length-1]:t[1],s=o[e]-r[e],l=s?(n-r[e])/s:0,u=(o[i]-r[i])*l;return r[i]+u}function oi(t,e){var n=t._adapter,i=t.options.time,a=i.parser,r=a||i.format,o=e;return"function"==typeof a&&(o=a(o)),V.isFinite(o)||(o="string"==typeof r?n.parse(o,r):n.parse(o)),null!==o?+o:(a||"function"!=typeof r||(o=r(e),V.isFinite(o)||(o=n.parse(o))),o)}function si(t,e){if(V.isNullOrUndef(e))return null;var n=t.options.time,i=oi(t,t.getRightValue(e));return null===i?i:(n.round&&(i=+t._adapter.startOf(i,n.round)),i)}function li(t,e,n,i){var a,r,o,s=ei.length;for(a=ei.indexOf(t);a<s-1;++a)if(o=(r=ti[ei[a]]).steps?r.steps:Qn,r.common&&Math.ceil((n-e)/(o*r.size))<=i)return ei[a];return ei[s-1]}function ui(t,e,n){var i,a,r=[],o={},s=e.length;for(i=0;i<s;++i)o[a=e[i]]=i,r.push({value:a,major:!1});return 0!==s&&n?function(t,e,n,i){var a,r,o=t._adapter,s=+o.startOf(e[0].value,i),l=e[e.length-1].value;for(a=s;a<=l;a=+o.add(a,1,i))(r=n[a])>=0&&(e[r].major=!0);return e}(t,r,o,n):r}var di=xn.extend({initialize:function(){this.mergeTicksOptions(),xn.prototype.initialize.call(this)},update:function(){var t=this,e=t.options,n=e.time||(e.time={}),i=t._adapter=new an._date(e.adapters.date);return Kn("time scale",n.format,"time.format","time.parser"),Kn("time scale",n.min,"time.min","ticks.min"),Kn("time scale",n.max,"time.max","ticks.max"),V.mergeIf(n.displayFormats,i.formats()),xn.prototype.update.apply(t,arguments)},getRightValue:function(t){return t&&void 0!==t.t&&(t=t.t),xn.prototype.getRightValue.call(this,t)},determineDataLimits:function(){var t,e,n,i,a,r,o,s=this,l=s.chart,u=s._adapter,d=s.options,h=d.time.unit||"day",c=Qn,f=Jn,g=[],p=[],m=[],v=s._getLabels();for(t=0,n=v.length;t<n;++t)m.push(si(s,v[t]));for(t=0,n=(l.data.datasets||[]).length;t<n;++t)if(l.isDatasetVisible(t))if(a=l.data.datasets[t].data,V.isObject(a[0]))for(p[t]=[],e=0,i=a.length;e<i;++e)r=si(s,a[e]),g.push(r),p[t][e]=r;else p[t]=m.slice(0),o||(g=g.concat(m),o=!0);else p[t]=[];m.length&&(c=Math.min(c,m[0]),f=Math.max(f,m[m.length-1])),g.length&&(g=n>1?function(t){var e,n,i,a={},r=[];for(e=0,n=t.length;e<n;++e)a[i=t[e]]||(a[i]=!0,r.push(i));return r}(g).sort(ni):g.sort(ni),c=Math.min(c,g[0]),f=Math.max(f,g[g.length-1])),c=si(s,ii(d))||c,f=si(s,ai(d))||f,c=c===Qn?+u.startOf(Date.now(),h):c,f=f===Jn?+u.endOf(Date.now(),h)+1:f,s.min=Math.min(c,f),s.max=Math.max(c+1,f),s._table=[],s._timestamps={data:g,datasets:p,labels:m}},buildTicks:function(){var t,e,n,i=this,a=i.min,r=i.max,o=i.options,s=o.ticks,l=o.time,u=i._timestamps,d=[],h=i.getLabelCapacity(a),c=s.source,f=o.distribution;for(u="data"===c||"auto"===c&&"series"===f?u.data:"labels"===c?u.labels:function(t,e,n,i){var a,r=t._adapter,o=t.options,s=o.time,l=s.unit||li(s.minUnit,e,n,i),u=Zn([s.stepSize,s.unitStepSize,1]),d="week"===l&&s.isoWeekday,h=e,c=[];if(d&&(h=+r.startOf(h,"isoWeek",d)),h=+r.startOf(h,d?"day":l),r.diff(n,e,l)>1e5*u)throw e+" and "+n+" are too far apart with stepSize of "+u+" "+l;for(a=h;a<n;a=+r.add(a,u,l))c.push(a);return a!==n&&"ticks"!==o.bounds||c.push(a),c}(i,a,r,h),"ticks"===o.bounds&&u.length&&(a=u[0],r=u[u.length-1]),a=si(i,ii(o))||a,r=si(i,ai(o))||r,t=0,e=u.length;t<e;++t)(n=u[t])>=a&&n<=r&&d.push(n);return i.min=a,i.max=r,i._unit=l.unit||(s.autoSkip?li(l.minUnit,i.min,i.max,h):function(t,e,n,i,a){var r,o;for(r=ei.length-1;r>=ei.indexOf(n);r--)if(o=ei[r],ti[o].common&&t._adapter.diff(a,i,o)>=e-1)return o;return ei[n?ei.indexOf(n):0]}(i,d.length,l.minUnit,i.min,i.max)),i._majorUnit=s.major.enabled&&"year"!==i._unit?function(t){for(var e=ei.indexOf(t)+1,n=ei.length;e<n;++e)if(ti[ei[e]].common)return ei[e]}(i._unit):void 0,i._table=function(t,e,n,i){if("linear"===i||!t.length)return[{time:e,pos:0},{time:n,pos:1}];var a,r,o,s,l,u=[],d=[e];for(a=0,r=t.length;a<r;++a)(s=t[a])>e&&s<n&&d.push(s);for(d.push(n),a=0,r=d.length;a<r;++a)l=d[a+1],o=d[a-1],s=d[a],void 0!==o&&void 0!==l&&Math.round((l+o)/2)===s||u.push({time:s,pos:a/(r-1)});return u}(i._timestamps.data,a,r,f),i._offsets=function(t,e,n,i,a){var r,o,s=0,l=0;return a.offset&&e.length&&(r=ri(t,"time",e[0],"pos"),s=1===e.length?1-r:(ri(t,"time",e[1],"pos")-r)/2,o=ri(t,"time",e[e.length-1],"pos"),l=1===e.length?o:(o-ri(t,"time",e[e.length-2],"pos"))/2),{start:s,end:l,factor:1/(s+1+l)}}(i._table,d,0,0,o),s.reverse&&d.reverse(),ui(i,d,i._majorUnit)},getLabelForIndex:function(t,e){var n=this,i=n._adapter,a=n.chart.data,r=n.options.time,o=a.labels&&t<a.labels.length?a.labels[t]:"",s=a.datasets[e].data[t];return V.isObject(s)&&(o=n.getRightValue(s)),r.tooltipFormat?i.format(oi(n,o),r.tooltipFormat):"string"==typeof o?o:i.format(oi(n,o),r.displayFormats.datetime)},tickFormatFunction:function(t,e,n,i){var a=this._adapter,r=this.options,o=r.time.displayFormats,s=o[this._unit],l=this._majorUnit,u=o[l],d=n[e],h=r.ticks,c=l&&u&&d&&d.major,f=a.format(t,i||(c?u:s)),g=c?h.major:h.minor,p=Zn([g.callback,g.userCallback,h.callback,h.userCallback]);return p?p(f,e,n):f},convertTicksToLabels:function(t){var e,n,i=[];for(e=0,n=t.length;e<n;++e)i.push(this.tickFormatFunction(t[e].value,e,t));return i},getPixelForOffset:function(t){var e=this._offsets,n=ri(this._table,"time",t,"pos");return this.getPixelForDecimal((e.start+n)*e.factor)},getPixelForValue:function(t,e,n){var i=null;if(void 0!==e&&void 0!==n&&(i=this._timestamps.datasets[n][e]),null===i&&(i=si(this,t)),null!==i)return this.getPixelForOffset(i)},getPixelForTick:function(t){var e=this.getTicks();return t>=0&&t<e.length?this.getPixelForOffset(e[t].value):null},getValueForPixel:function(t){var e=this._offsets,n=this.getDecimalForPixel(t)/e.factor-e.end,i=ri(this._table,"pos",n,"time");return this._adapter._create(i)},_getLabelSize:function(t){var e=this.options.ticks,n=this.ctx.measureText(t).width,i=V.toRadians(this.isHorizontal()?e.maxRotation:e.minRotation),a=Math.cos(i),r=Math.sin(i),o=$n(e.fontSize,z.global.defaultFontSize);return{w:n*a+o*r,h:n*r+o*a}},getLabelWidth:function(t){return this._getLabelSize(t).w},getLabelCapacity:function(t){var e=this,n=e.options.time,i=n.displayFormats,a=i[n.unit]||i.millisecond,r=e.tickFormatFunction(t,0,ui(e,[t],e._majorUnit),a),o=e._getLabelSize(r),s=Math.floor(e.isHorizontal()?e.width/o.w:e.height/o.h);return e.options.offset&&s--,s>0?s:1}}),hi={position:"bottom",distribution:"linear",bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,displayFormat:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{autoSkip:!1,source:"auto",major:{enabled:!1}}};di._defaults=hi;var ci={category:_n,linear:Dn,logarithmic:Rn,radialLinear:Gn,time:di},fi={datetime:"MMM D, YYYY, h:mm:ss a",millisecond:"h:mm:ss.SSS a",second:"h:mm:ss a",minute:"h:mm a",hour:"hA",day:"MMM D",week:"ll",month:"MMM YYYY",quarter:"[Q]Q - YYYY",year:"YYYY"};an._date.override("function"==typeof t?{_id:"moment",formats:function(){return fi},parse:function(e,n){return"string"==typeof e&&"string"==typeof n?e=t(e,n):e instanceof t||(e=t(e)),e.isValid()?e.valueOf():null},format:function(e,n){return t(e).format(n)},add:function(e,n,i){return t(e).add(n,i).valueOf()},diff:function(e,n,i){return t(e).diff(t(n),i)},startOf:function(e,n,i){return e=t(e),"isoWeek"===n?e.isoWeekday(i).valueOf():e.startOf(n).valueOf()},endOf:function(e,n){return t(e).endOf(n).valueOf()},_create:function(e){return t(e)}}:{}),z._set("global",{plugins:{filler:{propagate:!0}}});var gi={dataset:function(t){var e=t.fill,n=t.chart,i=n.getDatasetMeta(e),a=i&&n.isDatasetVisible(e)&&i.dataset._children||[],r=a.length||0;return r?function(t,e){return e<r&&a[e]._view||null}:null},boundary:function(t){var e=t.boundary,n=e?e.x:null,i=e?e.y:null;return V.isArray(e)?function(t,n){return e[n]}:function(t){return{x:null===n?t.x:n,y:null===i?t.y:i}}}};function pi(t,e,n){var i,a=t._model||{},r=a.fill;if(void 0===r&&(r=!!a.backgroundColor),!1===r||null===r)return!1;if(!0===r)return"origin";if(i=parseFloat(r,10),isFinite(i)&&Math.floor(i)===i)return"-"!==r[0]&&"+"!==r[0]||(i=e+i),!(i===e||i<0||i>=n)&&i;switch(r){case"bottom":return"start";case"top":return"end";case"zero":return"origin";case"origin":case"start":case"end":return r;default:return!1}}function mi(t){return(t.el._scale||{}).getPointPositionForValue?function(t){var e,n,i,a,r,o=t.el._scale,s=o.options,l=o.chart.data.labels.length,u=t.fill,d=[];if(!l)return null;for(e=s.ticks.reverse?o.max:o.min,n=s.ticks.reverse?o.min:o.max,i=o.getPointPositionForValue(0,e),a=0;a<l;++a)r="start"===u||"end"===u?o.getPointPositionForValue(a,"start"===u?e:n):o.getBasePosition(a),s.gridLines.circular&&(r.cx=i.x,r.cy=i.y,r.angle=o.getIndexAngle(a)-Math.PI/2),d.push(r);return d}(t):function(t){var e,n=t.el._model||{},i=t.el._scale||{},a=t.fill,r=null;if(isFinite(a))return null;if("start"===a?r=void 0===n.scaleBottom?i.bottom:n.scaleBottom:"end"===a?r=void 0===n.scaleTop?i.top:n.scaleTop:void 0!==n.scaleZero?r=n.scaleZero:i.getBasePixel&&(r=i.getBasePixel()),null!=r){if(void 0!==r.x&&void 0!==r.y)return r;if(V.isFinite(r))return{x:(e=i.isHorizontal())?r:null,y:e?null:r}}return null}(t)}function vi(t,e,n){var i,a=t[e].fill,r=[e];if(!n)return a;for(;!1!==a&&-1===r.indexOf(a);){if(!isFinite(a))return a;if(!(i=t[a]))return!1;if(i.visible)return a;r.push(a),a=i.fill}return!1}function bi(t){var e=t.fill,n="dataset";return!1===e?null:(isFinite(e)||(n="boundary"),gi[n](t))}function xi(t){return t&&!t.skip}function yi(t,e,n,i,a){var r,o,s,l;if(i&&a){for(t.moveTo(e[0].x,e[0].y),r=1;r<i;++r)V.canvas.lineTo(t,e[r-1],e[r]);if(void 0===n[0].angle)for(t.lineTo(n[a-1].x,n[a-1].y),r=a-1;r>0;--r)V.canvas.lineTo(t,n[r],n[r-1],!0);else for(o=n[0].cx,s=n[0].cy,l=Math.sqrt(Math.pow(n[0].x-o,2)+Math.pow(n[0].y-s,2)),r=a-1;r>0;--r)t.arc(o,s,l,n[r].angle,n[r-1].angle,!0)}}function _i(t,e,n,i,a,r){var o,s,l,u,d,h,c,f,g=e.length,p=i.spanGaps,m=[],v=[],b=0,x=0;for(t.beginPath(),o=0,s=g;o<s;++o)d=n(u=e[l=o%g]._view,l,i),h=xi(u),c=xi(d),r&&void 0===f&&h&&(s=g+(f=o+1)),h&&c?(b=m.push(u),x=v.push(d)):b&&x&&(p?(h&&m.push(u),c&&v.push(d)):(yi(t,m,v,b,x),b=x=0,m=[],v=[]));yi(t,m,v,b,x),t.closePath(),t.fillStyle=a,t.fill()}var ki={id:"filler",afterDatasetsUpdate:function(t,e){var n,i,a,r,o=(t.data.datasets||[]).length,s=e.propagate,l=[];for(i=0;i<o;++i)r=null,(a=(n=t.getDatasetMeta(i)).dataset)&&a._model&&a instanceof _t.Line&&(r={visible:t.isDatasetVisible(i),fill:pi(a,i,o),chart:t,el:a}),n.$filler=r,l.push(r);for(i=0;i<o;++i)(r=l[i])&&(r.fill=vi(l,i,s),r.boundary=mi(r),r.mapper=bi(r))},beforeDatasetsDraw:function(t){var e,n,i,a,r,o,s,l=t._getSortedVisibleDatasetMetas(),u=t.ctx;for(n=l.length-1;n>=0;--n)(e=l[n].$filler)&&e.visible&&(a=(i=e.el)._view,r=i._children||[],o=e.mapper,s=a.backgroundColor||z.global.defaultColor,o&&s&&r.length&&(V.canvas.clipArea(u,t.chartArea),_i(u,r,o,a,s,i._loop),V.canvas.unclipArea(u)))}},wi=V.rtl.getRtlAdapter,Mi=V.noop,Si=V.valueOrDefault;function Ci(t,e){return t.usePointStyle&&t.boxWidth>e?e:t.boxWidth}z._set("global",{legend:{display:!0,position:"top",align:"center",fullWidth:!0,reverse:!1,weight:1e3,onClick:function(t,e){var n=e.datasetIndex,i=this.chart,a=i.getDatasetMeta(n);a.hidden=null===a.hidden?!i.data.datasets[n].hidden:null,i.update()},onHover:null,onLeave:null,labels:{boxWidth:40,padding:10,generateLabels:function(t){var e=t.data.datasets,n=t.options.legend||{},i=n.labels&&n.labels.usePointStyle;return t._getSortedDatasetMetas().map((function(n){var a=n.controller.getStyle(i?0:void 0);return{text:e[n.index].label,fillStyle:a.backgroundColor,hidden:!t.isDatasetVisible(n.index),lineCap:a.borderCapStyle,lineDash:a.borderDash,lineDashOffset:a.borderDashOffset,lineJoin:a.borderJoinStyle,lineWidth:a.borderWidth,strokeStyle:a.borderColor,pointStyle:a.pointStyle,rotation:a.rotation,datasetIndex:n.index}}),this)}}},legendCallback:function(t){var e,n,i,a=document.createElement("ul"),r=t.data.datasets;for(a.setAttribute("class",t.id+"-legend"),e=0,n=r.length;e<n;e++)(i=a.appendChild(document.createElement("li"))).appendChild(document.createElement("span")).style.backgroundColor=r[e].backgroundColor,r[e].label&&i.appendChild(document.createTextNode(r[e].label));return a.outerHTML}});var Pi=X.extend({initialize:function(t){V.extend(this,t),this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1},beforeUpdate:Mi,update:function(t,e,n){var i=this;return i.beforeUpdate(),i.maxWidth=t,i.maxHeight=e,i.margins=n,i.beforeSetDimensions(),i.setDimensions(),i.afterSetDimensions(),i.beforeBuildLabels(),i.buildLabels(),i.afterBuildLabels(),i.beforeFit(),i.fit(),i.afterFit(),i.afterUpdate(),i.minSize},afterUpdate:Mi,beforeSetDimensions:Mi,setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0,t.minSize={width:0,height:0}},afterSetDimensions:Mi,beforeBuildLabels:Mi,buildLabels:function(){var t=this,e=t.options.labels||{},n=V.callback(e.generateLabels,[t.chart],t)||[];e.filter&&(n=n.filter((function(n){return e.filter(n,t.chart.data)}))),t.options.reverse&&n.reverse(),t.legendItems=n},afterBuildLabels:Mi,beforeFit:Mi,fit:function(){var t=this,e=t.options,n=e.labels,i=e.display,a=t.ctx,r=V.options._parseFont(n),o=r.size,s=t.legendHitBoxes=[],l=t.minSize,u=t.isHorizontal();if(u?(l.width=t.maxWidth,l.height=i?10:0):(l.width=i?10:0,l.height=t.maxHeight),i){if(a.font=r.string,u){var d=t.lineWidths=[0],h=0;a.textAlign="left",a.textBaseline="middle",V.each(t.legendItems,(function(t,e){var i=Ci(n,o)+o/2+a.measureText(t.text).width;(0===e||d[d.length-1]+i+2*n.padding>l.width)&&(h+=o+n.padding,d[d.length-(e>0?0:1)]=0),s[e]={left:0,top:0,width:i,height:o},d[d.length-1]+=i+n.padding})),l.height+=h}else{var c=n.padding,f=t.columnWidths=[],g=t.columnHeights=[],p=n.padding,m=0,v=0;V.each(t.legendItems,(function(t,e){var i=Ci(n,o)+o/2+a.measureText(t.text).width;e>0&&v+o+2*c>l.height&&(p+=m+n.padding,f.push(m),g.push(v),m=0,v=0),m=Math.max(m,i),v+=o+c,s[e]={left:0,top:0,width:i,height:o}})),p+=m,f.push(m),g.push(v),l.width+=p}t.width=l.width,t.height=l.height}else t.width=l.width=t.height=l.height=0},afterFit:Mi,isHorizontal:function(){return"top"===this.options.position||"bottom"===this.options.position},draw:function(){var t=this,e=t.options,n=e.labels,i=z.global,a=i.defaultColor,r=i.elements.line,o=t.height,s=t.columnHeights,l=t.width,u=t.lineWidths;if(e.display){var d,h=wi(e.rtl,t.left,t.minSize.width),c=t.ctx,f=Si(n.fontColor,i.defaultFontColor),g=V.options._parseFont(n),p=g.size;c.textAlign=h.textAlign("left"),c.textBaseline="middle",c.lineWidth=.5,c.strokeStyle=f,c.fillStyle=f,c.font=g.string;var m=Ci(n,p),v=t.legendHitBoxes,b=function(t,i){switch(e.align){case"start":return n.padding;case"end":return t-i;default:return(t-i+n.padding)/2}},x=t.isHorizontal();d=x?{x:t.left+b(l,u[0]),y:t.top+n.padding,line:0}:{x:t.left+n.padding,y:t.top+b(o,s[0]),line:0},V.rtl.overrideTextDirection(t.ctx,e.textDirection);var y=p+n.padding;V.each(t.legendItems,(function(e,i){var f=c.measureText(e.text).width,g=m+p/2+f,_=d.x,k=d.y;h.setWidth(t.minSize.width),x?i>0&&_+g+n.padding>t.left+t.minSize.width&&(k=d.y+=y,d.line++,_=d.x=t.left+b(l,u[d.line])):i>0&&k+y>t.top+t.minSize.height&&(_=d.x=_+t.columnWidths[d.line]+n.padding,d.line++,k=d.y=t.top+b(o,s[d.line]));var w=h.x(_);!function(t,e,i){if(!(isNaN(m)||m<=0)){c.save();var o=Si(i.lineWidth,r.borderWidth);if(c.fillStyle=Si(i.fillStyle,a),c.lineCap=Si(i.lineCap,r.borderCapStyle),c.lineDashOffset=Si(i.lineDashOffset,r.borderDashOffset),c.lineJoin=Si(i.lineJoin,r.borderJoinStyle),c.lineWidth=o,c.strokeStyle=Si(i.strokeStyle,a),c.setLineDash&&c.setLineDash(Si(i.lineDash,r.borderDash)),n&&n.usePointStyle){var s=m*Math.SQRT2/2,l=h.xPlus(t,m/2),u=e+p/2;V.canvas.drawPoint(c,i.pointStyle,s,l,u,i.rotation)}else c.fillRect(h.leftForLtr(t,m),e,m,p),0!==o&&c.strokeRect(h.leftForLtr(t,m),e,m,p);c.restore()}}(w,k,e),v[i].left=h.leftForLtr(w,v[i].width),v[i].top=k,function(t,e,n,i){var a=p/2,r=h.xPlus(t,m+a),o=e+a;c.fillText(n.text,r,o),n.hidden&&(c.beginPath(),c.lineWidth=2,c.moveTo(r,o),c.lineTo(h.xPlus(r,i),o),c.stroke())}(w,k,e,f),x?d.x+=g+n.padding:d.y+=y})),V.rtl.restoreTextDirection(t.ctx,e.textDirection)}},_getLegendItemAt:function(t,e){var n,i,a,r=this;if(t>=r.left&&t<=r.right&&e>=r.top&&e<=r.bottom)for(a=r.legendHitBoxes,n=0;n<a.length;++n)if(t>=(i=a[n]).left&&t<=i.left+i.width&&e>=i.top&&e<=i.top+i.height)return r.legendItems[n];return null},handleEvent:function(t){var e,n=this,i=n.options,a="mouseup"===t.type?"click":t.type;if("mousemove"===a){if(!i.onHover&&!i.onLeave)return}else{if("click"!==a)return;if(!i.onClick)return}e=n._getLegendItemAt(t.x,t.y),"click"===a?e&&i.onClick&&i.onClick.call(n,t.native,e):(i.onLeave&&e!==n._hoveredItem&&(n._hoveredItem&&i.onLeave.call(n,t.native,n._hoveredItem),n._hoveredItem=e),i.onHover&&e&&i.onHover.call(n,t.native,e))}});function Ai(t,e){var n=new Pi({ctx:t.ctx,options:e,chart:t});ge.configure(t,n,e),ge.addBox(t,n),t.legend=n}var Di={id:"legend",_element:Pi,beforeInit:function(t){var e=t.options.legend;e&&Ai(t,e)},beforeUpdate:function(t){var e=t.options.legend,n=t.legend;e?(V.mergeIf(e,z.global.legend),n?(ge.configure(t,n,e),n.options=e):Ai(t,e)):n&&(ge.removeBox(t,n),delete t.legend)},afterEvent:function(t,e){var n=t.legend;n&&n.handleEvent(e)}},Ti=V.noop;z._set("global",{title:{display:!1,fontStyle:"bold",fullWidth:!0,padding:10,position:"top",text:"",weight:2e3}});var Ii=X.extend({initialize:function(t){V.extend(this,t),this.legendHitBoxes=[]},beforeUpdate:Ti,update:function(t,e,n){var i=this;return i.beforeUpdate(),i.maxWidth=t,i.maxHeight=e,i.margins=n,i.beforeSetDimensions(),i.setDimensions(),i.afterSetDimensions(),i.beforeBuildLabels(),i.buildLabels(),i.afterBuildLabels(),i.beforeFit(),i.fit(),i.afterFit(),i.afterUpdate(),i.minSize},afterUpdate:Ti,beforeSetDimensions:Ti,setDimensions:function(){var t=this;t.isHorizontal()?(t.width=t.maxWidth,t.left=0,t.right=t.width):(t.height=t.maxHeight,t.top=0,t.bottom=t.height),t.paddingLeft=0,t.paddingTop=0,t.paddingRight=0,t.paddingBottom=0,t.minSize={width:0,height:0}},afterSetDimensions:Ti,beforeBuildLabels:Ti,buildLabels:Ti,afterBuildLabels:Ti,beforeFit:Ti,fit:function(){var t,e=this,n=e.options,i=e.minSize={},a=e.isHorizontal();n.display?(t=(V.isArray(n.text)?n.text.length:1)*V.options._parseFont(n).lineHeight+2*n.padding,e.width=i.width=a?e.maxWidth:t,e.height=i.height=a?t:e.maxHeight):e.width=i.width=e.height=i.height=0},afterFit:Ti,isHorizontal:function(){var t=this.options.position;return"top"===t||"bottom"===t},draw:function(){var t=this,e=t.ctx,n=t.options;if(n.display){var i,a,r,o=V.options._parseFont(n),s=o.lineHeight,l=s/2+n.padding,u=0,d=t.top,h=t.left,c=t.bottom,f=t.right;e.fillStyle=V.valueOrDefault(n.fontColor,z.global.defaultFontColor),e.font=o.string,t.isHorizontal()?(a=h+(f-h)/2,r=d+l,i=f-h):(a="left"===n.position?h+l:f-l,r=d+(c-d)/2,i=c-d,u=Math.PI*("left"===n.position?-.5:.5)),e.save(),e.translate(a,r),e.rotate(u),e.textAlign="center",e.textBaseline="middle";var g=n.text;if(V.isArray(g))for(var p=0,m=0;m<g.length;++m)e.fillText(g[m],0,p,i),p+=s;else e.fillText(g,0,0,i);e.restore()}}});function Fi(t,e){var n=new Ii({ctx:t.ctx,options:e,chart:t});ge.configure(t,n,e),ge.addBox(t,n),t.titleBlock=n}var Li={},Oi=ki,Ri=Di,zi={id:"title",_element:Ii,beforeInit:function(t){var e=t.options.title;e&&Fi(t,e)},beforeUpdate:function(t){var e=t.options.title,n=t.titleBlock;e?(V.mergeIf(e,z.global.title),n?(ge.configure(t,n,e),n.options=e):Fi(t,e)):n&&(ge.removeBox(t,n),delete t.titleBlock)}};for(var Ni in Li.filler=Oi,Li.legend=Ri,Li.title=zi,tn.helpers=V,function(){function t(t,e,n){var i;return"string"==typeof t?(i=parseInt(t,10),-1!==t.indexOf("%")&&(i=i/100*e.parentNode[n])):i=t,i}function e(t){return null!=t&&"none"!==t}function n(n,i,a){var r=document.defaultView,o=V._getParentNode(n),s=r.getComputedStyle(n)[i],l=r.getComputedStyle(o)[i],u=e(s),d=e(l),h=Number.POSITIVE_INFINITY;return u||d?Math.min(u?t(s,n,a):h,d?t(l,o,a):h):"none"}V.where=function(t,e){if(V.isArray(t)&&Array.prototype.filter)return t.filter(e);var n=[];return V.each(t,(function(t){e(t)&&n.push(t)})),n},V.findIndex=Array.prototype.findIndex?function(t,e,n){return t.findIndex(e,n)}:function(t,e,n){n=void 0===n?t:n;for(var i=0,a=t.length;i<a;++i)if(e.call(n,t[i],i,t))return i;return-1},V.findNextWhere=function(t,e,n){V.isNullOrUndef(n)&&(n=-1);for(var i=n+1;i<t.length;i++){var a=t[i];if(e(a))return a}},V.findPreviousWhere=function(t,e,n){V.isNullOrUndef(n)&&(n=t.length);for(var i=n-1;i>=0;i--){var a=t[i];if(e(a))return a}},V.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},V.almostEquals=function(t,e,n){return Math.abs(t-e)<n},V.almostWhole=function(t,e){var n=Math.round(t);return n-e<=t&&n+e>=t},V.max=function(t){return t.reduce((function(t,e){return isNaN(e)?t:Math.max(t,e)}),Number.NEGATIVE_INFINITY)},V.min=function(t){return t.reduce((function(t,e){return isNaN(e)?t:Math.min(t,e)}),Number.POSITIVE_INFINITY)},V.sign=Math.sign?function(t){return Math.sign(t)}:function(t){return 0===(t=+t)||isNaN(t)?t:t>0?1:-1},V.toRadians=function(t){return t*(Math.PI/180)},V.toDegrees=function(t){return t*(180/Math.PI)},V._decimalPlaces=function(t){if(V.isFinite(t)){for(var e=1,n=0;Math.round(t*e)/e!==t;)e*=10,n++;return n}},V.getAngleFromPoint=function(t,e){var n=e.x-t.x,i=e.y-t.y,a=Math.sqrt(n*n+i*i),r=Math.atan2(i,n);return r<-.5*Math.PI&&(r+=2*Math.PI),{angle:r,distance:a}},V.distanceBetweenPoints=function(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))},V.aliasPixel=function(t){return t%2==0?0:.5},V._alignPixel=function(t,e,n){var i=t.currentDevicePixelRatio,a=n/2;return Math.round((e-a)*i)/i+a},V.splineCurve=function(t,e,n,i){var a=t.skip?e:t,r=e,o=n.skip?e:n,s=Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.y,2)),l=Math.sqrt(Math.pow(o.x-r.x,2)+Math.pow(o.y-r.y,2)),u=s/(s+l),d=l/(s+l),h=i*(u=isNaN(u)?0:u),c=i*(d=isNaN(d)?0:d);return{previous:{x:r.x-h*(o.x-a.x),y:r.y-h*(o.y-a.y)},next:{x:r.x+c*(o.x-a.x),y:r.y+c*(o.y-a.y)}}},V.EPSILON=Number.EPSILON||1e-14,V.splineCurveMonotone=function(t){var e,n,i,a,r,o,s,l,u,d=(t||[]).map((function(t){return{model:t._model,deltaK:0,mK:0}})),h=d.length;for(e=0;e<h;++e)if(!(i=d[e]).model.skip){if(n=e>0?d[e-1]:null,(a=e<h-1?d[e+1]:null)&&!a.model.skip){var c=a.model.x-i.model.x;i.deltaK=0!==c?(a.model.y-i.model.y)/c:0}!n||n.model.skip?i.mK=i.deltaK:!a||a.model.skip?i.mK=n.deltaK:this.sign(n.deltaK)!==this.sign(i.deltaK)?i.mK=0:i.mK=(n.deltaK+i.deltaK)/2}for(e=0;e<h-1;++e)i=d[e],a=d[e+1],i.model.skip||a.model.skip||(V.almostEquals(i.deltaK,0,this.EPSILON)?i.mK=a.mK=0:(r=i.mK/i.deltaK,o=a.mK/i.deltaK,(l=Math.pow(r,2)+Math.pow(o,2))<=9||(s=3/Math.sqrt(l),i.mK=r*s*i.deltaK,a.mK=o*s*i.deltaK)));for(e=0;e<h;++e)(i=d[e]).model.skip||(n=e>0?d[e-1]:null,a=e<h-1?d[e+1]:null,n&&!n.model.skip&&(u=(i.model.x-n.model.x)/3,i.model.controlPointPreviousX=i.model.x-u,i.model.controlPointPreviousY=i.model.y-u*i.mK),a&&!a.model.skip&&(u=(a.model.x-i.model.x)/3,i.model.controlPointNextX=i.model.x+u,i.model.controlPointNextY=i.model.y+u*i.mK))},V.nextItem=function(t,e,n){return n?e>=t.length-1?t[0]:t[e+1]:e>=t.length-1?t[t.length-1]:t[e+1]},V.previousItem=function(t,e,n){return n?e<=0?t[t.length-1]:t[e-1]:e<=0?t[0]:t[e-1]},V.niceNum=function(t,e){var n=Math.floor(V.log10(t)),i=t/Math.pow(10,n);return(e?i<1.5?1:i<3?2:i<7?5:10:i<=1?1:i<=2?2:i<=5?5:10)*Math.pow(10,n)},V.requestAnimFrame="undefined"==typeof window?function(t){t()}:window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)},V.getRelativePosition=function(t,e){var n,i,a=t.originalEvent||t,r=t.target||t.srcElement,o=r.getBoundingClientRect(),s=a.touches;s&&s.length>0?(n=s[0].clientX,i=s[0].clientY):(n=a.clientX,i=a.clientY);var l=parseFloat(V.getStyle(r,"padding-left")),u=parseFloat(V.getStyle(r,"padding-top")),d=parseFloat(V.getStyle(r,"padding-right")),h=parseFloat(V.getStyle(r,"padding-bottom")),c=o.right-o.left-l-d,f=o.bottom-o.top-u-h;return{x:n=Math.round((n-o.left-l)/c*r.width/e.currentDevicePixelRatio),y:i=Math.round((i-o.top-u)/f*r.height/e.currentDevicePixelRatio)}},V.getConstraintWidth=function(t){return n(t,"max-width","clientWidth")},V.getConstraintHeight=function(t){return n(t,"max-height","clientHeight")},V._calculatePadding=function(t,e,n){return(e=V.getStyle(t,e)).indexOf("%")>-1?n*parseInt(e,10)/100:parseInt(e,10)},V._getParentNode=function(t){var e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e},V.getMaximumWidth=function(t){var e=V._getParentNode(t);if(!e)return t.clientWidth;var n=e.clientWidth,i=n-V._calculatePadding(e,"padding-left",n)-V._calculatePadding(e,"padding-right",n),a=V.getConstraintWidth(t);return isNaN(a)?i:Math.min(i,a)},V.getMaximumHeight=function(t){var e=V._getParentNode(t);if(!e)return t.clientHeight;var n=e.clientHeight,i=n-V._calculatePadding(e,"padding-top",n)-V._calculatePadding(e,"padding-bottom",n),a=V.getConstraintHeight(t);return isNaN(a)?i:Math.min(i,a)},V.getStyle=function(t,e){return t.currentStyle?t.currentStyle[e]:document.defaultView.getComputedStyle(t,null).getPropertyValue(e)},V.retinaScale=function(t,e){var n=t.currentDevicePixelRatio=e||"undefined"!=typeof window&&window.devicePixelRatio||1;if(1!==n){var i=t.canvas,a=t.height,r=t.width;i.height=a*n,i.width=r*n,t.ctx.scale(n,n),i.style.height||i.style.width||(i.style.height=a+"px",i.style.width=r+"px")}},V.fontString=function(t,e,n){return e+" "+t+"px "+n},V.longestText=function(t,e,n,i){var a=(i=i||{}).data=i.data||{},r=i.garbageCollect=i.garbageCollect||[];i.font!==e&&(a=i.data={},r=i.garbageCollect=[],i.font=e),t.font=e;var o,s,l,u,d,h=0,c=n.length;for(o=0;o<c;o++)if(null!=(u=n[o])&&!0!==V.isArray(u))h=V.measureText(t,a,r,h,u);else if(V.isArray(u))for(s=0,l=u.length;s<l;s++)null==(d=u[s])||V.isArray(d)||(h=V.measureText(t,a,r,h,d));var f=r.length/2;if(f>n.length){for(o=0;o<f;o++)delete a[r[o]];r.splice(0,f)}return h},V.measureText=function(t,e,n,i,a){var r=e[a];return r||(r=e[a]=t.measureText(a).width,n.push(a)),r>i&&(i=r),i},V.numberOfLabelLines=function(t){var e=1;return V.each(t,(function(t){V.isArray(t)&&t.length>e&&(e=t.length)})),e},V.color=k?function(t){return t instanceof CanvasGradient&&(t=z.global.defaultColor),k(t)}:function(t){return console.error("Color.js not found!"),t},V.getHoverColor=function(t){return t instanceof CanvasPattern||t instanceof CanvasGradient?t:V.color(t).saturate(.5).darken(.1).rgbString()}}(),tn._adapters=an,tn.Animation=Z,tn.animationService=$,tn.controllers=$t,tn.DatasetController=nt,tn.defaults=z,tn.Element=X,tn.elements=_t,tn.Interaction=ae,tn.layouts=ge,tn.platform=Fe,tn.plugins=Le,tn.Scale=xn,tn.scaleService=Oe,tn.Ticks=rn,tn.Tooltip=Ue,tn.helpers.each(ci,(function(t,e){tn.scaleService.registerScaleType(e,t,t._defaults)})),Li)Li.hasOwnProperty(Ni)&&tn.plugins.register(Li[Ni]);tn.platform.initialize();var Bi=tn;return"undefined"!=typeof window&&(window.Chart=tn),tn.Chart=tn,tn.Legend=Li.legend._element,tn.Title=Li.title._element,tn.pluginService=tn.plugins,tn.PluginBase=tn.Element.extend({}),tn.canvasHelpers=tn.helpers.canvas,tn.layoutService=tn.layouts,tn.LinearScaleBase=Sn,tn.helpers.each(["Bar","Bubble","Doughnut","Line","PolarArea","Radar","Scatter"],(function(t){tn[t]=function(e,n){return new tn(e,tn.helpers.merge(n||{},{type:t.charAt(0).toLowerCase()+t.slice(1)}))}})),Bi}));`
func ChartJS() io.Reader {
return strings.NewReader(chartjs)
}
| }
if chartfindjs == "chart.js" {
return ChartJS()
}
return nil
} | func ChartFindJS(chartfindjs string) io.Reader {
if strings.LastIndex(chartfindjs, "/") >= 0 {
chartfindjs = chartfindjs[strings.LastIndex(chartfindjs, "/")+1:] |
encryption.py | class cryto:
def decryp_Vige() :
|
def encryp_Vige() :
plaintext=input("plaintext=")
key=input("key=")
print()
print("cyphertext=",end='')
j=0
for i in plaintext :
c=ord(key[j])
if c < 97 :
c=c+32
c=c-97
x=ord(i)-26
if x < 65 :
x=x+c
if x < 65 :
x=x+26
else :
x=x+c
if x < 97 :
x=x+26
print(chr(x),end='')
j=j+1
print("\n")
def Make_a_rsa() :
print("公鑰(n,e) 只能加密小於n的整数m!!!")
while(1) :
p,q=map(int,input("choose two Prime number :(split with space)").split())
if p > 1 :
t=0
for i in range ( 2 , p ) :
if ( p % i ) == 0 :
print ( "請輸入質數",end="")
t=1
break
if t == 1 :
continue
if q > 1 :
t=0
for i in range ( 2 , q ) :
if ( q % i ) == 0 :
print ( "請輸入質數",end="")
t=1
break
if t == 1 :
continue
break
n=p*q
r=(p-1)*(q-1)
e=0
d=0
for i in range ( 2 , r ) :
if ( r-int(r/i)*i ) == 1 :
e=i
break
for i in range ( 2 , r ) :
if ( (i*e) % r ) == 1 :
d=i
break
print("Public key(N,e)=({0},{1})\nPrivate key(N,d)=({2},{3})".format(n, e, n, d))
def rsa_send() :
import math
import array as arr
n,k=map(int,input("input your key :(split with space)").split())
name=input("enter the path of your bin :(Don't use the used name of bin!)")
output_file = open(name+".bin", 'wb')
text=input("plaintext/cyphertext=")
fb=[]
for i in text :
i=ord(i)
i=pow(i,k,n)
fb.append(i)
int_array = arr.array('i', fb)
int_array.tofile(output_file)
output_file.close()
def rsa_read() :
n,k=map(int,input("input your key :(split with space)").split())
name=input("enter the path of your bin :")
with open(name + ".bin" , 'rb') as file:
int_bytes = file.read()
for i in int_bytes :
if i == 0 :
continue
i=pow(i,k,n)
print(chr(i), end="")
def linr_radom() :
text=input("plaintext/cyphertext=")
LFSR=input("LFSR_4=")
print()
print("cyphertext/plaintext=",end='')
a=int(LFSR[0])
b=int(LFSR[1])
c=int(LFSR[2])
d=int(LFSR[3])
for i in text :
print(int(i) ^ a,end="")
t= a ^ d
d=a
a=b
b=c
c=t
print()
def wood_decry() :
text=input("input the cryto :")
n=0
for i in text :
if n%4==0 :
print(i,end="")
n=n+1
def wood_encry() :
import random
text=input("input the plaintext :")
l=[]
for i in range(48,122) :
if (i>48 and i<57) or (i>65 and i<90) or (i>97 and i<122) :
l.append(i)
for i in text :
print(i,end="")
for j in range(3) :
r=random.choice(l)
print(chr(r),end="")
| cyphertext=input("cyphertext=")
key=input("key=")
print("plaintext=",end='')
j=0
for i in cyphertext :
c=ord(key[j])
if c < 97 :
c=c+32
c=c-97
x=ord(i)+26
if x < 123 :
x=x-c
if x > 90 :
x=x-26
else :
x=x-c
if x > 122 :
x=x-26
print(chr(x),end='')
j=j+1
print("\n") |
delete-scheduled-message-response.DTO.ts | import { Equals, IsInt } from 'class-validator';
export class DeleteScheduledMessageResponseDTO {
@IsInt() | @Equals(undefined)
body: undefined;
} | @Equals(204)
status!: number;
|
_compile_spec.py | from typing import List, Dict, Any
import torch
import trtorch._C
from trtorch import _types
def _supported_input_size_type(input_size: Any) -> bool:
if isinstance(input_size, torch.Size):
return True
elif isinstance(input_size, tuple):
return True
elif isinstance(input_size, list):
return True
else:
raise TypeError(
"Input sizes for inputs are required to be a List, tuple or torch.Size or a Dict of three sizes (min, opt, max), found type: "
+ str(type(input_size)))
def _parse_input_ranges(input_sizes: List) -> List:
if any(not isinstance(i, dict) and not _supported_input_size_type(i) for i in input_sizes):
raise KeyError("An input size must either be a static size or a range of three sizes (min, opt, max) as Dict")
parsed_input_sizes = []
for i in input_sizes:
if isinstance(i, dict):
if all(k in i for k in ["min", "opt", "min"]):
in_range = trtorch._C.InputRange()
in_range.min = i["min"]
in_range.opt = i["opt"]
in_range.max = i["max"]
parsed_input_sizes.append(in_range)
elif "opt" in i:
in_range = trtorch._C.InputRange()
in_range.min = i["opt"]
in_range.opt = i["opt"]
in_range.max = i["opt"]
parsed_input_sizes.append(in_range)
else:
raise KeyError(
"An input size must either be a static size or a range of three sizes (min, opt, max) as Dict")
elif isinstance(i, list):
in_range = trtorch._C.InputRange()
in_range.min = i
in_range.opt = i
in_range.max = i
parsed_input_sizes.append(in_range)
elif isinstance(i, tuple):
in_range = trtorch._C.InputRange()
in_range.min = list(i)
in_range.opt = list(i)
in_range.max = list(i)
parsed_input_sizes.append(in_range)
return parsed_input_sizes
def _parse_op_precision(precision: Any) -> _types.dtype:
if isinstance(precision, torch.dtype):
if precision == torch.int8:
return _types.dtype.int8
elif precision == torch.half:
return _types.dtype.half
elif precision == torch.float:
return _types.dtype.float
else:
raise TypeError("Provided an unsupported dtype as operating precision (support: int8, half, float), got: " +
str(precision))
elif isinstance(precision, _types.DataTypes):
return precision
else:
raise TypeError("Op precision type needs to be specified with a torch.dtype or a trtorch.dtype, got: " +
str(type(precision)))
def _parse_device_type(device: Any) -> _types.DeviceType:
if isinstance(device, torch.device):
if device.type == 'cuda':
return _types.DeviceType.gpu
else:
ValueError("Got a device type other than GPU or DLA (type: " + str(device.type) + ")")
elif isinstance(device, _types.DeviceType):
return device
elif isinstance(device, str):
if device == "gpu" or device == "GPU":
return _types.DeviceType.gpu
elif device == "dla" or device == "DLA":
return _types.DeviceType.dla
else:
ValueError("Got a device type other than GPU or DLA (type: " + str(device) + ")")
else:
raise TypeError("Device specification must be of type torch.device, string or trtorch.DeviceType, but got: " +
str(type(device)))
def _parse_compile_spec(compile_spec: Dict[str, Any]) -> trtorch._C.CompileSpec:
info = trtorch._C.CompileSpec()
if "input_shapes" not in compile_spec:
raise KeyError(
"Input shapes for inputs are required as a List, provided as either a static sizes or a range of three sizes (min, opt, max) as Dict"
)
info.input_ranges = _parse_input_ranges(compile_spec["input_shapes"])
if "op_precision" in compile_spec:
info.op_precision = _parse_op_precision(compile_spec["op_precision"])
if "refit" in compile_spec:
assert isinstance(compile_spec["refit"], bool)
info.refit = compile_spec["refit"]
if "debug" in compile_spec:
assert isinstance(compile_spec["debug"], bool)
info.debug = compile_spec["debug"]
if "strict_types" in compile_spec:
assert isinstance(compile_spec["strict_types"], bool)
info.strict_types = compile_spec["strict_types"]
if "allow_gpu_fallback" in compile_spec:
assert isinstance(compile_spec["allow_gpu_fallback"], bool)
info.allow_gpu_fallback = compile_spec["allow_gpu_fallback"]
if "device_type" in compile_spec:
info.device = _parse_device_type(compile_spec["device_type"])
if "capability" in compile_spec:
assert isinstance(compile_spec["capability"], _types.EngineCapability)
info.capability = compile_spec["capability"]
if "num_min_timing_iters" in compile_spec:
assert type(compile_spec["num_min_timing_iters"]) is int
info.num_min_timing_iters = compile_spec["num_min_timing_iters"] | assert type(compile_spec["num_avg_timing_iters"]) is int
info.num_avg_timing_iters = compile_spec["num_avg_timing_iters"]
if "workspace_size" in compile_spec:
assert type(compile_spec["workspace_size"]) is int
info.workspace_size = compile_spec["workspace_size"]
if "max_batch_size" in compile_spec:
assert type(compile_spec["max_batch_size"]) is int
info.max_batch_size = compile_spec["max_batch_size"]
return info
def TensorRTCompileSpec(compile_spec: Dict[str, Any]):
"""
Utility to create a formated spec dictionary for using the PyTorch TensorRT backend
Args:
compile_spec (dict): Compilation settings including operating precision, target device, etc.
One key is required which is ``input_shapes``, describing the input sizes or ranges for inputs
to the graph. All other keys are optional. Entries for each method to be compiled.
.. code-block:: py
CompileSpec = {
"forward" : trtorch.TensorRTCompileSpec({
"input_shapes": [
(1, 3, 224, 224), # Static input shape for input #1
{
"min": (1, 3, 224, 224),
"opt": (1, 3, 512, 512),
"max": (1, 3, 1024, 1024)
} # Dynamic input shape for input #2
],
"op_precision": torch.half, # Operating precision set to FP16
"refit": False, # enable refit
"debug": False, # enable debuggable engine
"strict_types": False, # kernels should strictly run in operating precision
"allow_gpu_fallback": True, # (DLA only) Allow layers unsupported on DLA to run on GPU
"device": torch.device("cuda"), # Type of device to run engine on (for DLA use trtorch.DeviceType.DLA)
"capability": trtorch.EngineCapability.DEFAULT, # Restrict kernel selection to safe gpu kernels or safe dla kernels
"num_min_timing_iters": 2, # Number of minimization timing iterations used to select kernels
"num_avg_timing_iters": 1, # Number of averaging timing iterations used to select kernels
"workspace_size": 0, # Maximum size of workspace given to TensorRT
"max_batch_size": 0, # Maximum batch size (must be >= 1 to be set, 0 means not set)
})
}
Input Sizes can be specified as torch sizes, tuples or lists. Op precisions can be specified using
torch datatypes or trtorch datatypes and you can use either torch devices or the trtorch device type enum
to select device type.
Returns:
torch.classes.tensorrt.CompileSpec: List of methods and formated spec objects to be provided to ``torch._C._jit_to_tensorrt``
"""
parsed_spec = _parse_compile_spec(compile_spec)
backend_spec = torch.classes.tensorrt.CompileSpec()
for i in parsed_spec.input_ranges:
ir = torch.classes.tensorrt.InputRange()
ir.set_min(i.min)
ir.set_opt(i.opt)
ir.set_max(i.max)
backend_spec.append_input_range(ir)
backend_spec.set_op_precision(int(parsed_spec.op_precision))
backend_spec.set_refit(parsed_spec.refit)
backend_spec.set_debug(parsed_spec.debug)
backend_spec.set_refit(parsed_spec.refit)
backend_spec.set_strict_types(parsed_spec.strict_types)
backend_spec.set_allow_gpu_fallback(parsed_spec.allow_gpu_fallback)
backend_spec.set_device(int(parsed_spec.device))
backend_spec.set_capability(int(parsed_spec.capability))
backend_spec.set_num_min_timing_iters(parsed_spec.num_min_timing_iters)
backend_spec.set_num_avg_timing_iters(parsed_spec.num_avg_timing_iters)
backend_spec.set_workspace_size(parsed_spec.workspace_size)
backend_spec.set_max_batch_size(parsed_spec.max_batch_size)
return backend_spec |
if "num_avg_timing_iters" in compile_spec: |
quiz4.rs | // quiz4.rs
// This quiz covers the sections:
// - Modules
// - Macros
// Write a macro that passes the quiz! No hints this time, you can do it!
#[macro_use]
macro_rules! my_macro {
($x: expr) => {
format!("Hello {}", $x);
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_my_macro_world() |
#[test]
fn test_my_macro_goodbye() {
assert_eq!(my_macro!("goodbye!"), "Hello goodbye!");
}
}
| {
assert_eq!(my_macro!("world!"), "Hello world!");
} |
grpclb_config.go | /*
*
* Copyright 2019 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package grpclb
import (
"encoding/json"
)
import (
"github.com/dubbogo/grpc-go"
"github.com/dubbogo/grpc-go/balancer/roundrobin"
"github.com/dubbogo/grpc-go/serviceconfig"
)
const (
roundRobinName = roundrobin.Name
pickFirstName = grpc.PickFirstBalancerName
)
type grpclbServiceConfig struct {
serviceconfig.LoadBalancingConfig
ChildPolicy *[]map[string]json.RawMessage
TargetName string
}
func (b *lbBuilder) ParseConfig(lbConfig json.RawMessage) (serviceconfig.LoadBalancingConfig, error) {
ret := &grpclbServiceConfig{}
if err := json.Unmarshal(lbConfig, ret); err != nil {
return nil, err
}
return ret, nil
}
func childIsPickFirst(sc *grpclbServiceConfig) bool {
if sc == nil |
childConfigs := sc.ChildPolicy
if childConfigs == nil {
return false
}
for _, childC := range *childConfigs {
// If round_robin exists before pick_first, return false
if _, ok := childC[roundRobinName]; ok {
return false
}
// If pick_first is before round_robin, return true
if _, ok := childC[pickFirstName]; ok {
return true
}
}
return false
}
| {
return false
} |
test_state.py | # type: ignore
from typing import List, Optional
from uuid import uuid4
import pytest
from nwastdlib import const
from orchestrator.domain.lifecycle import change_lifecycle
from orchestrator.forms import FormPage, post_process
from orchestrator.types import State, SubscriptionLifecycle
from orchestrator.utils.state import extract, form_inject_args, inject_args
STATE = {"one": 1, "two": 2, "three": 3, "four": 4}
def test_extract():
one, two, three, four = extract(("one", "two", "three", "four"), STATE)
assert one == 1
assert two == 2
assert three == 3
assert four == 4
four, three, two, one = extract(("four", "three", "two", "one"), STATE)
assert one == 1
assert two == 2
assert three == 3
assert four == 4
nothing = extract((), STATE)
assert len(nothing) == 0
def test_extract_key_error():
key = "I don't exist"
with pytest.raises(KeyError) as excinfo:
extract((key,), STATE)
assert key in excinfo.value.args
def test_state() -> None:
@inject_args
def step_func_ok(one):
assert one == STATE["one"]
return {"prefix_id": 42}
new_state = step_func_ok(STATE)
assert "prefix_id" in new_state
assert new_state["prefix_id"] == 42
@inject_args
def step_func_fail(i_am_not_in_the_state):
return {}
with pytest.raises(KeyError):
step_func_fail(STATE)
@inject_args
def step_func_opt_arg(opt: Optional[str] = None) -> None:
assert opt is None
step_func_opt_arg(STATE)
@inject_args
def step_func_default(default="bla"):
assert default == "bla"
step_func_default(STATE)
step_func_const = inject_args(const({}))
step_func_const(STATE)
@inject_args
def step_func_state(state, one):
assert state == STATE
assert one == STATE["one"]
step_func_state(STATE)
@inject_args
def step_func_empty():
pass
step_func_state(STATE)
def test_inject_args(generic_product_1, generic_product_type_1) -> None:
GenericProductOneInactive, GenericProduct = generic_product_type_1
product_id = generic_product_1.product_id
state = {"product": product_id, "organisation": uuid4()}
generic_sub = GenericProductOneInactive.from_product_id(
product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL
)
generic_sub.pb_1.rt_1 = "test"
generic_sub.pb_2.rt_2 = 42
generic_sub.pb_2.rt_3 = "test2"
generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE)
generic_sub.save()
@inject_args
def | (generic_sub: GenericProduct) -> State:
assert generic_sub.subscription_id
assert generic_sub.pb_1.rt_1 == "test"
generic_sub.pb_1.rt_1 = "test string"
return {"generic_sub": generic_sub}
# Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be
# certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved
# from the database.
state["generic_sub"] = generic_sub.subscription_id
state_amended = step_existing(state)
assert "generic_sub" in state_amended
# Do we now have an entire object instead of merely a UUID
assert isinstance(state_amended["generic_sub"], GenericProduct)
# And does it have the modifcations from the step functions
assert state_amended["generic_sub"].pb_1.rt_1 == "test string"
# Test `rt_1` has been persisted to the database with the modifications from the step function.`
fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id)
assert fresh_generic_sub.pb_1.rt_1 is not None
def test_inject_args_list(generic_product_1, generic_product_type_1) -> None:
GenericProductOneInactive, GenericProduct = generic_product_type_1
product_id = generic_product_1.product_id
state = {"product": product_id, "organisation": uuid4()}
generic_sub = GenericProductOneInactive.from_product_id(
product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL
)
generic_sub.pb_1.rt_1 = "test"
generic_sub.pb_2.rt_2 = 42
generic_sub.pb_2.rt_3 = "test2"
generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE)
generic_sub.save()
@inject_args
def step_existing(generic_sub: List[GenericProduct]) -> State:
assert len(generic_sub) == 1
assert generic_sub[0].subscription_id
assert generic_sub[0].pb_1.rt_1 == "test"
return {"generic_sub": generic_sub}
# Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be
# certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved
# from the database.
state["generic_sub"] = [generic_sub.subscription_id]
state_amended = step_existing(state)
assert "generic_sub" in state_amended
assert len(state_amended["generic_sub"]) == 1
# Do we now have an entire object instead of merely a UUID
assert isinstance(state_amended["generic_sub"][0], GenericProduct)
# And does it have the modifcations from the step functions
assert state_amended["generic_sub"][0].pb_1.rt_1 is not None
# Test `rt_1` has been persisted to the database with the modifications from the step function.`
fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"][0].subscription_id)
assert fresh_generic_sub.pb_1.rt_1 is not None
def test_inject_args_optional(generic_product_1, generic_product_type_1) -> None:
GenericProductOneInactive, GenericProduct = generic_product_type_1
product_id = generic_product_1.product_id
state = {"product": product_id, "organisation": uuid4()}
generic_sub = GenericProductOneInactive.from_product_id(
product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL
)
generic_sub.pb_1.rt_1 = "test"
generic_sub.pb_2.rt_2 = 42
generic_sub.pb_2.rt_3 = "test2"
generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE)
generic_sub.save()
@inject_args
def step_existing(generic_sub: Optional[GenericProduct]) -> State:
assert generic_sub is not None, "Generic Sub IS NONE"
assert generic_sub.subscription_id
assert generic_sub.pb_1.rt_1 == "test"
return {"generic_sub": generic_sub}
with pytest.raises(AssertionError) as exc_info:
step_existing(state)
assert "Generic Sub IS NONE" in str(exc_info.value)
# Put `light_path` as an UUID in. Entire `light_path` object would have worked as well, but this way we will be
# certain that if we end up with an entire `light_path` object in the step function, it will have been retrieved
# from the database.
state["generic_sub"] = generic_sub.subscription_id
state_amended = step_existing(state)
assert "generic_sub" in state_amended
# Do we now have an entire object instead of merely a UUID
assert isinstance(state_amended["generic_sub"], GenericProduct)
# And does it have the modifcations from the step functions
assert state_amended["generic_sub"].pb_1.rt_1 is not None
# Test `nso_service_id` has been persisted to the database with the modifications from the step function.`
fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id)
assert fresh_generic_sub.pb_1.rt_1 is not None
def test_form_inject_args(generic_product_1, generic_product_type_1) -> None:
GenericProductOneInactive, GenericProduct = generic_product_type_1
product_id = generic_product_1.product_id
state = {"product": product_id, "organisation": uuid4()}
generic_sub = GenericProductOneInactive.from_product_id(
product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL
)
generic_sub.pb_1.rt_1 = "test"
generic_sub.pb_2.rt_2 = 42
generic_sub.pb_2.rt_3 = "test2"
generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE)
generic_sub.save()
@form_inject_args
def form_function(generic_sub: GenericProduct) -> State:
assert generic_sub.subscription_id
assert generic_sub.pb_1.rt_1 == "test"
generic_sub.pb_1.rt_1 = "test string"
class Form(FormPage):
pass
_ = yield Form
return {"generic_sub": generic_sub}
# Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be
# certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved
# from the database.
state["generic_sub"] = generic_sub.subscription_id
state_amended = post_process(form_function, state, [{}])
assert "generic_sub" in state_amended
# Do we now have an entire object instead of merely a UUID
assert isinstance(state_amended["generic_sub"], GenericProduct)
# And does it have the modifcations from the step functions
assert state_amended["generic_sub"].pb_1.rt_1 == "test string"
# Test `rt_1` has been persisted to the database with the modifications from the step function.`
fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id)
assert fresh_generic_sub.pb_1.rt_1 is not None
def test_form_inject_args_simple(generic_product_1, generic_product_type_1) -> None:
GenericProductOneInactive, GenericProduct = generic_product_type_1
product_id = generic_product_1.product_id
state = {"product": product_id, "organisation": uuid4()}
generic_sub = GenericProductOneInactive.from_product_id(
product_id=state["product"], customer_id=state["organisation"], status=SubscriptionLifecycle.INITIAL
)
generic_sub.pb_1.rt_1 = "test"
generic_sub.pb_2.rt_2 = 42
generic_sub.pb_2.rt_3 = "test2"
generic_sub = change_lifecycle(generic_sub, SubscriptionLifecycle.ACTIVE)
generic_sub.save()
@form_inject_args
def form_function(generic_sub: GenericProduct) -> State:
assert generic_sub.subscription_id
assert generic_sub.pb_1.rt_1 == "test"
generic_sub.pb_1.rt_1 = "test string"
return {"generic_sub": generic_sub}
# Put `generic_sub` as an UUID in. Entire `generic_sub` object would have worked as well, but this way we will be
# certain that if we end up with an entire `generic_sub` object in the step function, it will have been retrieved
# from the database.
state["generic_sub"] = generic_sub.subscription_id
state_amended = form_function(state)
assert "generic_sub" in state_amended
# Do we now have an entire object instead of merely a UUID
assert isinstance(state_amended["generic_sub"], GenericProduct)
# And does it have the modifcations from the step functions
assert state_amended["generic_sub"].pb_1.rt_1 == "test string"
# Test `rt_1` has been persisted to the database with the modifications from the step function.`
fresh_generic_sub = GenericProduct.from_subscription(state_amended["generic_sub"].subscription_id)
assert fresh_generic_sub.pb_1.rt_1 is not None
| step_existing |
index.js | // This file will be included as an inline script tag by index.html. It
// also gets wrapped in a `window.onload = function() { ... }` wrapper
// so that the whole file doesn't need to be indented. This means things
// included in the bundle are available here.
'use strict';
const regl = window._regl = window.regl({
extensions: ['oes_standard_derivatives'],
optionalExtensions: ['oes_element_index_uint']
});
const scalar = cwise({
args: [{blockIndices: -1}],
body: function (A) {
A[0] = A[0] * 4 - 2;
A[1] = A[1] * 2 - 1;
A[2] = A[2] * 2 - 1;
}
})
const scale = A => {
scalar(A);
return A;
}
var n = [2, 11, 41];
const faces = window.f = [
[[u => [u, 0, 0], u => [u, 1, 0]], [v => [0, v, 0], v => [1, v, 0]]],
[[u => [u, 0, 1], u => [u, 1, 1]], [v => [0, v, 1], v => [1, v, 1]]],
[[u => [u, 0, 0], u => [u, 0, 1]], [w => [0, 0, w], w => [1, 0, w]]],
[[u => [u, 1, 0], u => [u, 1, 1]], [w => [0, 1, w], w => [1, 1, w]]],
[[v => [0, v, 0], v => [0, v, 0]], [w => [0, 0, w], w => [0, 1, w]]],
[[v => [1, v, 0], v => [1, v, 0]], [w => [1, 0, w], w => [1, 1, w]]],
]
.map((f, i) => tfi(zeros(n.filter((j, k) => k !== Math.floor(i / 2)).concat([3]), 'float32'), f))
.map(scale)
.map(createFace);
function | (arr) {
if (arr.constructor === Float32Array) {
return 4;
} else {
throw new Error('Unexpected array type: ' + String(arr.constructor));
}
}
function createFace (A, dir) {
var dir = Math.floor(dir / 2);
var dim = A.dimension;
var a, b, c, d, i, j;
var l = A.shape[0];
var m = A.shape[1];
var o = A.offset;
var si = A.stride[0];
var sj = A.stride[1];
var gridCoord = [];
var faces = [];
for (j = 0; j < m - 1; j++) {
for (i = 0; i < l - 1; i++) {
// c d
// a b
a = o + si * i + sj * j;
b = a + si;
c = a + sj;
d = b + sj;
faces.push(a, b, c);
faces.push(d, c, b);
}
}
var f1 = 20 / (A.shape[0] - 1);
var f2 = 20 / (A.shape[1] - 1);
for (j = 0; j < m; j++) {
for (i = 0; i < l; i++) {
a = o + si * i + sj * j;
gridCoord[a] = i * f1;
gridCoord[a + 1] = j * f2;
gridCoord[a + 2] = 0;
}
}
return {
array: A,
faces: faces,
buffer: A.data,
count: faces.length,
color: [1, 0, 0, 0.5],
byteSize: byteSize(A.data),
gridCoord: new Float32Array(gridCoord)
};
}
const camera = createCamera(regl, {
center: [0, 0, 0],
phi: Math.PI * 0.1,
theta: Math.PI * 0.25,
distance: 5
});
const drawFaces = regl({
frag: `
#extension GL_OES_standard_derivatives : enable
precision mediump float;
varying vec3 vBC;
uniform vec4 color;
float edgeFactor () {
vec3 d = fwidth(vBC);
vec3 a3 = smoothstep(vec3(0.0), 1.5 * d, 0.5 - abs(mod(vBC, 1.0) - 0.5));
return min(a3.x, a3.y);
}
void main () {
float ef = edgeFactor();
gl_FragColor = vec4(mix(vec3(0.0), vec3(1.0), ef), 1.0);
}`,
vert: `
precision mediump float;
varying vec3 vBC;
uniform mat4 projection, view;
uniform float time;
float omega = 5.0;
attribute vec3 position, gridCoord;
void main () {
vBC = gridCoord;
gl_Position = projection * view * vec4(
position.x + 0.05 * sin(4.0 * position.x - omega * time + 3.1415926 * 0.5) * exp((position.y - 0.5) * 2.0),
position.y + 0.025 * sin(4.0 * position.x - omega * time) * exp((position.y - 0.5) * 2.0),
position.z,
1.0
);
}`,
primitive: 'triangles',
attributes: {
position: {
buffer: regl.prop('buffer'),
stride: regl.prop('byteSize'),
},
gridCoord: {
buffer: regl.prop('gridCoord'),
stride: 4
}
},
uniforms: {
color: regl.prop('color'),
time: regl.context('time')
},
count: regl.prop('count'),
elements: regl.prop('faces')
})
regl.frame(({tick}) => {
//if (tick % 30 !== 0) return;
regl.clear({color: [1, 1, 1, 1]})
camera(() => {
drawFaces(faces)
});
})
| byteSize |
push_gitlab.py | """ Entry point for tsrc push """
import argparse
import itertools
from typing import cast, Any, List, Optional, Set # noqa
from gitlab import Gitlab
from gitlab.v4.objects import Group, User, Project, ProjectMergeRequest # noqa
from gitlab.exceptions import GitlabGetError
import ui
import tsrc
import tsrc.config
import tsrc.gitlab
import tsrc.git
import tsrc.cli.push
from tsrc.cli.push import RepositoryInfo
WIP_PREFIX = "WIP: "
class UserNotFound(tsrc.Error):
def __init__(self, username: str) -> None:
self.username = username
super().__init__("No user found with this username : %s" % self.username)
class TooManyUsers(tsrc.Error):
def __init__(self, max_users: int) -> None:
self.max_users = max_users
super().__init__("More than %s users found" % self.max_users)
class AmbiguousUser(tsrc.Error):
def __init__(self, query: str) -> None:
self.query = query
super().__init__("Found more that one user matching query: %s" % self.query)
def get_token() -> str:
config = tsrc.config.parse_tsrc_config()
res = config["auth"]["gitlab"]["token"] # type: str
return res
def wipify(title: str) -> str:
if not title.startswith(WIP_PREFIX):
return WIP_PREFIX + title
else:
return title
def unwipify(title: str) -> str:
if title.startswith(WIP_PREFIX):
return title[len(WIP_PREFIX):]
else:
return title
class PushAction(tsrc.cli.push.PushAction):
def __init__(self, repository_info: RepositoryInfo, args:
argparse.Namespace, gitlab_api: Optional[Gitlab] = None) -> None:
super().__init__(repository_info, args)
self.gitlab_api = gitlab_api
self.group = None # type: Optional[Group]
self.project = None # type: Optional[Project]
self.review_candidates = [] # type: List[User]
def _get_group(self, group_name: str) -> Optional[Group]:
assert self.gitlab_api
try:
return self.gitlab_api.groups.get(group_name)
except GitlabGetError as e:
if e.response_code == 404:
return None
else:
raise
def setup_service(self) -> None:
if not self.gitlab_api:
workspace = tsrc.cli.get_workspace(self.args)
workspace.load_manifest()
gitlab_url = workspace.get_gitlab_url()
token = get_token()
self.gitlab_api = Gitlab(gitlab_url, private_token=token)
assert self.project_name
self.project = self.gitlab_api.projects.get(self.project_name)
group_name = self.project_name.split("/")[0]
self.group = self._get_group(group_name)
def handle_assignee(self) -> User:
assert self.requested_assignee
return self.get_reviewer_by_username(self.requested_assignee)
def handle_approvers(self) -> List[User]:
res = list() # type: List[User]
if not self.args.reviewers:
return res
for requested_username in self.args.reviewers:
username = requested_username.strip()
approver = self.get_reviewer_by_username(username)
res.append(approver)
return res
def get_reviewer_by_username(self, username: str) -> User:
assert self.group
assert self.project
in_project = self.get_users_matching(self.project.members, username)
in_group = self.get_users_matching(self.group.members, username)
candidates = list()
seen = set() # type: Set[int]
for user in itertools.chain(in_project, in_group):
if user.id in seen:
continue
candidates.append(user)
seen.add(user.id)
if not candidates:
raise UserNotFound(username)
if len(candidates) > 1:
raise AmbiguousUser(username)
return candidates[0]
def get_users_matching(self, members: Any, query: str) -> List[User]:
res = members.list(active=True, query=query, per_page=100, as_list=False)
if res.next_page:
raise TooManyUsers(100)
return cast(List[User], res)
def post_push(self) -> None:
merge_request = self.ensure_merge_request()
assert self.gitlab_api
if self.args.close:
ui.info_2("Closing merge request #%s" % merge_request.iid)
merge_request.state_event = "close"
merge_request.save()
return
assignee = None
if self.requested_assignee:
assignee = self.handle_assignee()
if assignee:
ui.info_2("Assigning to", assignee.username)
title = self.handle_title(merge_request)
merge_request.title = title
merge_request.remove_source_branch = True
if self.requested_target_branch:
merge_request.target_branch = self.requested_target_branch
if assignee:
merge_request.assignee_id = assignee.id
approvers = self.handle_approvers()
merge_request.approvals.set_approvers([x.id for x in approvers])
merge_request.save()
if self.args.accept:
merge_request.merge(merge_when_pipeline_succeeds=True)
ui.info(ui.green, "::",
ui.reset, "See merge request at", merge_request.web_url)
def handle_title(self, merge_request: ProjectMergeRequest) -> str:
# If explicitely set, use it
if self.requested_title:
return self.requested_title
else:
# Else change the title if we need to
title = merge_request.title # type: str
if self.args.ready:
return unwipify(title)
if self.args.wip:
return wipify(title)
return title
def find_merge_request(self) -> Optional[ProjectMergeRequest]:
assert self.remote_branch
assert self.project
res = self.project.mergerequests.list(
state="opened",
source_branch=self.remote_branch, | if len(res) >= 2:
raise tsrc.Error("Found more than one opened merge request with the same branch")
if not res:
return None
return res[0]
def create_merge_request(self) -> ProjectMergeRequest:
assert self.project
if self.requested_target_branch:
target_branch = self.requested_target_branch
else:
target_branch = self.project.default_branch
assert self.remote_branch
return self.project.mergerequests.create(
{
"source_branch": self.remote_branch,
"target_branch": target_branch,
"title": self.remote_branch,
}
)
def ensure_merge_request(self) -> ProjectMergeRequest:
merge_request = self.find_merge_request()
if merge_request:
ui.info_2("Found existing merge request: !%s" % merge_request.iid)
return merge_request
else:
return self.create_merge_request() | all=True
) |
hero.service.ts | import * as _ from "lodash";
import { autoinject } from "aurelia-framework";
import { ILog, LoggerFactory } from "@ssv/au-core";
import { Hero } from "./hero.model";
import { HEROES } from "./mock-heroes";
const id = "heroService";
@autoinject
export class HeroService {
private logger: ILog;
constructor(
loggerFactory: LoggerFactory
) {
this.logger = loggerFactory.get(id);
this.logger.debug("ctor", "init");
}
getAll(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
getByKey(key: string): Promise<Hero> {
this.logger.info("getByKey", "finding...", { key: key });
return this.getAll()
.then(x => {
const result = _.find(x, { key: key });
this.logger.info("getByKey", "find complete.", { key: key, result: result });
if (!result) { | throw new Error(`Hero '${key}' not found`);
}
return result;
});
}
} | |
d5b5eb2e8dd0_added_branch_name.py | """added branch name
Revision ID: d5b5eb2e8dd0
Revises: 69a7e464fef3
Create Date: 2021-03-03 21:30:29.597634
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
from sqlalchemy.sql import column, table
revision = 'd5b5eb2e8dd0'
down_revision = '69a7e464fef3'
branch_labels = None
depends_on = None
def | ():
op.add_column('orgs', sa.Column('branch_name', sa.String(length=100), nullable=True))
op.add_column('orgs_version', sa.Column('branch_name', sa.String(length=100), nullable=True))
invitation_type_table = table('invitation_types',
column('code', sa.String(length=15)),
column('description', sa.String(length=100)),
column('default', sa.Boolean())
)
op.bulk_insert(
invitation_type_table,
[
{'code': 'GOVM', 'description': 'An invitation to activate a GOV Ministry account',
'default': False},
]
)
def downgrade():
op.drop_column('orgs', 'branch_name')
op.drop_column('orgs_version', 'branch_name')
op.execute("DELETE from invitation_types WHERE code='GOVM'")
| upgrade |
mod.rs | use infer::InferCtxt;
use infer::lexical_region_resolve::RegionResolutionError;
use infer::lexical_region_resolve::RegionResolutionError::*;
use syntax::source_map::Span;
use ty::{self, TyCtxt};
use util::common::ErrorReported;
mod different_lifetimes;
mod find_anon_type;
mod named_anon_conflict;
mod placeholder_error;
mod outlives_closure;
mod static_impl_trait;
mod util;
impl<'cx, 'gcx, 'tcx> InferCtxt<'cx, 'gcx, 'tcx> {
pub fn | (&self, error: &RegionResolutionError<'tcx>) -> bool {
match *error {
ConcreteFailure(..) | SubSupConflict(..) => {}
_ => return false, // inapplicable
}
if let Some(tables) = self.in_progress_tables {
let tables = tables.borrow();
NiceRegionError::new(self.tcx, error.clone(), Some(&tables)).try_report().is_some()
} else {
NiceRegionError::new(self.tcx, error.clone(), None).try_report().is_some()
}
}
}
pub struct NiceRegionError<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
error: Option<RegionResolutionError<'tcx>>,
regions: Option<(Span, ty::Region<'tcx>, ty::Region<'tcx>)>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
}
impl<'cx, 'gcx, 'tcx> NiceRegionError<'cx, 'gcx, 'tcx> {
pub fn new(
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
error: RegionResolutionError<'tcx>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
) -> Self {
Self { tcx, error: Some(error), regions: None, tables }
}
pub fn new_from_span(
tcx: TyCtxt<'cx, 'gcx, 'tcx>,
span: Span,
sub: ty::Region<'tcx>,
sup: ty::Region<'tcx>,
tables: Option<&'cx ty::TypeckTables<'tcx>>,
) -> Self {
Self { tcx, error: None, regions: Some((span, sub, sup)), tables }
}
pub fn try_report_from_nll(&self) -> Option<ErrorReported> {
// Due to the improved diagnostics returned by the MIR borrow checker, only a subset of
// the nice region errors are required when running under the MIR borrow checker.
self.try_report_named_anon_conflict()
.or_else(|| self.try_report_placeholder_conflict())
}
pub fn try_report(&self) -> Option<ErrorReported> {
self.try_report_from_nll()
.or_else(|| self.try_report_anon_anon_conflict())
.or_else(|| self.try_report_outlives_closure())
.or_else(|| self.try_report_static_impl_trait())
}
pub fn get_regions(&self) -> (Span, ty::Region<'tcx>, ty::Region<'tcx>) {
match (&self.error, self.regions) {
(Some(ConcreteFailure(origin, sub, sup)), None) => (origin.span(), sub, sup),
(Some(SubSupConflict(_, _, origin, sub, _, sup)), None) => (origin.span(), sub, sup),
(None, Some((span, sub, sup))) => (span, sub, sup),
(Some(_), Some(_)) => panic!("incorrectly built NiceRegionError"),
_ => panic!("trying to report on an incorrect lifetime failure"),
}
}
}
| try_report_nice_region_error |
foo.go | // Use `go run foo.go` to run your program
package main
import (
. "fmt"
"runtime"
"time"
)
var i = 0
func incrementing() {
for j := 0; j < 1000000; j++ {
i++
}
}
func decrementing() {
for j := 0; j < 1000000; j++ {
i--
}
}
func main() | {
runtime.GOMAXPROCS(runtime.NumCPU())
go incrementing()
go decrementing()
time.Sleep(100*time.Millisecond)
Println("The magic number is:", i)
} |
|
builder_test.go | package objectbuilder
import (
"fmt"
"testing"
)
const (
iPorts = "ports"
iProperties = "properties"
)
func TestBuildTemplates(t *testing.T) {
result := StringReplacement(
map[string]interface{}{
"A": map[string]interface{}{
"B": "=$property[\"Logging.LogLevel\"]",
},
"C": "MQTTTrigger.MaximumQOS", | },
map[string]interface{}{
"=$property[\"Logging.LogLevel\"]": "=$property[\"DataSource.Logging.LogLevel\"]",
"MQTTTrigger.MaximumQOS": "DataSource.MQTTTrigger.MaximumQOS",
})
log.Debug("-------", result)
} | |
XMLBIF.py | #!/usr/bin/env python
try:
from lxml import etree
except ImportError:
try:
import xml.etree.ElementTree as etree
except ImportError:
#try:
# import xml.etree.cElementTree as etree
# commented out because xml.etree.cElementTree is giving errors with dictionary attributes
print("Failed to import ElementTree from any known place")
import numpy as np
from pgmpy.models import BayesianModel
from pgmpy.factors import TabularCPD, State
from pgmpy.extern.six.moves import map, range
class XMLBIFReader(object):
"""
Base class for reading network file in XMLBIF format.
"""
def __init__(self, path=None, string=None):
"""
Initialisation of XMLBIFReader object.
Parameters
----------
path : file or str
File of XMLBIF data
string : str
String of XMLBIF data
Examples
--------
# xmlbif_test.xml is the file present in
# http://www.cs.cmu.edu/~fgcozman/Research/InterchangeFormat/
>>> reader = XMLBIFReader("xmlbif_test.xml")
"""
if path:
self.network = etree.ElementTree(file=path).getroot().find('NETWORK')
elif string:
self.network = etree.fromstring(string).find('NETWORK')
else:
raise ValueError("Must specify either path or string")
self.network_name = self.network.find('NAME').text
self.variables = self.get_variables()
self.variable_parents = self.get_parents()
self.edge_list = self.get_edges()
self.variable_states = self.get_states()
self.variable_CPD = self.get_cpd()
self.variable_property = self.get_property()
def get_variables(self):
"""
Returns list of variables of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_variables()
['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out']
"""
variables = [variable.find('NAME').text for variable in self.network.findall('VARIABLE')]
return variables
def get_edges(self):
"""
Returns the edges of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_edges()
[['family-out', 'light-on'],
['family-out', 'dog-out'],
['bowel-problem', 'dog-out'],
['dog-out', 'hear-bark']]
"""
edge_list = [[value, key] for key in self.variable_parents
for value in self.variable_parents[key]]
return edge_list
def get_states(self):
"""
Returns the states of variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_states()
{'bowel-problem': ['true', 'false'],
'dog-out': ['true', 'false'],
'family-out': ['true', 'false'],
'hear-bark': ['true', 'false'],
'light-on': ['true', 'false']}
"""
variable_states = {variable.find('NAME').text: [outcome.text for outcome in variable.findall('OUTCOME')]
for variable in self.network.findall('VARIABLE')}
return variable_states
def get_parents(self):
"""
Returns the parents of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_parents()
{'bowel-problem': [],
'dog-out': ['family-out', 'bowel-problem'],
'family-out': [],
'hear-bark': ['dog-out'],
'light-on': ['family-out']}
"""
variable_parents = {definition.find('FOR').text: [edge.text for edge in definition.findall('GIVEN')][::-1]
for definition in self.network.findall('DEFINITION')}
return variable_parents
def get_cpd(self):
"""
Returns the CPD of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_cpd()
{'bowel-problem': array([[ 0.01],
[ 0.99]]),
'dog-out': array([[ 0.99, 0.01, 0.97, 0.03],
[ 0.9 , 0.1 , 0.3 , 0.7 ]]),
'family-out': array([[ 0.15],
[ 0.85]]),
'hear-bark': array([[ 0.7 , 0.3 ],
[ 0.01, 0.99]]),
'light-on': array([[ 0.6 , 0.4 ],
[ 0.05, 0.95]])}
"""
variable_CPD = {definition.find('FOR').text: list(map(float, table.text.split()))
for definition in self.network.findall('DEFINITION')
for table in definition.findall('TABLE')}
for variable in variable_CPD:
arr = np.array(variable_CPD[variable])
arr = arr.reshape((len(self.variable_states[variable]),
arr.size//len(self.variable_states[variable])))
variable_CPD[variable] = arr
return variable_CPD
def get_property(self):
"""
Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = (155, 165)'],
'family-out': ['position = (112, 69)'],
'hear-bark': ['position = (154, 241)'],
'light-on': ['position = (73, 165)']}
"""
variable_property = {variable.find('NAME').text: [property.text for property in variable.findall('PROPERTY')]
for variable in self.network.findall('VARIABLE')}
return variable_property
def get_model(self):
model = BayesianModel(self.get_edges())
model.name = self.network_name
tabular_cpds = []
for var, values in self.variable_CPD.items():
cpd = TabularCPD(var, len(self.variable_states[var]), values,
evidence=self.variable_parents[var],
evidence_card=[len(self.variable_states[evidence_var])
for evidence_var in self.variable_parents[var]])
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
for node, properties in self.variable_property.items():
for prop in properties:
prop_name, prop_value = map(lambda t: t.strip(), prop.split('='))
model.node[node][prop_name] = prop_value
return model
class XMLBIFWriter(object):
"""
Base class for writing XMLBIF network file format.
"""
def __init__(self, model, encoding='utf-8', prettyprint=True):
|
def __str__(self):
"""
Return the XML as string.
"""
if self.prettyprint:
self.indent(self.xml)
return etree.tostring(self.xml, encoding=self.encoding)
def indent(self, elem, level=0):
"""
Inplace prettyprint formatter.
"""
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
self.indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def get_variables(self):
"""
Add variables to XMLBIF
Return
------
dict: dict of type {variable: variable tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_variables()
{'bowel-problem': <Element VARIABLE at 0x7fe28607dd88>,
'family-out': <Element VARIABLE at 0x7fe28607de08>,
'hear-bark': <Element VARIABLE at 0x7fe28607de48>,
'dog-out': <Element VARIABLE at 0x7fe28607ddc8>,
'light-on': <Element VARIABLE at 0x7fe28607de88>}
"""
variables = self.model.nodes()
variable_tag = {}
for var in sorted(variables):
variable_tag[var] = etree.SubElement(self.network, "VARIABLE", attrib={'TYPE': 'nature'})
etree.SubElement(variable_tag[var], "NAME").text = var
return variable_tag
def get_states(self):
"""
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>],
'family-out': [<Element OUTCOME at 0x7ffbabfd4108>, <Element OUTCOME at 0x7ffbabfd4148>],
'bowel-problem': [<Element OUTCOME at 0x7ffbabfd4088>, <Element OUTCOME at 0x7ffbabfd40c8>],
'hear-bark': [<Element OUTCOME at 0x7ffbabfcdf48>, <Element OUTCOME at 0x7ffbabfcdf88>],
'light-on': [<Element OUTCOME at 0x7ffbabfcdfc8>, <Element OUTCOME at 0x7ffbabfd4048>]}
"""
outcome_tag = {}
cpds = self.model.get_cpds()
for cpd in cpds:
var = cpd.variable
outcome_tag[var] = []
for state in [State(var, state) for state in range(cpd.get_cardinality([var])[var])]:
# for state in [cpd.variables[var]:
state_tag = etree.SubElement(self.variables[var], "OUTCOME")
state_tag.text = str(state.state)
outcome_tag[var].append(state_tag)
return outcome_tag
def get_properties(self):
"""
Add property to variables in XMLBIF
Return
------
dict: dict of type {variable: property tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_property()
{'light-on': <Element PROPERTY at 0x7f7a2ffac1c8>,
'family-out': <Element PROPERTY at 0x7f7a2ffac148>,
'hear-bark': <Element PROPERTY at 0x7f7a2ffac188>,
'bowel-problem': <Element PROPERTY at 0x7f7a2ffac0c8>,
'dog-out': <Element PROPERTY at 0x7f7a2ffac108>}
"""
variables = self.model.nodes()
property_tag = {}
for var in sorted(variables):
properties = self.model.node[var]
property_tag[var] = etree.SubElement(self.variables[var], "PROPERTY")
for prop, val in properties.items():
property_tag[var].text = str(prop) + " = " + str(val)
return property_tag
def get_definition(self):
"""
Add Definition to XMLBIF
Return
------
dict: dict of type {variable: definition tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_definition()
{'hear-bark': <Element DEFINITION at 0x7f1d48977408>,
'family-out': <Element DEFINITION at 0x7f1d489773c8>,
'dog-out': <Element DEFINITION at 0x7f1d48977388>,
'bowel-problem': <Element DEFINITION at 0x7f1d48977348>,
'light-on': <Element DEFINITION at 0x7f1d48977448>}
"""
cpds = self.model.get_cpds()
cpds.sort(key=lambda x: x.variable)
definition_tag = {}
for cpd in cpds:
definition_tag[cpd.variable] = etree.SubElement(self.network, "DEFINITION")
etree.SubElement(definition_tag[cpd.variable], "FOR").text = cpd.variable
for child in sorted([] if cpd.evidence is None else cpd.evidence):
etree.SubElement(definition_tag[cpd.variable], "GIVEN").text = child
return definition_tag
def get_cpd(self):
"""
Add Table to XMLBIF.
Return
---------------
dict: dict of type {variable: table tag}
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.get_cpd()
{'dog-out': <Element TABLE at 0x7f240726f3c8>,
'light-on': <Element TABLE at 0x7f240726f488>,
'bowel-problem': <Element TABLE at 0x7f240726f388>,
'family-out': <Element TABLE at 0x7f240726f408>,
'hear-bark': <Element TABLE at 0x7f240726f448>}
"""
cpds = self.model.get_cpds()
definition_tag = self.definition
table_tag = {}
for cpd in cpds:
table_tag[cpd.variable] = etree.SubElement(definition_tag[cpd.variable], "TABLE")
table_tag[cpd.variable].text = ''
for val in cpd.values.ravel():
table_tag[cpd.variable].text += str(val) + ' '
return table_tag
def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
writer = self.__str__()[:-1].decode('utf-8')
with open(filename, 'w') as fout:
fout.write(writer)
| """
Initialise a XMLBIFWriter object.
Parameters
----------
model: BayesianModel Instance
Model to write
encoding: str (optional)
Encoding for text data
prettyprint: Bool(optional)
Indentation in output XML if true
Examples
--------
>>> writer = XMLBIFWriter(model)
"""
if not isinstance(model, BayesianModel):
raise TypeError("model must an instance of BayesianModel")
self.model = model
self.encoding = encoding
self.prettyprint = prettyprint
self.xml = etree.Element("BIF", attrib={'version': '0.3'})
self.network = etree.SubElement(self.xml, 'NETWORK')
if self.model.name:
etree.SubElement(self.network, 'NAME').text = self.model.name
self.variables = self.get_variables()
self.states = self.get_states()
self.properties = self.get_properties()
self.definition = self.get_definition()
self.tables = self.get_cpd() |
getSqlManagedInstance.ts | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* A SqlManagedInstance.
* API Version: 2020-09-08-preview.
*/
export function getSqlManagedInstance(args: GetSqlManagedInstanceArgs, opts?: pulumi.InvokeOptions): Promise<GetSqlManagedInstanceResult> {
if (!opts) {
opts = {}
}
if (!opts.version) {
opts.version = utilities.getVersion();
}
return pulumi.runtime.invoke("azure-native:azuredata:getSqlManagedInstance", {
"resourceGroupName": args.resourceGroupName,
"sqlManagedInstanceName": args.sqlManagedInstanceName,
}, opts);
}
export interface GetSqlManagedInstanceArgs {
/**
* The name of the Azure resource group
*/
readonly resourceGroupName: string;
/**
* Name of SQL Managed Instance
*/
readonly sqlManagedInstanceName: string;
}
/**
* A SqlManagedInstance.
*/
export interface GetSqlManagedInstanceResult {
/**
* The instance admin user
*/
readonly admin?: string;
/**
* null
*/
readonly dataControllerId?: string;
/**
* The instance end time
*/
readonly endTime?: string;
/**
* Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
*/
readonly id: string;
/**
* The on premise instance endpoint
*/
readonly instanceEndpoint?: string;
/**
* The raw kubernetes information
*/
readonly k8sRaw?: any;
/**
* Last uploaded date from on premise cluster. Defaults to current date time
*/
readonly lastUploadedDate?: string;
/**
* The geo-location where the resource lives
*/
readonly location: string;
/**
* The name of the resource
*/
readonly name: string;
/**
* The instance start time
*/
readonly startTime?: string;
/** | * Read only system data
*/
readonly systemData: outputs.azuredata.SystemDataResponse;
/**
* Resource tags.
*/
readonly tags?: {[key: string]: string};
/**
* The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts.
*/
readonly type: string;
/**
* The instance vCore
*/
readonly vCore?: string;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.