//! \file       ImageRBP.cs
//! \date       2017 Dec 11
//! \brief      DiceSystem image format.
//
// Copyright (C) 2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//

using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;

// [000623][Marimo] Setsunai

namespace GameRes.Formats.Dice
{
    internal class RbpMetaData : ImageMetaData
    {
        public int  DataOffset;
    }

    [Export(typeof(ImageFormat))]
    public class RbpFormat : ImageFormat
    {
        public override string         Tag { get { return "RBP"; } }
        public override string Description { get { return "DiceSystem image format"; } }
        public override uint     Signature { get { return 0x31504252; } } // 'RBP1'

        public override ImageMetaData ReadMetaData (IBinaryStream file)
        {
            var header = file.ReadHeader (0x14);
            return new RbpMetaData {
                BPP = header.ToInt32 (4) == 1 ? 24 : 32,
                Width = header.ToUInt32 (8),
                Height = header.ToUInt32 (0xC),
                DataOffset = header.ToInt32 (0x10),
            };
        }

        public override ImageData Read (IBinaryStream file, ImageMetaData info)
        {
            var meta = (RbpMetaData)info;
            file.Position = meta.DataOffset;
            int stride = 4 * (int)meta.Width;
            var pixels = new byte[stride * (int)meta.Height];
            if (24 == meta.BPP)
            {
                for (int i = 0; i < pixels.Length; i += 4)
                {
                    int pixel = file.ReadInt24();
                    pixels[i  ] = (byte) (pixel << 3);
                    pixels[i+1] = (byte)((pixel >> 3) & 0xFC);
                    pixels[i+2] = (byte)((pixel >> 8) & 0xF8);
                    pixels[i+3] = (byte)((pixel >> 16) * 0xFF / 0x3F);
                }
            }
            else
            {
                file.Read (pixels, 0, pixels.Length);
                for (int i = 3; i < pixels.Length; i += 4)
                {
                    byte alpha = pixels[i];
                    if (alpha != 0)
                        pixels[i] = (byte)(alpha * 0xFF / 0x3F);
                }
            }
            return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, stride);
        }

        public override void Write (Stream file, ImageData image)
        {
            throw new System.NotImplementedException ("RbpFormat.Write not implemented");
        }
    }
}


/dts-v1/;

#include "bcm63268.dtsi"

#include <dt-bindings/input/input.h>

/ {
	model = "Broadcom BCM963268BU_P300 reference board";
	compatible = "brcm,bcm963268bu_p300", "brcm,bcm63268";

	chosen {
		bootargs = "rootfstype=squashfs,jffs2 noinitrd console=ttyS0,115200";
		stdout-path = "serial0:115200n8";
	};

	gpio-keys-polled {
		compatible = "gpio-keys-polled";
		#address-cells = <1>;
		#size-cells = <0>;
		poll-interval = <20>;
		debounce-interval = <60>;

		reset {
			label = "reset";
			gpios = <&pinctrl 32 0>;
			linux,code = <KEY_RESTART>;
		};

		wps {
			label = "wps";
			gpios = <&pinctrl 33 0>;
			linux,code = <KEY_WPS_BUTTON>;
		};
        };
};

&hsspi {
	status = "ok";

	flash@0 {
		compatible = "jedec,spi-nor";
		spi-max-frequency = <20000000>;
		spi-tx-bus-width = <2>;
		spi-rx-bus-width = <2>;
		reg = <0>;

		#address-cells = <1>;
		#size-cells = <1>;

		linux,part-probe = "bcm63xxpart";

		partitions {
			compatible = "brcm,bcm963xx-cfe-nor-partitions";
		};
	};
};

&uart0 {
	status = "ok";
};


@import "twbs-222/bootstrap.less";

@import "mixins.less";
@import "variables.less";
@import "font-site.less";

.text-align-right  { text-align: right; }
.text-align-center { text-align: center; }

.navbar .brand {
//  padding: 11px 20px 9px;
  color: @white;
  font-family: @serifFontFamily;
  .icon-flag { padding-right: 3px; }
}

.navbar .nav > li > a { padding: 12px 10px 9px; }

h1, h2, h3, h4, h5, h6 { font-family: @serifFontFamily; }

#iconCarousel {
  a { color: @white; }
//  border: solid 1px @white;
  @size: 280px;
  font-size: @size;
  text-align: center;
  line-height: @size + 5;
  text-shadow: 2px 2px 3px @grayDarker;
  .carousel-control {
    top: @size + 33px;
    .square(23px);
    border-width: 3px;
    font-size: 17px;
    line-height: 25px;
    left: @size / 2 - 23;
    &.right {
      left: auto;
      right: @size / 2 - 23;
    }
  }
}

//a[href^='http://'] {
//  &:after {
//    font-family: FontAwesome;
//    content: "\0020 \f08e";
//    &:hover {
//      text-decoration: none;
//    }
//  }
//}

.jumbotron {
  background: @red;
  border-bottom: 1px solid @redDark;
  padding: 90px 0 48px;
//  #gradient > .radial( lighten(@red, 10%), @red);
//  background-color: @red;
  &, h1 { color: @white; }

//  &:after {
//    content:'';
//    display:block;
//    position:absolute;
//    top:0;
//    right:0;
//    bottom:0;
//    left:0;
//    background:url(../img/grain-tm400.png);
//    opacity:.5;
//  }

  h1 {
    font-size: 80px;
    letter-spacing: -2px;
    line-height: 1;
  }
  p {
    margin-top: 15px;
    margin-bottom: 30px;
    font-size: 30px;
    line-height: 1.3;
  }
  text-shadow: 2px 2px 2px @grayDark;
  ul {
    margin-left: 50px;
    li {
      &.icon-large:before {
        text-indent: -2em;
        vertical-align: baseline;
      }
      font-size: 15px;
      line-height: 30px;
      text-shadow: 1px 1px 1px @grayDark;
    }
  }
//  a { color: #fffeb8; }
  .btn-large {
////    .buttonBackground(@white, #bbb);
    font-family: @serifFontFamily;
////    color: @grayDark;
//    margin-top: 15px;
    font-weight: bold;
    font-size: 18px;
    padding: 13px 23px 13px 22px;
//    padding-left: 24px + 40;
    margin-right: 10px;
//    .border-radius(8px);
//    position: relative;
    text-align: left;
//    i  {
//      position: absolute;
//      top: 8px;
//      left: 15px;
//      font-size: 46px;
//    }
  }
  .hero-content {
//    width: 620px;
    text-align: center;
  }
  .shameless-self-promotion {
    font-size: 12px;
    margin-top: 15px;
    color: mix(@white, @red, 50%);
    text-shadow: none;
  }
}

.btn-github {
  .buttonBackground(@white, mix(@grayLighter, @grayLight, 50%));
}

.btn-primary, .btn-github {
  color: @grayDark;
  text-shadow: 0 -1px 0 rgba(255,255,255,.25);
  &:hover {
    text-shadow: 0 -1px 0 rgba(255,255,255,.25);
    color: @grayDark;
  }
}

section {
  padding-top: 40px;
}

#social-buttons {
  padding: 22px 0;
  text-align: center;
  background-color: #f5f5f5;
  border-top: 1px solid #fff;
  border-bottom: 1px solid #ddd;
  .btn {
//    font-family: @serifFontFamily;
      font-weight: bold;
//    font-size: @baseFontSize;
    padding: 0px 5px;
    line-height: @baseLineHeight - 3;
  }
  .count.btn {
    background: @white;
    font-weight: normal;
  }
  .watch, .fork {
    margin-right: 30px;
  }
}

.the-icons {
  list-style-type: none;
  margin: 0;
  li {
    cursor: pointer;
    line-height: 32px;
    height: 32px;
    padding-left: 12px;
    .border-radius(6px);
//    vertical-align: middle;

    [class^="icon-"],
    [class*=" icon-"] {
      width: 32px;
      font-size: 14px;
    }
    &:hover {
      background-color: lighten(@errorBackground, 6%);
      [class^="icon-"], [class*=" icon-"] {
        *font-size: 28px;
        *vertical-align: middle;
      }

      [class^="icon-"]:before,
      [class*=" icon-"]:before {
        font-size: 28px;
        vertical-align: -5px;
      }
    }
  }
}

#why, #whats-new {
  .row {
    margin-bottom: 20px;
  }
  h4 {
//    line-height: 28px;
    [class^="icon-"],
    [class*=" icon-"] {
      vertical-align: -10%;
      font-size: 28px;
//      width: 30px;
//      height: 30px;
      margin-right: 5px;
    }
  }
}

#examples {
  .btn-toolbar {
    margin-top: 0;
    margin-bottom: 20px;
  }
}

#integration {
  .row { margin-bottom: 40px; }
}

#examples, #code {
  form {
    margin-bottom: 25px;
    input {
      line-height: 1; // fixes a safari placeholder alignment issue
    }
  }

  .rating {
    unicode-bidi: bidi-override;
    direction: rtl;

    font-size: 30px;
    span.star {
      font-family: FontAwesome;
      font-weight: normal;
      font-style: normal;
      display: inline-block;
      &:hover {
        cursor: pointer;
      }
    }
    span.star:before {
      content: "\f006"; // empty star
      padding-right: 5px;
      color: @grayLight;
    }

    span.star:hover:before, span.star:hover ~ span.star:before {
      content: "\f005"; // solid star
      color: #e3cf7a;
    }
  }
}

#kyruus {
  color: @gray;
  font-size: 18px;
  &, li { line-height: 25px; }
  p {
    margin-bottom: 22px;
    strong { color: @grayDarker; }
  }
  ul {
    margin-top: 5px;
    margin-bottom: 22px;
    li { margin-top: 10px; }
    i {
      margin-top: 5px;
//      margin-right: .4em;
//      color: mix(@grayLight, @grayLighter, 50%);
      color: mix(@blue, @blueDark, 50%);
    }
  }
  .border {
    .icon-medkit { font-size: 224px; }
    border: solid 10px @grayLighter;
    padding: 1em 1.5em;
    margin-left: .2em;
    .border-radius(10px);
    a:hover .icon-medkit { text-decoration: none; }
//    a:hover i { text-decoration: underline; }
  }
  a {
    font-weight: bold;
    color: mix(@blue, @blueDark, 50%);
    &:hover {
      color: @blueDark;
    }
  }
}

.modal {
  width: 560px;
  max-height: 610px;
  .modal-body {
    *overflow: hidden; // ie7 fix
    max-height: none;
    padding-bottom: 0;
    .row { margin-bottom: 15px; }
    div.thumbnail {
      text-align: center;
      div { margin: 8px; }
    }
    .icon6 {
      width: 330px;
      > div.thumbnail > div { .icon-size(280px); }
    }
    .icon5 {
      width: 180px;
      > div.thumbnail > div { .icon-size(140px); }
    }
    .icon4 {
      width: 215px;
      > div.thumbnail > div { .icon-size(112px); }
    }
    .icon3 {
      width: 120px;
      > div.thumbnail > div { .icon-size(56px); }
    }
    .icon2 {
      width: 75px;
      > div.thumbnail > div { .icon-size(28px); }
    }
    .icon1 {
      width: 60px;
      > div.thumbnail > div { .icon-size(14px); }
    }
  }
}

.label,
.badge {
  background-color: @grayLighter;
}

.well.well-transparent {
  background-color: transparent;
}

footer {
//  #gradient > .vertical(@navbarInverseBackgroundHighlight, @navbarInverseBackground);
  background-color: @red;
  border-top: 1px solid mix(@red, @redDark, 50%);
  a {
    color: @white;
    text-shadow: 0 -1px 0 rgba(0,0,0,.25);
    &:hover {
      color: @white;
    }

  }

  color: mix(@red, @white, 35%);
  text-shadow: 0 -1px 0 rgba(0,0,0,.25);
  margin-top: 60px;
  padding-top: 45px;
  padding-bottom: 60px;
  *zoom: 1; // ie7 hack
  ul {
//    margin-left: 30px;
    line-height: 25px;
  }
}


/*
 * Copyright 2015 Linaro Ltd.
 * Copyright (C) 2014 ZTE Corporation.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#ifndef __ZTE_CLK_H
#define __ZTE_CLK_H
#include <linux/clk-provider.h>
#include <linux/spinlock.h>

#define PNAME(x) static const char *x[]

#define CLK_HW_INIT(_name, _parent, _ops, _flags)			\
	&(struct clk_init_data) {					\
		.flags		= _flags,				\
		.name		= _name,				\
		.parent_names	= (const char *[]) { _parent },		\
		.num_parents	= 1,					\
		.ops		= _ops,					\
	}

#define CLK_HW_INIT_PARENTS(_name, _parents, _ops, _flags)		\
	&(struct clk_init_data) {					\
		.flags		= _flags,				\
		.name		= _name,				\
		.parent_names	= _parents,				\
		.num_parents	= ARRAY_SIZE(_parents),			\
		.ops		= _ops,					\
	}

struct zx_pll_config {
	unsigned long rate;
	u32 cfg0;
	u32 cfg1;
};

struct clk_zx_pll {
	struct clk_hw hw;
	void __iomem *reg_base;
	const struct zx_pll_config *lookup_table; /* order by rate asc */
	int count;
	spinlock_t *lock;
	u8 pd_bit;		/* power down bit */
	u8 lock_bit;		/* pll lock flag bit */
};

#define PLL_RATE(_rate, _cfg0, _cfg1)	\
{					\
	.rate = _rate,			\
	.cfg0 = _cfg0,			\
	.cfg1 = _cfg1,			\
}

#define ZX_PLL(_name, _parent, _reg, _table, _pd, _lock)		\
{									\
	.reg_base	= (void __iomem *) _reg,			\
	.lookup_table	= _table,					\
	.count		= ARRAY_SIZE(_table),				\
	.pd_bit		= _pd,						\
	.lock_bit	= _lock,					\
	.hw.init	 = CLK_HW_INIT(_name, _parent, &zx_pll_ops,	\
				CLK_GET_RATE_NOCACHE),			\
}

/*
 * The pd_bit is not available on ZX296718, so let's pass something
 * bigger than 31, e.g. 0xff, to indicate that.
 */
#define ZX296718_PLL(_name, _parent, _reg, _table)			\
ZX_PLL(_name, _parent, _reg, _table, 0xff, 30)

struct zx_clk_gate {
	struct clk_gate gate;
	u16		id;
};

#define GATE(_id, _name, _parent, _reg, _bit, _flag, _gflags)		\
{									\
	.gate = {							\
		.reg = (void __iomem *) _reg,				\
		.bit_idx = (_bit),					\
		.flags = _gflags,					\
		.lock = &clk_lock,					\
		.hw.init = CLK_HW_INIT(_name,				\
					_parent,			\
					&clk_gate_ops,			\
					_flag | CLK_IGNORE_UNUSED),	\
	},								\
	.id	= _id,							\
}

struct zx_clk_fixed_factor {
	struct clk_fixed_factor factor;
	u16	id;
};

#define FFACTOR(_id, _name, _parent, _mult, _div, _flag)		\
{									\
	.factor = {							\
		.div		= _div,					\
		.mult		= _mult,				\
		.hw.init	= CLK_HW_INIT(_name,			\
					      _parent,			\
					      &clk_fixed_factor_ops,	\
					      _flag),			\
	},								\
	.id = _id,							\
}

struct zx_clk_mux {
	struct clk_mux mux;
	u16	id;
};

#define MUX_F(_id, _name, _parent, _reg, _shift, _width, _flag, _mflag)	\
{									\
	.mux = {							\
		.reg		= (void __iomem *) _reg,		\
		.mask		= BIT(_width) - 1,			\
		.shift		= _shift,				\
		.flags		= _mflag,				\
		.lock		= &clk_lock,				\
		.hw.init	= CLK_HW_INIT_PARENTS(_name,		\
						      _parent,		\
						      &clk_mux_ops,	\
						      _flag),		\
	},								\
	.id = _id,							\
}

#define MUX(_id, _name, _parent, _reg, _shift, _width)			\
MUX_F(_id, _name, _parent, _reg, _shift, _width, 0, 0)

struct zx_clk_div {
	struct clk_divider div;
	u16	id;
};

#define DIV_T(_id, _name, _parent, _reg, _shift, _width, _flag, _table)	\
{									\
	.div = {							\
		.reg		= (void __iomem *) _reg,		\
		.shift		= _shift,				\
		.width		= _width,				\
		.flags		= 0,					\
		.table		= _table,				\
		.lock		= &clk_lock,				\
		.hw.init	= CLK_HW_INIT(_name,			\
					      _parent,			\
					      &clk_divider_ops,		\
					      _flag),			\
	},								\
	.id = _id,							\
}

struct clk_zx_audio_divider {
	struct clk_hw				hw;
	void __iomem				*reg_base;
	unsigned int				rate_count;
	spinlock_t				*lock;
	u16					id;
};

#define AUDIO_DIV(_id, _name, _parent, _reg)				\
{									\
	.reg_base	= (void __iomem *) _reg,			\
	.lock		= &clk_lock,					\
	.hw.init	= CLK_HW_INIT(_name,				\
				      _parent,				\
				      &zx_audio_div_ops,		\
				      0),				\
	.id = _id,							\
}

struct clk *clk_register_zx_pll(const char *name, const char *parent_name,
	unsigned long flags, void __iomem *reg_base,
	const struct zx_pll_config *lookup_table, int count, spinlock_t *lock);

struct clk_zx_audio {
	struct clk_hw hw;
	void __iomem *reg_base;
};

struct clk *clk_register_zx_audio(const char *name,
				  const char * const parent_name,
				  unsigned long flags, void __iomem *reg_base);

extern const struct clk_ops zx_pll_ops;
extern const struct clk_ops zx_audio_div_ops;

#endif


fragment NameRendererFragment on User {
  id
  nameRendererForContext(context: HEADER) @match {
    ...PlainUserNameRenderer_name @module(name: "PlainUserNameRenderer.react")
    ...MarkdownUserNameRenderer_name
      @module(name: "MarkdownUserNameRenderer.react")
  }
}

fragment PlainUserNameRenderer_name on PlainUserNameRenderer {
  plaintext
  data {
    text
  }
}

fragment MarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
  markdown
  data {
    markup
  }
}


/*
Copyright 2017 The Kubernetes 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.
*/

// This file was automatically generated by lister-gen

package v1alpha1

// PriorityClassListerExpansion allows custom methods to be added to
// PriorityClassLister.
type PriorityClassListerExpansion interface{}


DlangTokenType.ID ('write')
DlangTokenType.( ('(')
DlangTokenType.DOUBLE_QUOTED_STRING ('"1"')
DlangTokenType.) (')')
DlangTokenType.; (';')
WHITE_SPACE ('\n')
DlangTokenType.{ ('{')
WHITE_SPACE ('\n')
WHITE_SPACE ('    ')
DlangTokenType.ID ('write')
DlangTokenType.( ('(')
DlangTokenType.DOUBLE_QUOTED_STRING ('"2"')
DlangTokenType.) (')')
DlangTokenType.; (';')
WHITE_SPACE ('\n')
WHITE_SPACE ('    ')
DlangTokenType.scope ('scope')
DlangTokenType.( ('(')
DlangTokenType.ID ('exit')
DlangTokenType.) (')')
WHITE_SPACE (' ')
DlangTokenType.ID ('write')
DlangTokenType.( ('(')
DlangTokenType.DOUBLE_QUOTED_STRING ('"3"')
DlangTokenType.) (')')
DlangTokenType.; (';')
WHITE_SPACE ('\n')
WHITE_SPACE ('    ')
DlangTokenType.scope ('scope')
DlangTokenType.( ('(')
DlangTokenType.ID ('exit')
DlangTokenType.) (')')
WHITE_SPACE (' ')
DlangTokenType.ID ('write')
DlangTokenType.( ('(')
DlangTokenType.DOUBLE_QUOTED_STRING ('"4"')
DlangTokenType.) (')')
DlangTokenType.; (';')
WHITE_SPACE ('\n')
WHITE_SPACE ('    ')
DlangTokenType.ID ('write')
DlangTokenType.( ('(')
DlangTokenType.DOUBLE_QUOTED_STRING ('"5"')
DlangTokenType.) (')')
DlangTokenType.; (';')
WHITE_SPACE ('\n')
DlangTokenType.} ('}')
WHITE_SPACE ('\n')
DlangTokenType.ID ('writeln')
DlangTokenType.( ('(')
DlangTokenType.) (')')
DlangTokenType.; (';')


query FeedRepositoryQuery($type: FeedType!, $limit: Int!) {
  feed(type: $type, limit: $limit) {
    repository {
      name
    }
  }
}


require('../modules/core.dict');
require('../modules/core.get-iterator-method');
require('../modules/core.get-iterator');
require('../modules/core.is-iterable');
require('../modules/core.delay');
require('../modules/core.function.part');
require('../modules/core.object.is-object');
require('../modules/core.object.classof');
require('../modules/core.object.define');
require('../modules/core.object.make');
require('../modules/core.number.iterator');
require('../modules/core.regexp.escape');
require('../modules/core.string.escape-html');
require('../modules/core.string.unescape-html');
module.exports = require('../modules/_core');


select @@global.performance_schema_max_file_classes;
@@global.performance_schema_max_file_classes
123
select @@session.performance_schema_max_file_classes;
ERROR HY000: Variable 'performance_schema_max_file_classes' is a GLOBAL variable
show global variables like 'performance_schema_max_file_classes';
Variable_name	Value
performance_schema_max_file_classes	123
show session variables like 'performance_schema_max_file_classes';
Variable_name	Value
performance_schema_max_file_classes	123
select * from performance_schema.global_variables
where variable_name='performance_schema_max_file_classes';
VARIABLE_NAME	VARIABLE_VALUE
performance_schema_max_file_classes	123
select * from performance_schema.session_variables
where variable_name='performance_schema_max_file_classes';
VARIABLE_NAME	VARIABLE_VALUE
performance_schema_max_file_classes	123
set global performance_schema_max_file_classes=1;
ERROR HY000: Variable 'performance_schema_max_file_classes' is a read only variable
set session performance_schema_max_file_classes=1;
ERROR HY000: Variable 'performance_schema_max_file_classes' is a read only variable


Sample code provided with the SVG sources
=========================================

There are a few code samples for SVG usage in the folder _Samples_ under the project root.
All of these samples are included in the solution provided with the source code for easier usage.
The following samples are currently available:

SVGViewer
---------
This is a form-based .NET application that is able to read an SVG file and display it, along with it's
source XML. It also allows to edit the XML, so it can be used to see how arbitrary SVG code will be
displayed using the library.

Apart from being useful as a tool, the source code shows how to load an SVG image, render it, and
save it in another format (PNG in this case). You will find the relevant code in _SvgViewer.cs_

SvgSample
---------
This is a small command line application that reads in a sample SVG, changes the style of one of it's
elements, and saves it to a PNG file. It shows how to access and alter an element of the SVG source tree.

XMLOutputTester
---------------
This is a simple form-based application that shows how to create a new SVG document from scratch (in this
example representing a filled circle), display it's XML source and save it to a file.

Entities
--------
Another small command line application that loads an example file that references entities not present
in the file, and provides these entities with matching styles dynamically in the `SvgDocument.Open` call.

SvgConsole
----------
This is a simple command-line application to convert one or many input SVG files to PNG images. It shows how to open a SVG document and create bitmap, and how to save resulting bitmap to a PNG file.

---
As you can see, there are currently very few code samples. We encourage you to add your own sample code
in pull requests, or provide code snippets that can be made into samples.

This project lives from public contributions, and we appreciate any help!

---


# Linux Crash Dumping

Official builds of Chrome support crash dumping and reporting using the Google
crash servers. This is a guide to how this works.

[TOC]

## Breakpad

Breakpad is an open source library which we use for crash reporting across all
three platforms (Linux, Mac and Windows). For Linux, a substantial amount of
work was required to support cross-process dumping. At the time of writing this
code is currently forked from the upstream breakpad repo. While this situation
remains, the forked code lives in `third_party/breakpad/linux`. The upstream
repo is mirrored in `third_party/breakpad/breakpad`.

The code currently supports i386 only. Getting x86-64 to work should only be a
minor amount of work.

### Minidumps

Breakpad deals in a file format called 'minidumps'. This is a Microsoft format
and thus is defined by in-memory structures which are dumped, raw, to disk. The
main header file for this file format is
`third_party/breakpad/breakpad/src/google_breakpad/common/minidump_format.h`.

At the top level, the minidump file format is a list of key-value pairs. Many of
the keys are defined by the minidump format and contain cross-platform
representations of stacks, threads etc. For Linux we also define a number of
custom keys containing `/proc/cpuinfo`, `lsb-release` etc. These are defined in
`third_party/breakpad/breakpad/linux/minidump_format_linux.h`.

### Catching exceptions

Exceptional conditions (such as invalid memory references, floating point
exceptions, etc) are signaled by synchronous signals to the thread which caused
them. Synchronous signals are always run on the thread which triggered them as
opposed to asynchronous signals which can be handled by any thread in a
thread-group which hasn't masked that signal.

All the signals that we wish to catch are synchronous except SIGABRT, and we can
always arrange to send SIGABRT to a specific thread. Thus, we find the crashing
thread by looking at the current thread in the signal handler.

The signal handlers run on a pre-allocated stack in case the crash was triggered
by a stack overflow.

Once we have started handling the signal, we have to assume that the address
space is compromised. In order not to fall prey to this and crash (again) in the
crash handler, we observe some rules:

1.  We don't enter the dynamic linker. This, observably, can trigger crashes in
    the crash handler. Unfortunately, entering the dynamic linker is very easy
    and can be triggered by calling a function from a shared library who's
    resolution hasn't been cached yet. Since we can't know which functions have
    been cached we avoid calling any of these functions with one exception:
    `memcpy`. Since the compiler can emit calls to `memcpy` we can't really
    avoid it.
1.  We don't allocate memory via malloc as the heap may be corrupt. Instead we
    use a custom allocator (in `breadpad/linux/memory.h`) which gets clean pages
    directly from the kernel.

In order to avoid calling into libc we have a couple of header files which wrap
the system calls (`linux_syscall_support.h`) and reimplement a tiny subset of
libc (`linux_libc_support.h`).

### Self dumping

The simple case occurs when the browser process crashes. Here we catch the
signal and `clone` a new process to perform the dumping. We have to use a new
process because a process cannot ptrace itself.

The dumping process then ptrace attaches to all the threads in the crashed
process and writes out a minidump to `/tmp`. This is generic breakpad code.

Then we reach the Chrome specific parts in `chrome/app/breakpad_linux.cc`. Here
we construct another temporary file and write a MIME wrapping of the crash dump
ready for uploading. We then fork off `wget` to upload the file. Based on Debian
popcorn, `wget` is very commonly installed (much more so than `libcurl`) and
`wget` handles the HTTPS gubbins for us.

### Renderer dumping

In the case of a crash in the renderer, we don't want the renderer handling the
crash dumping itself. In the future we will sandbox the renderer and allowing it
the authority to crash dump itself is too much.

Thus, we split the crash dumping in two parts: the gathering of information
which is done in process and the external dumping which is done out of process.
In the case above, the latter half was done in a `clone`d child. In this case,
the browser process handles it.

When renderers are forked off, they have a `UNIX DGRAM` socket in file
descriptor 4. The signal handler then calls into Chrome specific code
(`chrome/renderer/render_crash_handler_linux.cc`) when it would otherwise
`clone`. The Chrome specific code sends a datagram to the socket which contains:

*   Information which is only available to the signal handler (such as the
    `ucontext` structure).
*   A file descriptor to a pipe which it then blocks on reading from.
*   A `CREDENTIALS` structure giving its PID.

The kernel enforces that the renderer isn't lying in the `CREDENTIALS` structure
so it can't ask the browser to crash dump another process.

The browser then performs the ptrace and minidump writing which would otherwise
be performed in the `clone`d process and does the MIME wrapping the uploading as
normal.

Once the browser has finished getting information from the crashed renderer via
ptrace, it writes a byte to the file descriptor which was passed from the
renderer. The renderer than wakes up (because it was blocking on reading from
the other end) and rethrows the signal to itself. It then appears to crash
'normally' and other parts of the browser notice the abnormal termination and
display the sad tab.

## How to test Breakpad support in Chromium

*   Build Chromium as normal.
*   Run the browser with the environment variable
    [CHROME_HEADLESS=1](https://crbug.com/19663). This enables crash dumping but
    prevents crash dumps from being uploaded and deleted.

    ```shell
    env CHROME_HEADLESS=1 ./out/Debug/chrome-wrapper
    ```
*   Visit the special URL `chrome://crash` to trigger a crash in the renderer
    process.
*   A crash dump file should appear in the directory
    `~/.config/chromium/Crash Reports`.


# -*- coding: utf-8 -*-
"""Module used to launch rating dialogues and send ratings to Trakt"""

import xbmc
import xbmcaddon
import xbmcgui
from resources.lib import utilities
from resources.lib import kodiUtilities
from resources.lib import globals
import logging

logger = logging.getLogger(__name__)

__addon__ = xbmcaddon.Addon("script.trakt")

def ratingCheck(media_type, items_to_rate, watched_time, total_time):
    """Check if a video should be rated and if so launches the rating dialog"""
    logger.debug("Rating Check called for '%s'" % media_type)
    if not kodiUtilities.getSettingAsBool("rate_%s" % media_type):
        logger.debug("'%s' is configured to not be rated." % media_type)
        return
    if items_to_rate is None:
        logger.debug("Summary information is empty, aborting.")
        return
    watched = (watched_time / total_time) * 100
    if watched >= kodiUtilities.getSettingAsFloat("rate_min_view_time"):
        rateMedia(media_type, items_to_rate)
    else:
        logger.debug("'%s' does not meet minimum view time for rating (watched: %0.2f%%, minimum: %0.2f%%)" % (media_type, watched, kodiUtilities.getSettingAsFloat("rate_min_view_time")))

def rateMedia(media_type, itemsToRate, unrate=False, rating=None):
    """Launches the rating dialog"""
    for summary_info in itemsToRate:
        if not utilities.isValidMediaType(media_type):
            logger.debug("Not a valid media type")
            return
        elif 'user' not in summary_info:
            logger.debug("No user data")
            return

        s = utilities.getFormattedItemName(media_type, summary_info)

        logger.debug("Summary Info %s" % summary_info)

        if unrate:
            rating = None

            if summary_info['user']['ratings']['rating'] > 0:
                rating = 0

            if not rating is None:
                logger.debug("'%s' is being unrated." % s)
                __rateOnTrakt(rating, media_type, summary_info, unrate=True)
            else:
                logger.debug("'%s' has not been rated, so not unrating." % s)

            return

        rerate = kodiUtilities.getSettingAsBool('rate_rerate')
        if rating is not None:
            if summary_info['user']['ratings']['rating'] == 0:
                logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating))
                __rateOnTrakt(rating, media_type, summary_info)
            else:
                if rerate:
                    if not summary_info['user']['ratings']['rating'] == rating:
                        logger.debug("Rating for '%s' is being set to '%d' manually." % (s, rating))
                        __rateOnTrakt(rating, media_type, summary_info)
                    else:
                        kodiUtilities.notification(kodiUtilities.getString(32043), s)
                        logger.debug("'%s' already has a rating of '%d'." % (s, rating))
                else:
                    kodiUtilities.notification(kodiUtilities.getString(32041), s)
                    logger.debug("'%s' is already rated." % s)
            return

        if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating']:
            if not rerate:
                logger.debug("'%s' has already been rated." % s)
                kodiUtilities.notification(kodiUtilities.getString(32041), s)
                return
            else:
                logger.debug("'%s' is being re-rated." % s)

        gui = RatingDialog(
            "script-trakt-RatingDialog.xml",
            __addon__.getAddonInfo('path'),
            media_type,
            summary_info,
            rerate
        )

        gui.doModal()
        if gui.rating:
            rating = gui.rating
            if rerate:
                if summary_info['user']['ratings'] and summary_info['user']['ratings']['rating'] > 0 and rating == summary_info['user']['ratings']['rating']:
                    rating = 0

            if rating == 0 or rating == "unrate":
                __rateOnTrakt(rating, gui.media_type, gui.media, unrate=True)
            else:
                __rateOnTrakt(rating, gui.media_type, gui.media)
        else:
            logger.debug("Rating dialog was closed with no rating.")

        del gui
        #Reset rating and unrate for multi part episodes
        unrate=False
        rating=None

def __rateOnTrakt(rating, media_type, media, unrate=False):
    logger.debug("Sending rating (%s) to Trakt.tv" % rating)

    params = media
    if utilities.isMovie(media_type):
        key = 'movies'
        params['rating'] = rating
        if 'movieid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetMovieDetails", "params": {"movieid": media['movieid'], "userrating": rating}})
    elif utilities.isShow(media_type):
        key = 'shows'
        params['rating'] = rating
        if 'tvshowid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetTVShowDetails", "params": {"tvshowid": media['tvshowid'], "userrating": rating}})
    elif utilities.isSeason(media_type):
        key = 'shows'
        params['seasons'] = [{'rating': rating, 'number': media['season']}]
    elif utilities.isEpisode(media_type):
        key = 'episodes'
        params['rating'] = rating
        if 'episodeid' in media:
            kodiUtilities.kodiJsonRequest({"jsonrpc": "2.0", "id": 1, "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid": media['episodeid'], "userrating": rating}})
    else:
        return
    root = {key: [params]}

    if not unrate:
        data = globals.traktapi.addRating(root)
    else:
        data = globals.traktapi.removeRating(root)

    if data:
        s = utilities.getFormattedItemName(media_type, media)
        if 'not_found' in data and not data['not_found']['movies'] and not data['not_found']['episodes'] and not data['not_found']['shows']:

            if not unrate:
                kodiUtilities.notification(kodiUtilities.getString(32040), s)
            else:
                kodiUtilities.notification(kodiUtilities.getString(32042), s)
        else:
            kodiUtilities.notification(kodiUtilities.getString(32044), s)

class RatingDialog(xbmcgui.WindowXMLDialog):
    buttons = {
        11030: 1,
        11031: 2,
        11032: 3,
        11033: 4,
        11034: 5,
        11035: 6,
        11036: 7,
        11037: 8,
        11038: 9,
        11039: 10
    }

    focus_labels = {
        11030: 32028,
        11031: 32029,
        11032: 32030,
        11033: 32031,
        11034: 32032,
        11035: 32033,
        11036: 32034,
        11037: 32035,
        11038: 32036,
        11039: 32027
    }

    def __init__(self, xmlFile, resourcePath, media_type, media, rerate):
        self.media_type = media_type
        self.media = media
        self.rating = None
        self.rerate = rerate
        self.default_rating = kodiUtilities.getSettingAsInt('rating_default')

    def __new__(cls, xmlFile, resourcePath, media_type, media, rerate):
        return super(RatingDialog, cls).__new__(cls, xmlFile, resourcePath)

    def onInit(self):
        s = utilities.getFormattedItemName(self.media_type, self.media)
        self.getControl(10012).setLabel(s)

        rateID = 11029 + self.default_rating
        if self.rerate and self.media['user']['ratings'] and int(self.media['user']['ratings']['rating']) > 0:
            rateID = 11029 + int(self.media['user']['ratings']['rating'])
        self.setFocus(self.getControl(rateID))

    def onClick(self, controlID):
        if controlID in self.buttons:
            self.rating = self.buttons[controlID]
            self.close()

    def onFocus(self, controlID):
        if controlID in self.focus_labels:
            s = kodiUtilities.getString(self.focus_labels[controlID])

            if self.rerate:
                if self.media['user']['ratings'] and self.media['user']['ratings']['rating'] == self.buttons[controlID]:
                    if utilities.isMovie(self.media_type):
                        s = kodiUtilities.getString(32037)
                    elif utilities.isShow(self.media_type):
                        s = kodiUtilities.getString(32038)
                    elif utilities.isEpisode(self.media_type):
                        s = kodiUtilities.getString(32039)
                    elif utilities.isSeason(self.media_type):
                        s = kodiUtilities.getString(32132)
                    else:
                        pass

            self.getControl(10013).setLabel(s)
        else:
            self.getControl(10013).setLabel('')


/*
TEST_OUTPUT:
---
fail_compilation/fail20448.d(16): Error: returning `p.x` escapes a reference to local variable `p`
fail_compilation/fail20448.d(22): Error: template instance `fail20448.member!"x"` error instantiating
---
*/

struct S
{
    int x, y;
}

ref int member(string mem)(S p)
{
    return p.x;
}

void main()
{
    S p;
    p.member!"x" = 2;
}


      November 15, 1996
      Dear Personal Donor:
      In the short while since Goodwill helped him find his job, Robert has
      learned to thoroughly clean a motel room in about 40 minutes. His job
      objectives call for him to do it in 30.
      He has no time to waste.
      Neither do we. With the help of friends like you, Goodwill has
      continued to adapt our services to meet the human needs of our changing
      society.
      We don't waste time as we are helping the community. And we don't
      waste money. The gift that I am asking you to make will be used to
      continue our mission of helping people prepare for, find and keep
      jobs.
      In their December, 1995 review of the nation's best charities, U.S.
      News & World Report called Goodwill one of the five "Standout Good
      Guys." The magazine stated that Goodwill (as well as the other standouts)
      is "uniquely effective, innovative or valuable."
      While I appreciate U.S. News & World Report's endorsement, the
      true value of your support is measured by the way Goodwill takes on
      problems that affect all of us.
      Every time we help someone find a solution to their employment
      barrier, the positive effects radiate throughout our community: The
      business community welcomes not only another worker, but a consumer with
      increased purchasing power. Parents act as role models of
      self-sufficiency instead of dependency. Tax dollars that would have been
      spent on public assistance are saved.
      You and I know that solutions to difficult problems don't just happen.
      At Goodwill, it is the hard work of staff and those who benefit from our
      services that produces the kind of inspiring results I see every day:
      A Goodwill staff member addresses a group of welfare recipients: "You
      can earn the money to support yourself and your family," she says. "You
      can get off welfare. I know you can... I did."
      A participant in a Goodwill program rushes back from a job interview
      to share the results with his classmates in our desktop publishing
      training program. once his tears have subsided, he confirms what his
      classmates have already figured out: he just received a job offer -- his
      first in five years.
      Addressing a meeting at a neighborhood center, a Goodwill staff member
      tells the audience how Goodwill can help them find and keep jobs. On his
      way home, he shares the story with four people at a street corner. At the
      next corner he tells five more.
      In order to develop job skills, a man with some serious disabilities
      begins working in Goodwill's industrial division. It takes a long time
      for him to gain the self-confidence to work elsewhere in the community.
      Eventually, he turns your support into a payoff for all of us. He proudly
      leaves Goodwill to support himself.
      These people and their successes are real. Just like the respect we've
      earned from U.S. News & World Report. Just like the impact Goodwill's
      work has on our community.
      Real work. Real results. A real difference in people's lives -- in all
      of our lives.
      The people who can benefit most directly from your generosity have no
      time to waste. Neither do the rest of us who feel the positive results of
      their success. Your support helps provide real solutions.
      Please use the enclosed response card and envelope to give generously
      to Goodwill today.
      Sincerely,

      Jack Dustman Board Member and Former Chairman


description=VCD NTSC
frame_rate_num=30000
frame_rate_den=1001
width=352
height=240
progressive=1
sample_aspect_num=10
sample_aspect_den=11
display_aspect_num=4
display_aspect_den=3
colorspace=601


from os.path import dirname

def load_tests(loader, standard_tests, pattern):
    this_dir = dirname(__file__)
    top_dir = dirname(dirname(this_dir))
    package_tests = loader.discover(start_dir=this_dir, pattern='test*.py',
                                    top_level_dir=top_dir)
    standard_tests.addTests(package_tests)
    return standard_tests


/***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and         *
* Martin Renou                                                             *
* Copyright (c) QuantStack                                                 *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XFRAME_XAXIS_FUNCTION_HPP
#define XFRAME_XAXIS_FUNCTION_HPP

#include "xtensor/xoptional.hpp"
#include "xtensor/xgenerator.hpp"

#include "xframe_expression.hpp"
#include "xframe_utils.hpp"
#include "xaxis_meta.hpp"
#include "xaxis_expression_leaf.hpp"

namespace xf
{
    /******************
     * xaxis_function *
     ******************/

    /**
     * @class xaxis_function
     * @brief An expression of xaxis
     *
     * The xaxis_function class is used for creating an expression on named axis, e.g.
     * `auto expr = not_equal(axis1, 2) && axis2 < 2`.
     *
     * @tparam F the function type.
     * @tparam R the result type.
     * @tparam CT the function argument types.
     * @sa xaxis_expression_leaf
     * @sa xnamed_axis
     */
    template <class F, class R, class... CT>
    class xaxis_function : public xt::xexpression<xaxis_function<F, R, CT...>>
    {
    public:

        using self_type = xaxis_function<F, R, CT...>;
        using functor_type = std::remove_reference_t<F>;

        using value_type = R;
        using reference = value_type;
        using const_reference = value_type;
        using pointer = value_type*;
        using const_pointer = const value_type*;
        using name_type = detail::common_name_type_t<std::decay_t<xaxis_expression_closure_t<CT>>...>;
        using size_type = xt::common_size_type_t<std::decay_t<xaxis_expression_closure_t<CT>>...>;

        template <std::size_t N = dynamic()>
        using selector_sequence_type = detail::xselector_sequence_t<std::pair<name_type, size_type>, N>;

        using expression_tag = xaxis_expression_tag;

        template <class Func, class U = std::enable_if<!std::is_base_of<Func, self_type>::value>>
        xaxis_function(Func&& f, CT... e) noexcept;

        template <std::size_t N = dynamic()>
        const_reference operator()(const selector_sequence_type<N>& selector) const;

    private:

        template <std::size_t N, std::size_t... I>
        const_reference evaluate(std::index_sequence<I...>, const selector_sequence_type<N>& selector) const;

        std::tuple<xaxis_expression_closure_t<CT>...> m_e;
        functor_type m_f;
    };

    /*********************************
     * xaxis_function implementation *
     *********************************/

    /**
     * Builds an axis function.
     * @param f the function to apply.
     * @param e the function arguments.
     */
    template <class F, class R, class... CT>
    template <class Func, class>
    inline xaxis_function<F, R, CT...>::xaxis_function(Func&& f, CT... e) noexcept
        : m_e(detail::get_axis_closure(std::forward<CT>(e))...),
          m_f(std::forward<Func>(f))
    {
    }

    /**
     * Returns an evaluation of the xaxis_function.
     * Example:
     * \code{.cpp}
     * auto axis1 = named_axis("abs", axis(16));
     * auto axis2 = named_axis("ord", axis({'a', 'c', 'i'}));
     *
     * auto func1 = axis1 < 5 && not_equal(axis2, 'i');
     *
     * // This will evaluate the xaxis_function for `axis1.label(10) == 9` and `axis2.label(1) == 'c'``
     * func1({{"abs", 10}, {"ord", 1}});
     * \endcode
     *
     * @param selector a selector_sequence_type for selecting the position
     *                 where you want to evaluate the function.
     * @return the evaluation of the xaxis_function
     */
    template <class F, class R, class... CT>
    template <std::size_t N>
    inline auto xaxis_function<F, R, CT...>::operator()(const selector_sequence_type<N>& selector) const -> const_reference
    {
        return evaluate<N>(std::make_index_sequence<sizeof...(CT)>(), selector);
    }

    template <class F, class R, class... CT>
    template <std::size_t N, std::size_t... I>
    inline auto xaxis_function<F, R, CT...>::evaluate(std::index_sequence<I...>, const selector_sequence_type<N>& selector) const -> const_reference
    {
#ifdef _MSC_VER
        return m_f(std::get<I>(m_e).operator()<N>(selector)...);
#else
        return m_f(std::get<I>(m_e).template operator()<N>(selector)...);
#endif
    }

    /**********************
     * axis_function_mask *
     **********************/

    namespace detail
    {
        template <class AF, class DM>
        class axis_function_mask_impl
        {
        public:

            using axis_function_type = std::remove_reference_t<AF>;

            using value_type = typename axis_function_type::value_type;
            using name_type = typename axis_function_type::name_type;
            using size_type = typename axis_function_type::size_type;

            template <std::size_t N = dynamic()>
            using selector_sequence_type = detail::xselector_sequence_t<std::pair<name_type, size_type>, N>;

            axis_function_mask_impl(AF&& axis_function, DM&& dim_mapping)
                : m_axis_function(std::forward<AF>(axis_function)),
                  m_dimension_mapping(std::forward<DM>(dim_mapping))
            {
            }

            template <class... Args>
            inline value_type operator()(Args... args) const
            {
                auto selector = make_selector(std::make_index_sequence<sizeof...(Args)>(), args...);
#ifdef _MSC_VER
                return m_axis_function.operator()<sizeof...(Args)>(selector);
#else
                return m_axis_function.template operator()<sizeof...(Args)>(selector);
#endif
            }

            template <class It>
            inline value_type element(It first, It last) const
            {
                // TODO avoid dynamic allocation
                auto selector = selector_sequence_type<dynamic()>();
                std::size_t i = 0;
                for (It it = first; it != last; ++it)
                {
                    selector.push_back(std::make_pair(m_dimension_mapping.label(i++), static_cast<size_type>(*it)));
                }
#ifdef _MSC_VER
                return m_axis_function.operator()<dynamic()>(selector);
#else
                return m_axis_function.template operator()<dynamic()>(selector);
#endif
            }

        private:

            AF m_axis_function;
            DM m_dimension_mapping;

            template <class... Args, std::size_t... I>
            inline selector_sequence_type<sizeof...(Args)> make_selector(std::index_sequence<I...>, Args&&... args) const
            {
                return {std::make_pair(m_dimension_mapping.label(I), static_cast<size_type>(args))...};
            }
        };
    }

    template <class AF, class DM, class S>
    inline auto axis_function_mask(AF&& axis_function, DM&& dim_mapping, const S& shape) noexcept
    {
        return xt::detail::make_xgenerator(
            detail::axis_function_mask_impl<AF, DM>(std::forward<AF>(axis_function), std::forward<DM>(dim_mapping)),
            shape
        );
    }
}

#endif


/*
 * Copyright 2016-present Open Networking Foundation
 *
 * 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 org.onosproject.rest.resources;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.cluster.NodeId;
import org.onosproject.cluster.RoleInfo;
import org.onosproject.mastership.MastershipAdminService;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.device.DeviceService;
import org.onosproject.rest.AbstractWebResource;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

import static org.onlab.util.Tools.nullIsNotFound;
import static org.onlab.util.Tools.readTreeFromStream;

/**
 * Manage the mastership of ONOS instances.
 */
@Path("mastership")
public final class MastershipWebResource extends AbstractWebResource {

    private static final String DEVICE_IDS = "deviceIds";
    private static final String DEVICE_ID = "deviceId";
    private static final String NODE_ID = "nodeId";

    private static final String DEVICE_ID_INVALID = "Invalid deviceId for setting role";
    private static final String NODE_ID_INVALID = "Invalid nodeId for setting role";

    private static final String DEVICE_ID_NOT_FOUND = "Device Id is not found";
    private static final String NODE_ID_NOT_FOUND = "Node id is not found";
    private static final String ROLE_INFO_NOT_FOUND = "Role info is not found";
    private static final String MASTERSHIP_ROLE_NOT_FOUND = "Mastership role is not found";

    /**
     * Returns the role of the local node for the specified device.
     *
     * @param deviceId device identifier
     * @return 200 OK with role of the current node
     * @onos.rsModel MastershipRole
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/local")
    public Response getLocalRole(@PathParam("deviceId") String deviceId) {
        MastershipService mastershipService = get(MastershipService.class);
        MastershipRole role = mastershipService.getLocalRole(DeviceId.deviceId(deviceId));
        ObjectNode root = codec(MastershipRole.class).encode(role, this);
        return ok(root).build();
    }

    /**
     * Returns the current master for a given device.
     *
     * @param deviceId device identifier
     * @return 200 OK with the identifier of the master controller for the device
     * @onos.rsModel NodeId
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/master")
    public Response getMasterFor(@PathParam("deviceId") String deviceId) {
        MastershipService mastershipService = get(MastershipService.class);
        NodeId id = nullIsNotFound(mastershipService.getMasterFor(
                    DeviceId.deviceId(deviceId)), NODE_ID_NOT_FOUND);

        ObjectNode root = mapper().createObjectNode();
        root.put(NODE_ID, id.id());
        return ok(root).build();
    }

    /**
     * Returns controllers connected to a given device, in order of
     * preference. The first entry in the list is the current master.
     *
     * @param deviceId device identifier
     * @return 200 OK with a list of controller identifiers
     * @onos.rsModel RoleInfo
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/role")
    public Response getNodesFor(@PathParam("deviceId") String deviceId) {
        MastershipService mastershipService = get(MastershipService.class);
        RoleInfo info = nullIsNotFound(mastershipService.getNodesFor(
                        DeviceId.deviceId(deviceId)), ROLE_INFO_NOT_FOUND);
        ObjectNode root = codec(RoleInfo.class).encode(info, this);
        return ok(root).build();
    }

    /**
     * Returns the devices for which a controller is master.
     *
     * @param nodeId controller identifier
     * @return 200 OK with a set of device identifiers
     * @onos.rsModel DeviceIds
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{nodeId}/device")
    public Response getDeviceOf(@PathParam("nodeId") String nodeId) {
        MastershipService mastershipService = get(MastershipService.class);
        ObjectNode root = mapper().createObjectNode();
        ArrayNode devicesNode = root.putArray(DEVICE_IDS);

        Set<DeviceId> devices = mastershipService.getDevicesOf(NodeId.nodeId(nodeId));
        if (devices != null) {
            devices.forEach(id -> devicesNode.add(id.toString()));
        }

        return ok(root).build();
    }

    /**
     * Returns the mastership status of the local controller for a given
     * device forcing master selection if necessary.
     *
     * @param deviceId device identifier
     * @return 200 OK with the role of this controller instance
     * @onos.rsModel MastershipRole
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/request")
    public Response requestRoleFor(@PathParam("deviceId") String deviceId) {
        MastershipService mastershipService = get(MastershipService.class);
        DeviceService deviceService = get(DeviceService.class);
        DeviceId id = DeviceId.deviceId(deviceId);
        nullIsNotFound(deviceService.getDevice(id), DEVICE_ID_NOT_FOUND);

        MastershipRole role = nullIsNotFound(mastershipService.requestRoleForSync(id),
                        MASTERSHIP_ROLE_NOT_FOUND);
        ObjectNode root = codec(MastershipRole.class).encode(role, this);
        return ok(root).build();
    }

    /**
     * Abandons mastership of the specified device on the local node thus
     * forcing selection of a new master. If the local node is not a master
     * for this device, no master selection will occur.
     *
     * @param deviceId device identifier
     * @return status of the request - CREATED if the JSON is correct
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{deviceId}/relinquish")
    public Response relinquishMastership(@PathParam("deviceId") String deviceId) {
        MastershipService mastershipService = get(MastershipService.class);
        DeviceId id = DeviceId.deviceId(deviceId);
        mastershipService.relinquishMastershipSync(id);
        return Response.created(id.uri()).build();
    }

    /**
     * Applies the current mastership role for the specified device.
     *
     * @param stream JSON representation of device, node, mastership info
     * @return status of the request - CREATED if the JSON is correct,
     * BAD_REQUEST if the JSON is invalid
     * @onos.rsModel MastershipPut
     */
    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public Response setRole(InputStream stream) {
        MastershipAdminService mastershipAdminService = get(MastershipAdminService.class);

        try {
            ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
            JsonNode deviceIdJson = jsonTree.get(DEVICE_ID);
            JsonNode nodeIdJson = jsonTree.get(NODE_ID);
            MastershipRole role = codec(MastershipRole.class).decode(jsonTree, this);

            if (deviceIdJson == null) {
                throw new IllegalArgumentException(DEVICE_ID_INVALID);
            }

            if (nodeIdJson == null) {
                throw new IllegalArgumentException(NODE_ID_INVALID);
            }

            mastershipAdminService.setRoleSync(NodeId.nodeId(nodeIdJson.asText()),
                    DeviceId.deviceId(deviceIdJson.asText()), role);

            return Response.ok().build();
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * Balances the mastership to be shared as evenly as possibly by all
     * online instances.
     *
     * @return status of the request - OK if the request is successfully processed
     */
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response balanceRoles() {
        MastershipAdminService mastershipAdminService = get(MastershipAdminService.class);
        mastershipAdminService.balanceRoles();
        return Response.ok().build();
    }
}


/*
 * 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.
 */
package org.apache.ambari.server.utils;

import javax.xml.bind.annotation.XmlElement;

public class JaxbMapKeyMap {
  @XmlElement public String  key;
  @XmlElement public JaxbMapKeyVal[] value;

  private JaxbMapKeyMap() {}

  public JaxbMapKeyMap(String key, JaxbMapKeyVal[] value)
  {
    this.key   = key;
    this.value = value;
  }
}


//: [Previous](@previous)

import UIKit
import PlaygroundSupport

let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
hostView.backgroundColor = UIColor.white
PlaygroundPage.current.liveView = hostView

let makeView = { (color: UIColor) -> UIView in
    let view = UIView(frame: .zero)
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = color
    return view
}

let iconImageView = UIImageView(image: UIImage(named: "IconFojusi"))
iconImageView.layer.cornerRadius = 20
iconImageView.clipsToBounds = true

let appNameLabel = UILabel(frame: .zero)
appNameLabel.font = UIFont.boldSystemFont(ofSize: 15)
appNameLabel.text = "Fojusi"
//appNameLabel.backgroundColor = UIColor.yellow

let devNameLabel = UILabel(frame: .zero)
devNameLabel.font = UIFont.systemFont(ofSize: 13)
devNameLabel.text = "Dominik Hauser"
//devNameLabel.backgroundColor = UIColor.red

let buyButton = UIButton(type: .system)
buyButton.setTitle("0,99 €", for: UIControl.State.normal)
buyButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 13)
buyButton.layer.cornerRadius = 5
buyButton.layer.borderColor = buyButton.tintColor.cgColor
buyButton.layer.borderWidth = 1

let headerView = UIView(frame: .zero)
//headerView.backgroundColor = UIColor.brownColor()

let metaDataStackView = UIStackView(arrangedSubviews: [appNameLabel, devNameLabel])
metaDataStackView.axis = .vertical

let leftHeaderStackView = UIStackView(arrangedSubviews: [metaDataStackView, buyButton])
leftHeaderStackView.axis = .vertical
leftHeaderStackView.distribution = UIStackView.Distribution.equalCentering

let headerStackView = UIStackView(arrangedSubviews: [iconImageView, leftHeaderStackView])
headerStackView.translatesAutoresizingMaskIntoConstraints = false
//  headerStackView.alignment = .Top
headerStackView.isLayoutMarginsRelativeArrangement = true
headerStackView.spacing = 10
headerView.addSubview(headerStackView)

let mainStackView = UIStackView(arrangedSubviews: [headerView])
mainStackView.translatesAutoresizingMaskIntoConstraints = false
hostView.addSubview(mainStackView)

NSLayoutConstraint.activate(
  [
  mainStackView.leadingAnchor.constraint(equalTo: hostView.leadingAnchor),
  mainStackView.trailingAnchor.constraint(equalTo: hostView.trailingAnchor),
  mainStackView.topAnchor.constraint(equalTo: hostView.topAnchor),
  mainStackView.bottomAnchor.constraint(equalTo: hostView.bottomAnchor),
  headerStackView.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 10),
  headerStackView.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: -10),
  headerStackView.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 10),
  iconImageView.widthAnchor.constraint(equalToConstant: 100),
  iconImageView.heightAnchor.constraint(equalToConstant: 100),
  ])

//: [Next](@next)


<?xml version="1.0" ?>
<annotation>
<folder>widerface</folder>
<filename>58--Hockey_58_Hockey_icehockey_puck_58_384.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>680</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>348</xmin>
<ymin>575</ymin>
<xmax>380</xmax>
<ymax>607</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>420</xmin>
<ymin>495</ymin>
<xmax>452</xmax>
<ymax>529</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>531</xmin>
<ymin>442</ymin>
<xmax>563</xmax>
<ymax>475</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>508</xmin>
<ymin>336</ymin>
<xmax>532</xmax>
<ymax>362</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>555</xmin>
<ymin>305</ymin>
<xmax>582</xmax>
<ymax>334</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>11</xmin>
<ymin>514</ymin>
<xmax>38</xmax>
<ymax>538</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>230</xmin>
<ymin>212</ymin>
<xmax>250</xmax>
<ymax>236</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>545</xmin>
<ymin>259</ymin>
<xmax>568</xmax>
<ymax>281</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>607</xmin>
<ymin>227</ymin>
<xmax>633</xmax>
<ymax>257</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>603</xmin>
<ymin>194</ymin>
<xmax>624</xmax>
<ymax>224</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>656</xmin>
<ymin>184</ymin>
<xmax>681</xmax>
<ymax>207</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>738</xmin>
<ymin>127</ymin>
<xmax>765</xmax>
<ymax>155</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>774</xmin>
<ymin>66</ymin>
<xmax>794</xmax>
<ymax>89</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>831</xmin>
<ymin>58</ymin>
<xmax>848</xmax>
<ymax>82</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>841</xmin>
<ymin>26</ymin>
<xmax>865</xmax>
<ymax>51</ymax>
</bndbox>
</object>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>853</xmin>
<ymin>4</ymin>
<xmax>875</xmax>
<ymax>22</ymax>
</bndbox>
</object>
</annotation>


.. _install:

Install and configure
~~~~~~~~~~~~~~~~~~~~~

This section describes how to install and configure the Messaging service,
code-named zaqar.

This section assumes that you already have a working OpenStack environment with
at least Identity service installed.

Note that installation and configuration vary by distribution.

.. toctree::

   install-obs.rst
   install-rdo.rst
   install-ubuntu.rst

Possible Minimum Scalable HA Setup
----------------------------------

Scalable HA (High availability) setup is out of scope in this chapter.

For a HA setup, a load balancer has to be placed in front of the web servers.

To provide high availability with minimum administration overhead for storage
use ``MongoDB`` driver and for transport use ``wsgi`` driver.

To have a small footprint while providing HA, you can use two web servers which
will host the application and three ``MongoDB`` servers (configured as
replica-set) which will host Messaging service's management store and
message store databases. At larger scale, the management store database and the
message store database are advised to be hosted on different ``MongoDB``
replica sets.


/**
 * Marlin 3D Printer Firmware
 * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
 *
 * Based on Sprinter and grbl.
 * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */
#pragma once

/**
 * Sainsmart 2-in-1 pin assignments
 */

#if HOTENDS > 2 || E_STEPPERS > 2
  #error "Sainsmart 2-in-1 supports up to 2 hotends / E-steppers. Comment out this line to continue."
#endif

#define BOARD_INFO_NAME "Sainsmart"

//
// Heaters / Fans
//
#define RAMPS_D10_PIN 9   // E
#define RAMPS_D9_PIN  7   // F PART FAN in front of board next to Extruder heat
     // RAMPS_D8_PIN  8   // B
#define MOSFET_D_PIN 10   // F / E

#include "pins_RAMPS.h"


fileFormatVersion: 2
guid: 0afec21454700d3479c4f9767f9382f9
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:


package tc.oc.pgm.filters.query;

import tc.oc.pgm.tracker.damage.DamageInfo;

public interface IDamageQuery extends IPlayerEventQuery {

    IPlayerQuery getVictim();

    DamageInfo getDamageInfo();
}


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Dummy Tests</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    {{content-for "head"}}
    {{content-for "test-head"}}

    <link rel="stylesheet" href="{{rootURL}}assets/vendor.css">
    <link rel="stylesheet" href="{{rootURL}}assets/dummy.css">
    <link rel="stylesheet" href="{{rootURL}}assets/test-support.css">

    {{content-for "head-footer"}}
    {{content-for "test-head-footer"}}
  </head>
  <body>
    {{content-for "body"}}
    {{content-for "test-body"}}

    <script src="/testem.js" integrity=""></script>
    <script src="{{rootURL}}assets/vendor.js"></script>
    <script src="{{rootURL}}assets/test-support.js"></script>
    <script src="{{rootURL}}assets/dummy.js"></script>
    <script src="{{rootURL}}assets/tests.js"></script>

    {{content-for "body-footer"}}
    {{content-for "test-body-footer"}}
  </body>
</html>


---
title: "Migration Guide to the .NET Framework 4.8, 4.7, 4.6, and 4.5"
description: A guide for migrating to newer .NET Framework versions that includes resources for new features and application compatibility.
ms.date: "04/18/2019"
helpviewer_keywords:
  - ".NET Framework, migrating applications to"
  - "migration, .NET Framework"
ms.assetid: 02d55147-9b3a-4557-a45f-fa936fadae3b
---
# Migrate to .NET Framework 4.8, 4.7, 4.6, and 4.5

If you created your app using an earlier version of .NET Framework, you can generally upgrade it to .NET Framework 4.5 and its point releases (4.5.1 and 4.5.2), .NET Framework 4.6 and its point releases (4.6.1 and 4.6.2), .NET Framework 4.7 and its point releases (4.7.1 and 4.7.2), or .NET Framework 4.8 easily. Open your project in Visual Studio. If your project was created in an earlier version of Visual Studio, the **Project Compatibility** dialog box automatically opens. For more information about upgrading a project in Visual Studio, see [Port, Migrate, and Upgrade Visual Studio Projects](/visualstudio/porting/port-migrate-and-upgrade-visual-studio-projects) and [Visual Studio 2019 Platform Targeting and Compatibility](/visualstudio/releases/2019/compatibility).

 However, some changes in .NET Framework require changes to your code. You may also want to take advantage of functionality that is new in .NET Framework 4.5 and its point releases, in .NET Framework 4.6 and its point releases, in .NET Framework 4.7 and its point releases, or in .NET Framework 4.8. Making these types of changes to your app for a new version of .NET Framework is typically referred to as *migration*. If your app doesn't have to be migrated, you can run it in .NET Framework 4.5 or a later version without recompiling it.

## Migration resources

Review the following documents before you migrate your app from earlier versions of .NET Framework to version 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, or 4.8:

- See [Versions and Dependencies](versions-and-dependencies.md) to understand the CLR version underlying each version of the .NET Framework and to review guidelines for targeting your apps successfully.

- Review [Application compatibility](application-compatibility.md) to find out about runtime and retargeting changes that might affect your app and how to handle them.

- Review [What's Obsolete in the Class Library](../whats-new/whats-obsolete.md) to determine any types or members in your code that have been made obsolete, and the recommended alternatives.

- See [What's New](../whats-new/index.md) for descriptions of new features that you may want to add to your app.

## See also

- [Application compatibility](application-compatibility.md)
- [Migrating from the .NET Framework 1.1](migrating-from-the-net-framework-1-1.md)
- [Version Compatibility](version-compatibility.md)
- [Versions and Dependencies](versions-and-dependencies.md)
- [How to: Configure an app to support .NET Framework 4 or later versions](how-to-configure-an-app-to-support-net-framework-4-or-4-5.md)
- [What's New](../whats-new/index.md)
- [What's Obsolete in the Class Library](../whats-new/whats-obsolete.md)
- [.NET Framework official support policy](https://dotnet.microsoft.com/platform/support/policy/dotnet-framework)
- [.NET Framework 4 migration issues](net-framework-4-migration-issues.md)


<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin" type="text/css"?>
<?xml-stylesheet href="chrome://mochikit/content/tests/SimpleTest/test.css" type="text/css"?>
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
        xmlns:html="http://www.w3.org/1999/xhtml"
        title="Test for Bug 159346">

<scrollbar id="scrollbar" curpos="0" maxpos="500"/>

Mozilla Bug 159346

</window>


import React, { Component } from "react";
import PropTypes from "prop-types";

class Html extends Component {
  render() {
    return (
      <html lang="fr" className="r-VerticalRhythm">
        {this.props.children}
      </html>
    );
  }
}

Html.propTypes = {
  children: PropTypes.array.isRequired
};

export default Html;


variable.ZRot = !query.is_in_water ? Math.cos((query.time_stamp + query.frame_alpha) * 14.32) * 90 : 0.0;

variable.AnimationAmountBlend = Math.lerp(variable.AnimationAmountPrev, variable.AnimationAmount, query.frame_alpha);


/*
 * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
 * its licensors.
 *
 * For complete copyright and license terms please see the LICENSE at the root of this
 * distribution (the "License"). All use of this software is governed by the License,
 * or, if provided, by the license below or the license accompanying this file. Do not
 * remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 */

#include "WhiteBox_precompiled.h"

#include "Util/WhiteBoxTextureUtil.h"
#include "WhiteBoxTestFixtures.h"

#include <AzCore/Casting/lossy_cast.h>
#include <AzCore/Casting/numeric_cast.h>
#include <AzCore/UnitTest/TestTypes.h>
#include <AzCore/std/containers/array.h>
#include <AzCore/std/containers/vector.h>
#include <AzTest/AzTest.h>
#include <AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h>
#include <WhiteBox/WhiteBoxToolApi.h>
#include <cmath>
#include <iostream>
#include <random>
#include <vector>

namespace UnitTest
{
    std::random_device rd;
    std::mt19937 gen(rd());

    // rngs for the first and subsequent significant figures of the random numbers
    std::uniform_real_distribution<> rndFirstSigFig(1.0, 10.0);
    std::uniform_real_distribution<> rndOtherSigFigs(0.0, 1.0);

    // generate noise after the specified decimal place with the first significant
    // figure always being one decimal place after afterDecimalPlace
    float GenerateNoiseWithSignificantFigures(AZ::u32 afterDecimalPlace)
    {
        // number of significant figures of randomness to generate
        const double numSigFigs = 8;

        // scaling factor to push the noise back into the desired range
        const double sigFactor = std::pow(10.0, numSigFigs + afterDecimalPlace);

        // random value for first guaranteed significant digit
        const double firstSigFig = azlossy_cast<AZ::u64>(rndFirstSigFig(gen)) * std::pow(10.0, numSigFigs - 1);

        // random value for the other significant digits
        const double otherSigFigs = azlossy_cast<AZ::u64>(rndOtherSigFigs(gen) * std::pow(10.0, numSigFigs - 1));

        // unscaled random value with rndSigFigs significant figures
        const double fixedLengthRandom = firstSigFig + otherSigFigs;

        // scaled random value to push the noise into the desired significant digit range
        const float noise = fixedLengthRandom / sigFactor;

        return noise;
    }

    // generates a vector of Vector3s with noise for in specified range decimal places
    std::vector<Vector3> GenerateNoiseForSignificantFigureRange(AZ::u32 startDecimalPlace, AZ::u32 endDecimalPlace)
    {
        std::vector<Vector3> noise(endDecimalPlace - startDecimalPlace + 1);

        for (AZ::u32 decimal = startDecimalPlace, i = 0; decimal <= endDecimalPlace; decimal++, i++)
        {
            float x = GenerateNoiseWithSignificantFigures(decimal);
            float y = GenerateNoiseWithSignificantFigures(decimal);
            float z = GenerateNoiseWithSignificantFigures(decimal);
            noise[i] = Vector3{x, y, z};
        }

        return noise;
    }

    // vector of noise vectors with between 3 and 6 significat figures
    const std::vector<Vector3> Noise = GenerateNoiseForSignificantFigureRange(3, 6);

    // noise source permutations to be applied to each test
    const std::vector<NoiseSource> Source = {
        NoiseSource::None,        NoiseSource::XComponent,  NoiseSource::YComponent,  NoiseSource::ZComponent,
        NoiseSource::XYComponent, NoiseSource::XZComponent, NoiseSource::YZComponent, NoiseSource::XYZComponent};

    enum CubeVertex : AZ::u32
    {
        FrontTopLeft,
        FrontTopRight,
        BackTopLeft,
        BackTopRight,
        FrontBottomLeft,
        FrontBottomRight,
        BackBottomLeft,
        BackBottomRight
    };

    const std::vector<AZ::Vector3> UnitCube = {
        AZ::Vector3(-0.5f, 0.5f, 0.5f), // FrontTopLeft
        AZ::Vector3(0.5f, 0.5f, 0.5f), // FrontTopRight
        AZ::Vector3(-0.5f, -0.5f, 0.5f), // BackTopLeft
        AZ::Vector3(0.5f, -0.5f, 0.5f), // BackTopRight
        AZ::Vector3(-0.5f, 0.5f, -0.5f), // FrontBottomLeft
        AZ::Vector3(0.5f, 0.5f, -0.5f), // FrontBottomRight
        AZ::Vector3(-0.5f, -0.5f, -0.5f), // BackBottomLeft
        AZ::Vector3(0.5f, -0.5f, -0.5f) // BackBottomRight
    };

    // returns a vector with noise applied to it as determined by the source
    AZ::Vector3 GenerateNoiseyVector(const AZ::Vector3& in, const Vector3& noise, NoiseSource source)
    {
        switch (source)
        {
        case NoiseSource::None:
            return in;
        case NoiseSource::XComponent:
            return AZ::Vector3(in.GetX() + noise.x, in.GetY(), in.GetZ());
        case NoiseSource::YComponent:
            return AZ::Vector3(in.GetX(), in.GetY() + noise.y, in.GetZ());
        case NoiseSource::ZComponent:
            return AZ::Vector3(in.GetX(), in.GetY(), in.GetZ() + noise.z);
        case NoiseSource::XYComponent:
            return AZ::Vector3(in.GetX() + noise.x, in.GetY() + noise.y, in.GetZ());
        case NoiseSource::XZComponent:
            return AZ::Vector3(in.GetX() + noise.x, in.GetY(), in.GetZ() + noise.z);
        case NoiseSource::YZComponent:
            return AZ::Vector3(in.GetX(), in.GetY() + noise.y, in.GetZ() + noise.z);
        case NoiseSource::XYZComponent:
            return AZ::Vector3(in.GetX() + noise.x, in.GetY() + noise.y, in.GetZ() + noise.z);

        default:
            return in;
        }
    }

    // returns a quaternion with the specified rotation
    AZ::Quaternion GetQuaternionFromRotation(Rotation rotation)
    {
        static const AZ::Quaternion qXAxis = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), 45);
        static const AZ::Quaternion qZAxis = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisZ(), 45);
        static const AZ::Quaternion qXZAxis = qXAxis + qZAxis;

        switch (rotation)
        {
        case Rotation::Identity:
            return AZ::Quaternion::CreateIdentity();
        case Rotation::XAxis:
            return qXAxis;
        case Rotation::ZAxis:
            return qZAxis;
        case Rotation::XZAxis:
            return qXZAxis;
        default:
            return AZ::Quaternion::CreateIdentity();
        }
    }

    TEST_P(WhiteBoxUVTestFixture, FrontFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(0.0f, -1.0f, 0.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopLeft]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopRight]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomLeft]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomRight]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 1.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(0.0f, 1.0f)));
    }

    TEST_P(WhiteBoxUVTestFixture, BackFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(0.0f, 1.0f, 0.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopLeft]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopRight]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomLeft]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomRight]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 1.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(0.0f, 1.0f)));
    }

    TEST_P(WhiteBoxUVTestFixture, LeftFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(-1.0f, 0.0f, 0.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopLeft]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopLeft]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomLeft]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomLeft]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 1.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(1.0f, 1.0f)));
    }

    TEST_P(WhiteBoxUVTestFixture, RightFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(1.0f, 0.0f, 0.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopRight]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopRight]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomRight]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomRight]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 1.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(1.0f, 1.0f)));
    }

    TEST_P(WhiteBoxUVTestFixture, TopFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(0.0f, 0.0f, 1.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopLeft]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[FrontTopRight]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopLeft]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[BackTopRight]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 1.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(0.0f, 1.0f)));
    }

    TEST_P(WhiteBoxUVTestFixture, BottomFaceCorners)
    {
        using WhiteBox::CreatePlanarUVFromVertex;
        const auto& [noise, source, rotation] = GetParam();

        const AZ::Quaternion qRotation = GetQuaternionFromRotation(rotation);
        const AZ::Vector3 normal = GenerateNoiseyVector(qRotation * AZ::Vector3(0.0f, 0.0f, -1.0f), noise, source);

        const AZ::Vector2 uv00 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomLeft]);
        const AZ::Vector2 uv10 = CreatePlanarUVFromVertex(normal, UnitCube[FrontBottomRight]);
        const AZ::Vector2 uv01 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomLeft]);
        const AZ::Vector2 uv11 = CreatePlanarUVFromVertex(normal, UnitCube[BackBottomRight]);

        EXPECT_THAT(uv00, IsClose(AZ::Vector2(1.0f, 0.0f)));
        EXPECT_THAT(uv10, IsClose(AZ::Vector2(0.0f, 0.0f)));
        EXPECT_THAT(uv01, IsClose(AZ::Vector2(1.0f, 1.0f)));
        EXPECT_THAT(uv11, IsClose(AZ::Vector2(0.0f, 1.0f)));
    }

    // test with permutations of all noise values and sources with rotations around the x and z axis
    INSTANTIATE_TEST_CASE_P(
        , WhiteBoxUVTestFixture,
        ::testing::Combine(
            ::testing::ValuesIn(Noise), ::testing::ValuesIn(Source),
            ::testing::Values(Rotation::Identity, Rotation::XZAxis)));

} // namespace UnitTest


const { openItem } = window.electron_functions

import { getLogger } from '../../../shared/logger'
const log = getLogger('render/msgFunctions')
import { Message } from 'deltachat-node'
/**
 * json representation of the message object we get from the backend
 */
type MsgObject = ReturnType<typeof Message.prototype.toJson>

export function onDownload(msg: MsgObject) {
  window.preload_functions.downloadFile(msg.file)
}

export function openAttachmentInShell(msg: MsgObject) {
  if (!openItem(msg.file)) {
    log.info(
      "file couldn't be opened, try saving it in a different place and try to open it from there"
    )
  }
}