text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SLoginSession.java
 *
 * Created on 11/11/2009, 05:12:17 PM
 */

package erp;

import erp.data.SDataConstantsSys;
import erp.lib.SLibConstants;
import erp.lib.form.SFormComponentItem;
import erp.lib.form.SFormField;
import erp.lib.form.SFormUtilities;
import erp.lib.form.SFormValidation;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;

/**
 *
 * @author Sergio Flores
 */
public class SLoginSession extends javax.swing.JDialog implements java.awt.event.ActionListener, java.awt.event.ItemListener {

    private int mnFormType;
    private int mnFormResult;
    private int mnFormStatus;
    private boolean mbFirstTime;
    private boolean mbResetingForm;
    private java.util.Vector<erp.lib.form.SFormField> mvFields;
    private erp.client.SClientInterface miClient;

    private erp.musr.data.SDataUser moUser;
    private erp.lib.form.SFormField moFieldWorkingDate;

    /** Creates new form SLoginSession */
    public SLoginSession(erp.client.SClientInterface client) {
        super(client.getFrame(), true);

        miClient = client;

        initComponents();
        initComponentsExtra();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jlUser = new javax.swing.JLabel();
        jtfUser = new javax.swing.JTextField();
        jckIsUniversal = new javax.swing.JCheckBox();
        jPanel3 = new javax.swing.JPanel();
        jlCompany = new javax.swing.JLabel();
        jtfCompany = new javax.swing.JTextField();
        jckIsUniversalCompany = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        jlCompanyBranch = new javax.swing.JLabel();
        jcbCompanyBranch = new javax.swing.JComboBox<SFormComponentItem>();
        jckIsUniversalCompanyBranch = new javax.swing.JCheckBox();
        jPanel6 = new javax.swing.JPanel();
        jlWorkingDate = new javax.swing.JLabel();
        jftWorkingDate = new javax.swing.JFormattedTextField();
        jbWorkingDate = new javax.swing.JButton();
        jtpEntities = new javax.swing.JTabbedPane();
        jpCashAccounts = new javax.swing.JPanel();
        jPanel12 = new javax.swing.JPanel();
        jlCashAccounts = new javax.swing.JLabel();
        jckIsUniversalEntityCh = new javax.swing.JCheckBox();
        jspCashAccounts = new javax.swing.JScrollPane();
        jltEntityCh = new javax.swing.JList<SFormComponentItem>();
        jpWarehouses = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jlWarehouses = new javax.swing.JLabel();
        jckIsUniversalEntityWh = new javax.swing.JCheckBox();
        jspWarehouses = new javax.swing.JScrollPane();
        jltEntityWh = new javax.swing.JList<SFormComponentItem>();
        jpPos = new javax.swing.JPanel();
        jPanel11 = new javax.swing.JPanel();
        jlPos = new javax.swing.JLabel();
        jckIsUniversalEntityPos = new javax.swing.JCheckBox();
        jspPos = new javax.swing.JScrollPane();
        jltEntityPos = new javax.swing.JList<SFormComponentItem>();
        jpPlants = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jlPlants = new javax.swing.JLabel();
        jckIsUniversalEntityPlt = new javax.swing.JCheckBox();
        jspPlants = new javax.swing.JScrollPane();
        jltEntityPlt = new javax.swing.JList<SFormComponentItem>();
        jPanel5 = new javax.swing.JPanel();
        jbOk = new javax.swing.JButton();
        jbCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sesión del usuario");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Acceso a la empresa:"));
        jPanel1.setLayout(new java.awt.GridLayout(4, 1, 5, 5));

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlUser.setText("Usuario:");
        jlUser.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel2.add(jlUser);

        jtfUser.setEditable(false);
        jtfUser.setText("COMPANY");
        jtfUser.setFocusable(false);
        jtfUser.setPreferredSize(new java.awt.Dimension(150, 23));
        jPanel2.add(jtfUser);

        jckIsUniversal.setText("Acceso universal");
        jckIsUniversal.setEnabled(false);
        jckIsUniversal.setPreferredSize(new java.awt.Dimension(160, 23));
        jPanel2.add(jckIsUniversal);

        jPanel1.add(jPanel2);

        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlCompany.setText("Empresa:");
        jlCompany.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel3.add(jlCompany);

        jtfCompany.setEditable(false);
        jtfCompany.setText("COMPANY");
        jtfCompany.setFocusable(false);
        jtfCompany.setPreferredSize(new java.awt.Dimension(300, 23));
        jPanel3.add(jtfCompany);

        jckIsUniversalCompany.setText("Acceso universal empresa");
        jckIsUniversalCompany.setEnabled(false);
        jckIsUniversalCompany.setPreferredSize(new java.awt.Dimension(160, 23));
        jPanel3.add(jckIsUniversalCompany);

        jPanel1.add(jPanel3);

        jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlCompanyBranch.setText("Sucursal empresa:");
        jlCompanyBranch.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel4.add(jlCompanyBranch);

        jcbCompanyBranch.setPreferredSize(new java.awt.Dimension(300, 23));
        jPanel4.add(jcbCompanyBranch);

        jckIsUniversalCompanyBranch.setText("Acceso universal sucursal");
        jckIsUniversalCompanyBranch.setEnabled(false);
        jckIsUniversalCompanyBranch.setPreferredSize(new java.awt.Dimension(160, 23));
        jPanel4.add(jckIsUniversalCompanyBranch);

        jPanel1.add(jPanel4);

        jPanel6.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0));

        jlWorkingDate.setText("Fecha trabajo: *");
        jlWorkingDate.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel6.add(jlWorkingDate);

        jftWorkingDate.setText("yyyy/mm/dd");
        jftWorkingDate.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel6.add(jftWorkingDate);

        jbWorkingDate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_cal.gif"))); // NOI18N
        jbWorkingDate.setToolTipText("Seleccionar fecha trabajo");
        jbWorkingDate.setFocusable(false);
        jbWorkingDate.setPreferredSize(new java.awt.Dimension(23, 23));
        jPanel6.add(jbWorkingDate);

        jPanel1.add(jPanel6);

        getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);

        jtpEntities.setBorder(javax.swing.BorderFactory.createTitledBorder("Entidades de la sucursal:"));

        jpCashAccounts.setLayout(new java.awt.BorderLayout());

        jPanel12.setLayout(new java.awt.BorderLayout());

        jlCashAccounts.setText("Seleccionar una cuenta de efectivo:");
        jlCashAccounts.setPreferredSize(new java.awt.Dimension(300, 14));
        jPanel12.add(jlCashAccounts, java.awt.BorderLayout.WEST);

        jckIsUniversalEntityCh.setText("Acceso universal a cuentas de efectivo");
        jckIsUniversalEntityCh.setEnabled(false);
        jckIsUniversalEntityCh.setPreferredSize(new java.awt.Dimension(250, 23));
        jPanel12.add(jckIsUniversalEntityCh, java.awt.BorderLayout.LINE_END);

        jpCashAccounts.add(jPanel12, java.awt.BorderLayout.NORTH);

        jspCashAccounts.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jltEntityCh.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jltEntityCh.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jspCashAccounts.setViewportView(jltEntityCh);

        jpCashAccounts.add(jspCashAccounts, java.awt.BorderLayout.CENTER);

        jtpEntities.addTab("Cuentas de efectivo", jpCashAccounts);

        jpWarehouses.setLayout(new java.awt.BorderLayout());

        jPanel8.setLayout(new java.awt.BorderLayout());

        jlWarehouses.setText("Seleccionar un almacén:");
        jlWarehouses.setPreferredSize(new java.awt.Dimension(300, 14));
        jPanel8.add(jlWarehouses, java.awt.BorderLayout.WEST);

        jckIsUniversalEntityWh.setText("Acceso universal a almacenes");
        jckIsUniversalEntityWh.setEnabled(false);
        jckIsUniversalEntityWh.setPreferredSize(new java.awt.Dimension(250, 23));
        jPanel8.add(jckIsUniversalEntityWh, java.awt.BorderLayout.LINE_END);

        jpWarehouses.add(jPanel8, java.awt.BorderLayout.NORTH);

        jspWarehouses.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jltEntityWh.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jltEntityWh.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jspWarehouses.setViewportView(jltEntityWh);

        jpWarehouses.add(jspWarehouses, java.awt.BorderLayout.CENTER);

        jtpEntities.addTab("Almacenes", jpWarehouses);

        jpPos.setLayout(new java.awt.BorderLayout());

        jPanel11.setLayout(new java.awt.BorderLayout());

        jlPos.setText("Seleccionar un punto de venta:");
        jlPos.setPreferredSize(new java.awt.Dimension(300, 14));
        jPanel11.add(jlPos, java.awt.BorderLayout.WEST);

        jckIsUniversalEntityPos.setText("Acceso universal a puntos de venta");
        jckIsUniversalEntityPos.setEnabled(false);
        jckIsUniversalEntityPos.setPreferredSize(new java.awt.Dimension(250, 23));
        jPanel11.add(jckIsUniversalEntityPos, java.awt.BorderLayout.LINE_END);

        jpPos.add(jPanel11, java.awt.BorderLayout.NORTH);

        jspPos.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jltEntityPos.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jltEntityPos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jspPos.setViewportView(jltEntityPos);

        jpPos.add(jspPos, java.awt.BorderLayout.CENTER);

        jtpEntities.addTab("Puntos de venta", jpPos);

        jpPlants.setLayout(new java.awt.BorderLayout());

        jPanel9.setLayout(new java.awt.BorderLayout());

        jlPlants.setText("Seleccionar una planta:");
        jlPlants.setPreferredSize(new java.awt.Dimension(300, 14));
        jPanel9.add(jlPlants, java.awt.BorderLayout.WEST);

        jckIsUniversalEntityPlt.setText("Acceso universal a plantas");
        jckIsUniversalEntityPlt.setEnabled(false);
        jckIsUniversalEntityPlt.setPreferredSize(new java.awt.Dimension(250, 23));
        jPanel9.add(jckIsUniversalEntityPlt, java.awt.BorderLayout.LINE_END);

        jpPlants.add(jPanel9, java.awt.BorderLayout.NORTH);

        jspPlants.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jltEntityPlt.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jltEntityPlt.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jspPlants.setViewportView(jltEntityPlt);

        jpPlants.add(jspPlants, java.awt.BorderLayout.CENTER);

        jtpEntities.addTab("Plantas", jpPlants);

        getContentPane().add(jtpEntities, java.awt.BorderLayout.CENTER);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jbOk.setText("Aceptar");
        jbOk.setToolTipText("[Ctrl + Enter]");
        jbOk.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel5.add(jbOk);

        jbCancel.setText("Cancelar");
        jbCancel.setToolTipText("[Escape]");
        jPanel5.add(jbCancel);

        getContentPane().add(jPanel5, java.awt.BorderLayout.SOUTH);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-648)/2, (screenSize.height-434)/2, 648, 434);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        windowActivated();
    }//GEN-LAST:event_formWindowActivated

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        jcbCompanyBranch.requestFocus();
    }//GEN-LAST:event_formWindowOpened

    private void initComponentsExtra() {
        moFieldWorkingDate = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftWorkingDate, jlWorkingDate);
        moFieldWorkingDate.setPickerButton(jbWorkingDate);

        mvFields = new Vector<SFormField>();
        mvFields.add(moFieldWorkingDate);

        jbOk.addActionListener(this);
        jbCancel.addActionListener(this);
        jbWorkingDate.addActionListener(this);

        jcbCompanyBranch.addItemListener(this);

        AbstractAction actionOk = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) { actionOk(); }
        };

        SFormUtilities.putActionMap(getRootPane(), actionOk, "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);

        AbstractAction actionCancel = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) { actionCancel(); }
        };

        SFormUtilities.putActionMap(getRootPane(), actionCancel, "cancel", KeyEvent.VK_ESCAPE, 0);
    }

    private void windowActivated() {
        if (mbFirstTime) {
            mbFirstTime = false;
            jcbCompanyBranch.requestFocus();
        }
    }

    private void selectDefaultEntity(javax.swing.JList list) {
        for (int i = 0; i < list.getModel().getSize(); i++) {
            if (((SFormComponentItem) list.getModel().getElementAt(i)).getItem().endsWith(" *")) {
                list.setSelectedIndex(i);
                break;
            }
        }
    }

    private void itemStateChangedCompanyBranch() {
        int companyBranchId = 0;
        Vector<SFormComponentItem> itemsCh = null;
        Vector<SFormComponentItem> itemsWh = null;
        Vector<SFormComponentItem> itemsPos = null;
        Vector<SFormComponentItem> itemsPlt = null;

        jckIsUniversalCompanyBranch.setSelected(false);
        jckIsUniversalEntityCh.setSelected(false);
        jckIsUniversalEntityWh.setSelected(false);
        jckIsUniversalEntityPos.setSelected(false);
        jckIsUniversalEntityPlt.setSelected(false);

        jltEntityCh.setListData(new SFormComponentItem[] {});
        jltEntityWh.setListData(new SFormComponentItem[] {});
        jltEntityPos.setListData(new SFormComponentItem[] {});
        jltEntityPlt.setListData(new SFormComponentItem[] {});

        if (jcbCompanyBranch.getSelectedIndex() > 0) {
            companyBranchId = ((int[]) ((SFormComponentItem) jcbCompanyBranch.getSelectedItem()).getPrimaryKey())[0];

            jckIsUniversalCompanyBranch.setSelected(miClient.getSessionXXX().getIsUniversalCompanyBranch(companyBranchId));
            jckIsUniversalEntityCh.setSelected(miClient.getSessionXXX().getIsUniversalCompanyBranchEntities(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_CASH));
            jckIsUniversalEntityWh.setSelected(miClient.getSessionXXX().getIsUniversalCompanyBranchEntities(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_WH));
            jckIsUniversalEntityPos.setSelected(miClient.getSessionXXX().getIsUniversalCompanyBranchEntities(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_POS));
            jckIsUniversalEntityPlt.setSelected(miClient.getSessionXXX().getIsUniversalCompanyBranchEntities(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_PLANT));

            itemsCh = new Vector<SFormComponentItem>();
            itemsWh = new Vector<SFormComponentItem>();
            itemsPos = new Vector<SFormComponentItem>();
            itemsPlt = new Vector<SFormComponentItem>();

            if (miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCurrentCompany() ||
                    jckIsUniversalCompanyBranch.isSelected() || jckIsUniversalEntityCh.isSelected()) {
                itemsCh = miClient.getSessionXXX().getAllCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_CASH, false);
            }
            else {
                itemsCh = miClient.getSessionXXX().getUserCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_CASH, false);
            }
            if (itemsCh.size() > 0) {
                jltEntityCh.setListData(itemsCh);
                selectDefaultEntity(jltEntityCh);
            }

            if (miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCurrentCompany() ||
                    jckIsUniversalCompanyBranch.isSelected() || jckIsUniversalEntityWh.isSelected()) {
                itemsWh = miClient.getSessionXXX().getAllCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_WH, false);
            }
            else {
                itemsWh = miClient.getSessionXXX().getUserCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_WH, false);
            }
            if (itemsWh.size() > 0) {
                jltEntityWh.setListData(itemsWh);
                selectDefaultEntity(jltEntityWh);
            }

            if (miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCurrentCompany() ||
                    jckIsUniversalCompanyBranch.isSelected() || jckIsUniversalEntityPos.isSelected()) {
                itemsPos = miClient.getSessionXXX().getAllCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_POS, false);
            }
            else {
                itemsPos = miClient.getSessionXXX().getUserCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_POS, false);
            }
            if (itemsPos.size() > 0) {
                jltEntityPos.setListData(itemsPos);
                selectDefaultEntity(jltEntityPos);
            }

            if (miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCurrentCompany() ||
                    jckIsUniversalCompanyBranch.isSelected() || jckIsUniversalEntityPlt.isSelected()) {
                itemsPlt = miClient.getSessionXXX().getAllCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_PLANT, false);
            }
            else {
                itemsPlt = miClient.getSessionXXX().getUserCompanyBranchEntitiesAsComponentItems(companyBranchId, SDataConstantsSys.CFGS_CT_ENT_PLANT, false);
            }
            if (itemsPlt.size() > 0) {
                jltEntityPlt.setListData(itemsPlt);
                selectDefaultEntity(jltEntityPlt);
            }
        }
    }

    private void actionWorkingDate() {
        miClient.getGuiDatePickerXXX().pickDate(moFieldWorkingDate.getDate(), moFieldWorkingDate);
    }

    private void actionOk() {
        SFormValidation validation = formValidate();

        if (validation.getIsError()) {
            if (validation.getComponent() != null) {
                validation.getComponent().requestFocus();
            }
            if (validation.getMessage().length() > 0) {
                miClient.showMsgBoxWarning(validation.getMessage());
            }
        }
        else {
            mnFormResult = SLibConstants.FORM_RESULT_OK;
            setVisible(false);
        }
    }

    private void actionCancel() {
        mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
        setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JButton jbCancel;
    private javax.swing.JButton jbOk;
    private javax.swing.JButton jbWorkingDate;
    private javax.swing.JComboBox<SFormComponentItem> jcbCompanyBranch;
    private javax.swing.JCheckBox jckIsUniversal;
    private javax.swing.JCheckBox jckIsUniversalCompany;
    private javax.swing.JCheckBox jckIsUniversalCompanyBranch;
    private javax.swing.JCheckBox jckIsUniversalEntityCh;
    private javax.swing.JCheckBox jckIsUniversalEntityPlt;
    private javax.swing.JCheckBox jckIsUniversalEntityPos;
    private javax.swing.JCheckBox jckIsUniversalEntityWh;
    private javax.swing.JFormattedTextField jftWorkingDate;
    private javax.swing.JLabel jlCashAccounts;
    private javax.swing.JLabel jlCompany;
    private javax.swing.JLabel jlCompanyBranch;
    private javax.swing.JLabel jlPlants;
    private javax.swing.JLabel jlPos;
    private javax.swing.JLabel jlUser;
    private javax.swing.JLabel jlWarehouses;
    private javax.swing.JLabel jlWorkingDate;
    private javax.swing.JList<SFormComponentItem> jltEntityCh;
    private javax.swing.JList<SFormComponentItem> jltEntityPlt;
    private javax.swing.JList<SFormComponentItem> jltEntityPos;
    private javax.swing.JList<SFormComponentItem> jltEntityWh;
    private javax.swing.JPanel jpCashAccounts;
    private javax.swing.JPanel jpPlants;
    private javax.swing.JPanel jpPos;
    private javax.swing.JPanel jpWarehouses;
    private javax.swing.JScrollPane jspCashAccounts;
    private javax.swing.JScrollPane jspPlants;
    private javax.swing.JScrollPane jspPos;
    private javax.swing.JScrollPane jspWarehouses;
    private javax.swing.JTextField jtfCompany;
    private javax.swing.JTextField jtfUser;
    private javax.swing.JTabbedPane jtpEntities;
    // End of variables declaration//GEN-END:variables

    public erp.lib.form.SFormValidation formValidate() {
        SFormValidation validation = new SFormValidation();

        for (int i = 0; i < mvFields.size(); i++) {
            if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) {
                validation.setIsError(true);
                validation.setComponent(mvFields.get(i).getComponent());
                break;
            }
        }

        if (!validation.getIsError()) {
            if (!jckIsUniversal.isSelected() && !jckIsUniversalCompany.isSelected()) {
                if (jcbCompanyBranch.getSelectedIndex() <= 0) {
                    validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jlCompanyBranch.getText() + "'.");
                    validation.setComponent(jcbCompanyBranch);
                }
                else if (!jckIsUniversalCompanyBranch.isSelected()) {
                    if (!jckIsUniversalEntityCh.isSelected() && jltEntityCh.getModel().getSize() > 0 && jltEntityCh.getSelectedIndex() == -1) {
                        jtpEntities.setSelectedIndex(0);
                        validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jtpEntities.getTitleAt(0) + "'.");
                        validation.setComponent(jltEntityCh);
                    }
                    else if (!jckIsUniversalEntityWh.isSelected() && jltEntityWh.getModel().getSize() > 0 && jltEntityWh.getSelectedIndex() == -1) {
                        jtpEntities.setSelectedIndex(1);
                        validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jtpEntities.getTitleAt(1) + "'.");
                        validation.setComponent(jltEntityWh);
                    }
                    else if (!jckIsUniversalEntityPos.isSelected() && jltEntityPos.getModel().getSize() > 0 && jltEntityPos.getSelectedIndex() == -1) {
                        jtpEntities.setSelectedIndex(2);
                        validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jtpEntities.getTitleAt(2) + "'.");
                        validation.setComponent(jltEntityPos);
                    }
                    else if (!jckIsUniversalEntityPlt.isSelected() && jltEntityPlt.getModel().getSize() > 0 && jltEntityPlt.getSelectedIndex() == -1) {
                        jtpEntities.setSelectedIndex(3);
                        validation.setMessage(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jtpEntities.getTitleAt(3) + "'.");
                        validation.setComponent(jltEntityPlt);
                    }
                }
            }
        }

        return validation;
    }

    public void reset() {
        Vector<SFormComponentItem> items = new Vector<SFormComponentItem>();

        moUser = miClient.getSessionXXX().getUser();
        mnFormResult = SLibConstants.UNDEFINED;
        mbFirstTime = true;

        // Display main user session settings:

        jtfUser.setText(miClient.getSessionXXX().getUser().getUser());
        jtfUser.setCaretPosition(0);
        jtfCompany.setText(miClient.getSessionXXX().getCompany().getCompany());
        jtfCompany.setCaretPosition(0);

        jckIsUniversal.setSelected(miClient.getSessionXXX().getIsUniversal());
        jckIsUniversalCompany.setSelected(miClient.getSessionXXX().getIsUniversalCurrentCompany());
        jckIsUniversalCompanyBranch.setSelected(false);
        jckIsUniversalEntityCh.setSelected(false);
        jckIsUniversalEntityWh.setSelected(false);
        jckIsUniversalEntityPos.setSelected(false);
        jckIsUniversalEntityPlt.setSelected(false);

        // Update company branches available to current user session:

        if (miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCurrentCompany()) {
            items = miClient.getSessionXXX().getAllCompanyBranchesAsComponentItems(true);
        }
        else {
            items = miClient.getSessionXXX().getUserCompanyBranchesAsComponentItems(true);
        }

        jcbCompanyBranch.removeItemListener(this);
        jcbCompanyBranch.removeAllItems();

        for (int i = 0; i < items.size(); i++) {
            jcbCompanyBranch.addItem(items.get(i));
        }

        SFormUtilities.locateComboBoxItem(jcbCompanyBranch, new int[] { miClient.getSessionXXX().getCurrentCompanyBranchId() });

        if (jcbCompanyBranch.getSelectedIndex() <= 0 && jcbCompanyBranch.getItemCount() == 2) {
            jcbCompanyBranch.setSelectedIndex(1);
        }

        itemStateChangedCompanyBranch();

        jcbCompanyBranch.addItemListener(this);

        // Select current company branch entities, if any:

        if (miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_CASH) == null) {
            jltEntityCh.setSelectedIndex(-1);
        }
        else {
            SFormUtilities.locateListItem(jltEntityCh,
                    miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_CASH));
        }

        if (miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_WH) == null) {
            jltEntityWh.setSelectedIndex(-1);
        }
        else {
            SFormUtilities.locateListItem(jltEntityWh,
                    miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_WH));
        }

        if (miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_POS) == null) {
            jltEntityPos.setSelectedIndex(-1);
        }
        else {
            SFormUtilities.locateListItem(jltEntityPos,
                    miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_POS));
        }

        if (miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_PLANT) == null) {
            jltEntityPlt.setSelectedIndex(-1);
        }
        else {
            SFormUtilities.locateListItem(jltEntityPlt,
                    miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(SDataConstantsSys.CFGS_CT_ENT_PLANT));
        }

        moFieldWorkingDate.setFieldValue(miClient.getSessionXXX().getWorkingDate());
    }

    public int getFormResult() {
        return mnFormResult;
    }

    public int getCurrentCompanyBranchId() {
        int id = 0;

        if (jcbCompanyBranch.getSelectedIndex() > 0) {
            id = ((int[]) ((SFormComponentItem) jcbCompanyBranch.getSelectedItem()).getPrimaryKey())[0];
        }

        return id;
    }

    public int[] getCurrentCompanyBranchEntityId(int categoryId) {
        int[] id = null;

        switch (categoryId) {
            case SDataConstantsSys.CFGS_CT_ENT_CASH:
                if (jltEntityCh.getSelectedValue() != null) {
                    id = (int[]) ((SFormComponentItem) jltEntityCh.getSelectedValue()).getPrimaryKey();
                }
                break;
            case SDataConstantsSys.CFGS_CT_ENT_WH:
                if (jltEntityWh.getSelectedValue() != null) {
                    id = (int[]) ((SFormComponentItem) jltEntityWh.getSelectedValue()).getPrimaryKey();
                }
                break;
            case SDataConstantsSys.CFGS_CT_ENT_POS:
                if (jltEntityPos.getSelectedValue() != null) {
                    id = (int[]) ((SFormComponentItem) jltEntityPos.getSelectedValue()).getPrimaryKey();
                }
                break;
            case SDataConstantsSys.CFGS_CT_ENT_PLANT:
                if (jltEntityPlt.getSelectedValue() != null) {
                    id = (int[]) ((SFormComponentItem) jltEntityPlt.getSelectedValue()).getPrimaryKey();
                }
                break;
            default:
                break;
        }

        return id;
    }

    public java.lang.String getCurrentBranch() {
        String name = "";

        if (jcbCompanyBranch.getSelectedIndex() > 0) {
            name = ((SFormComponentItem) jcbCompanyBranch.getSelectedItem()).getItem();
        }

        return name;
    }

    public java.lang.String getCurrentBranchWarehouse(int categoryId) {
        String name = "";

        switch (categoryId) {
            case SDataConstantsSys.CFGS_CT_ENT_CASH:
                name = ((SFormComponentItem) jltEntityCh.getSelectedValue()).getItem();
                break;
            case SDataConstantsSys.CFGS_CT_ENT_WH:
                name = ((SFormComponentItem) jltEntityWh.getSelectedValue()).getItem();
                break;
            case SDataConstantsSys.CFGS_CT_ENT_POS:
                name = ((SFormComponentItem) jltEntityPos.getSelectedValue()).getItem();
                break;
            case SDataConstantsSys.CFGS_CT_ENT_PLANT:
                name = ((SFormComponentItem) jltEntityPlt.getSelectedValue()).getItem();
                break;
            default:
                break;
        }

        return name;
    }

    public java.util.Date getWorkingDate() {
        return moFieldWorkingDate.getDate();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            JButton button = (JButton) e.getSource();

            if (button == jbOk) {
                actionOk();
            }
            else if (button == jbCancel) {
                actionCancel();
            }
            else if (button == jbWorkingDate) {
                actionWorkingDate();
            }
        }
    }

    @Override
    public void itemStateChanged(java.awt.event.ItemEvent e) {
        if (e.getSource() instanceof javax.swing.JComboBox) {
            JComboBox comboBox = (JComboBox) e.getSource();

            if (comboBox == jcbCompanyBranch) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    itemStateChangedCompanyBranch();
                }
            }
        }
    }
}


text:
/*
 *Ваши права на использование кода регулируются данной лицензией http://o-s-a.net/doc/license_simple_engine.pdf
*/

using System;
using System.Windows;
using System.Windows.Forms;
using MessageBox = System.Windows.MessageBox;
using TextBox = System.Windows.Forms.TextBox;

namespace OsEngine.Charts.CandleChart.Indicators
{
    /// <summary>
    /// Логика взаимодействия для Momentum.xaml
    /// </summary>
    public partial class MomentumUi
    {
        /// <summary>
        /// индикатор
        /// </summary>
        private Momentum _momentum;

        /// <summary>
        /// изменялись ли настройки индикатора
        /// </summary>
        public bool IsChange;

        /// <summary>
        /// конструктор
        /// </summary>
        public MomentumUi(Momentum momentum)
        {
            InitializeComponent();
            _momentum = momentum;

            TextBoxLenght.Text = _momentum.Nperiod.ToString();

            HostColorBase.Child = new TextBox();
            HostColorBase.Child.BackColor = _momentum.ColorBase;
            CheckBoxPaintOnOff.IsChecked = _momentum.PaintOn;
            CandleBox.Items.Add(PriceTypePoints.Close);
            CandleBox.Items.Add(PriceTypePoints.Open);
            CandleBox.Items.Add(PriceTypePoints.High);
            CandleBox.Items.Add(PriceTypePoints.Low);

            CandleBox.SelectedItem = _momentum.TypePoint;
        }

        /// <summary>
        /// кнопка принять
        /// </summary>
        private void ButtonAccept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (Convert.ToInt32(TextBoxLenght.Text) <= 0)
                {
                    throw new Exception("error");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Процесс сохранения прерван. В одном из полей недопустимые значения");
                return;
            }

            _momentum.ColorBase = HostColorBase.Child.BackColor;
            _momentum.Nperiod = Convert.ToInt32(TextBoxLenght.Text);
            _momentum.PaintOn = CheckBoxPaintOnOff.IsChecked.Value;
            Enum.TryParse(CandleBox.Text, out _momentum.TypePoint);

            _momentum.Save();

            IsChange = true;
            Close();
        }

        /// <summary>
        /// кнопка настроить цвет
        /// </summary>
        private void ButtonColor_Click(object sender, RoutedEventArgs e)
        {
            ColorDialog dialog = new ColorDialog();
            dialog.Color = HostColorBase.Child.BackColor;
            dialog.ShowDialog();
            HostColorBase.Child.BackColor = dialog.Color;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'wdolowicz'
from model.group import Group
from model.contact import Contact

def test_group_list(app, db):
    ui_list = app.group.get_group_list()
    def clean(group):
        return Group(id=group.id, name=group.name.strip())
    db_list = map(clean, db.get_group_list())
    assert sorted(ui_list, key=Group.id_or_max) == sorted(db_list, key=Group.id_or_max)

def test_contact_list(app, db):
    ui_list = app.contact.get_contact_list()
    def clean(contact):
        return Contact(id=contact.id, firstname=contact.firstname.strip(), lastname=contact.lastname.strip())
    db_list = map(clean, db.get_contact_list())
    assert sorted(ui_list, key=Contact.id_or_max) == sorted(db_list, key=Contact.id_or_max)


text:
---
uid: SolidEdgeConstants.BlockLabelOriginLocationConstants.igBlockLabelBottomCenter
summary: Block Label Position Bottom Center
remarks:
---


text:
Ext.define('Ozone.components.dashboard.Dashboard', {
    extend: 'Ext.panel.Panel',
    alias: ['widget.dashboard', 'widget.Ozone.components.dashboard.Dashboard'],

    activeWidget: null,

    plugins: [
        new Ozone.plugins.Dashboard()
    ],

    dashboardContainer: null,
    eventingContainer: null,
    widgetLauncher: null,
    addWidgetContainer: null,
    widgetStateHandler: null,
    windowGroup: null,
    widgetStateContainer: null,
    type: null,
    configRecord: null,
    config: {
        "name": "Default Dashboard",
        "alteredByAdmin": "false",
        "user": null,
        "isdefault": false,
        "locked": false,
        "guid": null,
        //todo remove this in favor of using the actual store
        "state": null
    },
    hideMode: 'visibility',
    cls: 'dashboard',

    // flag to determine whether or not a save is already in progress
    saveLock: false,

    // flag to determine whether changes have been made since last save
    hasChanged: false,

    dontSave: false,

    /**
     * datastore for config.state data
     */
    stateStore: null,
    widgetStore: null,

    widgetIframeDelay: 200,

//    defaultSettings: {},

    // array of panes
    panes: null,
    layout: 'fit',
    widgetCls: 'widgetwindow',

    buildItemsArray: function(cfg) {
        if(!cfg || !cfg.items)
            return;

        if(cfg.items.length === 0) {
            //TODO choose default by checking what layout types are available
            if(!cfg.paneType) {
                cfg.paneType = 'tabbedpane';
            }

            cfg.xtype = cfg.paneType;
        }
        else {

            if(cfg.xtype === "dashboarddesignerpane") {
                cfg.xtype = 'container';
                cfg.layout = "fit";
            }

            for(var i = 0, len = cfg.items.length; i < len; i++) {
                this.buildItemsArray(cfg.items[i]);
            }

        }

        return cfg;
    },

    initComponent: function() {
        var me = this;

        // TODO remove after support for old dashboard is added
        if(!me.configRecord.get('layoutConfig')) {
            me.configRecord.set('layoutConfig', {
                cls: null,
                height: "100%",
                items: [],
                paneType: null,
                xtype: "desktoppane"
            });
        }

        me.items = me.buildItemsArray(me.configRecord.get('layoutConfig')) || [];

        //make sure the store is registered under the guid
        if (this.stateStore != null && this.stateStore.storeId == null) {
            this.stateStore.storeId = this.guid;
            Ext.data.StoreManager.register(this.stateStore);
        }

        this.callParent(arguments);

        this.addEvents(
                'beforeserversave',
                'serversave',
                'widgetStartDrag',
                'widgetStopDrag',
                OWF.Events.Widget.BEFORE_LAUNCH,
                OWF.Events.Widget.AFTER_LAUNCH
        );

        this.enableBubble([OWF.Events.Widget.BEFORE_LAUNCH, OWF.Events.Widget.AFTER_LAUNCH]);

        this.on('activate', this.onActivate,this);
        this.on('deactivate', this.onDeActivate,this);

        if(!this.stateStore) {
            this.stateStore = Ext.create('Ozone.data.StateStore');
        }

        this.stateStore.on({
            add: {
                fn: function(){
                    if (this.rendered) {
                        this.hasChanged = true;
                   }
                },
                scope: this
            },
            update: {
                fn: function(){
                    if (this.rendered) {
                        this.hasChanged = true;
                    }
                },
                scope: this
            },
            remove: {
                fn: function(){
                    if (this.rendered) {
                        this.hasChanged = true;
                    }
                },
                scope: this
            },
            clear: {
                fn: function(){
                    if (this.rendered) {
                        this.hasChanged = true;
                    }
                },
                scope: this
            }
        });

        me.on(OWF.Events.Widget.BEFORE_LAUNCH, me.onBeforeWidgetLaunch, me);
        me.on('afterlayout', me.afterDashboardLayout, me, { single: true });
        me.on('beforedestroy', me.cleanup, me);
    },

    afterDashboardLayout: function() {
        var me = this,
            pane,
            allWidgetsDeferreds = [];

        this.panes = this.query('pane');

        // launch previously opened widgets
        for(var i = 0, len = this.panes.length ; i < len ; i++) {
            pane = this.panes[i];
            pane.widgetStateContainer = this.widgetStateContainer;

            //todo why not a concat here?
            allWidgetsDeferreds.push.apply( allWidgetsDeferreds, pane.launchPreviouslyOpenedWidgets() );
        }

        $.when(allWidgetsDeferreds).then(function() {
            me.fireEvent(OWF.Events.Dashboard.COMPLETE_RENDER, me);
            if(OWF.Mask) {
                OWF.Mask.hide();
                OWF.Mask = null;
            }

            //      loop through dashboard stateStore and validate intentConfig
            //      check intentConfig and remove any widgets that don't exist
            var items = me.stateStore.data.items;

            for (var i = 0, len = items.length; i < len; i++) {
                var rec = items[i];
                var intentConfig = rec.get('intentConfig');
                for (var intent in intentConfig) {
                    var destIds = intentConfig[intent];
                    var newDestIds = [];
                    for (var j = 0; j < destIds.length; j++) {
                        var id = Ozone.util.parseJson(destIds[j]).id;
                        if (me.stateStore.findExact('uniqueId',id) > -1) {
                            newDestIds.push(destIds[j]);
                        }
                    }
                    if (newDestIds.length > 0) {
                        intentConfig[intent] = newDestIds;
                    }
                    else {
                        delete intentConfig[intent];
                    }
                }
            }

            //console.timeEnd('page');
            console.timeEnd('initload');
        });
    },

    enableWidgetDragAndDrop: function () {
        this.dropZone = this.dropZone || new Ext.dd.DropZone(this.getEl(), {

            ddGroup: 'widgets',

            getTargetFromEvent: function(e) {
                return e.getTarget('.paneshim');
            },

            // On entry into a target node, highlight that node.
            onNodeEnter : function(target, dd, e, data) {
                Ext.fly(target).addCls('highlight-dashboard-designer-drop');
            },

            // On exit from a target node, unhighlight that node.
            onNodeOut : function(target, dd, e, data) {
                Ext.fly(target).removeCls('highlight-dashboard-designer-drop');
            },

            // While over a target node, return the default drop allowed class which
            // places a "tick" icon into the drag proxy.
            onNodeOver : function(target, dd, e, data) {
                return Ext.dd.DropZone.prototype.dropAllowed;
            },

            // On node drop we can interrogate the target to find the underlying
            // application object that is the real target of the dragged data.
            onNodeDrop : this.launchWidgets
        });

        this.enableWidgetMove();
    },

    disableWidgetDragAndDrop: function () {
        this.disableWidgetMove();
        this.cleanup();
    },

    cleanup: function() {
        // if dashboard isn't rendered, dropZone won't be setup
        if(this.dropZone) {
            this.dropZone.unreg();
            delete this.dropZone;
        }
    },

    launchWidgets: function(target, dd, coordinates, data) {
        var targetPaneId = target.id,
            targetPaneEl, offsets,
            targetPane = Ext.getCmp(targetPaneId),
            x, y;

        if( coordinates ) {
            x = coordinates['x'] ? coordinates['x'] : coordinates.getX();
            y = coordinates['y'] ? coordinates['y'] : coordinates.getY();
        }

        if(!targetPane || !targetPane.isXType('pane')) {
            targetPaneEl = Ext.get(target).up('.pane');
            if(targetPaneEl) {
                targetPane = Ext.getCmp(targetPaneEl.id);
            }
        }

        if(targetPane && targetPane.isXType('pane')) {
            targetPane = Ext.getCmp(targetPane.id);

            if(coordinates) {
                offsets = targetPane.el.getOffsetsTo(Ext.getBody());
                targetPane.launchWidgets(data.widgetModel, x - offsets[0], y - offsets[1], 0);
            }
            else {
                targetPane.launchWidgets(data.widgetModel);
            }
            return true;
        }

        return false;
    },

    onBeforeWidgetLaunch: function(pane, widgetModel, launchData) {
        var stateStore = this.stateStore,
            instanceId = widgetModel.get('uniqueId') || guid.util.guid(),
            isSingleton = widgetModel.get('singleton'),
            isBackground = widgetModel.get('background'),
            stateModel = stateStore.findRecord('widgetGuid', widgetModel.get('widgetGuid')),
            isAlreadyLaunched = !!stateModel,
            widget;

        if(isSingleton && isAlreadyLaunched) {
            pane.activateWidget(Ext.getCmp(stateModel.get('uniqueId')));
            return false;
        }

        if(isBackground) {
            widget = this.add({
                xtype: 'widgetiframe',
                style: 'display: none',
                isWidget: true,
                iframeProperties: OWF.Container.Eventing.getIframeProperties(
                    widgetModel.get('url'), instanceId, widgetModel.data, pane.id, launchData, this.configRecord.get('locked')
                )
            });

            var widgetState = {
                'uniqueId': instanceId,
                'dashboardGuid': this.id,
                'paneGuid': pane.id,
                'widgetGuid': widgetModel.get('widgetGuid'),
                'statePosition': ++pane.statePositionCount,
                'name': widgetModel.get('name'),
                'active': false,
                'width': widgetModel.get('width'),
                'height': widgetModel.get('height'),
                'x': 0,
                'y': 0,
                'zIndex': 0,
                'minimized': false,
                'maximized': false,
                'pinned': false,
                'collapsed': false,
                'columnPos': 0,
                'columnOrder': "",
                'buttonId': null,
                'buttonOpened': false,
                'region': "",
                'singleton': widgetModel.get('singleton'),
                'background': widgetModel.get('background')
            };

            // workaround for now
            // only way widgets get added to dashboard store is if 'add' event fires on pane's store
            // which it doesn't for background widgets as they dont go through state changes
            // so remove and add so that same record gets added to both stores
            var recordIndex = pane.stateStore.findExact('uniqueId', instanceId);
            if(recordIndex !== -1) {
                pane.stateStore.removeAt(recordIndex);
            }
            pane.stateStore.add(widgetState);

            //console.log('Launching background widget', widgetState.name)

            pane.fireEvent(OWF.Events.Widget.AFTER_LAUNCH, widget, widgetModel);
            return false;
        }

        if(!pane._launchingPreviouslyOpenedWidgets && !pane._reorderingWidgets && pane.dashboard.configRecord.get('locked')) {
            pane.launchFloatingWidget(widgetModel, null, null, instanceId, launchData);
            return false;
        }

        return true;
    },

    moveWidgetToPane: function(evt, sourcePane, targetPane, widget) {
        var me = this,
            widgetModel = widget.model,
            x = evt.getX(),
            y = evt.getY();

        if(!sourcePane || !targetPane || sourcePane === targetPane || this.configRecord.get("locked"))
            return;

        // use widget defination model instead of using state model
        // so that it gets a new instance id
        widgetModel = this.widgetStore.findRecord('widgetGuid', widgetModel.get('widgetGuid'));

        function doIt() {
            if(targetPane.isXType('fitpane') && targetPane.items.length > 0) {
                targetPane.confirmReplaceWidget(widget.id, widget.title, function() {
                    targetPane.clearWidgets(false);
                    targetPane.items.clear();
                    move();
                });
            }
            else {
                move();
            }
        }

        function move () {
            var pane = targetPane,
                widgetStateModelData = pane.cloneWidgetDataForTransfer(widget);

            widget.on('destroy', function () {
                me.launchWidgets(pane, null, {x: x, y: y}, {widgetModel: widgetStateModelData});
            });
            widget.destroy();
        }

        // delay for floating widgets so dragend events could be handled
        widget.isFloating() ? setTimeout(doIt, 500) : doIt();
    },

    onDestroy: function() {
        if (this.stateStore != null) {
            this.stateStore.destroyStore();
            this.stateStore = null;
        }
        this.callParent(arguments);
    },

    /**
    * @description Launches a widget instance based on the specified widget guid.
    * @member Ozone.layout.AccordionWindowManager
    * @param JSON object specifying the widget guid and an option launchOnlyIfClosed param.
    * @returns JSON object specifying success/failure, an error message, and the uniqueId of the widget that was launched.
    */
    launchWidgetInstance: function(sender, launchConfig) {
        var launchWidget = null,
            specifiedWidget = null,
            responseObj,
            pane = Ext.getCmp(sender.id).pane;

        //find the widget with the specified guid
        if (launchConfig.guid != null) {
            specifiedWidget = this.widgetStore.getById(launchConfig.guid);
        }
        else if (launchConfig.universalName != null){
            var index = this.widgetStore.findExact('universalName',launchConfig.universalName);
            if (index > -1) {
                specifiedWidget = this.widgetStore.getAt(index);
            }
        }

        // If the specified widget wasn't found return failure and error message
        if (specifiedWidget == null) {
            // Return failure and error message
            responseObj = {
                error: true,
                newWidgetLaunched: false,
                message: "The specified widget wasn't found."
            }
        }
        else {

            //make a copy so we don't alter the widgetdef if we change the title
            specifiedWidget = specifiedWidget.copy();

            //check if we need to change the widget's name
            if (launchConfig.title != null) {
                //regex was not used simply replace the title
                if (launchConfig.titleRegex == null) {
                    specifiedWidget.data.name = launchConfig.title;
                }
                else {
                    //check if a regex string by using a regex
                    var matches = launchConfig.titleRegex.match(/^\/(.*)\/(.*)$/);

                    //there are 2 capture groups so if the above regex matches
                    //matches[0] will be the full string
                    //matches[1] will be the titleRegex pattern
                    //matches[2] will be any flags
                    if (matches != null && matches[1] != '') {
                        //use regex string to alter the title
                        specifiedWidget.data.name = specifiedWidget.data.name.replace(
                            new RegExp(matches[1],matches[2]),launchConfig.title);
                    }
                }
            }

            // Determine which pane widget was last opened in
            if(!pane.isXType('fitpane')) {
                if (this.panes && this.panes.length > 1) {
                    var widgetState, latest, latestPane;
                    for (var i=0, len=this.panes.length; i<len; i++) {
                        var p = this.panes[i];
                        if(!p.isXType('fitpane')) {
                            if (p.defaultSettings && p.defaultSettings.widgetStates) {
                                widgetState = p.defaultSettings.widgetStates[specifiedWidget.data.widgetGuid];
                                if (widgetState && widgetState.timestamp) {
                                    if (!latest || widgetState.timestamp > latest) {
                                        latest = widgetState.timestamp;
                                        latestPane = p;
                                    }
                                }
                            }
                        }
                    }

                    // If a pane is found, launch in that one
                    if (latestPane) { pane = latestPane; }
                }
            }

            launchConfig.guid = specifiedWidget.data.widgetGuid;

            if (launchConfig.launchOnlyIfClosed) {
                // Cycle through all widget instances
                for (var i=0, len=this.stateStore.getCount(); i<len; i++) {
                    var stateWidget = this.stateStore.getAt(i);

                    if (stateWidget !=null && stateWidget.get('widgetGuid') == launchConfig.guid) {
                        launchWidget = stateWidget;

                        if (!specifiedWidget.get('background')) {
                            this.handleAlreadyLaunchedWidget(stateWidget.data);
                        }

                        // Return failure, error message, and the uniqueId of the widget instance
                        responseObj = {
                            error: false,
                            newWidgetLaunched: false,
                            message: "An instance of the specified widget already exists.",
                            uniqueId: stateWidget.get('uniqueId')
                        };

                        break;
                    }
                }
            }

            if (launchWidget == null) {
                var uniqueId = guid.util.guid();
                    if(pane.fireEvent( OWF.Events.Widget.BEFORE_LAUNCH, pane, specifiedWidget, launchConfig.data ) !== false) {
                        pane.launchWidget(specifiedWidget, null, null, uniqueId, launchConfig.data, true);
                    }

                // Return success and the uniqueId of the widget instance
                responseObj = {
                    error: false,
                    newWidgetLaunched: true,
                    uniqueId: uniqueId
                };
            }
        }

        return responseObj;
    },

    /**
     * @description Handles a request made from a widget.
     * @member Ozone.components.dashboard.Dashboard
     * @param config JSON object containing the function to call and the params required for that function.
     */
    handleWidgetRequest: function (config) {
        switch (config.fn) {
            case 'getWidgetState':
                return this.getWidgetState(config.params.guid);
            case 'getWidgetStateEvents':
                return this.getWidgetStateEvents(config.params.guid);
            case 'addStateEventListeners':
                return this.addWidgetStateEvents('listen', config.params.guid, config.params.events);
            case 'addStateEventOverrides':
                return this.addWidgetStateEvents('override', config.params.guid, config.params.events);
            case 'removeStateEventListeners':
                return this.removeWidgetStateEvents('listen', config.params.guid, config.params.events);
            case 'removeStateEventOverrides':
                return this.removeWidgetStateEvents('override', config.params.guid, config.params.events);
            case 'closeWidget':
                return this.closeWidget(config.params.guid);
            case 'activateWidget':
                return this.activateWidget(config.params.guid);
            case 'getWidgetConfig':
                var data = this.getWidgetState(config.params.guid);
                return Ext.JSON.encode(data);
            case 'refreshWidgetLaunchMenu':
                return this.refreshWidgetLaunchMenu();
            default:
                break;
        }
    },

    /**
     * @description Gets all events registered on a widget.
     * @member Ozone.components.dashboard.Dashboard
     * @param cmpId Id of the widget.
     */
    getWidgetStateEvents: function(cmpId) {
        // get component
        var widget = Ext.getCmp(cmpId);
        var eventList = [];

        if(widget) {
            for (var item in widget.events) {
                eventList.push(item);
            }
            return eventList.sort();
        }
        return eventList;
    },

    /**
     * @description Adds custom state event handlers to a widget.
     * @member Ozone.components.dashboard.Dashboard
     * @param eventAction Action to take when an event is received.  Valid values are "listen" and "override".
     * @param guid Id of the widget
     * @param events Array of events
     */
    addWidgetStateEvents: function(eventAction, guid, events) {
        // get widget by guid
        var widget = Ext.getCmp(guid),
            eventName;

        function stateEventHandler(widget, eventAction, eventName) {
            return function() {
                return widget.handleStateEvent(eventAction, eventName);
            };
        }

        if (widget) {

            // default to all events
            if (events == null || events == undefined || events.length == 0) {
                events = this.getWidgetStateEvents(guid);
            }

            // set event listener for specified events
            for (var i = 0, len = events.length; i < len; i++) {

                eventName = events[i];

                if(widget.tab && eventName.indexOf('close') > -1) {

                    if(eventAction === "override") {
                        widget.tab.purgeListener(eventName);
                    }
                    widget["on_" + eventName] = stateEventHandler(widget, eventAction, eventName);
                    widget.tab.on(eventName, widget["on_" + eventName]);
                }
                else {
                    if(eventAction === "override") {
                        widget.purgeListener(eventName);
                    }
                    widget["on_" + eventName] = stateEventHandler(widget, eventAction, eventName);
                    widget.on(eventName, widget["on_" + eventName]);
                }
            }

            return true;
        }

        return false;
    },

    /**
     * @description Removes custom state event handlers from a widget.
     * @member Ozone.components.dashboard.Dashboard
     * @param eventAction Action to take when an event is received.  Valid values are "listen" and "override".
     * @param guid Id of the widget
     * @param events Array of events
     */
    removeWidgetStateEvents: function(eventAction, guid, events) {
        // get widget by guid
        var widget = Ext.getCmp(guid),
            eventName, cmp;

        if (widget) {
            // default to all events
            if (events == null || events == undefined || events.length == 0) {
                events = this.getWidgetStateEvents(guid);
            }

            // set event listener for specified events
            for (var i = 0; i < events.length; i++) {
                eventName = events[i];
                cmp = widget; // reset cmp to widget

                if(widget.tab && eventName.indexOf('close') > -1) {
                    cmp = widget.tab;
                }
                if(cmp.hasListener(eventName)) {
                    cmp.un(eventName, widget["on_" + eventName]);
                }
                if (eventAction == "override") {
                    cmp.restoreListener(eventName);
                }
            }

            return true;
        }

        return false;
    },

    /**
     * @description Activates a widget. This method should be overridden by each dashboard that support activating a widget.
     * @member Ozone.components.dashboard.Dashboard
     * @param params guid of the widget to activate.
     */
    activateWidget: function(widgetInstanceId) {
        var widget = Ext.getCmp(widgetInstanceId);
        if(widget) {
            if(widget.floatingWidget) {
                widget.minimized === true ? widget.restoreFromMinimize(true) : widget.focus(false, false, true, true);

                this.updateActiveWidget(widget);
                return true;
            }
            else {
                return widget.pane.activateWidget(widget);
            }
        }
        return false;
    },

    /**
     * @description Closes a widget.  This method should be overridden by each dashboard type.
     * @member Ozone.components.dashboard.Dashboard
     * @param params guid of the widget to close.
     */
    closeWidget: function(guid){
        var widget = Ext.getCmp(guid);
        if (widget !== undefined) {
            widget.close();
            return true;
        }
        return false;
    },

    /**
     * @description Closes a widget.  This method should be overridden by each dashboard type.
     * @member Ozone.components.dashboard.Dashboard
     * @param params JSON object containing the guid of the widget to close.
     */
    refreshWidgetLaunchMenu: function () {
        var widgetLauncher = Ext.getCmp('widget-launcher');
        widgetLauncher.refresh();
    },

    /**
    * @description Defines what to do when launchWidgetInstance method was called on a widget
    * that is already launched and launchOnlyIfClosed is set to true.  This method should be
    * overridden by each dashboard type.
    * @member Ozone.components.dashboard.Dashboard
    * @param widget The widget instance in state
    */
    handleAlreadyLaunchedWidget: function (widgetData) {
        var widgetCmp = Ext.getCmp(widgetData.uniqueId);

        this.fireEvent(OWF.Events.Widget.AFTER_LAUNCH, widgetCmp, widgetCmp.model, true);

        Ext.getCmp(widgetData.paneGuid).activateWidget(widgetCmp);
    },

    /**
    * @description Returns the JSON representation of the specified widget.
    * @member Ozone.components.dashboard.Dashboard
    * @param guid Id of the specified widget
    * @returns Layout configuration object in JSON format.
    */
    getWidgetConfig: function (guid) {
       var rec = this.widgetStore.getById(guid);
       return rec ? rec.data : null;
    },

    /**
     * @description Returns the JSON representation of the specified widget instance's state.
     * @member Ozone.components.dashboard.Dashboard
     * @param guid Id of the specified widget
     * @returns Layout configuration object in JSON format.
     */
    getWidgetState: function (guid) {
        var widget = Ext.getCmp(guid),
            state, storeState, size;

        if(widget) {
            size  = widget.getSize();
            state = widget.getState();

            // use actual width and height if widget is maximized
            if(widget.maximized) {
                Ext.apply(state, {
                    height: size.height,
                    width: size.width
                });
            }
        }
        else {
            storeState = this.stateStore.getById(guid);
            state = storeState ? storeState.data : {};
        }

        delete state.launchData;
        return state;
     },

    /**
    * @description Removes the specified window configuration from state.
    * @member Ozone.components.dashboard.Dashboard
    * @param windowId Id of window to be removed.
    * @param dm DashboardMgmt object.
    * @returns None.
    */
    removeState: function(windowId) {
        this.stateStore.remove(this.stateStore.getById(windowId));
    },

    initNewWidget: function(widget) {
        widget.on('close', function() {
            this.updateActiveWidget(null,false);
        }, this);

        widget.on("statesave", function() {
            // For each record in state, add/update value in dashboard defaultStates object
            this.defaultSettings.widgetStates = this.defaultSettings.widgetStates || {};

            var items = this.stateStore.data.items;

            for (var i = 0, len = items.length; i < len; i++) {
                var record = items[i];
                this.defaultSettings.widgetStates[record.data.widgetGuid] = {
                    "x": record.data.x,
                    "y": record.data.y,
                    "height": record.data.height,
                    "width": record.data.width,
                    "columnPos": record.data.columnPos
                };
            }
        }, this);
    },

    initDashboard: function(){
        //register with windowmanager
        this.widgetLauncher.registerWindowManager(this);

        this.addWidgetContainer.registerWindowManager(this);

        //register with windowmanager
        this.widgetStateContainer.registerWindowManager(this);

        //set statestore in the state provider
        var sp = Ext.state.Manager.getProvider();
        if (sp.setStore && typeof sp.setStore === 'function') {
            sp.setStore(this.stateStore);
        }
        document.title = this.config.name;
    },

    // private
    onRender: function(ct, position){
        this.initDashboard();
        this.callParent(arguments);
    },

    onActivate: function(cmp) {
        var banner = this.dashboardContainer.getBanner();

        this.initDashboard();

        if (this.configRecord.get('locked')) {
            banner.disableLaunchMenu();
        } else {
            banner.enableLaunchMenu();
        }

        // hide all widgets to fire hide events on Widget State
        var items = this.stateStore.data.items;

        for (var i = 0, len = items.length; i < len; i++) {
            var rec = items[i],
                uniqueId = rec.get('uniqueId'),
                cmp = Ext.getCmp(uniqueId);

            //cmp.show();
            //cmp.fireEvent('show');
            var onShow;
            if(cmp && (onShow = cmp['on_show'])) {
                onShow();
            }
        }
    },

    onDeActivate: function(cmp){
        this.saveToServer();
        // hide all widgets to fire hide events on Widget State
        var items = this.stateStore.data.items;

        for (var i = 0, len = items.length; i < len; i++) {
            var rec = items[i],
                uniqueId = rec.get('uniqueId'),
                cmp = Ext.getCmp(uniqueId);

            //cmp.hide();
            //cmp.fireEvent('hide');
            var onHide;
            if(cmp && (onHide = cmp['on_hide'])) {
                onHide();
            }
        }
    },

    getJson: function() {
        var json = this.configRecord.data,
            pane,
            panes = this.query('pane'),
            paneWidgets;

        for(var i = 0, len = panes.length ; i < len ; i++) {
            pane = panes[i];

            pane.initialConfig.widgets = pane.getStatesOfAllWidgets();
            pane.initialConfig.defaultSettings = pane.defaultSettings;
        }

        json.state = [];
        json = Ext.clone(json);

        return json;
    },

    saveToServer: function(sync, force, saveAsNew, successCallback, failureCallback) {
        //save state
        if (this.configRecord && this.stateStore && !this.dontSave) {
            if (this.hasChanged || this.configRecord.dirty || force) {
                var dash = this;
                if (this.fireEvent('beforeserversave', this) !== false) {
                    if (!this.saveLock) {
                        this.saveLock = true;
                        Ozone.pref.PrefServer.createOrUpdateDashboard({
                            json: this.getJson(),
                            saveAsNew: (saveAsNew === true),
                            onSuccess: function(){
                                dash.configRecord.commit();
                                dash.hasChanged = false;
                                dash.fireEvent('serversave', dash, true);
                                dash.saveLock = false;
                                if(successCallback) {
                                    successCallback();
                                }
                            },
                            onFailure: function(){
                                dash.fireEvent('serversave', dash, false);
                                dash.saveLock = false;
                                if(failureCallback) {
                                    failureCallback();
                                }
                            },
                            async: !sync
                        });
                    }
                }
            }
        }
    },

    shimPanes: function() {
        var panes = this.panes;
        for (var i = 0, len = panes.length; i < len; i++) {
            panes[i].shim();
        }
    },

    unshimPanes: function() {
        var panes = this.panes;
        for (var i = 0, len = panes.length; i < len; i++) {
            panes[i].unshim();
        }
    },

    //Enables widget move to all but the sourcePane that originated the drag
    enableWidgetMove: function(sourcePane) {
        var panes = this.panes;

        for (var i = 0, len = panes.length; i < len; i++) {
            if(this.configRecord.get("locked") === true) {
                panes[i].disableWidgetMove();
            }
            else if(sourcePane) {
                if(panes[i].id !== sourcePane.id) {
                    panes[i].enableWidgetMove();
                }
                else {
                    //Still enable shim, just don't do highlight on mouseover
                    panes[i].shim();
                }
            }
            else {
                //Originated from launch menu, so enable all panes for drop
                panes[i].enableWidgetMove();
            }
        }
    },

    disableWidgetMove: function() {
        var panes = this.panes;

        if (!panes)
            return;

        for (var i = 0, len = panes.length; i < len; i++) {
            panes[i].disableWidgetMove();
        }
    },

    getViewPort: function() {
        return Ext.getCmp(this.viewportId);
    },

    getSite: function() {
        //find root context
        var baseContextPath = window.location.pathname;
        var baseContextPathRegex = /^(\/[^\/]+\/).*$/i;
        var matches = baseContextPath.match(baseContextPathRegex);
        if (matches && matches[1] && matches[1].length > 0) {
            baseContextPath = matches[1];
            //remove final /
            baseContextPath = baseContextPath.substring(0, baseContextPath.length - 1);
        }
        else {
            baseContextPath = '';
        }

        return window.location.protocol + "//" + window.location.host + (baseContextPath.charAt(0) != '/' ? ('/' + baseContextPath) : baseContextPath);
    },

    updateActiveWidget: function(widget, notify) {
        //console.log('updating active widget');
        if(!widget) {
            this.activeWidget = null;
            return;
        }

        if (this.activeWidget === widget && widget.iframeReady) {
            gadgets.rpc.call(widget.getIframeId(), '_widget_activated');
        }

        if(this.activeWidget && this.activeWidget !== widget) {
            this.activeWidget.active = false;
            this.activeWidget.removeCls(this.activeWidget.focusCls);

            if(this.activeWidget.iframeReady && notify !== false) {
                this.activeWidget._activated = false;
                var deactivatedWidgetId = this.activeWidget.getIframeId();
                if (deactivatedWidgetId) {
                    gadgets.rpc.call(deactivatedWidgetId, '_widget_deactivated');
                }
            }
        }

        this.activeWidget = widget;

        if(widget && notify !== false && this.activeWidget.iframeReady && !widget._activated) {
            widget.active = true;
            widget._activated = true;
            gadgets.rpc.call(widget.getIframeId(), '_widget_activated');
        }

    },

    getActiveWidget: function(id) {
        return Ext.getCmp(id) || this.activeWidget;
    },

    getViewHeight: function() {
        return Ext.getCmp('dashboardCardPanel').getHeight();
    },

    getViewWidth: function() {
        return Ext.getCmp('dashboardCardPanel').getWidth();
    },

    moveWidgetUp: function(id) {
        var widget = this.getActiveWidget(id);
        if(widget && widget.initialConfig.floatingWidget) {
            widget.pane.moveFloatingWidgetUp(widget);
        }
        else {
            widget && widget.pane.moveWidgetUp(widget);
        }
    },

    moveWidgetRight: function(id) {
        var widget = this.getActiveWidget(id);
        if(widget && widget.initialConfig.floatingWidget) {
            widget.pane.moveFloatingWidgetRight(widget);
        }
        else {
            widget && widget.pane.moveWidgetRight(widget);
        }
    },

    moveWidgetDown: function(id) {
        var widget = this.getActiveWidget(id);
        if(widget && widget.initialConfig.floatingWidget) {
            widget.pane.moveFloatingWidgetDown(widget);
        }
        else {
            widget && widget.pane.moveWidgetDown(widget);
        }
    },

    moveWidgetLeft: function(id) {
        var widget = this.getActiveWidget(id);
        if(widget && widget.initialConfig.floatingWidget) {
            widget.pane.moveFloatingWidgetLeft(widget);
        }
        else {
            widget && widget.pane.moveWidgetLeft(widget);
        }
    }
});


text:
package com.echsylon.kraken.request;

import com.echsylon.kraken.internal.CallCounter;

/**
 * This class can build a request that tries to cancel a previously placed
 * withdrawal of funds.
 * <p>
 * For further technical details see Kraken API documentation at:
 * https://www.kraken.com/help/api
 */
@SuppressWarnings("WeakerAccess")
public class WithdrawCancellationRequestBuilder extends RequestBuilder<Boolean, WithdrawCancellationRequestBuilder> {

    /**
     * Creates a new request builder.
     *
     * @param callCounter The request call counter. May be null.
     * @param baseUrl     The base url of the request.
     * @param key         The user API key.
     * @param secret      The corresponding secret.
     */
    public WithdrawCancellationRequestBuilder(final CallCounter callCounter,
                                              final String baseUrl,
                                              final String key,
                                              final byte[] secret) {

        super(1, callCounter, key, secret, baseUrl,
                "POST", "/0/private/WithdrawCancel",
                Boolean.class);
    }

    /**
     * Sets the one time password to use when performing the request.
     *
     * @param oneTimePassword The password.
     * @return This request builder instance allowing method call chaining.
     */
    public WithdrawCancellationRequestBuilder useOneTimePassword(final String oneTimePassword) {
        data.put("otp", oneTimePassword);
        return this;
    }

    /**
     * Sets the reference id request property.
     *
     * @param referenceId The reference id of the withdrawal to cancel.
     * @return This request builder instance allowing method call chaining.
     */
    public WithdrawCancellationRequestBuilder useReferenceId(final String referenceId) {
        data.put("refid", referenceId);
        return this;
    }

}


text:
// MIT License Copyright 2020 (c) David Melendez. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ElCamino.AspNetCore.Identity.AzureTable.Helpers;
using ElCamino.AspNetCore.Identity.AzureTable.Tests.Fakes;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using NuGet.Frameworks;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;

namespace ElCamino.AspNetCore.Identity.AzureTable.Tests
{
    public class KeyHelperTests
    {
        private readonly DefaultKeyHelper _defaultKeyHelper = new();
        private readonly SHA256KeyHelper _sha256KeyHelper = new();
        private readonly HashTestKeyHelperFake _fakeKeyHelper = new();
        protected readonly ITestOutputHelper _output;

        public KeyHelperTests(ITestOutputHelper output)
        {
            _output = output;
        }

        [Theory]
        [InlineData("HashTestKeyHelperFake _fakeKeyHelper = new HashTestKeyHelperFake();")]
        [InlineData("thisIs Some Test Text123323 for Hashing")]
        [InlineData("{F1FFCC02-83E0-4347-8377-72D6007E3D93}")]
        public void SHA1FormatBackwardCompat(string textToHash)
        {
            _output.WriteLine($"plain text: {textToHash}");
            var sw = new Stopwatch();
            sw.Start();
            string expected = _fakeKeyHelper.ConvertKeyToHashBackwardCompatSHA1(textToHash);
            sw.Stop();
            _output.WriteLine($"expected {sw.Elapsed.TotalMilliseconds} ms: {expected}");

            sw.Reset();
            sw.Start();
            string returned = _defaultKeyHelper.ConvertKeyToHash(textToHash);
            sw.Stop();
            _output.WriteLine($"returned {sw.Elapsed.TotalMilliseconds} ms: {returned}");
            Assert.Equal(expected, returned, StringComparer.InvariantCulture);
        }

        [Theory]
        [InlineData("HashTestKeyHelperFake _fakeKeyHelper = new HashTestKeyHelperFake();")]
        [InlineData("thisIs Some Test Text123323 for Hashing")]
        [InlineData("{F1FFCC02-83E0-4347-8377-72D6007E3D93}")]
        public void SHA256FormatBackwardCompat(string textToHash)
        {
            _output.WriteLine($"plain text: {textToHash}");
            var sw = new Stopwatch();
            sw.Start();
            string expected = _fakeKeyHelper.ConvertKeyToHashBackwardCompatSHA256(textToHash);
            sw.Stop();
            _output.WriteLine($"expected {sw.Elapsed.TotalMilliseconds} ms: {expected}");

            sw.Reset();
            sw.Start();
            string returned = _sha256KeyHelper.ConvertKeyToHash(textToHash);
            sw.Stop();
            _output.WriteLine($"returned {sw.Elapsed.TotalMilliseconds} ms: {returned}");
            Assert.Equal(expected, returned, StringComparer.InvariantCulture);
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0174_add_ab_testing_home_page_version_b_flag'),
    ]

    operations = [
        migrations.AddField(
            model_name='pagecounter',
            name='action',
            field=models.CharField(blank=True, null=True, max_length=128),
        ),
        migrations.AddField(
            model_name='pagecounter',
            name='file',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pagecounters', to='osf.BaseFileNode'),
        ),
        migrations.AddField(
            model_name='pagecounter',
            name='resource',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pagecounters', to='osf.Guid'),
        ),
        migrations.AddField(
            model_name='pagecounter',
            name='version',
            field=models.IntegerField(blank=True, null=True),
        ),
    ]


text:
<?php
namespace Concrete\Core\Html;

class Image
{

    protected $usePictureTag = false;
    protected $tag;

    protected $theme;

    protected function loadPictureSettingsFromTheme()
    {
        $c = \Page::getCurrentPage();
        if (is_object($c)) {
            $th = $c->getCollectionThemeObject();
            if (is_object($th)) {
                $this->theme = $th;
                $this->usePictureTag = count($th->getThemeResponsiveImageMap()) > 0;
            }
        }
    }

    /**
     * @param \File $f
     * @param null $usePictureTag
     */
    public function __construct(\File $f = null, $usePictureTag = null)
    {
        if (!is_object($f)) {
            return false;
        }

        if (isset($usePictureTag)) {
            $this->usePictureTag = $usePictureTag;
        } else {
            $this->loadPictureSettingsFromTheme();
        }

        if ($this->usePictureTag) {

            if (!isset($this->theme)) {
                $c = \Page::getCurrentPage();
                $this->theme = $c->getCollectionThemeObject();
            }
            $sources = array();
            $fallbackSrc = $f->getRelativePath();
            if(!$fallbackSrc) {
                $fallbackSrc = $f->getURL();
            }
            foreach($this->theme->getThemeResponsiveImageMap() as $thumbnail => $width) {
                $type = \Concrete\Core\File\Image\Thumbnail\Type\Type::getByHandle($thumbnail);
                if($type != NULL) {
                    $src = $f->getThumbnailURL($type->getBaseVersion());
                    $sources[] = array('src' => $src, 'width' => $width);
                    if ($width == 0) {
                        $fallbackSrc = $src;
                    }
                }
            }
            $this->tag = \Concrete\Core\Html\Object\Picture::create($sources, $fallbackSrc);
        } else {
            // Return a simple image tag.
            $path = $f->getRelativePath();
            if(!$path) {
                $path = $f->getURL();
            }
            $this->tag = \HtmlObject\Image::create($path);
            $this->tag->width($f->getAttribute('width'));
            $this->tag->height($f->getAttribute('height'));
        }
    }

    /**
     * @return \HTMLObject\Element\Tag
     */
    public function getTag()
    {
        return $this->tag;
    }

}


text:
var Point = require('../point/Point');

/**
 * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
 *
 * @function Phaser.Geom.Circle.CircumferencePoint
 * @since 3.0.0
 *
 * @generic {Phaser.Geom.Point} O - [out,$return]
 *
 * @param {Phaser.Geom.Circle} circle - The Circle to get the circumference point on.
 * @param {number} angle - The angle from the center of the Circle to the circumference to return the point from. Given in radians.
 * @param {(Phaser.Geom.Point|object)} [out] - A Point, or point-like object, to store the results in. If not given a Point will be created.
 *
 * @return {(Phaser.Geom.Point|object)} A Point object where the `x` and `y` properties are the point on the circumference.
 */
var CircumferencePoint = function (circle, angle, out)
{
    if (out === undefined) { out = new Point(); }

    out.x = circle.x + (circle.radius * Math.cos(angle));
    out.y = circle.y + (circle.radius * Math.sin(angle));

    return out;
};

module.exports = CircumferencePoint;


text:
"""
kombu.transport
===============

Built-in transports.

:copyright: (c) 2009 - 2011 by Ask Solem.
:license: BSD, see LICENSE for more details.

"""
import sys

from kombu.utils import rpartition

DEFAULT_TRANSPORT = "kombu.transport.pyamqplib.Transport"

MISSING_LIB = """
    The %(feature)s requires the %(lib)s module to be
    installed; http://pypi.python.org/pypi/%(lib)s

    Use pip to install this module::

        $ pip install %(lib)s

    or using easy_install::

        $ easy_install %(lib)s
"""

def _requires(feature, module, lib):
    try:
        __import__(module)
    except ImportError:
        raise ImportError(MISSING_LIB % {"feature": feature,
                                         "module": module,
                                         "lib": lib})

def _django_transport():
    _requires("Django transport", "djkombu", "django-kombu")
    return "djkombu.transport.DatabaseTransport"

def _sqlalchemy_transport():
    _requires("SQLAlchemy transport", "sqlakombu", "kombu-sqlalchemy")
    return "sqlakombu.transport.Transport"

def _ghettoq(name, new, alias=None):
    xxx = new

    def __inner():
        import warnings
        _new = callable(xxx) and xxx() or xxx
        gtransport = "ghettoq.taproot.%s" % name
        ktransport = "kombu.transport.%s.Transport" % _new
        this = alias or name
        warnings.warn("""
    Ghettoq does not work with Kombu, but there is now a built-in version
    of the %s transport.

    You should replace %r with simply: %r
        """ % (name, gtransport, this))
        print("TTT: %r" % ktransport)
        return ktransport

    return __inner

TRANSPORT_ALIASES = {
    "amqplib": "kombu.transport.pyamqplib.Transport",
    "librabbitmq": "kombu.transport.librabbitmq.Transport",
    "pika": "kombu.transport.pypika.AsyncoreTransport",
    "syncpika": "kombu.transport.pypika.SyncTransport",
    "memory": "kombu.transport.memory.Transport",
    "redis": "kombu.transport.pyredis.Transport",
    "beanstalk": "kombu.transport.beanstalk.Transport",
    "mongodb": "kombu.transport.mongodb.Transport",
    "couchdb": "kombu.transport.pycouchdb.Transport",
    "django": _django_transport,
    "sqlalchemy": _sqlalchemy_transport,

    "ghettoq.taproot.Redis": _ghettoq("Redis", "pyredis", "redis"),
    "ghettoq.taproot.Database": _ghettoq("Database", _django_transport,
                                         "django"),
    "ghettoq.taproot.MongoDB": _ghettoq("MongoDB", "mongodb"),
    "ghettoq.taproot.Beanstalk": _ghettoq("Beanstalk", "beanstalk"),
    "ghettoq.taproot.CouchDB": _ghettoq("CouchDB", "couchdb"),
}

_transport_cache = {}

def resolve_transport(transport=None):
    transport = TRANSPORT_ALIASES.get(transport, transport)
    if callable(transport):
        transport = transport()
    transport_module_name, _, transport_cls_name = rpartition(transport, ".")
    if not transport_module_name:
        raise KeyError("No such transport: %s" % (transport, ))
    return transport_module_name, transport_cls_name

def _get_transport_cls(transport=None):
    transport_module_name, transport_cls_name = resolve_transport(transport)
    __import__(transport_module_name)
    transport_module = sys.modules[transport_module_name]
    return getattr(transport_module, transport_cls_name)

def get_transport_cls(transport=None):
    """Get transport class by name.

    The transport string is the full path to a transport class, e.g.::

        "kombu.transport.pyamqplib.Transport"

    If the name does not include `"."` (is not fully qualified),
    the alias table will be consulted.

    """
    transport = transport or DEFAULT_TRANSPORT
    if transport not in _transport_cache:
        _transport_cache[transport] = _get_transport_cls(transport)
    return _transport_cache[transport]


text:
package main

import (
	"database/sql"
	"flag"
	"fmt"
	"os"

	_ "github.com/lib/pq"
	mp "github.com/mackerelio/go-mackerel-plugin"
	"github.com/mackerelio/mackerel-agent/logging"
)

var logger = logging.GetLogger("metrics.plugin.postgres")

var graphdef map[string](mp.Graphs) = map[string](mp.Graphs){
	"postgres.connections": mp.Graphs{
		Label: "Postgres Connections",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "active", Label: "Active", Diff: false, Stacked: true},
			mp.Metrics{Name: "waiting", Label: "Waiting", Diff: false, Stacked: true},
		},
	},
	"postgres.commits": mp.Graphs{
		Label: "Postgres Commits",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "xact_commit", Label: "Xact Commit", Diff: true, Stacked: false},
			mp.Metrics{Name: "xact_rollback", Label: "Xact Rollback", Diff: true, Stacked: false},
		},
	},
	"postgres.blocks": mp.Graphs{
		Label: "Postgres Blocks",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "blks_read", Label: "Blocks Read", Diff: true, Stacked: false},
			mp.Metrics{Name: "blks_hit", Label: "Blocks Hit", Diff: true, Stacked: false},
		},
	},
	"postgres.rows": mp.Graphs{
		Label: "Postgres Rows",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "tup_returned", Label: "Returned Rows", Diff: true, Stacked: false},
			mp.Metrics{Name: "tup_fetched", Label: "Fetched Rows", Diff: true, Stacked: true},
			mp.Metrics{Name: "tup_inserted", Label: "Inserted Rows", Diff: true, Stacked: true},
			mp.Metrics{Name: "tup_updated", Label: "Updated Rows", Diff: true, Stacked: true},
			mp.Metrics{Name: "tup_deleted", Label: "Deleted Rows", Diff: true, Stacked: true},
		},
	},
	"postgres.size": mp.Graphs{
		Label: "Postgres Data Size",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "total_size", Label: "Total Size", Diff: false, Stacked: false},
		},
	},
	"postgres.deadlocks": mp.Graphs{
		Label: "Postgres Dead Locks",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "deadlocks", Label: "Deadlocks", Diff: true, Stacked: false},
		},
	},
	"postgres.iotime": mp.Graphs{
		Label: "Postgres Block I/O time",
		Unit:  "float",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "blk_read_time", Label: "Block Read Time (ms)", Diff: true, Stacked: false},
			mp.Metrics{Name: "blk_write_time", Label: "Block Write Time (ms)", Diff: true, Stacked: false},
		},
	},
	"postgres.tempfile": mp.Graphs{
		Label: "Postgres Temporary file",
		Unit:  "integer",
		Metrics: [](mp.Metrics){
			mp.Metrics{Name: "temp_bytes", Label: "Temporary file size (byte)", Diff: true, Stacked: false},
		},
	},
}

type PostgresPlugin struct {
	Host     string
	Port     string
	Username string
	Password string
	SSLmode  string
	Timeout  int
	Tempfile string
        Option   string
}

func FetchStatDatabase(db *sql.DB) (map[string]float64, error) {
	rows, err := db.Query(`
		select xact_commit, xact_rollback, blks_read, blks_hit, blk_read_time, blk_write_time,
		tup_returned, tup_fetched, tup_inserted, tup_updated, tup_deleted, deadlocks, temp_bytes
		from pg_stat_database
	`)
	if err != nil {
		logger.Errorf("Failed to select pg_stat_database. %s", err)
		return nil, err
	}

	stat := make(map[string]float64)

	for rows.Next() {
		var xact_commit, xact_rollback, blks_read, blks_hit, blk_read_time, blk_write_time int
		var tup_returned, tup_fetched, tup_inserted, tup_updated, tup_deleted, deadlocks, temp_bytes int

		if err := rows.Scan(&xact_commit, &xact_rollback, &blks_read, &blks_hit, &blk_read_time, &blk_write_time, &tup_returned, &tup_fetched, &tup_inserted, &tup_updated, &tup_deleted, &deadlocks, &temp_bytes); err != nil {
			logger.Warningf("Failed to scan. %s", err)
			continue
		}

		stat["xact_commit"] += float64(xact_commit)
		stat["xact_rollback"] += float64(xact_rollback)
		stat["blks_read"] += float64(blks_read)
		stat["blks_hit"] += float64(blks_hit)
		stat["blk_read_time"] += float64(blks_hit)
		stat["blk_write_time"] += float64(blks_hit)
		stat["tup_returned"] += float64(tup_returned)
		stat["tup_fetched"] += float64(tup_fetched)
		stat["tup_inserted"] += float64(tup_inserted)
		stat["tup_updated"] += float64(tup_updated)
		stat["tup_deleted"] += float64(tup_deleted)
		stat["deadlocks"] += float64(deadlocks)
		stat["temp_bytes"] += float64(temp_bytes)
	}

	return stat, nil
}

func FetchConnections(db *sql.DB) (map[string]float64, error) {
	rows, err := db.Query(`
		select count(*), waiting from pg_stat_activity group by waiting
	`)
	if err != nil {
		logger.Errorf("Failed to select pg_stat_activity. %s", err)
		return nil, err
	}

	stat := make(map[string]float64)

	for rows.Next() {
		var count int
		var waiting string
		if err := rows.Scan(&count, &waiting); err != nil {
			logger.Warningf("Failed to scan %s", err)
			continue
		}
		if waiting != "" {
			stat["active"] += float64(count)
		} else {
			stat["waiting"] += float64(count)
		}
	}

	return stat, nil
}

func FetchDatabaseSize(db *sql.DB) (map[string]float64, error) {
	rows, err := db.Query("select sum(pg_database_size(datname)) as dbsize from pg_database")
	if err != nil {
		logger.Errorf("Failed to select pg_database_size. %s", err)
		return nil, err
	}

	stat := make(map[string]float64)

	for rows.Next() {
		var dbsize int
		if err := rows.Scan(&dbsize); err != nil {
			logger.Warningf("Failed to scan %s", err)
			continue
		}
		stat["total_size"] += float64(dbsize)
	}

	return stat, nil
}

func mergeStat(dst, src map[string]float64) {
	for k, v := range src {
		dst[k] = v
	}
}

func (p PostgresPlugin) FetchMetrics() (map[string]float64, error) {
	db, err := sql.Open("postgres", fmt.Sprintf("user=%s password=%s host=%s port=%s sslmode=%s connect_timeout=%d %s", p.Username, p.Password, p.Host, p.Port, p.SSLmode, p.Timeout, p.Option))
	if err != nil {
		logger.Errorf("FetchMetrics: ", err)
		return nil, err
	}
	defer db.Close()

	statStatDatabase, err := FetchStatDatabase(db)
	if err != nil {
		return nil, err
	}
	statConnections, err := FetchConnections(db)
	if err != nil {
		return nil, err
	}
	statDatabaseSize, err := FetchDatabaseSize(db)
	if err != nil {
		return nil, err
	}

	stat := make(map[string]float64)
	mergeStat(stat, statStatDatabase)
	mergeStat(stat, statConnections)
	mergeStat(stat, statDatabaseSize)

	return stat, err
}

func (p PostgresPlugin) GraphDefinition() map[string](mp.Graphs) {
	return graphdef
}

func main() {
	optHost := flag.String("hostname", "localhost", "Hostname to login to")
	optPort := flag.String("port", "5432", "Database port")
	optUser := flag.String("user", "", "Postgres User")
        optDatabase := flag.String("database", "", "Database name")
	optPass := flag.String("password", "", "Postgres Password")
	optSSLmode := flag.String("sslmode", "disable", "Whether or not to use SSL")
	optConnectTimeout := flag.Int("connect_timeout", 5, "Maximum wait for connection, in seconds.")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	if *optUser == "" {
		logger.Warningf("user is required")
		flag.PrintDefaults()
		os.Exit(1)
	}
	if *optPass == "" {
		logger.Warningf("password is required")
		flag.PrintDefaults()
		os.Exit(1)
	}
        option := ""
        if *optDatabase != "" {
		option = fmt.Sprintf("dbname=%s", *optDatabase)
        }

	var postgres PostgresPlugin
	postgres.Host = *optHost
	postgres.Port = *optPort
	postgres.Username = *optUser
	postgres.Password = *optPass
	postgres.SSLmode = *optSSLmode
	postgres.Timeout = *optConnectTimeout
	postgres.Option = option

	helper := mp.NewMackerelPlugin(postgres)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-postgres-%s-%s", *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}