text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SoftCore.Security;
using System.Data;
using Ext.Net;
using ExtMessage;

public partial class Modules_BaoHiem_QuyDinhChung_QuyDinhVeMucDongBaoHiem : UserControlBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!X.IsAjaxRequest)
        {
            hdfMaDonVi.Text = Session["MaDonVi"].ToString();
        }
    }
    protected void btnCapNhat_Click(object sender, DirectEventArgs e)
    {
        try
        {
            BHMUCDONGBAOHIEMInfo obj = new BHMUCDONGBAOHIEMInfo();
            BHMUCDONGBAOHIEMController ctr = new BHMUCDONGBAOHIEMController();

            if (dfNgayHieuLuc.SelectedDate.ToString().Contains("01/01/0001") == false)
            {
                obj.NgayHieuLuc = dfNgayHieuLuc.SelectedDate;
            }
            else
            {
                obj.NgayHieuLuc = DateTime.Now;
            }
            if (!string.IsNullOrEmpty(nfSanBHXH.Text))
                obj.SanBHXH = decimal.Parse(nfSanBHXH.Text.Replace(".", ","));
            //if (!string.IsNullOrEmpty(nfSanBHYT.Text))
            //    obj.SanBHYT = decimal.Parse(nfSanBHYT.Text.Replace(".", ","));
            //if (!string.IsNullOrEmpty(nfSanBHTN.Text))
            //    obj.SanBHTN = decimal.Parse(nfSanBHTN.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfTranBHXH.Text))
                obj.TranBHXH = decimal.Parse(nfTranBHXH.Text.Replace(".", ","));
            //if (!string.IsNullOrEmpty(nfTranBHYT.Text))
            //    obj.TranBHYT = decimal.Parse(nfTranBHYT.Text.Replace(".", ","));
            //if (!string.IsNullOrEmpty(nfTranBHTN.Text))
            //    obj.TranBHTN = decimal.Parse(nfTranBHTN.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHXHNhanVien.Text))
                obj.NVBYXH = decimal.Parse(nfBHXHNhanVien.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHYTNhanVien.Text))
                obj.NVBHYT = decimal.Parse(nfBHYTNhanVien.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHTNNhanVien.Text))
                obj.NVBHTN = decimal.Parse(nfBHTNNhanVien.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHXHDonVi.Text))
                obj.DVBHXH = decimal.Parse(nfBHXHDonVi.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHYTDonVi.Text))
                obj.DVBHYT = decimal.Parse(nfBHYTDonVi.Text.Replace(".", ","));
            if (!string.IsNullOrEmpty(nfBHTNDonVi.Text))
                obj.DVBHTN = decimal.Parse(nfBHTNDonVi.Text.Replace(".", ","));
            obj.UserID = CurrentUser.ID;
            obj.MaDonVi = Session["MaDonVi"].ToString();
            obj.DateCreate = DateTime.Now;
            if (e.ExtraParams["Command"] == "Edit")
            {
                if (!string.IsNullOrEmpty(hdfRecordID.Text))
                {
                    obj.ID = Convert.ToInt32(hdfRecordID.Text);
                }
                // tạm thời bỏ check ngày trùng
                //if (Check_NgayHieuLuc(dfNgayHieuLuc.SelectedDate) == true)
                //{
                //    X.MessageBox.Alert("Thông báo", " Ngày hiệu lực đã tồn tại").Show();
                //    dfNgayHieuLuc.Focus();
                //    return;
                //}
                //else
                //{
                    ctr.Update(obj);
                    wdAddWindow.Hide();
                //}
                //RM.RegisterClientScriptBlock("fd", string.Format("addUpdatedRecord('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}')", nfID.Text, nfNgayHieuLuc.Text, nfSanBHXH.Text, nfSanBHYT.Text, nfSanBHTN.Text, nfTranBHXH.Text, nfTranBHYT.Text, nfTranBHTN.Text, nfNVBYXH.Text, nfNVBHYT.Text, nfNVBHTN.Text, nfDVBHXH.Text, nfDVBHYT.Text, nfDVBHTN.Text, nfUserID.Text, nfDateCreate.Text, nfMaDonVi.Text));
            }
            else
            {
                if (Check_NgayHieuLuc(dfNgayHieuLuc.SelectedDate) == true)
                {
                    X.MessageBox.Alert("Thông báo", " Ngày hiệu lực đã tồn tại").Show();
                    dfNgayHieuLuc.Focus();
                    return;
                }
                else
                {
                    ctr.Insert(obj);
                    if (e.ExtraParams["Close"] == "True")
                    {
                        wdAddWindow.Hide();
                    }
                }
                // RM.RegisterClientScriptBlock("fd", string.Format("addRecord('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}', '{12}', '{13}', '{14}', '{15}', '{16}')", nfID.Text, nfNgayHieuLuc.Text, nfSanBHXH.Text, nfSanBHYT.Text, nfSanBHTN.Text, nfTranBHXH.Text, nfTranBHYT.Text, nfTranBHTN.Text, nfNVBYXH.Text, nfNVBHYT.Text, nfNVBHTN.Text, nfDVBHXH.Text, nfDVBHYT.Text, nfDVBHTN.Text, nfUserID.Text, nfDateCreate.Text, nfMaDonVi.Text));
            }
            GridPanel1.Reload();
        }
        catch (Exception ex)
        {

            X.MessageBox.Alert("Thông báo ", "Số năm vượt quá khoảng cho phép(1753->9999)").Show();
        }
    }
    protected bool Check_NgayHieuLuc(DateTime NgayHieuLuc)
    {
        DataTable record = DataController.DataHandler.GetInstance().ExecuteDataTable("GetAll_BHMucDongBH");
        if (record.Rows.Count>0)
        {
            for (int i = 0; i < record.Rows.Count; i++)
            {
                if (record.Rows[i]["NgayHieuLuc"].ToString()==NgayHieuLuc.ToString())
                {
                    return true;
                    break;
                }
            }
        }
        return false;
    }
    protected void btnOK_Click(object sender, DirectEventArgs e)
    {
        try
        {
            DataTable record = new BHMUCDONGBAOHIEMController().GetByPrkey(Convert.ToInt32(hdfCommand.Text));
            if (record.Rows.Count > 0)
            {
                Dialog.ShowNotification("Mã đã tồn tại");
            }
            else
            {
                record = new BHMUCDONGBAOHIEMController().GetByPrkey(Convert.ToInt32(hdfRecordID.Text));
                // record.Rows[0]["ID"] = Convert.ToInt32(nfmaloaihdcoppy.Text);
                BHMUCDONGBAOHIEMInfo item = new BHMUCDONGBAOHIEMInfo()
                {
                    ID = int.Parse(record.Rows[0]["ID"].ToString()),
                    NgayHieuLuc = DateTime.Parse(record.Rows[0]["NgayHieuLuc"].ToString().Replace(".", ",")),
                    SanBHXH = decimal.Parse(record.Rows[0]["SanBHXH"].ToString()),
                    //SanBHYT = decimal.Parse(record.Rows[0]["SanBHYT"].ToString()),
                    //SanBHTN = decimal.Parse(record.Rows[0]["SanBHTN"].ToString()),
                    TranBHXH = decimal.Parse(record.Rows[0]["TranBHXH"].ToString()),
                    //TranBHYT = decimal.Parse(record.Rows[0]["TranBHYT"].ToString()),
                    //TranBHTN = decimal.Parse(record.Rows[0]["TranBHTN"].ToString()),
                    NVBYXH = decimal.Parse(record.Rows[0]["NVBYXH"].ToString()),
                    NVBHYT = decimal.Parse(record.Rows[0]["NVBHYT"].ToString()),
                    NVBHTN = decimal.Parse(record.Rows[0]["NVBHTN"].ToString()),
                    DVBHXH = decimal.Parse(record.Rows[0]["DVBHXH"].ToString()),
                    DVBHYT = decimal.Parse(record.Rows[0]["DVBHYT"].ToString()),
                    DVBHTN = decimal.Parse(record.Rows[0]["DVBHTN"].ToString()),
                    UserID = int.Parse(record.Rows[0]["UserID"].ToString()),
                    DateCreate = DateTime.Parse(record.Rows[0]["DateCreate"].ToString()),
                    MaDonVi = record.Rows[0]["MaDonVi"].ToString(),
                };
                new BHMUCDONGBAOHIEMController().Insert(item);
            }
            GridPanel1.Reload();
            wdInputNewPrimaryKey.Hide();
        }
        catch (Exception ex)
        {
            Dialog.ShowError(ex.Message.ToString());
        }

    }

    [DirectMethod]
    public void DeleteRecord(string pr_key)
    {
        if (!string.IsNullOrEmpty(pr_key))
        {
            new BHMUCDONGBAOHIEMController().DeleteByPrkey(Convert.ToInt32(pr_key));
        }
        hdfRecordID.Text = "";
    }
    [DirectMethod]
    public void NhanDoiDuLieuTuTang()
    {
        //string pr_key = hdfRecordID.Text;
        //new BHMUCDONGBAOHIEMController().DuplucateByPrkey(pr_key);
    }

    [DirectMethod]
    public void ResetWindowTitle()
    {
        wdAddWindow.Icon = Icon.Add;
        wdAddWindow.Title = "Thêm mới quy định về mức đóng bảo hiểm";
        hdfCommand.SetValue("");
    }

    protected void btnEdit_Click(object sender, DirectEventArgs e)
    {
        int prkey = 0;
        if (!string.IsNullOrEmpty(hdfRecordID.Text))
        {
            prkey = Convert.ToInt32(hdfRecordID.Text);
        }
        DataTable record = new BHMUCDONGBAOHIEMController().GetByPrkey(prkey);
        if (record.Rows.Count > 0)
        {
            dfNgayHieuLuc.SelectedDate = DateTime.Parse(record.Rows[0]["NgayHieuLuc"].ToString());
            nfSanBHXH.Text = record.Rows[0]["SanBHXH"].ToString();
            //nfSanBHYT.Text = record.Rows[0]["SanBHYT"].ToString();
            //nfSanBHTN.Text = record.Rows[0]["SanBHTN"].ToString();
            nfTranBHXH.Text = record.Rows[0]["TranBHXH"].ToString();
            //nfTranBHYT.Text = record.Rows[0]["TranBHYT"].ToString();
            //nfTranBHTN.Text = record.Rows[0]["TranBHTN"].ToString();
            nfBHXHNhanVien.Text = record.Rows[0]["NVBYXH"].ToString();
            nfBHYTNhanVien.Text = record.Rows[0]["NVBHYT"].ToString();
            nfBHTNNhanVien.Text = record.Rows[0]["NVBHTN"].ToString();
            nfBHXHDonVi.Text = record.Rows[0]["DVBHXH"].ToString();
            nfBHYTDonVi.Text = record.Rows[0]["DVBHYT"].ToString();
            nfBHTNDonVi.Text = record.Rows[0]["DVBHTN"].ToString();
            hdfCommand.Text = "Update";
            wdAddWindow.Icon = Icon.Pencil;
            wdAddWindow.Title = "Sửa quy định về mức đóng bảo hiểm";
            wdAddWindow.Show();
        }
    }
}


text:
namespace jarvis
{
    partial class AddTaskDialog
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.label6 = new System.Windows.Forms.Label();
            this.cmbComplete = new System.Windows.Forms.ComboBox();
            this.label5 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.dtpTo = new System.Windows.Forms.DateTimePicker();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.txtDescn = new System.Windows.Forms.TextBox();
            this.dtpFrom = new System.Windows.Forms.DateTimePicker();
            this.cmbPriority = new System.Windows.Forms.ComboBox();
            this.cmbRecurring = new System.Windows.Forms.ComboBox();
            this.cmdOkay = new System.Windows.Forms.Button();
            this.cmdCancel = new System.Windows.Forms.Button();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // tableLayoutPanel1
            //
            this.tableLayoutPanel1.ColumnCount = 2;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Controls.Add(this.label6, 0, 5);
            this.tableLayoutPanel1.Controls.Add(this.cmbComplete, 1, 4);
            this.tableLayoutPanel1.Controls.Add(this.label5, 0, 4);
            this.tableLayoutPanel1.Controls.Add(this.label4, 0, 3);
            this.tableLayoutPanel1.Controls.Add(this.dtpTo, 1, 2);
            this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel1.Controls.Add(this.txtDescn, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.dtpFrom, 1, 1);
            this.tableLayoutPanel1.Controls.Add(this.cmbPriority, 1, 3);
            this.tableLayoutPanel1.Controls.Add(this.cmbRecurring, 1, 5);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 6;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
            this.tableLayoutPanel1.Size = new System.Drawing.Size(316, 166);
            this.tableLayoutPanel1.TabIndex = 0;
            //
            // label6
            //
            this.label6.AutoSize = true;
            this.label6.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label6.Location = new System.Drawing.Point(3, 135);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(76, 31);
            this.label6.TabIndex = 11;
            this.label6.Text = "Recurring";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // cmbComplete
            //
            this.cmbComplete.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cmbComplete.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbComplete.FormattingEnabled = true;
            this.cmbComplete.Items.AddRange(new object[] {
            "No",
            "Yes"});
            this.cmbComplete.Location = new System.Drawing.Point(85, 111);
            this.cmbComplete.Name = "cmbComplete";
            this.cmbComplete.Size = new System.Drawing.Size(228, 21);
            this.cmbComplete.TabIndex = 10;
            //
            // label5
            //
            this.label5.AutoSize = true;
            this.label5.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label5.Location = new System.Drawing.Point(3, 108);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(76, 27);
            this.label5.TabIndex = 9;
            this.label5.Text = "Complete";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label4.Location = new System.Drawing.Point(3, 81);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(76, 27);
            this.label4.TabIndex = 7;
            this.label4.Text = "Priority:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // dtpTo
            //
            this.dtpTo.CustomFormat = "yyyy-MM-dd hh:mm tt";
            this.dtpTo.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dtpTo.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.dtpTo.Location = new System.Drawing.Point(85, 57);
            this.dtpTo.Name = "dtpTo";
            this.dtpTo.Size = new System.Drawing.Size(228, 21);
            this.dtpTo.TabIndex = 6;
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label3.Location = new System.Drawing.Point(3, 54);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(76, 27);
            this.label3.TabIndex = 4;
            this.label3.Text = "To:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label2.Location = new System.Drawing.Point(3, 27);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(76, 27);
            this.label2.TabIndex = 2;
            this.label2.Text = "From:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(3, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(76, 27);
            this.label1.TabIndex = 0;
            this.label1.Text = "Description:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            //
            // txtDescn
            //
            this.txtDescn.Dock = System.Windows.Forms.DockStyle.Fill;
            this.txtDescn.Location = new System.Drawing.Point(85, 3);
            this.txtDescn.Name = "txtDescn";
            this.txtDescn.Size = new System.Drawing.Size(228, 21);
            this.txtDescn.TabIndex = 1;
            //
            // dtpFrom
            //
            this.dtpFrom.CustomFormat = "yyyy-MM-dd hh:mm tt";
            this.dtpFrom.Dock = System.Windows.Forms.DockStyle.Fill;
            this.dtpFrom.Format = System.Windows.Forms.DateTimePickerFormat.Custom;
            this.dtpFrom.Location = new System.Drawing.Point(85, 30);
            this.dtpFrom.Name = "dtpFrom";
            this.dtpFrom.Size = new System.Drawing.Size(228, 21);
            this.dtpFrom.TabIndex = 5;
            //
            // cmbPriority
            //
            this.cmbPriority.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cmbPriority.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbPriority.FormattingEnabled = true;
            this.cmbPriority.Items.AddRange(new object[] {
            "Standard",
            "Low",
            "High"});
            this.cmbPriority.Location = new System.Drawing.Point(85, 84);
            this.cmbPriority.Name = "cmbPriority";
            this.cmbPriority.Size = new System.Drawing.Size(228, 21);
            this.cmbPriority.TabIndex = 8;
            //
            // cmbRecurring
            //
            this.cmbRecurring.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cmbRecurring.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbRecurring.FormattingEnabled = true;
            this.cmbRecurring.Items.AddRange(new object[] {
            "None",
            "Daily",
            "Weekly",
            "Monthly"});
            this.cmbRecurring.Location = new System.Drawing.Point(85, 138);
            this.cmbRecurring.Name = "cmbRecurring";
            this.cmbRecurring.Size = new System.Drawing.Size(228, 21);
            this.cmbRecurring.TabIndex = 12;
            //
            // cmdOkay
            //
            this.cmdOkay.Location = new System.Drawing.Point(46, 172);
            this.cmdOkay.Name = "cmdOkay";
            this.cmdOkay.Size = new System.Drawing.Size(109, 22);
            this.cmdOkay.TabIndex = 9;
            this.cmdOkay.Text = "Okay";
            this.cmdOkay.UseVisualStyleBackColor = true;
            this.cmdOkay.Click += new System.EventHandler(this.cmdOkay_Click);
            //
            // cmdCancel
            //
            this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.cmdCancel.Location = new System.Drawing.Point(161, 172);
            this.cmdCancel.Name = "cmdCancel";
            this.cmdCancel.Size = new System.Drawing.Size(109, 22);
            this.cmdCancel.TabIndex = 10;
            this.cmdCancel.Text = "Cancel";
            this.cmdCancel.UseVisualStyleBackColor = true;
            this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
            //
            // AddTaskDialog
            //
            this.AcceptButton = this.cmdOkay;
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.CancelButton = this.cmdCancel;
            this.ClientSize = new System.Drawing.Size(316, 201);
            this.Controls.Add(this.cmdOkay);
            this.Controls.Add(this.cmdCancel);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.MaximizeBox = false;
            this.Name = "AddTaskDialog";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Task";
            this.Load += new System.EventHandler(this.AddTaskDialog_Load);
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox txtDescn;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.DateTimePicker dtpTo;
        private System.Windows.Forms.DateTimePicker dtpFrom;
        private System.Windows.Forms.Button cmdOkay;
        private System.Windows.Forms.Button cmdCancel;
        private System.Windows.Forms.ComboBox cmbComplete;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.ComboBox cmbPriority;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.ComboBox cmbRecurring;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package scala.pickling.test.issue50

import scala.pickling._, scala.pickling.Defaults._, json._
import org.scalatest.FunSuite

case class TestA(x: Option[Int])
case class TestB(x: Option[String])
class Simple(val x: (String, Int)) {}

class Issue50Test extends FunSuite {
  test("Issue #50") {
    val a = TestA(Some(1))
    val pa = a.pickle
    assert(pa.unpickle[TestA] == a)

    val b = TestB(Some("hello"))
    val pb = b.pickle
    assert(pb.unpickle[TestB] == b)
  }
}

class Issue50StackOverflowTest extends FunSuite {
  test("Issue #50 SO http://stackoverflow.com/questions/19413038/unpickler-for-class-with-tuple") {
    val s = new Simple(("test", 3))
    val simplePickled = s.pickle
    assert(simplePickled.unpickle[Simple].x == s.x)
  }
}


text:
Grove_Ultrasonic_Ranger
--------------------------------

[![Grove_Ultrasonic_Ranger](http://www.seeedstudio.com/wiki/images/thumb/3/3a/Ultrasonic_Ranger.jpg/300px-Ultrasonic_Ranger.jpg)](http://www.seeedstudio.com/depot/grove-ultrasonic-ranger-p-960.html?cPath=144_149)

This Grove - ultrasonic sensor is a non-contact distance measurement module which works at 42KHz, suitable for projects that require middle distance measurement.

**Note:**

This library is used for Seeed graphical programming Project only.

**Library Name**:Grove_Ultrasonic_Ranger

**API**
---

	/*
	 * Function Name: UltrasonicRangerRead
	 * Input: PinName, pin to connect
	 * Return: distance in cm
	 */
	int UltrasonicRangerRead(int PinName);

Test Case
---

	Get data from then sensor per 100ms, and print to Serial monitor.
	// test for seeed graphical programming project
	// loovee @ 2015-8-4

	#include "Ultrasonic.h"

	Ultrasonic ultrasonic;
	const int pin = 2;          // ultrasonic connect to D2

	void setup()
	{
	    Serial.begin(115200);
	    Serial.println("test for Seeed Graphical programming project");
	    Serial.println("Ultrasonic");
	}

	void loop()
	{
	    int dist_cm = ultrasonic.UltrasonicRangerRead(pin);         // read data from ultrasonic ranger
	    Serial.println(dist_cm);                                    // display it
	    delay(100);
	}

----

This software is written by Loovee for for [Seeed Technology Inc.](http://www.seeed.cc) and is licensed under [The MIT License](http://opensource.org/licenses/mit-license.php). Check License.txt/LICENSE for the details of MIT license.

Contributing to this software is warmly welcomed. You can do this basically by

[forking](https://help.github.com/articles/fork-a-repo), committing modifications and then [pulling requests](https://help.github.com/articles/using-pull-requests) (follow the links above

for operating guide). Adding change log and your contact into file header is encouraged.

Thanks for your contribution.

Seeed is a hardware innovation platform for makers to grow inspirations into differentiating products. By working closely with technology providers of all scale, Seeed provides accessible technologies with quality, speed and supply chain knowledge. When prototypes are ready to iterate, Seeed helps productize 1 to 1,000 pcs using in-house engineering, supply chain management and agile manufacture forces. Seeed also team up with incubators, Chinese tech ecosystem, investors and distribution channels to portal Maker startups beyond.

[![Analytics](https://ga-beacon.appspot.com/UA-46589105-3/Grove_Ultrasonic_Ranger)](https://github.com/igrigorik/ga-beacon)


text:
<?php

/*
 * Use it typing
 *
 * php app/console doctrine:fixtures:load
 *
 *
 *
 * Type
 *
 * php app/console doctrine:database:create
 *
 * to create database
 *
 *
 *
 * Type
 *
 * php app/console doctrine:schema:update --force
 *
 * to update database
 */

namespace AppBundle\DataFixtures\ORM;

use DateTime;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use AppBundle\Entity\Vendor;
use AppBundle\Entity\Slide;
use FOS\UserBundle\Model\UserManager;
use AppBundle\Entity\User;
use AppBundle\Entity\Role;

class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
    /** @var ContainerInterface */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        /** @var EntityManager $manager */
        $manager = $this->container->get('doctrine')->getManager();

        /* inserting vendors */
        $aperio = new Vendor();
        $aperio->setName("Aperio");
        $aperio->setFileExtension("svs");
        $manager->persist($aperio);

        $vendor = new Vendor();
        $vendor->setName("Aperio");
        $vendor->setFileExtension("tif");
        $manager->persist($vendor);

        $vendor->setName("Aperio");
        $vendor->setFileExtension("tiff");
        $manager->persist($vendor);

        $vendor->setName("Hamamatsu");
        $vendor->setFileExtension("vms");
        $manager->persist($vendor);

        $vendor->setName("Hamamatsu");
        $vendor->setFileExtension("vmu");
        $manager->persist($vendor);

        $vendor->setName("Hamamatsu");
        $vendor->setFileExtension("ndpi");
        $manager->persist($vendor);

        $vendor->setName("Leica");
        $vendor->setFileExtension("scn");
        $manager->persist($vendor);

        $vendor->setName("MIRAX");
        $vendor->setFileExtension("mrxs");
        $manager->persist($vendor);

        $vendor->setName("Philips");
        $vendor->setFileExtension("tiff");
        $manager->persist($vendor);

        $vendor->setName("Sakura");
        $vendor->setFileExtension("svslide");
        $manager->persist($vendor);

        $vendor->setName("Trestle");
        $vendor->setFileExtension("tif");
        $manager->persist($vendor);

        $vendor->setName("Ventana");
        $vendor->setFileExtension("bif");
        $manager->persist($vendor);

        $vendor->setName("Ventana");
        $vendor->setFileExtension("tif");
        $manager->persist($vendor);

        $vendor->setName("Generic tiled TIFF");
        $vendor->setFileExtension("tif");
        $manager->persist($vendor);

        $vendor->setName("Generic tiled TIFF");
        $vendor->setFileExtension("tiff");
        $manager->persist($vendor);

        /* Inserting slides */
        $slide = new Slide();
        $slide->setName('JP2K-33003-1');
        $slide->setDescription('JP2K-33003-1');
        $slide->setDateCreation(new DateTime(date('Y-m-d H:i:s')));
        $slide->setWidth(15374);
        $slide->setHeight(17497);
        $slide->setTileDim(256);
        $slide->setVendor($aperio);
        $slide->setNotes('Info collected from http://openslide.org/demo/');
        $manager->persist($slide);

        $slide = new Slide();
        $slide->setName('CMU-1');
        $slide->setDescription('CMU-1');
        $slide->setDateCreation(new DateTime(date('Y-m-d H:i:s')));
        $slide->setWidth(46000);
        $slide->setHeight(32914);
        $slide->setTileDim(256);
        $slide->setVendor($aperio);
        $slide->setNotes('Info collected from http://openslide.org/demo/');
        $manager->persist($slide);

        $slide = new Slide();
        $slide->setName('CMU-1-Small-Region');
        $slide->setDescription('CMU-1-Small-Region');
        $slide->setDateCreation(new DateTime(date('Y-m-d H:i:s')));
        $slide->setWidth(2220);
        $slide->setHeight(2967);
        $slide->setTileDim(256);
        $slide->setVendor($aperio);
        $slide->setNotes('Info collected from http://openslide.org/demo/');
        $manager->persist($slide);

        /* Inserting users */

        /** @var UserManager $fosUserManager */
        $fosUserManager = $this->container->get('fos_user.user_manager');

        /** @var User $user */
        $user = $fosUserManager->createUser();
        $user->setUsername('admin');
        $user->setPlainPassword('password');
        $user->setEmail('admin@mail.com');
        $user->setEnabled(true);
        $user->addRole('ROLE_ADMIN');

        $fosUserManager->updateUser($user);

        for ($i = 1; $i <= 20; $i++) {
            $user = $fosUserManager->createUser();
            $user->setUsername('paolo.rossi.' . $i);
            $user->setPlainPassword('password');
            $user->setEmail('paolo.rossi.' . $i . '@mail.com');
            $user->setEnabled($i % 2);

            $fosUserManager->updateUser($user);
        }

        /* inserting roles */

        /** @var Role $role */
        $role = new Role();
        $role->setName('admin');
        $role->setRole('ROLE_ADMIN');
        $manager->persist($role);

        $role = new Role();
        $role->setName('user');
        $role->setRole('ROLE_USER');
        $manager->persist($role);

        /* flushing all... */
        $manager->flush();
    }
}


text:
/*
 * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cmd

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
	"time"

	"github.com/fatih/color"
	"github.com/minio/cli"
)

// Check for new software updates.
var updateCmd = cli.Command{
	Name:   "update",
	Usage:  "Check for a new software update.",
	Action: mainUpdate,
	Flags: []cli.Flag{
		cli.BoolFlag{
			Name:  "quiet",
			Usage: "Disable any update messages.",
		},
	},
	CustomHelpTemplate: `Name:
   {{.HelpName}} - {{.Usage}}

USAGE:
   {{.HelpName}}{{if .VisibleFlags}} [FLAGS]{{end}}
{{if .VisibleFlags}}
FLAGS:
  {{range .VisibleFlags}}{{.}}
  {{end}}{{end}}
EXIT STATUS:
   0 - You are already running the most recent version.
   1 - New update is available.
  -1 - Error in getting update information.

EXAMPLES:
   1. Check if there is a new update available:
       $ {{.HelpName}}
`,
}

const (
	minioReleaseTagTimeLayout = "2006-01-02T15-04-05Z"
	minioReleaseURL           = "https://dl.minio.io/server/minio/release/" + runtime.GOOS + "-" + runtime.GOARCH + "/"
)

func getCurrentReleaseTime(minioVersion, minioBinaryPath string) (releaseTime time.Time, err error) {
	if releaseTime, err = time.Parse(time.RFC3339, minioVersion); err == nil {
		return releaseTime, err
	}

	if !filepath.IsAbs(minioBinaryPath) {
		// Make sure to look for the absolute path of the binary.
		minioBinaryPath, err = exec.LookPath(minioBinaryPath)
		if err != nil {
			return releaseTime, err
		}
	}

	// Looks like version is minio non-standard, we use minio binary's ModTime as release time.
	fi, err := osStat(minioBinaryPath)
	if err != nil {
		err = fmt.Errorf("Unable to get ModTime of %s. %s", minioBinaryPath, err)
	} else {
		releaseTime = fi.ModTime().UTC()
	}

	return releaseTime, err
}

// GetCurrentReleaseTime - returns this process's release time.  If it is official minio version,
// parsed version is returned else minio binary's mod time is returned.
func GetCurrentReleaseTime() (releaseTime time.Time, err error) {
	return getCurrentReleaseTime(Version, os.Args[0])
}

// Check if we are indeed inside docker.
// https://github.com/moby/moby/blob/master/daemon/initlayer/setup_unix.go#L25
//
//     "/.dockerenv":      "file",
//
func isDocker(dockerEnvFile string) (ok bool, err error) {
	_, err = os.Stat(dockerEnvFile)
	if err != nil {
		if os.IsNotExist(err) {
			err = nil
		}
		return false, err
	}
	return true, nil
}

// IsDocker - returns if the environment minio is running
// is docker or not.
func IsDocker() bool {
	found, err := isDocker("/.dockerenv")
	// We don't need to fail for this check, log
	// an error and return false.
	errorIf(err, "Error in docker check.")

	return found
}

// IsDCOS returns true if minio is running in DCOS.
func IsDCOS() bool {
	// http://mesos.apache.org/documentation/latest/docker-containerizer/
	// Mesos docker containerizer sets this value
	return os.Getenv("MESOS_CONTAINER_NAME") != ""
}

// IsKubernetes returns true if minio is running in kubernetes.
func IsKubernetes() bool {
	// Kubernetes env used to validate if we are
	// indeed running inside a kubernetes pod
	// is KUBERNETES_SERVICE_HOST but in future
	// we might need to enhance this.
	return os.Getenv("KUBERNETES_SERVICE_HOST") != ""
}

func isSourceBuild(minioVersion string) bool {
	_, err := time.Parse(time.RFC3339, minioVersion)
	return err != nil
}

// IsSourceBuild - returns if this binary is made from source or not.
func IsSourceBuild() bool {
	return isSourceBuild(Version)
}

// DO NOT CHANGE USER AGENT STYLE.
// The style should be
//
//   Minio (<OS>; <ARCH>[; dcos][; kubernetes][; docker][; source]) Minio/<VERSION> Minio/<RELEASE-TAG> Minio/<COMMIT-ID> [Minio/univers-<PACKAGE_NAME>]
//
// For any change here should be discussed by openning an issue at https://github.com/minio/minio/issues.
func getUserAgent(mode string) string {
	userAgent := "Minio (" + runtime.GOOS + "; " + runtime.GOARCH
	if mode != "" {
		userAgent += "; " + mode
	}
	if IsDCOS() {
		userAgent += "; dcos"
	}
	if IsKubernetes() {
		userAgent += "; kubernetes"
	}
	if IsDocker() {
		userAgent += "; docker"
	}
	if IsSourceBuild() {
		userAgent += "; source"
	}

	userAgent += ") Minio/" + Version + " Minio/" + ReleaseTag + " Minio/" + CommitID
	if IsDCOS() {
		universePkgVersion := os.Getenv("MARATHON_APP_LABEL_DCOS_PACKAGE_VERSION")
		// On DC/OS environment try to the get universe package version.
		if universePkgVersion != "" {
			userAgent += " Minio/" + "universe-" + universePkgVersion
		}
	}
	return userAgent
}

func downloadReleaseData(releaseChecksumURL string, timeout time.Duration, mode string) (data string, err error) {
	req, err := http.NewRequest("GET", releaseChecksumURL, nil)
	if err != nil {
		return data, err
	}
	req.Header.Set("User-Agent", getUserAgent(mode))

	client := &http.Client{
		Timeout: timeout,
		Transport: &http.Transport{
			// need to close connection after usage.
			DisableKeepAlives: true,
		},
	}

	resp, err := client.Do(req)
	if err != nil {
		return data, err
	}
	if resp == nil {
		return data, fmt.Errorf("No response from server to download URL %s", releaseChecksumURL)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return data, fmt.Errorf("Error downloading URL %s. Response: %v", releaseChecksumURL, resp.Status)
	}
	dataBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return data, fmt.Errorf("Error reading response. %s", err)
	}

	data = string(dataBytes)
	return data, err
}

// DownloadReleaseData - downloads release data from minio official server.
func DownloadReleaseData(timeout time.Duration, mode string) (data string, err error) {
	data, err = downloadReleaseData(minioReleaseURL+"minio.shasum", timeout, mode)
	if err == nil {
		return data, nil
	}
	return downloadReleaseData(minioReleaseURL+"minio.sha256sum", timeout, mode)
}

func parseReleaseData(data string) (releaseTime time.Time, err error) {
	fields := strings.Fields(data)
	if len(fields) != 2 {
		err = fmt.Errorf("Unknown release data `%s`", data)
		return releaseTime, err
	}

	releaseInfo := fields[1]
	if fields = strings.Split(releaseInfo, "."); len(fields) != 3 {
		err = fmt.Errorf("Unknown release information `%s`", releaseInfo)
		return releaseTime, err
	}

	if !(fields[0] == "minio" && fields[1] == "RELEASE") {
		err = fmt.Errorf("Unknown release '%s'", releaseInfo)
		return releaseTime, err
	}

	releaseTime, err = time.Parse(minioReleaseTagTimeLayout, fields[2])
	if err != nil {
		err = fmt.Errorf("Unknown release time format. %s", err)
	}

	return releaseTime, err
}

func getLatestReleaseTime(timeout time.Duration, mode string) (releaseTime time.Time, err error) {
	data, err := DownloadReleaseData(timeout, mode)
	if err != nil {
		return releaseTime, err
	}

	return parseReleaseData(data)
}

const (
	// Kubernetes deployment doc link.
	kubernetesDeploymentDoc = "https://docs.minio.io/docs/deploy-minio-on-kubernetes"

	// Mesos deployment doc link.
	mesosDeploymentDoc = "https://docs.minio.io/docs/deploy-minio-on-dc-os"
)

func getDownloadURL(buildDate time.Time) (downloadURL string) {
	// Check if we are in DCOS environment, return
	// deployment guide for update procedures.
	if IsDCOS() {
		return mesosDeploymentDoc
	}

	// Check if we are in kubernetes environment, return
	// deployment guide for update procedures.
	if IsKubernetes() {
		return kubernetesDeploymentDoc
	}

	// Check if we are docker environment, return docker update command
	if IsDocker() {
		// Construct release tag name.
		rTag := "RELEASE." + buildDate.Format(minioReleaseTagTimeLayout)
		return fmt.Sprintf("docker pull minio/minio:%s", rTag)
	}

	// For binary only installations, then we just show binary download link.
	if runtime.GOOS == "windows" {
		return minioReleaseURL + "minio.exe"
	}

	return minioReleaseURL + "minio"
}

func getUpdateInfo(timeout time.Duration, mode string) (older time.Duration,
	downloadURL string, err error) {

	var currentReleaseTime, latestReleaseTime time.Time
	currentReleaseTime, err = GetCurrentReleaseTime()
	if err != nil {
		return older, downloadURL, err
	}

	latestReleaseTime, err = getLatestReleaseTime(timeout, mode)
	if err != nil {
		return older, downloadURL, err
	}

	if latestReleaseTime.After(currentReleaseTime) {
		older = latestReleaseTime.Sub(currentReleaseTime)
		downloadURL = getDownloadURL(latestReleaseTime)
	}

	return older, downloadURL, nil
}

func mainUpdate(ctx *cli.Context) {
	if len(ctx.Args()) != 0 {
		cli.ShowCommandHelpAndExit(ctx, "update", -1)
	}

	quiet := ctx.Bool("quiet") || ctx.GlobalBool("quiet")
	if quiet {
		log.EnableQuiet()
	}

	minioMode := ""
	older, downloadURL, err := getUpdateInfo(10*time.Second, minioMode)
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	if updateMsg := computeUpdateMessage(downloadURL, older); updateMsg != "" {
		log.Println(updateMsg)
		os.Exit(1)
	}

	colorSprintf := color.New(color.FgGreen, color.Bold).SprintfFunc()
	log.Println(colorSprintf("You are already running the most recent version of 'minio'."))
	os.Exit(0)
}


text:
asyncio demo
============

A sample project for asyncio talk given at PYWeb-IL 52.

- `src/data_poller_client.py` - Getting data from `/dev/random As a Service`_.
- `src/server.py` - Subscribes to db changes and updates clients via web sockects.

Featuring:

- aiohttp_
- RethinkDB_
-

.. _aiohttp: http://pythonhosted.org/aiohttp/index.html
.. _RethinkDB: https://rethinkdb.com/
.. _/dev/random As a Service: http://phoeagon.github.io/dev-random-as-a-service/

License
-------

MIT


text:
import os
import shutil
from unittest import mock

# 3rd party libs
from hpOneView.exceptions import HPOneViewException

# Own libs
from oneview_redfish_toolkit.api.errors import OneViewRedfishException
from oneview_redfish_toolkit.api import scmb
from oneview_redfish_toolkit.api.scmb import SCMB
from oneview_redfish_toolkit import client_session
from oneview_redfish_toolkit.tests.base_test import BaseTest
from oneview_redfish_toolkit import util

class TestSCMB(BaseTest):
    """Tests for SCMB module"""
    def setUp(self):
        scmb.init_map_scmb_connections()

    @mock.patch.object(SCMB, '_is_cert_working_with_scmb')
    @mock.patch.object(scmb, 'config')
    @mock.patch('os.path.isfile')
    def test_check_cert_exist(self, isfile, config_mock,
                              _is_cert_working_with_scmb):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': ''
            }
        }

        # Files exist
        isfile.return_value = True
        _is_cert_working_with_scmb.return_value = True

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        self.assertTrue(scmb_thread._has_valid_certificates())

        # Certs files don't exist
        isfile.return_value = False
        _is_cert_working_with_scmb.return_value = False
        self.assertFalse(scmb_thread._has_valid_certificates())
        self.assertFalse(scmb_thread._has_valid_certificates())

    @mock.patch.object(scmb, 'config')
    def test_paths_generated_for_scmb_files(self, config_mock):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': '/dir/cert_file.crt'
            }
        }
        ov_ip = '1.1.1.1'
        self.assertEqual('/dir/scmb/1.1.1.1/oneview_ca.pem',
                         scmb._oneview_ca_path(ov_ip))
        self.assertEqual('/dir/scmb/1.1.1.1/oneview_scmb.pem',
                         scmb._scmb_cert_path(ov_ip))
        self.assertEqual('/dir/scmb/1.1.1.1/oneview_scmb.key',
                         scmb._scmb_key_path(ov_ip))

    @mock.patch.object(scmb, 'config')
    @mock.patch.object(scmb, 'logging')
    def test_check_cert_exist_when_config_key_is_missing(self,
                                                         logging_mock,
                                                         config_mock):
        config_mock.get_config.return_value = {
            'ssl': {}
        }

        with self.assertRaises(KeyError) as error:
            scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
            scmb_thread._has_valid_certificates()

        logging_mock.error.assert_called_with(
            'Invalid configuration for ssl cert. '
            'Verify the [ssl] section in config file')

        self.assertEqual("'SSLCertFile'", str(error.exception))

    @mock.patch.object(SCMB, '_is_cert_working_with_scmb')
    @mock.patch.object(scmb, 'config')
    @mock.patch.object(client_session, 'get_oneview_client')
    @mock.patch.object(SCMB, '_get_ov_ca_cert_base64data')
    def test_get_cert_already_exists(self,
                                     _get_ov_ca_cert_base64data,
                                     get_oneview_client,
                                     config_mock,
                                     _is_cert_working_with_scmb):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': 'cert_file.crt'
            }
        }

        os.makedirs(name='scmb', exist_ok=True)
        self.addCleanup(shutil.rmtree, 'scmb')

        # Certs Generated with success
        oneview_client = mock.MagicMock()
        oneview_client.certificate_authority.get.return_value = "CA CERT"
        oneview_client.certificate_rabbitmq.generate.return_value = True
        oneview_client.certificate_rabbitmq.get_key_pair.return_value = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'}
        get_oneview_client.return_value = oneview_client
        _is_cert_working_with_scmb.return_value = True

        # Certs already exist
        e = HPOneViewException({
            'errorCode': 'RABBITMQ_CLIENTCERT_CONFLICT',
            'message': 'certs already exist',
        })
        oneview_client.certificate_rabbitmq.generate.side_effect = e

        oneview_client.connection = 'con'
        _get_ov_ca_cert_base64data.return_value = "CA CERT"

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.get_scmb_certs()
        self.assertTrue(scmb_thread._has_valid_certificates())

    @mock.patch('pika.BlockingConnection')
    @mock.patch('pika.ConnectionParameters')
    @mock.patch('pika.credentials.ExternalCredentials')
    def test_scmb_connect(self, blk_conn, conn_params, ext_cred):
        blk_conn.return_value = {}
        conn_params.return_value = {}
        ext_cred.return_value = {}
        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        self.assertEqual(scmb_thread.scmb_connect(), {})

    @mock.patch.object(util, 'dispatch_event')
    def test_consume_message(self, dispatch_mock):
        with open(
            'oneview_redfish_toolkit/mockups/oneview/Alert.json'
        ) as f:
            event_mockup = f.read().encode('UTF-8')

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.consume_message(None, None, None, event_mockup)

        self.assertTrue(dispatch_mock.called)

    @mock.patch.object(SCMB, '_get_ov_ca_cert')
    @mock.patch.object(scmb, 'config')
    @mock.patch.object(SCMB, '_is_cert_working_with_scmb')
    @mock.patch.object(client_session, 'get_oneview_client')
    def test_generate_new_cert_for_oneview(self,
                                           get_oneview_client,
                                           _is_cert_working_with_scmb,
                                           config_mock,
                                           _get_ov_ca_cert
                                           ):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': 'cert_file.crt'
            }
        }

        cert_key_pair = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'
        }

        # Certs Generated with success
        oneview_client = mock.MagicMock()
        e = HPOneViewException({
            'errorCode': 'RESOURCE_NOT_FOUND',
            'message': 'Resource not found.',
        })

        oneview_client.certificate_authority.get.return_value = "CA CERT"
        oneview_client.certificate_rabbitmq.generate.return_value = True
        oneview_client.certificate_rabbitmq.get_key_pair.side_effect = \
            [e, cert_key_pair]
        get_oneview_client.return_value = oneview_client
        _is_cert_working_with_scmb.return_value = True

        _get_ov_ca_cert.return_value = {
            'type': 'CAInfo',
            'members': [
                {
                    'certificateDetails': {
                        'base64Data': 'CA CERT'
                        }
                    }
                ]
            }
        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.get_scmb_certs()
        self.assertTrue(scmb_thread._has_valid_certificates())

        # Return None if cert is not a dict
        _get_ov_ca_cert.return_value = []
        cert = scmb_thread._get_ov_ca_cert_base64data(oneview_client)
        self.assertEqual(cert, None)

    @mock.patch.object(scmb, 'config')
    @mock.patch.object(client_session, 'get_oneview_client')
    @mock.patch.object(SCMB, '_get_ov_ca_cert_base64data')
    @mock.patch.object(scmb, 'ResourceClient')
    @mock.patch.object(SCMB, 'scmb_connect')
    def test_get_oneview_cert_unexpected_error(self,
                                               scmb_connect,
                                               resource_client,
                                               _get_ov_ca_cert_base64data,
                                               get_oneview_client,
                                               config_mock):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': 'cert_file.crt'
            }
        }

        # Certs Generated with success
        oneview_client = mock.MagicMock()
        e = HPOneViewException({
            'errorCode': 'UNEXPECTED ERROR',
            'message': 'Unexpected error.',
        })
        hp_ov_exception_msg = "Unexpected error."

        oneview_client.certificate_authority.get.return_value = "CA CERT"
        oneview_client.certificate_rabbitmq.generate.return_value = True
        oneview_client.certificate_rabbitmq.get_key_pair.side_effect = e
        get_oneview_client.return_value = oneview_client

        oneview_client.connection = 'con'
        _get_ov_ca_cert_base64data.return_value = "CA CERT"

        with self.assertRaises(HPOneViewException) as hp_exception:
            scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
            scmb_thread.get_scmb_certs()

        test_exception = hp_exception.exception
        self.assertEqual(hp_ov_exception_msg, test_exception.msg)
        self.assertEqual(e.oneview_response, test_exception.oneview_response)

        scmb_connect.side_effect = e

        scmb_thread._listen_scmb()

        # test get certificate exception
        _get_ov_ca_cert_base64data.return_value = None

        with self.assertRaises(OneViewRedfishException) as redfish_exception:
            scmb_thread.get_scmb_certs()

        test_exception = redfish_exception.exception.msg
        self.assertEqual(test_exception,
                         "Failed to fetch OneView CA Certificate")

        e = HPOneViewException({
            'errorCode': 'RABBITMQ_CLIENTCERT_CONFLICT',
            'message': 'RABBITMQ_CLIENTCERT_CONFLICT',
        })
        oneview_client.certificate_rabbitmq.generate.side_effect = e
        scmb_thread._generate_certificate_in_oneview(oneview_client)

        resource_client.get.return_value = "Cert"

        scmb_thread._get_ov_ca_cert(oneview_client)

        # test certificate generation exception
        e = HPOneViewException({
            'errorCode': 'NOT_FOUND',
            'message': 'NOT_FOUND',
        })
        oneview_client.certificate_rabbitmq.generate.side_effect = e
        with self.assertRaises(HPOneViewException) as hp_exception:
            scmb_thread._generate_certificate_in_oneview(oneview_client)

        test_exception = hp_exception.exception.msg
        self.assertEqual(test_exception,
                         "NOT_FOUND")

    @mock.patch('pika.channel.Channel')
    @mock.patch('pika.BlockingConnection')
    @mock.patch('pika.ConnectionParameters')
    @mock.patch.object(scmb, 'config')
    @mock.patch.object(client_session, 'get_oneview_client')
    @mock.patch.object(SCMB, '_get_ov_ca_cert_base64data')
    def test_init_event_service_with_valid_certificate(self,
                                                       _get_ov_ca_cert,
                                                       get_oneview_client,
                                                       config_mock, conn_param,
                                                       block_conn, channel):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': 'cert_file.crt'
            },
        }

        os.makedirs(name='scmb', exist_ok=True)
        self.addCleanup(shutil.rmtree, 'scmb')

        oneview_client = mock.MagicMock()
        oneview_client.certificate_authority.get.return_value = "CA CERT"
        oneview_client.certificate_rabbitmq.generate.return_value = True
        get_oneview_client.return_value = oneview_client
        oneview_client.certificate_rabbitmq.get_key_pair.return_value = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'}

        oneview_client.connection = 'con'
        _get_ov_ca_cert.return_value = "CA CERT"

        pika_mock = mock.MagicMock()
        pika_mock.channel.Channel = {}
        block_conn.return_value = pika_mock
        conn_param.return_value = {}
        channel.return_value = {}

        scmb.init_event_service()

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.run()
        self.assertTrue(scmb_thread._has_valid_certificates())
        self.assertTrue(scmb_thread._is_cert_working_with_scmb())

    @mock.patch('pika.channel.Channel')
    @mock.patch('pika.BlockingConnection')
    @mock.patch('pika.ConnectionParameters')
    @mock.patch.object(SCMB, '_has_scmb_certificates_path')
    @mock.patch.object(client_session, 'get_oneview_client')
    @mock.patch.object(scmb, 'config')
    def test_init_event_service_with_certs_already_generated(self, config_mock,
                                                             get_ov_client,
                                                             _has_certs_path,
                                                             conn_param,
                                                             block_conn,
                                                             channel):
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': '/dir/cert_file.crt'
            },
        }

        pika_mock = mock.MagicMock()
        pika_mock.channel.Channel = {}
        block_conn.return_value = pika_mock
        conn_param.return_value = {}
        channel.return_value = {}
        oneview_client = mock.MagicMock()
        get_ov_client.return_value = oneview_client
        _has_certs_path.return_value = True

        scmb.init_event_service()

        scmb_thread = SCMB('1.1.1.1', 'cred', 'token')
        scmb_thread.run()

        self.assertTrue(scmb_thread._has_valid_certificates())

    @mock.patch.object(SCMB, '_get_ov_ca_cert_base64data')
    @mock.patch.object(client_session, 'get_oneview_client')
    @mock.patch.object(scmb, '_get_map_scmb_connections')
    @mock.patch.object(scmb, 'config')
    def test_is_cert_working_with_scmb_failed_case(self, config_mock,
                                                   get_map_scmb_connections,
                                                   get_oneview_client,
                                                   _get_ov_ca_cert_base64data):
        config_mock.get_authentication_mode.return_value = 'session'
        config_mock.get_oneview_multiple_ips.return_value = ['1.1.1.1']
        config_mock.get_config.return_value = {
            'ssl': {
                'SSLCertFile': '/dir/cert_file.crt'
            },
        }

        oneview_client = mock.MagicMock()
        get_oneview_client.return_value = oneview_client
        oneview_client.certificate_rabbitmq.get_key_pair.return_value = {
            'base64SSLCertData': 'Client CERT',
            'base64SSLKeyData': 'Client Key'}

        oneview_client.connection = 'con'
        _get_ov_ca_cert_base64data.return_value = "CA CERT"
        get_map_scmb_connections.return_value = []

        scmb.init_event_service()

        scmb_thread = SCMB('2.2.2.2', 'cred', 'token')

        self.assertFalse(scmb_thread._is_cert_working_with_scmb())


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<wicket:panel>
	<input type="text" wicket:id="grade" tabindex="-1"/>

<wicket:message key="grade.option.viewlog" />

View / Edit Comments

</wicket:panel>


text:
<?php
namespace ubud\assets;

use yii\web\AssetBundle;
use yii\web\View;

class AngularAsset extends AssetBundle
{
    public $sourcePath = '@bower';
    public $js = [
        'angular/angular.js',
        'angular-route/angular-route.js',
        'angular-strap/dist/angular-strap.js',
    ];
    //public $jsOptions = [
    //    'position' => View::POS_HEAD,
    //];
}


text:
package kafka.log

import kafka.server.{KafkaConfig, ThrottledReplicaListValidator}
import kafka.utils.TestUtils
import org.apache.kafka.common.config.ConfigDef.Importance.MEDIUM
import org.apache.kafka.common.config.ConfigDef.Type.INT
import org.apache.kafka.common.config.{ConfigException, TopicConfig}
import org.junit.jupiter.api.Assertions._
import org.junit.jupiter.api.Test

import java.util.{Collections, Properties}

class LogConfigTest {

  /**
   * This test verifies that KafkaConfig object initialization does not depend on
   * LogConfig initialization. Bad things happen due to static initialization
   * order dependencies. For example, LogConfig.configDef ends up adding null
   * values in serverDefaultConfigNames. This test ensures that the mapping of
   * keys from LogConfig to KafkaConfig are not missing values.
   */
  @Test
  def ensureNoStaticInitializationOrderDependency(): Unit = {
    // Access any KafkaConfig val to load KafkaConfig object before LogConfig.
    assertNotNull(KafkaConfig.LogRetentionTimeMillisProp)
    assertTrue(LogConfig.configNames.forall { config =>
      val serverConfigOpt = LogConfig.serverConfigName(config)
      serverConfigOpt.isDefined && (serverConfigOpt.get != null)
    })
  }

  @Test
  def testKafkaConfigToProps(): Unit = {
    val millisInHour = 60L * 60L * 1000L
    val kafkaProps = TestUtils.createBrokerConfig(nodeId = 0, zkConnect = "")
    kafkaProps.put(KafkaConfig.LogRollTimeHoursProp, "2")
    kafkaProps.put(KafkaConfig.LogRollTimeJitterHoursProp, "2")
    kafkaProps.put(KafkaConfig.LogRetentionTimeHoursProp, "2")

    val kafkaConfig = KafkaConfig.fromProps(kafkaProps)
    val logProps = LogConfig.extractLogConfigMap(kafkaConfig)
    assertEquals(2 * millisInHour, logProps.get(LogConfig.SegmentMsProp))
    assertEquals(2 * millisInHour, logProps.get(LogConfig.SegmentJitterMsProp))
    assertEquals(2 * millisInHour, logProps.get(LogConfig.RetentionMsProp))
  }

  @Test
  def testFromPropsEmpty(): Unit = {
    val p = new Properties()
    val config = LogConfig(p)
    assertEquals(LogConfig(), config)
  }

  @Test
  def testFromPropsInvalid(): Unit = {
    LogConfig.configNames.foreach(name => name match {
      case LogConfig.UncleanLeaderElectionEnableProp => assertPropertyInvalid(name, "not a boolean")
      case LogConfig.RetentionBytesProp => assertPropertyInvalid(name, "not_a_number")
      case LogConfig.RetentionMsProp => assertPropertyInvalid(name, "not_a_number" )
      case LogConfig.CleanupPolicyProp => assertPropertyInvalid(name, "true", "foobar")
      case LogConfig.MinCleanableDirtyRatioProp => assertPropertyInvalid(name, "not_a_number", "-0.1", "1.2")
      case LogConfig.MinInSyncReplicasProp => assertPropertyInvalid(name, "not_a_number", "0", "-1")
      case LogConfig.MessageFormatVersionProp => assertPropertyInvalid(name, "")
      case _ => assertPropertyInvalid(name, "not_a_number", "-1")
    })
  }

  @Test
  def testInvalidCompactionLagConfig(): Unit = {
    val props = new Properties
    props.setProperty(LogConfig.MaxCompactionLagMsProp, "100")
    props.setProperty(LogConfig.MinCompactionLagMsProp, "200")
    assertThrows(classOf[Exception], () => LogConfig.validate(props))
  }

  @Test
  def shouldValidateThrottledReplicasConfig(): Unit = {
    assertTrue(isValid("*"))
    assertTrue(isValid("* "))
    assertTrue(isValid(""))
    assertTrue(isValid(" "))
    assertTrue(isValid("100:10"))
    assertTrue(isValid("100:10,12:10"))
    assertTrue(isValid("100:10,12:10,15:1"))
    assertTrue(isValid("100:10,12:10,15:1  "))
    assertTrue(isValid("100:0,"))

    assertFalse(isValid("100"))
    assertFalse(isValid("100:"))
    assertFalse(isValid("100:0,10"))
    assertFalse(isValid("100:0,10:"))
    assertFalse(isValid("100:0,10:   "))
    assertFalse(isValid("100 :0,10:   "))
    assertFalse(isValid("100: 0,10:   "))
    assertFalse(isValid("100:0,10 :   "))
    assertFalse(isValid("*,100:10"))
    assertFalse(isValid("* ,100:10"))
  }

  /* Sanity check that toHtmlTable produces one of the expected configs */
  @Test
  def testToHtmlTable(): Unit = {
    val html = LogConfig.configDefCopy.toHtmlTable
    val expectedConfig = "file.delete.delay.ms	"
    assertTrue(html.contains(expectedConfig), s"Could not find `$expectedConfig` in:\n $html")
  }

  /* Sanity check that toHtml produces one of the expected configs */
  @Test
  def testToHtml(): Unit = {
    val html = LogConfig.configDefCopy.toHtml(4, (key: String) => "prefix_" + key, Collections.emptyMap())
    val expectedConfig = "
file.delete.delay.ms
"
    assertTrue(html.contains(expectedConfig), s"Could not find `$expectedConfig` in:\n $html")
  }

  /* Sanity check that toEnrichedRst produces one of the expected configs */
  @Test
  def testToEnrichedRst(): Unit = {
    val rst = LogConfig.configDefCopy.toEnrichedRst
    val expectedConfig = "``file.delete.delay.ms``"
    assertTrue(rst.contains(expectedConfig), s"Could not find `$expectedConfig` in:\n $rst")
  }

  /* Sanity check that toEnrichedRst produces one of the expected configs */
  @Test
  def testToRst(): Unit = {
    val rst = LogConfig.configDefCopy.toRst
    val expectedConfig = "``file.delete.delay.ms``"
    assertTrue(rst.contains(expectedConfig), s"Could not find `$expectedConfig` in:\n $rst")
  }

  @Test
  def testGetConfigValue(): Unit = {
    // Add a config that doesn't set the `serverDefaultConfigName`
    val configDef = LogConfig.configDefCopy
    val configNameWithNoServerMapping = "log.foo"
    configDef.define(configNameWithNoServerMapping, INT, 1, MEDIUM, s"$configNameWithNoServerMapping doc")

    val deleteDelayKey = configDef.configKeys.get(TopicConfig.FILE_DELETE_DELAY_MS_CONFIG)
    val deleteDelayServerDefault = configDef.getConfigValue(deleteDelayKey, LogConfig.ServerDefaultHeaderName)
    assertEquals(KafkaConfig.LogDeleteDelayMsProp, deleteDelayServerDefault)

    val keyWithNoServerMapping = configDef.configKeys.get(configNameWithNoServerMapping)
    val nullServerDefault = configDef.getConfigValue(keyWithNoServerMapping, LogConfig.ServerDefaultHeaderName)
    assertNull(nullServerDefault)
  }

  private def isValid(configValue: String): Boolean = {
    try {
      ThrottledReplicaListValidator.ensureValidString("", configValue)
      true
    } catch {
      case _: ConfigException => false
    }
  }

  private def assertPropertyInvalid(name: String, values: AnyRef*): Unit = {
    values.foreach((value) => {
      val props = new Properties
      props.setProperty(name, value.toString)
      assertThrows(classOf[Exception], () => LogConfig(props))
    })
  }

}


text:
#ifndef PED_CONSTRAINT_H_INCLUDED
#define PED_CONSTRAINT_H_INCLUDED

typedef struct _PedConstraint	PedConstraint;

#include <parted/device.h>
#include <parted/geom.h>
#include <parted/natmath.h>

struct _PedConstraint {
	PedAlignment*	start_align;
	PedAlignment*	end_align;
	PedGeometry*	start_range;
	PedGeometry*	end_range;
	PedSector	min_size;
	PedSector	max_size;
};

extern int
ped_constraint_init (
	PedConstraint* constraint,
	const PedAlignment* start_align,
	const PedAlignment* end_align,
	const PedGeometry* start_range,
	const PedGeometry* end_range,
	PedSector min_size,
	PedSector max_size);

extern PedConstraint*
ped_constraint_new (
	const PedAlignment* start_align,
	const PedAlignment* end_align,
	const PedGeometry* start_range,
	const PedGeometry* end_range,
	PedSector min_size,
	PedSector max_size);

extern PedConstraint*
ped_constraint_new_from_min_max (
	const PedGeometry* min,
	const PedGeometry* max);

extern PedConstraint*
ped_constraint_new_from_min (const PedGeometry* min);

extern PedConstraint*
ped_constraint_new_from_max (const PedGeometry* max);

extern PedConstraint*
ped_constraint_duplicate (const PedConstraint* constraint);

extern void
ped_constraint_done (PedConstraint* constraint);

extern void
ped_constraint_destroy (PedConstraint* constraint);

extern PedConstraint*
ped_constraint_intersect (const PedConstraint* a, const PedConstraint* b);

extern PedGeometry*
ped_constraint_solve_max (const PedConstraint* constraint);

extern PedGeometry*
ped_constraint_solve_nearest (
	const PedConstraint* constraint, const PedGeometry* geom);

extern int
ped_constraint_is_solution (const PedConstraint* constraint,
			    const PedGeometry* geom);

extern PedConstraint*
ped_constraint_any (const PedDevice* dev);

extern PedConstraint*
ped_constraint_exact (const PedGeometry* geom);

#endif /* PED_CONSTRAINT_H_INCLUDED */


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "UnrealEd.h"
#include "Toolkits/AssetEditorToolkit.h"
#include "Toolkits/SStandaloneAssetEditorToolkitHost.h"
#include "Toolkits/ToolkitManager.h"
#include "Toolkits/AssetEditorCommonCommands.h"
#include "Toolkits/GlobalEditorCommonCommands.h"
#include "Editor/MainFrame/Public/MainFrame.h"
#include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructureModule.h"
#include "ClassIconFinder.h"
#include "CollectionManagerModule.h"
#include "IUserFeedbackModule.h"
#include "IDocumentation.h"
#include "ReferenceViewer.h"
#include "ISizeMapModule.h"
#include "IIntroTutorials.h"
#include "SuperSearchModule.h"
#include "SDockTab.h"

#define LOCTEXT_NAMESPACE "AssetEditorToolkit"

TWeakPtr< IToolkitHost > FAssetEditorToolkit::PreviousWorldCentricToolkitHostForNewAssetEditor;

const FName FAssetEditorToolkit::ToolbarTabId( TEXT( "AssetEditorToolkit_Toolbar" ) );

FAssetEditorToolkit::FAssetEditorToolkit()
	: bCheckDirtyOnAssetSave(false)
	, bIsToolbarFocusable(false)
{
	WorkspaceMenuCategory = FWorkspaceItem::NewGroup(LOCTEXT("WorkspaceMenu_BaseAssetEditor", "Asset Editor"));
}

void FAssetEditorToolkit::InitAssetEditor( const EToolkitMode::Type Mode, const TSharedPtr< class IToolkitHost >& InitToolkitHost, const FName AppIdentifier, const TSharedRef<FTabManager::FLayout>& StandaloneDefaultLayout, const bool bCreateDefaultStandaloneMenu, const bool bCreateDefaultToolbar, UObject* ObjectToEdit, const bool bInIsToolbarFocusable )
{
	TArray< UObject* > ObjectsToEdit;
	ObjectsToEdit.Add( ObjectToEdit );

	InitAssetEditor( Mode, InitToolkitHost, AppIdentifier, StandaloneDefaultLayout, bCreateDefaultStandaloneMenu, bCreateDefaultToolbar, ObjectsToEdit, bInIsToolbarFocusable );
}

void FAssetEditorToolkit::InitAssetEditor( const EToolkitMode::Type Mode, const TSharedPtr< class IToolkitHost >& InitToolkitHost, const FName AppIdentifier, const TSharedRef<FTabManager::FLayout>& StandaloneDefaultLayout, const bool bCreateDefaultStandaloneMenu, const bool bCreateDefaultToolbar, const TArray<UObject*>& ObjectsToEdit, const bool bInIsToolbarFocusable )
{
	// Must not already be editing an object
	check( ObjectsToEdit.Num() > 0 );
	check( EditingObjects.Num() == 0 );

	bIsToolbarFocusable = bInIsToolbarFocusable;

	// cache reference to ToolkitManager; also ensure it was initialized.
	FToolkitManager& ToolkitManager = FToolkitManager::Get();

	EditingObjects.Append( ObjectsToEdit );

	// Store "previous" asset editing toolkit host, and clear it out
	PreviousWorldCentricToolkitHost = PreviousWorldCentricToolkitHostForNewAssetEditor;
	PreviousWorldCentricToolkitHostForNewAssetEditor.Reset();

	ToolkitMode = Mode;

	TSharedPtr<SWindow> ParentWindow;

	TSharedPtr<SDockTab> NewMajorTab;

	TSharedPtr< SStandaloneAssetEditorToolkitHost > NewStandaloneHost;
	if( ToolkitMode == EToolkitMode::WorldCentric )		// @todo toolkit major: Do we need to remember this setting on a per-asset editor basis?  Probably.
	{
		// Keep track of the level editor we're attached to (if any)
		ToolkitHost = InitToolkitHost;
	}
	else if( ensure( ToolkitMode == EToolkitMode::Standalone ) )
	{
		// Open a standalone app to edit this asset.
		check( AppIdentifier != NAME_None );

		// Create the label and the link for the toolkit documentation.
		TAttribute<FText> Label = TAttribute<FText>( this, &FAssetEditorToolkit::GetToolkitName );
		TAttribute<FText> ToolTipText = TAttribute<FText>( this, &FAssetEditorToolkit::GetToolkitToolTipText );
		FString DocLink = GetDocumentationLink();
		if ( !DocLink.StartsWith( "Shared/" ) )
		{
			DocLink = FString("Shared/") + DocLink;
		}

		// Create a new SlateToolkitHost
		NewMajorTab = SNew(SDockTab)
			.ContentPadding(0.0f)
			.TabRole(ETabRole::MajorTab)
			.ToolTip(IDocumentation::Get()->CreateToolTip(ToolTipText, nullptr, DocLink, GetToolkitFName().ToString()))
			.Icon( this, &FAssetEditorToolkit::GetDefaultTabIcon )
			.Label( Label );

		{
			static_assert(sizeof(EAssetEditorToolkitTabLocation) == sizeof(int32), "EAssetEditorToolkitTabLocation is the incorrect size");

			const UEditorStyleSettings* StyleSettings = GetDefault<UEditorStyleSettings>();

			// Work out where we should create this asset editor
			EAssetEditorToolkitTabLocation SavedAssetEditorToolkitTabLocation = StyleSettings->bOpenAssetEditorTabsInNewWindow ? EAssetEditorToolkitTabLocation::Standalone : EAssetEditorToolkitTabLocation::Docked;
			GConfig->GetInt(
				TEXT("AssetEditorToolkitTabLocation"),
				*ObjectsToEdit[0]->GetPathName(),
				reinterpret_cast<int32&>(SavedAssetEditorToolkitTabLocation),
				GEditorPerProjectIni
				);

			const FName AssetEditorToolkitTab = (SavedAssetEditorToolkitTabLocation == EAssetEditorToolkitTabLocation::Docked) ? "DockedToolkit" : "StandaloneToolkit";
			FGlobalTabmanager::Get()->InsertNewDocumentTab( AssetEditorToolkitTab, FTabManager::ESearchPreference::PreferLiveTab, NewMajorTab.ToSharedRef() );
		}

#if PLATFORM_MAC
		FSuperSearchModule& SuperSearchModule = FModuleManager::LoadModuleChecked< FSuperSearchModule >(TEXT("SuperSearch"));
		TSharedPtr< SEditableTextBox > ExposedEditableTextBox;
		TSharedRef<SWidget> SuperSearchWidget = SuperSearchModule.MakeSearchBox(ExposedEditableTextBox);
#endif

		IUserFeedbackModule& UserFeedback = FModuleManager::LoadModuleChecked<IUserFeedbackModule>(TEXT("UserFeedback"));
		TSharedRef<SWidget> UserFeedbackWidget = UserFeedback.CreateFeedbackWidget(GetBaseToolkitName());

		IIntroTutorials& IntroTutorials = FModuleManager::LoadModuleChecked<IIntroTutorials>(TEXT("IntroTutorials"));
		TSharedRef<SWidget> TutorialWidget = IntroTutorials.CreateTutorialsWidget(GetToolkitContextFName(), NewMajorTab->GetParentWindow());

		NewMajorTab->SetRightContent(
				SNew(SHorizontalBox)
				+ SHorizontalBox::Slot()
				.AutoWidth()
				.Padding(8.0f, 0.0f, 0.0f, 0.0f)
				.VAlign(VAlign_Center)
				[
					UserFeedbackWidget
				]
#if PLATFORM_MAC
				+SHorizontalBox::Slot()
				.AutoWidth()
				.Padding(16.0f, 0.0f, 0.0f, 0.0f)
				.VAlign(VAlign_Center)
				[
					SuperSearchWidget
				]
#endif
				+SHorizontalBox::Slot()
				.AutoWidth()
				.Padding(8.0f, 0.0f, 8.0f, 0.0f)
				.VAlign(VAlign_Center)
				[
					TutorialWidget
				]
			);

		const TSharedRef<FTabManager> NewTabManager = FGlobalTabmanager::Get()->NewTabManager( NewMajorTab.ToSharedRef() );
		NewTabManager->SetOnPersistLayout(FTabManager::FOnPersistLayout::CreateRaw(this, &FAssetEditorToolkit::HandleTabManagerPersistLayout));
		this->TabManager = NewTabManager;

		NewMajorTab->SetContent
		(

			SAssignNew( NewStandaloneHost, SStandaloneAssetEditorToolkitHost, NewTabManager, AppIdentifier )
			.OnRequestClose(this, &FAssetEditorToolkit::OnRequestClose)
		);

		// Assign our toolkit host before we setup initial content.  (Important: We must cache this pointer here as SetupInitialContent
		// will callback into the toolkit host.)
		ToolkitHost = NewStandaloneHost;
	}

	check( ToolkitHost.IsValid() );
	ToolkitManager.RegisterNewToolkit( SharedThis( this ) );

	if (ToolkitMode == EToolkitMode::Standalone)
	{
		TSharedRef<FTabManager::FLayout> LayoutToUse = FLayoutSaveRestore::LoadFromConfig(GEditorLayoutIni, StandaloneDefaultLayout);

		// Actually create the widget content
		NewStandaloneHost->SetupInitialContent( LayoutToUse, NewMajorTab, bCreateDefaultStandaloneMenu );
	}
	StandaloneHost = NewStandaloneHost;

	if (bCreateDefaultToolbar)
	{
		GenerateToolbar();
	}
	else
	{
		Toolbar = SNullWidget::NullWidget;
	}

	ToolkitCommands->MapAction(
		FAssetEditorCommonCommands::Get().SaveAsset,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::SaveAsset_Execute ),
		FCanExecuteAction::CreateSP( this, &FAssetEditorToolkit::CanSaveAsset ));

	ToolkitCommands->MapAction(
		FGlobalEditorCommonCommands::Get().FindInContentBrowser,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::FindInContentBrowser_Execute ) );

	ToolkitCommands->MapAction(
		FGlobalEditorCommonCommands::Get().ViewReferences,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::ViewReferences_Execute ),
		FCanExecuteAction::CreateSP( this, &FAssetEditorToolkit::CanViewReferences ));

	ToolkitCommands->MapAction(
		FGlobalEditorCommonCommands::Get().ViewSizeMap,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::ViewSizeMap_Execute ),
		FCanExecuteAction::CreateSP( this, &FAssetEditorToolkit::CanViewSizeMap ));

	ToolkitCommands->MapAction(
		FGlobalEditorCommonCommands::Get().OpenDocumentation,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::BrowseDocumentation_Execute ) );

	ToolkitCommands->MapAction(
		FAssetEditorCommonCommands::Get().ReimportAsset,
		FExecuteAction::CreateSP( this, &FAssetEditorToolkit::Reimport_Execute ) );

	FGlobalEditorCommonCommands::MapActions(ToolkitCommands);

	if( IsWorldCentricAssetEditor() )
	{
		ToolkitCommands->MapAction(
			FAssetEditorCommonCommands::Get().SwitchToStandaloneEditor,
			FExecuteAction::CreateStatic( &FAssetEditorToolkit::SwitchToStandaloneEditor_Execute, TWeakPtr< FAssetEditorToolkit >( AsShared() ) ) );
	}
	else
	{
		if( GetPreviousWorldCentricToolkitHost().IsValid() )
		{
			ToolkitCommands->MapAction(
				FAssetEditorCommonCommands::Get().SwitchToWorldCentricEditor,
				FExecuteAction::CreateStatic( &FAssetEditorToolkit::SwitchToWorldCentricEditor_Execute, TWeakPtr< FAssetEditorToolkit >( AsShared() ) ) );
		}
	}

	// NOTE: Currently, the AssetEditorManager will keep a hard reference to our object as we're editing it
	FAssetEditorManager::Get().NotifyAssetsOpened( EditingObjects, this );
}

FAssetEditorToolkit::~FAssetEditorToolkit()
{
	EditingObjects.Empty();

	// We're no longer editing this object, so let the editor know
	FAssetEditorManager::Get().NotifyEditorClosed( this );
}

void FAssetEditorToolkit::RegisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
	// Use the first child category of the local workspace root if there is one, otherwise use the root itself
	const auto& LocalCategories = InTabManager->GetLocalWorkspaceMenuRoot()->GetChildItems();
	TSharedRef<FWorkspaceItem> ToolbarSpawnerCategory = LocalCategories.Num() > 0 ? LocalCategories[0] : InTabManager->GetLocalWorkspaceMenuRoot();

	InTabManager->RegisterTabSpawner( ToolbarTabId, FOnSpawnTab::CreateSP(this, &FAssetEditorToolkit::SpawnTab_Toolbar) )
		.SetDisplayName( LOCTEXT("ToolbarTab", "Toolbar") )
		.SetGroup( ToolbarSpawnerCategory )
		.SetIcon( FSlateIcon(FEditorStyle::GetStyleSetName(), "Toolbar.Icon") );
}

void FAssetEditorToolkit::UnregisterTabSpawners(const TSharedRef<class FTabManager>& InTabManager)
{
	InTabManager->UnregisterTabSpawner( ToolbarTabId );
	InTabManager->ClearLocalWorkspaceMenuCategories();
}

bool FAssetEditorToolkit::IsAssetEditor() const
{
	return true;
}

FText FAssetEditorToolkit::GetToolkitName() const
{
	const UObject* EditingObject = GetEditingObject();

	check (EditingObject != NULL);

	return GetLabelForObject(EditingObject);
}

FText FAssetEditorToolkit::GetToolkitToolTipText() const
{
	const UObject* EditingObject = GetEditingObject();

	check (EditingObject != NULL);

	return GetToolTipTextForObject(EditingObject);
}

FText FAssetEditorToolkit::GetLabelForObject(const UObject* InObject)
{
	const bool bDirtyState = InObject->GetOutermost()->IsDirty();
	FString NameString;
	if(const AActor* ObjectAsActor = Cast<AActor>(InObject))
	{
		NameString = ObjectAsActor->GetActorLabel();
	}
	else
	{
		NameString = InObject->GetName();
	}

	FFormatNamedArguments Args;
	Args.Add( TEXT("ObjectName"), FText::FromString( NameString ));
	Args.Add( TEXT("DirtyState"), bDirtyState ? FText::FromString( TEXT( "*" ) ) : FText::GetEmpty() );
	return FText::Format( LOCTEXT("AssetEditorAppLabel", "{ObjectName}{DirtyState}"), Args );
}

FText FAssetEditorToolkit::GetToolTipTextForObject(const UObject* InObject)
{
	FString ToolTipString;
	if(const AActor* ObjectAsActor = Cast<AActor>(InObject))
	{
		ToolTipString += LOCTEXT("ToolTipActorLabel", "Actor").ToString();
		ToolTipString += TEXT(": ");
		ToolTipString += ObjectAsActor->GetActorLabel();
	}
	else
	{
		ToolTipString += LOCTEXT("ToolTipAssetLabel", "Asset").ToString();
		ToolTipString += TEXT(": ");
		ToolTipString += InObject->GetName();

		FCollectionManagerModule& CollectionManagerModule = FCollectionManagerModule::GetModule();

		const FString CollectionNames = CollectionManagerModule.Get().GetCollectionsStringForObject(*InObject->GetPathName(), ECollectionShareType::CST_All);
		if (!CollectionNames.IsEmpty())
		{
			ToolTipString += TEXT("\n");

			ToolTipString += LOCTEXT("ToolTipCollectionsLabel", "Collections").ToString();
			ToolTipString += TEXT(": ");
			ToolTipString += CollectionNames;
		}
	}

	return FText::FromString(ToolTipString);
}

class FEdMode* FAssetEditorToolkit::GetEditorMode() const
{
	return NULL;
}

const TArray< UObject* >* FAssetEditorToolkit::GetObjectsCurrentlyBeingEdited() const
{
	return &EditingObjects;
}

FName FAssetEditorToolkit::GetEditorName() const
{
	return GetToolkitFName();
}

void FAssetEditorToolkit::FocusWindow(UObject* ObjectToFocusOn)
{
	BringToolkitToFront();
}

bool FAssetEditorToolkit::CloseWindow()
{
	if (OnRequestClose())
	{
		// Close this toolkit
		FToolkitManager::Get().CloseToolkit( AsShared() );
	}
	return true;
}

void FAssetEditorToolkit::InvokeTab(const FTabId& TabId)
{
	GetTabManager()->InvokeTab(TabId);
}

TSharedPtr<class FTabManager> FAssetEditorToolkit::GetAssociatedTabManager()
{
	return TabManager;
}

double FAssetEditorToolkit::GetLastActivationTime()
{
	double MostRecentTime = 0.0;

	if (TabManager.IsValid())
	{
		TSharedPtr<SDockTab> OwnerTab = TabManager->GetOwnerTab();
		if (OwnerTab.IsValid())
		{
			MostRecentTime = OwnerTab->GetLastActivationTime();
		}
	}

	return MostRecentTime;
}

TSharedPtr< IToolkitHost > FAssetEditorToolkit::GetPreviousWorldCentricToolkitHost()
{
	return PreviousWorldCentricToolkitHost.Pin();
}

void FAssetEditorToolkit::SetPreviousWorldCentricToolkitHostForNewAssetEditor( TSharedRef< IToolkitHost > ToolkitHost )
{
	PreviousWorldCentricToolkitHostForNewAssetEditor = ToolkitHost;
}

UObject* FAssetEditorToolkit::GetEditingObject() const
{
	check( EditingObjects.Num() == 1 );
	return EditingObjects[ 0 ];
}

const TArray< UObject* >& FAssetEditorToolkit::GetEditingObjects() const
{
	check( EditingObjects.Num() > 0 );
	return EditingObjects;
}

void FAssetEditorToolkit::AddEditingObject(UObject* Object)
{
	EditingObjects.Add(Object);
	FAssetEditorManager::Get().NotifyAssetOpened( Object, this );
}

void FAssetEditorToolkit::RemoveEditingObject(UObject* Object)
{
	EditingObjects.Remove(Object);
	FAssetEditorManager::Get().NotifyAssetClosed( Object, this );
}

void FAssetEditorToolkit::SaveAsset_Execute()
{
	if( ensure( EditingObjects.Num() > 0 ) )
	{
		TArray< UPackage* > PackagesToSave;

		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
			const auto EditingObject = *ObjectIter;
			if( EditingObject != NULL && EditingObject->IsAsset() )
			{
				PackagesToSave.Add( EditingObject->GetOutermost() );
			}
		}

		FEditorFileUtils::PromptForCheckoutAndSave( PackagesToSave, bCheckDirtyOnAssetSave, /*bPromptToSave=*/ false );
	}
}

const FSlateBrush* FAssetEditorToolkit::GetDefaultTabIcon() const
{
	if (EditingObjects.Num() == 0)
	{
		return nullptr;
	}

	const FSlateBrush* IconBrush = nullptr;

	for (auto ObjectIt = EditingObjects.CreateConstIterator(); ObjectIt; ++ObjectIt)
	{
		const FSlateBrush* ThisAssetBrush = FClassIconFinder::FindIconForClass((*ObjectIt)->GetClass());

		if (!IconBrush)
		{
			IconBrush = ThisAssetBrush;
		}
		else if (IconBrush != ThisAssetBrush)
		{
			// Different types
			return nullptr;
		}
	}

	return IconBrush;
}

void FAssetEditorToolkit::SwitchToStandaloneEditor_Execute( TWeakPtr< FAssetEditorToolkit > ThisToolkitWeakRef )
{
	// NOTE: We're being very careful here with pointer handling because we need to make sure the tookit's
	// destructor is called when we call CloseToolkit, as it needs to be fully unregistered before we go
	// and try to open a new asset editor for the same asset

	// First, close the world-centric toolkit
	TArray< FWeakObjectPtr > ObjectsToEditStandaloneWeak;
	TSharedPtr< IToolkitHost > PreviousWorldCentricToolkitHost;
	{
		TSharedRef< FAssetEditorToolkit > ThisToolkit = ThisToolkitWeakRef.Pin().ToSharedRef();
		check( ThisToolkit->IsWorldCentricAssetEditor() );
		PreviousWorldCentricToolkitHost = ThisToolkit->GetToolkitHost();

		const auto& EditingObjects = *ThisToolkit->GetObjectsCurrentlyBeingEdited();

		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			ObjectsToEditStandaloneWeak.Add( *ObjectIter );
		}

		FToolkitManager::Get().CloseToolkit( ThisToolkit );

		// At this point, we should be the only referencer of the toolkit!  It will be fully destroyed when
		// as the code pointer exits this block.
		ensure( ThisToolkit.IsUnique() );
	}

	// Now, reopen the toolkit in "standalone" mode
	TArray< UObject* > ObjectsToEdit;

	for( auto ObjectPtrItr = ObjectsToEditStandaloneWeak.CreateIterator(); ObjectPtrItr; ++ObjectPtrItr )
	{
		const auto WeakObjectPtr = *ObjectPtrItr;
		if( WeakObjectPtr.IsValid() )
		{
			ObjectsToEdit.Add( WeakObjectPtr.Get() );
		}
	}

	if( ObjectsToEdit.Num() > 0 )
	{
		ensure( FAssetEditorManager::Get().OpenEditorForAssets( ObjectsToEdit, EToolkitMode::Standalone, PreviousWorldCentricToolkitHost.ToSharedRef() ) );
	}
}

void FAssetEditorToolkit::SwitchToWorldCentricEditor_Execute( TWeakPtr< FAssetEditorToolkit > ThisToolkitWeakRef )
{
	// @todo toolkit minor: Maybe also allow the user to drag and drop the standalone editor's tab into a specific level editor to switch to world-centric mode?

	// NOTE: We're being very careful here with pointer handling because we need to make sure the tookit's
	// destructor is called when we call CloseToolkit, as it needs to be fully unregistered before we go
	// and try to open a new asset editor for the same asset

	// First, close the standalone toolkit
	TArray< FWeakObjectPtr > ObjectToEditWorldCentricWeak;
	TSharedPtr< IToolkitHost > WorldCentricLevelEditor;
	{
		TSharedRef< FAssetEditorToolkit > ThisToolkit = ThisToolkitWeakRef.Pin().ToSharedRef();
		const auto& EditingObjects = *ThisToolkit->GetObjectsCurrentlyBeingEdited();

		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			ObjectToEditWorldCentricWeak.Add( *ObjectIter );
		}

		check( !ThisToolkit->IsWorldCentricAssetEditor() );
		WorldCentricLevelEditor = ThisToolkit->GetPreviousWorldCentricToolkitHost();

		FToolkitManager::Get().CloseToolkit( ThisToolkit );

		// At this point, we should be the only referencer of the toolkit!  It will be fully destroyed when
		// as the code pointer exits this block.
		ensure( ThisToolkit.IsUnique() );
	}

	// Now, reopen the toolkit in "world-centric" mode
	TArray< UObject* > ObjectsToEdit;
	for( auto ObjectPtrItr = ObjectToEditWorldCentricWeak.CreateIterator(); ObjectPtrItr; ++ObjectPtrItr )
	{
		const auto WeakObjectPtr = *ObjectPtrItr;
		if( WeakObjectPtr.IsValid() )
		{
			ObjectsToEdit.Add( WeakObjectPtr.Get() );
		}
	}

	if( ObjectsToEdit.Num() > 0 )
	{
		ensure( FAssetEditorManager::Get().OpenEditorForAssets( ObjectsToEdit, EToolkitMode::WorldCentric, WorldCentricLevelEditor ) );
	}
}

void FAssetEditorToolkit::FindInContentBrowser_Execute()
{
	if( ensure( EditingObjects.Num() > 0 ) )
	{
		TArray< UObject* > ObjectsToSyncTo;

		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
			const auto EditingObject = *ObjectIter;
			if( EditingObject != NULL && EditingObject->IsAsset() )
			{
				ObjectsToSyncTo.Add( EditingObject );
			}
		}

		GEditor->SyncBrowserToObjects( ObjectsToSyncTo );
	}
}

void FAssetEditorToolkit::BrowseDocumentation_Execute() const
{
	IDocumentation::Get()->Open(GetDocumentationLink(), FDocumentationSourceInfo(TEXT("help_menu_asset")));
}

void FAssetEditorToolkit::ViewReferences_Execute()
{
	if (ensure( ViewableObjects.Num() > 0))
	{
		IReferenceViewerModule::Get().InvokeReferenceViewerTab(ViewableObjects);
	}
}

bool FAssetEditorToolkit::CanViewReferences()
{
	ViewableObjects.Empty();
	for (const auto EditingObject : EditingObjects)
	{
		// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
		if (EditingObject != NULL && EditingObject->IsAsset())
		{
			ViewableObjects.Add(EditingObject->GetOuter()->GetFName());
		}
	}

	return ViewableObjects.Num() > 0;
}

void FAssetEditorToolkit::ViewSizeMap_Execute()
{
	if (ensure( ViewableObjects.Num() > 0))
	{
		ISizeMapModule::Get().InvokeSizeMapTab(ViewableObjects);
	}
}

bool FAssetEditorToolkit::CanViewSizeMap()
{
	ViewableObjects.Empty();
	for (const auto EditingObject : EditingObjects)
	{
		// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
		if (EditingObject != NULL && EditingObject->IsAsset())
		{
			ViewableObjects.Add(EditingObject->GetOuter()->GetFName());
		}
	}

	return ViewableObjects.Num() > 0;
}

FString FAssetEditorToolkit::GetDocumentationLink() const
{
	return FString(TEXT("%ROOT%"));
}

bool FAssetEditorToolkit::CanReimport() const
{
	for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
	{
		auto EditingObject = *ObjectIter;
		if ( CanReimport( EditingObject ) )
		{
			return true;
		}
	}
	return false;
}

bool FAssetEditorToolkit::CanReimport( UObject* EditingObject ) const
{
	// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
	if( EditingObject != NULL && EditingObject->IsAsset() )
	{
		if ( FReimportManager::Instance()->CanReimport( EditingObject ) )
		{
			return true;
		}
	}
	return false;
}

void FAssetEditorToolkit::Reimport_Execute()
{
	if( ensure( EditingObjects.Num() > 0 ) )
	{
		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			const auto EditingObject = *ObjectIter;
			Reimport_Execute( EditingObject );
		}
	}
}

void FAssetEditorToolkit::Reimport_Execute( UObject* EditingObject )
{
	// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
	if( EditingObject != NULL && EditingObject->IsAsset() )
	{
		// Reimport the asset
		FReimportManager::Instance()->Reimport(EditingObject, ShouldPromptForNewFilesOnReload(*EditingObject));
	}
}

bool FAssetEditorToolkit::ShouldPromptForNewFilesOnReload(const UObject& EditingObject) const
{
	return true;
}

TSharedRef<SDockTab> FAssetEditorToolkit::SpawnTab_Toolbar( const FSpawnTabArgs& Args )
{
	check( Args.GetTabId() == ToolbarTabId );

	TSharedRef<SDockTab> DockTab = SNew(SDockTab)
		.Label( NSLOCTEXT("AssetEditorToolkit", "Toolbar_TabTitle", "Toolbar") )
		.Icon(FEditorStyle::GetBrush("LevelEditor.Tabs.Toolbar"))
		.ShouldAutosize(true)
		[
			SAssignNew(ToolbarWidgetContent, SBorder)
			.Padding(0)
			.BorderImage(FEditorStyle::GetBrush("NoBorder"))
		];

	if (Toolbar.IsValid())
	{
		ToolbarWidgetContent->SetContent(Toolbar.ToSharedRef());
	}

	return DockTab;
}

void FAssetEditorToolkit::FillDefaultFileMenuCommands( FMenuBuilder& MenuBuilder )
{
	if( IsActuallyAnAsset() )
	{
		MenuBuilder.AddMenuEntry( FAssetEditorCommonCommands::Get().SaveAsset, "SaveAsset", TAttribute<FText>(), TAttribute<FText>(), FSlateIcon(FEditorStyle::GetStyleSetName(), "AssetEditor.SaveAsset.Greyscale") );

		MenuBuilder.AddMenuSeparator();
	}

	if( IsWorldCentricAssetEditor() )
	{
		// @todo toolkit minor: It would be awesome if the user could just "tear off" the SToolkitDisplay to do SwitchToStandaloneEditor
		//			Would need to probably drop at mouseup location though instead of using saved layout pos.
		MenuBuilder.AddMenuEntry( FAssetEditorCommonCommands::Get().SwitchToStandaloneEditor );
	}
	else
	{
		if( GetPreviousWorldCentricToolkitHost().IsValid() )
		{
			// @todo toolkit checkin: Disabled temporarily until we have world-centric "ready to use"!
			if( 0 )
			{
				MenuBuilder.AddMenuEntry( FAssetEditorCommonCommands::Get().SwitchToWorldCentricEditor );
			}
		}
	}
}

void FAssetEditorToolkit::FillDefaultAssetMenuCommands( FMenuBuilder& MenuBuilder )
{
	// Commands we only want to be accessible when editing an asset should go here
	if( IsActuallyAnAsset() )
	{
		MenuBuilder.AddMenuEntry( FGlobalEditorCommonCommands::Get().FindInContentBrowser, "FindInContentBrowser", LOCTEXT("FindInContentBrowser", "Find in Content Browser...") );
		MenuBuilder.AddMenuEntry( FGlobalEditorCommonCommands::Get().ViewReferences);
		MenuBuilder.AddMenuEntry( FGlobalEditorCommonCommands::Get().ViewSizeMap);

		// Add a reimport menu entry for each supported editable object
		for( auto ObjectIter = EditingObjects.CreateConstIterator(); ObjectIter; ++ObjectIter )
		{
			const auto EditingObject = *ObjectIter;
			if( EditingObject != NULL && EditingObject->IsAsset() )
			{
				if ( CanReimport( EditingObject ) )
				{
					FFormatNamedArguments LabelArguments;
					LabelArguments.Add(TEXT("Name"), FText::FromString( EditingObject->GetName() ));
					const FText LabelText = FText::Format( LOCTEXT("Reimport_Label", "Reimport {Name}..."), LabelArguments );
					FFormatNamedArguments ToolTipArguments;
					ToolTipArguments.Add(TEXT("Type"), FText::FromString( EditingObject->GetClass()->GetName() ));
					const FText ToolTipText = FText::Format( LOCTEXT("Reimport_ToolTip", "Reimports this {Type}"), ToolTipArguments );
					const FName IconName = TEXT( "AssetEditor.Reimport" );
					FUIAction UIAction;
					UIAction.ExecuteAction.BindRaw( this, &FAssetEditorToolkit::Reimport_Execute, EditingObject );
					MenuBuilder.AddMenuEntry( LabelText, ToolTipText, FSlateIcon(FEditorStyle::GetStyleSetName(), IconName), UIAction );
				}
			}
		}
	}
}

void FAssetEditorToolkit::FillDefaultHelpMenuCommands( FMenuBuilder& MenuBuilder )
{
	FFormatNamedArguments Args;
	Args.Add(TEXT("Editor"), GetBaseToolkitName());
	const FText ToolTip = FText::Format(LOCTEXT("BrowseDocumentationTooltip", "Browse {Editor} documentation..."), Args);

	MenuBuilder.AddMenuEntry(FGlobalEditorCommonCommands::Get().OpenDocumentation, NAME_None, ToolTip);
}

void FAssetEditorToolkit::GenerateToolbar()
{
	TSharedPtr<FExtender> Extender = FExtender::Combine(ToolbarExtenders);

	FToolBarBuilder ToolbarBuilder( GetToolkitCommands(), FMultiBoxCustomization::AllowCustomization( GetToolkitFName() ), Extender);
	ToolbarBuilder.SetIsFocusable(bIsToolbarFocusable);
	ToolbarBuilder.BeginSection("Asset");
	{
		if( IsActuallyAnAsset() )
		{
			ToolbarBuilder.AddToolBarButton(FAssetEditorCommonCommands::Get().SaveAsset);
			ToolbarBuilder.AddToolBarButton(FGlobalEditorCommonCommands::Get().FindInContentBrowser, NAME_None, LOCTEXT("FindInContentBrowserButton", "Find in CB"));
		}
	}
	ToolbarBuilder.EndSection();

	TSharedRef<SHorizontalBox> MiscWidgets = SNew(SHorizontalBox);

	for (int32 WidgetIdx = 0; WidgetIdx < ToolbarWidgets.Num(); ++WidgetIdx)
	{
		MiscWidgets->AddSlot()
		.AutoWidth()
		.VAlign(VAlign_Center)
		.Padding(0.0f, 2.0f, 0.0f, 2.0f)
		[
			ToolbarWidgets[WidgetIdx]
		];
	}

	Toolbar =
		SNew(SHorizontalBox)
		+SHorizontalBox::Slot()
		.HAlign(HAlign_Left)
		.VAlign(VAlign_Center)
		[
			SNew(SVerticalBox)
			+SVerticalBox::Slot()
			.AutoHeight()
			.VAlign(VAlign_Bottom)
			[
				ToolbarBuilder.MakeWidget()
			]
		]
		+SHorizontalBox::Slot()
		.HAlign(HAlign_Right)
		.VAlign(VAlign_Center)
		.AutoWidth()
		[
			SNew(SVerticalBox)
			+SVerticalBox::Slot()
			.AutoHeight()
			.VAlign(VAlign_Bottom)
			[
				SNew(SBorder)
				.BorderImage(FEditorStyle::GetBrush(TEXT("Toolbar.Background")))
				.Visibility(ToolbarWidgets.Num() > 0 ? EVisibility::Visible : EVisibility::Collapsed)
				[
					MiscWidgets
				]
			]
		];

	if (ToolbarWidgetContent.IsValid())
	{
		ToolbarWidgetContent->SetContent(Toolbar.ToSharedRef());
	}
}

void FAssetEditorToolkit::RegenerateMenusAndToolbars()
{
	RemoveAllToolbarWidgets();

	StandaloneHost.Pin()->GenerateMenus(false);

	if (Toolbar != SNullWidget::NullWidget)
	{
		GenerateToolbar();
	}

	PostRegenerateMenusAndToolbars();
}

void FAssetEditorToolkit::RestoreFromLayout(const TSharedRef<FTabManager::FLayout>& NewLayout)
{
	TSharedPtr< class SStandaloneAssetEditorToolkitHost > HostWidget = StandaloneHost.Pin();
	if (HostWidget.Get() != NULL)
	{
		// Save the old layout
		FLayoutSaveRestore::SaveToConfig(GEditorIni, TabManager->PersistLayout());

		// Load the potentially previously saved new layout
		TSharedRef<FTabManager::FLayout> UserConfiguredNewLayout = FLayoutSaveRestore::LoadFromConfig(GEditorLayoutIni, NewLayout);

		// Apply the new layout
		HostWidget->RestoreFromLayout(UserConfiguredNewLayout);
	}
}

bool FAssetEditorToolkit::IsActuallyAnAsset() const
{
	// Don't allow user to perform certain actions on objects that aren't actually assets (e.g. Level Script blueprint objects)
	bool bIsActuallyAnAsset = false;
	for( auto ObjectIter = GetObjectsCurrentlyBeingEdited()->CreateConstIterator(); !bIsActuallyAnAsset && ObjectIter; ++ObjectIter )
	{
		const auto ObjectBeingEdited = *ObjectIter;
		bIsActuallyAnAsset |= ObjectBeingEdited != NULL && ObjectBeingEdited->IsAsset();
	}
	return bIsActuallyAnAsset;
}

void FAssetEditorToolkit::AddMenuExtender(TSharedPtr<FExtender> Extender)
{
	StandaloneHost.Pin()->GetMenuExtenders().AddUnique(Extender);
}

void FAssetEditorToolkit::RemoveMenuExtender(TSharedPtr<FExtender> Extender)
{
	StandaloneHost.Pin()->GetMenuExtenders().Remove(Extender);
}

void FAssetEditorToolkit::AddToolbarExtender(TSharedPtr<FExtender> Extender)
{
	ToolbarExtenders.AddUnique(Extender);
}

void FAssetEditorToolkit::RemoveToolbarExtender(TSharedPtr<FExtender> Extender)
{
	ToolbarExtenders.Remove(Extender);
}

void FAssetEditorToolkit::SetMenuOverlay( TSharedRef<SWidget> Widget )
{
	StandaloneHost.Pin()->SetMenuOverlay( Widget );
}

void FAssetEditorToolkit::AddToolbarWidget(TSharedRef<SWidget> Widget)
{
	ToolbarWidgets.AddUnique(Widget);
}

void FAssetEditorToolkit::RemoveAllToolbarWidgets()
{
	ToolbarWidgets.Empty();
}

TSharedPtr<FExtender> FExtensibilityManager::GetAllExtenders()
{
	return FExtender::Combine(Extenders);
}

TSharedPtr<FExtender> FExtensibilityManager::GetAllExtenders(const TSharedRef<FUICommandList>& CommandList, const TArray<UObject*>& ContextSensitiveObjects)
{
	auto OutExtenders = Extenders;
	for (int32 i = 0; i < ExtenderDelegates.Num(); ++i)
	{
		if (ExtenderDelegates[i].IsBound())
		{
			OutExtenders.Add(ExtenderDelegates[i].Execute(CommandList, ContextSensitiveObjects));
		}
	}
	return FExtender::Combine(OutExtenders);
}

#undef LOCTEXT_NAMESPACE


text:
package de.flexiprovider.nf.iq.iqgq;

import de.flexiprovider.api.keys.KeySpec;
import de.flexiprovider.common.math.FlexiBigInt;
import de.flexiprovider.common.math.quadraticfields.QuadraticIdeal;

public class IQGQPrivateKeySpec implements KeySpec {
    private IQGQParameterSpec params;

    private QuadraticIdeal theta;

    private FlexiBigInt exponent;

    public IQGQPrivateKeySpec(IQGQParameterSpec params, QuadraticIdeal theta,
	    FlexiBigInt exponent) {
	this.params = params;
	this.theta = theta;
	this.exponent = exponent;
    }

    public IQGQParameterSpec getParams() {
	return params;
    }

    public QuadraticIdeal getTheta() {
	return theta;
    }

    public FlexiBigInt getExponent() {
	return exponent;
    }

}