text:
/// <reference path="../_references.ts"/>

module powerbi {
    import StringExtensions = jsCommon.StringExtensions;

    const maxExponent = 24;
    const defaultScientificBigNumbersBoundary = 1E15;
    const scientificSmallNumbersBoundary = 1E-4;

    export class DisplayUnit {
        // Fields
        public value: number;
        public title: string;
        public labelFormat: string;
        public applicableRangeMin: number;
        public applicableRangeMax: number;

        // Methods
        public project(value: number): number {
            if (this.value) {
                return value / this.value;
            } else {
                return value;
            }
        }

        public reverseProject(value: number): number {
            if (this.value) {
                return value * this.value;
            } else {
                return value;
            }
        }

        public isApplicableTo(value: number): boolean {
            value = Math.abs(value);
            let precision = Double.getPrecision(value, 3);
            return Double.greaterOrEqualWithPrecision(value, this.applicableRangeMin, precision) && Double.lessWithPrecision(value, this.applicableRangeMax, precision);
        }

        public isScaling(): boolean {
            return this.value > 1;
        }
    }

    export class DisplayUnitSystem {

        // Constants
        static UNSUPPORTED_FORMATS = /^(p\d*)|(.*\%)|(e\d*)$/i;
        static NUMBER_FORMAT = /#|0/;
        static SUPPORTED_SCIENTIFIC_FORMATS = /^((0*\.*\,*#*-*)*|g)*$/i;
        static DEFAULT_SCIENTIFIC_FORMAT = "0.######E+0";
        static AUTO_DISPLAYUNIT_VALUE = 0;
        static NONE_DISPLAYUNIT_VALUE = 1;

        // Fields
        public units: DisplayUnit[];
        public displayUnit: DisplayUnit;
        private unitBaseValue: number;

        // Constructor
        constructor(units?: DisplayUnit[]) {
            this.units = units ? units : [];
        }

        // Properties
        public get title(): string {
            return this.displayUnit ? this.displayUnit.title : undefined;
        }

        // Methods
        public update(value: number): void {
            if (value === undefined)
                return;

            this.unitBaseValue = value;
            this.displayUnit = this.findApplicableDisplayUnit(value);
        }

        private findApplicableDisplayUnit(value: number): DisplayUnit {
            for (let unit of this.units) {
                if (unit.isApplicableTo(value))
                    return unit;
            }

            return undefined;
        }

        public format(value: number, format: string, decimals?: number, trailingZeros?: boolean ): string {

            if (this.isFormatSupported(format)) {
                if (this.hasScientitifcFormat(format)) {
                    return this.formatHelper(value, value, '', format, decimals, trailingZeros);
                }
                if (this.isScalingUnit() && this.shouldRespectScalingUnit(format)) {
                    let projectedValue = this.displayUnit.project(value);
                    let nonScientificFormat = (trailingZeros)
                        ? DisplayUnitSystem.getNonScientificFormatWithPrecision(this.displayUnit.labelFormat, decimals)
                        : this.displayUnit.labelFormat;
                    return this.formatHelper(value, projectedValue, nonScientificFormat, format, decimals, trailingZeros);
                }
                if (decimals != null) {
                    if (trailingZeros && format && DisplayUnitSystem.NUMBER_FORMAT.test(format)) {
                        let formatWithPrecision = DisplayUnitSystem.getFormatWithPrecision(decimals);
                        //Using the regex below we can maintain the original format (with/without dot, $ etc.) while forcing precision.
                        let regex = /^[a-zA-Z0-9- ]*$/.test(format) ?/.0*/g:/0\.0*/g;
                        format = format.replace(regex, formatWithPrecision);
                        let decimalsForFormatting = this.getNumberOfDecimalsForFormatting(format, decimals);
                        return this.formatHelper(value, value, '', format, decimalsForFormatting, trailingZeros);
                    }
                    if (trailingZeros) {
                        let nonScientificFormat = DisplayUnitSystem.getNonScientificFormatWithPrecision('{0}', decimals);
                        return this.formatHelper(value, value, nonScientificFormat, format, decimals, trailingZeros);
                    }
                    return this.formatHelper(value, value, '', format, decimals, trailingZeros);
                }
            }

            format = this.removeFractionIfNecessary(format);
            return formattingService.formatValue(value, format);
        }

        public isFormatSupported(format: string): boolean {
            return !DisplayUnitSystem.UNSUPPORTED_FORMATS.test(format);
        }

        public getNumberOfDecimalsForFormatting(format: string, decimals?: number) {
            return decimals;
        }

        public isScalingUnit(): boolean {
            return this.displayUnit && this.displayUnit.isScaling();
        }

        public shouldRespectScalingUnit(format: string): boolean{
            return true;
        }

        private formatHelper(value: number, projectedValue: number, nonScientificFormat: string, format: string, decimals?: number, trailingZeros?: boolean) {
            let precision = (decimals != null) ? Double.pow10(decimals) : Double.getPrecision(value);

            let x = Double.roundToPrecision(projectedValue, precision);

            if (format && !formattingService.isStandardNumberFormat(format))
                return formattingService.formatNumberWithCustomOverride(x, format, nonScientificFormat);

            let textFormat = trailingZeros ? DisplayUnitSystem.getFormatWithPrecision(decimals) : 'G';
            let text = formattingService.formatValue(x, textFormat);
            return formattingService.format(nonScientificFormat, [text]);
        }

        private static getNonScientificFormatWithPrecision(baseFormat: string, decimals: number): string {
            if (!decimals || baseFormat === undefined)
                return baseFormat;

            let newFormat = "{0:" + DisplayUnitSystem.getFormatWithPrecision(decimals) + "}";

            return baseFormat.replace("{0}", newFormat);
        }

        private static getFormatWithPrecision(decimals?: number): string {
            if (decimals == null) return 'G';
            return ",0." + StringExtensions.repeat('0',Math.abs(decimals));
        }

        /** Formats a single value by choosing an appropriate base for the DisplayUnitSystem before formatting. */
        public formatSingleValue(value: number, format: string, decimals?: number, trailingZeros?: boolean): string {
            // Change unit base to a value appropriate for this value
            this.update(this.shouldUseValuePrecision(value) ? Double.getPrecision(value, 8) : value);

            return this.format(value, format, decimals, trailingZeros);
        }

        private shouldUseValuePrecision(value: number): boolean {
            if (this.units.length === 0)
                return true;

            // Check if the value is big enough to have a valid unit by checking against the smallest unit (that it's value bigger than 1).
            let applicableRangeMin: number = 0;
            for (let i = 0; i < this.units.length; i++) {
                if (this.units[i].isScaling()) {
                    applicableRangeMin = this.units[i].applicableRangeMin;
                    break;
                }
            }

            return Math.abs(value) < applicableRangeMin;
        }

        private removeFractionIfNecessary(formatString: string): string {
            if (formatString) {
                if (Math.abs(this.unitBaseValue) >= 0.01) {
                    formatString = formatString.replace(/^(p\d*)$/i, "p0");
                }
                if (Math.abs(this.unitBaseValue) >= 1.0) {
                    formatString = formatString.replace(/[#0]\.[#0]+$/, "0"); // Custom number format with hash/zero fraction
                    formatString = formatString.replace(/^(n\d*)$/i, "n0");
                    formatString = formatString.replace(/^(f\d*)$/i, "f0");
                    formatString = formatString.replace(/^(c\d*)$/i, "c0");
                }
            }
            return formatString;
        }

        protected isScientific(value: number): boolean {
            return value < - defaultScientificBigNumbersBoundary || value > defaultScientificBigNumbersBoundary ||
                (-scientificSmallNumbersBoundary < value && value < scientificSmallNumbersBoundary && value !== 0);
        }

        protected hasScientitifcFormat(format: string): boolean {
            return format && format.toUpperCase().indexOf("E") !== -1;
        }

        protected supportsScientificFormat(format: string): boolean {
            if (format)
                return DisplayUnitSystem.SUPPORTED_SCIENTIFIC_FORMATS.test(format);

            return true;
        }

        protected shouldFallbackToScientific(value: number, format: string) {
            return !this.hasScientitifcFormat(format)
                && this.supportsScientificFormat(format)
                && this.isScientific(value);
        }
    }

    /** Provides a unit system that is defined by formatting in the model, and is suitable for visualizations shown in single number visuals in explore mode. */
    export class NoDisplayUnitSystem extends DisplayUnitSystem {
        // Constructor
        constructor() {
            super([]);
        }
    }

    /** Provides a unit system that creates a more concise format for displaying values. This is suitable for most of the cases where
        we are showing values (chart axes) and as such it is the default unit system. */
    export class DefaultDisplayUnitSystem extends DisplayUnitSystem {
        private static units: DisplayUnit[];

        // Constructor
        constructor(unitLookup: (exponent: number) => DisplayUnitSystemNames) {
            super(DefaultDisplayUnitSystem.getUnits(unitLookup));
        }

        // Methods
        public format(data: number, format: string, decimals?: number, trailingZeros?: boolean): string {
            // Use scientific format outside of the range
            if (this.isFormatSupported(format) && this.shouldFallbackToScientific(data, format)) {
                if (trailingZeros && decimals)
                    format = "0." + StringExtensions.repeat('0', Math.abs(decimals)) + "E+0";
                else
                    format = DisplayUnitSystem.DEFAULT_SCIENTIFIC_FORMAT;
            }

            return super.format(data, format, decimals, trailingZeros);
        }

        public static reset(): void {
            DefaultDisplayUnitSystem.units = null;
        }

        private static getUnits(unitLookup: (exponent: number) => DisplayUnitSystemNames): DisplayUnit[] {
            if (!DefaultDisplayUnitSystem.units) {
                DefaultDisplayUnitSystem.units = createDisplayUnits(unitLookup, (value: number, previousUnitValue: number, min: number) => {
                    // When dealing with millions/billions/trillions we need to switch to millions earlier: for example instead of showing 100K 200K 300K we should show 0.1M 0.2M 0.3M etc
                    if (value - previousUnitValue >= 1000) {
                        return value / 10;
                    }

                    return min;
                });

                // Ensure last unit has max of infinity
                DefaultDisplayUnitSystem.units[DefaultDisplayUnitSystem.units.length - 1].applicableRangeMax = Infinity;
            }
            return DefaultDisplayUnitSystem.units;
        }
    }

    /** Provides a unit system that creates a more concise format for displaying values, but only allows showing a unit if we have at least
        one of those units (e.g. 0.9M is not allowed since it's less than 1 million). This is suitable for cases such as dashboard tiles
        where we have restricted space but do not want to show partial units. */
    export class WholeUnitsDisplayUnitSystem extends DisplayUnitSystem {
        private static units: DisplayUnit[];

        // Constructor
        constructor(unitLookup: (exponent: number) => DisplayUnitSystemNames) {
            super(WholeUnitsDisplayUnitSystem.getUnits(unitLookup));
        }

        public static reset(): void {
            WholeUnitsDisplayUnitSystem.units = null;
        }

        private static getUnits(unitLookup: (exponent: number) => DisplayUnitSystemNames): DisplayUnit[] {
            if (!WholeUnitsDisplayUnitSystem.units) {
                WholeUnitsDisplayUnitSystem.units = createDisplayUnits(unitLookup);

                // Ensure last unit has max of infinity
                WholeUnitsDisplayUnitSystem.units[WholeUnitsDisplayUnitSystem.units.length - 1].applicableRangeMax = Infinity;
            }

            return WholeUnitsDisplayUnitSystem.units;
        }

        public format(data: number, format: string, decimals?: number, trailingZeros?: boolean): string {
            // Use scientific format outside of the range
            if (this.isFormatSupported(format) && this.shouldFallbackToScientific(data, format)) {
                if (trailingZeros && decimals)
                    format = "0." + StringExtensions.repeat('0', Math.abs(decimals)) + "E+0";
                else
                    format = DisplayUnitSystem.DEFAULT_SCIENTIFIC_FORMAT;
            }

            return super.format(data, format, decimals, trailingZeros);
        }
    }

    export class DataLabelsDisplayUnitSystem extends DisplayUnitSystem {

        // Constants
        static UNSUPPORTED_FORMATS = /^(e\d*)$/i;
        static PERCENTAGE_FORMAT = '%';

        private static units: DisplayUnit[];

        constructor(unitLookup: (exponent: number) => DisplayUnitSystemNames) {
            super(DataLabelsDisplayUnitSystem.getUnits(unitLookup));
        }

        public isFormatSupported(format: string): boolean {
            return !DataLabelsDisplayUnitSystem.UNSUPPORTED_FORMATS.test(format);
        }

        public getNumberOfDecimalsForFormatting(format: string, decimals?: number) {
            if (format.indexOf(DataLabelsDisplayUnitSystem.PERCENTAGE_FORMAT) >= 0)
                return decimals -= 2;
        }

        public shouldRespectScalingUnit(format: string): boolean {
            return (!format || format.indexOf(DataLabelsDisplayUnitSystem.PERCENTAGE_FORMAT) < 0);
        }

        private static getUnits(unitLookup: (exponent: number) => DisplayUnitSystemNames): DisplayUnit[] {
            if (!DataLabelsDisplayUnitSystem.units) {
                let units = [];
                let adjustMinBasedOnPreviousUnit = (value: number, previousUnitValue: number, min: number): number => {
                    // Never returns true, we are always ignoring
                    // We do not early switch (e.g. 100K instead of 0.1M)
                    // Intended? If so, remove this function, otherwise, remove if statement
                    if (value === -1)
                        if (value - previousUnitValue >= 1000) {
                            return value / 10;
                        }
                    return min;
                };

                //Add Auto & None
                let names = unitLookup(-1);
                addUnitIfNonEmpty(units, DisplayUnitSystem.AUTO_DISPLAYUNIT_VALUE, names.title, names.format, adjustMinBasedOnPreviousUnit);

                names = unitLookup(0);
                addUnitIfNonEmpty(units, DisplayUnitSystem.NONE_DISPLAYUNIT_VALUE, names.title, names.format, adjustMinBasedOnPreviousUnit);

                //add normal units
                DataLabelsDisplayUnitSystem.units = units.concat(createDisplayUnits(unitLookup, adjustMinBasedOnPreviousUnit));

                // Ensure last unit has max of infinity
                DataLabelsDisplayUnitSystem.units[DataLabelsDisplayUnitSystem.units.length - 1].applicableRangeMax = Infinity;
            }
            return DataLabelsDisplayUnitSystem.units;
        }

        protected shouldFallbackToScientific(value: number, format: string) {
            if (!this.displayUnit)
                return super.shouldFallbackToScientific(value, format);
            else
                // Allow auto display unit to pass through
                return this.displayUnit.value !== DisplayUnitSystem.AUTO_DISPLAYUNIT_VALUE
                    && super.shouldFallbackToScientific(value, format);
        }

        public format(data: number, format: string, decimals?: number, trailingZeros?: boolean): string {
            // Use scientific format outside of the range
            if (this.shouldFallbackToScientific(data, format)) {
                if (trailingZeros && decimals)
                    format = "0." + StringExtensions.repeat('0', Math.abs(decimals)) + "E+0";
                else
                    format = '0E+0';
            }

            return super.format(data, format, decimals, trailingZeros);
        }
    }

    export interface DisplayUnitSystemNames {
        title: string;
        format: string;
    }

    function createDisplayUnits(unitLookup: (exponent: number) => DisplayUnitSystemNames, adjustMinBasedOnPreviousUnit?: (value: number, previousUnitValue: number, min: number) => number) {
        let units = [];
        for (let i = 3; i < maxExponent; i++) {
            let names = unitLookup(i);
            if (names)
                addUnitIfNonEmpty(units, Double.pow10(i), names.title, names.format, adjustMinBasedOnPreviousUnit);
        }

        return units;
    }

    function addUnitIfNonEmpty(
        units: DisplayUnit[],
        value: number,
        title: string,
        labelFormat: string,
        adjustMinBasedOnPreviousUnit?: (value: number, previousUnitValue: number, min: number) => number): void {
        if (title || labelFormat) {
            let min = value;

            if (units.length > 0) {
                let previousUnit = units[units.length - 1];

                if (adjustMinBasedOnPreviousUnit)
                    min = adjustMinBasedOnPreviousUnit(value, previousUnit.value, min);

                previousUnit.applicableRangeMax = min;
            }
            let unit = new DisplayUnit();
            unit.value = value;
            unit.applicableRangeMin = min;
            unit.applicableRangeMax = min * 1000;
            unit.title = title;
            unit.labelFormat = labelFormat;
            units.push(unit);
        }
    }
}


text:
/**
 * ui/CreateMenu.js
 * Create Menu
 */

function CreateMenu(view, menu, back) {
	var	g = this,
		defaultHeight = 50,
		menuHeight = 50;

	// background overlay
	var background = Ti.UI.createView({
		width: "auto",
		height: "auto",
		visible: false
	});
	view.add(background);

	// menu wrapper
	var wrap = Ti.UI.createView({
		layout: "vertical",
		top: 0,
		right: 0,
		width: g.dip(120),
		height: g.dip(defaultHeight)
	});
	view.add(wrap);

	// menu button (trigger)
	var button = Ti.UI.createLabel({
		id: "button",
		top: 0,
		right: 0,
		width: g.dip(50),
		height: g.dip(defaultHeight),
		backgroundColor: "#59c",
		text: "≡",
		textAlign: "center",
		color: "#fff",
		font: {fontSize: g.dip(24)}
	});
	wrap.add(button);

	// Back button (iOS only)
	if (! Ti.Platform.Android && back) {
		var back = Ti.UI.createImageView({
			top: g.dip(-50),
			width: g.dip(52),
			height: g.dip(defaultHeight),
			right: g.dip(50),
			backgroundColor: "#59c",
			image: "images/arrow.png"
		});
		var bar = Ti.UI.createLabel({
			top: 0,
			width: g.dip(2),
			height: g.dip(defaultHeight),
			right: 0,
			backgroundColor: "#59c",
			text: "|",
			textAlign: "center",
			color: "#fff",
			font: {fontSize: g.dip(24)}
		});
		back.add(bar);
		back.addEventListener("click", function () {
			g.currentWindow.close();
		});
		wrap.add(back);
	}

	// initialize
	function init() {
		background.visible = false;
		wrap.height = g.dip(defaultHeight);
	}

	// set menu list
	var rows = Object.keys(menu).map(function (key, index) {
		var	item = menu[key],
			font = {fontSize: g.dip(16)},
			color = "#fff";

		var row = Ti.UI.createTableViewRow({
			height: g.dip(menuHeight),
			color: color,
			font: font
		});

		if (Ti.Platform.Android)
			row.title = key
		else {
			var label = Ti.UI.createLabel({
				left: g.dip(5),
				right: g.dip(5),
				width: Ti.UI.FILL,
				color: color,
				font: font,
				text: key
			});
			row.add(label);
		}

		row.addEventListener("click", function (e) {
			init();
			// click event, menu title, menu index が渡される
			item.click(e, key, index);
		});
		return row;
	});
	var list = Ti.UI.createTableView({
		top: g.dip(1),
		right: g.dip(5),
		// iOS だけ、ウィンドウのサイズを超えるとはみ出す
		height: Ti.UI.SIZE,
		backgroundColor: "#888",
		data: rows
	});
	wrap.add(list);

	// background action
	background.addEventListener("click", init);
	wrap.addEventListener("click", function (e) {
		if (e.source.id !== "button")
			init();
	});

	// menu action
	button.addEventListener("click", function () {
		if (wrap.height === g.dip(defaultHeight)) {
			background.visible = true;
			wrap.height = Ti.UI.FILL;
		} else
			init();
	});

	// bind menu key (Android only)
	if (Ti.Platform.Android)
		g.currentWindow.activity.onPrepareOptionsMenu = function () {
			button.fireEvent("click");
		};

	return button;
}

module.exports = CreateMenu;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CCPDRequestData (Bouncy Castle Library 1.52 API Specification)</title>
<meta name="date" content="2015-03-01">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.dvcs

Class CCPDRequestData

java.lang.Object

org.bouncycastle.dvcs.DVCSRequestData

org.bouncycastle.dvcs.CCPDRequestData

public class CCPDRequestData
extends DVCSRequestData

Data piece of DVCRequest for CCPD service (Certify Claim of Possession of Data).
 It contains CCPD-specific selector interface.

 This objects are constructed internally,
 to build DVCS request to CCPD service use CCPDRequestBuilder.

Field Summary

Fields inherited from class org.bouncycastle.dvcs.DVCSRequestData

data

Method Summary

Methods

Modifier and Type
Method and Description

MessageImprint
getMessageImprint()

Get MessageImprint value

Methods inherited from class org.bouncycastle.dvcs.DVCSRequestData

toASN1Structure

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getMessageImprint

public MessageImprint getMessageImprint()

Get MessageImprint value

Returns:

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.52

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package au.com.btes.models.profile;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import au.com.btes.models.CampaignServiceUrl;

public class Profile {

	@SerializedName("PKey")
	@Expose
	private String pKey;
	@SerializedName("age")
	@Expose
	private Integer age;
	@SerializedName("birthDate")
	@Expose
	private String birthDate;
	@SerializedName("blackList")
	@Expose
	private Boolean blackList;
	@SerializedName("blackListEmail")
	@Expose
	private Boolean blackListEmail;
	@SerializedName("blackListFax")
	@Expose
	private Boolean blackListFax;
	@SerializedName("blackListMobile")
	@Expose
	private Boolean blackListMobile;
	@SerializedName("blackListPhone")
	@Expose
	private Boolean blackListPhone;
	@SerializedName("blackListPostalMail")
	@Expose
	private Boolean blackListPostalMail;
	@SerializedName("created")
	@Expose
	private String created;
	@SerializedName("cryptedId")
	@Expose
	private String cryptedId;
	@SerializedName("domain")
	@Expose
	private String domain;
	@SerializedName("email")
	@Expose
	private String email;
	@SerializedName("emailFormat")
	@Expose
	private String emailFormat;
	@SerializedName("fax")
	@Expose
	private String fax;
	@SerializedName("firstName")
	@Expose
	private String firstName;
	@SerializedName("gender")
	@Expose
	private String gender;
	@SerializedName("lastModified")
	@Expose
	private String lastModified;
	@SerializedName("lastName")
	@Expose
	private String lastName;
	@SerializedName("location")
	@Expose
	private Location location;
	@SerializedName("middleName")
	@Expose
	private String middleName;
	@SerializedName("mobilePhone")
	@Expose
	private String mobilePhone;
	@SerializedName("phone")
	@Expose
	private String phone;
	@SerializedName("postalAddress")
	@Expose
	private PostalAddress postalAddress;
	@SerializedName("salutation")
	@Expose
	private String salutation;
	@SerializedName("subscriptions")
	@Expose
	private CampaignServiceUrl urlToSubscriptions;
	@SerializedName("thumbnail")
	@Expose
	private String thumbnail;
	@SerializedName("title")
	@Expose
	private String title;

	/**
	 *
	 * @return
	 * The pKey
	 */
	public String getPKey() {
		return pKey;
	}

	/**
	 *
	 * @param pKey
	 * The PKey
	 */
	public void setPKey(String pKey) {
		this.pKey = pKey;
	}

	/**
	 *
	 * @return
	 * The age
	 */
	public Integer getAge() {
		return age;
	}

	/**
	 *
	 * @param age
	 * The age
	 */
	public void setAge(Integer age) {
		this.age = age;
	}

	/**
	 *
	 * @return
	 * The birthDate
	 */
	public String getBirthDate() {
		return birthDate;
	}

	/**
	 *
	 * @param birthDate
	 * The birthDate
	 */
	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}

	/**
	 *
	 * @return
	 * The blackList
	 */
	public Boolean getBlackList() {
		return blackList;
	}

	/**
	 *
	 * @param blackList
	 * The blackList
	 */
	public void setBlackList(Boolean blackList) {
		this.blackList = blackList;
	}

	/**
	 *
	 * @return
	 * The blackListEmail
	 */
	public Boolean getBlackListEmail() {
		return blackListEmail;
	}

	/**
	 *
	 * @param blackListEmail
	 * The blackListEmail
	 */
	public void setBlackListEmail(Boolean blackListEmail) {
		this.blackListEmail = blackListEmail;
	}

	/**
	 *
	 * @return
	 * The blackListFax
	 */
	public Boolean getBlackListFax() {
		return blackListFax;
	}

	/**
	 *
	 * @param blackListFax
	 * The blackListFax
	 */
	public void setBlackListFax(Boolean blackListFax) {
		this.blackListFax = blackListFax;
	}

	/**
	 *
	 * @return
	 * The blackListMobile
	 */
	public Boolean getBlackListMobile() {
		return blackListMobile;
	}

	/**
	 *
	 * @param blackListMobile
	 * The blackListMobile
	 */
	public void setBlackListMobile(Boolean blackListMobile) {
		this.blackListMobile = blackListMobile;
	}

	/**
	 *
	 * @return
	 * The blackListPhone
	 */
	public Boolean getBlackListPhone() {
		return blackListPhone;
	}

	/**
	 *
	 * @param blackListPhone
	 * The blackListPhone
	 */
	public void setBlackListPhone(Boolean blackListPhone) {
		this.blackListPhone = blackListPhone;
	}

	/**
	 *
	 * @return
	 * The blackListPostalMail
	 */
	public Boolean getBlackListPostalMail() {
		return blackListPostalMail;
	}

	/**
	 *
	 * @param blackListPostalMail
	 * The blackListPostalMail
	 */
	public void setBlackListPostalMail(Boolean blackListPostalMail) {
		this.blackListPostalMail = blackListPostalMail;
	}

	/**
	 *
	 * @return
	 * The created
	 */
	public String getCreated() {
		return created;
	}

	/**
	 *
	 * @param created
	 * The created
	 */
	public void setCreated(String created) {
		this.created = created;
	}

	/**
	 *
	 * @return
	 * The cryptedId
	 */
	public String getCryptedId() {
		return cryptedId;
	}

	/**
	 *
	 * @param cryptedId
	 * The cryptedId
	 */
	public void setCryptedId(String cryptedId) {
		this.cryptedId = cryptedId;
	}

	/**
	 *
	 * @return
	 * The domain
	 */
	public String getDomain() {
		return domain;
	}

	/**
	 *
	 * @param domain
	 * The domain
	 */
	public void setDomain(String domain) {
		this.domain = domain;
	}

	/**
	 *
	 * @return
	 * The email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 *
	 * @param email
	 * The email
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 *
	 * @return
	 * The emailFormat
	 */
	public String getEmailFormat() {
		return emailFormat;
	}

	/**
	 *
	 * @param emailFormat
	 * The emailFormat
	 */
	public void setEmailFormat(String emailFormat) {
		this.emailFormat = emailFormat;
	}

	/**
	 *
	 * @return
	 * The fax
	 */
	public String getFax() {
		return fax;
	}

	/**
	 *
	 * @param fax
	 * The fax
	 */
	public void setFax(String fax) {
		this.fax = fax;
	}

	/**
	 *
	 * @return
	 * The firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 *
	 * @param firstName
	 * The firstName
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 *
	 * @return
	 * The gender
	 */
	public String getGender() {
		return gender;
	}

	/**
	 *
	 * @param gender
	 * The gender
	 */
	public void setGender(String gender) {
		this.gender = gender;
	}

	/**
	 *
	 * @return
	 * The lastModified
	 */
	public String getLastModified() {
		return lastModified;
	}

	/**
	 *
	 * @param lastModified
	 * The lastModified
	 */
	public void setLastModified(String lastModified) {
		this.lastModified = lastModified;
	}

	/**
	 *
	 * @return
	 * The lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 *
	 * @param lastName
	 * The lastName
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 *
	 * @return
	 * The location
	 */
	public Location getLocation() {
		return location;
	}

	/**
	 *
	 * @param location
	 * The location
	 */
	public void setLocation(Location location) {
		this.location = location;
	}

	/**
	 *
	 * @return
	 * The middleName
	 */
	public String getMiddleName() {
		return middleName;
	}

	/**
	 *
	 * @param middleName
	 * The middleName
	 */
	public void setMiddleName(String middleName) {
		this.middleName = middleName;
	}

	/**
	 *
	 * @return
	 * The mobilePhone
	 */
	public String getMobilePhone() {
		return mobilePhone;
	}

	/**
	 *
	 * @param mobilePhone
	 * The mobilePhone
	 */
	public void setMobilePhone(String mobilePhone) {
		this.mobilePhone = mobilePhone;
	}

	/**
	 *
	 * @return
	 * The phone
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 *
	 * @param phone
	 * The phone
	 */
	public void setPhone(String phone) {
		this.phone = phone;
	}

	/**
	 *
	 * @return
	 * The postalAddress
	 */
	public PostalAddress getPostalAddress() {
		return postalAddress;
	}

	/**
	 *
	 * @param postalAddress
	 * The postalAddress
	 */
	public void setPostalAddress(PostalAddress postalAddress) {
		this.postalAddress = postalAddress;
	}

	/**
	 *
	 * @return
	 * The salutation
	 */
	public String getSalutation() {
		return salutation;
	}

	/**
	 *
	 * @param salutation
	 * The salutation
	 */
	public void setSalutation(String salutation) {
		this.salutation = salutation;
	}

	/**
	 *
	 * @return
	 * The subscriptions
	 */
	public CampaignServiceUrl getUrlToSubscriptions() {
		return urlToSubscriptions;
	}

	/**
	 *
	 * @param subscriptions
	 * The subscriptions
	 */
	public void setUrlToSubscriptions(CampaignServiceUrl urlToSubscriptions) {
		this.urlToSubscriptions = urlToSubscriptions;
	}

	/**
	 *
	 * @return
	 * The thumbnail
	 */
	public String getThumbnail() {
		return thumbnail;
	}

	/**
	 *
	 * @param thumbnail
	 * The thumbnail
	 */
	public void setThumbnail(String thumbnail) {
		this.thumbnail = thumbnail;
	}

	/**
	 *
	 * @return
	 * The title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 *
	 * @param title
	 * The title
	 */
	public void setTitle(String title) {
		this.title = title;
	}

	public Profile(String pKey) {
		this.pKey = pKey;
	}

}


text:
"""Test HTML5 notify platform."""
import json
from unittest.mock import MagicMock, mock_open, patch

from aiohttp.hdrs import AUTHORIZATION

import homeassistant.components.html5.notify as html5
from homeassistant.const import HTTP_INTERNAL_SERVER_ERROR
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component

CONFIG_FILE = "file.conf"

VAPID_CONF = {
    "vapid_pub_key": "BJMA2gDZEkHaXRhf1fhY_"
    + "QbKbhVIHlSJXI0bFyo0eJXnUPOjdgycCAbj-2bMKMKNKs"
    + "_rM8JoSnyKGCXAY2dbONI",
    "vapid_prv_key": "ZwPgwKpESGuGLMZYU39vKgrekrWzCijo-LsBM3CZ9-c",
    "vapid_email": "someone@example.com",
}

SUBSCRIPTION_1 = {
    "browser": "chrome",
    "subscription": {
        "endpoint": "https://googleapis.com",
        "keys": {"auth": "auth", "p256dh": "p256dh"},
    },
}
SUBSCRIPTION_2 = {
    "browser": "firefox",
    "subscription": {
        "endpoint": "https://example.com",
        "keys": {"auth": "bla", "p256dh": "bla"},
    },
}
SUBSCRIPTION_3 = {
    "browser": "chrome",
    "subscription": {
        "endpoint": "https://example.com/not_exist",
        "keys": {"auth": "bla", "p256dh": "bla"},
    },
}
SUBSCRIPTION_4 = {
    "browser": "chrome",
    "subscription": {
        "endpoint": "https://googleapis.com",
        "expirationTime": None,
        "keys": {"auth": "auth", "p256dh": "p256dh"},
    },
}

SUBSCRIPTION_5 = {
    "browser": "chrome",
    "subscription": {
        "endpoint": "https://fcm.googleapis.com/fcm/send/LONG-RANDOM-KEY",
        "expirationTime": None,
        "keys": {"auth": "auth", "p256dh": "p256dh"},
    },
}

REGISTER_URL = "/api/notify.html5"
PUBLISH_URL = "/api/notify.html5/callback"

async def mock_client(hass, hass_client, registrations=None):
    """Create a test client for HTML5 views."""
    if registrations is None:
        registrations = {}

    with patch(
        "homeassistant.components.html5.notify._load_config", return_value=registrations
    ):
        await async_setup_component(hass, "notify", {"notify": {"platform": "html5"}})
        await hass.async_block_till_done()

    return await hass_client()

class TestHtml5Notify:
    """Tests for HTML5 notify platform."""

    def test_get_service_with_no_json(self):
        """Test empty json file."""
        hass = MagicMock()

        m = mock_open()
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, {})

        assert service is not None

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_dismissing_message(self, mock_wp):
        """Test dismissing message."""
        hass = MagicMock()

        data = {"device": SUBSCRIPTION_1}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, {"gcm_sender_id": "100"})

        assert service is not None

        service.dismiss(target=["device", "non_existing"], data={"tag": "test"})

        assert len(mock_wp.mock_calls) == 3

        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"]
        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Call to send
        payload = json.loads(mock_wp.mock_calls[1][1][0])

        assert payload["dismiss"] is True
        assert payload["tag"] == "test"

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_sending_message(self, mock_wp):
        """Test sending message."""
        hass = MagicMock()

        data = {"device": SUBSCRIPTION_1}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, {"gcm_sender_id": "100"})

        assert service is not None

        service.send_message(
            "Hello", target=["device", "non_existing"], data={"icon": "beer.png"}
        )

        assert len(mock_wp.mock_calls) == 3

        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"]
        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Call to send
        payload = json.loads(mock_wp.mock_calls[1][1][0])

        assert payload["body"] == "Hello"
        assert payload["icon"] == "beer.png"

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_gcm_key_include(self, mock_wp):
        """Test if the gcm_key is only included for GCM endpoints."""
        hass = MagicMock()

        data = {"chrome": SUBSCRIPTION_1, "firefox": SUBSCRIPTION_2}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(
                hass, {"gcm_sender_id": "100", "gcm_api_key": "Y6i0JdZ0mj9LOaSI"}
            )

        assert service is not None

        service.send_message("Hello", target=["chrome", "firefox"])

        assert len(mock_wp.mock_calls) == 6

        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"]
        assert mock_wp.mock_calls[3][1][0] == SUBSCRIPTION_2["subscription"]

        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"
        assert mock_wp.mock_calls[5][0] == "().send().status_code.__eq__"

        # Get the keys passed to the WebPusher's send method
        assert mock_wp.mock_calls[1][2]["gcm_key"] is not None
        assert mock_wp.mock_calls[4][2]["gcm_key"] is None

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_fcm_key_include(self, mock_wp):
        """Test if the FCM header is included."""
        hass = MagicMock()

        data = {"chrome": SUBSCRIPTION_5}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, VAPID_CONF)

        assert service is not None

        service.send_message("Hello", target=["chrome"])

        assert len(mock_wp.mock_calls) == 3
        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_5["subscription"]

        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Get the keys passed to the WebPusher's send method
        assert mock_wp.mock_calls[1][2]["headers"]["Authorization"] is not None

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_fcm_send_with_unknown_priority(self, mock_wp):
        """Test if the gcm_key is only included for GCM endpoints."""
        hass = MagicMock()

        data = {"chrome": SUBSCRIPTION_5}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, VAPID_CONF)

        assert service is not None

        service.send_message("Hello", target=["chrome"], priority="undefined")

        assert len(mock_wp.mock_calls) == 3
        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_5["subscription"]

        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Get the keys passed to the WebPusher's send method
        assert mock_wp.mock_calls[1][2]["headers"]["priority"] == "normal"

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_fcm_no_targets(self, mock_wp):
        """Test if the gcm_key is only included for GCM endpoints."""
        hass = MagicMock()

        data = {"chrome": SUBSCRIPTION_5}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, VAPID_CONF)

        assert service is not None

        service.send_message("Hello")

        assert len(mock_wp.mock_calls) == 3
        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_5["subscription"]

        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Get the keys passed to the WebPusher's send method
        assert mock_wp.mock_calls[1][2]["headers"]["priority"] == "normal"

    @patch("homeassistant.components.html5.notify.WebPusher")
    def test_fcm_additional_data(self, mock_wp):
        """Test if the gcm_key is only included for GCM endpoints."""
        hass = MagicMock()

        data = {"chrome": SUBSCRIPTION_5}

        m = mock_open(read_data=json.dumps(data))
        with patch("homeassistant.util.json.open", m, create=True):
            service = html5.get_service(hass, VAPID_CONF)

        assert service is not None

        service.send_message("Hello", data={"mykey": "myvalue"})

        assert len(mock_wp.mock_calls) == 3
        # WebPusher constructor
        assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_5["subscription"]

        # Third mock_call checks the status_code of the response.
        assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

        # Get the keys passed to the WebPusher's send method
        assert mock_wp.mock_calls[1][2]["headers"]["priority"] == "normal"

def test_create_vapid_withoutvapid():
    """Test creating empty vapid."""
    resp = html5.create_vapid_headers(
        vapid_email=None, vapid_private_key=None, subscription_info=None
    )
    assert resp is None

async def test_registering_new_device_view(hass, hass_client):
    """Test that the HTML view works."""
    client = await mock_client(hass, hass_client)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))

    assert resp.status == 200
    assert len(mock_save.mock_calls) == 1
    assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_1}

async def test_registering_new_device_view_with_name(hass, hass_client):
    """Test that the HTML view works with name attribute."""
    client = await mock_client(hass, hass_client)

    SUB_WITH_NAME = SUBSCRIPTION_1.copy()
    SUB_WITH_NAME["name"] = "test device"

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        resp = await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))

    assert resp.status == 200
    assert len(mock_save.mock_calls) == 1
    assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_1}

async def test_registering_new_device_expiration_view(hass, hass_client):
    """Test that the HTML view works."""
    client = await mock_client(hass, hass_client)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))

    assert resp.status == 200
    assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4}

async def test_registering_new_device_fails_view(hass, hass_client):
    """Test subs. are not altered when registering a new device fails."""
    registrations = {}
    client = await mock_client(hass, hass_client, registrations)

    with patch(
        "homeassistant.components.html5.notify.save_json",
        side_effect=HomeAssistantError(),
    ):
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))

    assert resp.status == HTTP_INTERNAL_SERVER_ERROR
    assert registrations == {}

async def test_registering_existing_device_view(hass, hass_client):
    """Test subscription is updated when registering existing device."""
    registrations = {}
    client = await mock_client(hass, hass_client, registrations)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))

    assert resp.status == 200
    assert mock_save.mock_calls[0][1][1] == {"unnamed device": SUBSCRIPTION_4}
    assert registrations == {"unnamed device": SUBSCRIPTION_4}

async def test_registering_existing_device_view_with_name(hass, hass_client):
    """Test subscription is updated when reg'ing existing device with name."""
    registrations = {}
    client = await mock_client(hass, hass_client, registrations)

    SUB_WITH_NAME = SUBSCRIPTION_1.copy()
    SUB_WITH_NAME["name"] = "test device"

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        await client.post(REGISTER_URL, data=json.dumps(SUB_WITH_NAME))
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))

    assert resp.status == 200
    assert mock_save.mock_calls[0][1][1] == {"test device": SUBSCRIPTION_4}
    assert registrations == {"test device": SUBSCRIPTION_4}

async def test_registering_existing_device_fails_view(hass, hass_client):
    """Test sub. is not updated when registering existing device fails."""
    registrations = {}
    client = await mock_client(hass, hass_client, registrations)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_1))
        mock_save.side_effect = HomeAssistantError
        resp = await client.post(REGISTER_URL, data=json.dumps(SUBSCRIPTION_4))

    assert resp.status == HTTP_INTERNAL_SERVER_ERROR
    assert registrations == {"unnamed device": SUBSCRIPTION_1}

async def test_registering_new_device_validation(hass, hass_client):
    """Test various errors when registering a new device."""
    client = await mock_client(hass, hass_client)

    resp = await client.post(
        REGISTER_URL,
        data=json.dumps({"browser": "invalid browser", "subscription": "sub info"}),
    )
    assert resp.status == 400

    resp = await client.post(REGISTER_URL, data=json.dumps({"browser": "chrome"}))
    assert resp.status == 400

    with patch("homeassistant.components.html5.notify.save_json", return_value=False):
        resp = await client.post(
            REGISTER_URL,
            data=json.dumps({"browser": "chrome", "subscription": "sub info"}),
        )
    assert resp.status == 400

async def test_unregistering_device_view(hass, hass_client):
    """Test that the HTML unregister view works."""
    registrations = {"some device": SUBSCRIPTION_1, "other device": SUBSCRIPTION_2}
    client = await mock_client(hass, hass_client, registrations)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        resp = await client.delete(
            REGISTER_URL,
            data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}),
        )

    assert resp.status == 200
    assert len(mock_save.mock_calls) == 1
    assert registrations == {"other device": SUBSCRIPTION_2}

async def test_unregister_device_view_handle_unknown_subscription(hass, hass_client):
    """Test that the HTML unregister view handles unknown subscriptions."""
    registrations = {}
    client = await mock_client(hass, hass_client, registrations)

    with patch("homeassistant.components.html5.notify.save_json") as mock_save:
        resp = await client.delete(
            REGISTER_URL,
            data=json.dumps({"subscription": SUBSCRIPTION_3["subscription"]}),
        )

    assert resp.status == 200, resp.response
    assert registrations == {}
    assert len(mock_save.mock_calls) == 0

async def test_unregistering_device_view_handles_save_error(hass, hass_client):
    """Test that the HTML unregister view handles save errors."""
    registrations = {"some device": SUBSCRIPTION_1, "other device": SUBSCRIPTION_2}
    client = await mock_client(hass, hass_client, registrations)

    with patch(
        "homeassistant.components.html5.notify.save_json",
        side_effect=HomeAssistantError(),
    ):
        resp = await client.delete(
            REGISTER_URL,
            data=json.dumps({"subscription": SUBSCRIPTION_1["subscription"]}),
        )

    assert resp.status == HTTP_INTERNAL_SERVER_ERROR, resp.response
    assert registrations == {
        "some device": SUBSCRIPTION_1,
        "other device": SUBSCRIPTION_2,
    }

async def test_callback_view_no_jwt(hass, hass_client):
    """Test that the notification callback view works without JWT."""
    client = await mock_client(hass, hass_client)
    resp = await client.post(
        PUBLISH_URL,
        data=json.dumps(
            {"type": "push", "tag": "3bc28d69-0921-41f1-ac6a-7a627ba0aa72"}
        ),
    )

    assert resp.status == 401

async def test_callback_view_with_jwt(hass, hass_client):
    """Test that the notification callback view works with JWT."""
    registrations = {"device": SUBSCRIPTION_1}
    client = await mock_client(hass, hass_client, registrations)

    with patch("homeassistant.components.html5.notify.WebPusher") as mock_wp:
        await hass.services.async_call(
            "notify",
            "notify",
            {"message": "Hello", "target": ["device"], "data": {"icon": "beer.png"}},
            blocking=True,
        )

    assert len(mock_wp.mock_calls) == 3

    # WebPusher constructor
    assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_1["subscription"]
    # Third mock_call checks the status_code of the response.
    assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"

    # Call to send
    push_payload = json.loads(mock_wp.mock_calls[1][1][0])

    assert push_payload["body"] == "Hello"
    assert push_payload["icon"] == "beer.png"

    bearer_token = "Bearer {}".format(push_payload["data"]["jwt"])

    resp = await client.post(
        PUBLISH_URL, json={"type": "push"}, headers={AUTHORIZATION: bearer_token}
    )

    assert resp.status == 200
    body = await resp.json()
    assert body == {"event": "push", "status": "ok"}

async def test_send_fcm_without_targets(hass, hass_client):
    """Test that the notification is send with FCM without targets."""
    registrations = {"device": SUBSCRIPTION_5}
    await mock_client(hass, hass_client, registrations)
    with patch("homeassistant.components.html5.notify.WebPusher") as mock_wp:
        await hass.services.async_call(
            "notify",
            "notify",
            {"message": "Hello", "target": ["device"], "data": {"icon": "beer.png"}},
            blocking=True,
        )

    assert len(mock_wp.mock_calls) == 3

    # WebPusher constructor
    assert mock_wp.mock_calls[0][1][0] == SUBSCRIPTION_5["subscription"]
    # Third mock_call checks the status_code of the response.
    assert mock_wp.mock_calls[2][0] == "().send().status_code.__eq__"


text:
package hu.akarnokd.experiments.collections;

import java.util.*;

import org.junit.*;

public class RingListTest {
    @Test
    public void testRemoveFirst() {
        RingList<Integer> list = new RingList<Integer>(4);
        list.add(1);
        list.add(2);

        list.remove(1);

        List<Integer> other = new ArrayList<Integer>();
        list.addTo(other);

        Assert.assertEquals(Arrays.asList(2), other);
    }
    @Test
    public void testRemoveLast() {
        RingList<Integer> list = new RingList<Integer>(4);
        list.add(1);
        list.add(2);

        list.remove(2);

        List<Integer> other = new ArrayList<Integer>(4);
        list.addTo(other);

        Assert.assertEquals(Arrays.asList(1), other);
    }
    @Test
    public void testRemoveMiddle() {
        RingList<Integer> list = new RingList<Integer>(4);
        list.add(1);
        list.add(2);
        list.add(3);

        list.remove(2);

        List<Integer> other = new ArrayList<Integer>();
        list.addTo(other);

        Assert.assertEquals(Arrays.asList(1, 3), other);
    }
    @Test
    public void testRemoveSingle() {
        RingList<Integer> list = new RingList<Integer>(4);
        list.add(1);

        list.remove(1);

        List<Integer> other = new ArrayList<Integer>();
        list.addTo(other);

        Assert.assertEquals(Collections.emptyList(), other);

        list.add(1);

        list.addTo(other);
        Assert.assertEquals(Arrays.asList(1), other);
    }

    @Test
    public void testWrap() {
        RingList<Integer> list = new RingList<Integer>(4);
        list.add(1);
        list.add(2);

        list.remove(1);
        list.remove(2);

        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);

        List<Integer> other = new ArrayList<Integer>();
        list.addTo(other);

        Assert.assertEquals(Arrays.asList(3, 4, 5, 6), other);
    }

}


text:
module Openfire
  module Ruby
    class User < Base
      has_one :roster
    end
  end
end


text:
'use strict';

var controller = require('../controllers/socket.io');
var user = {};

module.exports = function(io) {
    io.use(function(socket, next) {
        var data = socket.request;

        if (data.headers.cookie) {
            data.cookie = require('cookie').parse(data.headers.cookie);
            socket.sessionID = data.cookie['express.sid'];

            if (!socket.sessionID) {
                next(new Error('No session transmitted.'));
            }
        } else {
           next(new Error('No cookie transmitted.'));
        }

        next();
    });

    io.on('connection', function(socket) {
        var sID = socket.sessionID;

        if (user[sID]) {
            socket.disconnect();
            return false;
        }

        user[sID] = {
            id: socket.id,
            ip: socket.request.connection.remoteAddress,
            agent: socket.request.headers['user-agent']
        };

        io.emit('user:count', Object.keys(user).length);

        socket.on('disconnect', function() {
            delete user[sID];
            socket.broadcast.emit('user:count', Object.keys(user).length);
        });

        controller.poll(socket, io);
    });
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>GOST28147ParameterSpec (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.bouncycastle.jce.spec

Class GOST28147ParameterSpec

java.lang.Object

org.bouncycastle.jcajce.spec.GOST28147ParameterSpec

org.bouncycastle.jce.spec.GOST28147ParameterSpec

All Implemented Interfaces:

java.security.spec.AlgorithmParameterSpec

Deprecated.

use  org.bouncycastle.jcajce.spec.GOST28147ParameterSpec

public class GOST28147ParameterSpec
extends GOST28147ParameterSpec

A parameter spec for the GOST-28147 cipher.

Constructor Summary

Constructors

Constructor and Description

GOST28147ParameterSpec(byte[] sBox)

Deprecated.

GOST28147ParameterSpec(byte[] sBox,
                      byte[] iv)

Deprecated.

GOST28147ParameterSpec(java.lang.String sBoxName)

Deprecated.

GOST28147ParameterSpec(java.lang.String sBoxName,
                      byte[] iv)

Deprecated.

Method Summary

Methods inherited from class org.bouncycastle.jcajce.spec.GOST28147ParameterSpec

getIV, getSbox

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GOST28147ParameterSpec

public GOST28147ParameterSpec(byte[] sBox)

Deprecated.

GOST28147ParameterSpec

public GOST28147ParameterSpec(byte[] sBox,
                      byte[] iv)

Deprecated.

GOST28147ParameterSpec

public GOST28147ParameterSpec(java.lang.String sBoxName)

Deprecated.

GOST28147ParameterSpec

public GOST28147ParameterSpec(java.lang.String sBoxName,
                      byte[] iv)

Deprecated.

Overview

Package

Class

Tree

Deprecated

Index

Help

Bouncy Castle Cryptography Library 1.54

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package commands

import (
	"flag"
	"fmt"
	"github.com/starkandwayne/cf-cli/cf/api"
	"github.com/starkandwayne/cf-cli/cf/app"
	"github.com/starkandwayne/cf-cli/cf/command_factory"
	"github.com/starkandwayne/cf-cli/cf/command_runner"
	"github.com/starkandwayne/cf-cli/cf/manifest"
	"github.com/starkandwayne/cf-cli/cf/net"
	testconfig "github.com/starkandwayne/cf-cli/testhelpers/configuration"
	testreq "github.com/starkandwayne/cf-cli/testhelpers/requirements"
	testterm "github.com/starkandwayne/cf-cli/testhelpers/terminal"
	"github.com/codegangsta/cli"
	"strings"
)

func NewContext(cmdName string, args []string) *cli.Context {
	targetCommand := findCommand(cmdName)

	flagSet := new(flag.FlagSet)
	for i, _ := range targetCommand.Flags {
		targetCommand.Flags[i].Apply(flagSet)
	}

	// move all flag args to the beginning of the list, go requires them all upfront
	firstFlagIndex := -1
	for index, arg := range args {
		if strings.HasPrefix(arg, "-") {
			firstFlagIndex = index
			break
		}
	}
	if firstFlagIndex > 0 {
		args := args[0:firstFlagIndex]
		flags := args[firstFlagIndex:]
		flagSet.Parse(append(flags, args...))
	} else {
		flagSet.Parse(args[0:])
	}

	globalSet := new(flag.FlagSet)

	return cli.NewContext(cli.NewApp(), flagSet, globalSet)
}

func findCommand(cmdName string) (cmd cli.Command) {
	fakeUI := &testterm.FakeUI{}
	configRepo := testconfig.NewRepository()
	manifestRepo := manifest.NewManifestDiskRepository()
	apiRepoLocator := api.NewRepositoryLocator(configRepo, map[string]net.Gateway{
		"auth":             net.NewUAAGateway(configRepo),
		"cloud-controller": net.NewCloudControllerGateway(configRepo),
		"uaa":              net.NewUAAGateway(configRepo),
	})

	cmdFactory := command_factory.NewFactory(fakeUI, configRepo, manifestRepo, apiRepoLocator)
	requirementsFactory := &testreq.FakeReqFactory{}
	cmdRunner := command_runner.NewRunner(cmdFactory, requirementsFactory)
	myApp := app.NewApp(cmdRunner, cmdFactory.CommandMetadatas()...)

	for _, cmd := range myApp.Commands {
		if cmd.Name == cmdName {
			return cmd
		}
	}
	panic(fmt.Sprintf("command %s does not exist", cmdName))
	return
}


text:
import React from 'react';
import { action } from '@storybook/addon-actions';
import ActionList from './ActionList.component';

const actions = [
	{
		label: 'Recent datasets',
		icon: 'talend-clock',
		'data-feature': 'actionlist.item',
		onClick: action('Recent clicked'),
	},
	{
		label: 'Favorite datasets of the year 2019',
		iconName: 'star',
		'data-feature': 'actionlist.item',
		onClick: action('Favorite clicked'),
		beta: true,
		active: true,
	},
	{
		label: 'Certified datasets',
		icon: 'talend-badge',
		'data-feature': 'actionlist.item',
		onClick: action('Certified clicked'),
	},
	{
		label: 'All datasets',
		icon: 'talend-expanded',
		'data-feature': 'actionlist.item',
		onClick: action('All clicked'),
	},
	{
		label: 'Import file',
		icon: 'talend-folder',
		'data-feature': 'actionlist.item',
		onClick: action('Import clicked'),
	},
	{
		label: 'Use magic',
		icon: 'talend-tdp-negative',
		'data-feature': 'actionlist.item',
		onClick: action('Magic clicked'),
	},
];

export default {
	title: 'Navigation/ActionList',
};

export const Default = () => (

		<ActionList
			id="context"
			actions={actions}
			onSelect={action('onItemSelect')}
			onToggleDock={action('onToggleDock')}
			tooltipPlacement="top"
		/>

);

export const WithCustomClassNames = () => (

You can add your custom classnames to the container and items

			{`
.custom-container-classname {
    border: 5px solid turquoise;
}

.custom-item-classname {
    background-color: pink;
}
                    `}

			{`
<ActionList
    className={'custom-container-classname'}
    itemClassName={'custom-item-classname'}
    {...otherProps}
/>
            `}

			<ActionList
				id="context"
				actions={actions}
				onSelect={action('onItemSelect')}
				onToggleDock={action('onToggleDock')}
				tooltipPlacement="top"
				className="custom-container-classname"
				itemClassName="custom-item-classname"
			/>

);

export const Single = () => (

		<ActionList
			id="context"
			actions={[actions[1]]}
			onSelect={action('onItemSelect')}
			onToggleDock={action('onToggleDock')}
			tooltipPlacement="top"
		/>

);


text:
package com.example.becomebeacon.beaconlocker.pictureserver;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;

import com.example.becomebeacon.beaconlocker.PermissionRequester;

import java.io.File;

/**
 * Created by gwmail on 2017-06-04.
 */

public class PicturePopup {
    private Context mContext;

    public static final int CHOOSE_PICTURE = 0;
    public static final int TAKE_PICTURE = 1;
    public static final int CROP_SMALL_PICTURE = 2;

    private Uri tempUri;

    public PicturePopup(Context context) throws Exception{
        this.mContext = context;
    }

    public void showChoosePicDialog(final Callback choosePictureCallback, final Callback takePictureCallback) throws Exception{
        int result1 = new PermissionRequester.Builder((Activity) mContext)
                .setTitle("권한 요청")
                .setMessage("권한을 요청합니다.")
                .setPositiveButtonName("네")
                .setNegativeButtonName("아니요.")
                .create()
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, 1000 , new PermissionRequester.OnClickDenyButtonListener() {
                    @Override
                    public void onClick(Activity activity) {

                    }
                });

        if (result1 == PermissionRequester.ALREADY_GRANTED) {

            if (ActivityCompat.checkSelfPermission( mContext,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            }
        }
        else if(result1 == PermissionRequester.NOT_SUPPORT_VERSION)
        {

        }

        else if(result1 == PermissionRequester.REQUEST_PERMISSION) {

            int result2 = new PermissionRequester.Builder((Activity) mContext)
                    .setTitle("권한 요청")
                    .setMessage("권한을 요청합니다.")
                    .setPositiveButtonName("네")
                    .setNegativeButtonName("아니요.")
                    .create()
                    .request(Manifest.permission.READ_EXTERNAL_STORAGE, 1000 , new PermissionRequester.OnClickDenyButtonListener() {
                        @Override
                        public void onClick(Activity activity) {

                        }
                    });

            if (result2 == PermissionRequester.ALREADY_GRANTED) {

                if (ActivityCompat.checkSelfPermission(mContext,
                        Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                }
            }
            else if(result2 == PermissionRequester.NOT_SUPPORT_VERSION)
            {

            }
            else if(result2 == PermissionRequester.REQUEST_PERMISSION) {

            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("사진선택");
        String[] items = { "사진 선택하기", "카메라" };
        builder.setNegativeButton("취소", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 사진 선택
                        Intent openAlbumIntent = new Intent(Intent.ACTION_PICK);
                        openAlbumIntent.setType("image/*");
                        choosePictureCallback.callBackMethod(openAlbumIntent);
                        break;
                    case TAKE_PICTURE: // 카메라
                        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp_image.png"));
                        // 카메라 찍은사진은 SD에 저장
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        takePictureCallback.callBackMethod(openCameraIntent);
                        break;
                }
            }
        });
        builder.show();
    }

    public void pictureActivityForResult (int requestCode, Intent data, Callback ImageToViewCallback) throws Exception{
        switch (requestCode) {
            case TAKE_PICTURE:
                ImageToViewCallback.callBackMethod(tempUri);
                break;
            case CHOOSE_PICTURE:
                tempUri = data.getData();
                ImageToViewCallback.callBackMethod(tempUri);
                break;
        }
    }

    public void cutImage(Callback cropSmallPictureCallback){
        if (tempUri == null) {

        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(tempUri, "image/*");
        // 설정
        intent.putExtra("crop", "true");
        // aspectX aspectY
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        // temp Uri 에 저장
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);

        cropSmallPictureCallback.callBackMethod(intent);
    }
}


text:
export default {
    activationFunction: {
        SIGMOID: (value, derivative = false) => {
            const sigmoidFn = 1 / (1 + Math.pow(Math.E, -value));
            const sigmoidFnDerivative = sigmoidFn * (1 - sigmoidFn);
            if (derivative) return sigmoidFnDerivative;
            if (!derivative) return sigmoidFn;
        },
        TANH: (value, derivative = false) => {
            const tanhFn = (Math.exp(value) - (1 / Math.exp(value))) / (Math.exp(value) + (1 / Math.exp(value)));
            const tanhFnDerivative = tanhFn - Math.pow(tanhFn, 2);
            if (derivative) return tanhFnDerivative;
            if (!derivative) return tanhFn;
        },
        LOGISTIC: (value, derivative = false) => {
            const logisticFn = 1 / (1 + Math.exp(-value));
            const logisticFnDerivative = logisticFn * (1 - logisticFn);
            if (derivative) return logisticFnDerivative;
            if (!derivative) return logisticFn;
        }
    },
    costFn: {
        CROSS_ENTROPY: (expected, output) => {
            let crossEntropy = 0;
            output.map((value, i) => {
                crossEntropy -= (expected[i] * Math.log(value + 1e-15)) + ((1 - value) * Math.log((1 + 1e-15) - output[i]));
            });
            return crossEntropy;
        },
        MSE: (expected, output) => {
            let mse = 0;
            output.map((value, i) => {
                mse += Math.pow(expected[i] - value, 2);
            });
            return mse / output.length;
        },
        BINARY: (expected, output) => {
            let misses = 0;
            output.map((value, i) => {
                misses += Math.round(expected[i] * 2) !== Math.round(value * 2);
            });
            return misses;
        }
    }
};


text:
<!DOCTYPE html>

  <title>My Blog</title>
  <meta charset="UTF-8">
  <link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Slabo+27px' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" type="text/css" href="../Stylesheet/stylesheet.css">

Updating the site!

09/27/2015

Feel free to check out past blog posts in the menu to the left!

Blog Posts

Blog Post 1

Blog Post 2

Arrays and Hashes

Thinking/Learning Style

Net-Neutrality

Enumerable Methods

Ruby Classes

Feedback!

Variable Scope

Stereotype Threat

JavaScript vs Ruby

Values

The Internet

Conflict

Questions

Updating the site!

    If you have been following me through phase 0 you will have noticed that I have made a lot of aesthetic improvements to the site this past week.  A lot of it was just toying around with CSS and making things a little prettier in general.

    It's funny because the difference between my sight from a visual standpoint is almost night and day.  Yet, changing backgrounds and editing the properties of different objects really isn't all that complicated.  If I looked at this sight 9 weeks ago I'd tell you there's no way I could make it despite it being pretty simple. It's amazing what dedication and practice will do even in short amounts of time.

    I was given one suggestion by a peer to make my "about me" and "resume" boxes closer together on the homepage. Personally, I liked them the way they were before but I went ahead and changed their orientation to please the masses (I'm a man of the people!). I'm not sure if moving things around makes that big of a difference.  However, as my site becomes more and more advanced it may eventually contribute to the overall user experience (UX).

    In any regard, I'm off to phase 1, people.  Wish me luck and hopefully I'll have time to continue making updates. Keep on keepin' on.


text:
import numpy as np
from scipy.stats import geom

# Here set up the parameters for the normal distribution.
# where loc is the mean and scale is the standard deviation.
p = 0.5
dist = geom(p)

# Setup the sample range
x = np.linspace(0, 5, 1000)

# Calling norm's PMF and CDF
pmf = dist.pmf(x)
cdf = dist.cdf(x)

# Here we draw out 500 random values from
sample = dist.rvs(500)


text:
package androidx.constraintLayout.desktop.constraintRendering.draw;

import androidx.constraintLayout.desktop.constraintRendering.SceneContext;

import java.awt.*;

/**
 * Paint interface for draw commands
 * This interface also implies a constructor that takes a String
 * Which can expand the serialization of the of the command
 */
public interface DrawCommand extends Comparable {
  int CONNECTION_LEVEL = 10 ;
  int COMPONENT_LEVEL = 20;
  int COMPONENT_SELECTED_LEVEL = 30;
  int CONNECTION_SELECTED_LEVEL = 40 ;
  int TARGET_LEVEL = 50;
  int CONNECTION_HOVER_LEVEL = 60;
  int CONNECTION_DELETE_LEVEL = 70;
  int TARGET_OVER_LEVEL = 80;
  int TOP_LEVEL = 100;
  int CLIP_LEVEL =  0;
  int UNCLIP_LEVEL =  1000;
  int POST_CLIP_LEVEL =  1010;
  int getLevel(); // things are drawn 0 first
  void paint(Graphics2D g, SceneContext sceneContext);
  String serialize();

  @Override
  default int compareTo(  Object o) {
    return Integer.compare(getLevel(), ((DrawCommand)o).getLevel());
  }
}


text:
/* 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.
 */
'use strict';

/**
 * General bootstrap of the application.
 */
angular.module('flowableModeler')
    .controller('EditorController', ['$rootScope', '$scope', '$http', '$q', '$routeParams', '$timeout', '$location', '$translate', '$modal', 'FormBuilderService',
        function ($rootScope, $scope, $http, $q, $routeParams, $timeout, $location, $translate, $modal, FormBuilderService) {

    $rootScope.editorFactory = $q.defer();

    $rootScope.forceSelectionRefresh = false;

    $rootScope.ignoreChanges = false; // by default never ignore changes

    $rootScope.staticIncludeVersion = Date.now();

    /**
     * Initialize the event bus: couple all Oryx events with a dispatch of the
     * event of the event bus. This way, it gets much easier to attach custom logic
     * to any event.
     */

    /* Helper method to fetch model from server (always needed) */
    function fetchModel() {

        var modelUrl;
        if ($routeParams.modelId) {
            modelUrl = FLOWABLE.URL.getModel($routeParams.modelId);
        } else {
            modelUrl = FLOWABLE.URL.newModelInfo();
        }

        $http({method: 'GET', url: modelUrl}).
            success(function (data, status, headers, config) {
                $rootScope.editor = new ORYX.Editor(data);
                $rootScope.modelData = angular.fromJson(data);
                $rootScope.editorFactory.resolve();
            }).
            error(function (data, status, headers, config) {
                $location.path("/processes/");
            });
    }

    function initScrollHandling() {
        var canvasSection = jQuery('#canvasSection');
        canvasSection.scroll(function() {

            // Hides the resizer and quick menu items during scrolling

            var selectedElements = $rootScope.editor.selection;
            var subSelectionElements = $rootScope.editor._subSelection;

            $scope.selectedElements = selectedElements;
            $scope.subSelectionElements = subSelectionElements;
            if (selectedElements && selectedElements.length > 0)
            {
            	$rootScope.selectedElementBeforeScrolling = selectedElements[0];
            }

            jQuery('.Oryx_button').each(function(i, obj) {
                  $scope.orginalOryxButtonStyle = obj.style.display;
                  obj.style.display = 'none';
            });
            jQuery('.resizer_southeast').each(function(i, obj) {
                  $scope.orginalResizerSEStyle = obj.style.display;
                  obj.style.display = 'none';
            });
            jQuery('.resizer_northwest').each(function(i, obj) {
                  $scope.orginalResizerNWStyle = obj.style.display;
                  obj.style.display = 'none';
            });
            $rootScope.editor.handleEvents({type:ORYX.CONFIG.EVENT_CANVAS_SCROLL});
        });

        canvasSection.scrollStopped(function(){

            // Puts the quick menu items and resizer back when scroll is stopped.

            $rootScope.editor.setSelection([]); // needed cause it checks for element changes and does nothing if the elements are the same
            $rootScope.editor.setSelection($scope.selectedElements, $scope.subSelectionElements);
            $scope.selectedElements = undefined;
            $scope.subSelectionElements = undefined;

            function handleDisplayProperty(obj) {
                if (jQuery(obj).position().top > 0) {
                    obj.style.display = 'block';
                } else {
                    obj.style.display = 'none';
                }
            }

            jQuery('.Oryx_button').each(function(i, obj) {
                handleDisplayProperty(obj);
            });
            jQuery('.resizer_southeast').each(function(i, obj) {
                handleDisplayProperty(obj);
            });
            jQuery('.resizer_northwest').each(function(i, obj) {
                handleDisplayProperty(obj);
            });

        });
    }

    /**
     * Initialize the Oryx Editor when the content has been loaded
     */
    if (!$rootScope.editorInitialized) {

        ORYX._loadPlugins();

        fetchModel();

        /**
         * A 'safer' apply that avoids concurrent updates (which $apply allows).
         */
        $rootScope.safeApply = function(fn) {
        	if (this.$root) {
	            var phase = this.$root.$$phase;
	            if(phase == '$apply' || phase == '$digest') {
	                if(fn && (typeof(fn) === 'function')) {
	                    fn();
	                }
	            } else {
	                this.$apply(fn);
	            }

        	} else {
                this.$apply(fn);
            }
        };

        /**
         * Initialize the event bus: couple all Oryx events with a dispatch of the
         * event of the event bus. This way, it gets much easier to attach custom logic
         * to any event.
         */

        $rootScope.editorFactory.promise.then(function() {

            $rootScope.formItems = undefined;

            FLOWABLE.eventBus.editor = $rootScope.editor;

            var eventMappings = [
                { oryxType : ORYX.CONFIG.EVENT_SELECTION_CHANGED, flowableType : FLOWABLE.eventBus.EVENT_TYPE_SELECTION_CHANGE },
                { oryxType : ORYX.CONFIG.EVENT_DBLCLICK, flowableType : FLOWABLE.eventBus.EVENT_TYPE_DOUBLE_CLICK },
                { oryxType : ORYX.CONFIG.EVENT_MOUSEOUT, flowableType : FLOWABLE.eventBus.EVENT_TYPE_MOUSE_OUT },
                { oryxType : ORYX.CONFIG.EVENT_MOUSEOVER, flowableType : FLOWABLE.eventBus.EVENT_TYPE_MOUSE_OVER }

            ];

            eventMappings.forEach(function(eventMapping) {
                $rootScope.editor.registerOnEvent(eventMapping.oryxType, function(event) {
                    FLOWABLE.eventBus.dispatch(eventMapping.flowableType, event);
                });
            });

            // The Oryx canvas is ready (we know since we're in this promise callback) and the
            // event bus is ready. The editor is now ready for use
            FLOWABLE.eventBus.dispatch(FLOWABLE.eventBus.EVENT_TYPE_EDITOR_READY, {type : FLOWABLE.eventBus.EVENT_TYPE_EDITOR_READY});

            // Show getting started if this is the first time (boolean true for use local storage)
            FLOWABLE_EDITOR_TOUR.gettingStarted($scope, $translate, $q, true);

        });

        // Hook in resizing of main panels when window resizes
        // TODO: perhaps move to a separate JS-file?
        jQuery(window).resize(function () {

            // Calculate the offset based on the bottom of the module header
            var offset = jQuery("#editor-header").offset();
            var propSectionHeight = jQuery('#propertySection').height();
            var canvas = jQuery('#canvasSection');
            var mainHeader = jQuery('#main-header');

            if (offset == undefined || offset === null
                || propSectionHeight === undefined || propSectionHeight === null
                || canvas === undefined || canvas === null || mainHeader === null) {
                return;
            }

            if ($rootScope.editor)
        	{
	        	var selectedElements = $rootScope.editor.selection;
	            var subSelectionElements = $rootScope.editor._subSelection;

	            $scope.selectedElements = selectedElements;
	            $scope.subSelectionElements = subSelectionElements;
	            if (selectedElements && selectedElements.length > 0)
	            {
	            	$rootScope.selectedElementBeforeScrolling = selectedElements[0];

	            	$rootScope.editor.setSelection([]); // needed cause it checks for element changes and does nothing if the elements are the same
	                $rootScope.editor.setSelection($scope.selectedElements, $scope.subSelectionElements);
	                $scope.selectedElements = undefined;
	                $scope.subSelectionElements = undefined;
	            }
        	}

            var totalAvailable = jQuery(window).height() - offset.top - mainHeader.height() - 21;
            canvas.height(totalAvailable - propSectionHeight);
            jQuery('#paletteSection').height(totalAvailable);

            // Update positions of the resize-markers, according to the canvas

            var actualCanvas = null;
            if (canvas && canvas[0].children[1]) {
                actualCanvas = canvas[0].children[1];
            }

            var canvasTop = canvas.position().top;
            var canvasLeft = canvas.position().left;
            var canvasHeight = canvas[0].clientHeight;
            var canvasWidth = canvas[0].clientWidth;
            var iconCenterOffset = 8;
            var widthDiff = 0;

            var actualWidth = 0;
            if(actualCanvas) {
                // In some browsers, the SVG-element clientwidth isn't available, so we revert to the parent
                actualWidth = actualCanvas.clientWidth || actualCanvas.parentNode.clientWidth;
            }

            if(actualWidth < canvas[0].clientWidth) {
                widthDiff = actualWidth - canvas[0].clientWidth;
                // In case the canvas is smaller than the actual viewport, the resizers should be moved
                canvasLeft -= widthDiff / 2;
                canvasWidth += widthDiff;
            }

            var iconWidth = 17;
            var iconOffset = 20;

            var north = jQuery('#canvas-grow-N');
            north.css('top', canvasTop + iconOffset + 'px');
            north.css('left', canvasLeft - 10 + (canvasWidth - iconWidth) / 2 + 'px');

            var south = jQuery('#canvas-grow-S');
            south.css('top', (canvasTop + canvasHeight - iconOffset - iconCenterOffset) +  'px');
            south.css('left', canvasLeft - 10 + (canvasWidth - iconWidth) / 2 + 'px');

            var east = jQuery('#canvas-grow-E');
            east.css('top', canvasTop - 10 + (canvasHeight - iconWidth) / 2 + 'px');
            east.css('left', (canvasLeft + canvasWidth - iconOffset - iconCenterOffset) + 'px');

            var west = jQuery('#canvas-grow-W');
            west.css('top', canvasTop -10 + (canvasHeight - iconWidth) / 2 + 'px');
            west.css('left', canvasLeft + iconOffset + 'px');

            north = jQuery('#canvas-shrink-N');
            north.css('top', canvasTop + iconOffset + 'px');
            north.css('left', canvasLeft + 10 + (canvasWidth - iconWidth) / 2 + 'px');

            south = jQuery('#canvas-shrink-S');
            south.css('top', (canvasTop + canvasHeight - iconOffset - iconCenterOffset) +  'px');
            south.css('left', canvasLeft +10 + (canvasWidth - iconWidth) / 2 + 'px');

            east = jQuery('#canvas-shrink-E');
            east.css('top', canvasTop + 10 + (canvasHeight - iconWidth) / 2 +  'px');
            east.css('left', (canvasLeft + canvasWidth - iconOffset - iconCenterOffset) + 'px');

            west = jQuery('#canvas-shrink-W');
            west.css('top', canvasTop + 10 + (canvasHeight - iconWidth) / 2 + 'px');
            west.css('left', canvasLeft + iconOffset + 'px');
        });

        jQuery(window).trigger('resize');

        jQuery.fn.scrollStopped = function(callback) {
            jQuery(this).scroll(function(){
                var self = this, $this = jQuery(self);
                if ($this.data('scrollTimeout')) {
                    clearTimeout($this.data('scrollTimeout'));
                }
                $this.data('scrollTimeout', setTimeout(callback,50,self));
            });
        };

        $rootScope.editorInitialized = true;

    } else {

        // Editor is already defined and in memory, we just need to fetch the model.
        fetchModel();

    }

    $scope.$on('$locationChangeStart', function(event, next, current) {
    	if ($rootScope.editor && !$rootScope.ignoreChanges) {
    		var plugins = $rootScope.editor.loadedPlugins;

    		var savePlugin;
    		for (var i=0; i<plugins.length; i++) {
    			if (plugins[i].type == 'ORYX.Plugins.Save') {
    				savePlugin = plugins[i];
    				break;
    			}
    		}

    		if (savePlugin && savePlugin.hasChanges()) {
    			// Always prevent location from changing. We'll use a popup to determine the action we want to take
    			event.preventDefault();

    			if (!$scope.unsavedChangesModalInstance) {

    				var handleResponseFunction = function (discard) {
    					$scope.unsavedChangesModalInstance = undefined;
    					if (discard) {
    						$rootScope.ignoreChanges = true;
    		                $location.url(next.substring(next.indexOf('/#') + 2));
    					} else {
    		                $rootScope.ignoreChanges = false;
    		                $rootScope.setMainPageById('processes');
    					}
    				};

    				$scope.handleResponseFunction = handleResponseFunction;

                    _internalCreateModal({
    					template: 'editor-app/popups/unsaved-changes.html',
    					scope: $scope
    				},  $modal, $scope);
    			}
    		}
    	}
    });

    // Always needed, cause the DOM element on wich the scroll event listeners are attached are changed for every new model
    initScrollHandling();

}]);

angular.module('flowableModeler')
  .controller('EditorUnsavedChangesPopupCtrl', ['$rootScope', '$scope', '$http', '$location', '$window', function ($rootScope, $scope, $http, $location, $window) {

    $scope.discard = function () {
      if ($scope.handleResponseFunction) {
        $scope.handleResponseFunction(true);
        // Also clear any 'onbeforeunload', added by oryx
        $window.onbeforeunload = undefined;
      }
      $scope.$hide();
    };

    $scope.save = function () {
      if ($scope.handleResponseFunction) {
        $scope.handleResponseFunction(false);
      }
      $scope.$hide();
    };

    $scope.cancel = function () {
      if ($scope.handleResponseFunction) {
        $scope.handleResponseFunction(null);
      }
      $scope.$hide();
    };
  }]);